Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

---------

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

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

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

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

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

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

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 21:54:13 +07:00
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
poli0981andClaude Fable 5.2 e20bf9abc0 feat(advanced): Advanced metrics is closed - the ten Streamline readings that waited for a spike are not read, with the reason (D154) (#463)
The owner was shown the catalog (140 entries, 110 read) and what the ten entries of reach
Spike hold, read from Streamline 2.14.16's own headers, with what reading them takes: none
is an export, a game gets each function through slGetFeatureFunction and keeps the pointer,
so seeing its calls means handing the game a function of ours in place of Streamline's
(rule 4) - and a game that fetched its functions before the attach never calls it. The
owner closed it.

The ten are RefusedRoute; that reach's sentence names the third refused route in English,
Vietnamese and Japanese; the guide no longer says a later release reads more; 18_GPU's
inventory, 20_OPEN_QUESTIONS M15 and HANDOFF say train D is not built. Nothing that was
read stops being read; no hook, layout, schema or stored value changes.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 14:04:54 +00:00
poli0981andClaude Fable 5.2 5440f8a34a fix(app): the two GPU labels say what each figure is, not which holds the other (D152) (#462)
* docs: owner-only item 47 read (the Cyberpunk difference is the driver's; the holes are gone from steady play); Streamline's Reflex and DLSS-RR guides read against the code

Item 47, run by the owner on 0.1.0-beta.49 (sessions 236-245), read from a copy of the
ledger and the Overlay's logs: in Cyberpunk 2077 without frame generation the driver's
active GPU time is longer than its two marks are apart on 4 917 of 5 394 frames, and on
none of 129 900 frames in five other games; samples without a report are confined to a
game's start; off means off; D141's stop fired in a real game for the first time.

NVIDIA's Streamline guides for Reflex and DLSS Ray Reconstruction (2.14.16), read whole:
the guide's page on Advanced metrics now says what bUseGameSleep and bLowLatencyMode
mean; two design tables no longer promise PC latency (D147); spike-notes 30 has what the
guides add. Two comments (fl_shm.h, dllmain.cpp) said super resolution and ray
reconstruction run together - they do not; comments only, no object code changes.

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

* docs(handoff): item 47 (f) and (g) in the owner's words - the NVIDIA App's Low Latency Mode is off, no hitch

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

* docs(handoff): item 47 (f) as the owner showed it - the NVIDIA App's Low Latency Mode is off for Cyberpunk 2077, the game's own Reflex is on

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

* fix(app): the two GPU labels say what each figure is, not which holds the other (D152)

"GPU active render (idle time excluded)" and "GPU render, start to end (idle time included)"
followed NVIDIA's header, which defines the active time as the span between the driver's two
GPU marks less its idle time. Item 47 counted it on 0.1.0-beta.49: in Cyberpunk 2077 without
frame generation the active time is the longer of the two on 4 917 of 5 394 frames. The owner
chose to reword the labels. They now read "GPU active render (the driver's own figure)" and
"GPU render (between the driver's start and end marks)", in English, Vietnamese and Japanese;
the guide says why. Strings only: the numbers and the means are unchanged.

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

* docs(handoff): D153 - of Reflex it is enough to tell whether a game has it: Reflex and PCL leave train D, D141's stop is unchanged

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

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 13:13:15 +00:00
poli0981andClaude Fable 5.2 dc329c09b4 docs: owner-only item 47 read; Streamline's Reflex and DLSS-RR guides read against the code (#461)
* docs: owner-only item 47 read (the Cyberpunk difference is the driver's; the holes are gone from steady play); Streamline's Reflex and DLSS-RR guides read against the code

Item 47, run by the owner on 0.1.0-beta.49 (sessions 236-245), read from a copy of the
ledger and the Overlay's logs: in Cyberpunk 2077 without frame generation the driver's
active GPU time is longer than its two marks are apart on 4 917 of 5 394 frames, and on
none of 129 900 frames in five other games; samples without a report are confined to a
game's start; off means off; D141's stop fired in a real game for the first time.

NVIDIA's Streamline guides for Reflex and DLSS Ray Reconstruction (2.14.16), read whole:
the guide's page on Advanced metrics now says what bUseGameSleep and bLowLatencyMode
mean; two design tables no longer promise PC latency (D147); spike-notes 30 has what the
guides add. Two comments (fl_shm.h, dllmain.cpp) said super resolution and ray
reconstruction run together - they do not; comments only, no object code changes.

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

* docs(handoff): item 47 (f) and (g) in the owner's words - the NVIDIA App's Low Latency Mode is off, no hitch

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

* docs(handoff): item 47 (f) as the owner showed it - the NVIDIA App's Low Latency Mode is off for Cyberpunk 2077, the game's own Reflex is on

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

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 12:55:35 +00:00
poli0981andClaude Fable 5.2 1a8a3cb713 docs(handoff): 0.1.0-beta.49's release facts - the tag's run, the digests, the delta, the wiki, the two rehearsals, what SonarCloud and Qodana said on the release's commit (#460)
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 11:32:35 +00:00
poli0981andClaude Fable 5.2 afe498452b release: 0.1.0-beta.49 - the latency report's frames counted for the log; a read a second on a grid; the Agent keeps the reading that waits (D148-D151); owner-only item 47 (#459)
* feat(overlay): the frames of NVIDIA's latency report are counted for the native log - each by its GPU span and the driver's active time, in batches that belong to one state of the sleep status (D148, D151; nothing published, no new call, no further member; in no release yet)

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

* test(guard): the log case's expected words are widened before they are multiplied (Qodana native: bugprone-implicit-widening-of-multiplication-result, two)

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

* fix(overlay): the watchdog's periodic tick is on a grid of one second, and a tick the loader woke no longer takes the driver read or publishes region 5 - a read a second whatever a tick's work took (D150, the Overlay's half; in no release yet)

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

* fix(agent): a reading that waits for a sample is no longer overwritten by the next one - two wait, the older is carried first; the guide says whose switches the latency table shows (D150, the Agent's half; D151)

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

* release: 0.1.0-beta.49 - item 46 read; the latency report's frames counted for the log, Reflex and frame generation together; a read a second on a grid; the Agent keeps the reading that waits (D148-D151); owner-only item 47

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

* test(guard): the measurement case prints the numbers it parsed, never a line of the log as it stands (SonarCloud cppsecurity:S5145)

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

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 17:42:58 +07:00
poli0981andClaude Fable 5.2 3838e26422 fix(agent): a reading that waits for a sample is no longer overwritten; the guide on whose switches the latency table shows (D150, D151) (#458)
* feat(overlay): the frames of NVIDIA's latency report are counted for the native log - each by its GPU span and the driver's active time, in batches that belong to one state of the sleep status (D148, D151; nothing published, no new call, no further member; in no release yet)

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

* test(guard): the log case's expected words are widened before they are multiplied (Qodana native: bugprone-implicit-widening-of-multiplication-result, two)

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

* fix(overlay): the watchdog's periodic tick is on a grid of one second, and a tick the loader woke no longer takes the driver read or publishes region 5 - a read a second whatever a tick's work took (D150, the Overlay's half; in no release yet)

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

* fix(agent): a reading that waits for a sample is no longer overwritten by the next one - two wait, the older is carried first; the guide says whose switches the latency table shows (D150, the Agent's half; D151)

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

* test(guard): the measurement case prints the numbers it parsed, never a line of the log as it stands (SonarCloud cppsecurity:S5145)

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

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 17:28:30 +07:00
poli0981andClaude Fable 5.2 f70a9153fa fix(overlay): the driver read is on a grid of one second; a tick the loader woke no longer takes it or publishes (D150, the Overlay's half) (#457)
* feat(overlay): the frames of NVIDIA's latency report are counted for the native log - each by its GPU span and the driver's active time, in batches that belong to one state of the sleep status (D148, D151; nothing published, no new call, no further member; in no release yet)

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

* test(guard): the log case's expected words are widened before they are multiplied (Qodana native: bugprone-implicit-widening-of-multiplication-result, two)

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

* fix(overlay): the watchdog's periodic tick is on a grid of one second, and a tick the loader woke no longer takes the driver read or publishes region 5 - a read a second whatever a tick's work took (D150, the Overlay's half; in no release yet)

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

* test(guard): the measurement case prints the numbers it parsed, never a line of the log as it stands (SonarCloud cppsecurity:S5145)

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

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 17:03:08 +07:00
poli0981andClaude Fable 5.2 4f02a17380 feat(overlay): the latency report's frames counted for the native log, by GPU span and active time, a batch per sleep-status state (D148, D151) (#456)
* feat(overlay): the frames of NVIDIA's latency report are counted for the native log - each by its GPU span and the driver's active time, in batches that belong to one state of the sleep status (D148, D151; nothing published, no new call, no further member; in no release yet)

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

* test(guard): the log case's expected words are widened before they are multiplied (Qodana native: bugprone-implicit-widening-of-multiplication-result, two)

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

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 16:14:48 +07:00
poli0981andClaude Fable 5.2 c97bf8bd98 docs(handoff): owner-only item 46 read - beta.48 on ten real sessions (#455)
* docs(handoff): owner-only item 46 read - ten sessions on beta.48: samples a second apart, both games gave the driver's own GPU times, the multipliers listed, off means off; active render longer than the span in Cyberpunk 2077 without frame generation, not explained

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

* docs(handoff): item 46 (g) - the owner's answer: no hitch with Advanced metrics on

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

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 07:36:55 +00:00
123 changed files with 9130 additions and 203 deletions

No files matched your search

+1 -1
View File
@@ -9,7 +9,7 @@ barrier. It is written for the person who has just met one; the details for deve
FrameLedger is a desktop program: its own window, its dialogs, its document windows, the icon by the clock and the
notices Windows shows for it. It draws nothing inside a game, so it cannot make a game itself any easier to use.
*Beta software: this page describes version 0.1.0-beta.48. In the app: Help ▸ Accessibility.*
*Beta software: this page describes version 0.1.0-beta.49. In the app: Help ▸ Accessibility.*
## What FrameLedger aims for
+64
View File
@@ -35,12 +35,76 @@ numeric core and does not move; the heading is the full version — corrected 20
## [Unreleased]
### Added
- **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**
(D154, the owner's decision). What a game sets and asks through Streamline's own functions for a feature — DLSS
frame generation's options and state, the video memory DLSS estimates for itself, the options of ray
reconstruction, Image Scaling and Dynamic Vibrance, the PC-latency markers — is reached only by handing the game
a function of FrameLedger's in place of Streamline's, which is refused. The *Sources* list says so, in English,
Vietnamese and Japanese, and the guide no longer says a later release reads more. Nothing that was read stops
being read.
- **The two lines of the graphics card's time say what each is, not which holds the other** (D152, the owner's
decision). *GPU active render (idle time excluded)* and *GPU render, start to end (idle time included)* are now
*GPU active render (the driver's own figure)* and *GPU render (between the driver's start and end marks)*, in
English, Vietnamese and Japanese, and the guide says why: in Cyberpunk 2077 without frame generation the
driver's active time is longer than its two marks are apart. The numbers are unchanged.
- **The guide's page on Advanced metrics says what two of the driver's switches mean** (`guide/12`): the latency
report is there in a game that has Reflex built in, whether Reflex is on or off in its menu; `bUseGameSleep`
says the game calls Reflex's sleep — NVIDIA asks for that even with Reflex off — and `bLowLatencyMode` is the
one that says the mode is on; frame generation needs Reflex, not the reverse. From NVIDIA's Streamline guide
for Reflex, and from the owner's ten sessions on 0.1.0-beta.49.
### Documentation
- **Owner-only item 47 was run and read** (`docs/HANDOFF.md`): in Cyberpunk 2077 without frame generation the
driver's active GPU time is longer than its own two marks are apart on 4 917 of 5 394 frames (1 849 µs beside
1 571 µs) and on none of 129 900 frames in five other games — the difference is the driver's; samples without a
report are now confined to a game's start; a session with the option off has no latency line; and the stop of
D141 fired in a real game for the first time (Kingdom Come: Deliverance II, one call of 5.3 ms while it
started).
- **Streamline's programming guides for Reflex and for DLSS Ray Reconstruction (2.14.16) read against the code**
(`docs/spike-notes/30-reflex-latency.md`, *Added 2026-11-14*). Ray reconstruction was already measured the way
the guide describes; two comments in the Overlay's source and one line of `17_HOOK_ENGINE` said super
resolution and ray reconstruction run together, and they do not. `03_METRICS` and `05_DETECTION` no longer
promise "PC latency as reported by Reflex" (D147). No code changed: comments only.
## Releases
Newest first. Each file holds that release's section exactly as it stood here.
| Version | Date | Notes |
|---|---|---|
| `0.1.0-beta.49` | 2026-11-14 | [`docs/changelog/0.1.0-beta.49.md`](docs/changelog/0.1.0-beta.49.md) |
| `0.1.0-beta.48` | 2026-11-14 | [`docs/changelog/0.1.0-beta.48.md`](docs/changelog/0.1.0-beta.48.md) |
| `0.1.0-beta.47` | 2026-11-14 | [`docs/changelog/0.1.0-beta.47.md`](docs/changelog/0.1.0-beta.47.md) |
| `0.1.0-beta.46` | 2026-11-13 | [`docs/changelog/0.1.0-beta.46.md`](docs/changelog/0.1.0-beta.46.md) |
+10 -1
View File
@@ -142,6 +142,11 @@ src/
# Since 0.1.0-beta.48 (D142-D144) also two figures the driver works out itself, of
# the same report - no further call: an entry of their own, nvapi.reflex.gpu_times,
# two adv.* series; and the table lists every frame-generation multiplier seen.
# Since 0.1.0-beta.49 (D148-D151) the Overlay also counts each frame of that report
# by its GPU span and the driver's active time - for its native log ONLY
# (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.
FrameLedger.Infrastructure/ # SQLite, shm reader, vendor APIs, injector interop, parsers,
# and Capture/ (PR-C): ShmRingAttacher/ShmCaptureSink over the
# reader, HeldProcessLivenessSource, TargetResolver (path only,
@@ -203,7 +208,11 @@ tools/ # accuracy-check, changelog-check, chokepoint-che
# the two on overlay-nvapi-allowed.txt),
# overlay-fields-check (D116, 2026-11-12: every member of a vendor's struct the
# Overlay reads for Advanced metrics is in fl_adv_fields.h and on
# overlay-allowed-fields.txt; a camera's position, axes and matrices nowhere)
# overlay-allowed-fields.txt; a camera's position, axes and matrices nowhere),
# input-readonly-check (D155-D163, 2026-11-14: every Windows function the input reader
# calls is declared in Infrastructure/Input/Win32Input.cs and on input-allowed-calls.txt;
# none sends to a device, injects input or reads a key; raw input is registered for
# joysticks and gamepads only; no native source names an input function)
# (six names added 2026-10-04)
# (PowerShell). This line used to name three, one of which
# — resx-audit — ~~does not exist~~ exists since 2026-09-13 with
+3 -2
View File
@@ -5,7 +5,7 @@ hooking on for — and reading the graphics calls the game makes. That is why it
resolution, the upscaler, frame generation and ray tracing apart. It is also where its limits come from. This
page lists them in plain words; each item links to the document that has the details.
*Beta software: this page describes version 0.1.0-beta.48.*
*Beta software: this page describes version 0.1.0-beta.49.*
## Games it will not measure
@@ -131,7 +131,8 @@ shown is recorded too, from outside the game. ([Capture](docs/04_CAPTURE.md))
second. They are the driver's numbers, not FrameLedger's measurement. **The stages overlap and do not add up to
the total**, and the graphics card's stage includes the time the card waited — in one game it is longer than the
whole frame; the driver's own figure for the card's active time is shown beside it where the driver gives one.
One point is one reading; with the sensor interval set above one second, some readings are not stored.
One point is one reading, drawn at the sample that carried it — up to a second after it was taken; with the
sensor interval set above one second, some readings are not stored.
FrameLedger asks the driver for them from inside the game; a read that is slow or faults is switched off until the game is closed, and the session says so.
([Advanced metrics](guide/12-advanced-metrics.md))
+2 -2
View File
@@ -13,7 +13,7 @@ app too (Help ▸ User guide, Help ▸ Limitations, Help ▸ Accessibility), and
<!-- accuracy-block:begin -->
> ⚠ **What FrameLedger actually measures today — 2026-11-11.** The software is a beta; its latest
> **beta is `0.1.0-beta.48`** (2026-11-14), an unsigned installer built from that tag with its
> **beta is `0.1.0-beta.49`** (2026-11-14), an unsigned installer built from that tag with its
> checksums published beside it (alphas — experimental builds that try a newer .NET — are published apart). The source holds the desktop app
> (library, store import, charts, settings) and the background Agent, which records a session when a
> game in the library runs (unless you switched its recording off), injects only into games you enabled
@@ -215,7 +215,7 @@ Elevation is **optional — for everything.** Hooked capture is the normal path
## Install
> **The latest beta is `v0.1.0-beta.48` (2026-11-14); before it `v0.1.0-beta.47` (2026-11-14), `v0.1.0-beta.46` (2026-11-13), `v0.1.0-beta.45` (2026-11-12), `v0.1.0-beta.44` (2026-11-12), `v0.1.0-beta.43` (2026-11-12), `v0.1.0-beta.42` (2026-11-12), `v0.1.0-beta.41` (2026-11-12), `v0.1.0-beta.40` (2026-11-12), `v0.1.0-beta.39` (2026-11-11), `v0.1.0-beta.38` (2026-11-11), `v0.1.0-beta.37` (2026-11-11), `v0.1.0-beta.36` (2026-11-10), `v0.1.0-beta.35` (2026-11-09), `v0.1.0-beta.34` (2026-11-06), `v0.1.0-beta.33` (2026-11-03), `v0.1.0-beta.32` (2026-10-31), `v0.1.0-beta.31` (2026-10-26), `v0.1.0-beta.30` (2026-10-26), `v0.1.0-beta.29` (2026-10-25), `v0.1.0-beta.28` (2026-10-20), `v0.1.0-beta.27` (2026-10-20), `v0.1.0-beta.26` (2026-10-19), `v0.1.0-beta.25` (2026-10-19), `v0.1.0-beta.24` (2026-10-19), `v0.1.0-beta.23` (2026-10-14), `v0.1.0-beta.22` (2026-10-13), `v0.1.0-beta.21` (2026-10-13), `v0.1.0-beta.20` (2026-10-12), `v0.1.0-beta.19` (2026-10-12), `v0.1.0-beta.18` (2026-10-07), `v0.1.0-beta.17` (2026-10-07), `v0.1.0-beta.16` (2026-10-06), `v0.1.0-beta.15` (2026-10-06), `v0.1.0-beta.14` (2026-10-06), `v0.1.0-beta.13` (2026-10-04), `v0.1.0-beta.12` (2026-10-04), `v0.1.0-beta.11` (2026-10-03), `v0.1.0-beta.10` (2026-09-28), `v0.1.0-beta.9` (2026-09-26), `v0.1.0-beta.8` (2026-09-25), `v0.1.0-beta.7` (2026-09-23), `v0.1.0-beta.6` (2026-09-23), `v0.1.0-beta.5` (2026-09-22), `v0.1.0-beta.4` (2026-09-21), `v0.1.0-beta.3` (2026-09-21), `v0.1.0-beta.2` (2026-09-17) and `v0.1.0-beta.1` (2026-09-16).** They are pre-releases: read the notes of the one you install — `CHANGELOG.md` links each release's own file under `docs/changelog/` — for what it measures, what it does not yet, and how to update, before installing. A source build is `docs/12_BUILD.md`.
> **The latest beta is `v0.1.0-beta.49` (2026-11-14); before it `v0.1.0-beta.48` (2026-11-14), `v0.1.0-beta.47` (2026-11-14), `v0.1.0-beta.46` (2026-11-13), `v0.1.0-beta.45` (2026-11-12), `v0.1.0-beta.44` (2026-11-12), `v0.1.0-beta.43` (2026-11-12), `v0.1.0-beta.42` (2026-11-12), `v0.1.0-beta.41` (2026-11-12), `v0.1.0-beta.40` (2026-11-12), `v0.1.0-beta.39` (2026-11-11), `v0.1.0-beta.38` (2026-11-11), `v0.1.0-beta.37` (2026-11-11), `v0.1.0-beta.36` (2026-11-10), `v0.1.0-beta.35` (2026-11-09), `v0.1.0-beta.34` (2026-11-06), `v0.1.0-beta.33` (2026-11-03), `v0.1.0-beta.32` (2026-10-31), `v0.1.0-beta.31` (2026-10-26), `v0.1.0-beta.30` (2026-10-26), `v0.1.0-beta.29` (2026-10-25), `v0.1.0-beta.28` (2026-10-20), `v0.1.0-beta.27` (2026-10-20), `v0.1.0-beta.26` (2026-10-19), `v0.1.0-beta.25` (2026-10-19), `v0.1.0-beta.24` (2026-10-19), `v0.1.0-beta.23` (2026-10-14), `v0.1.0-beta.22` (2026-10-13), `v0.1.0-beta.21` (2026-10-13), `v0.1.0-beta.20` (2026-10-12), `v0.1.0-beta.19` (2026-10-12), `v0.1.0-beta.18` (2026-10-07), `v0.1.0-beta.17` (2026-10-07), `v0.1.0-beta.16` (2026-10-06), `v0.1.0-beta.15` (2026-10-06), `v0.1.0-beta.14` (2026-10-06), `v0.1.0-beta.13` (2026-10-04), `v0.1.0-beta.12` (2026-10-04), `v0.1.0-beta.11` (2026-10-03), `v0.1.0-beta.10` (2026-09-28), `v0.1.0-beta.9` (2026-09-26), `v0.1.0-beta.8` (2026-09-25), `v0.1.0-beta.7` (2026-09-23), `v0.1.0-beta.6` (2026-09-23), `v0.1.0-beta.5` (2026-09-22), `v0.1.0-beta.4` (2026-09-21), `v0.1.0-beta.3` (2026-09-21), `v0.1.0-beta.2` (2026-09-17) and `v0.1.0-beta.1` (2026-09-16).** They are pre-releases: read the notes of the one you install — `CHANGELOG.md` links each release's own file under `docs/changelog/` — for what it measures, what it does not yet, and how to update, before installing. A source build is `docs/12_BUILD.md`.
1. Download the latest `FrameLedger.App-win-Setup.exe` from [Releases](https://github.com/poli0981/frameledger/releases). It installs into `%LOCALAPPDATA%\FrameLedger.App`; your data stays in `%LOCALAPPDATA%\FrameLedger`, and uninstalling asks before touching it.
2. SmartScreen may warn — releases are not code-signed (free, open-source project). Verify the SHA-256 checksum published with each release, then **More info → Run anyway**.
+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 }
+55 -1
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
@@ -1019,7 +1073,7 @@ processor's, not the whole PC's — averaged over the session's sensor ticks. `D
| RT active | measured per frame | not available |
| Path tracing | heuristic, confidence-scored, never asserted | not available |
| ~~Per-process VRAM~~ Game process memory (beta.12) | ~~exact~~ dedicated / shared GPU memory as Task Manager counts it — a known 512 MiB allocation read +512.0 MiB (`spike-notes` §16); private working set equal to Windows' own counter; read from outside the game | ~~not available~~ the same, from outside; an unpinned hold sums the executable's processes |
| PC latency | as reported by Reflex | not available |
| PC latency | ~~as reported by Reflex~~ **not available** (D147, *corrected 2026-11-14*): the driver's report ends at the end of the GPU's work, not at the display. The stages it does give are Advanced metrics — the driver's numbers, unchecked | not available |
| Display mode (beta.10) | per 100 ms sample: exclusive fullscreen as the swap chain answers it (DXGI; OpenGL and Vulkan cannot say), borderless, windowed, minimised; the window's size from user32 | per 1 s sample, from the window alone: windowed, minimised, or *fullscreen or borderless* — never split |
| GPU temp / load / power | vendor API accuracy, ±1 s sampling | same |
| GPU clocks / fan / memory temperature (beta.14) | vendor API accuracy, ±1 s sampling | same |
+2 -2
View File
@@ -22,8 +22,8 @@ Derived in the Agent from the record stream; the mapping is in `03_METRICS`. Sum
| Render resolution vs output resolution (incl. mid-session changes) | upscaler parameter reads + `ResizeBuffers` |
| Frame Generation mode + factor | NGX/SL/FFX FG feature evaluation, then cadence — **Tier 1 only**. ~~then (Tier 2 only) PresentMon `FrameType`~~ retired (§S31 row P2), and Tier 2 no longer produces frames to run cadence over either |
| Ray Tracing active | AS builds + `DispatchRays` (both, to catch inline RayQuery) |
| Ray Reconstruction | NGX `RayReconstruction` feature evaluated |
| Reflex on + PC latency | NVAPI Reflex hooks |
| Ray Reconstruction | ~~NGX `RayReconstruction` feature evaluated~~ Streamline's `slEvaluateFeature(kFeatureDLSS_RR)` — it runs **instead of** super resolution, in DLSS's own quality mode (Streamline's guide; measured 2026-08-15), so the upscaler is DLSS and this is a yes/no beside it. A game that calls NGX directly reads N/A (`03_METRICS` §RT/PT/RR) *(corrected 2026-11-14)* |
| ~~Reflex on + PC latency~~ The driver's latency report and sleep status (0.1.0-beta.47, Advanced metrics only) | ~~NVAPI Reflex hooks~~ two read-only getters of the driver, called by the Overlay (`17_HOOK_ENGINE` §Calls the Overlay makes into a driver). **PC latency — input to display — is not read** (D147): the report ends where the GPU's work ends, and NVIDIA's own figure is taken from outside the game (`spike-notes` §30, route E) *(corrected 2026-11-14)* |
| Per-process VRAM | `QueryVideoMemoryInfo` |
| PSO compilation events | pipeline-creation hooks |
| Display mode — exclusive fullscreen / borderless / windowed / minimised, with the window, back buffer and monitor (beta.10) | `GetFullscreenState` + `GetDesc` polled on the presenting chain (≤ 2 Hz, shared-memory region 4), and the window's geometry read by the Agent **out of process** — so this row is **both tiers**: a Tier-2 session has the window alone, and never splits exclusive from borderless (`03_METRICS` §Display mode) |
+62 -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.
@@ -496,6 +520,11 @@ Because Tier-1 and Tier-2 sessions carry different fields, every query that comp
> Sensor series are aligned to `t_ms` (milliseconds from `qpc_epoch`) and a tick with no reading is stored as
> **−1** — never 0, which would be a reading — because temperatures, loads, power and memory are never negative.
>
> **A reading taken inside a game stands at the sample that carried it** (0.1.0-beta.49, owner decision D150): the
> Overlay publishes about once a second and the Agent samples exactly once a second, so a publication waits for
> the next sample — two may wait, the older is carried first (`PendingInGameReadings`). An `adv.*` point that
> came from a game can therefore stand up to a second after its read; a tick with nothing waiting is NaN.
>
> **`t_ms` is the time axis; `hz` is the fallback** (written here 2026-11-14, owner decision D146 — the code cited
> this rule before the page had it). Every series of a session is stored beside `t_ms`, which carries each
> sample's own time, and the App draws against it; `hz` is read only for a row that has no `t_ms`
@@ -523,6 +552,15 @@ Because Tier-1 and Tier-2 sessions carry different fields, every query that comp
> (`AdvancedSessionBuilder.MaxSeries`); what is beyond is counted in its directory, not stored.
> **Size, measured 2026-11-11** on values shaped like the dev box's reader (17 series with a reading every tick, 41
> with one every fifth): one hour is 816 KiB raw and **189 KiB stored** — well inside NFR-5's 3 MB an hour.
>
> **The input series follow the same rule under their own name (schema 0024, owner decisions D155–D163).** A series
> whose name starts with `input.` stores NaN for a tick with nothing to say — the game was not in front, the
> controller was not connected, the tick carried no reading — through the same sparse encoder. `FindSensorsAsync`
> leaves them out as well (`series NOT LIKE 'input.%'`): a class's number is not a sensor's value, and the sensors'
> statistics and chart would take it for one. `FindInputSensorsAsync` returns them with `t_ms` first. A session
> stores `input.class` and, for each of its first eight controllers (`InputSessionBuilder.MaxDevices`),
> `input.dev.N.active` and — where the battery has a level — `input.dev.N.battery`: at most seventeen, a few KiB an
> hour stored.
## The `.partial` file
@@ -547,6 +585,7 @@ Because Tier-1 and Tier-2 sessions carry different fields, every query that comp
> | 8 `SensorsWide` | the same samples under a 32-bit presence mask that carries the game process's memory (D43) | each flush, since beta.12 *(row added 2026-10-04)* |
> | 9 `SensorsAdvanced` | the advanced readings of the samples of the type-8 chunk before it (D101): `u16` names, then per name `u16` bytes and UTF-8; `u32` samples, then per sample `i64` QPC, `u16` readings and per reading `u16` name, `f64` value. Each chunk carries its own names, so it reads without any earlier chunk | each flush **in which a sample carries any** — with Advanced metrics off, never; the file is then byte for byte what it was (2026-11-11) |
> | 10 `AdvancedContext` | UTF-8 JSON (`AdvancedJson.OfContext`): the PC's facts, the session's, its series' directory, each source's state; the last one wins | the first flush after the recorder set it, and again only when it changed (2026-11-11) |
> | 11 `SensorsInput` | the input readings of the samples of the type-8 chunk before it (D155–D163, `InputSampleCodec`): `u32` samples, then per sample `i64` QPC, seven `i32` (span, observed, in front, controller, keyboard and mouse, both, no input), `u8` flags, the reader's health (`u8` answers, six `i64` counts, `i32` faults), `u8` controllers and 23 bytes a controller — what it is (maker, the two USB ids, connection, XInput pad) and its part of the tick (connected, time in use, battery, connections, drops). Each sample describes every controller it counts, so a chunk reads without any earlier one | each flush **in which a sample carries one** — with the option off, never; the file is then byte for byte what it was (2026-11-14) |
>
> **A chunk of a type the reader does not know is skipped, not the end of the file (owner decision D106,
> 2026-11-11).** Its length and checksum have been verified by then, so it is a whole chunk a newer build wrote.
@@ -797,6 +836,28 @@ Sequential embedded SQL (`Migrations/0001_init.sql`, `0002_*.sql`, …), applied
> **Nothing produces a row yet**: the option that switches the reader on is the next pull request's.
> **A beta.38 cannot open a ledger a later build migrated.**
> **`0024_input_devices.sql` (0.1.0-beta.50, 2026-11-14, owner decisions D155–D163) — what a session was played
> with, and what a store lists.** ADD COLUMN only, twelve columns. **Nine on `sessions`**: `input_observed_ms`,
> `input_foreground_ms` and the four classes that add up to it (`input_controller_ms`, `input_km_ms`,
> `input_both_ms`, `input_idle_ms`), `input_method_switches`, `input_source`, and `input_devices` — the session's
> controllers as `Application.Recording.InputDevicesRecord`'s JSON (`03_METRICS` §Input). **On `sessions` and not in
> a table of their own, on purpose** (D160) — the opposite of 0023's choice, for the opposite reason: the trend and
> the comparison read a session's row, and these numbers are meant to be in the JSON export and the bug bundle,
> which carry the whole row; the Privacy Policy's §3A says so. What may never be a column or a key of that JSON: a
> controller's serial number, its Bluetooth address, its device path
> (`LedgerDatabaseTests.ScriptTwentyFourOnlyAddsColumnsAndNamesNoIdentifier`,
> `InputSessionBuilderTests.TheStoredJsonHasNoKeyThatCouldCarryASerialNumberAnAddressOrAPath`). **Three on
> `games`**: `controller_support` (`full`, `partial`, or `none` for a game the store knows and lists no support
> for), `controller_support_source` (`steam-appinfo`) and `controller_support_at` — the store's own word, from its
> file on the disk, never a verdict of FrameLedger's (D163). Written by `SessionFinalizer.Build` from the session's
> samples, before the tier branch — both tiers, and a session recovered from its crash file, which carries the
> readings in chunk 11. NULL before; with the option off; before the terms that describe the reading were accepted
> (D156); on a game no store file describes. The series are `sensor_blobs` rows named `input.*` (§Blob encoding).
> `LatestVersion` is 24; `LedgerDatabaseTests.ScriptTwentyFourAddsTheInputColumnsAndAnEarlierSessionAndGameHaveNone`,
> the repository round trip. **Nothing produces a reading yet, and nothing writes the three `games` columns yet**:
> the reader, the switch and the store file are the pull requests after this one.
> **A beta.49 cannot open a ledger a later build migrated.**
> **`0022_dlss_nr.sql` (beta.34, 2026-11-06, owner decision D84) — DLSS 5's neural rendering, measured.** One REAL column,
> ADD COLUMN only: `dlss_nr_pct`, the share (0–100) of the presents that drained a Streamline evaluation on which the game
> evaluated `kFeatureDLSS_NR` (`Domain.Metrics.NeuralRendering`). Written by the recorder's aggregation
+21 -2
View File
@@ -117,8 +117,27 @@ What the region is, as a contract between the two sides:
(`FlAdvancedState.request`, the word that was `reserved0`). The reader returns only a publication that names the
value it wrote: what a second session of the same game finds in the region before the first tick is the first
session's, and is not read. After an "off" the region keeps its last publication, untouched.
- **One writer, once a second.** The detours keep process-local accumulators; the watchdog copies them here at its
tick. No game thread writes the region, so the seqlock has a single writer: `seq` odd, the fields, `seq` even.
- **One writer, once a second — on a grid since 0.1.0-beta.49 (owner decision D150).** The detours keep
process-local accumulators; the watchdog copies them here at its **periodic** tick, one a second by the
performance counter (`fl_watchdog_tick.h`). Until then it published at *every* tick, and a tick was a second
and its own work after the one before — or at once, whenever the LoadLibrary detour woke the thread. So a
session's publications fell behind the Agent's samples a little with every tick, and a woken tick's publication
took the driver read with it and armed none: the publication after it was empty (0.4 to 16 % of a session's
samples carried no report, HANDOFF item 46; under a loader that never stops, 35 720 publications in eight
seconds and nine reads). A tick woken early still follows the request, installs and takes the census; it writes
nothing here. **A request first seen on a woken tick is published by the periodic tick that follows, however
soon that is**: a session's first publication may hold a moment's worth — one dispatch of a range that has two
ends — and every one after it a second's. A reader takes ranges and "seen" words as *since the request*, which
they are, and never reads a single publication as complete. No game thread writes the region, so the seqlock has a single writer: `seq` odd, the fields,
`seq` even.
- **A publication waits for a sample, and is not replaced while it waits** (0.1.0-beta.49, owner decision D150;
the Agent's half). `SessionRecorder` looks at the region and at the telemetry poller about ten times a second
and attaches a publication's readings to the newest sample it drains. It used to keep one set and overwrite it:
a publication that landed just after a sample left that sample without a report, and at the next change of
step the set that had waited was overwritten — one sample in five for minutes in the owner's session 223. Two
sets now wait, the older is carried first (`PendingInGameReadings`): a session lacks a report at one sample at
most when the two fall out of step, and loses no reading after it. With the sensor interval above a second
more publications arrive than samples and the oldest is pushed out, as before.
- **The reader keeps its last consistent copy** (`ShmRingReader.AdvancedState`): null until something was published
for its request;
the same copy while `seq` has not moved, without copying 1472 bytes again; and that copy still when the writer is
+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)
+12 -1
View File
@@ -174,7 +174,18 @@ others cannot say.** `fl_reflex_summary` (Catch2) drives `fl_adv_fields.h`'s rea
two newest frames held back, a frame summed once, a span the driver did not report, a span no frame can have, frame
ids that start again, and the ten words of a publication — and since 0.1.0-beta.48 the driver's two own times
(summed over the frames that gave one, each with its own count; zero and more than a second are not counted and
refuse nothing) and the bit a multiplier has. `fl_guard`'s seven `[latency]` cases inject the Overlay
refuse nothing) and the bit a multiplier has — and since 0.1.0-beta.49 the counts for the native log: every place
a summed frame can be in, a span of a microsecond, an active time as long as the span, a refused frame, when a
batch is due, a batch closed by a change of state and the thirty-two such closings a request has, the six lines
and what each carries; a hidden `[.bench]` case is the measurement of one report's cost. `fl_watchdog_tick`
(Catch2, no thread and no clock) drives the grid the watchdog's periodic tick is on: sixty ticks each late and
each followed by work keep whole seconds, a wait is never rounded down, a tick woken early is not periodic and
moves nothing, a late tick is not followed by another within half a period. `fl_guard`'s nine `[latency]` cases
(the eighth reads the log: the first batch after ten reads, by number, and what is left when a flush is asked for
— against the stand-in's `kModeGpuShapes`; the ninth keeps the loader waking the watchdog without pause — a
thread that asks for `opengl32.dll` for as long as the target lives — and holds one publication a second, each
with a read, none within half a second of another: 35 720 publications in eight seconds on the code before it; a
hidden `[.measure]` case prints ninety reads' own lines) inject the Overlay
into a Direct3D 12 target that has loaded a stand-in `nvapi64.dll`, and read that module's call counts from outside
through its named section (`fl_stub_nvapi_shared.h`) — so "the driver was not called" is a count: not asked → not
even asked for the addresses; asked → about one read a second, sums equal to the stand-in's, every counted read a
+44
View File
@@ -332,6 +332,50 @@ CI/CD with the native build (`release.yml` exists since P4 PR-5, 2026-09-14 —
**Total ≈ 5.5–6.5 weeks full-time** — roughly 1.5–2 weeks more than the ETW design, which is the honest price of the accuracy.
## After the controller train — the owner's order (2026-11-14)
Advanced metrics is closed (D154) and the controller feature is being built as 0.1.0-beta.50's train. Asked what
comes after, the owner was shown six directions and chose four of them, and added distribution. **This is the
order of work after the controller train; each begins with a plan of its own and the owner's approval.** Nothing
here is designed yet, and what is marked *to verify* is a lead, not a finding.
1. **Time actually played (AFK segmentation).** The v2 backlog's "AFK segmentation via `GetLastInputInfo`", moved
up: the controller train already stores when the keyboard, the mouse or a controller was in use, so the time
nobody was at the game can be told apart and left out of a session's averages. Timestamps of activity only —
never a key, as that train's Privacy text says.
2. **More from what is already stored — interface only, no hook.** The comparison of two stretches of one
session ("before and after I changed DLSS Quality to Balanced", v1.1 below), and a timeline for a game that
marks where the driver, the game's build or the settings changed, so a drop in frame rate has a date. *To
verify*: which of those changes the ledger already records for every session.
3. **Stutter from shader compilation (PSO).** `03_METRICS` defines *PSO stutter %* and `05_DETECTION` says no
writer exists. New hooks at pipeline creation: staged like Advanced metrics' train B — small releases, the
overhead measured, the owner's real games between them, never first on a game inside the user-mode
exception's trial (D38).
4. **The in-game overlay (FR-15).** v1.1's first line below: live frame rate, frame time, upscaler and
ray-tracing state drawn in the game, per game, off by default. The largest and the riskiest of the four — it
draws in the game's process — so it comes last, with a risk review of its own (rule 5, and what an
anti-cheat makes of a drawing module).
5. **Distribution: winget and the Microsoft Store.** The owner uploads to the Store and fills in its listing by
hand. FrameLedger has no product in Partner Center yet — the one there today is another program of the
owner's — so which type it is submitted as (*EXE or MSI app*, or *MSIX or PWA app*) is part of what the plan
settles. The repository's part is what the two channels need from a release. *To verify, before anything is promised*:
- whether the Store accepts an **unsigned** installer for an *EXE or MSI app* — the installer is unsigned
today (`CLAUDE.md`, Packaging), and if the Store wants a certificate that is a cost and a decision of the
owner's; whether an MSIX package is a real alternative for a program that loads a library into games and
registers a Vulkan layer;
- the installer's silent switch and a versioned, permanent download address for each release, which both
channels ask for; whether either takes a pre-release version;
- who updates an installation that came from winget or the Store — the App's own updater (Velopack) or the
channel — and that the two cannot fight;
- a winget manifest per release (address, SHA-256, switches) and whether `release.yml` writes it or the owner
submits it;
- rule 8 is untouched: a channel that delivers the installer is not a network call of the App's.
**Not chosen, and not refused**: a stabilising pass with a cross-check against another tool (the limits page
still says no reading has been checked against one), and export for CapFrameX and for video overlays. Two things
only the owner can settle stay open beside them: what leaving beta takes, and code signing — which direction 5
may force.
## v1.1 — earned features (only after the data path is stable)
- **In-game overlay** (FR-15): we are already in the process; draw live FPS/frametime/upscaler/RT state. Opt-in per game, off by default. Borderless and fullscreen-flip both handled since we own the swapchain.
+50 -3
View File
@@ -215,6 +215,33 @@ Overlay's flags, a report of 62 summed frames, 2 million reports × 3, twice): 3
— **+36 ns a read**, once a second, and after the call's time has been taken, so it cannot reach the 2 ms latch.
The present path is unchanged: one relaxed load.
**Since 0.1.0-beta.49 each summed frame is also counted for the native log** (owner decisions D148, D151;
§Native logging, `LATENCY_FRAMES`). The owner's ten sessions on beta.48 (HANDOFF, item 46) gave both of the
driver's own times in every frame report of both games — and in Cyberpunk 2077 without frame generation the mean
active time was **longer** than the mean span between the two GPU marks (3.17 against 2.79 ms), which the two
means cannot explain: the span's is over every summed frame, one of no length included, the active time's over
the frames that gave one. So the reader places each summed frame by its own two numbers (`CountGpuTimes`), after
the frame is accepted: which frames are summed does not change, and the seven spans, the two times and their
counts are what they were. **No new call, no further member of the report** — the two GPU marks and
`gpuActiveRenderTimeUs` were read already — and nothing of it leaves the process: the watchdog adds each read's
counts to a batch and writes the batch to the log. **Measured** (the same instrument: 2 million reports × 3,
twice): 424–435 ns before, 490–499 ns after — **+65 ns a read**, once a second, after the call's time has been
taken. `fl_reflex_summary_test "[.bench]"` is that measurement in the tree. The present path is unchanged.
**Since 0.1.0-beta.49 the read is on a grid of one second** (owner decision D150; `fl_watchdog_tick.h`). The
watchdog used to wait a second *after* each tick's work, and a tick the LoadLibrary detour woke was a tick like
any other: it took what the last read left, published it and — less than a second having passed since the last
arm — armed nothing, so the next publication carried no read. The Agent samples on a period of exactly one second
since 0.1.0-beta.48, and its sessions showed the holes: 0.4 to 16 % of a session's samples without a report
(HANDOFF, item 46). Now the watchdog's **periodic** tick is due at a deadline by the performance counter, and the
next deadline is one period after the one that was due, not after the moment the tick ran; a tick woken early
does everything it did — the request is followed and the hooks a session asks for go in at once — **except take
the driver read and publish region 5**, which are the periodic tick's. One read is armed at every periodic tick
(`g_latArmedQpc` and its "a second since the last arm" are gone). A periodic tick that ran more than half a
second late is not followed by another on the grid's next mark: the grid starts again from it, so **two reads are
never less than half a second apart** — "about once a second" still, and no longer "at most". Nothing on a game
thread changed: the presenting thread makes the read when it finds the gate armed, as before. **Measured** on `hook-harness` with the stand-in module, by the batches' own lines (`fl_guard_test "[.measure]"`): ten reads in 9 996 ms, the next twenty in 20 002, the next sixty in 59 997, each batch with as many periodic ticks as reads; and with a thread asking the loader for a module without pause — 18 240, 36 427 and 143 424 early wakes in the three batches — 9 997, 20 000 and 59 999 ms for the same reads. On the code before it the second case published 35 720 times in eight seconds, with nine reads. **Not measured in a game**, and not the whole of the holes: the Agent overwrote a reading that waited for a sample, which is its own change (`07_IPC` §Region 5).
**The gate.** One word, four states — idle, armed, reading, off (`dllmain.cpp`, above `ReadLatencyOnce`). Only the
watchdog arms; a presenting thread takes *armed* to *reading* by compare-exchange and owns the 15.4 KB report
buffer (static storage, never a game thread's stack) and the read's result until it stores *idle* or *off*; the
@@ -630,9 +657,11 @@ static_assert(sizeof(FlFrameRecord) == 64);
> v3 makes it safe by CONSTRUCTION. Every enum's 0 is now `NOT_REPORTED`, and
> `rtFlags`' polarity is flipped so its bits mean *observed*.
>
> Four answers items 4/6/7 owe had no home and now do: DLSS-SR **and** Ray
> Reconstruction concurrently (`featureFlags`, since RR was a mutually exclusive
> `upscaler` value), `upscalerSharpness`, and — in `FlWriterState`, because they
> Four answers items 4/6/7 owe had no home and now do: DLSS **with** Ray
> Reconstruction (`featureFlags`, since RR was a mutually exclusive
> `upscaler` value — *corrected 2026-11-14: this said "DLSS-SR and Ray
> Reconstruction concurrently"; RR runs instead of super resolution, it is still
> DLSS*), `upscalerSharpness`, and — in `FlWriterState`, because they
> are session facts and not per-frame — the device **RT tier** without which
> `03_METRICS`' definite RT `No` had no producer at all, plus `rtStateObjectsCreated`
> and `rasterPsoCreated`.
@@ -932,6 +961,24 @@ No logging in hook bodies. A small fixed-size in-memory ring of structured event
> `FlLatencyState`, the text what it means — and, when the module is found, two more with the end of the path
> `nvapi64.dll` was loaded from and of the image its getters are in. Written by the watchdog; a fault in a getter
> is a `FAULT` line from the presenting thread, as any fault is.
> **`LATENCY_FRAMES` (0.1.0-beta.49, owner decisions D148, D151)**: the frames the driver reads summed, counted
> for this log and nowhere else — nothing of it is published, stored or shown. Each summed frame is placed by its
> own two numbers, the span between its two GPU marks and the driver's active render time: no start mark, a span
> of no length, an active time with no span, a span with no active time, and — where a frame has both — *active
> longer than the span* or *active within the span*, each with its count and both sums in microseconds. No
> threshold: a span of one microsecond is a span. **A batch is seven lines and belongs to one state of the driver's
> sleep status** — its low-latency switch, its "the game sleeps" switch and its frame-generation multiplier —
> because the counts mean nothing apart from it: a read in another state closes the batch first (thirty-two such
> closings a request, after which a batch runs to its length and its first line says what it held). A batch is
> also written after a request's tenth read, its thirtieth and every sixtieth from there, when the Agent asks for
> a flush, at a new request and at a stop. `a` is printed in decimal and `b` in hex: *reads* and the switches
> seen on, off (`<<8`) and the multipliers seen (`<<16`); *frames summed* and refused; *GPU span absent* and of no
> length; *active time with no span* and span with no active time; then the two heaps, `a` their frames and `b`
> their span sum (`<<32`) and active sum; and the watchdog's own line — the *milliseconds the batch spans* and its
> ticks in them, on time (`<<32`) and woken early: a read a second is a thousand milliseconds a read and as many
> periodic ticks as reads (D150). **A game that exits by itself takes the batch in hand with it** — under a
> minute of reads. About seven lines a minute while a session with *Advanced metrics* reads the driver; none
> otherwise.
> **Three flush points — four since beta.42, the same note —, none on a present path:** the end of `InitThread` (so the
> file exists from the start of the session and a crash mid-session still leaves it), the watchdog when
> `FlControlBlock.logFlushRequested` changes (a counter the Agent bumps at session end; nothing clears it),
+18 -14
View File
@@ -724,7 +724,7 @@ Rules 4 and 5, the hook inventory, the measured overhead and the anti-cheat guar
every hook. `sl::Constants` is read without its camera position, axes and matrices: where the camera is, is where the
player is (rule 4). NGX stays closed by its licence (`17_HOOK_ENGINE` §NGX).
**Train D re-examines a refusal; it does not lift it.** `handoff/history/p0-queue-1-6.md` refused, on five grounds,
**Closed 2026-11-14 (owner decision D154): train D is not built, and the refusal stands.** The ten entries it would have read — what a game sets and asks through Streamline's feature functions — have reach `RefusedRoute`: seeing those calls takes handing the game a function of FrameLedger's in place of Streamline's, and a game that fetched its functions before the attach would never call it. What follows is the plan as it stood. **Train D re-examines a refusal; it does not lift it.** `handoff/history/p0-queue-1-6.md` refused, on five grounds,
hooking `slGetFeatureFunction` and patching the function it returns. The route to try is a different one:
`slGetFeatureFunction` is itself an export (`vendor-exports.json`), so its hook is an ordinary inventory row, and
what it hands back could be a wrapper for a fixed list of names instead of a patch at an address learned at run time
@@ -910,7 +910,7 @@ the catalog differ in either direction. **Reach** is where a value can be read f
FrameLedger measures, from the arguments of a call the Overlay hooks, while the session records Advanced metrics —
since 0.1.0-beta.40), `HookedCall` (an argument of a call the Overlay already hooks, not read yet), `NewHook` (a hook
that is not built — Train B; no entry carries it since 0.1.0-beta.45), `BeforeAttach` (a call the game makes once,
before FrameLedger is inside it, so no hook could read it — D129), `Spike` (Trains C and D), `Refused`, `Deferred`, `Identifier` (D104), `PlayerState`
before FrameLedger is inside it, so no hook could read it — D129), `Spike` (Trains C and D; no entry since D154), `Refused`, `Deferred`, `Identifier` (D104), `PlayerState`
(rule 4), `Licence`, `NotInHeaders`. ~~Only the first two are read by a build of Train A.~~ The first three are read
(`AdvancedMetric.IsRead`).
@@ -1099,7 +1099,11 @@ session that ended in a menu read 1). **Since 0.1.0-beta.48 (D142) two more seri
`adv.nvapi.reflex.gpu_times.` and `active_render`, `frame_time` — the driver's `gpuActiveRenderTimeUs` and
`gpuFrameTimeUs`, each the mean over the frames of that read that gave one. They are the driver's own figures, not
spans between two of its marks: in Phantom Blade Zero `gpu_render` (the two GPU marks, idle time included) was
longer than `total`, which is why its label now says what it includes (D143). An entry of their own keeps the
longer than `total`, which is why its label now says what it includes (D143). **Reworded 2026-11-14 (D152)**:
NVIDIA's header defines the active time as that span "excluding the idles in between", and in Cyberpunk 2077
without frame generation the active time is the longer of the two on nine frames in ten (HANDOFF, item 47) — so
the labels now say what each is (*the driver's own figure*; *between the driver's start and end marks*) and no
longer that one is the other less its idle time. The numbers and the means are unchanged. An entry of their own keeps the
seven spans within what one chart draws as lines. What the *game* asked of Reflex (`nvapi.reflex.mode`) is an argument of a function no module exports:
reading it takes a patch at an address learned at run time, which is refused.
@@ -1110,21 +1114,21 @@ reading it takes a patch at an address learned at run time, which is refused.
| `nvapi.reflex.frame_report` | Latency per frame: simulation, render submit, present, driver, OS queue, GPU render | Series, one per device | Nvapi | GameDriver | Microseconds |
| `nvapi.reflex.gpu_times` | The graphics card's time per frame, as the driver works it out: active render, frame to frame | Series, one per device | Nvapi | GameDriver | Microseconds |
**Inside the game: routes a spike decides**
**Inside the game: Streamline's feature functions — not read (D154, 2026-11-14)**
| Id | What it is | Scope | Source | Reach | Unit |
|---|---|---|---|---|---|
| `sl.dlss.optimal_settings` | The render size and sharpness DLSS recommends | SessionFact | Streamline | Spike | Text |
| `sl.dlss.vram_estimate` | DLSS's own estimate of its video memory | Series | Streamline | Spike | Mebibytes |
| `sl.dlssg.options` | DLSS frame generation: mode, frames to generate | SessionFact | Streamline | Spike | Text |
| `sl.dlssg.state` | DLSS frame generation: status, the most frames it can generate | SessionFact | Streamline | Spike | Text |
| `sl.dlssg.frames_presented` | Frames DLSS frame generation presented, by its own count | Series | Streamline | Spike | Count |
| `sl.dlssg.vram_estimate` | DLSS frame generation's estimate of its video memory | Series | Streamline | Spike | Mebibytes |
| `sl.dlssd.options` | Ray reconstruction's options | SessionFact | Streamline | Spike | Text |
| `sl.nis.options` | NVIDIA Image Scaling's options | SessionFact | Streamline | Spike | Text |
| `sl.deepdvc.options` | RTX Dynamic Vibrance's options | SessionFact | Streamline | Spike | Text |
| `sl.dlss.optimal_settings` | The render size and sharpness DLSS recommends | SessionFact | Streamline | RefusedRoute | Text |
| `sl.dlss.vram_estimate` | DLSS's own estimate of its video memory | Series | Streamline | RefusedRoute | Mebibytes |
| `sl.dlssg.options` | DLSS frame generation: mode, frames to generate | SessionFact | Streamline | RefusedRoute | Text |
| `sl.dlssg.state` | DLSS frame generation: status, the most frames it can generate | SessionFact | Streamline | RefusedRoute | Text |
| `sl.dlssg.frames_presented` | Frames DLSS frame generation presented, by its own count | Series | Streamline | RefusedRoute | Count |
| `sl.dlssg.vram_estimate` | DLSS frame generation's estimate of its video memory | Series | Streamline | RefusedRoute | Mebibytes |
| `sl.dlssd.options` | Ray reconstruction's options | SessionFact | Streamline | RefusedRoute | Text |
| `sl.nis.options` | NVIDIA Image Scaling's options | SessionFact | Streamline | RefusedRoute | Text |
| `sl.deepdvc.options` | RTX Dynamic Vibrance's options | SessionFact | Streamline | RefusedRoute | Text |
| `sl.reflex.state` | Reflex through Streamline: availability and its frame reports | SessionFact | Streamline | RefusedRoute | Table |
| `sl.pcl.markers` | PC-latency markers the game sets | Series | Streamline | Spike | Count |
| `sl.pcl.markers` | PC-latency markers the game sets | Series | Streamline | RefusedRoute | Count |
**Closed by a licence**
+2 -2
View File
@@ -1873,8 +1873,8 @@ Moved verbatim, in this order.
| M12 ❓ | **Advanced metrics — which NVAPI rows answer on real hardware (D101, 2026-11-11).** `18_GPU_VENDOR_APIS` §The inventory lists sixty `nvapi.` rows whose reach is `Agent`. They are declared in the vendored headers; **none has been called on a GPU**, and CI has no driver, so it never takes that branch. Unknown per row: whether the RTX 5080 on the current driver answers or returns `NVAPI_NOT_SUPPORTED` (the memory-temperature target already does not exist on that card). | **The measurement is the bridge's probe on the owner's PC**, then the page itself (the release's owner-only item). Pre-committed: a call that does not answer → that row is N/A with NVAPI's own status as the reason, and nothing is put in its place; a call that hangs or faults twice → the row is off for the session (§Runtime policy); a value that contradicts the vendor's own tool → the row is withheld until it is explained. **Half answered the same day, by the bridge's own test on the dev box** (ctest `fl_nvapi_bridge`, AVAILABLE branch; RTX 5080): every fact answers (`present = 0xFFFFF`), eight of ten live groups answer (`0x33F` — no board and no power-supply temperature sensor on this card: N/A, by the first pre-committed outcome), the display answers its four groups, the global profile lists 24 settings; figures in `18_GPU_VENDOR_APIS` §L3. **Still open**: the same values on the page beside the vendor's own tool, and the session rows (`nvapi.session.*`), which need a game. **And one thing seen once and not explained**: in one test run of about a dozen that day, `FlNvReadLive` came back with no field at all although `FlNvReadFacts`, a moment earlier in the same process, had answered everything; nine further runs did not show it. A handle the driver invalidated is the usual cause of that shape, and nothing here re-enumerates after `FlNvInit`. Pre-committed for the reader that owns the thread: two readings in a row with no field → release and initialise the bridge again, once, and say so in the log; if that does not bring the fields back the layer is off for the session, as any layer that fails twice is. |
| 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
| M15 ❓ | **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. |
| 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
| 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 |
#### §M5 — the decision table, pre-committed 2026-09-03 BEFORE the first run
+156
View File
@@ -0,0 +1,156 @@
# 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 reader exists and the Agent does not start it yet.** The model and the arithmetic
> (`FrameLedger.Domain.Input`, `FrameLedger.Application.Input`, `Application.Recording.InputSessionBuilder`), the
> storage (schema 0024, the `.partial` file's chunk 11, the finalizer for both tiers — `06_DATA_MODEL`) and the reader
> itself (`Application.Input.InputReader`, `Infrastructure.Input`) are written and under test. Nothing composes the
> reader into the Agent: the switch, the terms and the screens come in the pull requests after this one, and this
> note is rewritten by each. **No report from a real controller has passed through any of this code**
> (owner decision D157): the developer has no controller, and what happens on a real one is owner-only item 48.
## The owner's request and decisions (2026-11-14)
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. |
## 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.
+272 -75
View File
@@ -87,6 +87,7 @@ owner-only items stay below; the history of every train, the passed owner-only i
| `§beta.45`, what the owner's seven sessions on beta.45 showed, session by session (item 43), that release's facts and SonarCloud's gate on its commit, the traps of that train | [`handoff/history/0.1.0-beta.45.md`](handoff/history/0.1.0-beta.45.md) |
| `§beta.46`, what the owner's five sessions on beta.46 showed (item 44), the design of the train that followed as the plan's review left it (`§The train after 0.1.0-beta.46`), that release's facts, the traps of that train | [`handoff/history/0.1.0-beta.46.md`](handoff/history/0.1.0-beta.46.md) |
| `§beta.47`, what that release decided beyond D136–D141, what item 44's last part showed, that release's facts, the traps of that train, its NEXT as the owner's sessions of 2026-11-14 changed it | [`handoff/history/0.1.0-beta.47.md`](handoff/history/0.1.0-beta.47.md) |
| `§beta.48`, what that release decided beyond D142–D147, that release's facts, the traps of that train, its NEXT and its "Left open" as item 46 changed them | [`handoff/history/0.1.0-beta.48.md`](handoff/history/0.1.0-beta.48.md) |
| `§Owner-only`, an open item | [§Owner-only](#owner-only--no-pr-can-close-these) below |
| `§Owner-only`, a passed item (3, 12, 14–19, 38, 39) | [`handoff/owner-only-passed.md`](handoff/owner-only-passed.md) |
| `§Traps`, `§Two corrections carried forward` | [`handoff/traps.md`](handoff/traps.md) |
@@ -94,96 +95,115 @@ owner-only items stay below; the history of every train, the passed owner-only i
---
## **START HERE** — 2026-11-14, 0.1.0-beta.48: two real games read; the driver's own GPU times beside a span that includes idle; every multiplier seen; samples a second apart
## **START HERE** — 2026-11-14, 0.1.0-beta.49: item 46 read; the frames counted for the log, Reflex and frame generation together; a read a second on a grid; the Agent keeps the reading that waits
*Status is `docs/changelog/0.1.0-beta.48.md`; this is what no other file carries.* The owner ran eight sessions on
beta.47 the morning it was released and said, twice: check. They were read (#448, #449): Phantom Blade Zero three
times, Cyberpunk 2077 twice, two Direct3D 11 games and a Direct3D 12 game with no NVIDIA library — **the read
works in real games**, and four things came out of it that the owner ruled on the same morning (D142–D147) and
approved as one train: #450 (the Overlay reads two more members of the report and keeps the multipliers seen),
#451 (the Agent, the App, the texts — Privacy Policy 2.21, Disclaimer 2.17), #452 (the poller's period), and this
release. **What the eight sessions showed is item 45's last paragraphs, below; beta.47's own section, its traps
and its release facts are [`handoff/history/0.1.0-beta.47.md`](handoff/history/0.1.0-beta.47.md)**; what the
read is and what bounds it is [`17_HOOK_ENGINE.md`](17_HOOK_ENGINE.md) §Calls the Overlay makes into a driver.
*Status is `docs/changelog/0.1.0-beta.49.md`; this is what no other file carries.* The owner ran item 46 on
beta.48 the afternoon it was released — ten sessions, then eight more — and said: check (#455, and item 46's last
paragraphs, below). The read works, the samples are a second apart, both games give both of the driver's own
times, the multipliers are listed, off means off, **and the owner's word: no hitch**. Two things were left, the
owner said *do both*, and four answers given while planning made the train (D148–D151): #456 (the Overlay counts
each summed frame for its log), #457 (the watchdog's periodic tick on a grid), #458 (the Agent keeps the reading
that waits; the guide on whose switches the table shows), and this release. **beta.48's own section, its traps
and its release facts are [`handoff/history/0.1.0-beta.48.md`](handoff/history/0.1.0-beta.48.md).**
### What this release decided, beyond D142–D147
### What this release decided, beyond D148–D151
- **Two more members of a report already fetched are not a new call.** Rule 4's note stands as written: the same
two getters, the Overlay's own buffer, the two names on `tools/overlay-allowed-fields.txt`. The owner ruled on
them by name (D142); a third member is asked the same way.
- **The driver's own times have a count each, and zero means not given.** An older driver leaves both zero, and
so did the probe's frames. They are added after the frame is accepted, so which frames the seven spans are made
of did not move — a session's old series mean what they meant.
- **An entry of their own in the catalog** (`nvapi.reflex.gpu_times`), not an eighth and ninth line of the frame
report: `AdvancedPresenter.MaxLines` is 8, and nine series of one entry are drawn as a band.
- **The layout stayed 5 again**: line 0 of region 5 was full, so the four words came out of the seven reserved
words that ended the `sl::DLSSOptions` line. Three remain there, two on the `sl::Constants` line, two on the
FidelityFX line.
- **The fact's key no longer holds the last multiplier.** It held it since beta.47, so every menu rewrote the
session's context.
- **`hz` is measured from the samples, not taken from the setting**: the finalizer cannot see the setting, and a
session recovered from a `.partial` file never knew it.
- **The plan named `tools/agent-cost` for the poller's change and it was not run**: it runs the Agent unelevated,
where a poll takes a millisecond and the period was already a second. Said in #452 rather than run for show.
- **The counts are of each frame's own two numbers, with sums, and no threshold.** The draft counted spans of no
length; a sample whose mean span is half a microsecond says spans of one or two microseconds exist, and a count
of exact zeros would have read "the driver's" where it was "ours". So the frames that have both a span and an
active time are kept in two heaps — active longer than the span, or not — each with its count and both sums.
- **A batch's state is three things**: the driver's low-latency switch, its "the game sleeps" switch
(`bUseGameSleep`: NVAPI's "is `NvAPI_D3D_Sleep()` being called") and its frame-generation multiplier. The second
was added on the owner's word — Reflex goes with frame generation in the owner's games, and the low-latency
switch can be the NVIDIA App's override — and Clair Obscur's two sessions read exactly that: `bUseGameSleep`
off throughout without frame generation, on with ×3.
- **Only the driver read and the publication are the periodic tick's.** The request is still followed on every
tick, so the hooks a session asks for go in on the tick the loader woke — a game that has just loaded
Streamline calls it at once. A draft that moved the whole block would have missed those calls.
- **One read is armed at every periodic tick, and the grid is what keeps two apart**: half a second at the least,
after a tick that ran that late. "At most once a second" is no longer said anywhere.
- **A session's first publication may hold a moment's worth.** A request seen on a woken tick is published by the
periodic tick that follows, however soon. One test read a single publication as complete and had to stop.
- **The Agent keeps two sets, and an empty one does not wait.** A reading can stand at the sample after the one it
would have ridden — a second later. With the sensor interval above a second the oldest is still pushed out.
- **No legal text changed (D149)**, although a bug report carries the Overlay's logs and so these lines: the
owner was told and chose it. The Privacy Policy names the logs of the component loaded into games.
- **The plan was reviewed against the source by a second reader before the owner saw it, and sixteen things in
the draft were wrong** — among them the three above, and the whole of the Agent's half, which the draft did not
have.
### Traps this train left
- **A cause I wrote down before checking it.** "The third of a second is the processor's temperature" went into
five files on two facts — unelevated a poll takes a millisecond; the sessions without a `cpu_temp` series are a
second apart — and then four sessions *with* the series turned out to be a second apart too. The texts were
taken back to what is established before the commit. **Count the exceptions before naming a cause.**
- **A bash here-document ate a backslash again** (a Python one-liner with `'\\'`). Edit scripts are files — the
rule already existed.
- **`FETCH_HEAD` belongs to the worktree that fetched.** A merge in a second worktree needs the commit's id.
- **A squash-merge of the lower pull request conflicts the upper one in `CHANGELOG.md` every time** both added to
`[Unreleased]`. With Auto-fix on, the app asks for a merge of `main`, not a rebase: do it in a worktree of its
own when a gate is running in the main one, keep the upper branch's file (it is the superset), and check that
the merged tree equals the branch's tip — then the gate already run still stands.
- **The gate script's last lines do not reach a background task's output**: read the log's last line and hash the
`rules` folder by hand.
- **An analyzer wants a `<summary>` once any `<param>` is written** (RCS1139).
- **A cause I offered and then counted away**: "the holes are the sensor library's fifth tick" — 25 of 134 fell on
one. The pattern that was there (46 of 134 exactly five samples apart) was the Agent's own attach rule, found
by reading `SessionRecorder`, not by looking harder at the Overlay.
- **A fixture that proved nothing**: the case for a woken watchdog first churned `sl.common.dll`, which wakes
nobody — it is in neither the inventory nor the census — and passed. It was caught only because the case
asserts, from the log, that the watchdog *was* woken (0 early ticks). **A test of a mechanism asserts that the
mechanism ran.** `opengl32.dll` is the wake that unloads nothing under a hook.
- **Qodana's native report reads the tests**: `static_cast<unsigned long long>(a * b)` is
`bugprone-implicit-widening-of-multiplication-result`. Widen an operand, not the product.
- **A here-document with an apostrophe in it failed again.** Edit scripts are files.
- **No edit while a gate runs still holds when CI asks for one**: the Qodana fix went into a second worktree of
the lower branch, and reached the upper one by a merge.
- **The item's own text said "nothing is lost by it" of the holes**, on a reading of the Overlay alone. A reading
was lost at every return to step. Say what was looked at.
### NEXT
1. **The owner runs item 46** — one batch on beta.48, with what is left of item 45 in it. Every outcome's meaning
is written there.
2. **Then the owner's to say**: more titles; D141 on a larger sample (the slowest call seen in a game is 65 µs);
whether the processor update is worth timing on their PC and moving off the poll's thread (below).
1. ~~**The owner runs item 47**~~ **Run and read 2026-11-14** (item 47, *Run 2026-11-14*): the difference in
Cyberpunk 2077 is the driver's, the holes are gone from steady play, off means off, and the stop fired once.
2. **The two GPU labels were reworded on the owner's word** (D152, 2026-11-14; strings in three languages, the
guide — in `[Unreleased]`, not in a release yet). **D141's stop stays as it is, and nothing more of Reflex is read** (D153, the owner
the same evening: "it only has to tell whether the game has it or not; Kingdom Come: Deliverance II has no
Reflex in its settings" — so that session lost nothing to the stop). (f) and (g) are said: the App's *Low
Latency Mode* is off, and no hitch.
3. **`slAllocateResources`** keeps its patch (D135); looked at again when there are more sessions.
4. **Train D** after it, the same way: a spike first — `sl.pcl.markers` waits for it, and §30 found its hook
would miss a game that fetched its functions before the attach.
4. ~~**Train D**~~ **Advanced metrics is closed (D154, 2026-11-14): train D is not built.** The owner was shown
the catalog — 140 entries, 110 read — and what the ten entries of reach `Spike` hold (Streamline's own headers,
2.14.16: DLSS frame generation's options and state, the video-memory estimates, ray reconstruction's, Image
Scaling's and Dynamic Vibrance's options, the PCL markers), with what reading them takes: a function of ours
handed to the game in place of Streamline's (rule 4), which a game that fetched its functions before the
attach never calls. The owner: "Đóng luôn". The ten are `RefusedRoute` now, the guide no longer says a later
release reads more, and §M15 is decided. **What is next is the controller feature**, planned in a session of
its own.
### Left open by this session
- ~~**This release's own facts** — the tag's run, the digests, the delta — are not in any file yet: the release is cut
after this text. Record them in the next pull request, with what SonarCloud and Qodana said.~~ **Recorded
2026-11-14: 0.1.0-beta.48 was released 2026-11-14T04:49:19Z** (11:49 in the owner's time zone) from the signed
tag on `aec1736` (#453), by run 43556901499 — green at the first attempt, one run for the one tag push. Eight
2026-11-14: 0.1.0-beta.49 was released 2026-11-14T11:12:44Z** (18:12 in the owner's time zone) from the signed
tag on `afe4984` (#459), by run 43587336452 — green at the first attempt, one run for the one tag push. Eight
assets; the seven digests of `SHA256SUMS.txt` equal the ones GitHub computed, and the portable package hashed
here equals its line; the five native libraries in it carry `FL_BUILD_ID v0.1.0-beta.48`, none of them
`-dirty`. The delta from beta.47 is 1 944 037 bytes beside a full package of 110 800 248 — "Delta processed
0452 files. 0024 patched, 0428 unchanged". The wiki was published by run 43558546949. The rehearsal on the
release branch (run 43555020289, at `0c210d0`, the released tree) had made a delta of 1 966 174 bytes with the
same file counts. **SonarCloud answered on `aec1736`: the quality gate passed and no issue is open on `main`. Qodana's two reports, CodeQL and `check` are green on that
commit**, as they were on each of #450–#453 before its merge; no advisory check found anything in this train.
- **No real game has given the two new figures yet.** In the probe `gpuActiveRenderTimeUs` read 0; whether
Phantom Blade Zero's is the short number the reading of 2026-11-14 expects is item 46's to say.
- **Where the third of a second of a poll goes is not established.** Unelevated, a poll takes about a millisecond
(the layers composed as the Agent composes them, each read under a stopwatch). In the owner's ledger 180 of 186
sessions are 1.32 s apart and six are 1.0 s: the two with no `cpu_temp` series (an Agent not elevated) are among
the six — which points at the sensor library's processor update, run on the poll's thread as administrator
with PawnIO — **but four sessions that have the series kept one second** (22, 72, 73, 136). **Not measured**:
that call itself (it needs elevation), and whether it is processor time or waiting. The period no longer
depends on it; a poll that takes a third of every second is still a poll that takes a third of every second.
- **With the sensor interval above one second, some readings of the driver's report are not stored**: the newest
stands until a sample carries it (`SessionRecorder`). Said in the guide; not changed.
- **No test runs the whole path through the real Agent**: the injected tests stop at the shared memory and the
sampler's start from it; no end-to-end case loads the stand-in module under an Agent session.
- **Two install batches of beta.46 took 0.61 s and 1.26 s and nothing explains them.** Cyberpunk 2077's eight
batches on beta.47 took 85–221 ms, each in one apply; Hogwarts Legacy has not been run since.
- **The Japanese strings are new and unreviewed**, as every `ja` string is.
- **Off means off has never been exercised on a real game** (item 43 (f), 44 (g), 45 (g), now 46 (e)); nor (c)
and (h) of item 43, which only the owner sees.
here equals its line; the five native libraries in it carry `FL_BUILD_ID v0.1.0-beta.49`, none of them
`-dirty`. The delta from beta.48 is 1 100 211 bytes beside a full package of 110 803 443 — "Delta processed
0452 files. 0023 patched, 0429 unchanged". The wiki was published by run 43588972123. **Two rehearsals on the
release branch**: run 43580081466 at `1ab2809`, and — after a test-only fix reached the branch — run
43581734484 at `9f94356`, whose tree is the released one (a delta of 1 134 949 bytes, the same file counts).
**SonarCloud analysed `afe4984`: the quality gate passed and no issue is open on `main`. Qodana's two reports,
CodeQL and `check` are green on that commit.** On the way two advisory checks did find something, each in a
test of this train and each fixed before its pull request merged: Qodana's native report on #456 (two
products widened after the multiplication), SonarCloud on #457 (a line of the log handed to `printf`). **The
train stopped once for the owner**: two signed merges timed out at the passphrase prompt after #457; it went on
when the owner had unlocked the key. The tag's message reads `FrameLedger 0.1.0-beta.49` where the tags before
it read the bare version — nothing reads it, and a pushed tag is not moved.
- **Why Cyberpunk 2077's active render is longer than its span without frame generation** — item 47's to say. A
third session that afternoon repeated it (233: 3.40 against 3.13 ms at 292 of 296 samples) and a session of
menus did not (232: 0 of 126).
- **The Agent's half of the holes is read from the code and fits the ledger; it is not measured.** And with both
sides on a second a slip of phase can still leave a sample without a report: item 47 counts them.
- **A game that exits by itself loses the batch of counts in hand** — under a minute. Not changed: nothing runs
at a process's exit.
- **Where the third of a second of a poll goes is not established** (the history file of beta.48 has what is
known). Not looked at in this train.
- **With the sensor interval above one second, some readings of the driver's report are not stored** — the oldest
of the two that wait is pushed out. Said in the guide; not changed.
- **No test runs the whole path through the real Agent**: the injected tests stop at the shared memory, the
sampler's and the pending queue's start from it.
- **Two install batches of beta.46 took 0.61 s and 1.26 s and nothing explains them.** Item 46's ten sessions had none
above 191 ms.
- **The Japanese strings are unreviewed**, as every `ja` string is; this release added none.
- **(c) and (h) of item 43**, which only the owner sees, are still not exercised.
- **Valor Mortis's crash at 51 s** (twice, beta.40 and beta.44) **and Black Myth: Wukong's fault in Steam's crash
handler at every exit** are not explained. One session of each with hooking off is the comparison that is missing.
- **What item 41 left unexercised**: a configure through the FidelityFX 2.3 loader (Cyberpunk 2077 with FSR frame
@@ -194,7 +214,7 @@ read is and what bounds it is [`17_HOOK_ENGINE.md`](17_HOOK_ENGINE.md) §Calls t
- **`LIMITATIONS.md` and the accuracy statement still say the processor's, the memory's and the motherboard's
sensors "have never been read on real hardware"** — the owner's to reword. The alpha line still rests (D98).
**Owner-only:** item 46; one session each of Valor Mortis and Black Myth: Wukong with hooking off; what item 41
**Owner-only:** item 47; one session each of Valor Mortis and Black Myth: Wukong with hooking off; what item 41
left unexercised; item 40 (d).
## Owner-only — no PR can close these
@@ -830,6 +850,167 @@ left unexercised; item 40 (d).
and the driver reported no frame* are possible and neither is wrong. *(e) the log has a `LATENCY` line*: off
does not mean off — say so at once, with the log. **A fault, a freeze, a game closing by itself, a hitch every
second, or a session that says *stopped***: as item 45 says for each — say so at once.
**Run 2026-11-14, 12:49–14:12, and read the same afternoon** from a copy of the ledger and the logs: ten
sessions on beta.48 — Phantom Blade Zero seven times (217, 219, 220, 223–226), Cyberpunk 2077 three times (218,
221, 222). Every one tier 1, exit code 0, no fault counted, nothing dropped; nothing in Windows' application
log. (Session 216, an hour of Phantom Blade Zero, was still beta.47 — it ran while the release was cut — and
is 1.32 s apart like the ones before it.)
**The samples are a second apart**: the median gap is 996–1002 ms in all ten (session 223: 2 294 of 2 394 gaps
round to 1.00 s, the rest lie between 0.80 and 1.27 s), and `hz` reads 1.000–1.017.
(a) `legal_acceptance` holds Privacy Policy 2.21 and Disclaimer 2.17, accepted at 12:48:40.
(b) **Both figures were given by both games, in every frame report**: in the nine sessions with the option on,
every sample that has a *GPU render* span has both (3 834 of 3 834). **Phantom Blade Zero is what the reading of
2026-11-14 expected**: at 60 FPS (217) the span's median is 16.39 ms, *GPU frame time* 16.67 ms and *GPU active
render* **9.59 ms**; in the menu (224) 16.39 / 16.67 / **2.77**; at 91 FPS (225) 11.49 / 11.79 / 10.05; with
frame generation ×5 (223) 15.67 / 15.88 / 14.08. So in that game the span is the time from one frame to the
next less a third of a millisecond, whatever the card did in it, and active render is never longer than it
(0 of 3 406 samples). **Cyberpunk 2077 is the outcome written above as "active render longer than GPU render,
start to end"**: without frame generation it is longer at 157 of 158 samples (218: medians 3.17 against
2.79 ms, frame time 6.02) and at 48 of 48 (221: 2.03 against 1.82, frame time 2.37); with frame generation ×2
(222) it is shorter at all 222 (4.85 against 6.35, frame time 6.67). Shown as reported. **Why is not
established**, and two things could do it: the two are averages over different frames — the span over every
summed frame, one of no length included (the smallest mean span of a sample there is 0.5 µs, the smallest active
time 0.29 ms), active render over the frames that gave one — or the driver counts work the two marks do not
enclose. The ledger cannot tell them apart; a count of the frames whose span has no length would.
(c) `fgMultiplier` reads **1, 2** in Cyberpunk 2077 (222: ×2.0 for 69 % of it), **1, 5** in Phantom Blade Zero
(220: ×5.0 for 71 %, 30 → 151 FPS; 223: ×5.0 for 95 %, 63 → 316) and **1** in the seven sessions that generated
nothing.
(d) **Session 221** (Cyberpunk 2077, 59 s of menus at 421 FPS) is the only Cyberpunk session whose
`bLowLatencyMode` reads *on and off* — 218 and 222 read *on*, as 211 and 212 did — and is taken to be the one
where Reflex was switched off; the owner has not said which it was. Its line reads *read*, 48 of 57 samples
carry a report, every one from the first on, and the slowest call took 19 µs: the driver goes on reporting
frames.
(e) **Off means off, on a real game for the first time**: session 226 (`telemetry.advanced` 0) has no
`session_advanced` row and 19 series where the others have 240; its log has ten hooks, none of the ones
Advanced metrics adds, and **no `LATENCY` line**. The setting was still off when the ledger was copied.
(f) No other game was in the batch.
**The read itself**: one `reading the driver's latency report` line a session, 1.4–6.7 s after the attach, in
the same two files, and none after it; the slowest call of a session 18–123 µs; no latch. The install batches
took 75–191 ms, every one `install`.
**Samples with no report**: after a session's first report, 0.4–7.3 % of its samples carry none (1 of 223 in
222; 134 of 2 377 in 223, minutes of four in five there). They are not the sensor library's ticks (25 of the 134
fall on one, 24 just after one). What the code says, not measured: the watchdog ticks once a second and arms a
read when a second has passed since the last arm, so a tick that comes a moment early waits for the next one —
the reads are a second apart or two, the samples exactly one. Nothing is lost by it; a sample shows a gap.
(g) **The owner's answer, asked whether a game hitched once a second with the option on (2026-11-14): no
hitch.** What the frames say, in the sessions without frame
generation: a frame three times the median of the 120 before it and 8 ms longer comes 0.33 times a second
with the option on (225) and 0.32 with it off (226), and such frames do not gather at a period of one second
(vector strength 0.05–0.10 where chance gives 0.10–0.20; 217, 218 and 222 the same). Sessions with frame
generation cannot be judged that way. **Not seen in the ledger**: what the page looked like, and the Agent's
processor use now that a poll comes every second.
**Read, and (g) answered**: (a)–(g) each have their answer; ~~whether session 221 was (d) is inferred, and the
owner's to say~~ (d) is withdrawn in the next paragraph. The owner has not said the item is passed.
**Eight more sessions the same afternoon (227–234), read at once, and three things the owner said.** Still
beta.48: Cyberpunk 2077 three times (227 with the option off — no `LATENCY` line, no row; 232 mostly menus; 233
five minutes without frame generation), Phantom Blade Zero three times (228, 231, 234), Clair Obscur:
Expedition 33 twice (229 with frame generation ×3 for 79 % of it, 230 without). All tier 1, exit code 0, no
fault, nothing dropped; samples a second apart; slowest calls 10–29 µs; `fgMultiplier` *1, 3* in 229.
**The owner's words**: *Reflex is checked together with frame generation — without frame generation the game
does not switch Reflex on*; *a value that reads on and off is the NVIDIA App's override* (the App's page for
Phantom Blade Zero: **Low Latency Mode — Ultra**); and a session with Reflex off may be read. **So (d) above
is withdrawn as written**: session 221 was not "the one where Reflex was switched off in a menu", and nothing
here says what its `bLowLatencyMode` *on and off* was. What the sessions do read: **Clair Obscur without frame
generation has `bUseGameSleep` off throughout (230) and with ×3 on and off (229)** — the game's own Reflex
goes with its frame generation, as the owner said; **Phantom Blade Zero has `bLowLatencyMode` off throughout
in 234**; and in both the read is what it is with Reflex on — one `reading` line, a report at every read, the
two new figures in every one. **Cyberpunk 2077 without frame generation again has active render longer than
the span** (233: 3.40 against 3.13 ms at 292 of 296 samples), **and its menus do not** (232: 0 of 126; active
0.39 ms inside a span of 1.18).
**The holes are larger in short sessions**: 11.3 %, 16.2 % and 11.1 % of the samples after the first report
in 228, 229 and 231; 6.0 % in 230; 0.8 % in 232. **And "nothing is lost by it", above, was wrong**: it was
written on a reading of the Overlay alone. The Agent kept one set of readings until a sample carried it and
overwrote it — a publication that landed just after a sample left that sample without, and the set that had
waited was replaced at the next return to step (46 of session 223's 134 holes are exactly five samples
apart). The Overlay's part is the other half: its ticks were a second and their own work apart, and a tick the
loader woke published the read and armed none. Both are mended in 0.1.0-beta.49 (D150); neither is measured in
a game yet.
47. **beta.49 — whose the difference is in Cyberpunk 2077's GPU times; and the holes** (D148–D151). **One batch,
in pairs**: the same game with frame generation off and with it on, *Advanced metrics* on. Reflex is not
switched by hand — it goes with frame generation. **Not first on a game under the user-mode exception's
trial** (D38). Then say *check*; the logs and a copy of the ledger are read.
(a) **The update shows no terms window**: no legal text changed.
(b) **Cyberpunk 2077**: six minutes or more of play **without frame generation**, in a scene like session
218's; six minutes or more with **frame generation ×2**; two minutes of menus only.
(c) **Phantom Blade Zero**: six minutes or more without frame generation — the control — and six or more with.
(d) **About eight short sessions**, three minutes each, any Direct3D 12 game that uses Reflex: the step between
the game's side and the Agent's is different in every session, and one long session shows one of them.
(e) **One session with *Advanced metrics* off**; switch it back on afterwards.
(f) **What *Low Latency Mode* is set to for Cyberpunk 2077 in the NVIDIA App** — a word is enough.
(g) **How the games felt**, as always.
A game closed by itself loses its last batch of counts, under a minute: that is why six minutes and not two.
**What each outcome means, written before the run.** The log's `LATENCY_FRAMES` batches each carry the state
they belong to, so every one is read as *this state, these counts*.
*Cyberpunk without frame generation: nearly every frame that has both is in "active longer than span", and
their mean span is near the 2.8 ms the chart shows* — **the difference is the driver's**: it counts work the
two marks do not enclose. The numbers are shown as reported and the label "idle time included" is what is
wrong for that game: the owner decides its wording.
*"Active longer" is a minority whose spans are next to nothing, the rest have active within the span, and
spans of no length or of a microsecond are about as many as that minority* — **the difference is ours**: the
span's mean is pulled down by frames that have none. The owner decides whether the mean is taken over the
frames that have a span.
*Both heaps are large, with real spans* — both; the heaps' sums give the like-for-like figure, and it is said
with them.
*"GPU span absent" is not zero* — those reads published no GPU point at all, and were never in the comparison.
*Phantom Blade Zero shows many frames in "active longer"* — suspect the count before the driver: say so.
*The counts differ between a batch with `bUseGameSleep` on and one with it off, in the same game* — that is
the owner's point, measured: say the two side by side.
*The batches say a thousand milliseconds a read and as many periodic ticks as reads, and every session has
next to no sample without a report* — D150 did what it was for.
*The log says a thousand milliseconds a read and some sessions still lack a report at a steady share of their
samples* — the Agent's rule is not the whole of it: say the sessions and the share.
*The log says more than a thousand milliseconds a read* — the Overlay is still uneven; the line's tick counts
say whether the loader was waking it.
*(e) has a `LATENCY` or `LATENCY_FRAMES` line* — off does not mean off: say so at once, with the log.
**A fault, a freeze, a game closing by itself, a hitch every second, or a session that says *stopped***: as
item 45 says for each — say so at once.
**Run 2026-11-14 (sessions 236–245, ten on 0.1.0-beta.49), read the same day** from a copy of the ledger and
the Overlay's logs. All ten tier 1, exit code 0, no fault, nothing dropped. Phantom Blade Zero twice (236
without frame generation, 1 108 s; 237 with ×2, 811 s), Kingdom Come: Deliverance II (238), Clair Obscur (239),
Black Myth: Wukong (240), Lies of P (241, and 245 with the option off), Hogwarts Legacy (242), Dying Light: The
Beast (243), Cyberpunk 2077 (244). 239 and 240 ran at the same time, and so did 241, 242 and 243.
(a) **No new acceptance row** after the update: the terms window did not appear.
(b) **Cyberpunk 2077 was one session of 125 s without frame generation** (374 FPS); ×2 and the menus were not
run. It is enough for the question. 88 reads in one state — low-latency mode on, the game sleeping, ×1 — summed
5 394 frames: **4 917 in "active longer than span", mean span 1 571 µs, mean active 1 849 µs**; 96 within
(3 866 / 3 431 µs); 381 with a span of no length and an active time; none absent, none refused. **So the
difference is the driver's**: on frames that have a real span, its active time is 278 µs (18 %) longer than
the two marks are apart. A small part is ours as well — 7 % of the frames have a span of no length and pull the
span's mean down (the stored means are 1 892 and 2 138 µs). With frame generation on it is not measured on
this build (0.1.0-beta.48's means: never longer).
(c) **The count is not what is wrong**: in the six other sessions that reported (five games), **not one frame of 129 900** is
in "active longer", and no span is absent or of no length. Phantom Blade Zero: without frame generation
63 123 frames, span 16.4 ms, active 11.1 ms; with ×2 21 209 frames, span 33.2 ms, active 12.6 ms.
(d) **The holes**: in batches of twenty reads or more a read took 1 000.94 ms (236), 997.18 (237), 999.99 (242,
244), and up to 1 013 ms in the sessions that shared the PC with another game. Samples without a
report: 236 — 40 of 1 106, **39 of them in the first 46**, while the game started; 237 — 36 of 809, in the first 42 and
the last two; 244 — 9 of 123, in the first ten. Before, they were spread through a session (0.4–16 %). **D150 did what
it was for.** Where two or three games ran at once the holes are blocks in which the game did not present
(240: 103 of 477; 242: 80 of 402, 68 of them at its start; 243: 37 of 414; 239: 23 of 184): a read is taken on
the presenting thread, so a game that presents nothing is not read — Lies of P's log has sixty reads in 189 s.
(e) **Off means off**: session 245 has no `LATENCY` line and no Advanced row.
**The stop fired in a real game for the first time** (D141): Kingdom Come: Deliverance II, 12 s after the
attach, while the game was starting — the seventh read took 5 337 µs, and no further read was made; the
session says so (`Slow`), the game ran 287 s and closed normally. No frame had been reported in those seven
reads. **The owner: that game has no Reflex in its settings** — so there was no report to lose; the
session's line says *stopped* where, without the slow call, it would have said *the driver reported no
frame*. Elsewhere the slowest call was 22–235 µs. In Lies of P the driver reported no frame at all.
**What the states say of Reflex and frame generation** (each batch carries its own): low-latency mode was
**on at a multiplier of 1** in Cyberpunk 2077 (88 reads), Black Myth: Wukong (253), Hogwarts Legacy (299) and
Dying Light: The Beast (345); Phantom Blade Zero without frame generation sleeps through Reflex with
low-latency mode **off** (1 062 reads) and switches it on with ×2; Clair Obscur without frame generation has
both off and still reports its frames. The logs cannot say whether a game's menu or the NVIDIA App switched
the mode on. NVIDIA's own guide makes frame generation need Reflex and not the reverse
(`spike-notes` §30, *Added 2026-11-14*). Hogwarts Legacy gave a multiplier of 6 for seventeen reads.
(f), (g) **The owner, the same evening: "App reflex off, không khựng"** — *Low Latency Mode* is off in the
NVIDIA App, and no hitch. Read with (f) as it was asked, for Cyberpunk 2077: the low-latency mode its 88
reads show at a multiplier of 1 is then the game's own Reflex and not the App's override — Reflex on without
frame generation, as NVIDIA's guide allows. **Then shown, in two screenshots**: the NVIDIA App's *Program
Settings* for Cyberpunk 2077 have *Low Latency Mode* **Off**, set for that program (the rows that follow the
global setting read "Global - …"; this one does not); and the game's own *Video* page has **NVIDIA Reflex Low
Latency: On**, V-Sync off, borderless at 2560×1440, 378 FPS on the game's counter. So the driver's
`bLowLatencyMode` on, at a multiplier of 1, is the game's menu, seen from both sides. **The owner's**: the wording of the two GPU labels — *idle time excluded /
included* does not describe a game whose active time is the longer.
**Answered 2026-08-05, do not re-ask:** remove `gameguard` and keep `guard` (approved
over a red `Rules` gate, with the reasoning recorded in the merge commit); vendor NVAPI
@@ -991,6 +1172,22 @@ Where each owner decision is recorded — the file and its section, and a label
| D145 | [`../legal/ACCURACY.md`](../legal/ACCURACY.md) | the accuracy statement, the README and the guide say two real games were read on one driver (they said none); Privacy Policy 2.21 and Disclaimer 2.17 with it |
| D146 | [`06_DATA_MODEL.md`](06_DATA_MODEL.md) §sensor_blobs | the Agent's samples were 1.32 s apart under a 1 s setting (it waited the whole interval after its work): sample on a fixed period, and store the rate the samples had |
| D147 | [`03_METRICS.md`](03_METRICS.md) | the session summary's latency fields stay N/A: the driver's total is simulation start to GPU end, not input to display |
| D148 | [`17_HOOK_ENGINE.md`](17_HOOK_ENGINE.md) §Native logging | asked on 2026-11-14 with item 46's Cyberpunk 2077 numbers (active render longer than the span between the GPU marks): count the frames, and write the counts **only to the Overlay's native log** — no layout, schema, App or string change |
| D149 | [`17_HOOK_ENGINE.md`](17_HOOK_ENGINE.md) §Native logging | told that a bug report carries the five newest Overlay logs and so these lines: **no change to the legal texts** — the Privacy Policy names the logs of the component loaded into games, and the lines are counts and sums of microseconds |
| D150 | [`07_IPC.md`](07_IPC.md) §Region 5 | the samples that carry no report are mended **on both sides**: the Overlay reads and publishes on a grid of one second, and the Agent no longer overwrites a reading that waits for a sample |
| D151 | [`17_HOOK_ENGINE.md`](17_HOOK_ENGINE.md) §Native logging | the owner's word: Reflex is checked together with frame generation — without it the owner's games do not switch Reflex on, and a low-latency switch that reads on and off is the NVIDIA App's override. A batch of counts belongs to one state of the sleep status |
| 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 |
+79
View File
@@ -0,0 +1,79 @@
<!-- Moved from CHANGELOG.md's [Unreleased] when 0.1.0-beta.49 was cut, 2026-11-14 (D66). CHANGELOG.md lists every release. -->
## [0.1.0-beta.49] - 2026-11-14
**The forty-ninth pre-release: what the owner's sessions on 0.1.0-beta.48 showed, the same day.** Eighteen
sessions, sixteen of them with *Advanced metrics* on — Phantom Blade Zero, Cyberpunk 2077 and Clair Obscur:
Expedition 33, with frame generation on and off, with Reflex on and off. Sensors are now read every second; NVIDIA's driver gave both
of its own GPU times in every report of every game; the table lists every frame-generation multiplier; a game
started with the option off was left alone; the driver was read just the same with Reflex off; and the owner's
word on how the games felt: no hitch. The same unsigned installer: verify its hash against `SHA256SUMS.txt`, then
*More info → Run anyway*. **No legal text changed, so the terms window does not appear.**
**Two things those sessions showed, and what this release does about each.**
- **The *Latency* charts had holes.** After a session's first reading, between 0.4 and 16 % of its samples had
none. There were two reasons, one on each side. The part inside the game did its once-a-second round a second
*after* the last one finished — so it fell behind — and whenever the game loaded a library it was woken early,
published what it had, and asked the driver for nothing new. And the capture agent kept one reading until a
sample could carry it, and replaced it if another arrived first. Both are mended: the round inside the game is
now due at fixed moments, and the agent keeps the reading that waits.
- **In Cyberpunk 2077 without frame generation, NVIDIA's *GPU active render* time is longer than the time from the
card's start on a frame to its end** — which should contain it. Nothing stored can say whether that is the
driver's arithmetic or the way FrameLedger averages the two (one over every frame, one only over the frames that
gave a time). **This release changes no number you see.** It counts, frame by frame, how the two stand to each
other, and writes the counts to the game component's own log, together with the driver's low-latency state and
its frame-generation multiplier — the owner asked that Reflex and frame generation always be read together. The
next sessions say which it is; what to do about it is decided then.
**What it is not.** Not a promise that every sample now carries a reading: with both sides on one second a slip
can still leave one without, and the log says how often. The reason given for the agent's half was read from the
code and fits the pattern in the ledger; it has not been measured in a session. Nothing here is read on
Direct3D 11, Vulkan or OpenGL, and the figures remain the driver's, not a measurement by FrameLedger. The log of
the component inside a game grows by about seven lines a minute while *Advanced metrics* reads the driver — a few
tens of kilobytes an hour — and a bug report carries those logs, as it always carried them. A game that closes by
itself loses the last batch of counts, under a minute.
**Measured overhead this release.** A presented frame: unchanged — no line that runs with a present was touched.
The reading of the driver's report, once a second while a session with *Advanced metrics* runs in a Direct3D 12
game: 65 billionths of a second more (424–435 → 490–499 billionths, the same instrument as before), after the
request's own time has been taken. The background thread inside the game: ten readings in 9 996 ms, twenty in
20 002, sixty in 59 997 on the test harness — and the same with another thread waking it eighteen thousand times
in ten seconds, where the code before it published 35 720 times in eight seconds and read nine times.
### Added
- **The frames NVIDIA's latency report gives are counted, for the Overlay's own log** (owner decisions D148,
D151; nothing new is stored, shown, asked of the driver or read from its report). The owner's sessions on
0.1.0-beta.48 showed both of the driver's own GPU times in two games — and in Cyberpunk 2077 without frame
generation an *active render* time longer than the span from the card's start on a frame to its end, which the
two averages cannot explain: one is over every frame, one only over the frames that gave a time. While a session
with *Advanced metrics* reads the driver, the Overlay now places each frame by its own two numbers and writes
the counts to `overlay-<pid>-….log` as `LATENCY_FRAMES` lines, in batches that each belong to **one state of
the driver's low-latency status and its frame-generation multiplier** — the counts are read together with
Reflex and frame generation, never apart. About six lines a minute; a game that exits by itself loses the last
batch, under a minute. A bug report carries those logs, as it carried them before. Measured: 65 billionths of a
second more for each reading of the report, once a second; a presented frame costs what it did.
### Changed
- **The guide says whose switches the latency table shows**: the driver's, not the game's menu. `bLowLatencyMode`
is also on when *Low Latency Mode* is set for the game in the NVIDIA App, and `bUseGameSleep` says whether the
game itself paces its frames through Reflex — in some games only with frame generation on (the owner's word,
2026-11-14, and what Clair Obscur's sessions of that afternoon read).
### Fixed
- **NVIDIA's latency report is read on a grid of one second, and a busy loader no longer leaves holes in it**
(owner decision D150; the Overlay's half). After a session's first report, 0.4 to 16 % of its samples carried
none — the *Latency* charts had gaps. The Overlay's background thread waited a second *after* each round of its
work, so it fell behind the capture agent, which samples exactly every second; and whenever the game loaded a
library that thread was woken early, published what it had and asked for no new reading, so the round after it
had nothing to publish. Its once-a-second round is now due at fixed moments whatever the work took, and a round
woken early no longer publishes or takes a reading. Two readings are never less than half a second apart.
Nothing on a game's own threads changed.
- **A reading that waits for a sample is no longer overwritten by the next one** (D150; the capture agent's
half). The agent kept one reading from the game until a sensor sample could carry it, and replaced it when
another arrived first. When a reading landed just after a sample, that sample went without and a reading was
lost a little later — in one session of the owner's, one sample in five for four minutes. Two readings may now
wait and the older is stored first; a point can stand up to a second after its reading was taken. With the
sensor interval above one second, not every reading is stored, as before.
+115
View File
@@ -0,0 +1,115 @@
# HANDOFF history — 0.1.0-beta.48
*Moved verbatim from `docs/HANDOFF.md` when 0.1.0-beta.49 was cut, 2026-11-14 (owner decision D66); `docs/HANDOFF.md` §How this file is split lists every part. Nothing below was edited, so its "below" and "above" mean HANDOFF.md as it stood then, and a path it writes is relative to `docs/`. **Its NEXT and its "Left open" were written through the afternoon of 2026-11-14 as item 46 was read**: what they led to is HANDOFF.md's section for 0.1.0-beta.49.*
## **START HERE** — 2026-11-14, 0.1.0-beta.48: two real games read; the driver's own GPU times beside a span that includes idle; every multiplier seen; samples a second apart
*Status is `docs/changelog/0.1.0-beta.48.md`; this is what no other file carries.* The owner ran eight sessions on
beta.47 the morning it was released and said, twice: check. They were read (#448, #449): Phantom Blade Zero three
times, Cyberpunk 2077 twice, two Direct3D 11 games and a Direct3D 12 game with no NVIDIA library — **the read
works in real games**, and four things came out of it that the owner ruled on the same morning (D142–D147) and
approved as one train: #450 (the Overlay reads two more members of the report and keeps the multipliers seen),
#451 (the Agent, the App, the texts — Privacy Policy 2.21, Disclaimer 2.17), #452 (the poller's period), and this
release. **What the eight sessions showed is item 45's last paragraphs, below; beta.47's own section, its traps
and its release facts are [`handoff/history/0.1.0-beta.47.md`](handoff/history/0.1.0-beta.47.md)**; what the
read is and what bounds it is [`17_HOOK_ENGINE.md`](17_HOOK_ENGINE.md) §Calls the Overlay makes into a driver.
### What this release decided, beyond D142–D147
- **Two more members of a report already fetched are not a new call.** Rule 4's note stands as written: the same
two getters, the Overlay's own buffer, the two names on `tools/overlay-allowed-fields.txt`. The owner ruled on
them by name (D142); a third member is asked the same way.
- **The driver's own times have a count each, and zero means not given.** An older driver leaves both zero, and
so did the probe's frames. They are added after the frame is accepted, so which frames the seven spans are made
of did not move — a session's old series mean what they meant.
- **An entry of their own in the catalog** (`nvapi.reflex.gpu_times`), not an eighth and ninth line of the frame
report: `AdvancedPresenter.MaxLines` is 8, and nine series of one entry are drawn as a band.
- **The layout stayed 5 again**: line 0 of region 5 was full, so the four words came out of the seven reserved
words that ended the `sl::DLSSOptions` line. Three remain there, two on the `sl::Constants` line, two on the
FidelityFX line.
- **The fact's key no longer holds the last multiplier.** It held it since beta.47, so every menu rewrote the
session's context.
- **`hz` is measured from the samples, not taken from the setting**: the finalizer cannot see the setting, and a
session recovered from a `.partial` file never knew it.
- **The plan named `tools/agent-cost` for the poller's change and it was not run**: it runs the Agent unelevated,
where a poll takes a millisecond and the period was already a second. Said in #452 rather than run for show.
### Traps this train left
- **A cause I wrote down before checking it.** "The third of a second is the processor's temperature" went into
five files on two facts — unelevated a poll takes a millisecond; the sessions without a `cpu_temp` series are a
second apart — and then four sessions *with* the series turned out to be a second apart too. The texts were
taken back to what is established before the commit. **Count the exceptions before naming a cause.**
- **A bash here-document ate a backslash again** (a Python one-liner with `'\\'`). Edit scripts are files — the
rule already existed.
- **`FETCH_HEAD` belongs to the worktree that fetched.** A merge in a second worktree needs the commit's id.
- **A squash-merge of the lower pull request conflicts the upper one in `CHANGELOG.md` every time** both added to
`[Unreleased]`. With Auto-fix on, the app asks for a merge of `main`, not a rebase: do it in a worktree of its
own when a gate is running in the main one, keep the upper branch's file (it is the superset), and check that
the merged tree equals the branch's tip — then the gate already run still stands.
- **The gate script's last lines do not reach a background task's output**: read the log's last line and hash the
`rules` folder by hand.
- **An analyzer wants a `<summary>` once any `<param>` is written** (RCS1139).
### NEXT
1. ~~**The owner runs item 46**~~ **Run and read 2026-11-14** (the item, below): the samples are a second apart,
both games gave both figures, the multipliers are listed, off means off. **The owner's word, the same day: no
hitch.** What is left of it is whether session 221 was the one with Reflex off.
2. **Then the owner's to say**: more titles; D141 on a larger sample (the slowest call seen in a game is 65 µs);
whether the processor update is worth timing on their PC and moving off the poll's thread (below).
3. **`slAllocateResources`** keeps its patch (D135); looked at again when there are more sessions.
4. **Train D** after it, the same way: a spike first — `sl.pcl.markers` waits for it, and §30 found its hook
would miss a game that fetched its functions before the attach.
### Left open by this session
- ~~**This release's own facts** — the tag's run, the digests, the delta — are not in any file yet: the release is cut
after this text. Record them in the next pull request, with what SonarCloud and Qodana said.~~ **Recorded
2026-11-14: 0.1.0-beta.48 was released 2026-11-14T04:49:19Z** (11:49 in the owner's time zone) from the signed
tag on `aec1736` (#453), by run 43556901499 — green at the first attempt, one run for the one tag push. Eight
assets; the seven digests of `SHA256SUMS.txt` equal the ones GitHub computed, and the portable package hashed
here equals its line; the five native libraries in it carry `FL_BUILD_ID v0.1.0-beta.48`, none of them
`-dirty`. The delta from beta.47 is 1 944 037 bytes beside a full package of 110 800 248 — "Delta processed
0452 files. 0024 patched, 0428 unchanged". The wiki was published by run 43558546949. The rehearsal on the
release branch (run 43555020289, at `0c210d0`, the released tree) had made a delta of 1 966 174 bytes with the
same file counts. **SonarCloud answered on `aec1736`: the quality gate passed and no issue is open on `main`. Qodana's two reports, CodeQL and `check` are green on that
commit**, as they were on each of #450–#453 before its merge; no advisory check found anything in this train.
- ~~**No real game has given the two new figures yet.**~~ **Two have (item 46, 2026-11-14)**, in every frame
report: Phantom Blade Zero's active render is the short number the reading expected (9.6 ms inside a span of
16.4 ms at 60 FPS). **In Cyberpunk 2077 without frame generation active render is longer than the span between
the two GPU marks** (3.17 against 2.79 ms) **and why is not established** — the two averages are over different
frames, or the driver counts work outside the marks. The label says *idle time included*, which that game's
numbers do not show; the texts say the figures are the driver's own. Not changed.
- **After a session's first report, 0.4–7.3 % of its samples carry none** (item 46): the Overlay's reads are a
second apart or two — its watchdog's tick — and the Agent's samples exactly one. Read in the code, not measured;
not changed.
- **Where the third of a second of a poll goes is not established.** Unelevated, a poll takes about a millisecond
(the layers composed as the Agent composes them, each read under a stopwatch). In the owner's ledger 180 of 186
sessions are 1.32 s apart and six are 1.0 s: the two with no `cpu_temp` series (an Agent not elevated) are among
the six — which points at the sensor library's processor update, run on the poll's thread as administrator
with PawnIO — **but four sessions that have the series kept one second** (22, 72, 73, 136). **Not measured**:
that call itself (it needs elevation), and whether it is processor time or waiting. The period no longer
depends on it; a poll that takes a third of every second is still a poll that takes a third of every second.
- **With the sensor interval above one second, some readings of the driver's report are not stored**: the newest
stands until a sample carries it (`SessionRecorder`). Said in the guide; not changed.
- **No test runs the whole path through the real Agent**: the injected tests stop at the shared memory and the
sampler's start from it; no end-to-end case loads the stand-in module under an Agent session.
- **Two install batches of beta.46 took 0.61 s and 1.26 s and nothing explains them.** Cyberpunk 2077's eight
batches on beta.47 took 85–221 ms, each in one apply; Hogwarts Legacy has not been run since.
- **The Japanese strings are new and unreviewed**, as every `ja` string is.
- ~~**Off means off has never been exercised on a real game**~~ **It was, 2026-11-14** (item 46 (e), session
226: no `LATENCY` line, none of the hooks Advanced metrics adds, no row). (c) and (h) of item 43, which only the
owner sees, are still not.
- **Valor Mortis's crash at 51 s** (twice, beta.40 and beta.44) **and Black Myth: Wukong's fault in Steam's crash
handler at every exit** are not explained. One session of each with hooking off is the comparison that is missing.
- **What item 41 left unexercised**: a configure through the FidelityFX 2.3 loader (Cyberpunk 2077 with FSR frame
generation), a game with neither library.
- **A fault while a game is closing is not seen by a hooked session** (D127: written down, not changed).
- **`docs/LIST_GAME_TESTED.md` is as of 2026-11-06**: refreshing it is a new copy of the ledger and the owner's review.
- **Item 40 (d)** was not exercised and the owner has not said item 40 passed. **Items 36 (d) and 37 are still open.**
- **`LIMITATIONS.md` and the accuracy statement still say the processor's, the memory's and the motherboard's
sensors "have never been read on real hardware"** — the owner's to reword. The alpha line still rests (D98).
**Owner-only:** one session each of Valor Mortis and Black Myth: Wukong with hooking off; what item 41 left
unexercised; item 40 (d).
+55
View File
@@ -175,3 +175,58 @@ route.
The spike is [`spike-notes` §31](31-reflex-route-d-harness.md), run on 2026-11-13: none of the stop conditions
above fired on the harness, and it ends in the question of one real title.
### Added 2026-11-14: Streamline's two programming guides, read against this note and the code
`docs/ProgrammingGuideReflex.md` and `docs/ProgrammingGuideDLSS_RR.md` of NVIDIA's Streamline repository, both
"Version 2.14.16", fetched as text and read whole — at the owner's request. What they add, and what they change.
**Reflex**
- **Low latency and frame generation: the dependency runs one way.** The guide lists the plugin's parts as
"distinct to each other without any cross-dependencies", wants Reflex's default to be *On*, and its checklist
tests *Reflex On* with frame generation **off**. Frame generation is what needs Reflex. The owner's "without
frame generation the game cannot switch Reflex on" is true of some of the owner's games' menus, not of Reflex.
The sessions of 2026-11-14 agree (HANDOFF, item 47): low-latency mode on at a multiplier of 1 in four games;
Phantom Blade Zero switches it on with frame generation; Clair Obscur without frame generation has it off.
- **The sleep and the markers are sent whatever the mode.** "`slReflexSleep` and `slPCLSetMarker` must always be
called even when Reflex Low Latency mode is Off"; the verification overlay's *App Called Sleep* stays 1 with
Reflex off. So `bUseGameSleep` says the game calls the sleep, **not** that Reflex is on, and a report exists
with Reflex off — which is what the sessions on 0.1.0-beta.48 showed (HANDOFF, item 46). Phantom Blade Zero
without frame generation is exactly this: the game sleeps, low-latency mode off, 1 062 reads.
- **`slReflexSetOptions` is called once, and again only when an option changes.** A hook on it would see nothing
in most sessions even if it could be placed: `nvapi.reflex.mode` stays refused for a second reason.
- **The markers are the report.** `slPCLSetMarker` replaces `NvAPI_D3D_SetLatencyMarker`, and the times the
markers carry (simulation, render submit, present) are the ones the driver hands back in the report this
product already reads (route D). `sl.pcl.markers` would add a count of calls, the ping and the flash trigger —
nothing a player reads. **Recommended to the owner: leave Reflex and PCL out of train D** — **decided the
same evening (D153)**: whether a game has Reflex is all that is wanted.
- **PC latency is not in the report, and NVIDIA takes it from outside the game**: its PCL statistics, read by
tools started from an administrator's prompt (route E here). D147 stands on that; two design tables that still
promised "PC latency as reported by Reflex" were corrected today (`03_METRICS`, `05_DETECTION`).
- **The stages, in NVIDIA's words** (the verification overlay's table): *driver* is from the first buffer
submission to the last present submission; *OS queue* from the first significant buffer submission to the end
of the GPU's work; *GPU* from where its rendering starts to where it ends; *total render time* is "time spent
by GPU rendering". With frame generation the test's own columns split the GPU's part at "DLSS FG start". **Not
reconciled with what is stored**: an OS queue that ends with the GPU's work should not be shorter than the
GPU's span, and in Phantom Blade Zero it is (12.9 ms beside 16.4 ms). The guide's table describes an overlay,
not the fields of `NV_LATENCY_RESULT_PARAMS`; nothing is concluded from it, and no label was changed on it.
- **Where Reflex helps**, by the guide: GPU-bound, or V-Sync with variable refresh; not CPU-bound. FrameLedger
shows the driver's switches and draws no conclusion about benefit.
**DLSS Ray Reconstruction**
- **The code already has it right, and two comments had the reason wrong.** The guide: "When DLSS-RR is switched
on, it completely overrides DLSS (Super Resolution)", in the quality mode set for DLSS, through
`slEvaluateFeature(sl::kFeatureDLSS_RR, …)`. That is the present detour's RR arm (upscaler DLSS, the RR fact
beside it), measured on Cyberpunk 2077 on 2026-08-15. `fl_shm.h` and `dllmain.cpp` still said super resolution
and RR "run together" / "in the SAME frame"; they do not, and the comments now say what is true.
- **Off is a mode, not a release**: "set `sl::DLSSDOptions.mode` to `sl::DLSSDMode::eOff`, note that this does
NOT release any resources". So *loaded* and *allocated* (the Advanced tables of 0.1.0-beta.45) are not *in
use*; the RR verdict is taken from evaluations and from nothing else, which is why it is right.
- **If `sl.dlssd.options` is ever read** (it is a spike entry, set through a call no hook sees): the structure
carries `worldToCameraView` and `cameraViewToWorld` — camera matrices, never read (rule 4) — and RR ignores the
DLSS options `sharpness` and `useAutoExposure`, so a session's DLSS rows do not describe RR on those two.
What the entry would add is RR's preset for each mode and how normals and roughness are packed. Little.
- **No dynamic resolution under RR**: a change of input size re-initialises the denoiser. Nothing here depends
on it.
+26 -11
View File
@@ -85,20 +85,31 @@ under which of the three happened to each.
### What NVIDIA's driver says about each frame's stages
On an NVIDIA card, in a **Direct3D 12** game that uses **NVIDIA Reflex**, a session with Advanced metrics on also
stores the driver's own latency report: how long the driver says each stage of a frame took — *simulation*,
On an NVIDIA card, in a **Direct3D 12** game that has **NVIDIA Reflex** built in, a session with Advanced metrics
on also stores the driver's own latency report — whether Reflex is on or off in the game's menu, because a game
with Reflex marks its frames either way: how long the driver says each stage of a frame took — *simulation*,
*render submit*, *present*, *driver*, *operating system's render queue*, *GPU render*, and the *total* from the start
of simulation to the end of the graphics card's work. They are seven lines under **Latency**, one point about every
second, each the average of the frames of one reading, in microseconds. A table beside them shows the driver's
low-latency state as five switches, by NVIDIA's own names, each *On*, *Off* or *On at times, off at others*, and
`fgMultiplier`: every frame-generation multiplier the driver gave during the session (*1, 2* is a session that
generated frames at ×2 for part of it).
generated frames at ×2 for part of it). **They are the driver's switches, not the game's menu.** `bLowLatencyMode`
is on when the game switched Reflex on *and* when **Low Latency Mode** is set for that game in the NVIDIA App —
an override there shows here, and can read *On at times, off at others* in a game whose own setting never
changed. `bUseGameSleep` says whether the game calls Reflex's sleep each frame. NVIDIA asks games to call it even
while Reflex is off, so *On* there does not say Reflex is on — `bLowLatencyMode` does; some games call it only
while frame generation is on. Frame generation needs Reflex and not the other way round: the mode can be on
with `fgMultiplier` at 1.
**The stages overlap; they are not parts that add up to the total.** And *GPU render, start to end* includes the
time the card spent waiting between pieces of work — in one game it is longer than the whole frame. So a second
chart, **the graphics card's time per frame, as the driver works it out**, has two lines of the driver's own
figures: *GPU active render*, the same stage without the waiting, and *GPU frame time*, from the end of one
frame's work to the end of the next. A driver may give neither; the chart is then not there, and nothing is wrong.
**The stages overlap; they are not parts that add up to the total.** And *GPU render* is the time between two
marks the driver sets, at the start and at the end of the card's work on a frame: where the card waits between
pieces of work, the waiting is in it — in one game it is longer than the whole frame. So a second chart, **the
graphics card's time per frame, as the driver works it out**, has two lines of the driver's own figures: *GPU
active render*, how long the driver says the card worked on the frame, and *GPU frame time*, from the end of one
frame's work to the end of the next. **The active time is usually the shorter of the two, and not always**: in
Cyberpunk 2077 without frame generation it is about a fifth longer than the two marks are apart, frame after
frame — the driver counts work its marks do not enclose. Both are shown as the driver gives them. A driver may
give neither; the chart is then not there, and nothing is wrong.
Three things to know about them:
@@ -144,10 +155,14 @@ comes from, and whether it is read. Where it is not, the reason is written out:
administrator*);
- **not present on this PC** — the driver's own figures exist on NVIDIA cards only;
- **read inside a game FrameLedger measures, when the game makes the call** — what the game tells DLSS and FSR
(above). Some further readings inside the game **come with a later release**;
(above);
- **read inside a game FrameLedger measures, from the graphics driver** — NVIDIA's latency report (above);
- **not read: it would take a patch at an address found while the game runs, or a call the vendor forbids from
outside the game's own threads** — what the game asked of Reflex, and Reflex's state through Streamline;
- **not read: it would take a patch at an address found while the game runs, a function of FrameLedger's handed
to the game in place of the vendor's, or a call the vendor forbids from outside the game's own threads** — what
the game asked of Reflex, Reflex's state through Streamline, and what a game sets and asks through Streamline's
own functions for a feature: DLSS frame generation's options and state, the video memory DLSS estimates for
itself, and the options of ray reconstruction, Image Scaling and Dynamic Vibrance. No later release will read
these;
- **the game makes this call once, before FrameLedger is inside it** — what the game started Streamline with. It is
not read, and no later release will read it;
- **never read** — a serial number, a display's identification data, which other programs are encoding, the camera's
+1 -1
View File
@@ -12,7 +12,7 @@
HTML comments are not part of the block.
-->
> ⚠ **What FrameLedger actually measures today — 2026-11-11.** The software is a beta; its latest
> **beta is `0.1.0-beta.48`** (2026-11-14), an unsigned installer built from that tag with its
> **beta is `0.1.0-beta.49`** (2026-11-14), an unsigned installer built from that tag with its
> checksums published beside it (alphas — experimental builds that try a newer .NET — are published apart). The source holds the desktop app
> (library, store import, charts, settings) and the background Agent, which records a session when a
> game in the library runs (unless you switched its recording off), injects only into games you enabled
+1 -1
View File
@@ -125,7 +125,7 @@ Frame timing is derived from high-resolution timestamps taken at the moment the
<!-- accuracy-block:begin -->
> ⚠ **What FrameLedger actually measures today — 2026-11-11.** The software is a beta; its latest
> **beta is `0.1.0-beta.48`** (2026-11-14), an unsigned installer built from that tag with its
> **beta is `0.1.0-beta.49`** (2026-11-14), an unsigned installer built from that tag with its
> checksums published beside it (alphas — experimental builds that try a newer .NET — are published apart). The source holds the desktop app
> (library, store import, charts, settings) and the background Agent, which records a session when a
> game in the library runs (unless you switched its recording off), injects only into games you enabled
+3 -3
View File
@@ -958,7 +958,7 @@
<comment>review</comment>
</data>
<data name="AdvReach_RefusedRoute" xml:space="preserve">
<value>読み取りません: ゲーム実行中にしか分からないアドレスへのパッチ、またはゲーム自身のスレッド以外からの呼び出しをベンダーが禁じている関数が必要になるためです - どちらも行いません</value>
<value>読み取りません: ゲーム実行中にしか分からないアドレスへのパッチ、ベンダーの関数の代わりに FrameLedger の関数をゲームに渡すこと、またはゲーム自身のスレッド以外からの呼び出しをベンダーが禁じている関数が必要になるためです - いずれも行いません</value>
<comment>review</comment>
</data>
<data name="AdvReach_Spike" xml:space="preserve">
@@ -1054,7 +1054,7 @@
<comment>review</comment>
</data>
<data name="AdvToken_active_render" xml:space="preserve">
<value>GPU 実描画 (待機時間を除く)</value>
<value>GPU 実描画 (ドライバーの算出値)</value>
<comment>review</comment>
</data>
<data name="AdvToken_frame_time" xml:space="preserve">
@@ -1062,7 +1062,7 @@
<comment>review</comment>
</data>
<data name="AdvToken_gpu_render" xml:space="preserve">
<value>GPU 描画、開始から終了まで (待機時間を含む)</value>
<value>GPU 描画 (ドライバーの開始マークから終了マークまで)</value>
<comment>review</comment>
</data>
<data name="AdvToken_gsync_module" xml:space="preserve">
+3 -3
View File
@@ -724,7 +724,7 @@
<value>Not read: it would make the sensor library search every USB device</value>
</data>
<data name="AdvReach_RefusedRoute" xml:space="preserve">
<value>Not read: it would take a patch at an address found while the game runs, or a call the vendor forbids from outside the game's own threads - both refused</value>
<value>Not read: it would take a patch at an address found while the game runs, a function of FrameLedger's handed to the game in place of the vendor's, or a call the vendor forbids from outside the game's own threads - all refused</value>
</data>
<data name="AdvReach_Spike" xml:space="preserve">
<value>Being studied; not decided</value>
@@ -796,13 +796,13 @@
<value>Game Ready</value>
</data>
<data name="AdvToken_active_render" xml:space="preserve">
<value>GPU active render (idle time excluded)</value>
<value>GPU active render (the driver's own figure)</value>
</data>
<data name="AdvToken_frame_time" xml:space="preserve">
<value>GPU frame time, one frame's end to the next</value>
</data>
<data name="AdvToken_gpu_render" xml:space="preserve">
<value>GPU render, start to end (idle time included)</value>
<value>GPU render (between the driver's start and end marks)</value>
</data>
<data name="AdvToken_gsync_module" xml:space="preserve">
<value>G-SYNC module</value>
+3 -3
View File
@@ -719,7 +719,7 @@
<value>Không đọc: việc này khiến thư viện cảm biến dò mọi thiết bị USB</value>
</data>
<data name="AdvReach_RefusedRoute" xml:space="preserve">
<value>Không đọc: việc đó cần vá mã tại một địa chỉ chỉ tìm được khi game đang chạy, hoặc một lời gọi mà nhà cung cấp cấm thực hiện từ ngoài luồng của game - cả hai đều bị từ chối</value>
<value>Không đọc: việc đó cần vá mã tại một địa chỉ chỉ tìm được khi game đang chạy, hoặc đưa cho game một hàm của FrameLedger thay cho hàm của nhà cung cấp, hoặc một lời gọi mà nhà cung cấp cấm thực hiện từ ngoài luồng của game - tất cả đều bị từ chối</value>
</data>
<data name="AdvReach_Spike" xml:space="preserve">
<value>Đang nghiên cứu; chưa quyết định</value>
@@ -791,13 +791,13 @@
<value>Game Ready</value>
</data>
<data name="AdvToken_active_render" xml:space="preserve">
<value>GPU thực sự vẽ (không tính lúc nghỉ)</value>
<value>GPU thực sự vẽ (số do driver tự tính)</value>
</data>
<data name="AdvToken_frame_time" xml:space="preserve">
<value>nhịp khung của GPU, từ lúc xong khung này tới lúc xong khung kế</value>
</data>
<data name="AdvToken_gpu_render" xml:space="preserve">
<value>GPU vẽ, từ lúc bắt đầu tới lúc xong (gồm cả lúc nghỉ)</value>
<value>GPU vẽ (giữa mốc bắt đầu và mốc kết thúc của driver)</value>
</data>
<data name="AdvToken_gsync_module" xml:space="preserve">
<value>Mô-đun G-SYNC</value>
@@ -193,20 +193,24 @@ public static class AdvancedMetricCatalog
// its two GPU marks includes the card's idle time and was longer than a frame's whole in a real game.
SampledFamily("nvapi.reflex.gpu_times", Nvapi, GameDriver, Microseconds, Latency, "The graphics card's time per frame, as the driver works it out: active render, frame to frame"),
// ---- Inside the game: routes a spike decides ------------------------------------------------------------
Session("sl.dlss.optimal_settings", Streamline, Spike, Text, Upscaling, "The render size and sharpness DLSS recommends"),
Sampled("sl.dlss.vram_estimate", Streamline, Spike, Mebibytes, Upscaling, "DLSS's own estimate of its video memory"),
Session("sl.dlssg.options", Streamline, Spike, Text, FrameGeneration, "DLSS frame generation: mode, frames to generate"),
Session("sl.dlssg.state", Streamline, Spike, Text, FrameGeneration, "DLSS frame generation: status, the most frames it can generate"),
Sampled("sl.dlssg.frames_presented", Streamline, Spike, Count, FrameGeneration, "Frames DLSS frame generation presented, by its own count"),
Sampled("sl.dlssg.vram_estimate", Streamline, Spike, Mebibytes, FrameGeneration, "DLSS frame generation's estimate of its video memory"),
Session("sl.dlssd.options", Streamline, Spike, Text, Upscaling, "Ray reconstruction's options"),
Session("sl.nis.options", Streamline, Spike, Text, Upscaling, "NVIDIA Image Scaling's options"),
Session("sl.deepdvc.options", Streamline, Spike, Text, Upscaling, "RTX Dynamic Vibrance's options"),
// ---- Inside the game: Streamline's feature functions - not read ---------------------------------------
// Advanced metrics is closed (owner decision D154, 2026-11-14). None of these is an export: a game gets each
// function through slGetFeatureFunction and keeps the pointer, so seeing its calls would take handing the game
// a function of ours in place of Streamline's - a write to what the game receives (rule 4) - and would still
// miss every game that fetched its functions before the attach. They stay listed, with the reason.
Session("sl.dlss.optimal_settings", Streamline, RefusedRoute, Text, Upscaling, "The render size and sharpness DLSS recommends"),
Sampled("sl.dlss.vram_estimate", Streamline, RefusedRoute, Mebibytes, Upscaling, "DLSS's own estimate of its video memory"),
Session("sl.dlssg.options", Streamline, RefusedRoute, Text, FrameGeneration, "DLSS frame generation: mode, frames to generate"),
Session("sl.dlssg.state", Streamline, RefusedRoute, Text, FrameGeneration, "DLSS frame generation: status, the most frames it can generate"),
Sampled("sl.dlssg.frames_presented", Streamline, RefusedRoute, Count, FrameGeneration, "Frames DLSS frame generation presented, by its own count"),
Sampled("sl.dlssg.vram_estimate", Streamline, RefusedRoute, Mebibytes, FrameGeneration, "DLSS frame generation's estimate of its video memory"),
Session("sl.dlssd.options", Streamline, RefusedRoute, Text, Upscaling, "Ray reconstruction's options"),
Session("sl.nis.options", Streamline, RefusedRoute, Text, Upscaling, "NVIDIA Image Scaling's options"),
Session("sl.deepdvc.options", Streamline, RefusedRoute, Text, Upscaling, "RTX Dynamic Vibrance's options"),
// A refused route (owner decision D133): the Overlay calling slReflexGetState itself breaks the thread
// contract the vendor's header states.
Session("sl.reflex.state", Streamline, RefusedRoute, Table, Latency, "Reflex through Streamline: availability and its frame reports"),
Sampled("sl.pcl.markers", Streamline, Spike, Count, Latency, "PC-latency markers the game sets"),
Sampled("sl.pcl.markers", Streamline, RefusedRoute, Count, Latency, "PC-latency markers the game sets"),
// ---- Closed by a licence --------------------------------------------------------------------------------
Session("ngx.parameters", Ngx, Licence, Table, Upscaling, "NGX parameters: the quality value, the DLSS hints"),
@@ -25,7 +25,10 @@ public enum AdvancedReach
/// <summary>Needs a hook on a function its module exports; the hook is not built. No entry carries it since 0.1.0-beta.45.</summary>
NewHook = 4,
/// <summary>A route nobody has proven safe: a spike decides, and the owner says go or no.</summary>
/// <summary>
/// A route nobody has proven safe: a spike decides, and the owner says go or no. No entry carries it since the
/// owner closed Advanced metrics (D154, 2026-11-14): the ten that did are <see cref="RefusedRoute"/>.
/// </summary>
Spike = 5,
/// <summary>A source the project decided not to open (D103).</summary>
@@ -70,7 +73,8 @@ public enum AdvancedReach
/// <summary>
/// Reading it needs a route the project refused, whatever the source: a patch at an address learned at run time
/// (what a game asks of Reflex is an argument of a function no module exports), or a call the vendor's own header
/// forbids from a thread that is not the game's (owner decision D133). Never read.
/// forbids from a thread that is not the game's (owner decision D133), or a function of ours handed to the game in
/// place of the vendor's (what a game sets and asks through Streamline's feature functions - D154). Never read.
/// </summary>
RefusedRoute = 15,
}
@@ -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,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;
}
@@ -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;
}
@@ -0,0 +1,62 @@
// 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.Advanced;
namespace FrameLedger.Application.Recording;
/// <summary>
/// What a hooked game published and no telemetry sample carries yet (owner decision D150): at most
/// <see cref="Capacity"/> sets of readings, the older taken first.
/// </summary>
/// <remarks>
/// <para>
/// <b>Why not one.</b> A publication arrives about once a second and a sample exactly once a second, on two clocks,
/// and the recorder looks at both every tenth of a second or so. Until 0.1.0-beta.49 it kept the newest set and
/// overwrote it: when a publication landed just after a sample, a look could fall between the two - that sample went
/// without, and at the next change of step the set that had waited was overwritten by its successor. In the owner's
/// sessions that was one sample in five without a report for minutes on end (HANDOFF, item 46).
/// </para>
/// <para>
/// <b>What two give.</b> A set that waited is carried by the next sample instead of being replaced, so with both sides
/// on a second a session lacks a report at one sample at most - the first time the two fall out of step - and loses
/// none after it. A reading then stands at the sample after the one it would have ridden: a second later, no more.
/// </para>
/// <para>
/// <b>What it does not give.</b> With the sensor interval above a second more sets arrive than samples: a third
/// pushes the oldest out, and not every reading is stored - as before, and as the guide says.
/// </para>
/// </remarks>
public sealed class PendingInGameReadings
{
/// <summary>The most sets that wait: the one a sample is about to carry, and the one that arrived meanwhile.</summary>
public const int Capacity = 2;
private readonly Queue<IReadOnlyList<AdvancedReading>> _waiting = new(Capacity);
/// <summary>How many sets wait.</summary>
public int Count => _waiting.Count;
/// <summary>A publication's readings. A set with nothing in it does not wait: it would only stand in a real one's way.</summary>
/// <param name="readings">The readings of one publication.</param>
public void Offer(IReadOnlyList<AdvancedReading> readings)
{
ArgumentNullException.ThrowIfNull(readings);
if (readings.Count == 0)
{
return;
}
if (_waiting.Count == Capacity)
{
_ = _waiting.Dequeue();
}
_waiting.Enqueue(readings);
}
/// <summary>The oldest set that waits, which then waits no longer; false when none does.</summary>
/// <param name="readings">The set, when there is one.</param>
public bool TryTake([NotNullWhen(true)] out IReadOnlyList<AdvancedReading>? readings) => _waiting.TryDequeue(out readings);
}
@@ -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.
@@ -374,7 +374,7 @@ public sealed class SessionRecorder : ISessionRecorder
// What the game told its upscaler (train B): read inside the game by the Overlay, only for a session that
// records Advanced metrics - the same condition the shared reader is held under.
private readonly InGameAdvancedSampler? _inGame = advanced is null ? null : new InGameAdvancedSampler();
private IReadOnlyList<AdvancedReading>? _inGamePending;
private readonly PendingInGameReadings _inGamePending = new();
private (IReadOnlyList<AdvancedFact> Facts, AdvancedInGameStatus Status, InGameCallStates Calls) _inGameContext =
([], AdvancedInGameStatus.Unknown, default);
private IReadOnlyList<AdvancedFact> _sessionWithGame = [];
@@ -417,8 +417,9 @@ public sealed class SessionRecorder : ISessionRecorder
FollowAdapter(progress.AdapterLuid);
if (_inGame?.Take(progress.InGameAdvanced) is { } fresh)
{
// The newest stands until a telemetry sample carries it: both arrive once a second, out of step.
_inGamePending = fresh;
// It waits until a telemetry sample carries it: both arrive once a second, out of step - and it is no
// longer replaced by the one after it (owner decision D150; PendingInGameReadings says why).
_inGamePending.Offer(fresh);
}
DrainTelemetry();
@@ -631,13 +632,12 @@ public sealed class SessionRecorder : ISessionRecorder
_drained.Clear();
poller.Drain(_drained);
if (_inGamePending is { } pending && _drained.Count > 0)
if (_drained.Count > 0 && _inGamePending.TryTake(out IReadOnlyList<AdvancedReading>? pending))
{
// What the game said rides the newest sample of this drain, beside whatever the Agent's own reader
// gave it: one tick, one set of readings.
// gave it: one tick, one set of readings - the oldest that waits.
TelemetrySample newest = _drained[^1];
_drained[^1] = newest with { Advanced = newest.Advanced is { Count: > 0 } own ? [.. own, .. pending] : pending };
_inGamePending = null;
}
writer.AddSensors(_drained);
@@ -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)
+1 -1
View File
@@ -852,7 +852,7 @@ public enum FlLatencyState : uint
/// <summary>A getter faulted: off until the game exits.</summary>
Faulted = 8,
/// <summary>A call had not returned after a second: nothing can stop it.</summary>
/// <summary>A call had not returned after two seconds: nothing can stop it.</summary>
Stalled = 9,
}
@@ -675,12 +675,33 @@ inline void ObserveSlShutdown(Accumulators& a) noexcept {
// ---------------------------------------------------------------------------------------------------------------------
inline constexpr uint32_t kLatSpans =
7u; // simulation, submit, present, driver, OS queue, GPU, total: the region's order
inline constexpr uint32_t kLatGpu = 5u;
inline constexpr uint32_t kLatTotal = 6u;
inline constexpr uint32_t kLatReportFrames = 64u;
inline constexpr uint64_t kLatSpanLimitUs = 1000000u;
static_assert(sizeof(NV_LATENCY_RESULT_PARAMS::frameReport) / sizeof(NV_LATENCY_RESULT_PARAMS::FrameReport) ==
kLatReportFrames);
// HOW A FRAME'S GPU SPAN AND THE DRIVER'S ACTIVE TIME STAND TO EACH OTHER (0.1.0-beta.49, owner decision D148). In one
// real game the mean active time was LONGER than the mean span between the two GPU marks (HANDOFF, item 46), and the
// two means cannot say why: the span's is over every summed frame, one of no length included, the active time's over
// the frames that gave one. So each summed frame is put in one place here, by its own two numbers, and the frames
// that have both are kept in two heaps -- the active time longer than the span, or not -- each with its count and
// both sums. No threshold: a span of one microsecond is a span. FOR THE NATIVE LOG ONLY: nothing of it is published,
// and which frames are summed does not depend on it.
struct LatencyGpuCounts {
uint32_t spanAbsent = 0; // no GPU start mark
uint32_t spanZero = 0; // the two GPU marks are the same instant
uint32_t activeNoSpan = 0; // an active time, and no span with a length
uint32_t spanNoActive = 0; // a span with a length, and no active time
uint32_t longerFrames = 0; // both, and the active time is the LONGER
uint32_t longerSpanUs = 0; // ... their spans
uint32_t longerActiveUs = 0; // ... their active times
uint32_t withinFrames = 0; // both, and the active time is no longer than the span
uint32_t withinSpanUs = 0;
uint32_t withinActiveUs = 0;
};
// What one read of the report added up to.
struct LatencyTally {
uint32_t frames = 0; // frames summed
@@ -688,10 +709,11 @@ struct LatencyTally {
uint32_t sumUs[kLatSpans]{}; // microseconds, over the frames summed
uint32_t lacking = 0; // bit n: a summed frame did not report span n
// The driver's two own times, each over the summed frames that gave one: a count apiece.
uint32_t activeSumUs = 0;
uint32_t activeFrames = 0;
uint32_t frameTimeSumUs = 0;
uint32_t frameTimeFrames = 0;
uint32_t activeSumUs = 0;
uint32_t activeFrames = 0;
uint32_t frameTimeSumUs = 0;
uint32_t frameTimeFrames = 0;
LatencyGpuCounts gpu; // the summed frames, each by its GPU span and its active time: the native log's
};
// Where the reader is in the game's frame ids: the newest one already summed or refused. 0 = none yet.
@@ -728,13 +750,45 @@ inline uint64_t LatencyFrameId(const NV_LATENCY_RESULT_PARAMS::FrameReport& lf)
// (an older driver leaves both zero, and so did the probe's frames, which had no work for the card); more than a
// second is a time no frame can have. Neither is summed, and neither refuses the frame: which frames the spans are
// made of does not depend on these.
inline bool LatencyTimeGiven(uint32_t us) noexcept {
return us != 0u && us <= kLatSpanLimitUs;
}
inline void LatencyAddTime(uint32_t us, uint32_t& sumUs, uint32_t& frames) noexcept {
if (us != 0u && us <= kLatSpanLimitUs) {
if (LatencyTimeGiven(us)) {
sumUs += us;
++frames;
}
}
// One summed frame's place in LatencyGpuCounts: its GPU span as LatencySpan gave it, and the driver's active time
// of the same frame, "given" by the rule LatencyAddTime sums it by. An impossible span never comes here -- its frame
// was refused.
inline void CountGpuTimes(uint32_t spanKind, uint32_t spanUs, uint32_t activeUs, LatencyGpuCounts& counts) noexcept {
const bool span = spanKind == kLatSpanReported && spanUs != 0u;
const bool active = LatencyTimeGiven(activeUs);
if (spanKind == kLatSpanAbsent) {
++counts.spanAbsent;
} else if (spanUs == 0u) {
++counts.spanZero;
}
if (span && active) {
if (activeUs > spanUs) {
++counts.longerFrames;
counts.longerSpanUs += spanUs;
counts.longerActiveUs += activeUs;
} else {
++counts.withinFrames;
counts.withinSpanUs += spanUs;
counts.withinActiveUs += activeUs;
}
} else if (active) {
++counts.activeNoSpan;
} else if (span) {
++counts.spanNoActive;
}
}
inline void ObserveLatencyFrame(const NV_LATENCY_RESULT_PARAMS::FrameReport& lf, LatencyTally& tally) noexcept {
uint32_t us[kLatSpans]{};
const uint32_t kind[kLatSpans] = {
@@ -764,6 +818,7 @@ inline void ObserveLatencyFrame(const NV_LATENCY_RESULT_PARAMS::FrameReport& lf,
}
LatencyAddTime(lf.gpuActiveRenderTimeUs, tally.activeSumUs, tally.activeFrames);
LatencyAddTime(lf.gpuFrameTimeUs, tally.frameTimeSumUs, tally.frameTimeFrames);
CountGpuTimes(kind[kLatGpu], us[kLatGpu], lf.gpuActiveRenderTimeUs, tally.gpu);
}
// One report: the frames newer than the cursor, the two newest left for the next read.
@@ -825,6 +880,154 @@ inline uint32_t LatencyMultiplierBit(uint32_t value) noexcept {
return 1u << (value > 31u ? 31u : value);
}
// ---------------------------------------------------------------------------------------------------------------------
// THE COUNTS, IN BATCHES, FOR THE NATIVE LOG (0.1.0-beta.49, owner decisions D148, D151). The watchdog's.
//
// A BATCH BELONGS TO ONE STATE of the driver's sleep status -- its low-latency switch, its "the game sleeps" switch
// and its frame-generation multiplier -- because the counts mean nothing apart from it: the owner's games switch
// Reflex on only with frame generation, and the low-latency switch may be the NVIDIA App's override and not the
// game's. A read in another state closes the batch before it is added. A state that flickers would write a batch a
// read, so after kLatStateClosures such closings a request's batches run to their length whatever the state, and the
// "seen" words of the batch say what it held.
//
// A batch is also closed after the request's tenth read, its thirtieth, and every sixtieth from there: a game that
// exits takes the watchdog with it, and what was not written by then is lost -- under a minute of it.
//
// AND HOW EVENLY THE READS CAME (owner decision D150): the milliseconds the batch spans and the watchdog's ticks in
// them, periodic and woken early. A read a second is a thousand milliseconds a read and as many periodic ticks as
// reads; anything else says which side of it was uneven.
// ---------------------------------------------------------------------------------------------------------------------
inline constexpr uint32_t kLatBatchFirst = 10u;
inline constexpr uint32_t kLatBatchSecond = 30u;
inline constexpr uint32_t kLatBatchEvery = 60u;
inline constexpr uint32_t kLatStateClosures = 32u;
inline constexpr uint32_t kLatStateUnknown = 0xFFFFFFFFu; // a read whose sleep status did not come back
inline constexpr uint32_t kLatStateSwitches = 1u | 8u; // bLowLatencyMode, bUseGameSleep (ObserveSleepStatus)
struct LatencyBatch {
uint32_t reads = 0; // reads whose report came back, in this batch
uint32_t frames = 0; // frames they summed
uint32_t refused = 0; // frames they refused
LatencyGpuCounts gpu;
uint32_t sleepOn = 0; // switches the status showed on in this batch
uint32_t sleepOff = 0; // ... and off
uint32_t multipliers = 0; // LatencyMultiplierBit of every multiplier it gave
uint32_t state = kLatStateUnknown; // LatencyStateOf its first read
// The watchdog's own, set by it: not a read's.
uint32_t spannedMs = 0; // from the batch before -- or the request -- to this one's writing
uint32_t ticksOnTime = 0; // its periodic ticks in that time
uint32_t ticksEarly = 0; // ... and the ticks something woke early
};
struct LatencyBatchBook {
LatencyBatch batch;
uint32_t okReads = 0; // reads whose report came back, since the request
uint32_t closures = 0; // batches a change of state closed, since the request
};
inline uint32_t LatencyStateOf(bool sleepValid, const LatencySleep& sleep) noexcept {
if (!sleepValid) {
return kLatStateUnknown;
}
return (sleep.on & kLatStateSwitches) | ((sleep.multiplier > 255u ? 255u : sleep.multiplier) << 8);
}
// Whether the batch is to be written BEFORE a read in `state` is added to it.
inline bool LatencyBatchTurns(const LatencyBatchBook& book, uint32_t state) noexcept {
return book.batch.reads != 0u && book.batch.state != state && book.closures < kLatStateClosures;
}
// Whether the batch is to be written AFTER the request's okReads-th read was added.
inline bool LatencyBatchDue(uint32_t okReads) noexcept {
if (okReads <= kLatBatchSecond) {
return okReads == kLatBatchFirst || okReads == kLatBatchSecond;
}
return (okReads - kLatBatchSecond) % kLatBatchEvery == 0u;
}
// A batch is sixty reads of sixty-two frames at most, and a time is a second at most: under 2^32 microseconds. The
// sums stop there all the same, so that a word never wraps into a small number.
inline void LatencyAddStop(uint32_t& sum, uint32_t value) noexcept {
sum = value > 0xFFFFFFFFu - sum ? 0xFFFFFFFFu : sum + value;
}
inline void LatencyBatchAdd(LatencyBatchBook& book, const LatencyTally& tally, bool sleepValid,
const LatencySleep& sleep) noexcept {
LatencyBatch& batch = book.batch;
if (batch.reads == 0u) {
batch.state = LatencyStateOf(sleepValid, sleep);
}
++batch.reads;
++book.okReads;
LatencyAddStop(batch.frames, tally.frames);
LatencyAddStop(batch.refused, tally.refused);
LatencyAddStop(batch.gpu.spanAbsent, tally.gpu.spanAbsent);
LatencyAddStop(batch.gpu.spanZero, tally.gpu.spanZero);
LatencyAddStop(batch.gpu.activeNoSpan, tally.gpu.activeNoSpan);
LatencyAddStop(batch.gpu.spanNoActive, tally.gpu.spanNoActive);
LatencyAddStop(batch.gpu.longerFrames, tally.gpu.longerFrames);
LatencyAddStop(batch.gpu.longerSpanUs, tally.gpu.longerSpanUs);
LatencyAddStop(batch.gpu.longerActiveUs, tally.gpu.longerActiveUs);
LatencyAddStop(batch.gpu.withinFrames, tally.gpu.withinFrames);
LatencyAddStop(batch.gpu.withinSpanUs, tally.gpu.withinSpanUs);
LatencyAddStop(batch.gpu.withinActiveUs, tally.gpu.withinActiveUs);
if (sleepValid) {
batch.sleepOn |= sleep.on & FL_LAT_SLEEP_BITS;
batch.sleepOff |= ~sleep.on & FL_LAT_SLEEP_BITS;
batch.multipliers |= LatencyMultiplierBit(sleep.multiplier);
}
}
// The batch as lines of the native log: a text, the line's `a` (printed in decimal) and its `b` (printed in hex).
inline constexpr uint32_t kLatBatchLines = 7u;
struct LatencyLogLine {
const char* text;
uint32_t a;
uint64_t b;
};
constexpr uint64_t LatencyPair(uint32_t high, uint32_t low) noexcept {
return (static_cast<uint64_t>(high) << 32) | low;
}
constexpr LatencyLogLine LatencyBatchLine(const LatencyBatch& batch, uint32_t line) noexcept {
switch (line) {
case 0u:
return {"reads / sleep switches on | off<<8 | multipliers seen<<16", batch.reads,
batch.sleepOn | (batch.sleepOff << 8) | (static_cast<uint64_t>(batch.multipliers) << 16)};
case 1u:
return {"frames summed / refused", batch.frames, batch.refused};
case 2u:
return {"GPU span absent / of no length", batch.gpu.spanAbsent, batch.gpu.spanZero};
case 3u:
return {"active time with no span / span with no active time", batch.gpu.activeNoSpan, batch.gpu.spanNoActive};
case 4u:
return {"active longer than span: frames / span us<<32 | active us", batch.gpu.longerFrames,
LatencyPair(batch.gpu.longerSpanUs, batch.gpu.longerActiveUs)};
case 5u:
return {"active within span: frames / span us<<32 | active us", batch.gpu.withinFrames,
LatencyPair(batch.gpu.withinSpanUs, batch.gpu.withinActiveUs)};
default:
return {"ms spanned / watchdog ticks on time<<32 | woken early", batch.spannedMs,
LatencyPair(batch.ticksOnTime, batch.ticksEarly)};
}
}
// The longest of those texts, for whoever writes them into a line of fixed length.
constexpr uint32_t LatencyBatchLongestText() noexcept {
uint32_t longest = 0u;
for (uint32_t line = 0u; line < kLatBatchLines; ++line) {
const char* text = LatencyBatchLine(LatencyBatch{}, line).text;
uint32_t length = 0u;
while (text[length] != '\0') {
++length;
}
longest = length > longest ? length : longest;
}
return longest;
}
// What the watchdog publishes of it. THE WATCHDOG'S: filled from what a read left behind while nobody is reading.
struct LatencyOut {
uint32_t state = FL_LAT_NONE; // FlLatencyState
@@ -0,0 +1,64 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
// When the Overlay's watchdog makes its PERIODIC tick (0.1.0-beta.49, owner decision D150).
//
// WHAT WAS WRONG. The watchdog waited a second AFTER each tick's work, so its ticks were a second and that work
// apart -- and a tick the LoadLibrary detour woke early counted as a tick like any other. The driver's latency
// report is read once for each tick that arms it, and region 5 is published once a tick; the Agent samples on a
// period of exactly one second. So the Overlay fell behind the Agent a little with every tick, a woken tick took a
// read and armed none, and a session's samples had holes: 0.4 to 16 % of them carried no report (HANDOFF, item 46).
//
// WHAT THIS IS. A grid in performance-counter ticks: the periodic tick is due at a deadline, and the next deadline is
// one period after the one that was due -- not after the moment the tick ran, so nothing accumulates. A tick woken
// early is still a tick (the loader's signals must be acted on at once) but not a periodic one: it does not move the
// grid. A periodic tick that ran more than half a period late does not get a second one right behind it: the grid
// starts again from that tick, so two periodic ticks are never less than half a period apart.
//
// Pure arithmetic, no call: the watchdog's loop (dllmain.cpp) is the only user, and fl_watchdog_tick_test drives it
// without a thread.
#ifndef FRAMELEDGER_FL_WATCHDOG_TICK_H
#define FRAMELEDGER_FL_WATCHDOG_TICK_H
#include <cstdint>
namespace fl::watchdog {
struct Grid {
int64_t period = 1; // performance-counter ticks between two periodic ticks
int64_t deadline = 0; // the counter value the next periodic tick is due at
};
inline void StartGrid(Grid& grid, int64_t now, int64_t period) noexcept {
grid.period = period > 0 ? period : 1;
grid.deadline = now + grid.period;
}
// How long to wait for the periodic tick, in whole milliseconds ROUNDED UP -- a wait rounded down ends before the
// deadline and would have to be followed by another of a millisecond -- and never more than `ceilingMs`. Zero when
// the tick is due.
inline uint32_t WaitMs(const Grid& grid, int64_t now, int64_t frequency, uint32_t ceilingMs) noexcept {
if (now >= grid.deadline || frequency <= 0) {
return 0u;
}
const int64_t ms = ((grid.deadline - now) * 1000 + frequency - 1) / frequency;
return ms > static_cast<int64_t>(ceilingMs) ? ceilingMs : static_cast<uint32_t>(ms);
}
// Whether the tick that begins at `now` is the periodic one. A wait that timed out is: Windows counts a timeout in
// its own clock's ticks, so it may end a little short of the deadline by this counter, and that tick is the one the
// wait was for. A wait a signal ended is periodic only when the deadline has passed all the same.
inline bool IsPeriodic(const Grid& grid, int64_t now, bool timedOut) noexcept {
return timedOut || now >= grid.deadline;
}
// The grid after a periodic tick that began at `now`.
inline void Advance(Grid& grid, int64_t now) noexcept {
const int64_t next = grid.deadline + grid.period;
grid.deadline = next - now < grid.period / 2 ? now + grid.period : next;
}
} // namespace fl::watchdog
#endif // FRAMELEDGER_FL_WATCHDOG_TICK_H
+104 -28
View File
@@ -61,6 +61,7 @@
#include <fl_sl_inputs.h>
#include <fl_sl_seen.h>
#include <fl_tolerance.h>
#include <fl_watchdog_tick.h>
#include <knownfolders.h>
#include <MinHook.h>
#include <shlobj_core.h>
@@ -143,7 +144,10 @@ void PublishHandshake() noexcept {
// the log that should have said which hooks went in and what they were handed
// ended before the game had loaded its upscaler. Events are few and bounded
// (installs, a handful of first sights, three faults at most), so this is a few
// appends per session, on the watchdog's own tick.
// appends per session, on the watchdog's own tick -- and, since 0.1.0-beta.49,
// six lines a batch of the driver read's frame counts (LATENCY_FRAMES: a batch
// a minute at most once a session is under way), only while a session asks for
// Advanced metrics and the driver is being read.
// ---------------------------------------------------------------------------
enum FlLogCode : uint32_t {
kLogRingCreated = 1,
@@ -166,6 +170,7 @@ enum FlLogCode : uint32_t {
kLogFfxConfigureType,
kLogPatchBatch,
kLogLatency,
kLogLatencyFrames,
};
const char* LogCodeName(uint32_t code) noexcept {
@@ -210,6 +215,8 @@ const char* LogCodeName(uint32_t code) noexcept {
return "PATCH_BATCH";
case kLogLatency:
return "LATENCY";
case kLogLatencyFrames:
return "LATENCY_FRAMES";
default:
return "?";
}
@@ -227,6 +234,8 @@ struct FlLogEvent {
static_assert(sizeof(FlLogEvent) == 96, "the native log's event: 256 of them are static storage in a game's process");
static_assert(sizeof(fl::inventory::RowName::text) <= sizeof(FlLogEvent::text),
"a row's module!symbol name must fit an event's text, or two rows could log the same truncated name");
static_assert(fl::adv::LatencyBatchLongestText() < sizeof(FlLogEvent::text),
"a line of the driver read's frame counts must fit an event's text: LogNote cuts without saying so");
constexpr uint32_t kLogCapacity = 256;
FlLogEvent g_log[kLogCapacity]{};
@@ -750,10 +759,12 @@ void PublishD3D12Device(ID3D12Device* device) noexcept {
// Nothing is hooked for it and nothing is loaded for it.
//
// WHO DOES WHAT. The WATCHDOG finds the module and the two addresses, once for the process, and arms the gate at
// most once a second. A PRESENTING THREAD that finds the gate armed makes the read, after its frame's record is
// published: a call the driver holds stops the thread that made it, and the watchdog -- which supervises, installs
// and flushes -- must never be that thread (spike-notes §31, M2). So the call delays one present a second by its own
// length: 0.5-2.6 us measured, and one of 2 ms or more is the last one this process makes (D141).
// each of its PERIODIC ticks -- one a second on a grid, never two within half a second (fl_watchdog_tick.h; until
// 0.1.0-beta.49 "at most once a second", on ticks a second and their own work apart). A PRESENTING THREAD that finds
// the gate armed makes the read, after its frame's record is published: a call the driver holds stops the thread that
// made it, and the watchdog -- which supervises, installs and flushes -- must never be that thread (spike-notes §31,
// M2). So the call delays one present a second by its own length: 0.5-2.6 us measured, and one of 2 ms or more is the
// last one this process makes (D141).
//
// THE GATE, four states in one word, is what makes that safe without a lock:
// idle nobody is reading. g_latRead is the watchdog's: it takes what the last read left, then may arm.
@@ -801,9 +812,11 @@ fl::adv::LatencyOut g_latOut;
bool g_latResolved = false; // the two addresses are in g_latApi
bool g_latFinal = false; // the module was looked at and will not be read; g_latOut.state says why
bool g_latStalled = false;
int64_t g_latArmedQpc = 0;
int64_t g_latReadingSinceQpc = 0;
uint32_t g_latLoggedState = FL_LAT_NONE;
// The frame counts of the reads, for the native log only (fl_adv_fields.h; owner decisions D148, D151).
fl::adv::LatencyBatchBook g_latBook;
int64_t g_latBatchBeganQpc = 0; // the request's start, or the batch before's writing
// One read, on a presenting thread that found the gate armed. Not inlined: RecordPresent stays as small as it was.
__declspec(noinline) void ReadLatencyOnce() noexcept {
@@ -890,9 +903,34 @@ const char* LatencyStateName(uint32_t state) noexcept {
}
}
// THE WATCHDOG'S HALF, once a tick while a session asks. `now` is this tick's QPC.
// The batch of frame counts in hand, as LATENCY_FRAMES lines; nothing when no read is in it. The watchdog's: at the
// batch's end, when the Agent asks for a flush, at a new request and at a stop -- whatever a game that exits by
// itself had not had written by then is lost, under a minute of it.
void WriteLatencyBatch() noexcept {
if (g_latBook.batch.reads == 0u) {
return;
}
const int64_t now = QpcNow();
const uint64_t ticks = now > g_latBatchBeganQpc ? static_cast<uint64_t>(now - g_latBatchBeganQpc) : 0u;
const uint64_t millis = g_logQpcFreq != 0u ? ticks * 1000ull / g_logQpcFreq : 0u;
g_latBook.batch.spannedMs = millis > 0xFFFFFFFFull ? 0xFFFFFFFFu : static_cast<uint32_t>(millis);
for (uint32_t line = 0; line < fl::adv::kLatBatchLines; ++line) {
const fl::adv::LatencyLogLine entry = fl::adv::LatencyBatchLine(g_latBook.batch, line);
LogNote(kLogLatencyFrames, entry.text, entry.a, entry.b);
}
g_latBook.batch = fl::adv::LatencyBatch{};
g_latBatchBeganQpc = now;
}
// THE WATCHDOG'S HALF, once a PERIODIC tick while a session asks -- never on a tick something woke early, so that
// what it takes is the read its last call armed and what it arms is taken by its next (owner decision D150). `now`
// is this tick's QPC.
void TickLatency(bool newRequest, int64_t now) noexcept {
if (newRequest) {
// What the session before left of a batch is its own, written before this one's counts begin.
WriteLatencyBatch();
g_latBook = fl::adv::LatencyBatchBook{};
g_latBatchBeganQpc = now;
// A session's counts are its own; where the read stands is the process's and stays.
g_latOut.reads = 0u;
g_latOut.worstUs = 0u;
@@ -936,6 +974,16 @@ void TickLatency(bool newRequest, int64_t now) noexcept {
if (g_latRead.ok != 0u) {
g_latOut.tally = g_latRead.tally;
fl::adv::NoteBits(g_adv.validMask, FL_ADV_VALID_LATENCY);
// The same read's frames, counted for the log: a batch is of one state of the sleep status.
const bool sleepValid = g_latRead.sleepValid != 0u;
if (fl::adv::LatencyBatchTurns(g_latBook, fl::adv::LatencyStateOf(sleepValid, g_latRead.sleep))) {
WriteLatencyBatch();
++g_latBook.closures;
}
fl::adv::LatencyBatchAdd(g_latBook, g_latRead.tally, sleepValid, g_latRead.sleep);
if (fl::adv::LatencyBatchDue(g_latBook.okReads)) {
WriteLatencyBatch();
}
}
if (g_latRead.sleepValid != 0u) {
g_latOut.sleepSeenOn |= g_latRead.sleep.on & FL_LAT_SLEEP_BITS;
@@ -1000,10 +1048,10 @@ void TickLatency(bool newRequest, int64_t now) noexcept {
return;
}
}
if (g_latArmedQpc == 0 || static_cast<uint64_t>(now - g_latArmedQpc) >= g_logQpcFreq) {
g_latArmedQpc = now;
g_latGate.store(kLatGateArmed, std::memory_order_release);
}
// One read for each periodic tick. Until 0.1.0-beta.49 this asked that a second had passed since the last arm:
// a tick a moment early then armed nothing, and the publication after it carried no read. The grid is what keeps
// two of these apart now -- half a second at the least.
g_latGate.store(kLatGateArmed, std::memory_order_release);
}
// The request went off: a read that was wanted and not yet made is not made in a session that never asked.
@@ -1499,9 +1547,11 @@ bool MayObserve() noexcept {
// ---------------------------------------------------------------------------
// Which Streamline features were evaluated since the last present. Bits, not a
// last-writer-wins value: DLSS super-resolution and Ray Reconstruction run in
// the SAME frame (fl_shm.h retired FL_UPSCALER_RETIRED_RAY_RECONSTRUCTION for
// exactly that reason), so a single slot would drop one of them.
// last-writer-wins value: a game may evaluate more than one feature between two
// presents (several viewports, NIS after DLSS), so a single slot would drop one
// of them. NOT because DLSS super-resolution and Ray Reconstruction run in the
// same frame, as this said until 2026-11-14: RR runs INSTEAD of super-resolution
// (Streamline's guide; the measurement at the RR arm of the present detour).
// FRAME GENERATION NEEDS A COUNT, NOT A BIT, so the word is now split: features in
// the low byte, a saturating count of kFeatureDLSS_G evaluations above them
// (fl_sl_seen.h owns the encoding and is unit-tested without a hook). A bit
@@ -1927,7 +1977,7 @@ PFN_LoadLibraryExW g_origLoadLibraryExW = nullptr;
constexpr uint32_t kLoaderInstalledBit = 0x8000u;
constexpr uint32_t kLoaderCountMask = 0x7FFFu;
std::atomic<uint32_t> g_loaderSignals{0};
// Auto-reset; the watchdog waits on it with its 1 s timeout, so a signal ends the
// Auto-reset; the watchdog waits on it until its periodic tick is due, so a signal ends the
// wait early and a missing event (creation failed) degrades to the plain sleep.
HANDLE g_watchdogWake = nullptr;
@@ -3533,13 +3583,30 @@ bool InstallRtHooks() noexcept {
// exists; see the block comment above for why a thread is acceptable in the
// Overlay and was not in the Vulkan layer.
DWORD WatchdogLoop() noexcept {
// THE PERIODIC TICK IS ON A GRID (fl_watchdog_tick.h; owner decision D150): one a second by the performance
// counter, whatever a tick's work took and however often the loader woke this thread in between.
const auto frequency = static_cast<int64_t>(g_logQpcFreq);
fl::watchdog::Grid grid;
fl::watchdog::StartGrid(grid, QpcNow(), frequency * kWatchdogIntervalMs / 1000);
bool latencyRequestIsNew = false; // a request not yet handed to TickLatency, which runs on periodic ticks
for (;;) {
// The 1 s tick, OR the LoadLibrary detour's wake -- whichever comes first.
// An event that failed to create degrades to the plain sleep.
// The periodic tick's deadline, OR the LoadLibrary detour's wake -- whichever comes first. An event that
// failed to create, or a wait that failed, degrades to the plain sleep.
const DWORD waitMs = fl::watchdog::WaitMs(grid, QpcNow(), frequency, kWatchdogIntervalMs);
bool timedOut = true;
if (g_watchdogWake != nullptr) {
WaitForSingleObject(g_watchdogWake, kWatchdogIntervalMs);
const DWORD waited = WaitForSingleObject(g_watchdogWake, waitMs);
if (waited == WAIT_FAILED) {
Sleep(waitMs);
}
timedOut = waited != WAIT_OBJECT_0;
} else {
Sleep(kWatchdogIntervalMs);
Sleep(waitMs);
}
const int64_t tickQpc = QpcNow();
const bool periodic = fl::watchdog::IsPeriodic(grid, tickQpc, timedOut);
if (periodic) {
fl::watchdog::Advance(grid, tickQpc);
}
if (g_observing.load(std::memory_order_acquire) == 0) {
@@ -3560,6 +3627,7 @@ DWORD WatchdogLoop() noexcept {
std::atomic_ref<uint32_t> flushReq{g_control->logFlushRequested};
if (const uint32_t req = flushReq.load(std::memory_order_acquire); req != g_logFlushSeen) {
g_logFlushSeen = req;
WriteLatencyBatch(); // what is counted of the driver read so far is part of what the Agent asks for
FlushLog();
}
@@ -3568,24 +3636,31 @@ DWORD WatchdogLoop() noexcept {
// one writer. With the word at 0 nothing more is read in any hook and the region is never touched. A request
// not seen before is a new session's: the summaries start afresh BEFORE the detours are let in, so a range or
// a count never spans two sessions of a game that kept running.
//
// THE REQUEST IS FOLLOWED ON EVERY TICK, THE REGION IS WRITTEN ON THE PERIODIC ONE (0.1.0-beta.49, D150). The
// installers below put in the hooks a session asked for in the very tick that saw the request -- a tick the
// loader woke, when the game has just loaded Streamline -- so the word is read and the flag stored whatever
// the tick. The read of the driver and the publication are once a second: a tick woken early used to take the
// read, publish it and arm nothing, and the publication after it had no read in it.
std::atomic_ref<uint32_t> advancedReq{g_control->advancedRequested};
const uint32_t advancedNow = advancedReq.load(std::memory_order_acquire);
const bool advancedIsNew = advancedNow != 0u && advancedNow != g_advancedSeen;
if (advancedIsNew) {
if (advancedNow != 0u && advancedNow != g_advancedSeen) {
fl::adv::Reset(g_adv);
g_advancedSeen = advancedNow;
latencyRequestIsNew = true;
}
g_advancedRequested.store(advancedNow != 0u ? 1u : 0u, std::memory_order_relaxed);
if (advancedNow != 0u) {
// Initialised through QuadPart, the member read below, so that it is the active one (cpp:S6232).
LARGE_INTEGER advancedQpc{.QuadPart = 0};
QueryPerformanceCounter(&advancedQpc);
if (advancedNow == 0u) {
DisarmLatency();
} else if (periodic) {
++g_latBook.batch.ticksOnTime;
// The driver's latency report (train C): what the last read left is taken, and the next one armed,
// BEFORE the publication -- so the publication carries the read, and carries it once.
TickLatency(advancedIsNew, advancedQpc.QuadPart);
fl::adv::Publish(g_adv, g_advanced, advancedNow, static_cast<uint64_t>(advancedQpc.QuadPart), &g_latOut);
TickLatency(latencyRequestIsNew, tickQpc);
latencyRequestIsNew = false;
fl::adv::Publish(g_adv, g_advanced, advancedNow, static_cast<uint64_t>(tickQpc), &g_latOut);
} else {
DisarmLatency();
++g_latBook.batch.ticksEarly;
}
// The in-process stop, for a title that is NOT presenting (menu, hung,
@@ -3698,6 +3773,7 @@ DWORD WINAPI WatchdogThread(LPVOID) noexcept {
}
}
const bool complete = g_stopLogged.load(std::memory_order_acquire) != 0u;
WriteLatencyBatch(); // the watchdog's own book: no presenting thread ever touches it
LogNote(kLogStopFlushed, complete ? "every stop line is above" : "the stop was still writing", complete ? 1u : 0u);
FlushLog(true);
return r;
+7 -4
View File
@@ -176,9 +176,12 @@ enum FlUpscaler : uint8_t {
FL_UPSCALER_DLSS = 1,
// RETIRED, and the slot is reserved rather than reused. DLSS Ray
// Reconstruction was a value here, which made it MUTUALLY EXCLUSIVE with
// DLSS super-resolution -- but they run together, and 03_METRICS §RT/PT/RR
// makes RR an independent tri-state axis ("Yes / No if DLSS is active
// Reconstruction was a value here, which made it a technology BESIDE DLSS
// -- but it is DLSS: RR takes over the upscale, in DLSS's own quality mode
// (it does not run together with super-resolution, as this comment said
// until 2026-11-14: Streamline's guide has it "completely override" it, and
// Cyberpunk 2077 evaluated kFeatureDLSS_RR and never kFeatureDLSS). 03_METRICS
// §RT/PT/RR makes RR an independent tri-state axis ("Yes / No if DLSS is active
// without it"), which is also CLAUDE.md rule 7's trio. The record was the
// only place the two were conflated; 06_DATA_MODEL already stored them
// apart. RR is now FL_FEAT_RAY_RECONSTRUCTION in featureFlags.
@@ -1003,7 +1006,7 @@ enum FlLatencyState : uint32_t {
FL_LAT_ERROR = 6, // the last read returned an NVAPI status that is not OK; reading goes on
FL_LAT_SLOW = 7, // one call took 2 ms or more: off until the game exits (D141)
FL_LAT_FAULTED = 8, // a getter faulted: off until the game exits, and counted once in faultCount
FL_LAT_STALLED = 9, // a call had not returned after a second: nothing can stop it; reported and left
FL_LAT_STALLED = 9, // a call had not returned after two seconds: nothing can stop it; reported and left
};
// latState, above the state: the driver's sleep status as SEEN -- a switch can be in both groups in one session.
+10
View File
@@ -207,6 +207,16 @@ target_compile_definitions(fl_reflex_summary_test PRIVATE WIN32_LEAN_AND_MEAN NO
add_test(NAME fl_reflex_summary COMMAND fl_reflex_summary_test)
fl_catch2_test_completes(fl_reflex_summary)
# fl_watchdog_tick.h (0.1.0-beta.49, D150): when the Overlay's watchdog makes its periodic tick -- a grid that does
# not drift with a tick's work, a tick woken early that does not move it, a wait never rounded down, and two
# periodic ticks never within half a period. Pure arithmetic: no thread, no clock, no Windows header.
add_executable(fl_watchdog_tick_test watchdog_tick_test.cpp)
target_include_directories(fl_watchdog_tick_test PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Overlay/include")
target_link_libraries(fl_watchdog_tick_test PRIVATE fl_native_flags Catch2::Catch2WithMain)
target_compile_options(fl_watchdog_tick_test PRIVATE /EHsc)
add_test(NAME fl_watchdog_tick COMMAND fl_watchdog_tick_test)
fl_catch2_test_completes(fl_watchdog_tick)
# fl_ffx_types.h (0.1.0-beta.42, D121): the descriptor types an ffx-api module was handed, kept by the detours for
# the native log. The header the Overlay compiles, driven without the Overlay -- including from eight threads.
add_executable(fl_ffx_types_test ffx_types_test.cpp)
+281
View File
@@ -21,6 +21,7 @@
#include <catch2/catch_test_macros.hpp>
#include <catch2/reporters/catch_reporter_event_listener.hpp>
#include <catch2/reporters/catch_reporter_registrars.hpp>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <cwchar>
@@ -6198,6 +6199,38 @@ bool LogHasLine(const std::string& text, const char* code, const std::string& na
return false;
}
// The `a` and `b` of the LAST line of this code whose text starts with `name`; false when there is none.
bool LogLineWords(const std::string& text, const char* code, const std::string& name, uint32_t& a, uint64_t& b) {
const std::string head = std::string("s ") + code + " ";
bool found = false;
std::size_t at = 0;
while (at < text.size()) {
std::size_t end = text.find('\n', at);
if (end == std::string::npos) {
end = text.size();
}
const std::string line = text.substr(at, end - at);
const std::size_t h = line.find(head);
const std::size_t words = line.rfind(" a=");
if (h != std::string::npos && words != std::string::npos) {
std::size_t n = h + head.size();
while (n < line.size() && line[n] == ' ') {
++n;
}
unsigned first = 0;
unsigned long long second = 0;
if (line.compare(n, name.size(), name) == 0 &&
sscanf_s(line.c_str() + words, " a=%u b=0x%llx", &first, &second) == 2) {
a = first;
b = second;
found = true;
}
}
at = end + 1;
}
return found;
}
std::size_t CountOf(const std::string& text, const char* needle) {
std::size_t n = 0;
for (std::size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) {
@@ -7344,6 +7377,13 @@ TEST_CASE("FSR's plane at infinity (beta.42, D119): a far plane of FLT_MAX reach
SetAdvancedRequest(r, 11u);
fl::FlAdvancedState a{};
REQUIRE(ReadAdvanced(r, 11u, a, 0u, fl::FL_ADV_VALID_FFX_UPSCALE));
// The ranges are since the request, and the first publication that carries the descriptor may hold one dispatch
// of it: since 0.1.0-beta.49 a request seen on a tick the loader woke is published by the periodic tick that
// follows, however soon that is. The field of view alternates, so both of its values have been seen once the
// range is one.
for (int i = 0; i < 5 && a.ffxFovMinBits == a.ffxFovMaxBits; ++i) {
REQUIRE(ReadAdvanced(r, 11u, a, a.samples, fl::FL_ADV_VALID_FFX_UPSCALE));
}
INFO("near 0x" << std::hex << a.ffxNearBits << " far 0x" << a.ffxFarBits);
CHECK(a.ffxFarBits == FL_ADV_FLOAT_INFINITE);
CHECK(std::bit_cast<float>(a.ffxFarBits) > 3.0e38f); // the float it decodes to IS infinity
@@ -7857,6 +7897,247 @@ bool TargetHasModule(HANDLE process, const wchar_t* leaf) {
} // namespace
TEST_CASE("the frames a read summed are counted in the native log, each by its GPU span and the driver's active time: "
"a batch after ten reads, and what is left when the Agent asks",
"[guard][inject][shm][advanced][latency][log]") {
// WHY (0.1.0-beta.49, owner decisions D148, D151). In one real game the mean active time was longer than the mean
// span between the two GPU marks, and the two means cannot say whether that is the driver's doing or the way they
// are taken. The counts that can are written to the log only -- nothing of them is published -- in batches that
// each belong to one state of the sleep status.
LatencyTarget t;
REQUIRE(StartLatencyTarget(t, LatencyArgs(L"--hold-presenting-d3d12 40"), true));
const MappedRing& r = t.r;
fl::stubnv::Shared* stub = t.stub.words;
if (stub == nullptr || r.st == nullptr || r.ctl == nullptr) {
return; // not reached after the REQUIRE; said in the form a static analyser follows (cpp:S2259)
}
REQUIRE(WaitForRecords(r));
SetStubWord(stub->mode, fl::stubnv::kModeGpuShapes); // before the first read: every read is of these frames
SetAdvancedRequest(r, 7u);
// Ten reads sum the frames 5000..5151: sixty-two, then ten a read. By frameID % 5 (fl_stub_nvapi_shared.h) that is
// 31, 31, 30, 30, 30 of the five shapes.
const uint32_t zero = 31u + 30u; // shapes 1 and 4
const uint32_t longer = 30u; // shape 2
const uint32_t within = 31u; // shape 0
char tails[6][64]{};
snprintf(tails[0], sizeof(tails[0]), " a=10 b=0x%x", (1u | 8u) | ((2u | 4u | 16u) << 8) | ((1u << 2) << 16));
snprintf(tails[1], sizeof(tails[1]), " a=152 b=0x0");
snprintf(tails[2], sizeof(tails[2]), " a=0 b=0x%x", zero);
snprintf(tails[3], sizeof(tails[3]), " a=30 b=0x%x", 30u); // shape 4; shape 3
snprintf(tails[4], sizeof(tails[4]), " a=%u b=0x%llx", longer,
(static_cast<unsigned long long>(longer) * fl::stubnv::kGpuUs << 32) |
(static_cast<unsigned long long>(longer) * fl::stubnv::kGpuActiveLongUs));
snprintf(tails[5], sizeof(tails[5]), " a=%u b=0x%llx", within,
(static_cast<unsigned long long>(within) * fl::stubnv::kGpuUs << 32) |
(static_cast<unsigned long long>(within) * fl::stubnv::kGpuActiveUs));
const char* names[6] = {"reads / sleep switches", "frames summed / refused", "GPU span absent / of no length",
"active time with no span", "active longer than span", "active within span"};
std::wstring log;
std::string text;
bool complete = false;
for (int i = 0; i < 500 && !complete; ++i) {
++r.ctl->guardTicks;
Sleep(50);
if (i % 10 != 9 || (log.empty() && !FindOverlayLog(t.child.pi.dwProcessId, t.child.pi.hProcess, log))) {
continue;
}
text = ReadWholeFile(log);
complete = CountOf(text, "LATENCY_FRAMES") >= 7u;
}
INFO("log " << Narrow(log) << ":\n" << text);
REQUIRE(complete);
for (int line = 0; line < 6; ++line) {
INFO("line " << line << ": " << names[line] << " ..." << tails[line]);
CHECK(LogHasLine(text, "LATENCY_FRAMES", names[line], tails[line]));
}
// The seventh line is the watchdog's own: ten reads took about ten seconds and ten periodic ticks or a few more
// (the ticks before the module was found), and the loader woke it at most a few times.
uint32_t spannedMs = 0;
uint64_t ticks = 0;
REQUIRE(LogLineWords(text, "LATENCY_FRAMES", "ms spanned", spannedMs, ticks));
CHECK(spannedMs >= 9000u);
CHECK(spannedMs <= 16000u);
CHECK((ticks >> 32) >= 10u);
CHECK((ticks >> 32) <= 16u);
CHECK((ticks & 0xFFFFFFFFu) <= 8u);
CHECK(CountOf(text, "LATENCY_FRAMES") == 7u); // one batch: the next is twenty reads away
CHECK(r.ctl->logFlushRequested == 0u); // nobody asked for it
// What is published is what it was: these counts are the log's.
fl::FlAdvancedState a{};
REQUIRE(ReadAdvanced(r, 7u, a, 0u, fl::FL_ADV_VALID_LATENCY));
CHECK(LatStateOf(a) == fl::FL_LAT_READING);
for (uint32_t word : a.reservedDlss) {
CHECK(word == 0u);
}
// ---- THE REST, WHEN THE AGENT ASKS. A few reads more, then a flush request: the batch in hand is written with
// the log, seven lines whose frames are ten a read.
TickFor(r, 3200);
++r.ctl->logFlushRequested;
complete = false;
for (int i = 0; i < 100 && !complete; ++i) {
++r.ctl->guardTicks;
Sleep(50);
if (i % 10 == 9) {
text = ReadWholeFile(log);
complete = CountOf(text, "LATENCY_FRAMES") >= 14u;
}
}
INFO("log after the flush request:\n" << text);
REQUIRE(complete);
CHECK(CountOf(text, "LATENCY_FRAMES") == 14u);
bool rest = false;
for (uint32_t reads = 1u; reads < 20u && !rest; ++reads) { // the thirtieth read would close it itself
char frames[32]{};
snprintf(frames, sizeof(frames), " a=%u b=0x0", reads * fl::stubnv::kFrameIdStep);
rest = LogHasLine(text, "LATENCY_FRAMES", names[1], frames);
}
CHECK(rest);
CHECK(r.st->faultCount == 0u);
}
TEST_CASE("a watchdog the loader keeps waking reads the driver once a second all the same, and every publication "
"carries a read",
"[guard][inject][shm][advanced][latency][log]") {
// WHAT A REAL SESSION SHOWED (HANDOFF, item 46): 0.4 to 16 % of a session's samples carried no report. The
// watchdog's ticks were a second and their own work apart, and a tick the LoadLibrary detour woke took the read,
// published it and armed none. Here a thread asks the loader for opengl32.dll for as long as the target lives --
// a module the detour wakes the watchdog for, and one the harness already holds, so nothing is ever unloaded
// under a hook: the watchdog is woken without pause. Until 0.1.0-beta.49 every such tick published region 5.
// (sl.common.dll, D123's churn, wakes nobody: it is in neither the inventory nor the census.)
LatencyTarget t;
const std::wstring presenting = L"--churn-module opengl32.dll --hold-presenting-d3d12 30";
REQUIRE(StartLatencyTarget(t, LatencyArgs(presenting.c_str()), true));
const MappedRing& r = t.r;
fl::stubnv::Shared* stub = t.stub.words;
if (stub == nullptr || r.st == nullptr || r.ctl == nullptr) {
return; // not reached after the REQUIRE; said in the form a static analyser follows (cpp:S2259)
}
REQUIRE(WaitForRecords(r));
SetAdvancedRequest(r, 7u);
fl::FlAdvancedState first{};
REQUIRE(ReadAdvanced(r, 7u, first, 0u, fl::FL_ADV_VALID_LATENCY)); // the first publication with a read
// Eight seconds of publications, looked for every 20 ms: far finer than the half second two may be apart.
uint32_t lastSamples = first.samples;
uint32_t withFrames = 0;
uint32_t withoutFrames = 0;
bool twoAtOnce = false;
long long closestMs = 1'000'000;
const auto began = std::chrono::steady_clock::now();
auto lastAt = began;
bool haveLast = false;
while (std::chrono::steady_clock::now() - began < std::chrono::milliseconds(8000)) {
++r.ctl->guardTicks;
Sleep(20);
fl::FlAdvancedState a{};
if (!CopyAdvanced(r, a) || a.request != 7u || a.samples == lastSamples) {
continue;
}
const auto at = std::chrono::steady_clock::now();
twoAtOnce = twoAtOnce || a.samples != lastSamples + 1u;
if (haveLast) {
const long long apart = std::chrono::duration_cast<std::chrono::milliseconds>(at - lastAt).count();
closestMs = apart < closestMs ? apart : closestMs;
}
haveLast = true;
lastAt = at;
lastSamples = a.samples;
if ((a.latFrames & 0xFFFFu) != 0u) {
++withFrames;
} else {
++withoutFrames;
}
}
const uint32_t publications = lastSamples - first.samples;
INFO("publications " << publications << " in eight seconds: " << withFrames << " with frames, " << withoutFrames
<< " without; the two closest " << closestMs << " ms apart; stub calls "
<< StubWord(stub->latencyCalls));
CHECK(publications >= 6u);
CHECK(publications <= 9u); // one a second: not one for every time the loader woke the thread
CHECK_FALSE(twoAtOnce); // never two inside one look
CHECK(closestMs >= 400); // half a second at the least, less what the looking itself costs
CHECK(withoutFrames <= 1u); // a publication carries the read its tick's predecessor armed
CHECK(withFrames + 1u >= publications);
CHECK(StubWord(stub->latencyCalls) + 2u >= publications);
CHECK(StubWord(stub->latencyCalls) <= publications + 3u);
// THE FIXTURE DID WAKE IT: the batch's own line says how many ticks were on time and how many were woken early.
++r.ctl->logFlushRequested;
std::wstring log;
std::string text;
uint32_t spannedMs = 0;
uint64_t ticks = 0;
bool written = false;
for (int i = 0; i < 100 && !written; ++i) {
++r.ctl->guardTicks;
Sleep(50);
if (i % 10 != 9 || (log.empty() && !FindOverlayLog(t.child.pi.dwProcessId, t.child.pi.hProcess, log))) {
continue;
}
text = ReadWholeFile(log);
written = LogLineWords(text, "LATENCY_FRAMES", "ms spanned", spannedMs, ticks);
}
INFO("log " << Narrow(log) << ":\n" << text);
REQUIRE(written);
const auto onTime = static_cast<uint32_t>(ticks >> 32);
const auto wokenEarly = static_cast<uint32_t>(ticks & 0xFFFFFFFFu);
INFO("the batch spans " << spannedMs << " ms: " << onTime << " ticks on time, " << wokenEarly << " woken early");
CHECK(wokenEarly > 20u); // or this case proved nothing about a woken watchdog
CHECK(onTime >= 6u);
CHECK(onTime * 1000u <= spannedMs + 1500u); // a tick a second, by the batch's own clock
CHECK(r.st->faultCount == 0u);
}
// A number for a pull request, not a gate: how evenly the reads come over a minute and a half, by the batches' own
// seventh line. Hidden: `fl_guard_test "[.measure]"`.
TEST_CASE("how evenly the driver is read over ninety reads, with a quiet loader and with one that never stops",
"[.measure]") {
for (const wchar_t* presenting :
{L"--hold-presenting-d3d12 110", L"--churn-module opengl32.dll --hold-presenting-d3d12 110"}) {
LatencyTarget t;
REQUIRE(StartLatencyTarget(t, LatencyArgs(presenting), true));
const MappedRing& r = t.r;
REQUIRE(WaitForRecords(r));
SetAdvancedRequest(r, 7u);
std::wstring log;
std::string text;
for (int i = 0; i < 2100 && CountOf(text, "ms spanned") < 3u; ++i) {
++r.ctl->guardTicks;
Sleep(50);
if (i % 20 == 19 && (!log.empty() || FindOverlayLog(t.child.pi.dwProcessId, t.child.pi.hProcess, log))) {
text = ReadWholeFile(log);
}
}
// The numbers of each batch's first and last line, parsed: what a file held is never printed as it stands
// (SonarCloud's cppsecurity:S5145 on a line of the log handed to printf).
std::printf("%ls\n", presenting);
std::size_t at = 0;
while (at < text.size()) {
std::size_t end = text.find('\n', at);
end = end == std::string::npos ? text.size() : end;
const std::string line = text.substr(at, end - at);
const std::size_t words = line.rfind(" a=");
unsigned first = 0;
unsigned long long second = 0;
if (line.find("LATENCY_FRAMES") != std::string::npos && words != std::string::npos &&
sscanf_s(line.c_str() + words, " a=%u b=0x%llx", &first, &second) == 2) {
if (line.find("reads /") != std::string::npos) {
std::printf(" %u reads", first);
} else if (line.find("ms spanned") != std::string::npos) {
std::printf(" in %u ms: %llu ticks on time, %llu woken early\n", first, second >> 32,
second & 0xFFFFFFFFull);
}
}
at = end + 1;
}
CHECK(CountOf(text, "ms spanned") >= 3u);
}
}
TEST_CASE("the driver's latency report is read only while a session asks, once a second, and stops with the request "
"and with the hooks",
"[guard][inject][shm][advanced][latency]") {
+238
View File
@@ -12,7 +12,10 @@
// read as a game that has stopped.
#include <catch2/catch_test_macros.hpp>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <fl_adv_fields.h>
#include <memory>
@@ -310,3 +313,238 @@ TEST_CASE("a publication carries one read, packed as fl_shm.h says, and carries
CHECK(untouched.latGpuCounts == 0u);
CHECK(untouched.latMultipliersSeen == 0u);
}
// ---------------------------------------------------------------------------------------------------------------------
// THE COUNTS FOR THE NATIVE LOG (0.1.0-beta.49, owner decisions D148, D151).
// ---------------------------------------------------------------------------------------------------------------------
TEST_CASE("each summed frame is counted by its GPU span and the driver's active time, and what is summed does not move",
"[latency]") {
fl::adv::LatencyCursor cursor;
fl::adv::LatencyTally tally;
auto report = Report(100u); // 100..163: 100..161 are summed
for (std::uint32_t i = 0; i < 64u; ++i) {
Frame& f = report->frameReport[i];
switch (i % 6u) {
case 0u: // a span of 3700 and an active time that is the shorter
f.gpuActiveRenderTimeUs = 3500u;
break;
case 1u: // the two marks at one instant, and no active time
f.gpuRenderStartTime = f.gpuRenderEndTime;
break;
case 2u: // an active time longer than the span
f.gpuActiveRenderTimeUs = 4000u;
break;
case 3u: // the span, and no active time
break;
case 4u: // the two marks at one instant, and an active time
f.gpuRenderStartTime = f.gpuRenderEndTime;
f.gpuActiveRenderTimeUs = 3500u;
break;
default: // no start mark, and an active time
f.gpuRenderStartTime = 0u;
f.gpuActiveRenderTimeUs = 3500u;
break;
}
}
fl::adv::ObserveLatencyReport(*report, cursor, tally);
// Sixty-two frames: eleven each of the first two shapes, ten each of the other four.
REQUIRE(tally.frames == 62u);
CHECK(tally.refused == 0u);
CHECK(tally.gpu.withinFrames == 11u);
CHECK(tally.gpu.withinSpanUs == 11u * 3700u);
CHECK(tally.gpu.withinActiveUs == 11u * 3500u);
CHECK(tally.gpu.longerFrames == 10u);
CHECK(tally.gpu.longerSpanUs == 10u * 3700u);
CHECK(tally.gpu.longerActiveUs == 10u * 4000u);
CHECK(tally.gpu.spanZero == 11u + 10u);
CHECK(tally.gpu.spanAbsent == 10u);
CHECK(tally.gpu.spanNoActive == 10u);
CHECK(tally.gpu.activeNoSpan == 10u + 10u);
// Every summed frame is in exactly one place: the four counted here, or neither a span nor an active time -- the
// eleven whose two marks are one instant and that gave no time.
const std::uint32_t placed =
tally.gpu.withinFrames + tally.gpu.longerFrames + tally.gpu.spanNoActive + tally.gpu.activeNoSpan;
CHECK(placed + 11u == tally.frames);
// WHAT IS PUBLISHED IS WHAT IT WAS: the span over every frame that reported one, the time over those that gave one.
CHECK(tally.sumUs[fl::adv::kLatGpu] == (11u + 10u + 10u) * 3700u);
CHECK((tally.lacking & (1u << fl::adv::kLatGpu)) != 0u);
CHECK(tally.activeFrames == 11u + 10u + 10u + 10u);
CHECK(tally.activeSumUs == 31u * 3500u + 10u * 4000u);
CHECK(tally.sumUs[fl::adv::kLatTotal] == 62u * 7500u);
}
TEST_CASE(
"an active time as long as the span is not the longer; one of over a second was not given; a refused frame is "
"not counted",
"[latency]") {
fl::adv::LatencyGpuCounts counts;
fl::adv::CountGpuTimes(fl::adv::kLatSpanReported, 3700u, 3700u, counts);
CHECK(counts.withinFrames == 1u);
CHECK(counts.longerFrames == 0u);
fl::adv::CountGpuTimes(fl::adv::kLatSpanReported, 1u, 2u, counts); // a span of a microsecond is a span
CHECK(counts.longerFrames == 1u);
CHECK(counts.longerSpanUs == 1u);
CHECK(counts.longerActiveUs == 2u);
CHECK(counts.spanZero == 0u);
fl::adv::CountGpuTimes(fl::adv::kLatSpanReported, 3700u, 1'000'001u, counts); // no frame has such a time
CHECK(counts.spanNoActive == 1u);
CHECK(counts.longerFrames == 1u);
fl::adv::LatencyCursor cursor;
fl::adv::LatencyTally tally;
auto report = Report(100u);
for (auto& f : report->frameReport) {
f.gpuActiveRenderTimeUs = 3500u;
}
report->frameReport[5].presentEndTime = report->frameReport[5].presentStartTime - 50u; // refused whole
fl::adv::ObserveLatencyReport(*report, cursor, tally);
CHECK(tally.frames == 61u);
CHECK(tally.refused == 1u);
CHECK(tally.gpu.withinFrames == 61u);
CHECK(tally.gpu.withinSpanUs == 61u * 3700u);
}
TEST_CASE("a batch of the log's counts is written after ten reads, after thirty, and every sixty from there",
"[latency]") {
std::uint32_t due = 0u;
for (std::uint32_t reads = 1u; reads <= 400u; ++reads) {
const bool expected = reads == 10u || reads == 30u || reads == 90u || reads == 150u || reads == 210u ||
reads == 270u || reads == 330u || reads == 390u;
CHECK(fl::adv::LatencyBatchDue(reads) == expected);
due += fl::adv::LatencyBatchDue(reads) ? 1u : 0u;
}
CHECK(due == 8u);
CHECK_FALSE(fl::adv::LatencyBatchDue(0u));
}
TEST_CASE("a batch belongs to one state of the sleep status: another state closes it, until a request has closed "
"thirty-two that way",
"[latency]") {
fl::adv::LatencyTally tally;
tally.frames = 10u;
tally.refused = 1u;
tally.gpu.spanZero = 2u;
tally.gpu.longerFrames = 3u;
tally.gpu.longerSpanUs = 300u;
tally.gpu.longerActiveUs = 450u;
tally.gpu.withinFrames = 4u;
tally.gpu.withinSpanUs = 4000u;
tally.gpu.withinActiveUs = 3600u;
// The state: the low-latency switch, "the game sleeps", and the multiplier -- not the other three switches.
const fl::adv::LatencySleep reflexTwo{1u | 8u, 2u};
const fl::adv::LatencySleep reflexTwoVrr{1u | 2u | 8u | 16u, 2u};
const fl::adv::LatencySleep overrideOne{1u, 1u};
const fl::adv::LatencySleep manyFrames{0u, 900u};
CHECK(fl::adv::LatencyStateOf(true, reflexTwo) == ((1u | 8u) | (2u << 8)));
CHECK(fl::adv::LatencyStateOf(true, reflexTwoVrr) == fl::adv::LatencyStateOf(true, reflexTwo));
CHECK(fl::adv::LatencyStateOf(true, overrideOne) != fl::adv::LatencyStateOf(true, reflexTwo));
CHECK(fl::adv::LatencyStateOf(false, reflexTwo) == fl::adv::kLatStateUnknown);
CHECK(fl::adv::LatencyStateOf(true, manyFrames) == (255u << 8));
fl::adv::LatencyBatchBook book;
CHECK_FALSE(fl::adv::LatencyBatchTurns(book, fl::adv::LatencyStateOf(true, reflexTwo))); // nothing to close
fl::adv::LatencyBatchAdd(book, tally, true, reflexTwo);
fl::adv::LatencyBatchAdd(book, tally, true, reflexTwoVrr);
CHECK(book.okReads == 2u);
CHECK(book.batch.reads == 2u);
CHECK(book.batch.frames == 20u);
CHECK(book.batch.refused == 2u);
CHECK(book.batch.gpu.spanZero == 4u);
CHECK(book.batch.gpu.longerFrames == 6u);
CHECK(book.batch.gpu.longerActiveUs == 900u);
CHECK(book.batch.gpu.withinSpanUs == 8000u);
CHECK(book.batch.state == fl::adv::LatencyStateOf(true, reflexTwo));
CHECK(book.batch.sleepOn == (1u | 2u | 8u | 16u));
CHECK(book.batch.sleepOff == (2u | 4u | 16u)); // off in one read or the other
CHECK(book.batch.multipliers == (1u << 2));
CHECK_FALSE(fl::adv::LatencyBatchTurns(book, fl::adv::LatencyStateOf(true, reflexTwoVrr)));
CHECK(fl::adv::LatencyBatchTurns(book, fl::adv::LatencyStateOf(true, overrideOne)));
CHECK(fl::adv::LatencyBatchTurns(book, fl::adv::kLatStateUnknown)); // a read with no status is a state too
// A read with no status adds its frames and nothing to the "seen" words.
fl::adv::LatencyBatchAdd(book, tally, false, overrideOne);
CHECK(book.batch.reads == 3u);
CHECK(book.batch.sleepOn == (1u | 2u | 8u | 16u));
CHECK(book.batch.multipliers == (1u << 2));
// A status that flickers: after thirty-two closings the batch runs on, and says what it held.
book.closures = fl::adv::kLatStateClosures;
CHECK_FALSE(fl::adv::LatencyBatchTurns(book, fl::adv::LatencyStateOf(true, overrideOne)));
fl::adv::LatencyBatchAdd(book, tally, true, overrideOne);
CHECK(book.batch.state == fl::adv::LatencyStateOf(true, reflexTwo)); // its first read's
CHECK(book.batch.multipliers == ((1u << 1) | (1u << 2)));
CHECK(book.batch.sleepOff == (2u | 4u | 8u | 16u));
// A sum stops at the top of its word instead of wrapping into a small number.
std::uint32_t sum = 0xFFFFFFF0u;
fl::adv::LatencyAddStop(sum, 0x20u);
CHECK(sum == 0xFFFFFFFFu);
}
TEST_CASE("a batch is seven lines of the log: a text that fits, a count in decimal, and a word in hex", "[latency]") {
fl::adv::LatencyBatch batch;
batch.reads = 10u;
batch.frames = 152u;
batch.refused = 3u;
batch.sleepOn = 1u | 8u;
batch.sleepOff = 2u | 4u | 16u;
batch.multipliers = 1u << 2;
batch.gpu.spanAbsent = 5u;
batch.gpu.spanZero = 61u;
batch.gpu.activeNoSpan = 30u;
batch.gpu.spanNoActive = 31u;
batch.gpu.longerFrames = 30u;
batch.gpu.longerSpanUs = 111000u;
batch.gpu.longerActiveUs = 120000u;
batch.gpu.withinFrames = 26u;
batch.gpu.withinSpanUs = 96200u;
batch.gpu.withinActiveUs = 91000u;
batch.spannedMs = 10012u;
batch.ticksOnTime = 10u;
batch.ticksEarly = 3u;
const std::uint64_t expectedB[fl::adv::kLatBatchLines] = {
0x41609ull, 3ull, 61ull, 31ull, (111000ull << 32) | 120000ull, (96200ull << 32) | 91000ull,
(10ull << 32) | 3ull};
const std::uint32_t expectedA[fl::adv::kLatBatchLines] = {10u, 152u, 5u, 30u, 30u, 26u, 10012u};
for (std::uint32_t line = 0; line < fl::adv::kLatBatchLines; ++line) {
const fl::adv::LatencyLogLine entry = fl::adv::LatencyBatchLine(batch, line);
INFO("line " << line << ": " << entry.text);
CHECK(entry.a == expectedA[line]);
CHECK(entry.b == expectedB[line]);
CHECK(std::strlen(entry.text) <= fl::adv::LatencyBatchLongestText());
CHECK(std::strlen(entry.text) < 72u); // the native log's event has 72 characters of text, the last a zero
for (std::uint32_t other = 0; other < line; ++other) {
CHECK(std::strcmp(entry.text, fl::adv::LatencyBatchLine(batch, other).text) != 0);
}
}
}
// What summing one report costs: the reader runs on a game's presenting thread, once a second. Hidden -- a number
// for a pull request, not a gate: `fl_reflex_summary_test "[.bench]"`.
TEST_CASE("what summing one report of sixty-four frames costs", "[.bench]") {
auto report = Report(5000u);
for (auto& f : report->frameReport) {
f.gpuActiveRenderTimeUs = 3500u;
f.gpuFrameTimeUs = 4200u;
}
constexpr std::uint32_t kRuns = 2'000'000u;
std::uint64_t frames = 0u;
for (int pass = 0; pass < 5; ++pass) {
const auto began = std::chrono::steady_clock::now();
for (std::uint32_t run = 0; run < kRuns; ++run) {
fl::adv::LatencyCursor cursor; // every run sums the report's sixty-two frames anew
fl::adv::LatencyTally tally;
fl::adv::ObserveLatencyReport(*report, cursor, tally);
frames += tally.frames + tally.gpu.withinFrames;
}
const auto nanos =
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - began).count();
std::printf("pass %d: %.1f ns a report\n", pass, static_cast<double>(nanos) / kRuns);
}
CHECK(frames == 5ull * kRuns * (62u + 62u));
}
+99
View File
@@ -0,0 +1,99 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
// fl_watchdog_tick.h: when the Overlay's watchdog makes its periodic tick (0.1.0-beta.49, owner decision D150),
// driven without a thread and without a clock -- the header the Overlay compiles, on counter values written here.
//
// What it holds: the grid does not drift with the work of a tick or with the lateness of a wake; a tick woken early
// is not the periodic one and does not move the grid; a wait is never rounded down to end before its deadline; and
// two periodic ticks are never less than half a period apart, however late one ran.
#include <catch2/catch_test_macros.hpp>
#include <cstdint>
#include <fl_watchdog_tick.h>
namespace {
constexpr std::int64_t kFrequency = 10'000'000; // the performance counter's on the machines this runs on
constexpr std::int64_t kPeriod = kFrequency; // one second
constexpr std::int64_t kMs = kFrequency / 1000;
} // namespace
TEST_CASE("the periodic tick keeps a grid of one period whatever each tick's work and lateness were", "[watchdog]") {
fl::watchdog::Grid grid;
fl::watchdog::StartGrid(grid, 5 * kPeriod, kPeriod);
CHECK(grid.deadline == 6 * kPeriod);
// Sixty ticks, each begun 3 to 17 ms after its deadline (the timer's own granularity and a busy machine) and each
// followed by work of up to 240 ms: the deadlines stay whole seconds.
std::int64_t now = 5 * kPeriod;
for (std::int64_t tick = 0; tick < 60; ++tick) {
const std::uint32_t wait = fl::watchdog::WaitMs(grid, now, kFrequency, 1000u);
CHECK(wait <= 1000u);
CHECK(now + wait * kMs >= grid.deadline); // never rounded down to end short of it
now = grid.deadline + (3 + tick % 15) * kMs;
REQUIRE(fl::watchdog::IsPeriodic(grid, now, true));
fl::watchdog::Advance(grid, now);
CHECK(grid.deadline == (7 + tick) * kPeriod);
now += (tick % 5) * 60 * kMs; // the tick's work
}
}
TEST_CASE("a wait is whole milliseconds rounded up, zero when the tick is due, and never longer than its ceiling",
"[watchdog]") {
fl::watchdog::Grid grid;
fl::watchdog::StartGrid(grid, 0, kPeriod);
CHECK(fl::watchdog::WaitMs(grid, 0, kFrequency, 1000u) == 1000u);
CHECK(fl::watchdog::WaitMs(grid, kPeriod - 5 * kMs, kFrequency, 1000u) == 5u);
CHECK(fl::watchdog::WaitMs(grid, kPeriod - 5 * kMs + 1, kFrequency, 1000u) == 5u); // 4.9999 ms: five, not four
CHECK(fl::watchdog::WaitMs(grid, kPeriod - 1, kFrequency, 1000u) == 1u);
CHECK(fl::watchdog::WaitMs(grid, kPeriod, kFrequency, 1000u) == 0u);
CHECK(fl::watchdog::WaitMs(grid, kPeriod + 40 * kMs, kFrequency, 1000u) == 0u);
CHECK(fl::watchdog::WaitMs(grid, -3 * kPeriod, kFrequency, 1000u) == 1000u); // a counter that went back
CHECK(fl::watchdog::WaitMs(grid, 0, 0, 1000u) == 0u); // no frequency: no wait to compute
}
TEST_CASE("a tick something woke early is not the periodic one and leaves the grid where it was", "[watchdog]") {
fl::watchdog::Grid grid;
fl::watchdog::StartGrid(grid, 0, kPeriod);
const std::int64_t deadline = grid.deadline;
// Five wakes inside one period: none is periodic, and the wait after each is what is left to the same deadline.
for (std::int64_t wake = 1; wake <= 5; ++wake) {
const std::int64_t now = wake * 150 * kMs;
CHECK_FALSE(fl::watchdog::IsPeriodic(grid, now, false));
CHECK(grid.deadline == deadline);
CHECK(fl::watchdog::WaitMs(grid, now, kFrequency, 1000u) == static_cast<std::uint32_t>(1000 - wake * 150));
}
// A signal that came when the deadline had passed all the same: that tick is the periodic one.
CHECK(fl::watchdog::IsPeriodic(grid, deadline + 2 * kMs, false));
// And a wait that timed out a little short of the deadline, by this counter, is the tick the wait was for.
CHECK(fl::watchdog::IsPeriodic(grid, deadline - kMs / 2, true));
fl::watchdog::Advance(grid, deadline - kMs / 2);
CHECK(grid.deadline == deadline + kPeriod); // on the grid, not a period after the early moment
}
TEST_CASE("a periodic tick that ran late is not followed by another within half a period", "[watchdog]") {
fl::watchdog::Grid grid;
fl::watchdog::StartGrid(grid, 0, kPeriod);
// 400 ms late: the next is on the grid, 600 ms away.
fl::watchdog::Advance(grid, kPeriod + 400 * kMs);
CHECK(grid.deadline == 2 * kPeriod);
// 600 ms late: the grid's next would be 400 ms away, so the grid starts again from this tick.
fl::watchdog::Advance(grid, 2 * kPeriod + 600 * kMs);
CHECK(grid.deadline == 3 * kPeriod + 600 * kMs);
// A tick whose work took seconds (an install batch on a loaded machine): one tick follows, a period on -- not
// one for each deadline that passed.
fl::watchdog::Advance(grid, 9 * kPeriod);
CHECK(grid.deadline == 10 * kPeriod);
CHECK(fl::watchdog::WaitMs(grid, 9 * kPeriod, kFrequency, 1000u) == 1000u);
// A period that is not a positive number is one tick, not a division by zero or a wait without end.
fl::watchdog::StartGrid(grid, 100, 0);
CHECK(grid.period == 1);
CHECK(grid.deadline == 101);
}
@@ -25,6 +25,13 @@ enum Mode : std::uint32_t {
kModeFault = 3, // an access violation inside GetLatency
kModeNoDriverSpan = 4, // reports whose driverStartTime is zero: what the driver gives without a sleep mode
kModeImpossible = 5, // reports whose present ends before it starts
// Reports whose frames differ in their GPU span and in the driver's active time, by frameID % 5:
// 0 as kModeReports: a span of kGpuUs and an active time of kGpuActiveUs, which is the shorter
// 1 the two GPU marks at the same instant, and no active time
// 2 an active time of kGpuActiveLongUs, longer than the span
// 3 the span, and no active time
// 4 the two GPU marks at the same instant, and an active time
kModeGpuShapes = 6,
};
// One frame of kModeReports, in microseconds: every frame has these spans.
@@ -38,7 +45,8 @@ inline constexpr std::uint32_t kTotalUs = 7500u;
// The two times a driver works out itself, of every frame: the card at work, and one frame's GPU end to the next's.
inline constexpr std::uint32_t kGpuActiveUs = 3500u;
inline constexpr std::uint32_t kGpuFrameUs = 4200u;
inline constexpr std::uint32_t kFgMultiplier = 2u; // what GetSleepStatus gives while `fgMultiplier` is zero
inline constexpr std::uint32_t kGpuActiveLongUs = 4000u; // kModeGpuShapes: longer than kGpuUs
inline constexpr std::uint32_t kFgMultiplier = 2u; // what GetSleepStatus gives while `fgMultiplier` is zero
inline constexpr std::uint32_t kFirstFrameId = 5000u;
inline constexpr std::uint32_t kFrameIdStep = 10u; // how far the ids move on at each call
@@ -125,6 +125,18 @@ NvAPI_Status __cdecl StubGetLatency(IUnknown* device, NV_LATENCY_RESULT_PARAMS*
if (mode == fl::stubnv::kModeImpossible) {
r.presentEndTime = r.presentStartTime - 50u;
}
if (mode == fl::stubnv::kModeGpuShapes) {
const std::uint64_t shape = id % 5u;
if (shape == 1u || shape == 4u) {
r.gpuRenderStartTime = r.gpuRenderEndTime; // a span of no length; the frame's total is as it was
}
if (shape == 1u || shape == 3u) {
r.gpuActiveRenderTimeUs = 0u;
}
if (shape == 2u) {
r.gpuActiveRenderTimeUs = fl::stubnv::kGpuActiveLongUs;
}
}
}
return NVAPI_OK;
}
@@ -455,13 +455,16 @@ public sealed class AdvancedPresenterTests
];
AdvancedPresenter.Metrics(series, []).Select(static m => m.Id).Should().BeEquivalentTo("nvapi.reflex.frame_report", "nvapi.reflex.gpu_times");
// The span between the driver's two GPU marks says what it includes, in every language (D143).
// The span between the driver's two GPU marks says what it is, in every language (D143) - and neither label says
// which of the two holds the other (D152): in Cyberpunk 2077 the driver's active time is the longer.
foreach (string culture in new[] { "", "vi", "ja" })
{
string render = Strings.ResourceManager.GetString(nameof(Strings.AdvToken_gpu_render), CultureInfo.GetCultureInfo(culture))!;
string active = Strings.ResourceManager.GetString(nameof(Strings.AdvToken_active_render), CultureInfo.GetCultureInfo(culture))!;
render.Should().Contain("(", "the label carries what the span includes");
render.Should().Contain("(", "the label carries what the span is");
render.Should().NotBe(active);
render.Should().NotContain("idle", "the span is not said to include the active time's idle time");
active.Should().NotContain("idle", "the active time is not said to be the span less its idle time");
}
}
@@ -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);
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more