Compare commits

..
Author SHA1 Message Date
poli0981andClaude Fable 5.2 ffd5501811 docs(guide): the settings page listed Controllers and input twice
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 04:56:30 +07:00
poli0981 a7ee7fd8ed Merge main (#467 squashed) into feat/input-agent: the trees are the same below this branch's own commits 2026-11-15 04:35:33 +07:00
poli0981andClaude Fable 5.2 e3dab94834 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) (#467)
* 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>

* 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>

* 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>

* 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>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 16:20:55 +00:00
poli0981 9afbeb6801 Merge feat/input-reader (main with #466) into feat/input-agent 2026-11-14 23:04:48 +07:00
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 7dbb3c573a Merge feat/input-reader (main at 1d1d4ff) into feat/input-agent 2026-11-14 22:53:00 +07:00
poli0981 102dcdd3f1 Merge feat/input-storage (main at 1d1d4ff) into feat/input-reader 2026-11-14 22:52:58 +07:00
poli0981andClaude Fable 5.2 ac360eae01 style(input): import order in the Agent's composition; no redundant qualifier in a test (InspectCode)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 22:52:56 +07:00
poli0981 43e0c2b347 Merge branch 'main' into feat/input-storage 2026-11-14 22:48:46 +07:00
poli0981andClaude Fable 5.2 b579133128 wip(input): the Agent records what a session was played with - the switch, the terms, the legal texts
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 22:48:03 +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
poli0981andClaude Fable 5.2 b29993ba82 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>
2026-11-14 21:44:42 +07:00
123 changed files with 7810 additions and 69 deletions

No files matched your search

+41
View File
@@ -35,6 +35,47 @@ numeric core and does not move; the heading is the full version — corrected 20
## [Unreleased]
### Added
- **A session records what it was played with — a controller, the keyboard and mouse, both, or neither** (D155–D163,
the owner's decisions of 2026-11-14; *Settings ▸ Controllers and input*, on unless you switch it off). While a game
is recorded, FrameLedger's agent notes — from Windows, never from the game — which game controllers are connected
and in use, their battery level, and whether the keyboard or mouse is in use, and the session stores how the time
the game was in front divides between them, how often each controller connected and dropped, and its battery. It
works for a game FrameLedger does not measure too. **No button, stick, key or text is kept; nothing is sent to a
controller; and nothing is read until you have accepted the Privacy Policy that describes it** — after this
update, sessions recorded before FrameLedger has been opened once have no such figures. The screens that show the
figures come with the same release. Xbox-compatible controllers and the DualSense are read for use; another
controller is listed and never counted as in use. **None of this had been read from a real controller when it was
written** — it was checked against data written by hand (`LIMITATIONS.md` §Controllers and input).
- **The terms are shown once: Privacy Policy 2.22 and Disclaimer 2.18.** Both said FrameLedger never reads input.
They now say what is read — that a controller, or the keyboard or mouse, is in use — what is kept, and what never
is (`docs/legal-drift-history.md`).
- **For developers: the arithmetic of controller statistics, with nothing reading a device yet** (D155–D163, the
owner's decisions of 2026-11-14; `docs/21_INPUT_DEVICES.md`, `docs/03_METRICS.md` §Input). `FrameLedger.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 seen twice; `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. 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
- **Advanced metrics is closed: the ten readings that were "being studied" are now "not read", with the reason**
+28 -2
View File
@@ -6,7 +6,7 @@ Read this file first, then the reading order at the bottom. **`docs/19_SAFETY_AN
## Architecture in one paragraph
A C++ DLL (`FrameLedger.Overlay.dll`) is injected into games the user explicitly enabled. It hooks the presentation path (DXGI for D3D11/D3D12, plus OpenGL) and the upscaler/RT APIs, writes fixed-size frame records into a lock-free shared-memory ring, and never blocks. A C# Agent drains that ring at ~10 Hz, enriches with GPU telemetry from vendor APIs, and writes sessions to SQLite. A WPF UI reads SQLite. Vulkan uses an implicit **layer** instead of hooking. If injection is refused or fails there is **no measurement**: the session records duration, hardware telemetry and the reason, and every measured field reads `N/A` (Tier 2, owner decision 2026-08-28).
A C++ DLL (`FrameLedger.Overlay.dll`) is injected into games the user explicitly enabled. It hooks the presentation path (DXGI for D3D11/D3D12, plus OpenGL) and the upscaler/RT APIs, writes fixed-size frame records into a lock-free shared-memory ring, and never blocks. A C# Agent drains that ring at ~10 Hz, enriches with GPU telemetry from vendor APIs, and writes sessions to SQLite. A WPF UI reads SQLite. Vulkan uses an implicit **layer** instead of hooking. If injection is refused or fails there is **no measurement**: the session records duration, hardware telemetry and the reason, and every measured field reads `N/A` (Tier 2, owner decision 2026-08-28) — **and, since owner decision D161 (2026-11-14), what the Agent reads from outside the game**: the game process's memory (beta.12, D43) and which controllers, or the keyboard and mouse, the session was played with (`docs/21_INPUT_DEVICES.md`). Nothing measured inside the game is among them.
## Non-negotiable rules
@@ -147,6 +147,28 @@ src/
# (LATENCY_FRAMES, a batch per state of the sleep status; nothing published or
# stored); its watchdog's periodic tick is on a grid (fl_watchdog_tick.h), and
# Recording/PendingInGameReadings keeps the reading that waits for a sample.
# Controllers and input (0.1.0-beta.50, owner decisions D155-D163, docs/21_INPUT_DEVICES):
# Input/ - InputReader (a slice ten times a second over the port IInputBackend),
# InputTickAccumulator (one session's slices into a reading a tick), InputTerms (the
# reading waits for Privacy Policy 2.22, D156), the ports IInputDevices /
# IInputActivitySource; Recording/InputSessionBuilder (totals, the controllers as JSON,
# the input.* series; schema 0024). Domain/Input holds the arithmetic and the two
# parsers (an XInput state, a DualSense report). Infrastructure/Input is the Windows
# side: Win32InputBackend (raw input for joysticks and gamepads, three XInput getters,
# GetLastInputInfo - it opens no device and sends nothing to one) and InputDeviceHub
# (one thread for the Agent, only while a session has a view). Read from OUTSIDE the
# game, both tiers; `capture.input_devices`, on by default.
# Controllers and input (0.1.0-beta.50, owner decisions D155-D163, docs/21_INPUT_DEVICES):
# Input/ - InputReader (a slice ten times a second over the port IInputBackend),
# InputTickAccumulator (one session's slices into a reading a tick), InputTerms (the
# reading waits for Privacy Policy 2.22, D156), the ports IInputDevices /
# IInputActivitySource; Recording/InputSessionBuilder (totals, the controllers as JSON,
# the input.* series; schema 0024). Domain/Input holds the arithmetic and the two
# parsers (an XInput state, a DualSense report). Infrastructure/Input is the Windows
# side: Win32InputBackend (raw input for joysticks and gamepads, three XInput getters,
# GetLastInputInfo - it opens no device and sends nothing to one) and InputDeviceHub
# (one thread for the Agent, only while a session has a view). Read from OUTSIDE the
# game, both tiers; `capture.input_devices`, on by default.
FrameLedger.Infrastructure/ # SQLite, shm reader, vendor APIs, injector interop, parsers,
# and Capture/ (PR-C): ShmRingAttacher/ShmCaptureSink over the
# reader, HeldProcessLivenessSource, TargetResolver (path only,
@@ -208,7 +230,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
+31 -1
View File
@@ -36,7 +36,8 @@ page lists them in plain words; each item links to the document that has the det
When a game is not measured — any of the reasons above — its session still records **how long it ran, the
machine's sensors (GPU temperature, load, power; CPU load; memory), how much memory the game itself used (read from
Windows, outside the game) and why nothing was measured.** Every
Windows, outside the game), what it was played with ([Controllers and input](#controllers-and-input)) and why nothing
was measured.** Every
frame-rate, upscaler, frame-generation and ray-tracing value reads **N/A**, never 0. How the game's window was
shown is recorded too, from outside the game. ([Capture](docs/04_CAPTURE.md))
@@ -149,6 +150,35 @@ shown is recorded too, from outside the game. ([Capture](docs/04_CAPTURE.md))
N/A for video memory. AMD and Intel graphics cards have not been tested.
([Metrics](docs/03_METRICS.md))
## Controllers and input
Since 0.1.0-beta.50 a session records what it was played with. All of it is read from Windows, from outside the
game — so it is there for a game FrameLedger does not measure as well.
- **It says a controller was in use while the game was in front — not what the game did with it.** A controller
held while a game ignores it reads as a controller in use.
- **Keyboard and mouse are one figure.** FrameLedger reads only the time of the last keyboard or mouse input; it
cannot tell the two apart, and never reads a key.
- **Input a program makes counts as keyboard and mouse**: Steam Input mapping a controller to keys, a macro tool, a
remapper. A controller mapped that way reads as *both*.
- **Only the time the game is in front counts.** A game whose window belongs to another process than the one
FrameLedger follows reads as never in front, and has no shares.
- **Xbox-compatible controllers and the DualSense are read for use.** Any other controller — a DualShock 4, a
Switch Pro controller — is listed with its connections and disconnections and is never counted as in use.
- **A controller that Windows presents as an Xbox pad is "Xbox"**, whoever made it. Its model is named only when it
cannot be mistaken for another one that is connected.
- **Battery.** An Xbox controller on a cable reads "wired"; on Bluetooth it may report nothing. A DualSense on
Bluetooth reports its battery only where Steam or the game has switched it to its long report — FrameLedger never
asks a controller for anything. An Xbox controller's level is four words, a DualSense's is in steps of ten per
cent.
- **Steam Input shows a controller twice** — the one you hold and an Xbox pad Steam presents for it. FrameLedger
folds the two into one when they move together; with another remapper it may list two.
- **Nothing is read until you have accepted the Privacy Policy that describes it.** After an update, sessions
recorded before FrameLedger has been opened once have no such figures, and say so in their notes.
- **None of this had been read from a real controller when 0.1.0-beta.50 was written.** It was checked against data
written by hand; what real controllers do is in the developer's notes once the owner has tried them.
([Input devices](docs/21_INPUT_DEVICES.md))
## Display mode (full-screen, borderless, windowed)
- **Exclusive full-screen is known only for a measured Direct3D (DXGI) game** — the game's own swap chain
+11 -1
View File
@@ -107,6 +107,16 @@ app too (Help ▸ User guide, Help ▸ Limitations, Help ▸ Accessibility), and
> temperature in every session, and, on NVIDIA cards only, how much of the time its power limit or its temperature held
> it back, read once a second; and frames per watt — the game's own frames per second for each watt the graphics card
> drew, never counting generated frames, `N/A` where the game's own frame rate is not known.
> - **Controllers and input (since beta.50; on unless you switch it off in Settings, and only once you have accepted
> the Privacy Policy that describes it):** how much of the time a game was in front it was played with a
> controller, with the keyboard or mouse, with both or with neither; each controller's connections and drops; its
> battery. All of it is read from Windows, from outside the game: it says a controller was in use while the game
> was in front, not what the game did with it. Keyboard and mouse are one figure — only the time of the last input
> is read — and input a program injects (Steam Input mapping a controller to keys, a macro tool) counts as keyboard
> and mouse. An Xbox-compatible controller and a DualSense are read for use; another maker's controller is listed
> and never counted as in use. A DualSense on Bluetooth reports its battery only where Steam or the game has
> switched it to its long report, and an Xbox controller on Bluetooth may report none. **None of this had been
> read from a real controller when it was written (2026-11-14)**: it was checked against data written by hand.
> - **Processor and memory:** how busy the processor was (time busy, all cores together — not the
> frequency-scaled figure Task Manager draws) and how much system memory was in use, read from
> Windows once a second and charted. Processor temperature is read only when the Agent runs as
@@ -188,7 +198,7 @@ FrameLedger is built to keep that risk small and to be honest about it:
| **Off by default** | Injection is disabled for every game until you enable it individually, after a consent prompt |
| **Hard refusal** | Known anti-cheat/anti-tamper components are detected before injection and every 30 s during a session. Detected ⇒ FrameLedger refuses, or stops capturing at the next scan — so up to 30 s can pass before it reacts to anti-cheat that loads mid-session. For Direct3D/OpenGL that means hooks are removed; for Vulkan it means the layer goes passthrough, because a layer cannot leave the loader chain of a running game. **There is no override — not in settings, not in a config file, not on the command line**<br><br>**One narrow exception since beta.9 (owner decisions D33, D38):** per game, after its own disclosure and only while a Settings option (off by default) is on, a game whose only finding is one anti-cheat that runs entirely in user mode — no driver file in its folder, on no title list — may be hooked under a user-mode exception. ~~and that FrameLedger has measured successfully at least twice~~ *(corrected 2026-10-03: since beta.11, D38, a grant needs no earlier session; its first two hooked sessions are a trial, and one that does not go well ends it for good.)* The guard still runs every check under it, refuses anything else it finds, and ends it on anything new; a ban remains possible (`legal/DISCLAIMER.md` §2A).<br><br>✅ **Both halves run since 2026-09-10.** The *pre-injection* refusal runs every documented check, and during every capture the Agent re-runs them every 30 s: the component inside the game removes its hooks within one frame of being told to, and within 65 s if it stops hearing from the scanner. *(Until 2026-09-15 this cell said the in-session re-scan did not run at all, which stopped being true when the Agent's capture loop landed.)* For a Vulkan title the stop is the layer's own: it checks the scanner's counter on every present and goes passthrough within one present of the stop flag, or after 65 s without a scan — a title that has stopped presenting is not stopped by that deadline, and presents nothing to be observed either. |
| **No evasion, ever** | FrameLedger does not hide, rename, obfuscate, or disguise itself. It keeps its real name, real exports, and version info. It is meant to be plainly visible to any security software that looks. This is an architectural rule, not a setting |
| **Read-only** | It never reads or writes game memory, never modifies game behavior, never touches saves or input, and never changes GPU clocks, fans, or power limits |
| **Read-only** | It never reads or writes game memory, never modifies game behavior, never touches saves, never reads what you type or which buttons you press — from outside the game it notes only whether a controller, or the keyboard or mouse, is in use — and never changes GPU clocks, fans, or power limits |
| **Always a way out** | FrameLedger refuses rather than pushes through. When the guard finds anti-cheat, or the hook fails, or you have not enabled a game, it **stops** — and records the session anyway: start, end, duration, whatever hardware sensors your machine provides, and the reason there is nothing else. Every measured value reads `N/A`; it never estimates one.<br><br>**The way out is that it does not inject, not that it measures another way.** An earlier version of this row promised a no-injection measurement mode. It was designed around Intel PresentMon, that was dropped on 2026-08-27 after measurement, and no replacement was chosen — so **frame times require hooking**. Said in this row rather than a footnote because the row is in the SAFETY table, and a reader deciding whether to enable a game needs the real alternative, not a comfortable one |
**FrameLedger is for offline and single-player games.** If you enable it for anything with an online or competitive component, that is your call and your responsibility. The developer cannot reverse a ban. Please read [`legal/DISCLAIMER.md`](legal/DISCLAIMER.md) and [`docs/19_SAFETY_AND_ANTICHEAT.md`](docs/19_SAFETY_AND_ANTICHEAT.md) before enabling it for anything.
+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 }
+20
View File
@@ -102,6 +102,26 @@ Tray icon states (idle / capturing T1 / capturing T2 / paused); menu; toasts for
### FR-15 In-game overlay *(v1.1, opt-in, off by default)*
Draw live FPS/frametime/upscaler info inside the game. Only for games already hooked; a separate toggle; never on by default. Deferred until the data path is stable (`15_ROADMAP` P5).
### FR-16 Controllers and input *(owner decisions D155–D163, 2026-11-14)*
What a session was played with, read by the Agent from outside the game — so for hooked and unhooked sessions alike (`21_INPUT_DEVICES`, `03_METRICS` §Input).
- FR-16.1 The share of the time the game was in front that it was played with a controller, with the keyboard or mouse (one class), with both, with neither; the number of switches between a controller and the keyboard and mouse.
- FR-16.2 Each controller: its maker and model by its USB ids, how it is connected, its connections and disconnections during the session, the time it was in use.
- FR-16.3 Each controller's battery: the time at each level, the level that lasted longest, the first and the last, a rate where one can be worked out.
- FR-16.4 Each maker's share of the time controllers were in use, and the number of switches between makers. A pad that is one controller seen twice (Steam Input) counts once.
- FR-16.5 Whether a game supports controllers, as evidence and never a verdict: what the store's own file on the disk says, which input libraries the game loaded, how it was played (D163).
- FR-16.6 An option, **on unless switched off**, that reads nothing until the Privacy Policy describing it has been accepted on the PC (D156). Off means nothing is read or stored.
- FR-16.7 Never read or stored: which button, stick, trigger or key; text; the mouse's position; a serial number, a Bluetooth address, a device path. Nothing is ever sent to a controller (D159). Held by `tools/input-readonly-check.ps1`.
### FR-16 Controllers and input *(owner decisions D155–D163, 2026-11-14)*
What a session was played with, read by the Agent from outside the game — so for hooked and unhooked sessions alike (`21_INPUT_DEVICES`, `03_METRICS` §Input).
- FR-16.1 The share of the time the game was in front that it was played with a controller, with the keyboard or mouse (one class), with both, with neither; the number of switches between a controller and the keyboard and mouse.
- FR-16.2 Each controller: its maker and model by its USB ids, how it is connected, its connections and disconnections during the session, the time it was in use.
- FR-16.3 Each controller's battery: the time at each level, the level that lasted longest, the first and the last, a rate where one can be worked out.
- FR-16.4 Each maker's share of the time controllers were in use, and the number of switches between makers. A pad that is one controller seen twice (Steam Input) counts once.
- FR-16.5 Whether a game supports controllers, as evidence and never a verdict: what the store's own file on the disk says, which input libraries the game loaded, how it was played (D163).
- FR-16.6 An option, **on unless switched off**, that reads nothing until the Privacy Policy describing it has been accepted on the PC (D156). Off means nothing is read or stored.
- FR-16.7 Never read or stored: which button, stick, trigger or key; text; the mouse's position; a serial number, a Bluetooth address, a device path. Nothing is ever sent to a controller (D159). Held by `tools/input-readonly-check.ps1`.
## Non-functional requirements
- **NFR-1 Game-side overhead:** ≤ 1 µs per present, ≤ 8 MB resident, measured game FPS impact ≤ 0.5% vs uninstrumented.
+54
View File
@@ -976,6 +976,60 @@ min / max in `sensor_stats_json` (§Sensor aggregates). MiB stored; shown in GB
~~`vramUsedMb` from `IDXGIAdapter3::QueryVideoMemoryInfo(LOCAL)` inside the game = **this game's** usage and budget. **MiB, truncating, and it must use the same divisor as `vramBudgetMb`** — the two are compared, and mismatched rounding would put a systematic bias into `budget_exceeded_pct`. Residual: a flip within 1 MiB of the budget, 0.004% of a 24 GiB card. Stored as its own series and clearly labelled apart from the adapter-wide figure from `18_GPU_VENDOR_APIS`. Aggregates: avg, max, and `budget_exceeded_pct` (share of samples where `CurrentUsage > Budget`, i.e. the driver was likely evicting — a genuinely useful stutter explanation).~~
## Input — what a session was played with, both tiers (owner decisions D155–D163)
**Owner request, 2026-11-14:** the share of a session played with a controller and with the keyboard, how often a
controller connected and dropped, the battery state that lasted longest, the switches between makers' controllers.
What is read and what never is: [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md). The arithmetic is
`Domain.Input` and `Application.Recording.InputSessionBuilder`. **Not built end to end yet** — nothing reads a device
until the pull requests after the one that wrote this section; until then these are definitions under test.
**What it can say, and what it cannot.** Everything is read from outside the game. So a number here says that a
controller, or the keyboard or mouse, was *in use while the game's window was in front* — never what the game did with
it, and never which button or key.
**The unit is a slice** of about a tenth of a second, and a slice counts for a session only when a window of the
session's game was in front and the session was not paused (a pause is a gap, as for frames). A slice with another
program in front is not classified: typing in a browser beside the game is not the game played with the keyboard.
| Class | A slice in front in which |
|---|---|
| Controller | a controller was in use and the time of the last keyboard-or-mouse input did not move |
| Keyboard & mouse | that time moved and no controller was in use. One class: only a time is read (D158) |
| Both | both |
| No input | neither |
- **A controller is in use** when a button is down, a trigger is past its threshold, or a stick is outside its dead
zone. A stick held counts. One that drifts inside the dead zone does not — a pad lying on a desk is not played with.
- **A share** is a class's time over the time the game was in front (`input_foreground_ms`). The four add up to it.
- **A switch of method** is a change between *controller* and *keyboard & mouse* from one tick (a second) to a later
one. A tick played with both, or with neither, is no one thing and does not end the run before it: putting the
controller down and picking it up again is not a switch.
- **Connections** are counted from the session's second slice: a controller that is there when the session starts has
not connected. A Bluetooth pad that goes to sleep has disconnected.
- **A battery** is timed by the clock, in front or not: the time at each level, the level that lasted longest, the
first and the last. Each source keeps its own steps — XInput's four words, a DualSense's per cent in tens — and none
is converted into another's. **A rate**, in per cent an hour, is the fall from the first to the last reading on
battery over the time read on battery; it is given only for a level in per cent that fell, was not put on power in
between, and was read on battery for ten minutes or more.
- **A maker's share** is the time its controllers were in use over that time for every maker. **A switch of maker**
is counted like a switch of method, between ticks in which one maker's controllers alone were in use.
- **One pad seen twice is one controller.** With Steam Input in front of a controller Windows shows the controller the
player holds and an Xbox pad Steam presents for it. One of XInput's pads that was in use at the same moments as
another controller — nine tenths of the busier one's time, over ten seconds or more — is folded into it: into a
controller that is not XInput's at any time, into another of XInput's pads only in a session in which Steam's
virtual gamepad was seen. Two players pressing in step are two players.
**The timeline** is one series, `input.class`: what each tick was mostly played with, as the class's number (0 no
input, 1 controller, 2 keyboard & mouse, 3 both), and no value for a tick with the game not in front. Each of the
first eight controllers has `input.dev.N.active` (the part of the tick's time in front it was in use; no value where
it was not connected) and, with a battery that has a level, `input.dev.N.battery`.
**Known limits.** Keyboard and mouse cannot be told apart. Input a program injects counts as keyboard and mouse — Steam
Input mapping a pad to keys, a macro tool — so a pad mapped that way reads as *both*. A game whose window belongs to
another process reads as never in front (the focus sample's limit). Whether a controller's own input moves Windows'
last-input time has not been checked on a real PC.
## Sensor aggregates
Per session over 1 Hz samples: `avg` (mean of non-null), `max` — and since beta.12 the `median` (the linear-interpolation
+2 -1
View File
@@ -350,6 +350,7 @@ What the Agent checks **before** asking the guard is the thing the native side s
|---|---|---|---|
| **Session loop** (`CaptureSession.RunAsync`, one async loop per session) | `Task.Delay(100 ms)` drain ticks; the 30 s guard scan is awaited inline | The ring reader, for the life of the session — drain, `PublishGuardResult`, `SetPaused`, `RequestLogFlush` — and the record buffer it fills | Samples foreground and the display mode per tick (beta.10), drains the telemetry queue per tick (PR-D), writes `.partial` itself (PR-D) |
| **Telemetry** (`fl-telemetry`, `TelemetryPoller`, one per session) | 1 Hz, never faster than 500 ms | Its own `ConcurrentQueue` of `TelemetrySample` | Reads the composite source only; L2 has a thread of its own inside the library, and the composite is read from this thread and no other |
| **Input** (`fl-input`, `InputDeviceHub`, **one for the Agent**, since 0.1.0-beta.50) | A slice every 100 ms, only while a session has a view of it — with none there is no thread, no window, no registration | The message-only window raw input is delivered to, and the registration for joysticks and gamepads; the reader's device table | Raw input's buffer, three XInput getters, `GetLastInputInfo`, the window in front. Hands each slice to every session's view under one lock; the telemetry thread takes a view's sum once a tick. Opens no device, sends nothing to one (`21_INPUT_DEVICES`) |
| **Watcher** (built 2026-09-10, PR-F: `CaptureOrchestrator.RunAsync` on a `PeriodicTimer(1 s)`) | 1 Hz process snapshot | The watcher's events and the running-session table — ~~`PollOnceAsync` is their only writer; there is no `Channel`, because there is no second consumer~~ **since 2026-09-13 (P3 PR-1b) the table has one lock**: `PollOnceAsync` on the timer, `LaunchAsync` and `StopSession` from the pipe's tasks (HANDOFF §P3 D12 as built — two commands do not justify a channel); the sessions themselves never take it | The `games` rows (one read per poll) and never the ring; each session it starts runs on its own task |
| **Finalize** (PR-D) | Once, on the session loop's task | The one SQLite connection, behind a `SemaphoreSlim(1)` | `ApplicationStopping` cancels the loop; finalize gets a grace window, then the `.partial` stays for recovery |
| **Pipe** (built 2026-09-13, P3 PR-1: `PipeServer.RunAsync` accepting, one reader and one writer task per client) | Per frame | Each client's bounded outbound queue (drop-oldest, so a publisher never waits) and the answer to each request | `Hello` / `GetStatus` / `Ping` read `AgentStatus`, an immutable snapshot the publisher swaps whole; **never the ring, never the recorder**. The events themselves are handed over ON the session loop's task by `SessionEventPublisher` (`ISessionObserver`, called after the recorder's own work each tick) — the loop enqueues a frame and returns |
@@ -372,7 +373,7 @@ the pipe's tasks touches the ring or the recorder, and the session loop never wa
## Telemetry poller
1 Hz (the session's `telemetry.interval_ms`, 500–2000 ms) on its own thread: `CompositeTelemetrySource.TryRead` (`18_GPU_VENDOR_APIS` — DXGI/PDH baseline, LibreHardwareMonitor sensors, NVAPI extras on NVIDIA) ~~+ optional CPU sample when the Agent is elevated and PawnIO is present~~ + *(corrected 2026-10-04)* the machine's reading on the same tick — CPU load and memory in use without elevation, CPU temperature only when elevated with PawnIO — and the game process's memory (beta.12, D43). Never called from the game process, never faster than 500 ms. Samples carry the session QPC epoch for timeline alignment.
1 Hz (the session's `telemetry.interval_ms`, 500–2000 ms) on its own thread: `CompositeTelemetrySource.TryRead` (`18_GPU_VENDOR_APIS` — DXGI/PDH baseline, LibreHardwareMonitor sensors, NVAPI extras on NVIDIA) ~~+ optional CPU sample when the Agent is elevated and PawnIO is present~~ + *(corrected 2026-10-04)* the machine's reading on the same tick — CPU load and memory in use without elevation, CPU temperature only when elevated with PawnIO — and the game process's memory (beta.12, D43). **Since 0.1.0-beta.50 (D155, D156) also what the session was played with**: when the option `capture.input_devices` is on and its terms are accepted, the poller opens a view of the Agent's input reader at its start, tells it which processes are the session's game (`Follow`), and attaches to each sample what that view saw since the tick before — `TelemetrySample.Input` (`21_INPUT_DEVICES` §The reader). A tick only the input view answered is still a sample. Never called from the game process, never faster than 500 ms. Samples carry the session QPC epoch for timeline alignment.
## Session recorder — state machine
+59 -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.
@@ -467,6 +491,8 @@ switch's rule); integers are invariant-culture within an inclusive range; choice
| `capture.run_elevated` | bool | `0` | | The App when it starts the Agent, and an Agent the logon task started — both BEFORE the Agent exists, through `Infrastructure.Startup.RunElevatedSetting` (one row, `PRAGMA query_only`, no version gate, anything but `1` is off) (D34, beta.10): on, Windows is asked for administrator rights at every Agent start (`01_ARCHITECTURE` ADR-9) |
| `capture.min_session_s` | int | `30` | 5–600 | Agent, per session (FR-3.6) |
| `telemetry.interval_ms` | int | `1000` | 500–2000 | Agent, per session (FR-3.5) |
| `capture.input_devices` | bool | `1` | | Agent, per session (FR-16, owner decisions D155 and D156, 2026-11-14): **Controllers and input**. On — and only once the Privacy Policy that describes the reading (2.22 or later) is in `legal_acceptance` (`Application.Input.InputTerms`) — a session has a view of the Agent's input reader and stores what it was played with (schema 0024); off, or before that acceptance, nothing of it is read or stored, and a session held back by the terms says so in its notes. Any row that is not exactly `0` is on. Settings ▸ Recording (`21_INPUT_DEVICES`) |
| `capture.input_devices` | bool | `1` | | Agent, per session (FR-16, owner decisions D155 and D156, 2026-11-14): **Controllers and input**. On — and only once the Privacy Policy that describes the reading (2.22 or later) is in `legal_acceptance` (`Application.Input.InputTerms`) — a session has a view of the Agent's input reader and stores what it was played with (schema 0024); off, or before that acceptance, nothing of it is read or stored, and a session held back by the terms says so in its notes. Any row that is not exactly `0` is on. Settings ▸ Recording (`21_INPUT_DEVICES`) |
| `telemetry.advanced` | bool | `0` | | Agent, per session (FR-5.6, owner decision D101, 2026-11-11): **Advanced metrics**. On, a session holds the Agent's shared reader and stores its `adv.*` series and its `session_advanced` row (schema 0023); off — and any row that is not exactly `1` — nothing more is read or stored, and a session recorded while off has no row. Settings ▸ Recording (`18_GPU_VENDOR_APIS` §The switch) |
| `retention.raw_sessions_per_game` | int | `20` | 0–10000; **0 = unlimited** | Agent, per session (§Retention) |
| `retention.remove_uninstalled_games` | bool | `1` | | Agent, at every detection sweep (beta.19, D55, FR-1.8): on, an entry whose executable has been gone for ten minutes — its drive connected, the folder it was installed in still there — and that has no session and no anti-cheat block or exception is removed; off, it stays and reads *Not installed* (D41's behaviour) |
@@ -528,6 +554,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 +587,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 +838,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)
+20
View File
@@ -1265,6 +1265,26 @@ outlives a rules change, a game update and *Change executable*; §What a finding
> the user. Cautious mode returns with the overlay, when there is something
> for it to switch off.
## What the Agent reads about input, from outside every game (owner decisions D155–D159)
Since 0.1.0-beta.50 the Agent can say what a session was played with (`21_INPUT_DEVICES`). It is on this page
because of what it must never become:
- **It is read from Windows, by the Agent. Nothing is added to a game**: no hook, no injected code, nothing in
`17_HOOK_ENGINE` §Hook inventory. Rule 4 is untouched, and a game the guard refuses is read like any other —
nothing about it touches the game's process.
- **No hook of any kind.** `SetWindowsHookEx` stays forbidden everywhere (`tools/chokepoint-check.ps1`); keyboard
and mouse are known by one call that returns a time (`GetLastInputInfo`), and raw input is registered for
joysticks and gamepads only — never for a keyboard or a mouse. A tool that hooks or registers for the keyboard is
what security software, and some anti-cheat, look for; this is not one.
- **No device is opened and nothing is sent to one.** A handle of FrameLedger's on a controller could make a game's
own exclusive open fail; an output or feature report could change how a controller reports to the game. Neither
is done.
- **A committed list holds it**: `tools/input-readonly-check.ps1` (`12_BUILD` step 14g).
Whether any anti-cheat objects to a background program that receives controllers' reports is not known; none is
documented to. It reads nothing of, and does nothing to, the game.
## Honest limits to document to users
The Disclaimer states these explicitly, and the UI consent dialog echoes them:
+1
View File
@@ -1874,6 +1874,7 @@ Moved verbatim, in this order.
| M13 ❓ | **Advanced metrics — LibreHardwareMonitor's CPU, memory, motherboard and storage groups, elevated, with PawnIO (D103, 2026-11-11).** Never opened by any build: §M10's elevated run has not been taken either, and this is a larger surface — a sensor chip on the LPC bus, the embedded controller, SPD over SMBus, SMART. Unknown: whether each group opens on the owner's board, what a refresh costs, whether opening the storage group touches removable drives (this PC once had a failing USB drive), and whether any group enables a privilege (`PrivilegeFootprintTests`). | **One elevated run with the probe verb, before the option exists.** Pre-committed: the storage group cannot be opened without touching removable drives → `lhm.storage.*` stays N/A in beta.39 and its reach reads `Deferred`; a node that throws twice → skipped for the session; the Agent above 1% of one core or 150 MB with the option on (NFR-2) → the slow groups are read less often or dropped before the release; a privilege enabled by a group → that group is not opened, and the owner is asked. **Two of the four answered 2026-11-11, before the option exists.** (1) **Storage: not opened, by the first outcome.** LibreHardwareMonitor 0.9.6's `StorageGroup` lists every drive through DiskInfoToolkit's `ReloadStorages` with no filter by bus and follows drives plugged in later — it cannot be opened without touching removable drives. `lhm.storage.*` reads `Deferred`, and `LhmGroups` has no member for it. (2) **Cost, unelevated, measured with `probe-advanced`** on the dev box: one refresh of the graphics-card group alone is 14 ms of processor time (62 ms elapsed) — 1.4% of one core at one a second, above NFR-2 — and one NVAPI read 0.4 ms. By the third outcome the sensor library is read every fifth tick (0.28%). **Still open, and the owner's**: the same probe as administrator with PawnIO — whether the processor, memory and motherboard groups open on this board, what they cost, and `PrivilegeFootprintTests`' new case on a token that holds the privileges (CI's does; the dev box's unelevated run passes by construction). **The first run was taken on 2026-11-12, by the owner, in ordinary use** (0.1.0-beta.40, the Agent as administrator with PawnIO, an i7-14700KF on a board with an IT8689E chip, an RTX 5080), and read here from a copy of the ledger and the Agent's log, not from a probe. **The groups open and read**: nine of ten sessions stored 119 processor series (a clock and a load per thread, temperatures, powers, voltages), 14 memory series and 21 motherboard series (six fans, six temperatures, nine voltages) beside the card's 41 — 195 from the sensor library in all. **No value was compared with another tool**; that is still the owner's. **Two faults, one cause** (`Infrastructure.Telemetry.LhmLibrary`): the Agent held up to three `Computer`s at once, and the library keeps the driver it reads the processor through and its bus mutexes per process — closing one `Computer` let go of them under the others. After seven sessions the Advanced reader's processor device threw `NullReferenceException` twice and was left alone (the page lost the processor until the reader reopened); once a session's start met another instance's close, the reader's `Open` threw `ObjectDisposedException`, and that session stored 17 series instead of 212. **Fixed 2026-11-12**: opens and closes are serialised and a `Computer` is parked, not closed, while another is in use. The cause is read from the log's timing and was not reproduced — it needs this elevation — so **whether the faults are gone is the owner's next sessions to show**: no `advanced: a device is left alone` and no `did not open` in the Agent's log. **First evidence, 2026-11-12, 0.1.0-beta.41, the same PC:** seven sessions between 06:38 and 07:01 with no `advanced:` line at all, each with the option on storing 212 or 213 series; on beta.40 that morning the processor device faulted out after each of six sessions (04:34–05:07) — thirteen of sixteen over the night. The reader failing to open was seen once in sixteen, so this is not yet enough to call that one gone. Still open: any value beside another tool. |
| M16 ✅ | **The L2 telemetry layer's cost — the first number, and it is above NFR-2 (found 2026-11-11, measuring something else).** `LhmTelemetrySource` refreshes LibreHardwareMonitor's graphics-card group once a second in every recorded session. `probe-advanced` measured that refresh, through the same library and the same group, at **14 ms of processor time** on the dev box (RTX 5080, 41 mapped sensors, about twenty of them the Direct3D engine nodes the library enumerates per card) — 1.4% of one core, where NFR-2 allows the whole Agent 1% during capture and `14_TESTING` §Hook overhead's Agent figure has never been measured. This is a measurement of the call, not yet of a session: L2's own poller was not instrumented. | **Measure L2 in a session** (the Agent's processor time over a ten-minute capture, telemetry at 1000 ms and at 2000 ms). Pre-committed: at or under 1% → this row closes with the number; above → the owner chooses between a slower default for `telemetry.interval_ms`, reading the sensors the layer keeps from NVAPI on NVIDIA cards (L3 already has most, at 0.4 ms), or amending NFR-2 to what is measured. Not decided here, and nothing about L2 changes in the Advanced-metrics train. **Measured in a real Agent, 2026-11-11 (owner decision D110), and answered (D117).** `tools/agent-cost.ps1` runs the shipped `FrameLedger.Agent.exe --console capture` against a copy of hook-harness in a scratch data folder — a session that is not hooked, so the telemetry poller runs as in every session and nothing drains frames — and reads the Agent process's own processor time at exit; the cost per second is the slope between a 45 s and a 165 s session, two runs of each. Dev box (RTX 5080, not elevated, layers `l1+lhm+nvapi`): **19.3 ms of processor time per second of session = 1.93 % of one core with Advanced metrics off** (2,312 and 2,312 ms over 45 s; 4,594 and 4,656 ms over 165 s), **20.4 ms = 2.04 % with it on** (2,984 and 3,000; 5,547 and 5,344); peak working set 113 MiB and 119 MiB. A first pass with 30 s and 90 s sessions gave 1.56 % and 2.21 % — its two short runs differed by 670 ms, which is why the lengths were raised. So the probe's number holds in a session: the Agent's steady cost is about twice NFR-2's 1 %, nearly all of it the layer every session has always used, and the new option adds about a tenth of a percent. **The owner's answer: NFR-2 is amended to ≤ 2.5 % of one core** — the limit had never been measured, the sensors keep their one reading a second, and nothing in the code changes. Not measured: a hooked session (the drain's cost on top), a session with the Agent elevated and PawnIO's groups open, another PC. |
| M14 ❓ | **Reflex latency per frame — is there a route within rules 4 and 5? (Train C, 2026-11-11.)** `17_HOOK_ENGINE` §Memory / latency names hooks on `NvAPI_D3D_SetSleepMode` / `SetLatencyMarker` and a call to `NvAPI_D3D_GetLatency`. NVAPI resolves all three through `nvapi_QueryInterface` by id — they are not exports, so a hook on them is a patch at an address learned at run time, the class refused on 2026-08-09. The route to try first needs no hook: the Overlay's own background thread **calls** `GetLatency` with the device of the swap chain it already hooks, once a second (the call returns the last 64 frames' reports). Unknown: whether calling into the driver from that thread is safe on every device kind, what it costs, what it returns when the game never enabled Reflex, and what it means for the Disclaimer's sentence about that thread. | **A spike on `hook-harness` and a stub first, then one real title.** Pre-committed: no route without a patch at a run-time address or a loader-lock call on the game's thread → Reflex stays N/A and the page says why; overhead above NFR-1 → the same. The owner says go or no on the spike's result. **2026-11-12 — the reading that comes before that spike is `spike-notes` §30** (owner decision D130: a document first, beside 0.1.0-beta.45; nothing was run). It finds: a hook on NVAPI's latency functions is the refused class, and a hook on Streamline's Reflex and PCL functions is train D's wrapper (§M15) — and would miss a game that fetched them before the attach, as `slInit` is missed (D129); the Overlay calling `slReflexGetState` itself breaks the thread contract the vendor's header states; **what remains is the route named in this row**, the Overlay calling two driver getters with the game's device, and a no-injection ETW route that gives the game-side markers only and makes the game post messages to its own window. Corrected there: `nvapi64.dll` exports **two** functions on the dev box (`nvapi_Direct_GetMethod` beside `nvapi_QueryInterface`), not one. The go or no is the owner's, and a go needs the owner's ruling that calling a driver getter with the game's device is inside rule 4. **2026-11-13 — the owner answered (D132, D133).** Route D goes to the spike this row names, on `hook-harness` and a stub `nvapi64.dll`, with the ruling: a driver's read-only getter called with the device of the swap chain the Overlay hooks is inside rule 4 (`CLAUDE.md`, the rule's note of that day). No real game before the owner has seen the result, and nothing shipped changes for the spike (`spike-notes` §31, written after 0.1.0-beta.46). Route C is **refused**; the ETW route **stays closed**, and §G is not reopened. **2026-11-13 — the harness spike is done (`spike-notes` §31), and none of its stop conditions fired.** With a stand-in module: nothing is called or loaded when `nvapi64.dll` is absent, a missing getter is refused whole, an error and a report of nothing read as what they are, and a call the driver holds for seconds stops only the thread that made it — so not the watchdog. With the installed driver (32.0.16.2114, RTX 5080), in the probe's own process and with the probe setting the markers a game would: no fault before `NvAPI_Initialize`, without markers, or across 38 million reads beside a marker-setting thread; a call costs half a microsecond to a microsecond and a half; the report is readable from markers alone, in microseconds; and the Direct3D 12 **device** — the object the Overlay already holds — is what the driver takes. What only a game can say is unanswered: a game's own device, a real report, another driver. **The owner's next word is go or no for one real title**; a go is a plan of its own first. **2026-11-13, the same evening — go (D136)**: a plan for one title, Cyberpunk 2077; no code before the plan is approved, and no release carrying it before a stop while a game runs has been exercised on 0.1.0-beta.46 (owner-only item 44 (d)). **2026-11-13, the plan and four more answers (D138–D141).** The read has **no switch of its own**: it is part of Advanced metrics, so after the release it reaches every Direct3D 12 game that loaded the driver's `nvapi64.dll`, for everyone who switched Advanced metrics on — "one title" is the order of the owner's first runs, not a limit in code (D138). The probe ran a leg with a sleep mode first (D139; `spike-notes` §31, *The leg with a sleep*): **the getters do not wait behind `NvAPI_D3D_Sleep`** — thirty-one million reads beside a thread that slept 97 % of the time, none of a millisecond; a read after a sleeping frame costs about 2.6 µs. An `nvapi64.dll` loaded from the game's own folder is refused with the reason (D140). One call of 2 ms or more switches the read off until the game exits (D141). The plan's design, as reviewed against the source, is in [`handoff/history/0.1.0-beta.46.md`](handoff/history/0.1.0-beta.46.md) §The train after 0.1.0-beta.46. **2026-11-13, night — written; released as 0.1.0Line truncated
| M17 | **What the input reader does on a real PC with a real controller — unmeasured (2026-11-14, owner decision D157: built without a probe).** Written and tested against a Windows whose answers the tests write, and run on the developer's PC with no controller connected. Open, each read from the counts a session stores (`InputHealth`) and the Agent's log: (a) **whether XInput answers a program with no window in front** — Microsoft's `XInputEnable` page says the system switches controller input by focus; the reader counts the slices in which a device's own reports changed and XInput said nothing, and falls back to the reports after ten; (b) whether raw input delivers, in the background, the reports of an Xbox pad on USB, on the wireless adapter and on Bluetooth, and of a DualSense on USB and on Bluetooth; (c) whether XInput returns a battery for an Xbox pad on Bluetooth (reported not to); (d) whether a DualSense's reports are laid out as `Domain.Input.DualSenseReport` reads them, and whether its battery is there on Bluetooth with Steam running; (e) whether a controller's own input moves `GetLastInputInfo`'s time (if it does, a controller reads as *both*); (f) **the reader's cost with a controller that sends several hundred reports a second**, against NFR-2's 2.5 % of one core, of which about 2 % is already used — `tools/agent-cost.ps1` measures it with no controller only. **Measured 2026-11-14, the real Agent, no controller connected**: in four sessions of 30 and 90 s the reader took 277 and 834 slices, Windows accepted the registration, XInput's library and the time of the last input were there, and the reader's thread used 15–62 ms of processor time — under 0.2 % of one core in the worst of them. The whole Agent, per second of session: 2.06 % of one core with nothing optional, 1.54 % with input read, 1.61 % with Advanced metrics — three numbers inside the tool's own run-to-run variation (the two 90 s medians with and without input differ by 48 ms), so **the reader's cost is not distinguishable from nothing with no controller connected, and unmeasured with one**; (g) an unelevated Agent beside a game that runs as administrator. Owner-only item 48 (`HANDOFF`) |
| M15 🅓 | **Decided 2026-11-14 (D154): not built. The owner closed Advanced metrics with the refusal standing; the ten entries are listed as not read, with the reason.** ~~**The Streamline state behind `slGetFeatureFunction` — re-examined, not reopened (Train D, 2026-11-11).**~~ The owner asked for the refusal in `handoff/history/p0-queue-1-6.md` to be looked at again. `18_GPU_VENDOR_APIS` §The trains states the route to try (hook the export, hand back a wrapper for a fixed list of names) and what it raises: the wrapper is a write to what the game receives, which rule 4 forbids as written; a wrapper must outlive the Overlay's unhook; a game that fetched its functions before the hook existed is never seen. | **A written design against each of the five grounds, then a spike.** Pre-committed: any ground unanswered → the route stays refused, and `sl.dlssg.*`, `sl.reflex.*` and the rest of that block read N/A with "refused" as the reason. Proceeding needs the owner's amendment of rule 4, asked with the rule quoted. |
| M10 ✅ | ~~PDH `\GPU Engine(*)\Utilization Percentage` summed across engines does not reproduce the Task Manager figure the doc invokes. Decide what we actually report and label it accordingly~~ **Decided 2026-09-09 (PR-E1): L1 does not read the engine counters at all.** `LoadPct` is L2's vendor-reported `GPU Core` load (measured ✓ on NVIDIA, §M5 row R1) and is labelled *GPU load (vendor)* wherever it is shown; on a machine without L2 the field is N/A, never a sum that is not the number the user expects. What L1 does read from PDH is one counter, `\GPU Adapter Memory(luid_…_phys_0)\Dedicated Usage`, bound by LUID — the figure Task Manager labels "Dedicated GPU memory", measured 1301 MB at an idle desktop on the RTX 5080. Reopening this needs a measurement of `max(engine)` against Task Manager's own number, not a decision |
+168
View File
@@ -0,0 +1,168 @@
# 21 — Input devices: controllers, and keyboard-and-mouse activity
What FrameLedger reads about game controllers and about the keyboard and mouse, from where, and what it never reads.
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 — the Agent records it; the App does not show it yet.** A session recorded with the option
> on, after the terms were accepted, stores what it was played with: the model and the arithmetic
> (`FrameLedger.Domain.Input`, `FrameLedger.Application.Input`, `Application.Recording.InputSessionBuilder`), the
> storage (schema 0024, the `.partial` file's chunk 11 — `06_DATA_MODEL`), the reader (`Application.Input.InputReader`,
> `Infrastructure.Input`) and its composition into the Agent (`capture.input_devices`, `Application.Input.InputTerms`)
> are written and under test. The screens, the store's word and the input libraries 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)
The request: whether a game supports controllers, on the game's page; the share of a session played with a controller
and with the keyboard; how often a controller connected and disconnected in a session; the battery state that lasted
longest; switches between makers' controllers and each maker's share; stored, and drawn; Xbox controllers and the
DualSense first.
| | Decision |
|---|---|
| **D155** | Controllers are read **by the Agent, from outside the game**. No hook is added to a game and CLAUDE.md rule 4 is untouched. A session that is not hooked has the numbers as a hooked one does. |
| **D156** | The reading is **on unless switched off** (Settings ▸ Controllers and input, `capture.input_devices`), and **reads nothing until the Privacy Policy that describes it — 2.22 or later — has been accepted on the PC**. An Agent that the logon task started after an update records sessions without it until the App has been opened once. |
| **D157** | **Built without a probe.** Asked whether to run a probe tool with real controllers first, the owner chose to build straight. So every source says what it did (§What the reader says about itself), and each pull request and `LIMITATIONS.md` say what was verified against hand-made data only. |
| **D158** | Keyboard and mouse are **one class, known only by the time of the last input** (`GetLastInputInfo`). No Raw Input registration for a keyboard or a mouse, no hook: no key ever enters FrameLedger's process. |
| **D159** | **Nothing is ever sent to a controller**: no output report, no feature-report request, no `XInputSetState`. A DualSense on Bluetooth therefore has a battery level only when Steam or the game has already switched it to its long report (§DualSense). |
| **D160** | The numbers are **in the CSV/JSON export and in a bug bundle** — they are columns of `sessions`, as the display mode's are — and the Privacy Policy's §3A says so. |
| **D161** | **A session that is not hooked is: duration, hardware telemetry, the reason — and what the Agent reads from outside the game** (the game's memory since beta.12, controllers now). Every field measured inside the game still reads N/A. CLAUDE.md's sentence is amended with the pull request that makes it true. |
| **D162** | Also built: the number of switches between a controller and the keyboard and mouse, and the share of time with no input; marks on the frame-time chart where a controller connected, dropped or ran low; a battery's first and last level and its rate; the kind of connection; a note where Steam Input presented the controller as an Xbox pad; a trend metric, a row in Compare, and "usually played with" on the game's page. |
| **D163** | "Supports controllers" is **three pieces of evidence, never a verdict**: what Steam's own file on the disk says (no network: rule 8), which input libraries the game loaded, and how the game was actually played. From outside a game one can know that a controller was in use while the game was in front — not what the game did with it. |
## The switch, and the terms
`capture.input_devices` — Settings ▸ Recording ▸ *Controllers and input* — is **on unless switched off** (D156), and
is read at each session's start like every setting the Agent reads. On is not enough: the Agent is usually started
at logon, and after an update that is before the App has shown the Privacy Policy that describes this reading. So
`SettingsRecorderPolicy` gives a session the reader only when `legal_acceptance` holds the Privacy Policy at
`InputTerms.MinimumPrivacyVersion` (2.22) or later. Until then the session reads nothing of controllers or of the
keyboard and mouse, stores none of schema 0024's columns, and says so: the slot `input=terms_pending` in
`sessions.capture_notes` (`CaptureNotes.InputHeldForTerms`), and a line in its `.partial` file's notes. An operator's console with no acceptance store reads
nothing either. Off, or held back, a session is byte for byte what it was before the reading existed.
## What is read, and from where
Everything is a Windows API in a library Windows ships. **No third-party library is added.**
| Source | What it gives | Why this one |
|---|---|---|
| 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`) |
| Steam's `appcache\appinfo.vdf`, on the disk | whether the store lists controller support for a library game | a local file: no request is made (rule 8) |
**Rejected, with the reason** (the checklist of `18_GPU_VENDOR_APIS` §Checklist applies to any library):
- **Windows.Gaming.Input** — its readings stop when the program is not in front, which the Agent never is.
- **GameInput** — on a PC it is a NuGet package under Microsoft's licence terms with a redistributable to install.
- **Opening the HID device** (`CreateFile`) — a handle of FrameLedger's on a controller can make a game's, or a
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
Which button, where a stick or a trigger is, the motion sensors, the touchpad; which key, what was typed, where the
mouse is; a controller's serial number, its Bluetooth address, its device path. A report is looked at to answer one
question — *is anything on this pad in use?* — and, for a DualSense, to take its battery byte; the answer is kept and
the report is not. `InputSessionBuilderTests` hold the stored JSON to a list of keys, so a key that could carry an
identifier has to be added to a test first.
## Who a controller is
By its USB vendor and product ids only (`Domain.Input.ControllerCatalog`): Microsoft is the Xbox family, Sony
PlayStation, Nintendo Nintendo, anything else *other* — except that a pad Windows presents through XInput is in the
Xbox family whoever made it, because that is all Windows says of it. A model has a name only where the catalog lists
its ids; a wrong name would be worse than none. Two pads of one model on one kind of connection cannot be told apart
across a reconnect, and are not.
## XInput
A state is a pad *in use* when a button is down, a trigger is past `XINPUT_GAMEPAD_TRIGGER_THRESHOLD` or a stick is
outside its `XINPUT_GAMEPAD_*_THUMB_DEADZONE` (`Domain.Input.XInputPad`) — a stick held counts, one that drifts inside
the dead zone does not. Its battery is XInput's words: a wired pad, or four levels with no word for charging.
Two things about XInput are not established and are what item 48 is for: Microsoft's page for `XInputEnable` says
that on Windows 10 and later "game controller input is automatically enabled/disabled by the system based on the
application window focus", which may mean a program in the background reads a neutral state; and a pad on Bluetooth
is reported not to answer `XInputGetBatteryInformation`. XInput also has no documented way to say which device one of
its four pads is.
## DualSense
Sony's 054C:0CE6, and the Edge, 054C:0DF2 (`Domain.Input.DualSenseReport`). Three reports:
| Connection | Report | What it carries |
|---|---|---|
| USB | `0x01`, 64 bytes | sticks, triggers, buttons — and the battery: a level in tenths and what the battery is doing |
| Bluetooth, as connected | `0x01`, 10 bytes | sticks, buttons, triggers. **No battery** |
| Bluetooth, once switched | `0x31`, 78 bytes | the USB report's body, one byte later |
The pad sends the short report until some program asks it for a feature report or sends it an output report; from then
until it reconnects it sends the long one. **FrameLedger never asks** (D159): a game that reads the short report through
DirectInput would lose its input. So over Bluetooth the level is there when Steam or the game switched the pad, and is
not otherwise. Windows hands every report of a device over at the length of the device's longest, so the short report
arrives padded to 78 bytes with the id the USB report has: the connection, not the length, says which layout a report
`0x01` has.
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
registration, how many reports came and how many could not be read, whether XInput's library was there and how many
states it returned, how often a controller's own reports said *in use* while XInput said nothing, whether the time of
the last input could be read, how many slices were taken and how much processor time the reader's thread used. Counts
and yes-or-no answers; nothing in it names a device.
+9
View File
@@ -1179,6 +1179,15 @@ Where each owner decision is recorded — the file and its section, and a label
| D152 | [`18_GPU_VENDOR_APIS.md`](18_GPU_VENDOR_APIS.md) §The inventory | the two GPU labels say what each figure is — *the driver's own figure*, *between the driver's start and end marks* — not "idle time excluded / included": item 47 counted the active time as the longer in Cyberpunk 2077. Strings only; numbers and means unchanged |
| D153 | [`spike-notes/30-reflex-latency.md`](spike-notes/30-reflex-latency.md) *Added 2026-11-14* | the owner's word: of Reflex it is enough to tell whether a game has it. Reflex and PCL leave train D (`sl.pcl.markers` stays refused), and D141's stop is not changed for a game's first seconds. My reading of one sentence; nothing shipped is removed by it |
| D154 | [`18_GPU_VENDOR_APIS.md`](18_GPU_VENDOR_APIS.md) §The trains, [`20_OPEN_QUESTIONS.md`](20_OPEN_QUESTIONS.md) §M15 | Advanced metrics is closed: train D is not built, the ten Streamline entries that waited for a spike are not read (`RefusedRoute`), rule 4 is not amended for them. Nothing shipped is removed |
| D155 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | controllers are read by the Agent, from outside the game: no hook is added, rule 4 is untouched, and a session that is not hooked has the numbers too |
| D156 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | the reading is on unless switched off (`capture.input_devices`), and reads nothing until the Privacy Policy that describes it (2.22 or later) has been accepted on the PC |
| D157 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | built without a probe run on real controllers first ("Xây thẳng"): every source reports what it did, and what was verified against hand-made data only is said in each pull request |
| D158 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | keyboard and mouse are one class known only by `GetLastInputInfo`'s time: no Raw Input for them, no hook, no key in the process |
| D159 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §DualSense | nothing is ever sent to a controller; a DualSense on Bluetooth has a battery level only where Steam or the game switched it |
| D160 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | the numbers are columns of `sessions`, so they are in the CSV/JSON export and in a bug bundle, and the Privacy Policy's §3A says so |
| D161 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | a session that is not hooked is duration, hardware telemetry, the reason — and what the Agent reads from outside the game; CLAUDE.md's sentence is amended with the pull request that makes it true |
| D162 | [`03_METRICS.md`](03_METRICS.md) §Input | also built: switches of method and the share with no input, marks on the frame-time chart, a battery's first and last level and its rate, the kind of connection, the Steam Input note, a trend metric, a Compare row, "usually played with" |
| D163 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | "supports controllers" is three pieces of evidence and never a verdict: Steam's own file on the disk (no network), the input libraries the game loaded, how the game was played |
| D109 | [`../legal/DISCLAIMER.md`](../legal/DISCLAIMER.md) §5, §5A | asked on 2026-11-11 with both sentences quoted: the Disclaimer goes to 2.15 with the Privacy Policy — PawnIO and the admin mode are no longer "for the CPU temperature" alone; with Advanced metrics on they also read the processor's, the memory's and the motherboard's sensors. The admin mode's disclosure follows (`agent-admin-dialog/2`) |
---
+1
View File
@@ -69,6 +69,7 @@ are safety items, and something listed there as unresolved should not be built t
| [`18_GPU_VENDOR_APIS.md`](18_GPU_VENDOR_APIS.md) | Telemetry layers (DXGI/PDH, LibreHardwareMonitor, NVAPI), the game process's memory, licences |
| [`19_SAFETY_AND_ANTICHEAT.md`](19_SAFETY_AND_ANTICHEAT.md) | The anti-cheat guard, what a finding does, the user-mode exception, what will never be built |
| [`20_OPEN_QUESTIONS.md`](20_OPEN_QUESTIONS.md) | Every unresolved question, defect and measurement, with its status marker |
| [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) | Controllers and keyboard-and-mouse activity: what is read from outside the game, from where, and what never is |
| [`HANDOFF.md`](HANDOFF.md) | Sequencing, the open owner-only items, the index of the owner's decisions |
| [`handoff/`](handoff/) | Since beta.24 (D66): the history of every train and phase, the passed owner-only items, the traps — moved out of `HANDOFF.md` verbatim |
| [`open-questions/`](open-questions/) | Since beta.24 (D66): the entries §S24 marks resolved, moved out of `20_OPEN_QUESTIONS.md` verbatim — a table there lists them |
+20
View File
@@ -63,6 +63,26 @@ are kept because they record what each version changed and why (owner decision D
>
> Version 2.5 (2026-09-27, 0.1.0-beta.10) adds how a tracked game's window is shown — read from Windows — and the engine build name read from an Unreal Engine game's executable. It is also the first version to say two things the software already did: it reads the **content** of a library game's executable (markers in its first 8 MB and its import table, since the detection of engines and features; and, when a session starts, the graphics-library markers in the whole file), and it reads the processor load and the memory in use (since 0.1.0-beta.3). Nothing here leaves your device, as before.
### What version 2.22 of the Privacy Policy and 2.18 of the Disclaimer changed (0.1.0-beta.50)
**Both documents said FrameLedger never reads input, and it now reads that a controller, or the keyboard or mouse,
is in use** (owner decisions D155–D163; the sentences were shown to the owner with the plan of 2026-11-14 and
approved with it). Until this version the Privacy Policy's §4 said it "does not read game saves, chat, input
content", the Disclaimer's §1 that it never reads "save files, input, chat", the README that it "never touches saves
or input", and the guide that it never reads "your input". The **Privacy Policy** (2.22) adds to §1 what a session
stores of controllers and input and what it never does — which button, stick, trigger or key, text, the mouse's
position, a serial number, a Bluetooth address; to §3A that these numbers, unlike Advanced metrics', **are** in an
export and in a bug report (D160); to §4 what is observed — the controllers' reports, looked at and not kept,
XInput's state and battery, the time of the last keyboard or mouse input, the window in front — and that nothing is
opened or sent; and narrows the sentence after it to what is still true. It also says, in §1 and §4, that nothing
of this is read until that version has been accepted on the PC (D156): the option is on unless switched off, and an
Agent that started before the App showed the document records without it. The **Disclaimer** (2.18) gains a
paragraph in §1 for what is read from outside the game about controllers, the keyboard and the mouse, and its "what
it never does" names what is kept instead of the word "input", and adds that nothing is sent to a controller
(D159). The **accuracy statement** — and so the README and the Disclaimer — gains a paragraph that ends: none of
this had been read from a real controller when it was written. The trademarks notice names Sony's and Nintendo's
products, which the App now shows as a controller's model.
### What version 2.21 of the Privacy Policy and 2.17 of the Disclaimer changed (0.1.0-beta.48)
**Two real games had been read, and the texts still said none** (owner decisions D142–D145; the wording's main
+4 -2
View File
@@ -16,8 +16,10 @@ your decision and your risk.
refuses — or stops measuring at the next check — and turns hooking off for that game. **There is no switch that
overrides this**, apart from the one narrow exception below.
- **It never hides.** It keeps its real name and does nothing to avoid being seen by security software.
- **It never reads or changes the game's memory**, its saves or your input. It only observes the graphics calls the
game makes.
- **It never reads or changes the game's memory** or its saves, and never what you type or which buttons you press.
Inside the game it only observes the graphics calls the game makes. From outside it — unless you switch
*Controllers and input* off in Settings — it notes whether a controller, or the keyboard or mouse, is in use, and
sends nothing to a controller.
## What it cannot promise
+1
View File
@@ -22,6 +22,7 @@ The link under them, *Read what the hook does and does not do*, opens the safety
| **Minimum session length (s)** | A shorter session is not kept. 5 to 600 seconds. *Agent.* | 30 |
| **Sensor interval (ms)** | How often the PC's sensors are read during a session. 500 to 2000 ms. With a value above 1000, not every reading of NVIDIA's latency report — made about once a second inside the game — becomes a point: each point is still one reading ([Advanced metrics](12-advanced-metrics.md)). *Agent.* | 1000 |
| **Raw series kept per game** | How many of each game's newest sessions keep their per-frame data; older ones keep their statistics. 0 keeps everything. *Agent.* | 20 |
| **Controllers and input** | Records what a session was played with: which game controllers were connected and in use, their battery level, and whether the keyboard or mouse was in use — as times, read from Windows and never from the game. No button, stick, key or text is kept, and nothing is sent to a controller. Nothing is read until you have accepted the Privacy Policy that describes it, so after an update the first sessions have no such figures until FrameLedger has been opened once. Off: nothing of this is read or stored. It applies from the next session; a session recorded while it was off is not filled in later. *Agent.* | On |
| **Advanced metrics** | Reads more from the graphics driver and the hardware sensors during a session — the graphics card's memory and load in detail, each fan and voltage, what your display can do, the driver's settings for the game — and stores it with the session. In a game FrameLedger measures from inside it also reads what the game tells DLSS, Streamline and FSR, and — on an NVIDIA card, in a Direct3D 12 game that uses NVIDIA's library — asks the graphics driver about once a second how long each stage of a frame took ([Advanced metrics](12-advanced-metrics.md)). Off: nothing more is read or stored. It applies from the next session; a session recorded while it was off is not filled in later. While it is on, the **Advanced** page is in the list on the left ([Advanced metrics](12-advanced-metrics.md)). *Agent.* | Off |
## Data
+10
View File
@@ -106,6 +106,16 @@
> temperature in every session, and, on NVIDIA cards only, how much of the time its power limit or its temperature held
> it back, read once a second; and frames per watt — the game's own frames per second for each watt the graphics card
> drew, never counting generated frames, `N/A` where the game's own frame rate is not known.
> - **Controllers and input (since beta.50; on unless you switch it off in Settings, and only once you have accepted
> the Privacy Policy that describes it):** how much of the time a game was in front it was played with a
> controller, with the keyboard or mouse, with both or with neither; each controller's connections and drops; its
> battery. All of it is read from Windows, from outside the game: it says a controller was in use while the game
> was in front, not what the game did with it. Keyboard and mouse are one figure — only the time of the last input
> is read — and input a program injects (Steam Input mapping a controller to keys, a macro tool) counts as keyboard
> and mouse. An Xbox-compatible controller and a DualSense are read for use; another maker's controller is listed
> and never counted as in use. A DualSense on Bluetooth reports its battery only where Steam or the game has
> switched it to its long report, and an Xbox controller on Bluetooth may report none. **None of this had been
> read from a real controller when it was written (2026-11-14)**: it was checked against data written by hand.
> - **Processor and memory:** how busy the processor was (time busy, all cores together — not the
> frequency-scaled figure Task Manager draws) and how much system memory was in use, read from
> Windows once a second and charted. Processor temperature is read only when the Agent runs as
+14 -2
View File
@@ -1,6 +1,6 @@
# FrameLedger — Disclaimer
**Version:** 2.17 · **Effective:** {{RELEASE_DATE}}
**Version:** 2.18 · **Effective:** {{RELEASE_DATE}}
## 0. This is pre-release software
@@ -47,9 +47,11 @@ Install it somewhere only you can write to, and verify the published SHA-256 che
**What it reads about the game from outside it, in every session:** the game process's own memory use — its dedicated and shared video memory and its working sets, the figures Windows' Task Manager shows — from Windows' performance counters and process-memory information. For a game it does not inject into, FrameLedger opens the game's process for this with the least access Windows offers, once a second, and closes it again; it reads nothing inside the process.
**What it reads about controllers, the keyboard and the mouse, from outside the game, unless you switch it off:** which game controllers are connected, whether one is in use, its battery level, and the time of the last keyboard or mouse input — to say how much of a session was played with a controller and how much with the keyboard or mouse. It asks Windows, never the game; it opens no controller and sends nothing to one; and it keeps no key, button or text (the Privacy Policy says exactly what is kept). It reads none of this until you have accepted the Privacy Policy that describes it.
> **What of that list is observed today is stated once, in §4 below** (the block `legal/ACCURACY.md` carries, dated). The list here describes what the software is designed to observe, and the boundary — API arguments, and the one report asked of the graphics driver that the line above names; nothing of the game's own memory — holds for all of it.
**What it never does:** read or write the game's memory outside those API arguments; read save files, input, chat, or network traffic; modify game behavior; hide itself from any security software; or install a kernel driver of its own.
**What it never does:** read or write the game's memory outside those API arguments; read save files, chat, or network traffic; read what you type or which buttons you press — it keeps only whether a controller, or the keyboard or mouse, was in use, read from Windows and never from the game; send anything to a controller; modify game behavior; hide itself from any security software; or install a kernel driver of its own.
## 2. Anti-cheat systems — the main risk to you
@@ -219,6 +221,16 @@ Frame timing is derived from high-resolution timestamps taken at the moment the
> temperature in every session, and, on NVIDIA cards only, how much of the time its power limit or its temperature held
> it back, read once a second; and frames per watt — the game's own frames per second for each watt the graphics card
> drew, never counting generated frames, `N/A` where the game's own frame rate is not known.
> - **Controllers and input (since beta.50; on unless you switch it off in Settings, and only once you have accepted
> the Privacy Policy that describes it):** how much of the time a game was in front it was played with a
> controller, with the keyboard or mouse, with both or with neither; each controller's connections and drops; its
> battery. All of it is read from Windows, from outside the game: it says a controller was in use while the game
> was in front, not what the game did with it. Keyboard and mouse are one figure — only the time of the last input
> is read — and input a program injects (Steam Input mapping a controller to keys, a macro tool) counts as keyboard
> and mouse. An Xbox-compatible controller and a DualSense are read for use; another maker's controller is listed
> and never counted as in use. A DualSense on Bluetooth reports its battery only where Steam or the game has
> switched it to its long report, and an Xbox controller on Bluetooth may report none. **None of this had been
> read from a real controller when it was written (2026-11-14)**: it was checked against data written by hand.
> - **Processor and memory:** how busy the processor was (time busy, all cores together — not the
> frequency-scaled figure Task Manager draws) and how much system memory was in use, read from
> Windows once a second and charted. Processor temperature is read only when the Agent runs as
+5 -4
View File
@@ -1,6 +1,6 @@
# FrameLedger — Privacy Policy
**Version:** 2.21 · **Effective:** {{RELEASE_DATE}}
**Version:** 2.22 · **Effective:** {{RELEASE_DATE}}
**Short version: everything stays on your PC. FrameLedger has no accounts, no telemetry, no analytics, and never uploads your data anywhere.**
@@ -12,6 +12,7 @@ Stored in `%LOCALAPPDATA%\FrameLedger` on your device:
- Images you choose for a game (Edit…), copied into the `covers` folder; choosing the store's image again, or removing the game together with its sessions, deletes the copy. Artwork a store's app keeps on your PC, or a game ships in its own folder, is shown from where it is and not copied.
- Performance sessions: frame timing series, computed statistics, hardware sensor series (temperatures, load, power, memory usage, and the graphics card's clock speeds, fan speed, memory temperature and whether its power limit or heat held it back), the game's own memory use (its dedicated and shared video memory, private working set, working set and commit, once a second), session duration, crash flags, the graphics driver's settings the game ran under (NVIDIA only), how the game's window was shown (full-screen, borderless or windowed, for how long, its size and the monitor's), tags and notes you write.
- **Only while Settings ▸ Advanced metrics is on** (it is off unless you switch it on), with each session: more hardware sensor series — the graphics card's memory use in detail, its load by part, its clocks, voltages, currents, power, each fan and its video encoder's use; and, when the capture agent runs as administrator with PawnIO installed, the processor's temperatures, load, clocks, power and voltages by core, the memory in use and its modules' temperatures, and the motherboard's temperatures, fans and voltages — and a description of the hardware: the graphics card's firmware version, architecture, bus and memory sizes, the graphics driver's package and the chipset it names, the motherboard's and the memory modules' model names, what each connected display can do (the HDR formats it accepts, its brightness range, variable refresh), whether variable refresh was in use on the display the game ran on and the colour space the game presented in, and the graphics driver's settings — its global ones and the ones it holds for the game (NVIDIA only). For a game FrameLedger injects into, a session then also stores what the game itself passed to its upscaler in the calls FrameLedger intercepts: the output size, the model presets and the exposure values it gave DLSS, whether it said its colour buffers are HDR, auto-exposure and alpha upscaling; and the sharpening, the size of the jitter, the exposure, the depth range, the lowest and highest field of view and the flags it gave FSR, the frame time it reported to FSR, and FSR's own video memory when the game asked for it; what the game told NVIDIA Streamline about each frame — the size of the jitter, the motion-vector scale, the depth range and whether depth is inverted, the lowest and highest field of view, the aspect ratio, whether the projection is orthographic, how its motion vectors are stored and how often it reset the upscaler's history; and how it configured FSR frame generation — on or off, whether it may run asynchronously, its flags, whether only generated frames are presented, and the rectangle it generates in; and what NVIDIA Streamline answered when the game asked it about a feature — which features the game asked about, the version of each and of its NGX model, and what each requires: the graphics APIs it supports, whether V-Sync must be off and hardware-accelerated GPU scheduling on, how many processor threads, viewports and buffers, and the versions of Windows and of the graphics driver that Streamline found beside the ones the feature needs ; and, for each Streamline feature the game asks about or controls: whether Streamline answers that it is supported, whether it is loaded, whether the game switched it on or off while it ran, and how many times its resources were allocated and freed; and whether the game shut Streamline down, and how many times — never the lists Streamline's answer points to (the buffers' names, the names of Vulkan extensions and features), never what identifies the graphics card that the game hands over with its question, never the content of a graphics resource, and never where the game's camera is, which way it looks, or its matrices. For a Direct3D 12 game that had itself loaded NVIDIA's driver library, a session also stores what the graphics driver reports about the game's frames when FrameLedger asks it, about once a second, from inside the game: how long each stage of a frame took — simulation, render submit, present, the driver, the operating system's queue and the graphics card, and the whole from the start of simulation to the end of the graphics card's work — as averages in microseconds, with two figures the driver works out itself (how long the graphics card was actually at work on a frame, and the time from the end of one frame's work to the end of the next), and the driver's low-latency state (five switches it reports, and the frame-generation multipliers it gave during the session) — never a time of day, and never the moment the player pressed anything. No serial number, no display identification data (EDID) and no list of other programs is read or stored. Switching the option off stops the reading, inside a game as well; what earlier sessions stored stays with them until you delete those sessions.
- **Unless you switch Settings ▸ Controllers and input off** — and it reads nothing until you have accepted this version of this document — with each session: which game controllers were connected (the model's name, its maker and how it was connected: USB, Bluetooth or a wireless adapter), how many times each connected and disconnected, its battery level when the controller reports one, and, for each second the game was in front, whether a controller was in use, whether the keyboard or mouse was in use, both, or neither. Never which button, stick, trigger or key, never text, never where the mouse is, and never a serial number or a Bluetooth address. Switching the option off stops the reading; what earlier sessions stored stays with them until you delete those sessions.
- A hardware snapshot per session (CPU/GPU model, driver version, RAM size, OS build, display mode) used for the "what changed between sessions" feature.
- App settings, logs (rotated daily — the app keeps 7 days, the capture agent 14 — including the logs written by the component loaded into games), and, after a crash of the app itself, crash dump files.
- Which games you enabled code injection for, and when you consented.
@@ -39,13 +40,13 @@ The "Report a bug" feature builds a zip file **on your device**, shows you exact
## 3A. Sharing an export or a bug report
An exported session (CSV or JSON) and a bug report can contain your games' names and **the paths to their files** — which include your **Windows user name** when a game is installed under your user folder — your hardware model, graphics driver and Windows build, the times you played, and your tags and notes. What a session stores only while Advanced metrics is on (§1) is in neither: an export and a bug report carry what they carried before. A bug report removes user directory paths from its logs; an export is written as it is. Look at a file before you share it. Once you share it, it is outside FrameLedger: whoever receives it, and the site you post it to, can read it under their own terms.
An exported session (CSV or JSON) and a bug report can contain your games' names and **the paths to their files** — which include your **Windows user name** when a game is installed under your user folder — your hardware model, graphics driver and Windows build, the times you played, and your tags and notes. What a session stores only while Advanced metrics is on (§1) is in neither. What a session stores of controllers and input (§1) is in both: the shares of its time played with a controller and with the keyboard or mouse, and each controller's model name, how it was connected, its battery levels and its connection counts. A bug report removes user directory paths from its logs; an export is written as it is. Look at a file before you share it. Once you share it, it is outside FrameLedger: whoever receives it, and the site you post it to, can read it under their own terms.
## 4. What the app can technically observe
To do its job, FrameLedger observes: which of *your tracked* executables — the entries in your library whose recording is on — are running, and their process trees; whether a game you enabled hooking for runs in an app container, and which of Windows' code-protection settings it runs under (for example, accepting only Microsoft-signed code), read from Windows before any injection; the parameters your games pass to the graphics APIs it intercepts (presentation, upscaling, ray tracing, pipeline creation) — and, only while Advanced metrics is on, more of the parameters of the upscaling calls, and the parameters of ten further calls it begins to intercept in a game only once a session with that option on has started there (the constants the game gives NVIDIA Streamline for each frame, the game's configuration of FSR frame generation, Streamline's answers to the game's four questions about a feature — which version it is, what it requires, whether it is supported and whether it is loaded — and the game switching a feature on or off, allocating and freeing its resources, and shutting Streamline down), which are then stored with the session (sizes, presets, exposure, sharpening, the jitter's size, the motion-vector scale, the depth range, the range of the field of view, flags, the reported frame time, the upscaler's own memory, how frame generation is configured, the versions and requirements of Streamline's features, whether each is supported and loaded, and how often the game switched it, allocated and freed its resources and shut Streamline down), never the camera's position, direction or matrices, and never what identifies the graphics card; and — only while Advanced metrics is on, only in a Direct3D 12 game that had itself loaded NVIDIA's driver library — the graphics driver's own report of the game's last frames and its low-latency state, which the component asks that driver for itself about once a second (it makes that call; the game does not), keeping only how long each stage took; the memory use of a tracked game's process — its dedicated and shared video memory, from Windows' GPU performance counters, and its working sets and commit, from Windows' process-memory information, for which a game it does not inject into is opened with the least access Windows offers and closed again (never its memory's content); loaded module names of a game being captured, the version information of its upscaling, frame-generation and neural-rendering libraries, and whether each was loaded from the game's folder or from the graphics driver's own copy (for detection and for the anti-cheat safety check); the names of the files in each library game's install folder, the version information of its executable and of the upscaling and neural-rendering libraries it ships, the content of its executable file (the markers of the engine and of the graphics libraries it carries, the libraries it imports, and the engine build name an Unreal Engine game carries), the version marks an engine keeps in its own files (Unity's player library and the header of its data file, the header of a Godot data pack, an RPG Maker game's title, core script and Game.ini, the library Game.ini names, and the version file of a Ren'Py game's engine), and the store files that name it (Steam's and GOG's, on your disk) and, for a game the Xbox app or the Microsoft Store installed, the package files in its install folder that describe it (`MicrosoftGame.config` and `appxmanifest.xml`) — to detect its engine, its engine version and its features and to check it for anti-cheat before any injection is possible; the lists of installed games that the Steam, GOG GALAXY, Epic Games and itch apps keep on your disk, and where GOG GALAXY is installed, the folders the Xbox app installs games into on each drive (named by the `.GamingRoot` file at the drive's root) with each game's package files, and Windows' answer to whether that game's package is installed for you — read when you import your library and when you press Play, to find the store that installed a game and hand the game to that store's app — Steam's and GOG GALAXY's also when you open a game's page, to find the artwork their apps keep for it; the cover and banner images that the Steam and GOG GALAXY apps keep on your disk for a game in your library and the logo and splash-screen images a game from the Xbox app ships in its own folder — read to show them on its page, never copied or sent anywhere; the size, position and state of a tracked game's window and the monitor it is on, read from Windows and not from the game, and — for a game FrameLedger injects into — whether the game asked for exclusive full-screen; the NVIDIA driver's settings for your tracked executables (read only: the DLSS and frame-generation overrides the NVIDIA App set); hardware sensor values from your graphics driver's own libraries; and — only while Advanced metrics is on — that driver's description of the graphLine truncated
To do its job, FrameLedger observes: which of *your tracked* executables — the entries in your library whose recording is on — are running, and their process trees; whether a game you enabled hooking for runs in an app container, and which of Windows' code-protection settings it runs under (for example, accepting only Microsoft-signed code), read from Windows before any injection; the parameters your games pass to the graphics APIs it intercepts (presentation, upscaling, ray tracing, pipeline creation) — and, only while Advanced metrics is on, more of the parameters of the upscaling calls, and the parameters of ten further calls it begins to intercept in a game only once a session with that option on has started there (the constants the game gives NVIDIA Streamline for each frame, the game's configuration of FSR frame generation, Streamline's answers to the game's four questions about a feature — which version it is, what it requires, whether it is supported and whether it is loaded — and the game switching a feature on or off, allocating and freeing its resources, and shutting Streamline down), which are then stored with the session (sizes, presets, exposure, sharpening, the jitter's size, the motion-vector scale, the depth range, the range of the field of view, flags, the reported frame time, the upscaler's own memory, how frame generation is configured, the versions and requirements of Streamline's features, whether each is supported and loaded, and how often the game switched it, allocated and freed its resources and shut Streamline down), never the camera's position, direction or matrices, and never what identifies the graphics card; and — only while Advanced metrics is on, only in a Direct3D 12 game that had itself loaded NVIDIA's driver library — the graphics driver's own report of the game's last frames and its low-latency state, which the component asks that driver for itself about once a second (it makes that call; the game does not), keeping only how long each stage took; the memory use of a tracked game's process — its dedicated and shared video memory, from Windows' GPU performance counters, and its working sets and commit, from Windows' process-memory information, for which a game it does not inject into is opened with the least access Windows offers and closed again (never its memory's content); loaded module names of a game being captured, the version information of its upscaling, frame-generation and neural-rendering libraries, and whether each was loaded from the game's folder or from the graphics driver's own copy (for detection and for the anti-cheat safety check); the names of the files in each library game's install folder, the version information of its executable and of the upscaling and neural-rendering libraries it ships, the content of its executable file (the markers of the engine and of the graphics libraries it carries, the libraries it imports, and the engine build name an Unreal Engine game carries), the version marks an engine keeps in its own files (Unity's player library and the header of its data file, the header of a Godot data pack, an RPG Maker game's title, core script and Game.ini, the library Game.ini names, and the version file of a Ren'Py game's engine), and the store files that name it (Steam's and GOG's, on your disk) and, for a game the Xbox app or the Microsoft Store installed, the package files in its install folder that describe it (`MicrosoftGame.config` and `appxmanifest.xml`) — to detect its engine, its engine version and its features and to check it for anti-cheat before any injection is possible; the lists of installed games that the Steam, GOG GALAXY, Epic Games and itch apps keep on your disk, and where GOG GALAXY is installed, the folders the Xbox app installs games into on each drive (named by the `.GamingRoot` file at the drive's root) with each game's package files, and Windows' answer to whether that game's package is installed for you — read when you import your library and when you press Play, to find the store that installed a game and hand the game to that store's app — Steam's and GOG GALAXY's also when you open a game's page, to find the artwork their apps keep for it; the cover and banner images that the Steam and GOG GALAXY apps keep on your disk for a game in your library and the logo and splash-screen images a game from the Xbox app ships in its own folder — read to show them on its page, never copied or sent anywhere; the size, position and state of a tracked game's window and the monitor it is on, read from Windows and not from the game, and — for a game FrameLedger injects into — whether the game asked for exclusive full-screen; the NVIDIA driver's settings for your tracked executables (read only: the DLSS and frame-generation overrides the NVIDIA App set); hardware sensor values from your graphics driver's own libraries; and — only while Advanced metrics is on — that driver's description of the graphLine truncated
It does **not** read game memory outside those API parameters, and does not read game saves, chat, input content, network traffic, or anything unrelated to performance measurement. It records only for programs you added to your library and did not switch recording off for — a program whose recording is off is not watched at all — and injects only into games you individually enabled.
It does **not** read game memory outside those API parameters, and does not read game saves, chat, what you type or which buttons you press — only that a controller, or the keyboard or mouse, was in use (§1) — network traffic, or anything unrelated to performance measurement. It records only for programs you added to your library and did not switch recording off for — a program whose recording is off is not watched at all — and injects only into games you individually enabled.
All of this stays on your device. None of it is transmitted anywhere.
+2 -1
View File
@@ -12,7 +12,8 @@ Microsoft Corporation. NVIDIA, GeForce, RTX, DLSS,
Reflex, NVAPI and Streamline are trademarks of NVIDIA Corporation. AMD, Radeon, FSR and FidelityFX are trademarks of
Advanced Micro Devices, Inc. Intel, Arc and XeSS are trademarks of Intel Corporation. Vulkan is a registered trademark
of the Khronos Group Inc.; OpenGL is a registered trademark of Hewlett Packard Enterprise, used under licence by the
Khronos Group. Steam and Valve are trademarks of Valve Corporation; Epic Games, the Epic Games Store and Unreal Engine of
Khronos Group. PlayStation, DualSense and DualShock are trademarks of Sony Interactive Entertainment Inc.; Nintendo Switch is a
trademark of Nintendo. Steam and Valve are trademarks of Valve Corporation; Epic Games, the Epic Games Store and Unreal Engine of
Epic Games, Inc.; Unity of Unity Technologies. GOG, GOG Galaxy and itch.io are trademarks of their respective owners. The
names of anti-cheat and anti-tamper products, and the names and store identifiers of games, belong to their respective
owners. All other product names are trademarks of their respective owners.
@@ -5,6 +5,7 @@ using FrameLedger.Application.Advanced;
using FrameLedger.Application.AntiCheat;
using FrameLedger.Application.Capture;
using FrameLedger.Application.Consent;
using FrameLedger.Application.Input;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Recording;
using FrameLedger.Infrastructure.Display;
@@ -45,6 +46,7 @@ internal sealed class AgentRecording
private readonly UserModeExceptionLapsePolicy _exceptionLapse;
private readonly ICrashReporterSightings _reporters;
private readonly IAdvancedHardware _advanced;
private readonly IInputDevices _input;
public AgentRecording(
IGameConsentStore store,
@@ -70,9 +72,11 @@ internal sealed class AgentRecording
IOverlayToleranceChannel tolerance,
UserModeExceptionLapsePolicy exceptionLapse,
ICrashReporterSightings reporters,
IAdvancedHardware advanced)
IAdvancedHardware advanced,
IInputDevices input)
{
_advanced = advanced;
_input = input;
_reporters = reporters;
_profiles = profiles;
_exceptions = exceptions;
@@ -123,7 +127,7 @@ internal sealed class AgentRecording
_partials,
_finalizer,
_crashes,
options => Poller(options.TelemetryInterval, options.AdvancedMetrics ? _advanced : null),
options => Poller(options.TelemetryInterval, options.AdvancedMetrics ? _advanced : null, options.InputDevices ? _input : null),
TimeProvider.System,
new RecorderOptions { MinimumSessionLength = minimum, PartialFlushInterval = flush },
_observer,
@@ -137,7 +141,8 @@ internal sealed class AgentRecording
/// <summary>L1 + L2 + L3 under the composite, one poller per session; the poller owns and disposes the layers. The interval is the session's (<c>telemetry.interval_ms</c>, D16).</summary>
/// <param name="interval">Between two polls.</param>
/// <param name="advanced">The Agent's shared advanced reader when the session records Advanced metrics (D101); null — the option off — composes none.</param>
public static TelemetryPoller Poller(TimeSpan interval, IAdvancedHardware? advanced = null)
/// <param name="input">The Agent's one input reader when the session reads controllers and input (D155, D156); null - the option off, or its terms not accepted - opens none.</param>
public static TelemetryPoller Poller(TimeSpan interval, IAdvancedHardware? advanced = null, IInputDevices? input = null)
{
// Ownership walks up one step at a time and each local is nulled at its hand-off, so a throw
// anywhere below disposes exactly what nobody owns yet.
@@ -168,7 +173,7 @@ internal sealed class AgentRecording
// The game process's own memory (beta.12, D43): read from outside it through FrameLedger.ProcessStats.dll, for
// whichever process the capture loop tells the poller to follow. Absent DLL = N/A, never a fault.
game = new GameMemoryReader(new NativeProcessStats());
var poller = new TelemetryPoller(composite, new TelemetryPollerOptions { Interval = interval }, TimeProvider.System, ownsSource: true, system, game, advanced);
var poller = new TelemetryPoller(composite, new TelemetryPollerOptions { Interval = interval }, TimeProvider.System, ownsSource: true, system, game, advanced, input);
composite = null;
system = null;
game = null;
@@ -7,6 +7,7 @@ using FrameLedger.Application.AntiCheat;
using FrameLedger.Application.Capture;
using FrameLedger.Application.Consent;
using FrameLedger.Application.Detection;
using FrameLedger.Application.Input;
using FrameLedger.Application.Ipc;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Recording;
@@ -19,6 +20,7 @@ using FrameLedger.Infrastructure.Blobs;
using FrameLedger.Infrastructure.Capture;
using FrameLedger.Infrastructure.Detection;
using FrameLedger.Infrastructure.Import;
using FrameLedger.Infrastructure.Input;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Infrastructure.Recording;
@@ -72,6 +74,8 @@ internal static class AgentServices
services.AddSingleton<ISettingsStore, SqliteSettingsStore>();
// The registry over the store (P3 PR-3, D16): the recorder resolves its three keys at each session start.
services.AddSingleton<RegisteredSettings>();
// Read by the recorder's policy only: the input reading waits for the Privacy Policy that describes it (D156).
services.AddSingleton<ILegalAcceptanceStore, SqliteLegalAcceptanceStore>();
services.AddSingleton<IRecorderPolicy, SettingsRecorderPolicy>();
services.AddSingleton<SettingsKillSwitch>();
services.AddSingleton<IKillSwitch>(static sp => sp.GetRequiredService<SettingsKillSwitch>());
@@ -130,6 +134,18 @@ internal static class AgentServices
interval: TimeSpan.FromSeconds(1),
linger: TimeSpan.FromSeconds(10),
static line => Serilog.Log.Information("{Line}", line)));
// Controllers and input (owner decisions D155-D159): ONE reader for the whole Agent, on a thread of its own, that
// exists only while a session has a view of it - a session recorded with the option on, after the terms that
// describe the reading were accepted (D156). Constructing it opens nothing: with no session there is no thread,
// no window and no registration. It is paused with the recording. The container disposes it with the host.
services.AddSingleton<IInputDevices>(static sp =>
{
CapturePause pause = sp.GetRequiredService<CapturePause>();
return new InputDeviceHub(
static () => new Win32InputBackend(),
paused: () => pause.IsPaused,
note: static line => Serilog.Log.Information("{Line}", line));
});
services.AddSingleton<AgentRecording>();
}
@@ -227,6 +227,19 @@
IsChecked="{Binding ViewModel.AdvancedMetrics, Mode=TwoWay}"
IsEnabled="{Binding ViewModel.ActsOnThisPc}" />
</ui:CardControl>
<!-- Controllers and input (owner decisions D155 and D156, 2026-11-14): on unless switched off, and read only
once the Privacy Policy that describes it has been accepted. The Agent reads it at each session's start. -->
<ui:CardControl Margin="0,8,0,0" Icon="{ui:SymbolIcon XboxController24}">
<ui:CardControl.Header>
<StackPanel>
<ui:TextBlock FontTypography="BodyStrong" Text="{x:Static res:Strings.Settings_Input_Label}" />
<ui:TextBlock MaxWidth="560" HorizontalAlignment="Left" Style="{StaticResource SecondaryText}" Text="{x:Static res:Strings.Settings_Input_Body}" TextWrapping="Wrap" />
</StackPanel>
</ui:CardControl.Header>
<ui:ToggleSwitch AutomationProperties.Name="{x:Static res:Strings.Settings_Input_Label}"
IsChecked="{Binding ViewModel.InputDevices, Mode=TwoWay}"
IsEnabled="{Binding ViewModel.ActsOnThisPc}" />
</ui:CardControl>
<!-- beta.12: "Record games launched outside FrameLedger" stood here; nothing read it (capture.background,
06_DATA_MODEL §Settings registry), and with no way to start a game from the App "off" could only have
meant recording nothing. Removed until a launch path exists. -->
@@ -102,7 +102,7 @@ public sealed class SessionExporter
w.WriteLine("# exe: " + game.Fingerprint.ExePath);
w.WriteLine("# started_at: " + row.StartedAt.ToString("O", _inv));
w.WriteLine("# ended_at: " + row.EndedAt.ToString("O", _inv));
w.WriteLine("# capture_tier: " + ((int)row.Tier).ToString(_inv) + (row.Tier == CaptureTier.Hooked ? " (hooked, measured)" : " (not hooked: duration and sensors only; no per-frame rows)"));
w.WriteLine("# capture_tier: " + ((int)row.Tier).ToString(_inv) + (row.Tier == CaptureTier.Hooked ? " (hooked, measured)" : " (not hooked: duration, sensors and what is read from outside the game; no per-frame rows)"));
if (row.AcExceptionFamily is { Length: > 0 } excepted)
{
// D33: a session hooked under the game's user-mode anti-cheat exception says so wherever it goes (the JSON carries
+6
View File
@@ -1294,6 +1294,8 @@ public static class Strings
nameof(Settings_HideScrollBars_Label),
nameof(Settings_HookedGames_Label),
nameof(Settings_HookedGames_Revoke),
nameof(Settings_Input_Body),
nameof(Settings_Input_Label),
nameof(Settings_Interval_Body),
nameof(Settings_Interval_Label),
nameof(Settings_Invalid_Format),
@@ -4092,6 +4094,10 @@ public static class Strings
public static string Settings_HookedGames_Revoke => ResourceManager.GetString(nameof(Settings_HookedGames_Revoke), Culture) ?? nameof(Settings_HookedGames_Revoke);
public static string Settings_Input_Body => ResourceManager.GetString(nameof(Settings_Input_Body), Culture) ?? nameof(Settings_Input_Body);
public static string Settings_Input_Label => ResourceManager.GetString(nameof(Settings_Input_Label), Culture) ?? nameof(Settings_Input_Label);
public static string Settings_Interval_Body => ResourceManager.GetString(nameof(Settings_Interval_Body), Culture) ?? nameof(Settings_Interval_Body);
public static string Settings_Interval_Label => ResourceManager.GetString(nameof(Settings_Interval_Label), Culture) ?? nameof(Settings_Interval_Label);
+9 -1
View File
@@ -1589,6 +1589,14 @@
<value>詳細メトリクス</value>
<comment>review</comment>
</data>
<data name="Settings_Input_Body" xml:space="preserve">
<value>セッションが何でプレイされたかを記録します - 接続されていたゲーム コントローラーと使用中だったコントローラー、そのバッテリー残量、キーボードまたはマウスが使われていたかどうか - を時間として、ゲームからではなく Windows から読み取ります。ボタン、スティック、キー、文字は保存されず、コントローラーには何も送信されず、これを説明するプライバシー ポリシーに同意するまでは何も読み取りません。オフ: これらは読み取りも保存もされません。次のセッションから適用され、オフの間に記録されたセッションが後から補われることはありません。</value>
<comment>review</comment>
</data>
<data name="Settings_Input_Label" xml:space="preserve">
<value>コントローラーと入力</value>
<comment>review</comment>
</data>
<data name="Settings_Appearance_Header" xml:space="preserve">
<value>外観</value>
<comment>review</comment>
@@ -2474,7 +2482,7 @@
<comment>review</comment>
</data>
<data name="Tier_NotHooked_Tooltip" xml:space="preserve">
<value>ティア 2: フックなし — 時間、センサー、ゲームのメモリのみ。フレームから算出する値はすべて N/A</value>
<value>ティア 2: フックなし — 時間、センサー、ゲームのメモリ、何でプレイされたかのみ。フレームから算出する値はすべて N/A</value>
<comment>review</comment>
</data>
<data name="Upscaler_None" xml:space="preserve">
+7 -1
View File
@@ -1197,6 +1197,12 @@
<data name="Settings_Advanced_Label" xml:space="preserve">
<value>Advanced metrics</value>
</data>
<data name="Settings_Input_Body" xml:space="preserve">
<value>Record what a session was played with: which game controllers were connected and in use, their battery level, and whether the keyboard or mouse was in use - as times, read from Windows and never from the game. No button, stick, key or text is kept, nothing is sent to a controller, and nothing is read until you have accepted the Privacy Policy that describes it. Off: nothing of this is read or stored. It applies from the next session, and a session recorded while it was off is not filled in later.</value>
</data>
<data name="Settings_Input_Label" xml:space="preserve">
<value>Controllers and input</value>
</data>
<data name="Settings_Appearance_Header" xml:space="preserve">
<value>Appearance</value>
</data>
@@ -1861,7 +1867,7 @@
<value>T2</value>
</data>
<data name="Tier_NotHooked_Tooltip" xml:space="preserve">
<value>Tier 2: not hooked — duration, sensors and the game's memory only; every frame-derived value is N/A</value>
<value>Tier 2: not hooked — duration, sensors, the game's memory and what it was played with only; every frame-derived value is N/A</value>
</data>
<data name="Upscaler_None" xml:space="preserve">
<value>No upscaler</value>
+7 -1
View File
@@ -1192,6 +1192,12 @@
<data name="Settings_Advanced_Label" xml:space="preserve">
<value>Thông số nâng cao</value>
</data>
<data name="Settings_Input_Body" xml:space="preserve">
<value>Ghi lại phiên được chơi bằng gì: tay cầm nào đang kết nối và đang được dùng, mức pin của chúng, và bàn phím hay chuột có được dùng hay không - dưới dạng thời gian, đọc từ Windows chứ không bao giờ từ game. Không lưu nút, cần, phím hay văn bản nào, không gửi gì tới tay cầm, và không đọc gì cho tới khi bạn chấp nhận Chính sách quyền riêng tư mô tả việc này. Tắt: không đọc hay lưu gì trong số này. Áp dụng từ phiên kế tiếp; phiên ghi lúc đang tắt sẽ không được bổ sung về sau.</value>
</data>
<data name="Settings_Input_Label" xml:space="preserve">
<value>Tay cầm và thao tác nhập</value>
</data>
<data name="Settings_Appearance_Header" xml:space="preserve">
<value>Giao diện</value>
</data>
@@ -1856,7 +1862,7 @@
<value>T2</value>
</data>
<data name="Tier_NotHooked_Tooltip" xml:space="preserve">
<value>Mức 2: không hook — chỉ có thời lượng, cảm biến và bộ nhớ của game; mọi giá trị suy ra từ khung hình đều là N/A</value>
<value>Mức 2: không hook — chỉ có thời lượng, cảm biến, bộ nhớ của game và việc phiên được chơi bằng gì; mọi giá trị suy ra từ khung hình đều là N/A</value>
</data>
<data name="Upscaler_None" xml:space="preserve">
<value>Không upscaler</value>
@@ -87,6 +87,14 @@ public sealed partial class SettingsViewModel : ObservableObject
[ObservableProperty]
private bool _advancedMetrics;
/// <summary>
/// "Controllers and input" (owner decisions D155 and D156, <c>capture.input_devices</c>, on by default): the Agent
/// reads which controllers are connected and in use and the time of the last keyboard or mouse input, from outside
/// the game, and a session stores what it was played with; off, nothing of it is read or stored.
/// </summary>
[ObservableProperty]
private bool _inputDevices;
[ObservableProperty]
private int _minSessionSeconds;
@@ -443,6 +451,8 @@ public sealed partial class SettingsViewModel : ObservableObject
Persist(SettingsRegistry.TelemetryAdvanced, value);
}
partial void OnInputDevicesChanged(bool value) => Persist(SettingsRegistry.CaptureInputDevices, value);
partial void OnHideAntiCheatHookingChanged(bool value) => Persist(SettingsRegistry.UiHideAntiCheatHooking, value);
/// <summary>D33: the option is one settings row the Agent reads at every session start and command; the list follows it.</summary>
@@ -599,6 +609,7 @@ public sealed partial class SettingsViewModel : ObservableObject
RetentionRawSessions = await _settings.GetIntegerAsync(SettingsRegistry.RetentionRawSessionsPerGame).ConfigureAwait(true);
RemoveUninstalledGames = await _settings.GetBooleanAsync(SettingsRegistry.RetentionRemoveUninstalledGames).ConfigureAwait(true);
AdvancedMetrics = await _settings.GetBooleanAsync(SettingsRegistry.TelemetryAdvanced).ConfigureAwait(true);
InputDevices = await _settings.GetBooleanAsync(SettingsRegistry.CaptureInputDevices).ConfigureAwait(true);
MinimizeToTray = await _settings.GetBooleanAsync(SettingsRegistry.UiMinimizeToTray).ConfigureAwait(true);
HideAntiCheatHooking = await _settings.GetBooleanAsync(SettingsRegistry.UiHideAntiCheatHooking).ConfigureAwait(true);
UserModeExceptions = await _settings.GetBooleanAsync(SettingsRegistry.HookingUserModeExceptions).ConfigureAwait(true);
@@ -0,0 +1,20 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Diagnostics.CodeAnalysis;
using FrameLedger.Application.Telemetry;
namespace FrameLedger.Application.Input;
/// <summary>
/// One session's view of <see cref="IInputDevices"/>: the slices in which a window of the session's own game was in
/// front, added up between two reads. Several sessions can run at once; each has its own.
/// </summary>
public interface IInputActivitySource : IDisposable
{
/// <summary>The processes whose windows count as the session's game. Called from the session's loop.</summary>
void Follow(GameProcess target);
/// <summary>What was seen since the last read; false when the reader took no slice since then. Called from the telemetry thread, and never throws into it.</summary>
bool TryRead([NotNullWhen(true)] out InputReading? reading);
}
@@ -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,15 @@
// 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 Agent's one reader of game controllers and of keyboard-and-mouse activity (owner decisions of 2026-11-14,
/// <c>21_INPUT_DEVICES</c>). It reads from outside every game - nothing is hooked, nothing in a game is opened - and
/// only while a session holds a view of it: with no session it does not run at all.
/// </summary>
public interface IInputDevices
{
/// <summary>One session's view of the reader. The reader runs from the first view opened to the last disposed.</summary>
IInputActivitySource Open();
}
@@ -0,0 +1,39 @@
// 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>
/// One game controller the Agent saw, as far as a session keeps it (<c>21_INPUT_DEVICES</c> §Who a controller is): its
/// maker and model by their USB ids, how it is connected, and whether it is one of XInput's four pads.
/// </summary>
/// <remarks>
/// <b>What is not here is not read:</b> no serial number, no Bluetooth address, no device path. Two pads of one model
/// on one kind of connection cannot be told apart across a reconnect, and are not.
/// </remarks>
public sealed record InputDevice
{
/// <summary>The reader's own number for the device, the same for as long as the reader runs. It names nothing outside the Agent.</summary>
public required int Id { get; init; }
public ControllerFamily Family { get; init; }
/// <summary>The USB vendor id; 0 for one of XInput's pads that nothing could name.</summary>
public int VendorId { get; init; }
/// <summary>The USB product id; 0 with a <see cref="VendorId"/> of 0.</summary>
public int ProductId { get; init; }
public ControllerConnection Connection { get; init; }
/// <summary>Whether the ids are those of a pad a program presents - Steam's virtual gamepad - rather than one a player holds.</summary>
public bool IsVirtual { get; init; }
/// <summary>Which of XInput's four pads this is (0-3); null for a controller Windows does not present through XInput.</summary>
public int? XInputSlot { get; init; }
/// <summary>The model's product name, or null for ids this build does not list.</summary>
public string? Model => ControllerCatalog.ModelOf(VendorId, ProductId);
}
@@ -0,0 +1,17 @@
// 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>One controller during one tick.</summary>
/// <param name="DeviceId">The <see cref="InputDevice.Id"/> it is about.</param>
/// <param name="Connected">Whether it was connected at the end of the tick.</param>
/// <param name="ActiveMs">The time it was in use while the game was in front and the session was not paused.</param>
/// <param name="Battery">Its battery at the tick's last reading, when it reported one.</param>
/// <param name="Connects">How many times it connected during the tick. Being there when the session began is not a connection.</param>
/// <param name="Disconnects">How many times it disconnected during the tick.</param>
[StructLayout(LayoutKind.Auto)]
public readonly record struct InputDeviceReading(int DeviceId, bool Connected, int ActiveMs, BatteryReading? Battery, int Connects, int Disconnects);
@@ -0,0 +1,85 @@
// 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 each source of the input reader did, as counts (<c>21_INPUT_DEVICES</c> §What the reader says about itself).
/// The reader was built without a controller to try it on (owner decision, 2026-11-14), so a session carries the
/// evidence of what answered on the PC it ran on: whether Windows accepted the registration, how many reports came,
/// whether XInput said anything while the Agent was in the background. Counts only - nothing here names a device.
/// </summary>
public sealed record InputHealth
{
/// <summary>Whether Windows accepted the registration for game controllers' reports.</summary>
public bool RawInputRegistered { get; init; }
/// <summary>Reports of game controllers received.</summary>
public long RawReports { get; init; }
/// <summary>Reports that could not be read: a layout the parser does not know, or one Windows' own parser refused.</summary>
public long RawReportsUnread { get; init; }
/// <summary>Whether XInput's library was there to ask.</summary>
public bool XInputAvailable { get; init; }
/// <summary>States XInput returned for a connected pad.</summary>
public long XInputReads { get; init; }
/// <summary>
/// Slices in which a controller Windows presents through XInput sent reports that are a pad in use while XInput's
/// own state said nothing was. More than a handful means XInput does not answer a program in the background on
/// this PC, and its pads were then read from their reports alone.
/// </summary>
public long XInputSilent { get; init; }
/// <summary>Whether Windows gave the time of the last keyboard or mouse input.</summary>
public bool LastInputAvailable { get; init; }
/// <summary>Slices the reader took.</summary>
public long Slices { get; init; }
/// <summary>Processor time the reader's thread used, in milliseconds.</summary>
public long ThreadCpuMs { get; init; }
/// <summary>Slices that failed with an error and were skipped.</summary>
public int Faults { get; init; }
/// <summary>What happened since <paramref name="start"/>: the counts less the ones it holds; the yes-or-no answers are the later ones.</summary>
public InputHealth Since(InputHealth start)
{
ArgumentNullException.ThrowIfNull(start);
return this with
{
RawReports = RawReports - start.RawReports,
RawReportsUnread = RawReportsUnread - start.RawReportsUnread,
XInputReads = XInputReads - start.XInputReads,
XInputSilent = XInputSilent - start.XInputSilent,
Slices = Slices - start.Slices,
ThreadCpuMs = ThreadCpuMs - start.ThreadCpuMs,
Faults = Faults - start.Faults,
};
}
/// <summary>The sources that answered, as <c>sessions.input_source</c> stores them: <c>rawinput</c>, <c>xinput</c> and <c>lastinput</c>, joined by <c>+</c>; empty when none did.</summary>
public string Sources()
{
var parts = new List<string>(3);
if (RawInputRegistered)
{
parts.Add("rawinput");
}
if (XInputAvailable)
{
parts.Add("xinput");
}
if (LastInputAvailable)
{
parts.Add("lastinput");
}
return string.Join('+', parts);
}
}
@@ -0,0 +1,84 @@
// 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 words a ledger stores for a controller's family, its connection and its battery (<c>06_DATA_MODEL</c>
/// §<c>sessions.input_devices</c>). They are data, not text shown to anyone: the App has its own, translated, and a
/// word here is never renamed once a release has written it.
/// </summary>
public static class InputNames
{
public const string Other = "other";
public const string Unknown = "unknown";
public const string None = "none";
public static string Of(ControllerFamily family) => family switch
{
ControllerFamily.Xbox => "xbox",
ControllerFamily.PlayStation => "playstation",
ControllerFamily.Nintendo => "nintendo",
_ => Other,
};
public static ControllerFamily FamilyOf(string? name) => name switch
{
"xbox" => ControllerFamily.Xbox,
"playstation" => ControllerFamily.PlayStation,
"nintendo" => ControllerFamily.Nintendo,
_ => ControllerFamily.Other,
};
public static string Of(ControllerConnection connection) => connection switch
{
ControllerConnection.Usb => "usb",
ControllerConnection.Bluetooth => "bluetooth",
ControllerConnection.Wireless => "wireless",
_ => Unknown,
};
public static ControllerConnection ConnectionOf(string? name) => name switch
{
"usb" => ControllerConnection.Usb,
"bluetooth" => ControllerConnection.Bluetooth,
"wireless" => ControllerConnection.Wireless,
_ => ControllerConnection.Unknown,
};
public static string Of(BatteryState state) => state switch
{
BatteryState.Discharging => "discharging",
BatteryState.Charging => "charging",
BatteryState.Full => "full",
BatteryState.Wired => "wired",
_ => Unknown,
};
public static BatteryState StateOf(string? name) => name switch
{
"discharging" => BatteryState.Discharging,
"charging" => BatteryState.Charging,
"full" => BatteryState.Full,
"wired" => BatteryState.Wired,
_ => BatteryState.Unknown,
};
public static string Of(BatteryScale scale) => scale switch
{
BatteryScale.FourLevels => "levels",
BatteryScale.Percent => "percent",
_ => None,
};
public static BatteryScale ScaleOf(string? name) => name switch
{
"levels" => BatteryScale.FourLevels,
"percent" => BatteryScale.Percent,
_ => BatteryScale.None,
};
}
@@ -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,45 @@
// 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 the input reader saw for one session during one tick of the telemetry poller (<c>03_METRICS</c> §Input): how
/// the time the game was in front divides between a controller, the keyboard and mouse, both and neither, and each
/// controller's part in it.
/// </summary>
/// <remarks>
/// It holds times and counts. Which button, where a stick was, which key, what was typed and where the mouse was are
/// not in it because the reader never keeps them (<c>21_INPUT_DEVICES</c> §What is never read).
/// </remarks>
public sealed record InputReading
{
/// <summary>The time the tick covers: every slice, in front or not, paused or not. What a battery level and a connection are timed by.</summary>
public int SpanMs { get; init; }
/// <summary>Of <see cref="SpanMs"/>, the time the session was not paused.</summary>
public int ObservedMs { get; init; }
/// <summary>Of <see cref="ObservedMs"/>, the time a window of the game was in front. The four below add up to it.</summary>
public int ForegroundMs { get; init; }
public int ControllerMs { get; init; }
public int KeyboardMouseMs { get; init; }
public int BothMs { get; init; }
public int IdleMs { get; init; }
/// <summary>Whether a pad a program presents - Steam's virtual gamepad - was among XInput's pads during the tick.</summary>
public bool VirtualPad { get; init; }
/// <summary>The controllers that were connected at some moment of the tick.</summary>
public IReadOnlyList<InputDeviceReading> Devices { get; init; } = [];
/// <summary>What each controller in <see cref="Devices"/> is. A reading stands alone: it names every device it counts.</summary>
public IReadOnlyList<InputDevice> Table { get; init; } = [];
/// <summary>What the reader's sources did since the session began reading.</summary>
public InputHealth Health { get; init; } = new();
}
@@ -0,0 +1,30 @@
// 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 the input reader saw of the whole PC in one slice - about a tenth of a second (<c>21_INPUT_DEVICES</c> §The
/// reader). It is the same for every session running: which session a slice counts for is decided by whose window was
/// in front (<see cref="InputTickAccumulator"/>).
/// </summary>
public sealed record InputSlice
{
/// <summary>The time since the slice before.</summary>
public int ElapsedMs { get; init; }
/// <summary>The process whose window was in front; 0 when Windows named none.</summary>
public uint ForegroundProcessId { get; init; }
/// <summary>Whether Windows' time of the last keyboard or mouse input moved during the slice.</summary>
public bool KeyboardMouseActive { get; init; }
/// <summary>Whether a pad a program presents was among XInput's pads.</summary>
public bool VirtualPad { get; init; }
/// <summary>The controllers connected during the slice.</summary>
public IReadOnlyList<InputSliceDevice> Devices { get; init; } = [];
/// <summary>What the reader's sources did since the reader started.</summary>
public InputHealth Health { get; init; } = new();
}
@@ -0,0 +1,14 @@
// 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>One connected controller during one slice.</summary>
/// <param name="Device">What it is.</param>
/// <param name="Active">Whether anything on it was in use during the slice.</param>
/// <param name="Battery">Its battery, when it reported one.</param>
[StructLayout(LayoutKind.Auto)]
public readonly record struct InputSliceDevice(InputDevice Device, bool Active, BatteryReading? Battery);
@@ -0,0 +1,45 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Globalization;
namespace FrameLedger.Application.Input;
/// <summary>
/// The terms that describe the input reading, and whether they have been accepted on this PC (owner decision D156,
/// 2026-11-14). The option is on unless switched off, and the Agent is often started at logon - before the App that
/// shows a new Privacy Policy has been opened. So the Agent reads controllers and keyboard-and-mouse activity only
/// when the Privacy Policy the user accepted is the one that first described that reading, or a later one.
/// </summary>
public static class InputTerms
{
/// <summary>The Privacy Policy's key in <c>legal_acceptance</c> - the App's <c>LegalDocuments.Privacy</c>, which a test holds to this.</summary>
public const string PrivacyDocument = "privacy";
/// <summary>The first version of the Privacy Policy that describes the reading.</summary>
public const string MinimumPrivacyVersion = "2.22";
/// <summary>
/// Whether an accepted version is <see cref="MinimumPrivacyVersion"/> or later. A version is two whole numbers with
/// a dot between them, compared as numbers - 2.9 is before 2.22. No version, and anything that is not one, is not
/// accepted: a document nobody can be shown to have accepted permits nothing.
/// </summary>
public static bool Accepted(string? acceptedVersion) =>
Parse(acceptedVersion) is { } accepted && Parse(MinimumPrivacyVersion) is { } minimum
&& (accepted.Major > minimum.Major || (accepted.Major == minimum.Major && accepted.Minor >= minimum.Minor));
private static (int Major, int Minor)? Parse(string? version)
{
if (version is null)
{
return null;
}
string[] parts = version.Trim().Split('.');
return parts.Length == 2
&& int.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out int major)
&& int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out int minor)
? (major, minor)
: null;
}
}
@@ -0,0 +1,205 @@
// 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>
/// One session's slices added up into one <see cref="InputReading"/> per tick (<c>03_METRICS</c> §Input). The reader
/// adds a slice about ten times a second on its own thread; the telemetry poller takes the sum once a second on its.
/// </summary>
/// <remarks>
/// <para>
/// <b>Only time the game was in front is classified.</b> A slice in which another program's window was in front counts
/// for nothing but <see cref="InputReading.SpanMs"/>: typing in a browser beside the game is not the game played with
/// the keyboard. A slice of a paused session is not observed either (a pause is a gap, <c>03_METRICS</c>).
/// </para>
/// <para>
/// <b>A controller that is there when the session starts has not connected.</b> Connections and disconnections are
/// counted from the second slice on, by comparing each slice's controllers with those of the slice before - paused or
/// not, in front or not: a pad that drops out while the player is in another window still dropped out.
/// </para>
/// </remarks>
public sealed class InputTickAccumulator
{
private readonly Lock _gate = new();
private readonly Dictionary<int, Entry> _devices = [];
private HashSet<int> _connected = [];
private bool _started;
private InputHealth? _healthAtStart;
private InputHealth _health = new();
private int _spanMs;
private int _observedMs;
private int _foregroundMs;
private int _controllerMs;
private int _keyboardMouseMs;
private int _bothMs;
private int _idleMs;
private bool _virtualPad;
private bool _any;
/// <summary>Adds one slice.</summary>
/// <param name="slice">What the reader saw.</param>
/// <param name="inFront">Whether the process in front is one of the session's.</param>
/// <param name="paused">Whether the session is paused.</param>
public void Add(InputSlice slice, bool inFront, bool paused)
{
ArgumentNullException.ThrowIfNull(slice);
int elapsed = Math.Max(0, slice.ElapsedMs);
lock (_gate)
{
_any = true;
_healthAtStart ??= slice.Health;
_health = slice.Health;
_spanMs += elapsed;
_virtualPad |= slice.VirtualPad;
bool counted = inFront && !paused;
bool controller = Track(slice.Devices, counted ? elapsed : 0);
if (paused)
{
return;
}
_observedMs += elapsed;
if (!inFront)
{
return;
}
_foregroundMs += elapsed;
switch (controller, slice.KeyboardMouseActive)
{
case (true, true):
_bothMs += elapsed;
break;
case (true, false):
_controllerMs += elapsed;
break;
case (false, true):
_keyboardMouseMs += elapsed;
break;
default:
_idleMs += elapsed;
break;
}
}
}
/// <summary>The sum since the last take, or null when no slice was added since then.</summary>
public InputReading? Take()
{
lock (_gate)
{
if (!_any)
{
return null;
}
var devices = new List<InputDeviceReading>(_devices.Count);
var table = new List<InputDevice>(_devices.Count);
foreach ((int id, Entry entry) in _devices.OrderBy(static p => p.Key))
{
devices.Add(new InputDeviceReading(id, _connected.Contains(id), entry.ActiveMs, entry.Battery, entry.Connects, entry.Disconnects));
table.Add(entry.Device);
}
var reading = new InputReading
{
SpanMs = _spanMs,
ObservedMs = _observedMs,
ForegroundMs = _foregroundMs,
ControllerMs = _controllerMs,
KeyboardMouseMs = _keyboardMouseMs,
BothMs = _bothMs,
IdleMs = _idleMs,
VirtualPad = _virtualPad,
Devices = devices,
Table = table,
Health = _health.Since(_healthAtStart ?? _health),
};
// The next tick starts with the controllers still connected and nothing counted for them yet.
foreach (int id in _devices.Keys.Where(id => !_connected.Contains(id)).ToArray())
{
_devices.Remove(id);
}
foreach (Entry entry in _devices.Values)
{
entry.Reset();
}
_spanMs = _observedMs = _foregroundMs = _controllerMs = _keyboardMouseMs = _bothMs = _idleMs = 0;
_virtualPad = false;
_any = false;
return reading;
}
}
/// <summary>Notes each controller of the slice and what changed since the slice before; returns whether any was in use.</summary>
private bool Track(IReadOnlyList<InputSliceDevice> devices, int countedMs)
{
var now = new HashSet<int>(devices.Count);
bool anyActive = false;
foreach (InputSliceDevice device in devices)
{
int id = device.Device.Id;
if (!now.Add(id))
{
continue;
}
if (!_devices.TryGetValue(id, out Entry? entry))
{
entry = new Entry(device.Device);
_devices[id] = entry;
}
entry.Device = device.Device;
entry.Battery = device.Battery ?? entry.Battery;
if (_started && !_connected.Contains(id))
{
entry.Connects++;
}
if (device.Active)
{
anyActive = true;
entry.ActiveMs += countedMs;
}
}
foreach (int gone in _connected)
{
if (!now.Contains(gone) && _devices.TryGetValue(gone, out Entry? entry))
{
entry.Disconnects++;
}
}
_connected = now;
_started = true;
return anyActive;
}
private sealed class Entry(InputDevice device)
{
public InputDevice Device { get; set; } = device;
public int ActiveMs { get; set; }
public BatteryReading? Battery { get; set; }
public int Connects { get; set; }
public int Disconnects { get; set; }
public void Reset()
{
ActiveMs = 0;
Connects = 0;
Disconnects = 0;
}
}
}
@@ -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;
}
@@ -52,12 +52,23 @@ public readonly record struct CaptureNotes(string? End, string? GuardReason, str
/// <summary>beta.14: a crash reporter the game started that did not count — the game kept running (<c>crash_reporter_seen=</c>).</summary>
public string? CrashReporterSeen { get; init; }
public static CaptureNotes Parse(string? notes)
/// <summary>
/// 0.1.0-beta.50 (owner decision D156): the session read nothing of controllers or of the keyboard and mouse
/// because the Privacy Policy that describes the reading was not accepted on the PC yet (<see cref="InputHeldSlot"/>).
/// False on every other session - one that read, one recorded with the option off, one from before the reading existed.
/// </summary>
public bool InputHeldForTerms { get; init; }
/// <summary>The slot of a session whose input reading waited for the terms (D156).</summary>
public const string InputHeldSlot = "input=terms_pending";
public static CaptureNotes Parse(string? notes) => string.IsNullOrWhiteSpace(notes)
? default
: Slots(notes) with { InputHeldForTerms = notes.Split(';').Any(static part => string.Equals(part.Trim(), InputHeldSlot, StringComparison.Ordinal)) };
/// <summary>The slots that carry a value, each by its prefix.</summary>
private static CaptureNotes Slots(string notes)
{
if (string.IsNullOrWhiteSpace(notes))
{
return default;
}
string? end = null, reason = null, family = null, signal = null, acException = null, scanAtExit = null, reporter = null, reporterSeen = null;
int? exitCode = null, launchError = null;
@@ -0,0 +1,25 @@
// 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.Application.Recording;
/// <summary>A controller's battery over the session, in <see cref="InputDeviceRecord"/>.</summary>
public sealed record InputBatteryRecord
{
/// <summary><c>levels</c> (0 empty to 3 full), <c>percent</c>, or <c>none</c> for a wired pad.</summary>
public string Scale { get; init; } = InputNames.None;
/// <summary>Every state it was read in, the longest first.</summary>
public IReadOnlyList<InputBatteryStateRecord> States { get; init; } = [];
/// <summary>The first level read, in <see cref="Scale"/>; null when no reading had a level.</summary>
public int? First { get; init; }
/// <summary>The last level read.</summary>
public int? Last { get; init; }
/// <summary>How fast it ran down, in per cent an hour, when that could be worked out (<c>03_METRICS</c> §Input).</summary>
public double? DrainPercentPerHour { get; init; }
}
@@ -0,0 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Application.Recording;
/// <summary>One battery state and the time it was read, in <see cref="InputBatteryRecord"/>.</summary>
/// <param name="State">What the battery was doing, in <c>InputNames</c>' words.</param>
/// <param name="Level">The level, in the battery's scale.</param>
/// <param name="Ms">The time it was read in this state.</param>
public sealed record InputBatteryStateRecord(string State, int Level, long Ms);
@@ -0,0 +1,42 @@
// 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.Application.Recording;
/// <summary>One controller of a session, in <see cref="InputDevicesRecord"/>.</summary>
public sealed record InputDeviceRecord
{
/// <summary>The controller's number in the session, from 1: what its series are named by (<c>input.dev.N.active</c>).</summary>
public int Index { get; init; }
public string Family { get; init; } = InputNames.Other;
public int VendorId { get; init; }
public int ProductId { get; init; }
public string? Model { get; init; }
public string Connection { get; init; } = InputNames.Unknown;
public int? XInputSlot { get; init; }
/// <summary>The pad is one a program presents and no controller a player holds was found behind it.</summary>
public bool Virtual { get; init; }
/// <summary>A second pad moved exactly as this one did and was folded into it: Steam Input, or another remapper, was presenting this controller to games as an Xbox pad.</summary>
public bool Remapped { get; init; }
public long ConnectedMs { get; init; }
/// <summary>The time it was in use while the game was in front.</summary>
public long ActiveMs { get; init; }
public int Connects { get; init; }
public int Disconnects { get; init; }
public InputBatteryRecord? Battery { get; init; }
}
@@ -0,0 +1,56 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Text.Json;
using FrameLedger.Application.Input;
namespace FrameLedger.Application.Recording;
/// <summary>
/// <c>sessions.input_devices</c> (schema 0024, owner decisions of 2026-11-14): the controllers of a session as JSON -
/// what each was, how long it was connected and in use, how often it connected and dropped, its battery - with each
/// maker's share, how often the maker changed, and what the reader's sources did.
/// </summary>
/// <remarks>
/// The words for a family, a connection and a battery state are <see cref="InputNames"/>'s, lower case, and are never
/// renamed: a ledger keeps them. A model is a product name or absent. No serial number, address or path is here, and
/// <c>InputSessionBuilderTests</c> hold that no key of the JSON could carry one.
/// </remarks>
public sealed record InputDevicesRecord
{
/// <summary>The format's version; 1.</summary>
public int V { get; init; } = 1;
public IReadOnlyList<InputDeviceRecord> Devices { get; init; } = [];
/// <summary>Each maker's part of the time controllers were in use, the largest first.</summary>
public IReadOnlyList<InputFamilyRecord> Families { get; init; } = [];
/// <summary>How many times the maker of the controller in use changed.</summary>
public int FamilySwitches { get; init; }
/// <summary>Whether a pad a program presents - Steam's virtual gamepad - was seen.</summary>
public bool VirtualPad { get; init; }
public InputHealth Health { get; init; } = new();
public static string ToJson(InputDevicesRecord record) => JsonSerializer.Serialize(record, RecordingJsonContext.Default.InputDevicesRecord);
/// <summary>The column's text back, or null for a null, empty or unparsable column.</summary>
public static InputDevicesRecord? Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return null;
}
try
{
return JsonSerializer.Deserialize(json, RecordingJsonContext.Default.InputDevicesRecord);
}
catch (JsonException)
{
return null;
}
}
}
@@ -0,0 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Application.Recording;
/// <summary>One maker's part of the time controllers were in use, in <see cref="InputDevicesRecord"/>.</summary>
/// <param name="Family">The maker, in <c>InputNames</c>' words.</param>
/// <param name="ActiveMs">The time its controllers were in use while the game was in front.</param>
/// <param name="Share">That time over the same time of every maker, 0 to 1.</param>
public sealed record InputFamilyRecord(string Family, long ActiveMs, double Share);
@@ -0,0 +1,316 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Globalization;
using FrameLedger.Application.Input;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Telemetry;
using FrameLedger.Domain.Input;
namespace FrameLedger.Application.Recording;
/// <summary>
/// What a session stores of its input readings (<c>03_METRICS</c> §Input, owner decisions of 2026-11-14): the totals,
/// the controllers with their batteries and makers, and the series a timeline is drawn from - all from the samples, so
/// a session recovered from its <c>.partial</c> file has them as a finished one does.
/// </summary>
/// <remarks>
/// <para>
/// <b>Nothing in, nothing out.</b> A session none of whose samples carries a reading - the option was off, or the
/// terms that say what is read were not accepted yet - stores no series and no summary, and is byte for byte what it
/// was before this existed.
/// </para>
/// <para>
/// <b>One pad seen twice is one controller.</b> Windows shows a controller that Steam Input stands in front of twice:
/// the one the player holds, and an Xbox pad Steam presents for it. An XInput pad that was in use at the same moments
/// as another controller is folded into it (<see cref="VirtualPad"/>) - into a controller that is not XInput's at any
/// time, into another of XInput's pads only in a session where Steam's virtual gamepad was seen.
/// </para>
/// </remarks>
public static class InputSessionBuilder
{
/// <summary>The most controllers one session stores series for; more are counted in the totals and not listed.</summary>
public const int MaxDevices = 8;
public const string ClassSeries = "input.class";
/// <summary>What every series of this builder starts with: how a reader tells them from the sensors' and the advanced ones.</summary>
public const string SeriesPrefix = "input.";
public static string ActiveSeries(int index) => string.Create(CultureInfo.InvariantCulture, $"input.dev.{index}.active");
public static string BatterySeries(int index) => string.Create(CultureInfo.InvariantCulture, $"input.dev.{index}.battery");
/// <summary>The session's input series as blobs and its summary - nothing when no sample carries a reading.</summary>
/// <param name="sensors">The session's samples, in order.</param>
/// <param name="codec">How a series is encoded.</param>
/// <param name="hz">The rate the samples had, stored with each series as the fallback for a reader with no <c>t_ms</c>.</param>
public static (IReadOnlyList<SensorBlob> Blobs, InputSessionSummary? Summary) Build(IReadOnlyList<TelemetrySample> sensors, ISeriesCodec codec, double hz = 1)
{
ArgumentNullException.ThrowIfNull(sensors);
ArgumentNullException.ThrowIfNull(codec);
if (!sensors.Any(static s => s.Input is not null))
{
return ([], null);
}
List<Track> tracks = Tracks(sensors);
bool virtualPad = sensors.Any(static s => s.Input?.VirtualPad == true);
Fold(tracks, virtualPad);
Track[] kept = [.. tracks.Where(static t => !t.Folded)];
var blobs = new List<SensorBlob> { Blob(ClassSeries, ClassColumn(sensors), codec, hz) };
var devices = new List<InputDeviceRecord>(kept.Length);
for (int d = 0; d < kept.Length; d++)
{
devices.Add(kept[d].ToRecord(d + 1));
if (d < MaxDevices)
{
blobs.Add(Blob(ActiveSeries(d + 1), kept[d].ActiveColumn(sensors), codec, hz));
if (kept[d].Battery.Any(static b => b is { Scale: not BatteryScale.None }))
{
blobs.Add(Blob(BatterySeries(d + 1), kept[d].BatteryColumn(), codec, hz));
}
}
}
InputHealth health = sensors.Last(static s => s.Input is not null).Input!.Health;
var record = new InputDevicesRecord
{
Devices = devices,
Families = Families(kept),
FamilySwitches = InputSwitches.Count(FamilyTicks(kept, sensors.Count)),
VirtualPad = virtualPad,
Health = health,
};
return (blobs, new InputSessionSummary
{
ObservedMs = sensors.Sum(static s => (long)(s.Input?.ObservedMs ?? 0)),
ForegroundMs = sensors.Sum(static s => (long)(s.Input?.ForegroundMs ?? 0)),
ControllerMs = sensors.Sum(static s => (long)(s.Input?.ControllerMs ?? 0)),
KeyboardMouseMs = sensors.Sum(static s => (long)(s.Input?.KeyboardMouseMs ?? 0)),
BothMs = sensors.Sum(static s => (long)(s.Input?.BothMs ?? 0)),
IdleMs = sensors.Sum(static s => (long)(s.Input?.IdleMs ?? 0)),
MethodSwitches = InputSwitches.Count(sensors.Select(static s => s.Input is { } r
? InputSwitches.Exclusive(r.ControllerMs, r.KeyboardMouseMs, r.BothMs)
: null)),
Source = health.Sources(),
DevicesJson = InputDevicesRecord.ToJson(record),
});
}
private static SensorBlob Blob(string series, float[] column, ISeriesCodec codec, double hz) =>
new() { Series = series, Hz = hz, Codec = codec.Tag, Data = codec.EncodeSparseFloat32(column) };
/// <summary>What each tick was mostly played with, as <see cref="InputClass"/>'s number; NaN for a tick with no reading or with the game not in front.</summary>
private static float[] ClassColumn(IReadOnlyList<TelemetrySample> sensors)
{
float[] column = new float[sensors.Count];
for (int i = 0; i < sensors.Count; i++)
{
column[i] = sensors[i].Input is { } r && InputSwitches.Dominant(r.ControllerMs, r.KeyboardMouseMs, r.BothMs, r.IdleMs) is { } dominant
? (int)dominant
: float.NaN;
}
return column;
}
/// <summary>One track per controller the samples name, in the order they first appear.</summary>
private static List<Track> Tracks(IReadOnlyList<TelemetrySample> sensors)
{
var tracks = new List<Track>();
var byId = new Dictionary<int, Track>();
for (int i = 0; i < sensors.Count; i++)
{
if (sensors[i].Input is not { } reading)
{
continue;
}
foreach (InputDevice device in reading.Table)
{
if (!byId.TryGetValue(device.Id, out Track? track))
{
track = new Track(device, sensors.Count);
byId[device.Id] = track;
tracks.Add(track);
}
track.Device = device;
}
foreach (InputDeviceReading d in reading.Devices)
{
if (byId.TryGetValue(d.DeviceId, out Track? track))
{
track.Add(i, d, reading.SpanMs);
}
}
}
return tracks;
}
/// <summary>Folds each of XInput's pads that moved with another controller into that controller.</summary>
private static void Fold(List<Track> tracks, bool virtualPad)
{
foreach (Track pad in tracks.Where(static t => t.Device.XInputSlot is not null))
{
// A controller that is not XInput's first: it is the one the player holds. Then, only with Steam's pad seen,
// an XInput pad of a lower number - which of the two Steam presents cannot be told, and it does not matter.
Track? into = tracks.FirstOrDefault(t => !t.Folded && t.Device.XInputSlot is null && VirtualPad.IsSamePad(pad.ActiveMs, t.ActiveMs));
if (into is null && virtualPad)
{
into = tracks.FirstOrDefault(t => !t.Folded && !ReferenceEquals(t, pad) && t.Device.XInputSlot < pad.Device.XInputSlot
&& VirtualPad.IsSamePad(pad.ActiveMs, t.ActiveMs));
}
if (into is not null)
{
pad.Folded = true;
into.Remapped = true;
}
}
}
private static List<InputFamilyRecord> Families(Track[] kept)
{
long total = kept.Sum(static t => t.TotalActiveMs);
return [.. kept
.GroupBy(static t => t.Device.Family)
.Select(g => (Family: g.Key, Ms: g.Sum(static t => t.TotalActiveMs)))
.Where(static f => f.Ms > 0)
.OrderByDescending(static f => f.Ms)
.ThenBy(static f => f.Family)
.Select(f => new InputFamilyRecord(InputNames.Of(f.Family), f.Ms, Math.Round((double)f.Ms / total, 4)))];
}
/// <summary>The one maker whose controller was in use on each tick, or null where none or more than one was.</summary>
private static IEnumerable<ControllerFamily?> FamilyTicks(Track[] kept, int ticks)
{
for (int i = 0; i < ticks; i++)
{
ControllerFamily? only = null;
bool several = false;
foreach (Track track in kept)
{
if (track.ActiveMs[i] <= 0)
{
continue;
}
several |= only is { } seen && seen != track.Device.Family;
only = track.Device.Family;
}
yield return several ? null : only;
}
}
/// <summary>One controller across the session's ticks.</summary>
private sealed class Track(InputDevice device, int ticks)
{
private readonly bool[] _connected = new bool[ticks];
private readonly BatteryTally _tally = new();
private long _connectedMs;
private int _connects;
private int _disconnects;
public InputDevice Device { get; set; } = device;
public int[] ActiveMs { get; } = new int[ticks];
public BatteryReading?[] Battery { get; } = new BatteryReading?[ticks];
public long TotalActiveMs => ActiveMs.Sum(static ms => (long)ms);
/// <summary>Another controller's, and not listed.</summary>
public bool Folded { get; set; }
/// <summary>A pad that moved with it was folded into it.</summary>
public bool Remapped { get; set; }
public void Add(int tick, InputDeviceReading reading, int spanMs)
{
ActiveMs[tick] = reading.ActiveMs;
_connected[tick] = reading.Connected;
_connects += reading.Connects;
_disconnects += reading.Disconnects;
if (!reading.Connected)
{
return;
}
_connectedMs += spanMs;
if (reading.Battery is { } battery)
{
Battery[tick] = battery;
_tally.Add(battery, spanMs);
}
}
/// <summary>The part of each tick's time in front that the controller was in use, 0 to 1; NaN where it was not connected.</summary>
public float[] ActiveColumn(IReadOnlyList<TelemetrySample> sensors)
{
float[] column = new float[ActiveMs.Length];
for (int i = 0; i < column.Length; i++)
{
int front = sensors[i].Input?.ForegroundMs ?? 0;
column[i] = !_connected[i] ? float.NaN : front <= 0 ? 0f : Math.Clamp((float)ActiveMs[i] / front, 0f, 1f);
}
return column;
}
/// <summary>The battery's level on each tick, in its own scale; NaN where there was none.</summary>
public float[] BatteryColumn()
{
float[] column = new float[Battery.Length];
for (int i = 0; i < column.Length; i++)
{
column[i] = Battery[i] is { Scale: not BatteryScale.None } b ? b.Level : float.NaN;
}
return column;
}
public InputDeviceRecord ToRecord(int index) => new()
{
Index = index,
Family = InputNames.Of(Device.Family),
VendorId = Device.VendorId,
ProductId = Device.ProductId,
Model = Device.Model,
Connection = InputNames.Of(Device.Connection),
XInputSlot = Device.XInputSlot,
Virtual = Device.IsVirtual,
Remapped = Remapped,
ConnectedMs = _connectedMs,
ActiveMs = TotalActiveMs,
Connects = _connects,
Disconnects = _disconnects,
Battery = BatteryRecord(),
};
private InputBatteryRecord? BatteryRecord()
{
if (!_tally.Any)
{
return null;
}
BatterySummary summary = _tally.Summary();
BatteryScale scale = summary.States.Select(static s => s.Scale).FirstOrDefault(static s => s != BatteryScale.None);
return new InputBatteryRecord
{
Scale = InputNames.Of(scale),
States = [.. summary.States.Select(static s => new InputBatteryStateRecord(InputNames.Of(s.State), s.Level, s.Ms))],
First = summary.First is { Scale: not BatteryScale.None } first ? first.Level : null,
Last = summary.Last is { Scale: not BatteryScale.None } last ? last.Level : null,
DrainPercentPerHour = summary.DrainPercentPerHour,
};
}
}
}
@@ -0,0 +1,33 @@
// 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.Application.Recording;
/// <summary>What <see cref="InputSessionBuilder"/> makes of a session's input readings: the totals a session row stores, and the controllers as JSON.</summary>
public sealed record InputSessionSummary
{
/// <summary>The time the reader ran and the session was not paused.</summary>
public long ObservedMs { get; init; }
/// <summary>Of that, the time a window of the game was in front: what every share is a share of.</summary>
public long ForegroundMs { get; init; }
public long ControllerMs { get; init; }
public long KeyboardMouseMs { get; init; }
public long BothMs { get; init; }
public long IdleMs { get; init; }
/// <summary>How many times the player went from a controller to the keyboard and mouse or back.</summary>
public int MethodSwitches { get; init; }
/// <summary>The sources that answered (<see cref="InputHealth.Sources"/>).</summary>
public string Source { get; init; } = string.Empty;
/// <summary><c>sessions.input_devices</c>.</summary>
public string DevicesJson { get; init; } = string.Empty;
}
@@ -24,4 +24,17 @@ public sealed record RecorderOptions
/// nothing more than a session always did.
/// </summary>
public bool AdvancedMetrics { get; init; }
/// <summary>
/// Whether this session reads controllers and keyboard-and-mouse activity (owner decisions D155 and D156): the
/// option <c>capture.input_devices</c> is on AND the Privacy Policy that describes the reading has been accepted on
/// this PC. False - the default, and every recorder with no input reader - reads and stores nothing of it.
/// </summary>
public bool InputDevices { get; init; }
/// <summary>
/// The option is on and the reading is held back because the terms that describe it are not accepted yet (D156).
/// The session says so in its notes, so that "nothing was read" has a reason beside it.
/// </summary>
public bool InputHeldForTerms { get; init; }
}
@@ -14,6 +14,7 @@ namespace FrameLedger.Application.Recording;
[JsonSerializable(typeof(FgMixRecord))]
[JsonSerializable(typeof(DriverProfileRecord))]
[JsonSerializable(typeof(Dictionary<string, SensorSeriesStats>))]
[JsonSerializable(typeof(InputDevicesRecord))]
public sealed partial class RecordingJsonContext : JsonSerializerContext
{
}
@@ -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.
@@ -118,6 +118,9 @@ public sealed class SessionRecorder : ISessionRecorder
}
}
/// <summary>The note of a session whose input reading waits for the terms (owner decision D156).</summary>
public const string InputHeldNote = "input: not read - the Privacy Policy that describes it is not accepted on this PC yet";
private async Task<RecordedSession> RecordStartedAsync(RecordRequest request, GameRow game, Guid guid, DateTimeOffset startedAt,
long qpcEpoch, long snapshotId, RecorderOptions options, CancellationToken ct)
{
@@ -151,6 +154,13 @@ public sealed class SessionRecorder : ISessionRecorder
using var writer = new PartialSessionWriter(_partials.Create(header), _clock, options.PartialFlushInterval);
var run = new Run(writer, poller, _clock, _observer, guid, advanced, request.NormalisedExePath);
writer.Note("started " + request.Mode);
if (options.InputHeldForTerms)
{
// D156: the option is on and nothing of controllers or of the keyboard and mouse is read, because the
// Privacy Policy that describes the reading has not been accepted on this PC yet.
writer.Note(InputHeldNote);
}
CaptureOutcome outcome = await RunLoopAsync(request, run, ct).ConfigureAwait(false);
DateTimeOffset endedAt = _clock.GetUtcNow();
await run.CompleteAdvancedAsync().ConfigureAwait(false);
@@ -213,7 +223,7 @@ public sealed class SessionRecorder : ISessionRecorder
bool crashEvent = hadPid && _crashes.FoundCrash(query);
ExitStatus exit = ExitStatusMapper.Map(outcome.Reason, outcome.ExitCode, crashEvent, reporterCounted);
SessionRow skeleton = Skeleton(header, outcome, endedAt, exit, new CrashWitness(crashEvent, reporter?.Image, reporterCounted), hooked) with { DriverProfileJson = driverProfile };
SessionRow skeleton = WithInputHeld(Skeleton(header, outcome, endedAt, exit, new CrashWitness(crashEvent, reporter?.Image, reporterCounted), hooked), options.InputHeldForTerms) with { DriverProfileJson = driverProfile };
var input = new FinalizeInput
{
Skeleton = skeleton,
@@ -263,6 +273,10 @@ public sealed class SessionRecorder : ISessionRecorder
};
}
/// <summary>D156: a session whose input reading waited for the terms says so in its stored notes, so the App can say why it has no input figures.</summary>
private static SessionRow WithInputHeld(SessionRow row, bool held) =>
held ? row with { CaptureNotes = row.CaptureNotes + "; " + CaptureNotes.InputHeldSlot } : row;
private static SessionRow Skeleton(PartialHeader h, CaptureOutcome o, DateTimeOffset endedAt, ExitStatus exit, CrashWitness crash, bool hooked)
{
string notes = ExitStatusMapper.Describe(o.Reason, o.ExitCode, crash.ApplicationLog, crash.Reporter, crash.ReporterCounted);
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FrameLedger.Application.Input;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Settings;
namespace FrameLedger.Application.Recording;
@@ -12,11 +14,23 @@ namespace FrameLedger.Application.Recording;
/// already under the product's) keeps its bound — the setting raises or lowers the product's rule, not the
/// operator's.
/// </summary>
/// <remarks>
/// <b>The input reading has a second condition</b> (owner decision D156): <c>capture.input_devices</c> is on unless
/// switched off, and the Agent may be recording before the App has shown the Privacy Policy that describes the
/// reading. So a session reads controllers and keyboard-and-mouse activity only when the accepted Privacy Policy is
/// that version or a later one (<see cref="InputTerms"/>). With no acceptance store given - an operator's console -
/// nothing can be shown to be accepted, and nothing is read.
/// </remarks>
public sealed class SettingsRecorderPolicy : IRecorderPolicy
{
private readonly RegisteredSettings _settings;
private readonly ILegalAcceptanceStore? _legal;
public SettingsRecorderPolicy(RegisteredSettings settings) => _settings = settings ?? throw new ArgumentNullException(nameof(settings));
public SettingsRecorderPolicy(RegisteredSettings settings, ILegalAcceptanceStore? legal = null)
{
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_legal = legal;
}
public async ValueTask<RecorderOptions> ResolveAsync(RecorderOptions baseline, CancellationToken ct = default)
{
@@ -25,6 +39,9 @@ public sealed class SettingsRecorderPolicy : IRecorderPolicy
int keep = await _settings.GetIntegerAsync(SettingsRegistry.RetentionRawSessionsPerGame, ct).ConfigureAwait(false);
int intervalMs = await _settings.GetIntegerAsync(SettingsRegistry.TelemetryIntervalMs, ct).ConfigureAwait(false);
bool advanced = await _settings.GetBooleanAsync(SettingsRegistry.TelemetryAdvanced, ct).ConfigureAwait(false);
bool input = await _settings.GetBooleanAsync(SettingsRegistry.CaptureInputDevices, ct).ConfigureAwait(false);
bool accepted = input && _legal is not null
&& InputTerms.Accepted((await _legal.FindAsync(InputTerms.PrivacyDocument, ct).ConfigureAwait(false))?.Version);
TimeSpan minimum = baseline.MinimumSessionLength < SessionFinalizer.MinimumSessionLength
? baseline.MinimumSessionLength
@@ -35,6 +52,8 @@ public sealed class SettingsRecorderPolicy : IRecorderPolicy
RetentionKeep = keep == 0 ? int.MaxValue : keep,
TelemetryInterval = TimeSpan.FromMilliseconds(intervalMs),
AdvancedMetrics = advanced,
InputDevices = accepted,
InputHeldForTerms = input && !accepted,
};
}
}
@@ -206,6 +206,22 @@ public static class SettingsRegistry
AgentReads = true,
};
/// <summary>
/// "Controllers and input" (owner decisions D155 and D156, 2026-11-14): whether the Agent reads, from outside the
/// game, which controllers are connected and in use, their batteries and the time of the last keyboard or mouse
/// input, and a session stores what it was played with (<c>21_INPUT_DEVICES</c>). <b>On by default</b> - and read
/// only once the Privacy Policy that describes it has been accepted on the PC (<c>Input.InputTerms</c>), which is
/// the recorder policy's to check, not this key's. Off means nothing is read or stored; a session recorded while
/// it was off is never filled in afterwards. Read at each session's start. Exactly "0" is off.
/// </summary>
public static readonly SettingDefinition CaptureInputDevices = new()
{
Key = "capture.input_devices",
Kind = SettingKind.Boolean,
Default = "1",
AgentReads = true,
};
/// <summary>FR-3.5: telemetry at 1 Hz, configurable 0.5–2 s. Milliseconds.</summary>
public static readonly SettingDefinition TelemetryIntervalMs = new()
{
@@ -284,7 +300,7 @@ public static class SettingsRegistry
public static IReadOnlyList<SettingDefinition> All { get; } =
[
UiLanguage, UiTheme, UiStartWithWindows, UiMinimizeToTray, UiHideAntiCheatHooking, UiFpsDecimals, UiHideScrollBars, UiLibraryView, UiPlayMode,
UiGameArt, UiGameArtTint, CaptureBackground, HookingKillSwitch, HookingUserModeExceptions, CaptureRunElevated, CaptureMinSessionSeconds, TelemetryIntervalMs, TelemetryAdvanced, RetentionRawSessionsPerGame,
UiGameArt, UiGameArtTint, CaptureBackground, HookingKillSwitch, HookingUserModeExceptions, CaptureRunElevated, CaptureMinSessionSeconds, CaptureInputDevices, TelemetryIntervalMs, TelemetryAdvanced, RetentionRawSessionsPerGame,
RetentionRemoveUninstalledGames, UpdateChannel, UpdateAutoCheck, PrivacyOnlineMetadata, LogDebug,
];
@@ -3,6 +3,7 @@
using System.Runtime.InteropServices;
using FrameLedger.Application.Advanced;
using FrameLedger.Application.Input;
namespace FrameLedger.Application.Telemetry;
@@ -32,5 +33,11 @@ namespace FrameLedger.Application.Telemetry;
/// was new at this poll, or null — the option is off, or that reader published nothing since the last poll. Null on
/// every sample recorded before it existed. Never a repeat of an earlier tick's readings: a reading is of one tick.
/// </param>
/// <param name="Input">
/// What the input reader saw for this session since the sample before (owner decisions of 2026-11-14,
/// <c>21_INPUT_DEVICES</c>): how the time the game was in front divides between a controller, the keyboard and mouse,
/// both and neither, and each controller's part. Null when the option is off, when the terms that say what is read
/// were not accepted yet, and on every sample recorded before it existed.
/// </param>
[StructLayout(LayoutKind.Auto)]
public readonly record struct TelemetrySample(long QpcTicks, GpuSample Sample, SystemReading System = default, ProcessReading Game = default, IReadOnlyList<AdvancedReading>? Advanced = null);
public readonly record struct TelemetrySample(long QpcTicks, GpuSample Sample, SystemReading System = default, ProcessReading Game = default, IReadOnlyList<AdvancedReading>? Advanced = null, InputReading? Input = null);
@@ -0,0 +1,28 @@
// 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.Domain.Input;
/// <summary>A controller's battery at one reading: what it was doing and how full it was, in the source's own steps.</summary>
/// <param name="State">What the battery was doing.</param>
/// <param name="Scale">What <paramref name="Level"/> counts in.</param>
/// <param name="Level">The level in <paramref name="Scale"/>; 0 when the scale is <see cref="BatteryScale.None"/>.</param>
[StructLayout(LayoutKind.Auto)]
public readonly record struct BatteryReading(BatteryState State, BatteryScale Scale, int Level)
{
/// <summary>A wired controller: no battery.</summary>
public static BatteryReading Wired { get; } = new(BatteryState.Wired, BatteryScale.None, 0);
/// <summary>
/// Whether a player would call the level low while the controller runs on its battery: XInput's "empty" or "low",
/// or 10 % and under. Never while it charges, and never for a reading with no level.
/// </summary>
public bool IsLow => State is BatteryState.Discharging or BatteryState.Unknown && Scale switch
{
BatteryScale.FourLevels => Level <= 1,
BatteryScale.Percent => Level <= 10,
_ => false,
};
}
@@ -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.Domain.Input;
/// <summary>What a <see cref="BatteryReading.Level"/> counts in: each source keeps its own steps, none is converted into another's.</summary>
public enum BatteryScale
{
/// <summary>No level: a wired controller, or one that reported a state only.</summary>
None = 0,
/// <summary>XInput's four words: 0 empty, 1 low, 2 medium, 3 full.</summary>
FourLevels,
/// <summary>Per cent, 0 to 100 - a DualSense reports it in steps of ten.</summary>
Percent,
}
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>What a controller's battery was doing at one reading.</summary>
public enum BatteryState
{
/// <summary>The controller reported a battery and not what it was doing, or reported a fault.</summary>
Unknown = 0,
/// <summary>Running on its battery.</summary>
Discharging,
/// <summary>Charging.</summary>
Charging,
/// <summary>Charged and on power.</summary>
Full,
/// <summary>A wired controller with no battery to report (XInput's word).</summary>
Wired,
}
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>One battery state a controller held during a session, and for how long.</summary>
/// <param name="State">What the battery was doing.</param>
/// <param name="Scale">What <paramref name="Level"/> counts in.</param>
/// <param name="Level">The level, in <paramref name="Scale"/>.</param>
/// <param name="Ms">The time it was read in this state, in milliseconds.</param>
public sealed record BatteryStateTime(BatteryState State, BatteryScale Scale, int Level, long Ms);
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>What <see cref="BatteryTally"/> adds up to for one controller.</summary>
public sealed record BatterySummary
{
/// <summary>Every state the battery was read in, the longest first.</summary>
public IReadOnlyList<BatteryStateTime> States { get; init; } = [];
/// <summary>The state that lasted longest - the first of <see cref="States"/> - or null when nothing was read.</summary>
public BatteryStateTime? Longest => States.Count > 0 ? States[0] : null;
/// <summary>The first reading of the session.</summary>
public BatteryReading? First { get; init; }
/// <summary>The last reading of the session.</summary>
public BatteryReading? Last { get; init; }
/// <summary>
/// How fast the battery ran down, in per cent an hour: the fall between the first and the last reading on battery
/// over the time read on battery. Null unless the level is in per cent, it fell, it was not put on power in
/// between, and at least <see cref="BatteryTally.MinimumDrainTime"/> was read on battery.
/// </summary>
public double? DrainPercentPerHour { get; init; }
}
@@ -0,0 +1,76 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>
/// One controller's battery readings over a session, accumulated by the time each stood for (<c>03_METRICS</c> §Input):
/// how long it spent at each level, which lasted longest, where it started and ended, and how fast it ran down.
/// </summary>
public sealed class BatteryTally
{
/// <summary>The least time on battery a rate is worked out over: a level moves in steps of ten, and less says nothing.</summary>
public static readonly TimeSpan MinimumDrainTime = TimeSpan.FromMinutes(10);
private readonly Dictionary<BatteryReading, long> _ms = [];
private BatteryReading? _first;
private BatteryReading? _last;
private int? _drainFrom;
private int _drainTo;
private long _drainMs;
private bool _drainBroken;
/// <summary>Whether any reading was added.</summary>
public bool Any => _first is not null;
/// <summary>Adds one reading that stood for <paramref name="elapsedMs"/> milliseconds (negative is treated as 0).</summary>
public void Add(BatteryReading reading, long elapsedMs)
{
long ms = Math.Max(0, elapsedMs);
_ms[reading] = _ms.GetValueOrDefault(reading) + ms;
_first ??= reading;
_last = reading;
if (reading.Scale != BatteryScale.Percent)
{
return;
}
if (reading.State == BatteryState.Discharging)
{
_drainFrom ??= reading.Level;
_drainTo = reading.Level;
_drainMs += ms;
}
else if (_drainFrom is not null && reading.State is BatteryState.Charging or BatteryState.Full)
{
// It was put on power after it had begun to run down: the fall between first and last is not one run.
_drainBroken = true;
}
}
public BatterySummary Summary()
{
BatteryStateTime[] states = [.. _ms
.Select(static p => new BatteryStateTime(p.Key.State, p.Key.Scale, p.Key.Level, p.Value))
.OrderByDescending(static s => s.Ms)
.ThenBy(static s => s.State)
.ThenByDescending(static s => s.Level)];
return new BatterySummary
{
States = states,
First = _first,
Last = _last,
DrainPercentPerHour = Drain(),
};
}
private double? Drain()
{
if (_drainBroken || _drainFrom is not { } from || from <= _drainTo || _drainMs < MinimumDrainTime.TotalMilliseconds)
{
return null;
}
return Math.Round((from - _drainTo) / (_drainMs / 3_600_000d), 1);
}
}
@@ -0,0 +1,72 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>
/// What a controller's USB vendor and product ids say about it (<c>21_INPUT_DEVICES</c> §Who a controller is): its
/// family, a model name for the ones this build knows, and whether it is a pad a program presents rather than one a
/// player holds. The ids are the only thing read of a device's identity - never a serial number, never an address.
/// </summary>
/// <remarks>
/// The model names are product names, the same in every language. A product id that is not listed has no name, and the
/// App then shows the family and the two ids: a wrong name would be worse than none.
/// </remarks>
public static class ControllerCatalog
{
public const int Microsoft = 0x045E;
public const int Sony = 0x054C;
public const int Nintendo = 0x057E;
public const int Valve = 0x28DE;
/// <summary>The Xbox 360 pad the Steam client presents when Steam Input stands between a controller and a game.</summary>
public const int SteamVirtualGamepad = 0x11FF;
public const int DualSense = 0x0CE6;
public const int DualSenseEdge = 0x0DF2;
private static readonly Dictionary<(int Vendor, int Product), string> _models = new()
{
[(Microsoft, 0x028E)] = "Xbox 360 Controller",
[(Microsoft, 0x028F)] = "Xbox 360 Wireless Controller",
[(Microsoft, 0x02D1)] = "Xbox One Controller",
[(Microsoft, 0x02DD)] = "Xbox One Controller",
[(Microsoft, 0x02E3)] = "Xbox Elite Wireless Controller",
[(Microsoft, 0x02EA)] = "Xbox One S Controller",
[(Microsoft, 0x02FD)] = "Xbox One S Controller",
[(Microsoft, 0x0B00)] = "Xbox Elite Wireless Controller Series 2",
[(Microsoft, 0x0B05)] = "Xbox Elite Wireless Controller Series 2",
[(Microsoft, 0x0B22)] = "Xbox Elite Wireless Controller Series 2",
[(Microsoft, 0x0B12)] = "Xbox Wireless Controller",
[(Microsoft, 0x0B13)] = "Xbox Wireless Controller",
[(Microsoft, 0x0B20)] = "Xbox Wireless Controller",
[(Sony, 0x05C4)] = "DualShock 4",
[(Sony, 0x09CC)] = "DualShock 4",
[(Sony, DualSense)] = "DualSense",
[(Sony, DualSenseEdge)] = "DualSense Edge",
[(Nintendo, 0x2009)] = "Switch Pro Controller",
[(Valve, SteamVirtualGamepad)] = "Steam Virtual Gamepad",
};
/// <summary>The family of a device with this vendor id; a device Windows presents through XInput is <see cref="ControllerFamily.Xbox"/> whoever made it.</summary>
public static ControllerFamily FamilyOf(int vendorId, bool xinput) => vendorId switch
{
Microsoft => ControllerFamily.Xbox,
Sony => ControllerFamily.PlayStation,
Nintendo => ControllerFamily.Nintendo,
_ => xinput ? ControllerFamily.Xbox : ControllerFamily.Other,
};
/// <summary>The model's product name, or null for ids this build does not list.</summary>
public static string? ModelOf(int vendorId, int productId) => _models.GetValueOrDefault((vendorId, productId));
/// <summary>Whether the ids are those of a pad a program presents - Steam's - rather than one a player holds.</summary>
public static bool IsVirtual(int vendorId, int productId) => vendorId == Valve && productId == SteamVirtualGamepad;
/// <summary>Whether the ids are a DualSense's or a DualSense Edge's, whose reports <see cref="DualSenseReport"/> reads.</summary>
public static bool IsDualSense(int vendorId, int productId) => vendorId == Sony && productId is DualSense or DualSenseEdge;
}
@@ -0,0 +1,20 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>How a controller reached the PC, as far as Windows says.</summary>
public enum ControllerConnection
{
/// <summary>Nothing said how.</summary>
Unknown = 0,
/// <summary>A cable.</summary>
Usb,
/// <summary>Bluetooth, classic or low energy.</summary>
Bluetooth,
/// <summary>A wireless link that is not known to be Bluetooth - XInput's own word, with no more detail.</summary>
Wireless,
}
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>
/// Whose controller a device is, from its USB vendor id (<c>03_METRICS</c> §Input). <see cref="Xbox"/> is also what
/// Windows presents through XInput with no vendor id: a pad of another maker that says it is an Xbox pad is one here,
/// because that is all Windows tells.
/// </summary>
public enum ControllerFamily
{
/// <summary>A game controller of a maker this build has no name for.</summary>
Other = 0,
/// <summary>Microsoft's, and every pad Windows presents through XInput with no vendor id.</summary>
Xbox,
/// <summary>Sony's: DualSense, DualSense Edge, DualShock 4.</summary>
PlayStation,
/// <summary>Nintendo's.</summary>
Nintendo,
}
@@ -0,0 +1,133 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>
/// What one input report of a DualSense says that a session keeps (<c>21_INPUT_DEVICES</c> §DualSense): whether
/// anything on the pad was in use, and its battery when the report carries one. The buttons and sticks are looked at to
/// answer the first and are not returned - nothing here can say which was pressed.
/// </summary>
/// <remarks>
/// <para>
/// <b>Three reports.</b> Over USB the pad sends report <c>0x01</c>, 64 bytes. Over Bluetooth it sends a short report
/// <c>0x01</c> of 10 bytes - sticks, buttons and triggers, no battery - until some program asks it for a feature report
/// or sends it an output report; from then until it reconnects it sends report <c>0x31</c>, 78 bytes, whose body is the
/// USB one moved by one byte. FrameLedger never asks: a game that reads the short report would lose its input (owner
/// decision, 2026-11-14). So over Bluetooth the battery is there only when Steam or the game switched the pad.
/// </para>
/// <para>
/// The layout is the one the pad's makers' drivers and the open descriptions of the protocol agree on; it was written
/// from those descriptions, and <b>no report from a real pad had passed through it when it was written</b>.
/// </para>
/// </remarks>
public static class DualSenseReport
{
public const int UsbLength = 64;
public const int BluetoothShortLength = 10;
public const int BluetoothLength = 78;
/// <summary>How far a stick must be from its centre (128) to count: a quarter of its travel, as XInput's own dead zone is.</summary>
public const int StickDeadzone = 32;
/// <summary>How far a trigger must be pulled (0-255) to count: XInput's threshold.</summary>
public const int TriggerThreshold = 30;
private const int _usbReportId = 0x01;
private const int _bluetoothReportId = 0x31;
private const int _hatNeutral = 8;
// Offsets in the full report's body, which starts after the report id over USB and one byte later over Bluetooth.
private const int _fullTriggers = 4;
private const int _fullButtons = 7;
private const int _fullStatus = 52;
private const int _fullBodyLength = 53;
/// <summary>Reads one report; false for anything that is not one of the three, which is then not counted as a report of this pad.</summary>
/// <param name="report">The report as Windows hands it over, its id first.</param>
/// <param name="bluetooth">
/// Whether the pad is on Bluetooth. The length cannot say: Windows hands every report of a device over at the length
/// of its longest, so the short Bluetooth report arrives padded to 78 bytes with the same id as the USB one.
/// </param>
/// <param name="active">Whether anything on the pad was in use.</param>
/// <param name="battery">The battery, when the report carries it.</param>
public static bool TryRead(ReadOnlySpan<byte> report, bool bluetooth, out bool active, out BatteryReading? battery)
{
active = false;
battery = null;
if (report.IsEmpty)
{
return false;
}
if (!bluetooth)
{
if (report.Length < 1 + _fullBodyLength || report[0] != _usbReportId)
{
return false;
}
ReadFull(report[1..], out active, out battery);
return true;
}
if (report[0] == _bluetoothReportId && report.Length >= 2 + _fullBodyLength)
{
ReadFull(report[2..], out active, out battery);
return true;
}
if (report[0] == _usbReportId && report.Length >= BluetoothShortLength)
{
// x, y, rx, ry, three bytes of buttons (the third's upper six bits are a counter), the two triggers.
active = SticksMoved(report[1..5]) || ButtonsDown(report[5], report[6], report[7] & 0x03) || TriggersPulled(report[8], report[9]);
return true;
}
return false;
}
private static void ReadFull(ReadOnlySpan<byte> body, out bool active, out BatteryReading? battery)
{
// x, y, rx, ry, the two triggers, a counter, then the buttons: hat and face, shoulders and sticks, the rest.
active = SticksMoved(body[..4])
|| TriggersPulled(body[_fullTriggers], body[_fullTriggers + 1])
|| ButtonsDown(body[_fullButtons], body[_fullButtons + 1], body[_fullButtons + 2]);
battery = BatteryOf(body[_fullStatus]);
}
private static bool SticksMoved(ReadOnlySpan<byte> axes)
{
foreach (byte axis in axes)
{
if (Math.Abs(axis - 128) > StickDeadzone)
{
return true;
}
}
return false;
}
private static bool TriggersPulled(byte left, byte right) => left > TriggerThreshold || right > TriggerThreshold;
private static bool ButtonsDown(byte hatAndFace, byte shoulders, int rest) =>
(hatAndFace & 0x0F) < _hatNeutral || (hatAndFace & 0xF0) != 0 || shoulders != 0 || rest != 0;
/// <summary>The status byte: the low four bits are the level in tenths (10 is 100 %), the high four what the battery is doing.</summary>
private static BatteryReading BatteryOf(byte status)
{
int level = Math.Min(status & 0x0F, 10) * 10;
return (status >> 4) switch
{
0x0 => new BatteryReading(BatteryState.Discharging, BatteryScale.Percent, level),
0x1 => new BatteryReading(BatteryState.Charging, BatteryScale.Percent, level),
0x2 => new BatteryReading(BatteryState.Full, BatteryScale.Percent, 100),
// 0xA and 0xB are "not charging" for voltage or temperature, 0xF a charging fault: a level and no state.
_ => new BatteryReading(BatteryState.Unknown, BatteryScale.Percent, level),
};
}
}
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>
/// What a stretch of a session was played with (<c>03_METRICS</c> §Input): decided for each slice of time the game was
/// in front, from outside the game. It says a device was in use while the game was in front, never what the game did
/// with it.
/// </summary>
public enum InputClass
{
/// <summary>Neither a controller nor the keyboard or mouse was in use.</summary>
None = 0,
/// <summary>A controller was in use and the keyboard and mouse were not.</summary>
Controller,
/// <summary>The keyboard or the mouse was in use and no controller was. The two are one class: only the time of the last input is read.</summary>
KeyboardMouse,
/// <summary>A controller and the keyboard or mouse were both in use.</summary>
Both,
}
@@ -0,0 +1,79 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>
/// How many times a session went from one thing to another (<c>03_METRICS</c> §Input): from a controller to the
/// keyboard and mouse and back, or from one maker's controller to another's.
/// </summary>
public static class InputSwitches
{
/// <summary>
/// The number of changes in a sequence of ticks, where each tick is either one value or nothing. A tick with
/// nothing - no input, or two things at once - is skipped and does not end what came before it: a player who puts
/// the controller down, waits, and picks it up again has not switched.
/// </summary>
public static int Count<T>(IEnumerable<T?> ticks)
where T : struct
{
ArgumentNullException.ThrowIfNull(ticks);
int switches = 0;
T? previous = null;
foreach (T? tick in ticks)
{
if (tick is not { } now)
{
continue;
}
if (previous is { } before && !EqualityComparer<T>.Default.Equals(before, now))
{
switches++;
}
previous = now;
}
return switches;
}
/// <summary>The one class a tick was played with, or null when it was played with both or with neither.</summary>
public static InputClass? Exclusive(long controllerMs, long keyboardMouseMs, long bothMs)
{
if (bothMs > 0 || (controllerMs > 0 && keyboardMouseMs > 0))
{
return null;
}
if (controllerMs > 0)
{
return InputClass.Controller;
}
return keyboardMouseMs > 0 ? InputClass.KeyboardMouse : null;
}
/// <summary>The class a tick was mostly played with - what its point on the timeline shows - or null when the game was not in front at all.</summary>
public static InputClass? Dominant(long controllerMs, long keyboardMouseMs, long bothMs, long idleMs)
{
if (controllerMs + keyboardMouseMs + bothMs + idleMs <= 0)
{
return null;
}
InputClass best = InputClass.None;
long most = idleMs;
if (keyboardMouseMs > most)
{
(best, most) = (InputClass.KeyboardMouse, keyboardMouseMs);
}
if (controllerMs > most)
{
(best, most) = (InputClass.Controller, controllerMs);
}
return bothMs > most ? InputClass.Both : best;
}
}
@@ -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;
}
}
@@ -0,0 +1,67 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>
/// Whether two entries of a session's controller list are one pad seen twice (<c>03_METRICS</c> §Input). With Steam
/// Input between a controller and a game, Windows shows the controller the player holds and an Xbox pad Steam presents
/// for it; both move together. Counted as two, a session would have twice the controllers and a share for a maker
/// nobody held.
/// </summary>
public static class VirtualPad
{
/// <summary>How much of the busier entry's time the other must share for the two to be one pad.</summary>
public const double MergeAt = 0.9;
/// <summary>The least time in use the two must have: a few seconds moving together prove nothing.</summary>
public const long MinimumActiveMs = 10_000;
/// <summary>
/// How much two controllers were in use at the same moments: the time both were in use over the time the busier of
/// the two was, 0 to 1. Each array holds a controller's milliseconds in use for every tick of the session, tick for
/// tick.
/// </summary>
public static double Coincidence(ReadOnlySpan<int> a, ReadOnlySpan<int> b)
{
long together = 0;
long sumA = 0;
long sumB = 0;
int n = Math.Min(a.Length, b.Length);
for (int i = 0; i < n; i++)
{
together += Math.Min(a[i], b[i]);
}
foreach (int ms in a)
{
sumA += ms;
}
foreach (int ms in b)
{
sumB += ms;
}
long busier = Math.Max(sumA, sumB);
return busier <= 0 ? 0 : (double)together / busier;
}
/// <summary>Whether the two are one pad: they were in use for long enough, and at the same moments.</summary>
public static bool IsSamePad(ReadOnlySpan<int> a, ReadOnlySpan<int> b)
{
long sumA = 0;
long sumB = 0;
foreach (int ms in a)
{
sumA += ms;
}
foreach (int ms in b)
{
sumB += ms;
}
return Math.Min(sumA, sumB) >= MinimumActiveMs && Coincidence(a, b) >= MergeAt;
}
}
+50
View File
@@ -0,0 +1,50 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>
/// What XInput's answers about one of its four pads mean to a session (<c>21_INPUT_DEVICES</c> §XInput): whether the
/// state it returned is a pad in use, and what its battery words are. The thresholds are the ones XInput's own header
/// recommends, so "in use" here is what a game written to that header would call input.
/// </summary>
public static class XInputPad
{
/// <summary><c>XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE</c>.</summary>
public const int LeftThumbDeadzone = 7849;
/// <summary><c>XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE</c>.</summary>
public const int RightThumbDeadzone = 8689;
/// <summary><c>XINPUT_GAMEPAD_TRIGGER_THRESHOLD</c>.</summary>
public const int TriggerThreshold = 30;
private const int _typeWired = 0x01;
private const int _typeAlkaline = 0x02;
private const int _typeNimh = 0x03;
private const int _levelFull = 0x03;
/// <summary>Whether a state is a pad in use: a button down, a trigger past the threshold, or a stick outside its dead zone. A stick held counts; one that drifts inside the dead zone does not.</summary>
public static bool IsActive(int buttons, int leftTrigger, int rightTrigger, int thumbLx, int thumbLy, int thumbRx, int thumbRy) =>
buttons != 0
|| leftTrigger > TriggerThreshold
|| rightTrigger > TriggerThreshold
|| Outside(thumbLx, thumbLy, LeftThumbDeadzone)
|| Outside(thumbRx, thumbRy, RightThumbDeadzone);
/// <summary>
/// <c>XINPUT_BATTERY_INFORMATION</c> as a reading: null for "disconnected" and for a type this build does not know,
/// <see cref="BatteryReading.Wired"/> for a wired pad, and the four levels for a battery. XInput does not say whether
/// a battery charges, so one that is not wired is read as discharging.
/// </summary>
public static BatteryReading? Battery(int type, int level) => type switch
{
_typeWired => BatteryReading.Wired,
_typeAlkaline or _typeNimh => new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, Math.Clamp(level, 0, _levelFull)),
// 0 is XInput's "disconnected" and 0xFF its "unknown": neither is a battery to show.
_ => null,
};
private static bool Outside(int x, int y, int deadzone) => ((long)x * x) + ((long)y * y) > (long)deadzone * deadzone;
}
@@ -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)
@@ -4,6 +4,7 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using FrameLedger.Application.Advanced;
using FrameLedger.Application.Input;
using FrameLedger.Application.Telemetry;
namespace FrameLedger.Infrastructure.Telemetry;
@@ -49,6 +50,12 @@ public sealed class TelemetryPoller : ITelemetryPoller
private IDisposable? _advancedHold;
private AdvancedSnapshot? _lastAdvanced;
// Controllers and input (owner decisions D155 and D156): the Agent's one reader, of which this poller opens a
// view for its session and reads it on every tick. Null when the option is off or its terms are not accepted.
private readonly IInputDevices? _input;
private IInputActivitySource? _inputView;
private volatile GameProcess? _followed;
private Thread? _thread;
private int _queued;
private long _dropped;
@@ -65,9 +72,11 @@ public sealed class TelemetryPoller : ITelemetryPoller
/// <param name="system">The machine beside the GPU, read on the same tick (2026-09-21); owned and disposed with <paramref name="source"/> when <paramref name="ownsSource"/> is set. Null composes none, and every sample's <see cref="TelemetrySample.System"/> is empty.</param>
/// <param name="game">The game process's own memory (beta.12, D43), read on the same tick for the process <see cref="Follow"/> named; owned and disposed with the others when <paramref name="ownsSource"/> is set. Null composes none, and every sample's <see cref="TelemetrySample.Game"/> is empty.</param>
/// <param name="advanced">The Agent's shared reader of advanced metrics (owner decision D101), held while this poller runs and never owned by it: each of its ticks is attached to one sample. Null - the option is off - composes none, and every sample's <see cref="TelemetrySample.Advanced"/> is null.</param>
/// <param name="input">The Agent's one input reader (owner decisions D155 and D156), never owned by this poller: a view of it is open while the poller runs, and what it saw since the last tick is attached to each sample. Null - the option is off, or its terms are not accepted - opens none, and every sample's <see cref="TelemetrySample.Input"/> is null.</param>
public TelemetryPoller(IGpuTelemetrySource source, TelemetryPollerOptions options, TimeProvider clock, bool ownsSource = false,
ISystemTelemetrySource? system = null, IGameMemorySource? game = null, IAdvancedHardware? advanced = null)
ISystemTelemetrySource? system = null, IGameMemorySource? game = null, IAdvancedHardware? advanced = null, IInputDevices? input = null)
{
_input = input;
_source = source ?? throw new ArgumentNullException(nameof(source));
_system = system;
_game = game;
@@ -107,6 +116,9 @@ public sealed class TelemetryPoller : ITelemetryPoller
// Held from here to Dispose: the shared reader runs while a session samples, and closes some seconds after
// the last session and the page have let go (D107).
_advancedHold = _advanced?.Acquire();
// The input reader runs from its first view to its last (D155): this session's view is open from here to Dispose.
_ = InputView();
_thread = new Thread(Loop)
{
IsBackground = true,
@@ -130,14 +142,16 @@ public sealed class TelemetryPoller : ITelemetryPoller
ProcessReading game = default;
bool measured = _game is not null && _game.TryRead(out game);
IReadOnlyList<AdvancedReading>? advanced = NewAdvancedReadings();
if (!gpu && !machine && !measured && advanced is null)
InputReading? played = null;
bool read = InputView() is { } view && view.TryRead(out played);
if (!gpu && !machine && !measured && advanced is null && !read)
{
return;
}
// A tick only the machine or the game answered still carries them: the placeholder names no layer and no field.
sample ??= new GpuSample { TakenAt = _clock.GetUtcNow(), Layer = TelemetryLayer.None };
_queue.Enqueue(new TelemetrySample(_clock.GetTimestamp(), sample, system, game, advanced));
_queue.Enqueue(new TelemetrySample(_clock.GetTimestamp(), sample, system, game, advanced, played));
if (Interlocked.Increment(ref _queued) > _options.QueueCapacity && _queue.TryDequeue(out _))
{
Interlocked.Decrement(ref _queued);
@@ -163,6 +177,25 @@ public sealed class TelemetryPoller : ITelemetryPoller
return snapshot.Readings.Count > 0 ? snapshot.Readings : null;
}
/// <summary>
/// This session's view of the input reader, opened where it is first needed - <see cref="Start"/> in the Agent, the
/// first tick where a test drives the poller without its thread - and told at once whose windows are the game's.
/// Null when no reader was composed: the option is off, or its terms are not accepted.
/// </summary>
private IInputActivitySource? InputView()
{
if (_inputView is null && _input is not null && !_disposed)
{
_inputView = _input.Open();
if (_followed is { } target)
{
_inputView.Follow(target);
}
}
return _inputView;
}
public bool FollowAdapter(ulong luid) => _source is IGpuAdapterSelector selector && selector.SelectAdapter(luid);
/// <summary>The game process whose memory the next ticks read (beta.12, D43); ignored without a game source.</summary>
@@ -170,6 +203,10 @@ public sealed class TelemetryPoller : ITelemetryPoller
{
ArgumentNullException.ThrowIfNull(target);
_game?.Follow(target);
// Whose windows count as this session's game (D155). Kept, so a view opened after this is told as well.
_followed = target;
_inputView?.Follow(target);
}
public int Drain(ICollection<TelemetrySample> into)
@@ -198,6 +235,7 @@ public sealed class TelemetryPoller : ITelemetryPoller
_thread?.Join(TimeSpan.FromSeconds(2));
_stop.Dispose();
_advancedHold?.Dispose();
_inputView?.Dispose();
if (_ownsSource)
{
_source.Dispose();
@@ -3,6 +3,7 @@
using FluentAssertions;
using FrameLedger.App.Services;
using FrameLedger.Application.Input;
using FrameLedger.Shared;
namespace FrameLedger.App.Tests;
@@ -58,6 +59,22 @@ public sealed class LegalDocumentsTests
}
}
/// <summary>
/// D156: the Agent reads controllers and input only once the Privacy Policy that describes the reading has been
/// accepted. The Agent knows that document by a key and a version of its own; both must be the App's - the key
/// the Legal Gate stores an acceptance under, and a version the shipped document has reached.
/// </summary>
[Fact]
public void TheInputReadingsTermsAreThePrivacyPolicyThisBuildShips()
{
InputTerms.PrivacyDocument.Should().Be(LegalDocuments.Privacy);
LegalDocument privacy = LegalDocuments.Load(BuildLine.Main).Single(static d => string.Equals(d.Key, LegalDocuments.Privacy, StringComparison.Ordinal));
InputTerms.Accepted(privacy.Version).Should().BeTrue(
"accepting the document this build shows must be enough for the reading it describes; shipped is " + privacy.Version);
privacy.Text.Should().Contain("Controllers and input", "the document the reading waits for is the one that describes it");
}
[Fact]
public void TheVersionLineIsTheDocumentsOwn()
{
@@ -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);
@@ -448,6 +448,32 @@ public sealed class SettingsViewModelTests
}
}
[Fact]
public async Task ControllersAndInputIsOnByDefaultAndItsToggleIsPersisted()
{
// Owner decisions D155 and D156 (2026-11-14): capture.input_devices, default 1. The Agent reads it at the next
// session's start - and uses it only once the terms that describe the reading are accepted, which is not the
// page's to decide.
await using ScratchLedger s = await ScratchLedger.OpenAsync();
Harness h = await OpenAsync(s);
h.Vm.InputDevices.Should().BeTrue("on unless switched off");
(await h.Settings.GetBooleanAsync(SettingsRegistry.CaptureInputDevices, Ct)).Should().BeTrue();
h.Vm.InputDevices = false;
Task off = h.Vm.Pending;
await off;
(await h.Settings.GetBooleanAsync(SettingsRegistry.CaptureInputDevices, Ct)).Should().BeFalse();
Harness reopened = await OpenAsync(s);
reopened.Vm.InputDevices.Should().BeFalse("the page shows what the row holds");
reopened.Vm.InputDevices = true;
Task on = reopened.Vm.Pending;
await on;
(await reopened.Settings.GetBooleanAsync(SettingsRegistry.CaptureInputDevices, Ct)).Should().BeTrue();
}
[Fact]
public async Task AdvancedMetricsIsOffByDefaultAndItsToggleIsPersisted()
{
@@ -155,6 +155,7 @@ public sealed class ViewerModeTests
[SettingsRegistry.HookingUserModeExceptions.Key] = ("IsChecked", "UserModeExceptions, Mode=TwoWay"),
[SettingsRegistry.CaptureRunElevated.Key] = ("IsChecked", "RunElevated, Mode=TwoWay"),
[SettingsRegistry.CaptureMinSessionSeconds.Key] = ("Value", "MinSessionSeconds, Mode=TwoWay"),
[SettingsRegistry.CaptureInputDevices.Key] = ("IsChecked", "InputDevices, Mode=TwoWay"),
[SettingsRegistry.TelemetryIntervalMs.Key] = ("Value", "TelemetryIntervalMs, Mode=TwoWay"),
[SettingsRegistry.TelemetryAdvanced.Key] = ("IsChecked", "AdvancedMetrics, Mode=TwoWay"),
[SettingsRegistry.RetentionRawSessionsPerGame.Key] = ("Value", "RetentionRawSessions, Mode=TwoWay"),
@@ -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");
}
}
@@ -0,0 +1,267 @@
// 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;
namespace FrameLedger.Application.Tests.Input;
/// <summary>
/// One session's slices added up into a reading a tick (<c>03_METRICS</c> §Input): only the time the game was in front
/// is classified, a pause is not observed, and a controller that was there at the start has not connected.
/// </summary>
public sealed class InputTickAccumulatorTests
{
private static readonly InputDevice _xbox = new() { Id = 1, Family = ControllerFamily.Xbox, XInputSlot = 0 };
private static readonly InputDevice _dualSense = new()
{
Id = 2,
Family = ControllerFamily.PlayStation,
VendorId = ControllerCatalog.Sony,
ProductId = ControllerCatalog.DualSense,
Connection = ControllerConnection.Usb,
};
private static InputSlice Slice(bool keyboardMouse = false, InputHealth? health = null, bool virtualPad = false, params InputSliceDevice[] devices) => new()
{
ElapsedMs = 100,
ForegroundProcessId = 42,
KeyboardMouseActive = keyboardMouse,
VirtualPad = virtualPad,
Devices = devices,
Health = health ?? new InputHealth(),
};
private static InputSliceDevice Pad(InputDevice device, bool active = false, BatteryReading? battery = null) => new(device, active, battery);
[Fact]
public void NothingAddedIsNothingToTake() =>
new InputTickAccumulator().Take().Should().BeNull();
[Fact]
public void EachSliceInFrontCountsForOneOfTheFourClasses()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_xbox, active: true)), inFront: true, paused: false);
accumulator.Add(Slice(devices: Pad(_xbox, active: true)), inFront: true, paused: false);
accumulator.Add(Slice(keyboardMouse: true, devices: Pad(_xbox)), inFront: true, paused: false);
accumulator.Add(Slice(keyboardMouse: true, devices: Pad(_xbox, active: true)), inFront: true, paused: false);
accumulator.Add(Slice(devices: Pad(_xbox)), inFront: true, paused: false);
InputReading reading = accumulator.Take()!;
reading.SpanMs.Should().Be(500);
reading.ObservedMs.Should().Be(500);
reading.ForegroundMs.Should().Be(500);
reading.ControllerMs.Should().Be(200);
reading.KeyboardMouseMs.Should().Be(100);
reading.BothMs.Should().Be(100);
reading.IdleMs.Should().Be(100);
reading.Devices.Should().Equal(new InputDeviceReading(1, Connected: true, ActiveMs: 300, Battery: null, Connects: 0, Disconnects: 0));
reading.Table.Should().Equal(_xbox);
}
/// <summary>Typing in a browser beside the game is not the game played with the keyboard.</summary>
[Fact]
public void ASliceWithAnotherProgramInFrontIsNotClassified()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(keyboardMouse: true, devices: Pad(_xbox, active: true)), inFront: false, paused: false);
accumulator.Add(Slice(devices: Pad(_xbox, active: true)), inFront: true, paused: false);
InputReading reading = accumulator.Take()!;
reading.SpanMs.Should().Be(200);
reading.ObservedMs.Should().Be(200);
reading.ForegroundMs.Should().Be(100);
reading.ControllerMs.Should().Be(100);
reading.KeyboardMouseMs.Should().Be(0);
reading.BothMs.Should().Be(0);
reading.Devices[0].ActiveMs.Should().Be(100, "a controller's time in use is time in the game");
}
[Fact]
public void APausedSliceIsNotObservedButItsTimeAndItsControllersAre()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_xbox, active: true)), inFront: true, paused: true);
accumulator.Add(Slice(), inFront: true, paused: true);
InputReading reading = accumulator.Take()!;
reading.SpanMs.Should().Be(200, "a battery level is timed by the clock, paused or not");
reading.ObservedMs.Should().Be(0);
reading.ForegroundMs.Should().Be(0);
reading.ControllerMs.Should().Be(0);
reading.Devices.Should().Equal(new InputDeviceReading(1, Connected: false, ActiveMs: 0, Battery: null, Connects: 0, Disconnects: 1));
}
[Fact]
public void AControllerThereAtTheStartHasNotConnectedAndOneThatComesLaterHas()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_xbox)), inFront: true, paused: false);
accumulator.Add(Slice(devices: [Pad(_xbox), Pad(_dualSense)]), inFront: true, paused: false);
InputReading reading = accumulator.Take()!;
reading.Devices.Should().Equal(
new InputDeviceReading(1, Connected: true, ActiveMs: 0, Battery: null, Connects: 0, Disconnects: 0),
new InputDeviceReading(2, Connected: true, ActiveMs: 0, Battery: null, Connects: 1, Disconnects: 0));
reading.Table.Should().Equal(_xbox, _dualSense);
}
[Fact]
public void ADropAndAReturnAreCountedEvenAcrossTicks()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_dualSense)), inFront: true, paused: false);
accumulator.Add(Slice(), inFront: true, paused: false);
InputReading dropped = accumulator.Take()!;
accumulator.Add(Slice(), inFront: true, paused: false);
InputReading gone = accumulator.Take()!;
accumulator.Add(Slice(devices: Pad(_dualSense)), inFront: true, paused: false);
InputReading back = accumulator.Take()!;
dropped.Devices.Should().Equal(new InputDeviceReading(2, Connected: false, ActiveMs: 0, Battery: null, Connects: 0, Disconnects: 1));
gone.Devices.Should().BeEmpty("a controller that left is not carried into the next tick");
gone.Table.Should().BeEmpty();
back.Devices.Should().Equal(new InputDeviceReading(2, Connected: true, ActiveMs: 0, Battery: null, Connects: 1, Disconnects: 0));
}
[Fact]
public void ATakeStartsTheNextTickFromNothingButTheControllersStillConnected()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(keyboardMouse: true, virtualPad: true, devices: Pad(_xbox, active: true)), inFront: true, paused: false);
accumulator.Take().Should().NotBeNull();
accumulator.Take().Should().BeNull("no slice since the last take");
accumulator.Add(Slice(devices: Pad(_xbox)), inFront: true, paused: false);
InputReading next = accumulator.Take()!;
next.SpanMs.Should().Be(100);
next.BothMs.Should().Be(0);
next.IdleMs.Should().Be(100);
next.VirtualPad.Should().BeFalse();
next.Devices.Should().Equal(new InputDeviceReading(1, Connected: true, ActiveMs: 0, Battery: null, Connects: 0, Disconnects: 0));
}
[Fact]
public void TheBatteryIsTheLastOneReportedAndASliceWithNoneKeepsIt()
{
var eighty = new BatteryReading(BatteryState.Discharging, BatteryScale.Percent, 80);
var seventy = new BatteryReading(BatteryState.Discharging, BatteryScale.Percent, 70);
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_dualSense, battery: eighty)), inFront: true, paused: false);
accumulator.Add(Slice(devices: Pad(_dualSense, battery: seventy)), inFront: true, paused: false);
accumulator.Add(Slice(devices: Pad(_dualSense)), inFront: true, paused: false);
accumulator.Take()!.Devices[0].Battery.Should().Be(seventy);
accumulator.Add(Slice(devices: Pad(_dualSense)), inFront: true, paused: false);
accumulator.Take()!.Devices[0].Battery.Should().Be(seventy, "the level a pad last reported is still its level");
}
[Fact]
public void AVirtualPadSeenInAnySliceMarksTheTick()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(), inFront: true, paused: false);
accumulator.Add(Slice(virtualPad: true), inFront: false, paused: true);
accumulator.Take()!.VirtualPad.Should().BeTrue();
}
[Fact]
public void TheSameControllerNamedTwiceInASliceCountsOnce()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: [Pad(_xbox, active: true), Pad(_xbox, active: true)]), inFront: true, paused: false);
accumulator.Take()!.Devices.Should().Equal(new InputDeviceReading(1, Connected: true, ActiveMs: 100, Battery: null, Connects: 0, Disconnects: 0));
}
/// <summary>The reader runs before and after a session: a session's counts start where it began to read.</summary>
[Fact]
public void TheHealthIsWhatHappenedSinceTheSessionsFirstSlice()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(health: new InputHealth { RawInputRegistered = true, RawReports = 1000, Slices = 50, ThreadCpuMs = 7, XInputReads = 40 }), inFront: true, paused: false);
accumulator.Add(Slice(health: new InputHealth { RawInputRegistered = true, XInputAvailable = true, RawReports = 1250, RawReportsUnread = 2, Slices = 51, ThreadCpuMs = 9, XInputReads = 44, XInputSilent = 1, Faults = 1 }), inFront: true, paused: false);
InputHealth health = accumulator.Take()!.Health;
health.Should().Be(new InputHealth
{
RawInputRegistered = true,
XInputAvailable = true,
RawReports = 250,
RawReportsUnread = 2,
Slices = 1,
ThreadCpuMs = 2,
XInputReads = 4,
XInputSilent = 1,
Faults = 1,
});
health.Sources().Should().Be("rawinput+xinput");
}
[Fact]
public void TheSourcesAreTheOnesThatAnswered()
{
new InputHealth().Sources().Should().BeEmpty();
new InputHealth { LastInputAvailable = true }.Sources().Should().Be("lastinput");
new InputHealth { RawInputRegistered = true, XInputAvailable = true, LastInputAvailable = true }.Sources().Should().Be("rawinput+xinput+lastinput");
}
[Fact]
public void ANegativeElapsedTimeCountsForNothing()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_xbox, active: true)) with { ElapsedMs = -40 }, inFront: true, paused: false);
InputReading reading = accumulator.Take()!;
reading.SpanMs.Should().Be(0);
reading.ControllerMs.Should().Be(0);
}
[Fact]
public void TheStoredWordsReadBackAsWhatTheyWere()
{
foreach (ControllerFamily family in Enum.GetValues<ControllerFamily>())
{
InputNames.FamilyOf(InputNames.Of(family)).Should().Be(family);
}
foreach (ControllerConnection connection in Enum.GetValues<ControllerConnection>())
{
InputNames.ConnectionOf(InputNames.Of(connection)).Should().Be(connection);
}
foreach (BatteryState state in Enum.GetValues<BatteryState>())
{
InputNames.StateOf(InputNames.Of(state)).Should().Be(state);
}
foreach (BatteryScale scale in Enum.GetValues<BatteryScale>())
{
InputNames.ScaleOf(InputNames.Of(scale)).Should().Be(scale);
}
InputNames.FamilyOf("a word a later release wrote").Should().Be(ControllerFamily.Other);
InputNames.ConnectionOf(null).Should().Be(ControllerConnection.Unknown);
InputNames.StateOf(null).Should().Be(BatteryState.Unknown);
InputNames.ScaleOf(null).Should().Be(BatteryScale.None);
}
[Fact]
public void ADevicesModelIsItsCatalogName()
{
_dualSense.Model.Should().Be("DualSense");
_xbox.Model.Should().BeNull("one of XInput's pads that nothing named has no ids to look up");
}
}
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more