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>
This commit is contained in:
poli0981andClaude Fable 5.2 authored and GitHub committed 2026-11-14 15:02:57 +00:00
1 parent e20bf9abc0
commit 8f24854aa5
43 files changed
+2929 -1

No files matched your search

+10
View File
@@ -35,6 +35,16 @@ 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.**
### Changed
- **Advanced metrics is closed: the ten readings that were "being studied" are now "not read", with the reason**
+54
View File
@@ -976,6 +976,60 @@ min / max in `sensor_stats_json` (§Sensor aggregates). MiB stored; shown in GB
~~`vramUsedMb` from `IDXGIAdapter3::QueryVideoMemoryInfo(LOCAL)` inside the game = **this game's** usage and budget. **MiB, truncating, and it must use the same divisor as `vramBudgetMb`** — the two are compared, and mismatched rounding would put a systematic bias into `budget_exceeded_pct`. Residual: a flip within 1 MiB of the budget, 0.004% of a 24 GiB card. Stored as its own series and clearly labelled apart from the adapter-wide figure from `18_GPU_VENDOR_APIS`. Aggregates: avg, max, and `budget_exceeded_pct` (share of samples where `CurrentUsage > Budget`, i.e. the driver was likely evicting — a genuinely useful stutter explanation).~~
## Input — what a session was played with, both tiers (owner decisions D155–D163)
**Owner request, 2026-11-14:** the share of a session played with a controller and with the keyboard, how often a
controller connected and dropped, the battery state that lasted longest, the switches between makers' controllers.
What is read and what never is: [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md). The arithmetic is
`Domain.Input` and `Application.Recording.InputSessionBuilder`. **Not built end to end yet** — nothing reads a device
until the pull requests after the one that wrote this section; until then these are definitions under test.
**What it can say, and what it cannot.** Everything is read from outside the game. So a number here says that a
controller, or the keyboard or mouse, was *in use while the game's window was in front* — never what the game did with
it, and never which button or key.
**The unit is a slice** of about a tenth of a second, and a slice counts for a session only when a window of the
session's game was in front and the session was not paused (a pause is a gap, as for frames). A slice with another
program in front is not classified: typing in a browser beside the game is not the game played with the keyboard.
| Class | A slice in front in which |
|---|---|
| Controller | a controller was in use and the time of the last keyboard-or-mouse input did not move |
| Keyboard & mouse | that time moved and no controller was in use. One class: only a time is read (D158) |
| Both | both |
| No input | neither |
- **A controller is in use** when a button is down, a trigger is past its threshold, or a stick is outside its dead
zone. A stick held counts. One that drifts inside the dead zone does not — a pad lying on a desk is not played with.
- **A share** is a class's time over the time the game was in front (`input_foreground_ms`). The four add up to it.
- **A switch of method** is a change between *controller* and *keyboard & mouse* from one tick (a second) to a later
one. A tick played with both, or with neither, is no one thing and does not end the run before it: putting the
controller down and picking it up again is not a switch.
- **Connections** are counted from the session's second slice: a controller that is there when the session starts has
not connected. A Bluetooth pad that goes to sleep has disconnected.
- **A battery** is timed by the clock, in front or not: the time at each level, the level that lasted longest, the
first and the last. Each source keeps its own steps — XInput's four words, a DualSense's per cent in tens — and none
is converted into another's. **A rate**, in per cent an hour, is the fall from the first to the last reading on
battery over the time read on battery; it is given only for a level in per cent that fell, was not put on power in
between, and was read on battery for ten minutes or more.
- **A maker's share** is the time its controllers were in use over that time for every maker. **A switch of maker**
is counted like a switch of method, between ticks in which one maker's controllers alone were in use.
- **One pad seen twice is one controller.** With Steam Input in front of a controller Windows shows the controller the
player holds and an Xbox pad Steam presents for it. One of XInput's pads that was in use at the same moments as
another controller — nine tenths of the busier one's time, over ten seconds or more — is folded into it: into a
controller that is not XInput's at any time, into another of XInput's pads only in a session in which Steam's
virtual gamepad was seen. Two players pressing in step are two players.
**The timeline** is one series, `input.class`: what each tick was mostly played with, as the class's number (0 no
input, 1 controller, 2 keyboard & mouse, 3 both), and no value for a tick with the game not in front. Each of the
first eight controllers has `input.dev.N.active` (the part of the tick's time in front it was in use; no value where
it was not connected) and, with a battery that has a level, `input.dev.N.battery`.
**Known limits.** Keyboard and mouse cannot be told apart. Input a program injects counts as keyboard and mouse — Steam
Input mapping a pad to keys, a macro tool — so a pad mapped that way reads as *both*. A game whose window belongs to
another process reads as never in front (the focus sample's limit). Whether a controller's own input moves Windows'
last-input time has not been checked on a real PC.
## Sensor aggregates
Per session over 1 Hz samples: `avg` (mean of non-null), `max` — and since beta.12 the `median` (the linear-interpolation
+108
View File
@@ -0,0 +1,108 @@
# 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 — nothing reads a device yet.** The model and the arithmetic exist (`FrameLedger.Domain.Input`,
> `FrameLedger.Application.Input`, `Application.Recording.InputSessionBuilder`), under tests whose every byte and
> reading was written by hand. The reader, the storage, the switch and the screens come in the pull requests after
> it, and this note is rewritten by each. **No report from a real controller has passed through any of this code**
> (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`) | the reports game controllers send, while the Agent is in the background; a controller arriving and leaving; its vendor and product ids | the documented way to receive a HID controller's reports without being in front, and it opens no handle to the device |
| `hid.dll`'s parser (`HidP_GetCaps`, `HidP_GetUsages`, `HidP_GetUsageValue`) | which usages of a report are set | a parser, not I/O: it reads the bytes Raw Input handed over |
| 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.
## 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.
## What the reader says about itself
`Application.Input.InputHealth`, carried by every reading and stored with the session: whether Windows accepted the
registration, how many reports came and how many could not be read, whether XInput's library was there and how many
states it returned, how often a controller's own reports said *in use* while XInput said nothing, whether the time of
the last input could be read, how many slices were taken and how much processor time the reader's thread used. Counts
and yes-or-no answers; nothing in it names a device.
+9
View File
@@ -1179,6 +1179,15 @@ Where each owner decision is recorded — the file and its section, and a label
| D152 | [`18_GPU_VENDOR_APIS.md`](18_GPU_VENDOR_APIS.md) §The inventory | the two GPU labels say what each figure is — *the driver's own figure*, *between the driver's start and end marks* — not "idle time excluded / included": item 47 counted the active time as the longer in Cyberpunk 2077. Strings only; numbers and means unchanged |
| D153 | [`spike-notes/30-reflex-latency.md`](spike-notes/30-reflex-latency.md) *Added 2026-11-14* | the owner's word: of Reflex it is enough to tell whether a game has it. Reflex and PCL leave train D (`sl.pcl.markers` stays refused), and D141's stop is not changed for a game's first seconds. My reading of one sentence; nothing shipped is removed by it |
| D154 | [`18_GPU_VENDOR_APIS.md`](18_GPU_VENDOR_APIS.md) §The trains, [`20_OPEN_QUESTIONS.md`](20_OPEN_QUESTIONS.md) §M15 | Advanced metrics is closed: train D is not built, the ten Streamline entries that waited for a spike are not read (`RefusedRoute`), rule 4 is not amended for them. Nothing shipped is removed |
| D155 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | controllers are read by the Agent, from outside the game: no hook is added, rule 4 is untouched, and a session that is not hooked has the numbers too |
| D156 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | the reading is on unless switched off (`capture.input_devices`), and reads nothing until the Privacy Policy that describes it (2.22 or later) has been accepted on the PC |
| D157 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | built without a probe run on real controllers first ("Xây thẳng"): every source reports what it did, and what was verified against hand-made data only is said in each pull request |
| D158 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | keyboard and mouse are one class known only by `GetLastInputInfo`'s time: no Raw Input for them, no hook, no key in the process |
| D159 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §DualSense | nothing is ever sent to a controller; a DualSense on Bluetooth has a battery level only where Steam or the game switched it |
| D160 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | the numbers are columns of `sessions`, so they are in the CSV/JSON export and in a bug bundle, and the Privacy Policy's §3A says so |
| D161 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | a session that is not hooked is duration, hardware telemetry, the reason — and what the Agent reads from outside the game; CLAUDE.md's sentence is amended with the pull request that makes it true |
| D162 | [`03_METRICS.md`](03_METRICS.md) §Input | also built: switches of method and the share with no input, marks on the frame-time chart, a battery's first and last level and its rate, the kind of connection, the Steam Input note, a trend metric, a Compare row, "usually played with" |
| D163 | [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) §The owner's request and decisions | "supports controllers" is three pieces of evidence and never a verdict: Steam's own file on the disk (no network), the input libraries the game loaded, how the game was played |
| D109 | [`../legal/DISCLAIMER.md`](../legal/DISCLAIMER.md) §5, §5A | asked on 2026-11-11 with both sentences quoted: the Disclaimer goes to 2.15 with the Privacy Policy — PawnIO and the admin mode are no longer "for the CPU temperature" alone; with Advanced metrics on they also read the processor's, the memory's and the motherboard's sensors. The admin mode's disclosure follows (`agent-admin-dialog/2`) |
---
+1
View File
@@ -69,6 +69,7 @@ are safety items, and something listed there as unresolved should not be built t
| [`18_GPU_VENDOR_APIS.md`](18_GPU_VENDOR_APIS.md) | Telemetry layers (DXGI/PDH, LibreHardwareMonitor, NVAPI), the game process's memory, licences |
| [`19_SAFETY_AND_ANTICHEAT.md`](19_SAFETY_AND_ANTICHEAT.md) | The anti-cheat guard, what a finding does, the user-mode exception, what will never be built |
| [`20_OPEN_QUESTIONS.md`](20_OPEN_QUESTIONS.md) | Every unresolved question, defect and measurement, with its status marker |
| [`21_INPUT_DEVICES.md`](21_INPUT_DEVICES.md) | Controllers and keyboard-and-mouse activity: what is read from outside the game, from where, and what never is |
| [`HANDOFF.md`](HANDOFF.md) | Sequencing, the open owner-only items, the index of the owner's decisions |
| [`handoff/`](handoff/) | Since beta.24 (D66): the history of every train and phase, the passed owner-only items, the traps — moved out of `HANDOFF.md` verbatim |
| [`open-questions/`](open-questions/) | Since beta.24 (D66): the entries §S24 marks resolved, moved out of `20_OPEN_QUESTIONS.md` verbatim — a table there lists them |
@@ -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,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,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,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;
}
@@ -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
{
}
@@ -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,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 _typeDisconnected = 0x00;
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)),
_typeDisconnected => null,
_ => null,
};
private static bool Outside(int x, int y, int deadzone) => ((long)x * x) + ((long)y * y) > (long)deadzone * deadzone;
}
@@ -0,0 +1,267 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FluentAssertions;
using FrameLedger.Application.Input;
using FrameLedger.Domain.Input;
namespace FrameLedger.Application.Tests.Input;
/// <summary>
/// One session's slices added up into a reading a tick (<c>03_METRICS</c> §Input): only the time the game was in front
/// is classified, a pause is not observed, and a controller that was there at the start has not connected.
/// </summary>
public sealed class InputTickAccumulatorTests
{
private static readonly InputDevice _xbox = new() { Id = 1, Family = ControllerFamily.Xbox, XInputSlot = 0 };
private static readonly InputDevice _dualSense = new()
{
Id = 2,
Family = ControllerFamily.PlayStation,
VendorId = ControllerCatalog.Sony,
ProductId = ControllerCatalog.DualSense,
Connection = ControllerConnection.Usb,
};
private static InputSlice Slice(bool keyboardMouse = false, InputHealth? health = null, bool virtualPad = false, params InputSliceDevice[] devices) => new()
{
ElapsedMs = 100,
ForegroundProcessId = 42,
KeyboardMouseActive = keyboardMouse,
VirtualPad = virtualPad,
Devices = devices,
Health = health ?? new InputHealth(),
};
private static InputSliceDevice Pad(InputDevice device, bool active = false, BatteryReading? battery = null) => new(device, active, battery);
[Fact]
public void NothingAddedIsNothingToTake() =>
new InputTickAccumulator().Take().Should().BeNull();
[Fact]
public void EachSliceInFrontCountsForOneOfTheFourClasses()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_xbox, active: true)), inFront: true, paused: false);
accumulator.Add(Slice(devices: Pad(_xbox, active: true)), inFront: true, paused: false);
accumulator.Add(Slice(keyboardMouse: true, devices: Pad(_xbox)), inFront: true, paused: false);
accumulator.Add(Slice(keyboardMouse: true, devices: Pad(_xbox, active: true)), inFront: true, paused: false);
accumulator.Add(Slice(devices: Pad(_xbox)), inFront: true, paused: false);
InputReading reading = accumulator.Take()!;
reading.SpanMs.Should().Be(500);
reading.ObservedMs.Should().Be(500);
reading.ForegroundMs.Should().Be(500);
reading.ControllerMs.Should().Be(200);
reading.KeyboardMouseMs.Should().Be(100);
reading.BothMs.Should().Be(100);
reading.IdleMs.Should().Be(100);
reading.Devices.Should().Equal(new InputDeviceReading(1, Connected: true, ActiveMs: 300, Battery: null, Connects: 0, Disconnects: 0));
reading.Table.Should().Equal(_xbox);
}
/// <summary>Typing in a browser beside the game is not the game played with the keyboard.</summary>
[Fact]
public void ASliceWithAnotherProgramInFrontIsNotClassified()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(keyboardMouse: true, devices: Pad(_xbox, active: true)), inFront: false, paused: false);
accumulator.Add(Slice(devices: Pad(_xbox, active: true)), inFront: true, paused: false);
InputReading reading = accumulator.Take()!;
reading.SpanMs.Should().Be(200);
reading.ObservedMs.Should().Be(200);
reading.ForegroundMs.Should().Be(100);
reading.ControllerMs.Should().Be(100);
reading.KeyboardMouseMs.Should().Be(0);
reading.BothMs.Should().Be(0);
reading.Devices[0].ActiveMs.Should().Be(100, "a controller's time in use is time in the game");
}
[Fact]
public void APausedSliceIsNotObservedButItsTimeAndItsControllersAre()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_xbox, active: true)), inFront: true, paused: true);
accumulator.Add(Slice(), inFront: true, paused: true);
InputReading reading = accumulator.Take()!;
reading.SpanMs.Should().Be(200, "a battery level is timed by the clock, paused or not");
reading.ObservedMs.Should().Be(0);
reading.ForegroundMs.Should().Be(0);
reading.ControllerMs.Should().Be(0);
reading.Devices.Should().Equal(new InputDeviceReading(1, Connected: false, ActiveMs: 0, Battery: null, Connects: 0, Disconnects: 1));
}
[Fact]
public void AControllerThereAtTheStartHasNotConnectedAndOneThatComesLaterHas()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_xbox)), inFront: true, paused: false);
accumulator.Add(Slice(devices: [Pad(_xbox), Pad(_dualSense)]), inFront: true, paused: false);
InputReading reading = accumulator.Take()!;
reading.Devices.Should().Equal(
new InputDeviceReading(1, Connected: true, ActiveMs: 0, Battery: null, Connects: 0, Disconnects: 0),
new InputDeviceReading(2, Connected: true, ActiveMs: 0, Battery: null, Connects: 1, Disconnects: 0));
reading.Table.Should().Equal(_xbox, _dualSense);
}
[Fact]
public void ADropAndAReturnAreCountedEvenAcrossTicks()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_dualSense)), inFront: true, paused: false);
accumulator.Add(Slice(), inFront: true, paused: false);
InputReading dropped = accumulator.Take()!;
accumulator.Add(Slice(), inFront: true, paused: false);
InputReading gone = accumulator.Take()!;
accumulator.Add(Slice(devices: Pad(_dualSense)), inFront: true, paused: false);
InputReading back = accumulator.Take()!;
dropped.Devices.Should().Equal(new InputDeviceReading(2, Connected: false, ActiveMs: 0, Battery: null, Connects: 0, Disconnects: 1));
gone.Devices.Should().BeEmpty("a controller that left is not carried into the next tick");
gone.Table.Should().BeEmpty();
back.Devices.Should().Equal(new InputDeviceReading(2, Connected: true, ActiveMs: 0, Battery: null, Connects: 1, Disconnects: 0));
}
[Fact]
public void ATakeStartsTheNextTickFromNothingButTheControllersStillConnected()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(keyboardMouse: true, virtualPad: true, devices: Pad(_xbox, active: true)), inFront: true, paused: false);
accumulator.Take().Should().NotBeNull();
accumulator.Take().Should().BeNull("no slice since the last take");
accumulator.Add(Slice(devices: Pad(_xbox)), inFront: true, paused: false);
InputReading next = accumulator.Take()!;
next.SpanMs.Should().Be(100);
next.BothMs.Should().Be(0);
next.IdleMs.Should().Be(100);
next.VirtualPad.Should().BeFalse();
next.Devices.Should().Equal(new InputDeviceReading(1, Connected: true, ActiveMs: 0, Battery: null, Connects: 0, Disconnects: 0));
}
[Fact]
public void TheBatteryIsTheLastOneReportedAndASliceWithNoneKeepsIt()
{
var eighty = new BatteryReading(BatteryState.Discharging, BatteryScale.Percent, 80);
var seventy = new BatteryReading(BatteryState.Discharging, BatteryScale.Percent, 70);
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_dualSense, battery: eighty)), inFront: true, paused: false);
accumulator.Add(Slice(devices: Pad(_dualSense, battery: seventy)), inFront: true, paused: false);
accumulator.Add(Slice(devices: Pad(_dualSense)), inFront: true, paused: false);
accumulator.Take()!.Devices[0].Battery.Should().Be(seventy);
accumulator.Add(Slice(devices: Pad(_dualSense)), inFront: true, paused: false);
accumulator.Take()!.Devices[0].Battery.Should().Be(seventy, "the level a pad last reported is still its level");
}
[Fact]
public void AVirtualPadSeenInAnySliceMarksTheTick()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(), inFront: true, paused: false);
accumulator.Add(Slice(virtualPad: true), inFront: false, paused: true);
accumulator.Take()!.VirtualPad.Should().BeTrue();
}
[Fact]
public void TheSameControllerNamedTwiceInASliceCountsOnce()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: [Pad(_xbox, active: true), Pad(_xbox, active: true)]), inFront: true, paused: false);
accumulator.Take()!.Devices.Should().Equal(new InputDeviceReading(1, Connected: true, ActiveMs: 100, Battery: null, Connects: 0, Disconnects: 0));
}
/// <summary>The reader runs before and after a session: a session's counts start where it began to read.</summary>
[Fact]
public void TheHealthIsWhatHappenedSinceTheSessionsFirstSlice()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(health: new InputHealth { RawInputRegistered = true, RawReports = 1000, Slices = 50, ThreadCpuMs = 7, XInputReads = 40 }), inFront: true, paused: false);
accumulator.Add(Slice(health: new InputHealth { RawInputRegistered = true, XInputAvailable = true, RawReports = 1250, RawReportsUnread = 2, Slices = 51, ThreadCpuMs = 9, XInputReads = 44, XInputSilent = 1, Faults = 1 }), inFront: true, paused: false);
InputHealth health = accumulator.Take()!.Health;
health.Should().Be(new InputHealth
{
RawInputRegistered = true,
XInputAvailable = true,
RawReports = 250,
RawReportsUnread = 2,
Slices = 1,
ThreadCpuMs = 2,
XInputReads = 4,
XInputSilent = 1,
Faults = 1,
});
health.Sources().Should().Be("rawinput+xinput");
}
[Fact]
public void TheSourcesAreTheOnesThatAnswered()
{
new InputHealth().Sources().Should().BeEmpty();
new InputHealth { LastInputAvailable = true }.Sources().Should().Be("lastinput");
new InputHealth { RawInputRegistered = true, XInputAvailable = true, LastInputAvailable = true }.Sources().Should().Be("rawinput+xinput+lastinput");
}
[Fact]
public void ANegativeElapsedTimeCountsForNothing()
{
var accumulator = new InputTickAccumulator();
accumulator.Add(Slice(devices: Pad(_xbox, active: true)) with { ElapsedMs = -40 }, inFront: true, paused: false);
InputReading reading = accumulator.Take()!;
reading.SpanMs.Should().Be(0);
reading.ControllerMs.Should().Be(0);
}
[Fact]
public void TheStoredWordsReadBackAsWhatTheyWere()
{
foreach (ControllerFamily family in Enum.GetValues<ControllerFamily>())
{
InputNames.FamilyOf(InputNames.Of(family)).Should().Be(family);
}
foreach (ControllerConnection connection in Enum.GetValues<ControllerConnection>())
{
InputNames.ConnectionOf(InputNames.Of(connection)).Should().Be(connection);
}
foreach (BatteryState state in Enum.GetValues<BatteryState>())
{
InputNames.StateOf(InputNames.Of(state)).Should().Be(state);
}
foreach (BatteryScale scale in Enum.GetValues<BatteryScale>())
{
InputNames.ScaleOf(InputNames.Of(scale)).Should().Be(scale);
}
InputNames.FamilyOf("a word a later release wrote").Should().Be(ControllerFamily.Other);
InputNames.ConnectionOf(null).Should().Be(ControllerConnection.Unknown);
InputNames.StateOf(null).Should().Be(BatteryState.Unknown);
InputNames.ScaleOf(null).Should().Be(BatteryScale.None);
}
[Fact]
public void ADevicesModelIsItsCatalogName()
{
_dualSense.Model.Should().Be("DualSense");
_xbox.Model.Should().BeNull("one of XInput's pads that nothing named has no ids to look up");
}
}
@@ -0,0 +1,319 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Text.Json;
using FluentAssertions;
using FrameLedger.Application.Input;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Recording;
using FrameLedger.Application.Telemetry;
using FrameLedger.Domain.Input;
namespace FrameLedger.Application.Tests.Recording;
/// <summary>
/// What a session stores of its input readings (<c>03_METRICS</c> §Input): the totals, the controllers with their
/// batteries and makers, the series of the timeline - and nothing at all when no sample carries a reading. Every
/// reading here is made by hand: <b>none came from a controller</b>.
/// </summary>
public sealed class InputSessionBuilderTests
{
private static readonly InputDevice _xbox = new() { Id = 7, Family = ControllerFamily.Xbox, VendorId = ControllerCatalog.Microsoft, ProductId = 0x0B12, Connection = ControllerConnection.Usb, XInputSlot = 0 };
private static readonly InputDevice _steamPad = new() { Id = 8, Family = ControllerFamily.Xbox, VendorId = ControllerCatalog.Microsoft, ProductId = 0x0B12, Connection = ControllerConnection.Usb, XInputSlot = 1 };
private static readonly InputDevice _dualSense = new() { Id = 9, Family = ControllerFamily.PlayStation, VendorId = ControllerCatalog.Sony, ProductId = ControllerCatalog.DualSense, Connection = ControllerConnection.Bluetooth };
private static BatteryReading Percent(int level) => new(BatteryState.Discharging, BatteryScale.Percent, level);
/// <summary>A tick of one second with the game in front the whole time.</summary>
private static InputReading Tick(int controller = 0, int keyboardMouse = 0, int both = 0, bool virtualPad = false, InputHealth? health = null, params (InputDevice Device, InputDeviceReading Reading)[] devices) => new()
{
SpanMs = 1000,
ObservedMs = 1000,
ForegroundMs = 1000,
ControllerMs = controller,
KeyboardMouseMs = keyboardMouse,
BothMs = both,
IdleMs = 1000 - controller - keyboardMouse - both,
VirtualPad = virtualPad,
Devices = [.. devices.Select(static d => d.Reading)],
Table = [.. devices.Select(static d => d.Device)],
Health = health ?? new InputHealth { RawInputRegistered = true, XInputAvailable = true, LastInputAvailable = true },
};
private static (InputDevice, InputDeviceReading) Pad(InputDevice device, int activeMs = 0, bool connected = true, BatteryReading? battery = null, int connects = 0, int disconnects = 0) =>
(device, new InputDeviceReading(device.Id, connected, activeMs, battery, connects, disconnects));
private static List<TelemetrySample> Samples(params InputReading?[] readings)
{
List<TelemetrySample> samples = SessionFixtures.Sensors(readings.Length);
for (int i = 0; i < readings.Length; i++)
{
samples[i] = samples[i] with { Input = readings[i] };
}
return samples;
}
private static float[] Series(IReadOnlyList<SensorBlob> blobs, string name) => RawSeriesCodec.Floats(blobs.Single(b => string.Equals(b.Series, name, StringComparison.Ordinal)).Data);
[Fact]
public void WithNoReadingNothingIsStoredAtAll()
{
(IReadOnlyList<SensorBlob> blobs, InputSessionSummary? summary) = InputSessionBuilder.Build(SessionFixtures.Sensors(5), new RawSeriesCodec());
blobs.Should().BeEmpty();
summary.Should().BeNull("no summary is how a session says the option was off, or the terms not accepted yet");
}
[Fact]
public void TheTotalsAreTheTicksAddedUpAndTheSharesAreOfTheTimeInFront()
{
List<TelemetrySample> samples = Samples(
Tick(controller: 1000, devices: Pad(_xbox, 1000)),
Tick(controller: 600, keyboardMouse: 200, both: 100, devices: Pad(_xbox, 700)),
null,
Tick(keyboardMouse: 1000, devices: Pad(_xbox)),
Tick(devices: Pad(_xbox)) with { ObservedMs = 400, ForegroundMs = 0, IdleMs = 0 });
(_, InputSessionSummary? summary) = InputSessionBuilder.Build(samples, new RawSeriesCodec());
summary!.ObservedMs.Should().Be(3400);
summary.ForegroundMs.Should().Be(3000);
summary.ControllerMs.Should().Be(1600);
summary.KeyboardMouseMs.Should().Be(1200);
summary.BothMs.Should().Be(100);
summary.IdleMs.Should().Be(100);
(summary.ControllerMs + summary.KeyboardMouseMs + summary.BothMs + summary.IdleMs).Should().Be(summary.ForegroundMs);
summary.Source.Should().Be("rawinput+xinput+lastinput");
}
/// <summary>A tick played with both is no one thing; it does not end the run before it.</summary>
[Fact]
public void AMethodSwitchIsFromAControllerToTheKeyboardAndMouseOrBack()
{
List<TelemetrySample> samples = Samples(
Tick(controller: 1000),
Tick(),
Tick(controller: 900, both: 100),
Tick(controller: 1000),
Tick(keyboardMouse: 1000),
null,
Tick(keyboardMouse: 300),
Tick(controller: 400));
InputSessionBuilder.Build(samples, new RawSeriesCodec()).Summary!.MethodSwitches.Should().Be(2);
}
[Fact]
public void TheTimelineIsWhatEachTickWasMostlyPlayedWithAndNaNWhereThereIsNothingToSay()
{
List<TelemetrySample> samples = Samples(
Tick(controller: 800, keyboardMouse: 100),
Tick(keyboardMouse: 700),
Tick(both: 600),
Tick(),
null,
Tick() with { ForegroundMs = 0, IdleMs = 0 });
(IReadOnlyList<SensorBlob> blobs, _) = InputSessionBuilder.Build(samples, new RawSeriesCodec(), hz: 0.98);
float[] timeline = Series(blobs, InputSessionBuilder.ClassSeries);
timeline[..4].Should().Equal((float)InputClass.Controller, (float)InputClass.KeyboardMouse, (float)InputClass.Both, (float)InputClass.None);
float.IsNaN(timeline[4]).Should().BeTrue("a tick with no reading");
float.IsNaN(timeline[5]).Should().BeTrue("a tick with the game not in front");
blobs.Should().OnlyContain(static b => b.Hz == 0.98 && b.Series.StartsWith(InputSessionBuilder.SeriesPrefix, StringComparison.Ordinal));
}
[Fact]
public void AControllerHasItsTimesItsCountsAndItsSeries()
{
List<TelemetrySample> samples = Samples(
Tick(controller: 500, devices: Pad(_dualSense, 500, battery: Percent(80))),
Tick(controller: 1000, devices: Pad(_dualSense, 1000, battery: Percent(80))),
Tick(devices: Pad(_dualSense, connected: false, disconnects: 1)),
Tick(),
Tick(controller: 250, devices: Pad(_dualSense, 250, battery: Percent(70), connects: 1)) with { ForegroundMs = 500, IdleMs = 250 });
(IReadOnlyList<SensorBlob> blobs, InputSessionSummary? summary) = InputSessionBuilder.Build(samples, new RawSeriesCodec());
InputDevicesRecord record = InputDevicesRecord.Parse(summary!.DevicesJson)!;
InputDeviceRecord pad = record.Devices.Should().ContainSingle().Subject;
pad.Index.Should().Be(1);
pad.Family.Should().Be("playstation");
pad.Model.Should().Be("DualSense");
pad.Connection.Should().Be("bluetooth");
pad.XInputSlot.Should().BeNull();
pad.ConnectedMs.Should().Be(3000);
pad.ActiveMs.Should().Be(1750);
pad.Connects.Should().Be(1);
pad.Disconnects.Should().Be(1);
pad.Battery!.Scale.Should().Be("percent");
pad.Battery.States.Should().Equal(new InputBatteryStateRecord("discharging", 80, 2000), new InputBatteryStateRecord("discharging", 70, 1000));
pad.Battery.First.Should().Be(80);
pad.Battery.Last.Should().Be(70);
pad.Battery.DrainPercentPerHour.Should().BeNull("three seconds on battery say nothing about a rate");
float[] active = Series(blobs, InputSessionBuilder.ActiveSeries(1));
active[0].Should().Be(0.5f);
active[1].Should().Be(1f);
float.IsNaN(active[2]).Should().BeTrue("disconnected");
float.IsNaN(active[3]).Should().BeTrue("not there");
active[4].Should().Be(0.5f, "250 ms of the 500 the game was in front");
float[] battery = Series(blobs, InputSessionBuilder.BatterySeries(1));
battery[0].Should().Be(80f);
float.IsNaN(battery[2]).Should().BeTrue();
battery[4].Should().Be(70f);
}
[Fact]
public void AWiredPadHasABatteryStateAndNoBatterySeries()
{
List<TelemetrySample> samples = Samples(Tick(devices: Pad(_xbox, battery: BatteryReading.Wired)), Tick(devices: Pad(_xbox, battery: BatteryReading.Wired)));
(IReadOnlyList<SensorBlob> blobs, InputSessionSummary? summary) = InputSessionBuilder.Build(samples, new RawSeriesCodec());
InputBatteryRecord battery = InputDevicesRecord.Parse(summary!.DevicesJson)!.Devices[0].Battery!;
battery.Scale.Should().Be("none");
battery.States.Should().Equal(new InputBatteryStateRecord("wired", 0, 2000));
battery.First.Should().BeNull();
blobs.Select(static b => b.Series).Should().Equal(InputSessionBuilder.ClassSeries, InputSessionBuilder.ActiveSeries(1));
}
[Fact]
public void EachMakerHasItsShareAndAChangeOfMakerIsCounted()
{
var ticks = new List<InputReading?>();
for (int i = 0; i < 6; i++)
{
ticks.Add(Tick(controller: 1000, devices: [Pad(_xbox, 1000), Pad(_dualSense)]));
}
ticks.Add(Tick(controller: 1000, devices: [Pad(_xbox, 500), Pad(_dualSense, 500)]));
for (int i = 0; i < 2; i++)
{
ticks.Add(Tick(controller: 1000, devices: [Pad(_xbox), Pad(_dualSense, 1000)]));
}
ticks.Add(Tick(controller: 1000, devices: [Pad(_xbox, 1000), Pad(_dualSense)]));
InputDevicesRecord record = InputDevicesRecord.Parse(InputSessionBuilder.Build(Samples([.. ticks]), new RawSeriesCodec()).Summary!.DevicesJson)!;
record.Devices.Select(static d => d.Family).Should().Equal("xbox", "playstation");
record.Families.Should().Equal(new InputFamilyRecord("xbox", 7500, 0.75), new InputFamilyRecord("playstation", 2500, 0.25));
record.FamilySwitches.Should().Be(2, "to the DualSense and back; the tick with both in use is no one maker's");
record.VirtualPad.Should().BeFalse();
record.Devices.Should().OnlyContain(static d => !d.Remapped);
}
/// <summary>
/// Steam Input in front of a DualSense: Windows shows the DualSense and an Xbox pad that moves with it. The Xbox
/// pad is the DualSense, and the session has one controller - Sony's.
/// </summary>
[Fact]
public void AnXInputPadThatMovesWithAnotherControllerIsThatController()
{
var ticks = new List<InputReading?>();
for (int i = 0; i < 12; i++)
{
ticks.Add(Tick(controller: 1000, virtualPad: true, devices: [Pad(_dualSense, 1000), Pad(_xbox, 950)]));
}
InputDevicesRecord record = InputDevicesRecord.Parse(InputSessionBuilder.Build(Samples([.. ticks]), new RawSeriesCodec()).Summary!.DevicesJson)!;
InputDeviceRecord pad = record.Devices.Should().ContainSingle().Subject;
pad.Family.Should().Be("playstation");
pad.Remapped.Should().BeTrue();
record.Families.Should().Equal(new InputFamilyRecord("playstation", 12_000, 1));
record.FamilySwitches.Should().Be(0);
record.VirtualPad.Should().BeTrue();
}
/// <summary>Two of XInput's pads that move together are one only where Steam's virtual gamepad was seen: two players pressing in step are two players.</summary>
[Fact]
public void TwoXInputPadsThatMoveTogetherAreOneOnlyWhereSteamsPadWasSeen()
{
InputReading?[] Session(bool virtualPad) => [.. Enumerable.Range(0, 12).Select(_ => Tick(controller: 1000, virtualPad: virtualPad, devices: [Pad(_xbox, 1000), Pad(_steamPad, 1000)]))];
InputDevicesRecord with = InputDevicesRecord.Parse(InputSessionBuilder.Build(Samples(Session(virtualPad: true)), new RawSeriesCodec()).Summary!.DevicesJson)!;
InputDevicesRecord without = InputDevicesRecord.Parse(InputSessionBuilder.Build(Samples(Session(virtualPad: false)), new RawSeriesCodec()).Summary!.DevicesJson)!;
InputDeviceRecord kept = with.Devices.Should().ContainSingle().Subject;
kept.XInputSlot.Should().Be(0, "the higher of the two is the one folded");
kept.Remapped.Should().BeTrue();
without.Devices.Should().HaveCount(2);
without.Devices.Should().OnlyContain(static d => !d.Remapped);
}
[Fact]
public void OnlyTheFirstEightControllersHaveSeriesAndAllAreListed()
{
(InputDevice, InputDeviceReading)[] pads = [.. Enumerable.Range(0, InputSessionBuilder.MaxDevices + 2)
.Select(static i => Pad(new InputDevice { Id = 100 + i, Family = ControllerFamily.Other, VendorId = 0x1234, ProductId = i }))];
(IReadOnlyList<SensorBlob> blobs, InputSessionSummary? summary) = InputSessionBuilder.Build(Samples(Tick(devices: pads)), new RawSeriesCodec());
InputDevicesRecord.Parse(summary!.DevicesJson)!.Devices.Should().HaveCount(InputSessionBuilder.MaxDevices + 2);
blobs.Should().HaveCount(1 + InputSessionBuilder.MaxDevices);
}
[Fact]
public void TheHealthStoredIsTheLastReadingsAndTheSourceNamesWhatAnswered()
{
var early = new InputHealth { RawInputRegistered = true, RawReports = 10, Slices = 10 };
var late = new InputHealth { RawInputRegistered = true, LastInputAvailable = true, RawReports = 2500, Slices = 30, XInputSilent = 4, ThreadCpuMs = 12 };
InputSessionSummary summary = InputSessionBuilder.Build(Samples(Tick(health: early), null, Tick(health: late), null), new RawSeriesCodec()).Summary!;
summary.Source.Should().Be("rawinput+lastinput");
InputDevicesRecord.Parse(summary.DevicesJson)!.Health.Should().Be(late);
}
/// <summary>
/// Nothing that could name a person or a device is stored: the JSON has the keys listed here and no other, so a
/// serial number, an address or a path would need a key added to this test first.
/// </summary>
[Fact]
public void TheStoredJsonHasNoKeyThatCouldCarryASerialNumberAnAddressOrAPath()
{
string json = InputSessionBuilder.Build(Samples(Tick(controller: 1000, devices: Pad(_dualSense, 1000, battery: Percent(50)))), new RawSeriesCodec()).Summary!.DevicesJson;
var keys = new SortedSet<string>(StringComparer.Ordinal);
Collect(JsonElement.Parse(json), keys);
keys.Should().Equal(
"ActiveMs", "Battery", "ConnectedMs", "Connection", "Connects", "Devices", "Disconnects", "DrainPercentPerHour", "Families", "Family",
"FamilySwitches", "Faults", "First", "Health", "Index", "Last", "LastInputAvailable", "Level", "Model", "Ms", "ProductId", "RawInputRegistered",
"RawReports", "RawReportsUnread", "Remapped", "Scale", "Share", "Slices", "State", "States", "ThreadCpuMs", "V", "VendorId", "Virtual",
"VirtualPad", "XInputAvailable", "XInputReads", "XInputSilent", "XInputSlot");
json.Should().NotContainAny("\\\\", "HID#", "VID_", "serial", "Serial");
}
[Fact]
public void AColumnThatIsEmptyOrNotJsonReadsAsNothing()
{
InputDevicesRecord.Parse(null).Should().BeNull();
InputDevicesRecord.Parse(" ").Should().BeNull();
InputDevicesRecord.Parse("{ not json").Should().BeNull();
InputDevicesRecord.Parse("{}")!.Devices.Should().BeEmpty();
}
private static void Collect(JsonElement element, SortedSet<string> keys)
{
if (element.ValueKind == JsonValueKind.Object)
{
foreach (JsonProperty property in element.EnumerateObject())
{
keys.Add(property.Name);
Collect(property.Value, keys);
}
}
else if (element.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement item in element.EnumerateArray())
{
Collect(item, keys);
}
}
}
}
@@ -0,0 +1,170 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FluentAssertions;
using FrameLedger.Domain.Input;
namespace FrameLedger.Domain.Tests.Input;
/// <summary>
/// Who a controller is by its two USB ids, what XInput's words mean, and a battery's readings added up over a session
/// (<c>03_METRICS</c> §Input).
/// </summary>
public sealed class ControllerAndBatteryTests
{
private static BatteryReading Percent(int level, BatteryState state = BatteryState.Discharging) => new(state, BatteryScale.Percent, level);
[Theory]
[InlineData(ControllerCatalog.Microsoft, false, ControllerFamily.Xbox)]
[InlineData(ControllerCatalog.Sony, false, ControllerFamily.PlayStation)]
[InlineData(ControllerCatalog.Nintendo, false, ControllerFamily.Nintendo)]
[InlineData(0x2DC8, true, ControllerFamily.Xbox)] // another maker's pad that Windows presents through XInput
[InlineData(0x2DC8, false, ControllerFamily.Other)]
[InlineData(0, true, ControllerFamily.Xbox)] // one of XInput's pads that nothing named
public void AFamilyIsTheMakerOrWhatWindowsPresentsThePadAs(int vendor, bool xinput, ControllerFamily family) =>
ControllerCatalog.FamilyOf(vendor, xinput).Should().Be(family);
[Fact]
public void AModelHasANameOnlyWhereThisBuildListsIt()
{
ControllerCatalog.ModelOf(ControllerCatalog.Sony, ControllerCatalog.DualSense).Should().Be("DualSense");
ControllerCatalog.ModelOf(ControllerCatalog.Sony, ControllerCatalog.DualSenseEdge).Should().Be("DualSense Edge");
ControllerCatalog.ModelOf(ControllerCatalog.Microsoft, 0x0B12).Should().Be("Xbox Wireless Controller");
ControllerCatalog.ModelOf(ControllerCatalog.Microsoft, 0xFFFF).Should().BeNull("a wrong name would be worse than none");
ControllerCatalog.ModelOf(0, 0).Should().BeNull();
}
[Fact]
public void SteamsVirtualGamepadIsAPadAProgramPresents()
{
ControllerCatalog.IsVirtual(ControllerCatalog.Valve, ControllerCatalog.SteamVirtualGamepad).Should().BeTrue();
ControllerCatalog.IsVirtual(ControllerCatalog.Valve, 0x1142).Should().BeFalse("a Steam Controller is one a player holds");
ControllerCatalog.IsVirtual(ControllerCatalog.Microsoft, 0x028E).Should().BeFalse();
}
[Fact]
public void OnlySonysTwoDualSensesAreReadByTheDualSenseParser()
{
ControllerCatalog.IsDualSense(ControllerCatalog.Sony, ControllerCatalog.DualSense).Should().BeTrue();
ControllerCatalog.IsDualSense(ControllerCatalog.Sony, ControllerCatalog.DualSenseEdge).Should().BeTrue();
ControllerCatalog.IsDualSense(ControllerCatalog.Sony, 0x09CC).Should().BeFalse("a DualShock 4 has another layout");
ControllerCatalog.IsDualSense(ControllerCatalog.Microsoft, ControllerCatalog.DualSense).Should().BeFalse();
}
[Fact]
public void AnXInputPadAtRestIsNotInUse() =>
XInputPad.IsActive(0, 0, 0, 0, 0, 0, 0).Should().BeFalse();
[Theory]
[InlineData(0x1000, 0, 0, 0, 0, 0, 0)] // a button
[InlineData(0, 31, 0, 0, 0, 0, 0)] // the left trigger past the threshold
[InlineData(0, 0, 255, 0, 0, 0, 0)] // the right trigger
[InlineData(0, 0, 0, 7850, 0, 0, 0)] // the left stick just outside its dead zone
[InlineData(0, 0, 0, 0, -32768, 0, 0)] // held fully down
[InlineData(0, 0, 0, 0, 0, 6200, 6200)] // the right stick, diagonally outside
public void AButtonATriggerOrAStickOutsideItsDeadZoneIsAPadInUse(int buttons, int lt, int rt, int lx, int ly, int rx, int ry) =>
XInputPad.IsActive(buttons, lt, rt, lx, ly, rx, ry).Should().BeTrue();
[Theory]
[InlineData(0, 30, 30, 0, 0, 0, 0)] // triggers at the threshold
[InlineData(0, 0, 0, 7849, 0, 0, 0)] // on the edge of the left dead zone
[InlineData(0, 0, 0, 5000, 5000, 0, 0)] // drift
[InlineData(0, 0, 0, 0, 0, 8689, 0)] // on the edge of the right dead zone
public void DriftInsideADeadZoneIsNotUse(int buttons, int lt, int rt, int lx, int ly, int rx, int ry) =>
XInputPad.IsActive(buttons, lt, rt, lx, ly, rx, ry).Should().BeFalse();
[Fact]
public void XInputsBatteryWordsAreAWiredPadFourLevelsOrNothing()
{
XInputPad.Battery(type: 1, level: 0).Should().Be(BatteryReading.Wired);
XInputPad.Battery(type: 2, level: 0).Should().Be(new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, 0));
XInputPad.Battery(type: 3, level: 3).Should().Be(new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, 3));
XInputPad.Battery(type: 3, level: 9).Should().Be(new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, 3), "a level past full is full");
XInputPad.Battery(type: 0, level: 0).Should().BeNull("disconnected");
XInputPad.Battery(type: 0xFF, level: 2).Should().BeNull("a type XInput itself calls unknown has nothing to show");
}
[Fact]
public void LowIsEmptyOrLowOrTenPerCentAndOnlyOnBattery()
{
new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, 1).IsLow.Should().BeTrue();
new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, 2).IsLow.Should().BeFalse();
Percent(10).IsLow.Should().BeTrue();
Percent(20).IsLow.Should().BeFalse();
Percent(10, BatteryState.Unknown).IsLow.Should().BeTrue("a level with no state is still a level");
Percent(10, BatteryState.Charging).IsLow.Should().BeFalse("it is on power");
BatteryReading.Wired.IsLow.Should().BeFalse();
}
[Fact]
public void TheLongestStateIsTheOneReadForTheMostTime()
{
var tally = new BatteryTally();
tally.Any.Should().BeFalse();
tally.Add(Percent(80), 600_000);
tally.Add(Percent(70), 1_500_000);
tally.Add(Percent(70), 300_000);
tally.Add(Percent(60), 200_000);
tally.Add(Percent(60), -5);
BatterySummary summary = tally.Summary();
tally.Any.Should().BeTrue();
summary.Longest.Should().Be(new BatteryStateTime(BatteryState.Discharging, BatteryScale.Percent, 70, 1_800_000));
summary.States.Select(static s => s.Level).Should().Equal(70, 80, 60);
summary.First.Should().Be(Percent(80));
summary.Last.Should().Be(Percent(60));
}
[Fact]
public void AnEmptyTallyHasNoLongestState()
{
BatterySummary summary = new BatteryTally().Summary();
summary.Longest.Should().BeNull();
summary.First.Should().BeNull();
summary.DrainPercentPerHour.Should().BeNull();
}
[Fact]
public void TheDrainIsTheFallOverTheTimeOnBattery()
{
var tally = new BatteryTally();
tally.Add(Percent(90), 1_800_000);
tally.Add(Percent(80), 1_800_000);
tally.Add(Percent(70), 1_800_000);
// Twenty points in an hour and a half.
tally.Summary().DrainPercentPerHour.Should().Be(13.3);
}
[Fact]
public void NoDrainIsWorkedOutFromTooLittleTimeARiseAChargeOrFourLevels()
{
var brief = new BatteryTally();
brief.Add(Percent(90), 200_000);
brief.Add(Percent(80), 200_000);
brief.Summary().DrainPercentPerHour.Should().BeNull("under ten minutes, a level that moves in tens says nothing");
var steady = new BatteryTally();
steady.Add(Percent(80), 3_600_000);
steady.Summary().DrainPercentPerHour.Should().BeNull("it did not fall");
var charged = new BatteryTally();
charged.Add(Percent(40), 1_200_000);
charged.Add(Percent(50, BatteryState.Charging), 1_200_000);
charged.Add(Percent(30), 1_200_000);
charged.Summary().DrainPercentPerHour.Should().BeNull("it was put on power in between: the fall is not one run");
var chargedFirst = new BatteryTally();
chargedFirst.Add(Percent(100, BatteryState.Full), 600_000);
chargedFirst.Add(Percent(100), 1_800_000);
chargedFirst.Add(Percent(80), 1_800_000);
chargedFirst.Summary().DrainPercentPerHour.Should().Be(20, "being on power before it began to run down breaks nothing");
var levels = new BatteryTally();
levels.Add(new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, 3), 3_600_000);
levels.Add(new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, 1), 3_600_000);
levels.Summary().DrainPercentPerHour.Should().BeNull("four words are not per cent");
}
}
@@ -0,0 +1,173 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FluentAssertions;
using FrameLedger.Domain.Input;
namespace FrameLedger.Domain.Tests.Input;
/// <summary>
/// The three input reports of a DualSense (<c>21_INPUT_DEVICES</c> §DualSense), as bytes written here from the layout:
/// <b>none of them came from a pad</b>. They hold what the reader takes from a report - in use or not, and the battery
/// where the report has one - and that a Bluetooth pad's short report is not read as a USB one.
/// </summary>
public sealed class DualSenseReportTests
{
private const int _hatNeutral = 0x08;
/// <summary>A USB report of a pad at rest: sticks centred, hat neutral, nothing down, the battery byte as given.</summary>
private static byte[] Usb(byte status = 0x08)
{
byte[] report = new byte[DualSenseReport.UsbLength];
report[0] = 0x01;
report[1] = report[2] = report[3] = report[4] = 128;
report[8] = _hatNeutral;
report[53] = status;
return report;
}
/// <summary>The same body behind a Bluetooth extended report's two leading bytes.</summary>
private static byte[] BluetoothFull(byte status = 0x08)
{
byte[] report = new byte[DualSenseReport.BluetoothLength];
report[0] = 0x31;
Usb(status).AsSpan(1).CopyTo(report.AsSpan(2));
return report;
}
/// <summary>The short Bluetooth report, padded to the device's longest report as Windows hands it over.</summary>
private static byte[] BluetoothShort()
{
byte[] report = new byte[DualSenseReport.BluetoothLength];
report[0] = 0x01;
report[1] = report[2] = report[3] = report[4] = 128;
report[5] = _hatNeutral;
return report;
}
[Fact]
public void APadAtRestIsNotInUse()
{
DualSenseReport.TryRead(Usb(), bluetooth: false, out bool active, out _).Should().BeTrue();
active.Should().BeFalse();
}
[Theory]
[InlineData(1, 200)] // left stick, x
[InlineData(2, 40)] // left stick, y
[InlineData(3, 255)] // right stick, x
[InlineData(4, 0)] // right stick, y
[InlineData(5, 200)] // left trigger
[InlineData(6, 31)] // right trigger, just past the threshold
[InlineData(8, 0x00)] // the hat, up
[InlineData(8, 0x28)] // a face button, the hat neutral
[InlineData(9, 0x01)] // a shoulder button
[InlineData(10, 0x01)] // the PS button
public void AnythingMovedOrHeldIsAPadInUse(int index, byte value)
{
byte[] report = Usb();
report[index] = value;
DualSenseReport.TryRead(report, bluetooth: false, out bool active, out _).Should().BeTrue();
active.Should().BeTrue();
}
[Theory]
[InlineData(1, 128 + DualSenseReport.StickDeadzone)] // a stick that drifts inside its dead zone
[InlineData(5, DualSenseReport.TriggerThreshold)] // a trigger at the threshold, not past it
[InlineData(7, 0xFF)] // the counter between the triggers and the buttons
[InlineData(16, 0xFF)] // the gyroscope: a pad lying on a desk still reports it
[InlineData(33, 0x7F)] // the touchpad
public void WhatIsNotAButtonAStickOrATriggerIsNotUse(int index, byte value)
{
byte[] report = Usb();
report[index] = value;
DualSenseReport.TryRead(report, bluetooth: false, out bool active, out _).Should().BeTrue();
active.Should().BeFalse("drift, the report counter, motion and the touchpad are not the pad being played with");
}
[Theory]
[InlineData(0x08, BatteryState.Discharging, 80)]
[InlineData(0x00, BatteryState.Discharging, 0)]
[InlineData(0x0A, BatteryState.Discharging, 100)]
[InlineData(0x0F, BatteryState.Discharging, 100)] // a level past ten is ten
[InlineData(0x15, BatteryState.Charging, 50)]
[InlineData(0x2A, BatteryState.Full, 100)]
[InlineData(0x20, BatteryState.Full, 100)] // full is 100 whatever the level bits say
[InlineData(0xA4, BatteryState.Unknown, 40)] // not charging: voltage or temperature
[InlineData(0xF3, BatteryState.Unknown, 30)] // a charging fault
public void TheBatteryByteIsALevelInTenthsAndWhatTheBatteryIsDoing(byte status, BatteryState state, int level)
{
DualSenseReport.TryRead(Usb(status), bluetooth: false, out _, out BatteryReading? battery).Should().BeTrue();
battery.Should().Be(new BatteryReading(state, BatteryScale.Percent, level));
}
[Fact]
public void TheExtendedBluetoothReportIsTheUsbBodyOneByteLater()
{
byte[] report = BluetoothFull(0x16);
report[2 + 4] = 255; // the left trigger, where the USB report has it at 5
DualSenseReport.TryRead(report, bluetooth: true, out bool active, out BatteryReading? battery).Should().BeTrue();
active.Should().BeTrue();
battery.Should().Be(new BatteryReading(BatteryState.Charging, BatteryScale.Percent, 60));
}
/// <summary>
/// Windows hands the short report over at the length of the device's longest, with the id the USB report has. Read
/// as a USB report it would be a pad with an empty battery and its buttons taken for triggers.
/// </summary>
[Fact]
public void TheShortBluetoothReportHasNoBatteryAndIsNotReadAsAUsbOne()
{
DualSenseReport.TryRead(BluetoothShort(), bluetooth: true, out bool active, out BatteryReading? battery).Should().BeTrue();
active.Should().BeFalse();
battery.Should().BeNull("the short report carries none: over Bluetooth the level is there only once something switched the pad");
}
[Theory]
[InlineData(1, 0)] // a stick
[InlineData(5, 0x00)] // the hat, up
[InlineData(6, 0x02)] // a shoulder button
[InlineData(7, 0x01)] // the PS button
[InlineData(8, 200)] // the left trigger
[InlineData(9, 200)] // the right trigger
public void TheShortBluetoothReportSaysWhenThePadIsInUse(int index, byte value)
{
byte[] report = BluetoothShort();
report[index] = value;
DualSenseReport.TryRead(report, bluetooth: true, out bool active, out _).Should().BeTrue();
active.Should().BeTrue();
}
[Fact]
public void TheCounterInTheShortReportsLastButtonByteIsNotAButton()
{
byte[] report = BluetoothShort();
report[7] = 0xFC; // the upper six bits count reports
DualSenseReport.TryRead(report, bluetooth: true, out bool active, out _).Should().BeTrue();
active.Should().BeFalse();
}
[Fact]
public void WhatIsNotOneOfTheThreeReportsIsRefused()
{
DualSenseReport.TryRead([], bluetooth: false, out _, out _).Should().BeFalse();
DualSenseReport.TryRead(new byte[20], bluetooth: false, out _, out _).Should().BeFalse("too short for a USB report");
DualSenseReport.TryRead(BluetoothFull(), bluetooth: false, out _, out _).Should().BeFalse("report 0x31 is not sent over USB");
DualSenseReport.TryRead([0x31, 0, 0], bluetooth: true, out _, out _).Should().BeFalse("a truncated extended report");
DualSenseReport.TryRead([0x01, 128, 128], bluetooth: true, out _, out _).Should().BeFalse("a truncated short report");
DualSenseReport.TryRead(new byte[78], bluetooth: true, out _, out _).Should().BeFalse("an unknown report id");
}
}
@@ -0,0 +1,112 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FluentAssertions;
using FrameLedger.Domain.Input;
namespace FrameLedger.Domain.Tests.Input;
/// <summary>
/// How a tick is named by what it was played with, how changes are counted, and when two entries of a session's
/// controller list are one pad (<c>03_METRICS</c> §Input).
/// </summary>
public sealed class InputSwitchesTests
{
[Fact]
public void AChangeIsCountedBetweenTwoDifferentValuesAndNothingInBetweenEndsARun()
{
InputClass?[] ticks =
[
null,
InputClass.Controller,
InputClass.Controller,
null, // the controller put down for a moment
InputClass.Controller,
InputClass.KeyboardMouse,
null,
null,
InputClass.Controller,
];
InputSwitches.Count(ticks).Should().Be(2);
}
[Fact]
public void NoTicksAndOneValueAreNoChange()
{
InputSwitches.Count(Array.Empty<InputClass?>()).Should().Be(0);
InputSwitches.Count(new InputClass?[] { null, null }).Should().Be(0);
InputSwitches.Count(new ControllerFamily?[] { ControllerFamily.Xbox, ControllerFamily.Xbox }).Should().Be(0);
InputSwitches.Count(new ControllerFamily?[] { ControllerFamily.Xbox, ControllerFamily.PlayStation, ControllerFamily.Xbox }).Should().Be(2);
}
[Theory]
[InlineData(900, 0, 0, InputClass.Controller)]
[InlineData(0, 400, 0, InputClass.KeyboardMouse)]
public void ATickPlayedWithOneThingIsThatThing(long controller, long keyboardMouse, long both, InputClass expected) =>
InputSwitches.Exclusive(controller, keyboardMouse, both).Should().Be(expected);
[Theory]
[InlineData(0, 0, 0)] // neither
[InlineData(500, 500, 0)] // one then the other within the tick
[InlineData(900, 0, 100)] // both at once for a moment
public void ATickPlayedWithBothOrWithNeitherIsNoOneThing(long controller, long keyboardMouse, long both) =>
InputSwitches.Exclusive(controller, keyboardMouse, both).Should().BeNull();
[Theory]
[InlineData(600, 300, 0, 100, InputClass.Controller)]
[InlineData(100, 700, 0, 200, InputClass.KeyboardMouse)]
[InlineData(100, 100, 500, 300, InputClass.Both)]
[InlineData(100, 100, 100, 700, InputClass.None)]
[InlineData(0, 0, 0, 1000, InputClass.None)]
[InlineData(500, 500, 0, 0, InputClass.KeyboardMouse)] // a tie goes to the one named first: none, keyboard, controller, both
public void TheDominantClassIsTheOneWithTheMostTime(long controller, long keyboardMouse, long both, long idle, InputClass expected) =>
InputSwitches.Dominant(controller, keyboardMouse, both, idle).Should().Be(expected);
[Fact]
public void ATickWithTheGameNotInFrontHasNoDominantClass() =>
InputSwitches.Dominant(0, 0, 0, 0).Should().BeNull();
[Fact]
public void TwoPadsThatMoveTogetherAreOnePad()
{
int[] held = [1000, 1000, 0, 1000, 900, 1000, 1000, 1000, 1000, 1000, 1000, 1000];
int[] presented = [1000, 900, 0, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000];
VirtualPad.Coincidence(held, presented).Should().BeGreaterThan(0.95);
VirtualPad.IsSamePad(held, presented).Should().BeTrue();
}
[Fact]
public void TwoPadsUsedAtDifferentMomentsAreTwoPads()
{
int[] first = [1000, 1000, 1000, 1000, 1000, 1000, 0, 0, 0, 0, 0, 0];
int[] second = [0, 0, 0, 0, 0, 0, 1000, 1000, 1000, 1000, 1000, 1000];
VirtualPad.Coincidence(first, second).Should().Be(0);
VirtualPad.IsSamePad(first, second).Should().BeFalse();
}
[Fact]
public void APadThatSharesOnlyPartOfTheBusierOnesTimeIsNotIt()
{
// Two players: the second joins for a third of the time the first plays.
int[] first = [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000];
int[] second = [1000, 1000, 1000, 1000, 0, 0, 0, 0, 0, 0, 0, 0];
VirtualPad.Coincidence(first, second).Should().BeApproximately(1 / 3d, 1e-9);
VirtualPad.IsSamePad(first, second).Should().BeFalse();
}
[Fact]
public void AFewSecondsTogetherProveNothing()
{
int[] a = [1000, 1000, 1000];
int[] b = [1000, 1000, 1000];
VirtualPad.Coincidence(a, b).Should().Be(1);
VirtualPad.IsSamePad(a, b).Should().BeFalse("under ten seconds in use");
VirtualPad.Coincidence([], []).Should().Be(0);
VirtualPad.Coincidence([0, 0], [0, 0]).Should().Be(0);
}
}