Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43e0c2b347 | ||
|
|
e24f09ae8a | ||
|
|
8b4cccbb25 | ||
|
|
2dd0e4f271 | ||
|
|
dca740e94b | ||
|
|
b29993ba82 |
No files matched your search
@@ -44,6 +44,13 @@ numeric core and does not move; the heading is the full version — corrected 20
|
||||
slices and turns them into a reading a second; `InputSessionBuilder` turns a session's readings into its totals, its
|
||||
controllers as JSON and its timeline. A telemetry sample can carry a reading; none does. **Every byte and reading
|
||||
under test was written by hand — no report from a real controller has passed through this code.**
|
||||
- **For developers: a session can store what it was played with — schema 0024** (D160; `docs/06_DATA_MODEL.md`). Nine
|
||||
columns on `sessions` (the time in front and its four classes, the switches of method, the sources that answered,
|
||||
the controllers as JSON) and three on `games` (what a store lists of controller support), ADD COLUMN only; the
|
||||
`.partial` file gains chunk 11, so a session recovered after the Agent died keeps its readings; the finalizer
|
||||
stores them for hooked and unhooked sessions alike; the input series are `sensor_blobs` rows named `input.*`, which
|
||||
the sensors' read leaves out. Nothing produces a reading yet. **A ledger this build has opened cannot be opened by
|
||||
0.1.0-beta.49 or earlier.**
|
||||
|
||||
### Changed
|
||||
|
||||
|
||||
+57
-1
@@ -342,7 +342,25 @@ CREATE TABLE sessions (
|
||||
display_source TEXT, -- swapchain | opengl | window: the strongest witness any sample had
|
||||
display_window_w INTEGER, display_window_h INTEGER, -- client area, in the mode that lasted longest (the last seen, beta.27)
|
||||
display_buffer_w INTEGER, display_buffer_h INTEGER, -- the swap chain's back buffer, same mode
|
||||
display_monitor_w INTEGER, display_monitor_h INTEGER, display_monitor_hz INTEGER
|
||||
display_monitor_w INTEGER, display_monitor_h INTEGER, display_monitor_hz INTEGER,
|
||||
|
||||
-- schema 0024 (2026-11-14, beta.50, D155-D163): what the session was played with, both tiers (03_METRICS §Input) -
|
||||
-- read by the Agent from outside the game. Milliseconds. NULL before, with the option off, and before the terms
|
||||
-- that describe the reading were accepted - N/A, never 0. From the samples, so a recovered session has them.
|
||||
input_observed_ms INTEGER, -- the reader ran and the session was not paused
|
||||
input_foreground_ms INTEGER, -- of it, a window of the game was in front: the four below add up to this
|
||||
input_controller_ms INTEGER, -- a controller in use, the keyboard and mouse not
|
||||
input_km_ms INTEGER, -- the keyboard or mouse in use (one class - only a time is read), no controller
|
||||
input_both_ms INTEGER,
|
||||
input_idle_ms INTEGER, -- no input at all
|
||||
input_method_switches INTEGER, -- changes between a controller and the keyboard and mouse
|
||||
input_source TEXT, -- the sources that answered: rawinput, xinput, lastinput, joined by +
|
||||
input_devices TEXT -- InputDevicesRecord's JSON: {"V":1,"Devices":[{"Index","Family","VendorId",
|
||||
-- "ProductId","Model","Connection","XInputSlot","Virtual","Remapped",
|
||||
-- "ConnectedMs","ActiveMs","Connects","Disconnects","Battery":{"Scale",
|
||||
-- "States":[{"State","Level","Ms"}],"First","Last","DrainPercentPerHour"}}],
|
||||
-- "Families":[{"Family","ActiveMs","Share"}],"FamilySwitches","VirtualPad",
|
||||
-- "Health":{...counts...}} - no serial number, no address, no path
|
||||
);
|
||||
CREATE INDEX ix_sessions_game_started ON sessions(game_id, started_at DESC);
|
||||
|
||||
@@ -402,6 +420,12 @@ CREATE TABLE sensor_blobs (
|
||||
-- since schema 0023 (2026-11-11, D102) also the ADVANCED series, every one under a name
|
||||
-- that starts with `adv.` (Application.Advanced.AdvancedMetricCatalog): NaN, not -1,
|
||||
-- for a tick with no reading, and read by FindAdvancedSensorsAsync only
|
||||
-- since schema 0024 (2026-11-14, D155-D163) also the INPUT series, every one under a
|
||||
-- name that starts with `input.`: input.class (what the tick was mostly played with:
|
||||
-- 0 no input, 1 controller, 2 keyboard and mouse, 3 both), input.dev.N.active (the
|
||||
-- part of the tick's time in front controller N was in use, 0-1) and
|
||||
-- input.dev.N.battery (its level, in its own scale) - NaN for a tick with nothing to
|
||||
-- say, and read by FindInputSensorsAsync only
|
||||
-- cpu_load / ram_mb / cpu_temp and sessions.avg_cpu_load, avg_cpu_temp, max_cpu_temp,
|
||||
-- avg_ram_mb were in schema 0001 with NO producer until 2026-09-21 (Telemetry.SystemTelemetrySource
|
||||
-- on the poller's tick). Rows before that date hold NULL, which is what they measured; no migration.
|
||||
@@ -528,6 +552,15 @@ Because Tier-1 and Tier-2 sessions carry different fields, every query that comp
|
||||
> (`AdvancedSessionBuilder.MaxSeries`); what is beyond is counted in its directory, not stored.
|
||||
> **Size, measured 2026-11-11** on values shaped like the dev box's reader (17 series with a reading every tick, 41
|
||||
> with one every fifth): one hour is 816 KiB raw and **189 KiB stored** — well inside NFR-5's 3 MB an hour.
|
||||
>
|
||||
> **The input series follow the same rule under their own name (schema 0024, owner decisions D155–D163).** A series
|
||||
> whose name starts with `input.` stores NaN for a tick with nothing to say — the game was not in front, the
|
||||
> controller was not connected, the tick carried no reading — through the same sparse encoder. `FindSensorsAsync`
|
||||
> leaves them out as well (`series NOT LIKE 'input.%'`): a class's number is not a sensor's value, and the sensors'
|
||||
> statistics and chart would take it for one. `FindInputSensorsAsync` returns them with `t_ms` first. A session
|
||||
> stores `input.class` and, for each of its first eight controllers (`InputSessionBuilder.MaxDevices`),
|
||||
> `input.dev.N.active` and — where the battery has a level — `input.dev.N.battery`: at most seventeen, a few KiB an
|
||||
> hour stored.
|
||||
|
||||
## The `.partial` file
|
||||
|
||||
@@ -552,6 +585,7 @@ Because Tier-1 and Tier-2 sessions carry different fields, every query that comp
|
||||
> | 8 `SensorsWide` | the same samples under a 32-bit presence mask that carries the game process's memory (D43) | each flush, since beta.12 *(row added 2026-10-04)* |
|
||||
> | 9 `SensorsAdvanced` | the advanced readings of the samples of the type-8 chunk before it (D101): `u16` names, then per name `u16` bytes and UTF-8; `u32` samples, then per sample `i64` QPC, `u16` readings and per reading `u16` name, `f64` value. Each chunk carries its own names, so it reads without any earlier chunk | each flush **in which a sample carries any** — with Advanced metrics off, never; the file is then byte for byte what it was (2026-11-11) |
|
||||
> | 10 `AdvancedContext` | UTF-8 JSON (`AdvancedJson.OfContext`): the PC's facts, the session's, its series' directory, each source's state; the last one wins | the first flush after the recorder set it, and again only when it changed (2026-11-11) |
|
||||
> | 11 `SensorsInput` | the input readings of the samples of the type-8 chunk before it (D155–D163, `InputSampleCodec`): `u32` samples, then per sample `i64` QPC, seven `i32` (span, observed, in front, controller, keyboard and mouse, both, no input), `u8` flags, the reader's health (`u8` answers, six `i64` counts, `i32` faults), `u8` controllers and 23 bytes a controller — what it is (maker, the two USB ids, connection, XInput pad) and its part of the tick (connected, time in use, battery, connections, drops). Each sample describes every controller it counts, so a chunk reads without any earlier one | each flush **in which a sample carries one** — with the option off, never; the file is then byte for byte what it was (2026-11-14) |
|
||||
>
|
||||
> **A chunk of a type the reader does not know is skipped, not the end of the file (owner decision D106,
|
||||
> 2026-11-11).** Its length and checksum have been verified by then, so it is a whole chunk a newer build wrote.
|
||||
@@ -802,6 +836,28 @@ Sequential embedded SQL (`Migrations/0001_init.sql`, `0002_*.sql`, …), applied
|
||||
> **Nothing produces a row yet**: the option that switches the reader on is the next pull request's.
|
||||
> **A beta.38 cannot open a ledger a later build migrated.**
|
||||
|
||||
> **`0024_input_devices.sql` (0.1.0-beta.50, 2026-11-14, owner decisions D155–D163) — what a session was played
|
||||
> with, and what a store lists.** ADD COLUMN only, twelve columns. **Nine on `sessions`**: `input_observed_ms`,
|
||||
> `input_foreground_ms` and the four classes that add up to it (`input_controller_ms`, `input_km_ms`,
|
||||
> `input_both_ms`, `input_idle_ms`), `input_method_switches`, `input_source`, and `input_devices` — the session's
|
||||
> controllers as `Application.Recording.InputDevicesRecord`'s JSON (`03_METRICS` §Input). **On `sessions` and not in
|
||||
> a table of their own, on purpose** (D160) — the opposite of 0023's choice, for the opposite reason: the trend and
|
||||
> the comparison read a session's row, and these numbers are meant to be in the JSON export and the bug bundle,
|
||||
> which carry the whole row; the Privacy Policy's §3A says so. What may never be a column or a key of that JSON: a
|
||||
> controller's serial number, its Bluetooth address, its device path
|
||||
> (`LedgerDatabaseTests.ScriptTwentyFourOnlyAddsColumnsAndNamesNoIdentifier`,
|
||||
> `InputSessionBuilderTests.TheStoredJsonHasNoKeyThatCouldCarryASerialNumberAnAddressOrAPath`). **Three on
|
||||
> `games`**: `controller_support` (`full`, `partial`, or `none` for a game the store knows and lists no support
|
||||
> for), `controller_support_source` (`steam-appinfo`) and `controller_support_at` — the store's own word, from its
|
||||
> file on the disk, never a verdict of FrameLedger's (D163). Written by `SessionFinalizer.Build` from the session's
|
||||
> samples, before the tier branch — both tiers, and a session recovered from its crash file, which carries the
|
||||
> readings in chunk 11. NULL before; with the option off; before the terms that describe the reading were accepted
|
||||
> (D156); on a game no store file describes. The series are `sensor_blobs` rows named `input.*` (§Blob encoding).
|
||||
> `LatestVersion` is 24; `LedgerDatabaseTests.ScriptTwentyFourAddsTheInputColumnsAndAnEarlierSessionAndGameHaveNone`,
|
||||
> the repository round trip. **Nothing produces a reading yet, and nothing writes the three `games` columns yet**:
|
||||
> the reader, the switch and the store file are the pull requests after this one.
|
||||
> **A beta.49 cannot open a ledger a later build migrated.**
|
||||
|
||||
> **`0022_dlss_nr.sql` (beta.34, 2026-11-06, owner decision D84) — DLSS 5's neural rendering, measured.** One REAL column,
|
||||
> ADD COLUMN only: `dlss_nr_pct`, the share (0–100) of the presents that drained a Streamline evaluation on which the game
|
||||
> evaluated `kFeatureDLSS_NR` (`Domain.Metrics.NeuralRendering`). Written by the recorder's aggregation
|
||||
|
||||
@@ -6,8 +6,9 @@ The numbers a session makes of it are in [`03_METRICS.md`](03_METRICS.md) §Inpu
|
||||
|
||||
> **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**
|
||||
> reading was written by hand; and a session can store what it is given — schema 0024, the `.partial` file's chunk
|
||||
> 11, the finalizer for both tiers (`06_DATA_MODEL`). The reader, 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)
|
||||
|
||||
@@ -128,6 +128,19 @@ public sealed record GameRow
|
||||
/// </summary>
|
||||
public AntiCheatExceptionState AcException { get; init; } = AntiCheatExceptionState.None;
|
||||
|
||||
/// <summary>
|
||||
/// What the store's own file on the disk says of controller support (schema 0024, D163): <c>full</c>, <c>partial</c>,
|
||||
/// or <c>none</c> for a game the store knows and lists no support for. Null when no store file describes the game or
|
||||
/// none was read yet. It is the store's word, one of three pieces of evidence - never a verdict of FrameLedger's.
|
||||
/// </summary>
|
||||
public string? ControllerSupport { get; init; }
|
||||
|
||||
/// <summary>The file <see cref="ControllerSupport"/> was read from: <c>steam-appinfo</c> (schema 0024).</summary>
|
||||
public string? ControllerSupportSource { get; init; }
|
||||
|
||||
/// <summary>When <see cref="ControllerSupport"/> was read (schema 0024).</summary>
|
||||
public DateTimeOffset? ControllerSupportAt { get; init; }
|
||||
|
||||
public bool InLibrary => RemovedAt is null;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -88,6 +88,14 @@ public interface ISessionRepository
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<SensorBlob>> FindAdvancedSensorsAsync(long sessionId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The session's input series (schema 0024, <c>03_METRICS</c> §Input), still encoded, with <c>t_ms</c> first: what
|
||||
/// each tick was mostly played with, and each controller's part and battery. For a session that stored none that
|
||||
/// is <c>t_ms</c> alone, or nothing. They are not among <see cref="FindSensorsAsync"/>'s for the reason the advanced
|
||||
/// ones are not: NaN marks a tick with nothing to say, and their values are not a sensor's.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<SensorBlob>> FindInputSensorsAsync(long sessionId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The session's row of <c>session_advanced</c> with the machine profile it points to, or null: it was recorded
|
||||
/// with Advanced metrics off (or before they existed).
|
||||
|
||||
@@ -401,4 +401,38 @@ public sealed record SessionRow
|
||||
|
||||
/// <summary>Application frames per joule of the card's power — FPS per watt; never over displayed frames (rule 6).</summary>
|
||||
public double? AppFramesPerJoule { get; init; }
|
||||
|
||||
// --- Schema 0024 (beta.50, D155-D163): what the session was played with (03_METRICS §Input), both tiers - read by the
|
||||
// Agent from outside the game. Null on a row written before it, with the option off, and before the terms that
|
||||
// describe the reading were accepted.
|
||||
|
||||
/// <summary>The time the input reader ran and the session was not paused, in milliseconds.</summary>
|
||||
public long? InputObservedMs { get; init; }
|
||||
|
||||
/// <summary>Of <see cref="InputObservedMs"/>, the time a window of the game was in front: what every share is a share of.</summary>
|
||||
public long? InputForegroundMs { get; init; }
|
||||
|
||||
/// <summary>The time in front a controller was in use and the keyboard and mouse were not.</summary>
|
||||
public long? InputControllerMs { get; init; }
|
||||
|
||||
/// <summary>The time in front the keyboard or mouse was in use and no controller was. One class: only the time of the last input is read (D158).</summary>
|
||||
public long? InputKeyboardMouseMs { get; init; }
|
||||
|
||||
public long? InputBothMs { get; init; }
|
||||
|
||||
/// <summary>The time in front with no input at all.</summary>
|
||||
public long? InputIdleMs { get; init; }
|
||||
|
||||
/// <summary>How many times the player went from a controller to the keyboard and mouse or back.</summary>
|
||||
public int? InputMethodSwitches { get; init; }
|
||||
|
||||
/// <summary>The sources that answered: <c>rawinput</c>, <c>xinput</c>, <c>lastinput</c>, joined by <c>+</c>.</summary>
|
||||
public string? InputSource { get; init; }
|
||||
|
||||
/// <summary>The session's controllers, their batteries and makers, and what the reader's sources did, as <c>InputDevicesRecord</c>'s JSON.</summary>
|
||||
public string? InputDevicesJson { get; init; }
|
||||
|
||||
/// <summary>The share of the time in front spent in one class, 0-100; null when nothing was read or the game was never in front.</summary>
|
||||
public double? InputSharePercent(long? classMs) =>
|
||||
InputForegroundMs is > 0 and var front && classMs is { } ms ? 100d * ms / front : null;
|
||||
}
|
||||
@@ -61,6 +61,12 @@ public sealed class SessionFinalizer
|
||||
// hooked has them all the same. Nothing when the option was off - no series, no row.
|
||||
double hz = SampleRate(input.Sensors, row.QpcFrequency);
|
||||
(IReadOnlyList<SensorBlob> advancedBlobs, AdvancedSessionRow? advanced) = AdvancedSessionBuilder.Build(input.Sensors, input.Advanced, _codec, hz);
|
||||
|
||||
// What the session was played with (D155-D163), both tiers and for the same reason: the Agent reads it from outside
|
||||
// the game. From the samples alone, so a session recovered from its .partial file has it. Nothing when no sample
|
||||
// carries a reading - the option was off, or the terms that describe the reading were not accepted yet.
|
||||
(IReadOnlyList<SensorBlob> inputBlobs, InputSessionSummary? played) = InputSessionBuilder.Build(input.Sensors, _codec, hz);
|
||||
row = WithInput(row, played);
|
||||
if (input.Hooked is null)
|
||||
{
|
||||
// A Tier-2 row has no frames and every sensor the machine provided (2026-09-22): the same averages a
|
||||
@@ -68,7 +74,7 @@ public sealed class SessionFinalizer
|
||||
return new FinalizedSession
|
||||
{
|
||||
Row = SessionAggregator.WithSensorAggregates(row with { Tier = CaptureTier.NotHooked }, input.Sensors),
|
||||
Sensors = [.. EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency, hz), .. advancedBlobs],
|
||||
Sensors = [.. EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency, hz), .. advancedBlobs, .. inputBlobs],
|
||||
Advanced = advanced,
|
||||
};
|
||||
}
|
||||
@@ -83,11 +89,27 @@ public sealed class SessionFinalizer
|
||||
{
|
||||
FirstPresentMs = FirstPresentMs(r.Dominant, row.QpcEpoch, row.QpcFrequency),
|
||||
},
|
||||
Sensors = [.. EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency, hz), .. advancedBlobs],
|
||||
Sensors = [.. EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency, hz), .. advancedBlobs, .. inputBlobs],
|
||||
Advanced = advanced,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The row with what the session was played with (schema 0024); unchanged when nothing was read.</summary>
|
||||
private static SessionRow WithInput(SessionRow row, InputSessionSummary? played) => played is null
|
||||
? row
|
||||
: row with
|
||||
{
|
||||
InputObservedMs = played.ObservedMs,
|
||||
InputForegroundMs = played.ForegroundMs,
|
||||
InputControllerMs = played.ControllerMs,
|
||||
InputKeyboardMouseMs = played.KeyboardMouseMs,
|
||||
InputBothMs = played.BothMs,
|
||||
InputIdleMs = played.IdleMs,
|
||||
InputMethodSwitches = played.MethodSwitches,
|
||||
InputSource = played.Source,
|
||||
InputDevicesJson = played.DevicesJson,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The rate the session's samples had, a second (owner decision D146): the gaps between the first and the last
|
||||
/// over the time between them, to a thousandth. 1 where there are fewer than two samples or no time between them.
|
||||
|
||||
@@ -19,7 +19,6 @@ public static class XInputPad
|
||||
/// <summary><c>XINPUT_GAMEPAD_TRIGGER_THRESHOLD</c>.</summary>
|
||||
public const int TriggerThreshold = 30;
|
||||
|
||||
private const int _typeDisconnected = 0x00;
|
||||
private const int _typeWired = 0x01;
|
||||
private const int _typeAlkaline = 0x02;
|
||||
private const int _typeNimh = 0x03;
|
||||
@@ -42,7 +41,8 @@ public static class XInputPad
|
||||
{
|
||||
_typeWired => BatteryReading.Wired,
|
||||
_typeAlkaline or _typeNimh => new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, Math.Clamp(level, 0, _levelFull)),
|
||||
_typeDisconnected => null,
|
||||
|
||||
// 0 is XInput's "disconnected" and 0xFF its "unknown": neither is a battery to show.
|
||||
_ => null,
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
-- 0024 (2026-11-14, 0.1.0-beta.50, owner decisions D155-D163): what a session was played with, and whether a game's
|
||||
-- store lists controller support (03_METRICS §Input, 21_INPUT_DEVICES).
|
||||
--
|
||||
-- sessions: milliseconds, read by the Agent from outside the game - so both tiers have them. `input_observed_ms` is the
|
||||
-- time the reader ran and the session was not paused; `input_foreground_ms` is the part of it a window of the game was
|
||||
-- in front, and the four classes add up to it: a controller in use, the keyboard or mouse in use (one class - only the
|
||||
-- time of the last input is read), both, neither. `input_method_switches` counts the changes between a controller and
|
||||
-- the keyboard and mouse. `input_source` names the sources that answered (rawinput, xinput, lastinput, joined by +).
|
||||
-- `input_devices` is InputDevicesRecord's JSON: each controller's maker, model and connection, its time connected and
|
||||
-- in use, its connections and drops, its battery; each maker's share; what the reader's sources did. No serial number,
|
||||
-- no address, no path. The series of the timeline are sensor_blobs rows named input.* (NaN where there is no value).
|
||||
--
|
||||
-- These are columns of sessions, not a table of their own, on purpose (D160): the trend and the comparison read a
|
||||
-- session's row, and the CSV/JSON export and the bug bundle carry it - the Privacy Policy's section 3A says so.
|
||||
--
|
||||
-- games: `controller_support` is what the store's own file on the disk says - 'full', 'partial', or 'none' for a game
|
||||
-- the store knows and lists no support for; `controller_support_source` names the file ('steam-appinfo');
|
||||
-- `controller_support_at` is when it was read (unix ms). No network request is made for it.
|
||||
--
|
||||
-- NULL on every row written before; on a session recorded with the option off, or before the terms that describe the
|
||||
-- reading were accepted (D156); on a game no store file describes. ADD COLUMN only.
|
||||
|
||||
ALTER TABLE sessions ADD COLUMN input_observed_ms INTEGER;
|
||||
ALTER TABLE sessions ADD COLUMN input_foreground_ms INTEGER;
|
||||
ALTER TABLE sessions ADD COLUMN input_controller_ms INTEGER;
|
||||
ALTER TABLE sessions ADD COLUMN input_km_ms INTEGER;
|
||||
ALTER TABLE sessions ADD COLUMN input_both_ms INTEGER;
|
||||
ALTER TABLE sessions ADD COLUMN input_idle_ms INTEGER;
|
||||
ALTER TABLE sessions ADD COLUMN input_method_switches INTEGER;
|
||||
ALTER TABLE sessions ADD COLUMN input_source TEXT;
|
||||
ALTER TABLE sessions ADD COLUMN input_devices TEXT;
|
||||
|
||||
ALTER TABLE games ADD COLUMN controller_support TEXT;
|
||||
ALTER TABLE games ADD COLUMN controller_support_source TEXT;
|
||||
ALTER TABLE games ADD COLUMN controller_support_at INTEGER;
|
||||
@@ -19,10 +19,10 @@ namespace FrameLedger.Infrastructure.Persistence;
|
||||
internal static class SessionRowColumns
|
||||
{
|
||||
public const string Insert =
|
||||
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz, game_vram_dedicated_avg_mb, game_vram_dedicated_median_mb, game_vram_dedicated_max_mb, game_vram_shared_max_mb, game_ram_private_avg_mb, game_ram_private_median_mb, game_ram_private_max_mb, game_ram_ws_max_mb, game_commit_max_mb, game_memory_processes, game_memory_source, sensor_stats_json, time_below_30_pct, time_below_60_pct, time_below_refresh_pct, frametime_delta_mean_ms, vsync_present_pct, tearing_allowed_pct, avg_gpu_core_clock_mhz, avg_gpu_mem_clock_mhz, avg_gpu_fan_rpm, max_gpu_mem_temp, power_limit_pct, thermal_limit_pct, app_frames_per_joule, fg_mix, runtime_module_sources, dlss_nr_pct) "
|
||||
+ "VALUES (@session_guid, @game_id, @snapshot_id, @started_at, @ended_at, @duration_s, @qpc_epoch, @qpc_frequency, @capture_tier, @capture_mode, @capture_notes, @ac_exception_family, @late_attach, @telemetry_source, @overlay_build_id, @exit_status, @drain_ticks, @foreground_ticks, @records_before_attach, @dxgi_presents_before_hook, @gap_count, @guard_ticks_published, @launch_wait_ms, @api, @present_mode, @swap_effect, @hdr_flag, @hdr_source, @sync_interval_mode, @upscaler, @upscaler_quality, @upscaler_sharpness, @upscaler_driver_reported, @render_w, @render_h, @output_w, @output_h, @upscale_ratio, @settings_changed_midsession, @fg_mode, @fg_source, @fg_factor, @fg_driver_reported, @fg_runtime_census, @fg_none_withheld_reason, @fg_refusal, @fg_refusal_detail, @fg_factor_scope, @fg_steady_share, @presented_fps, @presented_qualifier, @dxgi_unseen_total, @dxgi_present_samples, @displayed_counted_by, @sl_tag_census, @sl_interposer_version, @runtime_modules, @driver_profile, @executable_markers, @ngx_driver_words, @rt_flag, @rt_source, @pt_flag, @pt_source, @pt_confidence, @rr_flag, @rr_source, @rt_frame_pct, @rays_per_pixel, @rt_pso_count, @rt_tier, @hooks_installed_mask, @raster_pso_count, @frame_count, @app_frame_count, @displayed_frame_count, @dropped_frames, @native_fps, @displayed_fps, @median_fps, @p1_low_fps, @p01_low_fps, @displayed_p1_low_fps, @min_fps, @max_fps, @frametime_stddev_ms, @stutter_count, @stutter_time_pct, @pso_stutter_pct, @reflex_active, @latency_avg_us, @latency_p95_us, @dropped_records, @fault_count, @data_quality_warnings, @writer_status_at_end, @early_stop_family, @loader_signals, @vram_proc_avg_mb, @vram_proc_max_mb, @vram_budget_exceeded_pct, @vram_adapter_max_mb, @avg_cpu_temp, @max_cpu_temp, @avg_gpu_temp, @max_gpu_temp, @max_gpu_hotspot, @avg_gpu_load, @avg_cpu_load, @avg_ram_mb, @avg_gpu_power_w, @throttle_pct, @display_exclusive_ms, @display_borderless_ms, @display_windowed_ms, @display_covers_ms, @display_minimized_ms, @display_nowindow_ms, @display_changes, @display_source, @display_window_w, @display_window_h, @display_buffer_w, @display_buffer_h, @display_monitor_w, @display_monitor_h, @display_monitor_hz, @game_vram_dedicated_avg_mb, @game_vram_dedicated_median_mb, @game_vram_dedicated_max_mb, @game_vram_shared_max_mb, @game_ram_private_avg_mb, @game_ram_private_median_mb, @game_ram_private_max_mb, @game_ram_ws_max_mb, @game_commit_max_mb, @game_memory_processes, @game_memory_source, @sensor_stats_json, @time_below_30_pct, @time_below_60_pct, @time_below_refresh_pct, @frametime_delta_mean_ms, @vsync_present_pct, @tearing_allowed_pct, @avg_gpu_core_clock_mhz, @avg_gpu_mem_clock_mhz, @avg_gpu_fan_rpm, @max_gpu_mem_temp, @power_limit_pct, @thermal_limit_pct, @app_frames_per_joule, @fg_mix, @runtime_module_sources, @dlss_nr_pct) RETURNING id";
|
||||
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz, game_vram_dedicated_avg_mb, game_vram_dedicated_median_mb, game_vram_dedicated_max_mb, game_vram_shared_max_mb, game_ram_private_avg_mb, game_ram_private_median_mb, game_ram_private_max_mb, game_ram_ws_max_mb, game_commit_max_mb, game_memory_processes, game_memory_source, sensor_stats_json, time_below_30_pct, time_below_60_pct, time_below_refresh_pct, frametime_delta_mean_ms, vsync_present_pct, tearing_allowed_pct, avg_gpu_core_clock_mhz, avg_gpu_mem_clock_mhz, avg_gpu_fan_rpm, max_gpu_mem_temp, power_limit_pct, thermal_limit_pct, app_frames_per_joule, fg_mix, runtime_module_sources, dlss_nr_pct, input_observed_ms, input_foreground_ms, input_controller_ms, input_km_ms, input_both_ms, input_idle_ms, input_method_switches, input_source, input_devices) "
|
||||
+ "VALUES (@session_guid, @game_id, @snapshot_id, @started_at, @ended_at, @duration_s, @qpc_epoch, @qpc_frequency, @capture_tier, @capture_mode, @capture_notes, @ac_exception_family, @late_attach, @telemetry_source, @overlay_build_id, @exit_status, @drain_ticks, @foreground_ticks, @records_before_attach, @dxgi_presents_before_hook, @gap_count, @guard_ticks_published, @launch_wait_ms, @api, @present_mode, @swap_effect, @hdr_flag, @hdr_source, @sync_interval_mode, @upscaler, @upscaler_quality, @upscaler_sharpness, @upscaler_driver_reported, @render_w, @render_h, @output_w, @output_h, @upscale_ratio, @settings_changed_midsession, @fg_mode, @fg_source, @fg_factor, @fg_driver_reported, @fg_runtime_census, @fg_none_withheld_reason, @fg_refusal, @fg_refusal_detail, @fg_factor_scope, @fg_steady_share, @presented_fps, @presented_qualifier, @dxgi_unseen_total, @dxgi_present_samples, @displayed_counted_by, @sl_tag_census, @sl_interposer_version, @runtime_modules, @driver_profile, @executable_markers, @ngx_driver_words, @rt_flag, @rt_source, @pt_flag, @pt_source, @pt_confidence, @rr_flag, @rr_source, @rt_frame_pct, @rays_per_pixel, @rt_pso_count, @rt_tier, @hooks_installed_mask, @raster_pso_count, @frame_count, @app_frame_count, @displayed_frame_count, @dropped_frames, @native_fps, @displayed_fps, @median_fps, @p1_low_fps, @p01_low_fps, @displayed_p1_low_fps, @min_fps, @max_fps, @frametime_stddev_ms, @stutter_count, @stutter_time_pct, @pso_stutter_pct, @reflex_active, @latency_avg_us, @latency_p95_us, @dropped_records, @fault_count, @data_quality_warnings, @writer_status_at_end, @early_stop_family, @loader_signals, @vram_proc_avg_mb, @vram_proc_max_mb, @vram_budget_exceeded_pct, @vram_adapter_max_mb, @avg_cpu_temp, @max_cpu_temp, @avg_gpu_temp, @max_gpu_temp, @max_gpu_hotspot, @avg_gpu_load, @avg_cpu_load, @avg_ram_mb, @avg_gpu_power_w, @throttle_pct, @display_exclusive_ms, @display_borderless_ms, @display_windowed_ms, @display_covers_ms, @display_minimized_ms, @display_nowindow_ms, @display_changes, @display_source, @display_window_w, @display_window_h, @display_buffer_w, @display_buffer_h, @display_monitor_w, @display_monitor_h, @display_monitor_hz, @game_vram_dedicated_avg_mb, @game_vram_dedicated_median_mb, @game_vram_dedicated_max_mb, @game_vram_shared_max_mb, @game_ram_private_avg_mb, @game_ram_private_median_mb, @game_ram_private_max_mb, @game_ram_ws_max_mb, @game_commit_max_mb, @game_memory_processes, @game_memory_source, @sensor_stats_json, @time_below_30_pct, @time_below_60_pct, @time_below_refresh_pct, @frametime_delta_mean_ms, @vsync_present_pct, @tearing_allowed_pct, @avg_gpu_core_clock_mhz, @avg_gpu_mem_clock_mhz, @avg_gpu_fan_rpm, @max_gpu_mem_temp, @power_limit_pct, @thermal_limit_pct, @app_frames_per_joule, @fg_mix, @runtime_module_sources, @dlss_nr_pct, @input_observed_ms, @input_foreground_ms, @input_controller_ms, @input_km_ms, @input_both_ms, @input_idle_ms, @input_method_switches, @input_source, @input_devices) RETURNING id";
|
||||
|
||||
public const string Select = "SELECT id, session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz, game_vram_dedicated_avg_mb, game_vram_dedicated_median_mb, game_vram_dedicated_max_mb, game_vram_shared_max_mb, game_ram_private_avg_mb, game_ram_private_median_mb, game_ram_private_max_mb, game_ram_ws_max_mb, game_commit_max_mb, game_memory_processes, game_memory_source, sensor_stats_json, time_below_30_pct, time_below_60_pct, time_below_refresh_pct, frametime_delta_mean_ms, vsync_present_pct, tearing_allowed_pct, avg_gpu_core_clock_mhz, avg_gpu_mem_clock_mhz, avg_gpu_fan_rpm, max_gpu_mem_temp, power_limit_pct, thermal_limit_pct, app_frames_per_joule, fg_mix, runtime_module_sources, dlss_nr_pct FROM sessions";
|
||||
public const string Select = "SELECT id, session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz, game_vram_dedicated_avg_mb, game_vram_dedicated_median_mb, game_vram_dedicated_max_mb, game_vram_shared_max_mb, game_ram_private_avg_mb, game_ram_private_median_mb, game_ram_private_max_mb, game_ram_ws_max_mb, game_commit_max_mb, game_memory_processes, game_memory_source, sensor_stats_json, time_below_30_pct, time_below_60_pct, time_below_refresh_pct, frametime_delta_mean_ms, vsync_present_pct, tearing_allowed_pct, avg_gpu_core_clock_mhz, avg_gpu_mem_clock_mhz, avg_gpu_fan_rpm, max_gpu_mem_temp, power_limit_pct, thermal_limit_pct, app_frames_per_joule, fg_mix, runtime_module_sources, dlss_nr_pct, input_observed_ms, input_foreground_ms, input_controller_ms, input_km_ms, input_both_ms, input_idle_ms, input_method_switches, input_source, input_devices FROM sessions";
|
||||
|
||||
public static Dictionary<string, object?> Parameters(SessionRow s)
|
||||
{
|
||||
@@ -35,10 +35,11 @@ internal static class SessionRowColumns
|
||||
Parameters5(d, s);
|
||||
Parameters6(d, s);
|
||||
Parameters7(d, s);
|
||||
Parameters8(d, s);
|
||||
return d;
|
||||
}
|
||||
|
||||
public static SessionRow Read(DbDataReader r) => Read7(Read6(Read5(Read4(Read3(Read2(Read1(Read0(r), r), r), r), r), r), r), r);
|
||||
public static SessionRow Read(DbDataReader r) => Read8(Read7(Read6(Read5(Read4(Read3(Read2(Read1(Read0(r), r), r), r), r), r), r), r), r);
|
||||
|
||||
|
||||
private static void Parameters0(Dictionary<string, object?> d, SessionRow s)
|
||||
@@ -425,6 +426,33 @@ internal static class SessionRowColumns
|
||||
DlssNrPct = D(r, "dlss_nr_pct"),
|
||||
};
|
||||
|
||||
// Schema 0024 (beta.50, D155-D163): what the session was played with - read by the Agent from outside the game.
|
||||
private static void Parameters8(Dictionary<string, object?> d, SessionRow s)
|
||||
{
|
||||
d["input_observed_ms"] = s.InputObservedMs;
|
||||
d["input_foreground_ms"] = s.InputForegroundMs;
|
||||
d["input_controller_ms"] = s.InputControllerMs;
|
||||
d["input_km_ms"] = s.InputKeyboardMouseMs;
|
||||
d["input_both_ms"] = s.InputBothMs;
|
||||
d["input_idle_ms"] = s.InputIdleMs;
|
||||
d["input_method_switches"] = s.InputMethodSwitches;
|
||||
d["input_source"] = s.InputSource;
|
||||
d["input_devices"] = s.InputDevicesJson;
|
||||
}
|
||||
|
||||
private static SessionRow Read8(SessionRow row, DbDataReader r) => row with
|
||||
{
|
||||
InputObservedMs = L(r, "input_observed_ms"),
|
||||
InputForegroundMs = L(r, "input_foreground_ms"),
|
||||
InputControllerMs = L(r, "input_controller_ms"),
|
||||
InputKeyboardMouseMs = L(r, "input_km_ms"),
|
||||
InputBothMs = L(r, "input_both_ms"),
|
||||
InputIdleMs = L(r, "input_idle_ms"),
|
||||
InputMethodSwitches = I(r, "input_method_switches"),
|
||||
InputSource = S(r, "input_source"),
|
||||
InputDevicesJson = S(r, "input_devices"),
|
||||
};
|
||||
|
||||
public static string ExitStatusText(ExitStatus status) => Vocabulary.ExitStatusText(status);
|
||||
|
||||
public static ExitStatus ParseExitStatus(string text) => text switch
|
||||
|
||||
@@ -33,7 +33,8 @@ public sealed class SqliteGameRepository : IGameRepository
|
||||
+ "ac_exception_eligible, ac_exception_verdict, ac_exception_sessions, ac_exception_checked_rules_version, "
|
||||
+ "ac_exception_checked_exe_size_bytes, ac_exception_checked_exe_mtime_ms, ac_exception_checked_block, ac_exception_at, "
|
||||
+ "ac_exception_family, ac_exception_disclosure_version, ac_exception_exe_size_bytes, ac_exception_exe_mtime_ms, "
|
||||
+ "ac_exception_lapsed_at, ac_exception_lapsed_reason, engine_version_source, ac_exception_trial_failed_at";
|
||||
+ "ac_exception_lapsed_at, ac_exception_lapsed_reason, engine_version_source, ac_exception_trial_failed_at, "
|
||||
+ "controller_support, controller_support_source, controller_support_at";
|
||||
|
||||
private const string _selectByPath = $"SELECT {_columns} FROM games WHERE exe_path = @path";
|
||||
|
||||
@@ -376,8 +377,11 @@ public sealed class SqliteGameRepository : IGameRepository
|
||||
ExeFileVersion = SqliteReaders.String(r, 36),
|
||||
ExeProductVersion = SqliteReaders.String(r, 37),
|
||||
Libraries = LibraryVersionsJson.Parse(SqliteReaders.String(r, 38)),
|
||||
AcException = ReadException(r) with { TrialFailedAt = At(SqliteReaders.Int64(r, 54)) }, // schema 0017, the last column
|
||||
AcException = ReadException(r) with { TrialFailedAt = At(SqliteReaders.Int64(r, 54)) }, // schema 0017
|
||||
EngineVersionSource = SqliteReaders.String(r, 53), // schema 0015
|
||||
ControllerSupport = SqliteReaders.String(r, 55), // schema 0024, the last three columns
|
||||
ControllerSupportSource = SqliteReaders.String(r, 56),
|
||||
ControllerSupportAt = At(SqliteReaders.Int64(r, 57)),
|
||||
};
|
||||
|
||||
/// <summary>Schema 0014's columns, 39 onwards in <see cref="_columns"/>' order.</summary>
|
||||
|
||||
@@ -53,8 +53,14 @@ public sealed class SqliteSessionRepository : ISessionRepository
|
||||
|
||||
// The fixed series; an advanced one (schema 0023) is a row of the same table under a name that starts with 'adv.'.
|
||||
// In LIKE the dot is a literal and the only wildcard is the trailing %, so 'adv.%' is exactly that prefix.
|
||||
// The input series (schema 0024) are rows of it too, under 'input.': a class's number and a controller's part are
|
||||
// not sensor values, and they too mark a tick with nothing to say by NaN.
|
||||
private const string _selectSensors =
|
||||
"SELECT series, hz, codec, data FROM sensor_blobs WHERE session_id = @sessionId AND series NOT LIKE 'adv.%' ORDER BY series";
|
||||
"SELECT series, hz, codec, data FROM sensor_blobs WHERE session_id = @sessionId AND series NOT LIKE 'adv.%' AND series NOT LIKE 'input.%' ORDER BY series";
|
||||
|
||||
private const string _selectInputSensors =
|
||||
"SELECT series, hz, codec, data FROM sensor_blobs WHERE session_id = @sessionId AND (series = 't_ms' OR series LIKE 'input.%') "
|
||||
+ "ORDER BY CASE WHEN series = 't_ms' THEN 0 ELSE 1 END, series";
|
||||
|
||||
private const string _selectAdvancedSensors =
|
||||
"SELECT series, hz, codec, data FROM sensor_blobs WHERE session_id = @sessionId AND (series = 't_ms' OR series LIKE 'adv.%') "
|
||||
@@ -217,6 +223,11 @@ public sealed class SqliteSessionRepository : ISessionRepository
|
||||
c, new CommandDefinition(_selectAdvancedSensors, new { sessionId }, cancellationToken: token),
|
||||
static r => new SensorBlob { Series = r.GetString(0), Hz = r.GetDouble(1), Codec = r.GetString(2), Data = (byte[])r.GetValue(3) }), ct);
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindInputSensorsAsync(long sessionId, CancellationToken ct = default) =>
|
||||
_db.ReadAsync((c, token) => SqliteReaders.ReadAllAsync(
|
||||
c, new CommandDefinition(_selectInputSensors, new { sessionId }, cancellationToken: token),
|
||||
static r => new SensorBlob { Series = r.GetString(0), Hz = r.GetDouble(1), Codec = r.GetString(2), Data = (byte[])r.GetValue(3) }), ct);
|
||||
|
||||
public ValueTask<AdvancedSessionRow?> FindAdvancedAsync(long sessionId, CancellationToken ct = default) =>
|
||||
_db.ReadAsync((c, token) => SqliteReaders.ReadOneAsync(
|
||||
c, new CommandDefinition(_selectAdvanced, new { sessionId }, cancellationToken: token),
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using FrameLedger.Application.Input;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Domain.Input;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Recording;
|
||||
|
||||
/// <summary>
|
||||
/// The input readings of a batch of telemetry samples, as one chunk of a <c>.partial</c> file (owner decisions
|
||||
/// D155-D163, <c>06_DATA_MODEL</c> §<c>.partial</c>): so a session that is recovered after the Agent died has what it
|
||||
/// was played with, as a finished one does.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A chunk of its own, after the sensors' and the advanced one, for the reason <see cref="AdvancedSampleCodec"/> has
|
||||
/// one: the sensor chunk's form is fixed, and a reading is attached to its sample by the QPC the sample already has. A
|
||||
/// session recorded with the option off never writes one, and its file is byte for byte what it was.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Each chunk stands alone</b>: every controller a sample counts is described in that sample - its maker, its two
|
||||
/// USB ids, its connection - so a file cut anywhere still reads up to its last whole chunk.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Layout, little-endian: <c>u32 samples</c>, then per sample <c>i64 qpc</c>, seven <c>i32</c> (span, observed, in
|
||||
/// front, controller, keyboard and mouse, both, no input), <c>u8 flags</c> (1 a virtual pad), the health (<c>u8</c>
|
||||
/// answers: 1 raw input registered, 2 XInput there, 4 last input readable; six <c>i64</c> counts; <c>i32 faults</c>),
|
||||
/// <c>u8 controllers</c> and per controller 23 bytes: <c>i32 id</c>, <c>u8 family</c>, <c>u16 vendor</c>,
|
||||
/// <c>u16 product</c>, <c>u8 connection</c>, <c>u8 flags</c> (1 virtual, 2 one of XInput's pads, 4 connected, 8 a
|
||||
/// battery), <c>u8 slot</c>, <c>i32 active ms</c>, <c>u8</c> battery state, scale and level, <c>u16 connects</c>,
|
||||
/// <c>u16 disconnects</c>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class InputSampleCodec
|
||||
{
|
||||
private const int _sampleBytes = 8 + (7 * 4) + 1 + _healthBytes + 1;
|
||||
private const int _healthBytes = 1 + (6 * 8) + 4;
|
||||
private const int _deviceBytes = 23;
|
||||
|
||||
private const byte _virtualPad = 1;
|
||||
|
||||
private const byte _rawRegistered = 1;
|
||||
private const byte _xinputAvailable = 2;
|
||||
private const byte _lastInputAvailable = 4;
|
||||
|
||||
private const byte _deviceVirtual = 1;
|
||||
private const byte _deviceXInput = 2;
|
||||
private const byte _deviceConnected = 4;
|
||||
private const byte _deviceBattery = 8;
|
||||
|
||||
/// <summary>The chunk for the samples of <paramref name="samples"/> that carry an input reading, or null when none does.</summary>
|
||||
public static byte[]? Write(ReadOnlySpan<TelemetrySample> samples)
|
||||
{
|
||||
int carrying = 0;
|
||||
int bytes = 4;
|
||||
foreach (ref readonly TelemetrySample sample in samples)
|
||||
{
|
||||
if (sample.Input is { } reading)
|
||||
{
|
||||
carrying++;
|
||||
bytes += _sampleBytes + (Devices(reading).Count * _deviceBytes);
|
||||
}
|
||||
}
|
||||
|
||||
if (carrying == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
byte[] payload = new byte[bytes];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(payload, (uint)carrying);
|
||||
int at = 4;
|
||||
foreach (ref readonly TelemetrySample sample in samples)
|
||||
{
|
||||
if (sample.Input is { } reading)
|
||||
{
|
||||
at += WriteSample(payload.AsSpan(at), sample.QpcTicks, reading);
|
||||
}
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
/// <summary>The reading of each sample in a chunk, by the sample's QPC; false when the chunk is not well formed.</summary>
|
||||
public static bool TryRead(ReadOnlySpan<byte> payload, List<(long Qpc, InputReading Reading)> into)
|
||||
{
|
||||
if (payload.Length < 4)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
uint samples = BinaryPrimitives.ReadUInt32LittleEndian(payload);
|
||||
int at = 4;
|
||||
var read = new List<(long, InputReading)>();
|
||||
for (uint s = 0; s < samples; s++)
|
||||
{
|
||||
if (payload.Length - at < _sampleBytes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
int devices = payload[at + _sampleBytes - 1];
|
||||
if (payload.Length - at - _sampleBytes < devices * _deviceBytes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
read.Add(ReadSample(payload.Slice(at, _sampleBytes + (devices * _deviceBytes)), devices));
|
||||
at += _sampleBytes + (devices * _deviceBytes);
|
||||
}
|
||||
|
||||
if (at != payload.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
into.AddRange(read);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The controllers of a reading that can be written: each with its description, at most 255.</summary>
|
||||
private static List<(InputDevice Device, InputDeviceReading Reading)> Devices(InputReading reading)
|
||||
{
|
||||
var devices = new List<(InputDevice, InputDeviceReading)>(reading.Devices.Count);
|
||||
foreach (InputDeviceReading d in reading.Devices)
|
||||
{
|
||||
if (devices.Count < byte.MaxValue && reading.Table.FirstOrDefault(t => t.Id == d.DeviceId) is { } device)
|
||||
{
|
||||
devices.Add((device, d));
|
||||
}
|
||||
}
|
||||
|
||||
return devices;
|
||||
}
|
||||
|
||||
private static int WriteSample(Span<byte> to, long qpc, InputReading reading)
|
||||
{
|
||||
BinaryPrimitives.WriteInt64LittleEndian(to, qpc);
|
||||
int at = 8;
|
||||
foreach (int ms in (ReadOnlySpan<int>)[reading.SpanMs, reading.ObservedMs, reading.ForegroundMs, reading.ControllerMs, reading.KeyboardMouseMs, reading.BothMs, reading.IdleMs])
|
||||
{
|
||||
BinaryPrimitives.WriteInt32LittleEndian(to[at..], ms);
|
||||
at += 4;
|
||||
}
|
||||
|
||||
to[at++] = reading.VirtualPad ? _virtualPad : (byte)0;
|
||||
|
||||
InputHealth h = reading.Health;
|
||||
to[at++] = (byte)((h.RawInputRegistered ? _rawRegistered : 0) | (h.XInputAvailable ? _xinputAvailable : 0) | (h.LastInputAvailable ? _lastInputAvailable : 0));
|
||||
foreach (long count in (ReadOnlySpan<long>)[h.RawReports, h.RawReportsUnread, h.XInputReads, h.XInputSilent, h.Slices, h.ThreadCpuMs])
|
||||
{
|
||||
BinaryPrimitives.WriteInt64LittleEndian(to[at..], count);
|
||||
at += 8;
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteInt32LittleEndian(to[at..], h.Faults);
|
||||
at += 4;
|
||||
|
||||
List<(InputDevice Device, InputDeviceReading Reading)> devices = Devices(reading);
|
||||
to[at++] = (byte)devices.Count;
|
||||
foreach ((InputDevice device, InputDeviceReading d) in devices)
|
||||
{
|
||||
WriteDevice(to.Slice(at, _deviceBytes), device, d);
|
||||
at += _deviceBytes;
|
||||
}
|
||||
|
||||
return at;
|
||||
}
|
||||
|
||||
private static void WriteDevice(Span<byte> to, InputDevice device, InputDeviceReading d)
|
||||
{
|
||||
BinaryPrimitives.WriteInt32LittleEndian(to, device.Id);
|
||||
to[4] = (byte)device.Family;
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(to[5..], (ushort)Math.Clamp(device.VendorId, 0, ushort.MaxValue));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(to[7..], (ushort)Math.Clamp(device.ProductId, 0, ushort.MaxValue));
|
||||
to[9] = (byte)device.Connection;
|
||||
to[10] = (byte)((device.IsVirtual ? _deviceVirtual : 0)
|
||||
| (device.XInputSlot is not null ? _deviceXInput : 0)
|
||||
| (d.Connected ? _deviceConnected : 0)
|
||||
| (d.Battery is not null ? _deviceBattery : 0));
|
||||
to[11] = (byte)Math.Clamp(device.XInputSlot ?? 0, 0, byte.MaxValue);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(to[12..], d.ActiveMs);
|
||||
to[16] = (byte)(d.Battery?.State ?? BatteryState.Unknown);
|
||||
to[17] = (byte)(d.Battery?.Scale ?? BatteryScale.None);
|
||||
to[18] = (byte)Math.Clamp(d.Battery?.Level ?? 0, 0, byte.MaxValue);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(to[19..], (ushort)Math.Clamp(d.Connects, 0, ushort.MaxValue));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(to[21..], (ushort)Math.Clamp(d.Disconnects, 0, ushort.MaxValue));
|
||||
}
|
||||
|
||||
private static (long Qpc, InputReading Reading) ReadSample(ReadOnlySpan<byte> from, int deviceCount)
|
||||
{
|
||||
long qpc = BinaryPrimitives.ReadInt64LittleEndian(from);
|
||||
int at = 8;
|
||||
Span<int> ms = stackalloc int[7];
|
||||
for (int i = 0; i < ms.Length; i++)
|
||||
{
|
||||
ms[i] = BinaryPrimitives.ReadInt32LittleEndian(from[at..]);
|
||||
at += 4;
|
||||
}
|
||||
|
||||
bool virtualPad = (from[at++] & _virtualPad) != 0;
|
||||
byte answers = from[at++];
|
||||
Span<long> counts = stackalloc long[6];
|
||||
for (int i = 0; i < counts.Length; i++)
|
||||
{
|
||||
counts[i] = BinaryPrimitives.ReadInt64LittleEndian(from[at..]);
|
||||
at += 8;
|
||||
}
|
||||
|
||||
int faults = BinaryPrimitives.ReadInt32LittleEndian(from[at..]);
|
||||
at += 4 + 1;
|
||||
|
||||
var devices = new InputDeviceReading[deviceCount];
|
||||
var table = new InputDevice[deviceCount];
|
||||
for (int i = 0; i < deviceCount; i++)
|
||||
{
|
||||
(table[i], devices[i]) = ReadDevice(from.Slice(at, _deviceBytes));
|
||||
at += _deviceBytes;
|
||||
}
|
||||
|
||||
return (qpc, new InputReading
|
||||
{
|
||||
SpanMs = ms[0],
|
||||
ObservedMs = ms[1],
|
||||
ForegroundMs = ms[2],
|
||||
ControllerMs = ms[3],
|
||||
KeyboardMouseMs = ms[4],
|
||||
BothMs = ms[5],
|
||||
IdleMs = ms[6],
|
||||
VirtualPad = virtualPad,
|
||||
Devices = devices,
|
||||
Table = table,
|
||||
Health = new InputHealth
|
||||
{
|
||||
RawInputRegistered = (answers & _rawRegistered) != 0,
|
||||
XInputAvailable = (answers & _xinputAvailable) != 0,
|
||||
LastInputAvailable = (answers & _lastInputAvailable) != 0,
|
||||
RawReports = counts[0],
|
||||
RawReportsUnread = counts[1],
|
||||
XInputReads = counts[2],
|
||||
XInputSilent = counts[3],
|
||||
Slices = counts[4],
|
||||
ThreadCpuMs = counts[5],
|
||||
Faults = faults,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private static (InputDevice Device, InputDeviceReading Reading) ReadDevice(ReadOnlySpan<byte> from)
|
||||
{
|
||||
byte flags = from[10];
|
||||
int id = BinaryPrimitives.ReadInt32LittleEndian(from);
|
||||
var device = new InputDevice
|
||||
{
|
||||
Id = id,
|
||||
|
||||
// A value this build has no name for was written by a later one: it reads as the word for "do not know".
|
||||
Family = Known<ControllerFamily>(from[4]),
|
||||
VendorId = BinaryPrimitives.ReadUInt16LittleEndian(from[5..]),
|
||||
ProductId = BinaryPrimitives.ReadUInt16LittleEndian(from[7..]),
|
||||
Connection = Known<ControllerConnection>(from[9]),
|
||||
IsVirtual = (flags & _deviceVirtual) != 0,
|
||||
XInputSlot = (flags & _deviceXInput) != 0 ? from[11] : null,
|
||||
};
|
||||
|
||||
BatteryReading? battery = (flags & _deviceBattery) != 0
|
||||
? new BatteryReading(Known<BatteryState>(from[16]), Known<BatteryScale>(from[17]), from[18])
|
||||
: null;
|
||||
return (device, new InputDeviceReading(
|
||||
id,
|
||||
Connected: (flags & _deviceConnected) != 0,
|
||||
ActiveMs: BinaryPrimitives.ReadInt32LittleEndian(from[12..]),
|
||||
battery,
|
||||
Connects: BinaryPrimitives.ReadUInt16LittleEndian(from[19..]),
|
||||
Disconnects: BinaryPrimitives.ReadUInt16LittleEndian(from[21..])));
|
||||
}
|
||||
|
||||
private static T Known<T>(byte value)
|
||||
where T : struct, Enum
|
||||
{
|
||||
T parsed = (T)Enum.ToObject(typeof(T), value);
|
||||
return Enum.IsDefined(parsed) ? parsed : default;
|
||||
}
|
||||
}
|
||||
@@ -49,4 +49,12 @@ internal enum PartialChunkType
|
||||
/// last one wins.
|
||||
/// </summary>
|
||||
AdvancedContext = 10,
|
||||
|
||||
/// <summary>
|
||||
/// The input readings of the samples of the <see cref="SensorsWide"/> chunk before it (owner decisions D155-D163):
|
||||
/// <c>InputSampleCodec</c> - per sample its QPC, how its time in front divides between a controller, the keyboard
|
||||
/// and mouse, both and neither, and each controller's part with what the controller is. Written only when a sample
|
||||
/// of the batch carries one, so a session recorded with the option off has none.
|
||||
/// </summary>
|
||||
SensorsInput = 11,
|
||||
}
|
||||
@@ -6,6 +6,7 @@ using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Input;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Shared;
|
||||
@@ -166,6 +167,7 @@ public static class PartialSessionFile
|
||||
PartialChunkType.Touches => Int64s(payload, _touches),
|
||||
PartialChunkType.SensorsAdvanced => AdvancedSensors(payload),
|
||||
PartialChunkType.AdvancedContext => AdvancedContext(payload),
|
||||
PartialChunkType.SensorsInput => InputSensors(payload),
|
||||
|
||||
// A type this build does not know, in a chunk whose length and checksum are right (TryReadChunk has
|
||||
// verified both): a newer build wrote it, and it is passed over (owner decision D106, 2026-11-11).
|
||||
@@ -302,6 +304,30 @@ public static class PartialSessionFile
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The input readings of samples already read, attached as <see cref="AdvancedSensors"/> attaches its own: by QPC, to the last sample that has none yet.</summary>
|
||||
private bool InputSensors(ReadOnlySpan<byte> payload)
|
||||
{
|
||||
var read = new List<(long Qpc, InputReading Reading)>();
|
||||
if (!InputSampleCodec.TryRead(payload, read))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ((long qpc, InputReading reading) in read)
|
||||
{
|
||||
for (int i = _sensors.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (_sensors[i].QpcTicks == qpc && _sensors[i].Input is null)
|
||||
{
|
||||
_sensors[i] = _sensors[i] with { Input = reading };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool AdvancedContext(ReadOnlySpan<byte> payload)
|
||||
{
|
||||
_advancedContext = Encoding.UTF8.GetString(payload);
|
||||
@@ -405,6 +431,12 @@ public static class PartialSessionFile
|
||||
{
|
||||
Append(PartialChunkType.SensorsAdvanced, advanced);
|
||||
}
|
||||
|
||||
// And the input readings, the same way and for the same reason (D155-D163).
|
||||
if (InputSampleCodec.Write(samples) is byte[] input)
|
||||
{
|
||||
Append(PartialChunkType.SensorsInput, input);
|
||||
}
|
||||
}
|
||||
|
||||
public void AppendAdvancedContext(string json)
|
||||
|
||||
@@ -143,6 +143,8 @@ public sealed class SeriesDigestTests
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindAdvancedSensorsAsync(long sessionId, CancellationToken ct = default) => inner.FindAdvancedSensorsAsync(sessionId, ct);
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindInputSensorsAsync(long sessionId, CancellationToken ct = default) => inner.FindInputSensorsAsync(sessionId, ct);
|
||||
|
||||
public ValueTask<AdvancedSessionRow?> FindAdvancedAsync(long sessionId, CancellationToken ct = default) => inner.FindAdvancedAsync(sessionId, ct);
|
||||
|
||||
public ValueTask<long> InsertFinalizedAsync(FinalizedSession session, CancellationToken ct = default) => inner.InsertFinalizedAsync(session, ct);
|
||||
|
||||
@@ -130,7 +130,12 @@ internal sealed class FakeSessionRepository : ISessionRepository
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindSensorsAsync(long sessionId, CancellationToken ct = default) =>
|
||||
ValueTask.FromResult<IReadOnlyList<SensorBlob>>(sessionId >= 1 && sessionId <= Stored.Count
|
||||
? [.. Stored[(int)sessionId - 1].Sensors.Where(static s => !s.Series.StartsWith("adv.", StringComparison.Ordinal))]
|
||||
? [.. Stored[(int)sessionId - 1].Sensors.Where(static s => !s.Series.StartsWith("adv.", StringComparison.Ordinal) && !s.Series.StartsWith("input.", StringComparison.Ordinal))]
|
||||
: []);
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindInputSensorsAsync(long sessionId, CancellationToken ct = default) =>
|
||||
ValueTask.FromResult<IReadOnlyList<SensorBlob>>(sessionId >= 1 && sessionId <= Stored.Count
|
||||
? [.. Stored[(int)sessionId - 1].Sensors.Where(static s => string.Equals(s.Series, "t_ms", StringComparison.Ordinal) || s.Series.StartsWith("input.", StringComparison.Ordinal))]
|
||||
: []);
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindAdvancedSensorsAsync(long sessionId, CancellationToken ct = default) =>
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
|
||||
using System.Reflection;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Input;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Domain.Input;
|
||||
using FrameLedger.Domain.Sessions;
|
||||
using FrameLedger.Shared;
|
||||
|
||||
@@ -218,6 +220,71 @@ public sealed class SessionFinalizerTests
|
||||
SensorSeriesStats.Parse("{not json").Should().BeEmpty("text this build cannot read is no statistics, never a throw into the UI");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a session was played with (D155-D163) is read by the Agent from outside the game, so a session that was not
|
||||
/// hooked has it as a hooked one does: the totals on the row, the series beside the sensors'.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void BothTiersStoreWhatTheSessionWasPlayedWith(bool hooked)
|
||||
{
|
||||
(SessionFinalizer finalizer, _) = Make();
|
||||
List<Application.Telemetry.TelemetrySample> sensors = SessionFixtures.Sensors(3);
|
||||
var pad = new InputDevice { Id = 1, Family = ControllerFamily.Xbox, XInputSlot = 0 };
|
||||
sensors[0] = sensors[0] with { Input = Played(controller: 1000, pad) };
|
||||
sensors[2] = sensors[2] with { Input = Played(controller: 0, pad) with { KeyboardMouseMs = 700, IdleMs = 300 } };
|
||||
|
||||
FinalizedSession built = finalizer.Build(hooked
|
||||
? new FinalizeInput { Skeleton = SessionFixtures.Skeleton(), Hooked = SessionFixtures.Hooked(SessionFixtures.Stream(600, FlMeasured.None)), Sensors = sensors }
|
||||
: new FinalizeInput { Skeleton = SessionFixtures.Skeleton(tier: CaptureTier.NotHooked), Sensors = sensors });
|
||||
|
||||
built.Row.Tier.Should().Be(hooked ? CaptureTier.Hooked : CaptureTier.NotHooked);
|
||||
built.Row.InputObservedMs.Should().Be(2000);
|
||||
built.Row.InputForegroundMs.Should().Be(2000);
|
||||
built.Row.InputControllerMs.Should().Be(1000);
|
||||
built.Row.InputKeyboardMouseMs.Should().Be(700);
|
||||
built.Row.InputBothMs.Should().Be(0);
|
||||
built.Row.InputIdleMs.Should().Be(300);
|
||||
built.Row.InputMethodSwitches.Should().Be(1);
|
||||
built.Row.InputSource.Should().Be("rawinput+lastinput");
|
||||
built.Row.InputSharePercent(built.Row.InputControllerMs).Should().Be(50);
|
||||
InputDevicesRecord.Parse(built.Row.InputDevicesJson)!.Devices.Should().ContainSingle().Which.XInputSlot.Should().Be(0);
|
||||
built.Sensors.Select(static s => s.Series).Should().Contain(["t_ms", "input.class", "input.dev.1.active"]);
|
||||
float[] timeline = RawSeriesCodec.Floats(built.Sensors.Single(static s => string.Equals(s.Series, "input.class", StringComparison.Ordinal)).Data);
|
||||
timeline[0].Should().Be((float)InputClass.Controller);
|
||||
float.IsNaN(timeline[1]).Should().BeTrue("the tick the reader took no slice in");
|
||||
timeline[2].Should().Be((float)InputClass.KeyboardMouse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASessionWithNoInputReadingKeepsEveryInputColumnNullAndStoresNoInputSeries()
|
||||
{
|
||||
(SessionFinalizer finalizer, _) = Make();
|
||||
|
||||
FinalizedSession built = finalizer.Build(new FinalizeInput { Skeleton = SessionFixtures.Skeleton(tier: CaptureTier.NotHooked), Sensors = SessionFixtures.Sensors(3) });
|
||||
|
||||
built.Row.InputObservedMs.Should().BeNull("the option was off, or the terms that describe the reading were not accepted yet: N/A, never a zero");
|
||||
built.Row.InputForegroundMs.Should().BeNull();
|
||||
built.Row.InputControllerMs.Should().BeNull();
|
||||
built.Row.InputMethodSwitches.Should().BeNull();
|
||||
built.Row.InputSource.Should().BeNull();
|
||||
built.Row.InputDevicesJson.Should().BeNull();
|
||||
built.Sensors.Should().NotContain(static s => s.Series.StartsWith("input.", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private static InputReading Played(int controller, InputDevice pad) => new()
|
||||
{
|
||||
SpanMs = 1000,
|
||||
ObservedMs = 1000,
|
||||
ForegroundMs = 1000,
|
||||
ControllerMs = controller,
|
||||
IdleMs = 1000 - controller,
|
||||
Devices = [new InputDeviceReading(pad.Id, Connected: true, ActiveMs: controller, Battery: null, Connects: 0, Disconnects: 0)],
|
||||
Table = [pad],
|
||||
Health = new InputHealth { RawInputRegistered = true, LastInputAvailable = true },
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task TooShortIsDiscardedAndNothingIsWritten()
|
||||
{
|
||||
|
||||
@@ -962,6 +962,79 @@ public sealed class LedgerDatabaseTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Schema 0024 (2026-11-14, owner decisions D155-D163): what a session was played with, nine columns of
|
||||
/// <c>sessions</c>, and what a game's store lists of controller support, three of <c>games</c> - ADD COLUMN only. A
|
||||
/// session and a game written before have none of them: N/A, never a zero.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ScriptTwentyFourAddsTheInputColumnsAndAnEarlierSessionAndGameHaveNone()
|
||||
{
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(24);
|
||||
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
|
||||
new() { ExePath = @"C:\Games\A\a.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "A", Ct).ConfigureAwait(true)).Id;
|
||||
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "g" }, DateTimeOffset.UnixEpoch, Ct)
|
||||
.ConfigureAwait(true);
|
||||
string path = f.Path;
|
||||
await f.Db.DisposeAsync().ConfigureAwait(true);
|
||||
var c23 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
|
||||
await using (c23.ConfigureAwait(true))
|
||||
{
|
||||
await c23.OpenAsync(Ct).ConfigureAwait(true);
|
||||
await RewindToAsync(c23, 23).ConfigureAwait(true);
|
||||
(await c23.ExecuteScalarAsync<long>(new CommandDefinition(
|
||||
"SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name LIKE 'input!_%' ESCAPE '!'", cancellationToken: Ct)).ConfigureAwait(true))
|
||||
.Should().Be(0, "a ledger at schema 23 has no input column");
|
||||
await c23.ExecuteAsync(new CommandDefinition(
|
||||
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, exit_status, frame_count, app_frame_count, displayed_frame_count, dropped_frames) "
|
||||
+ "VALUES ('00000000-0000-0000-0000-000000000024', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 2, 'attach', 'normal', 0, 0, 0, 0)",
|
||||
new { gameId, snapshotId }, cancellationToken: Ct)).ConfigureAwait(true);
|
||||
}
|
||||
|
||||
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
|
||||
await using (migrated.ConfigureAwait(true))
|
||||
{
|
||||
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
|
||||
IReadOnlyList<string> sessionColumns = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
|
||||
"SELECT name FROM pragma_table_info('sessions') WHERE name LIKE 'input!_%' ESCAPE '!' ORDER BY cid", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
|
||||
IReadOnlyList<string> gameColumns = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
|
||||
"SELECT name FROM pragma_table_info('games') WHERE name LIKE 'controller!_%' ESCAPE '!' ORDER BY cid", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
|
||||
sessionColumns.Should().Equal(
|
||||
"input_observed_ms", "input_foreground_ms", "input_controller_ms", "input_km_ms", "input_both_ms", "input_idle_ms", "input_method_switches", "input_source", "input_devices");
|
||||
gameColumns.Should().Equal("controller_support", "controller_support_source", "controller_support_at");
|
||||
|
||||
var sessions = new SqliteSessionRepository(migrated);
|
||||
SessionRow before = (await sessions.FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000024"), Ct).ConfigureAwait(true))!;
|
||||
before.InputObservedMs.Should().BeNull("a session recorded before the reading existed has none - N/A, never a zero");
|
||||
before.InputForegroundMs.Should().BeNull();
|
||||
before.InputMethodSwitches.Should().BeNull();
|
||||
before.InputSource.Should().BeNull();
|
||||
before.InputDevicesJson.Should().BeNull();
|
||||
before.InputSharePercent(before.InputControllerMs).Should().BeNull();
|
||||
(await sessions.FindInputSensorsAsync(before.Id, Ct).ConfigureAwait(true)).Should().BeEmpty();
|
||||
|
||||
GameRow game = (await new SqliteGameRepository(migrated).FindByIdAsync(gameId, Ct).ConfigureAwait(true))!;
|
||||
game.ControllerSupport.Should().BeNull();
|
||||
game.ControllerSupportSource.Should().BeNull();
|
||||
game.ControllerSupportAt.Should().BeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ScriptTwentyFourOnlyAddsColumnsAndNamesNoIdentifier()
|
||||
{
|
||||
// D160: the numbers are columns of sessions on purpose - the trend, the comparison, the export and the bug bundle
|
||||
// read a session's row. What may never be a column: a controller's serial number, its address, its path.
|
||||
string sql = MigrationRunner.Scripts()[24];
|
||||
string statements = string.Join('\n', sql.Split('\n').Where(static l => !l.TrimStart().StartsWith("--", StringComparison.Ordinal)).Select(static l => l.Split("--")[0]));
|
||||
|
||||
statements.Should().NotContainAny("CREATE", "DROP", "UPDATE", "DELETE");
|
||||
statements.Should().NotContainAny("serial", "address", "path", "mac", "uuid");
|
||||
Regex.Matches(statements, @"ALTER\s+TABLE\s+(?<table>\w+)\s+ADD\s+COLUMN", RegexOptions.ExplicitCapture, TimeSpan.FromSeconds(1)).Select(static m => m.Groups["table"].Value)
|
||||
.Distinct(StringComparer.Ordinal).Should().Equal("sessions", "games");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ScriptTwentyThreeAddsNoColumnToSessionsAndNamesNoIdentifier()
|
||||
{
|
||||
|
||||
@@ -111,6 +111,15 @@ public sealed class SqliteSessionRepositoryTests
|
||||
AppFramesPerJoule = 0.3125,
|
||||
RuntimeModuleSourcesJson = "{\"nvngx_dlss.dll\":\"graphics_driver\"}",
|
||||
DlssNrPct = 97.25,
|
||||
InputObservedMs = 5_400_000,
|
||||
InputForegroundMs = 5_000_000,
|
||||
InputControllerMs = 3_500_000,
|
||||
InputKeyboardMouseMs = 900_000,
|
||||
InputBothMs = 100_000,
|
||||
InputIdleMs = 500_000,
|
||||
InputMethodSwitches = 4,
|
||||
InputSource = "rawinput+xinput+lastinput",
|
||||
InputDevicesJson = "{\"V\":1,\"Devices\":[{\"Index\":1,\"Family\":\"playstation\",\"Model\":\"DualSense\"}]}",
|
||||
FgMixJson = "{\"Rows\":[{\"Kind\":\"generated\",\"Factor\":3.99,\"NativeFps\":70.5,\"DisplayedFps\":281.3,\"Seconds\":120,\"Share\":0.75,\"Windows\":24}]}",
|
||||
};
|
||||
|
||||
@@ -547,6 +556,34 @@ public sealed class SqliteSessionRepositoryTests
|
||||
float.IsNaN(rail[1]).Should().BeTrue("a tick with no reading is NaN");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheInputSeriesAreReadOnTheirOwnAndTheFixedReadNeverSeesThem()
|
||||
{
|
||||
// Schema 0024 (D155-D163). The input series are rows of sensor_blobs too, and the read every summary and chart
|
||||
// uses leaves them out: a class's number is not a sensor's value, and NaN marks a tick with nothing to say.
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
(long gameId, long snapshotId) = await SeedAsync(f);
|
||||
var repo = new SqliteSessionRepository(f.Db);
|
||||
SensorBlob[] sensors =
|
||||
[
|
||||
.. SensorsWithAdvanced(),
|
||||
new() { Series = "input.class", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeSparseFloat32([1f, float.NaN, 2f]) },
|
||||
new() { Series = "input.dev.1.active", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeSparseFloat32([1f, float.NaN, 0f]) },
|
||||
];
|
||||
|
||||
long id = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId), Sensors = sensors, Advanced = Advanced() }, Ct);
|
||||
long without = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000)), Sensors = [.. SensorsWithAdvanced().Take(2)] }, Ct);
|
||||
|
||||
(await repo.FindSensorsAsync(id, Ct)).Select(static s => s.Series).Should().Equal("gpu_temp", "t_ms");
|
||||
(await repo.FindAdvancedSensorsAsync(id, Ct)).Select(static s => s.Series).Should().NotContain(static s => s.StartsWith("input.", StringComparison.Ordinal));
|
||||
IReadOnlyList<SensorBlob> series = await repo.FindInputSensorsAsync(id, Ct);
|
||||
series.Select(static s => s.Series).Should().Equal("t_ms", "input.class", "input.dev.1.active");
|
||||
float[] timeline = SeriesCodec.DecodeFloat32(series[1].Data.ToArray());
|
||||
timeline[0].Should().Be(1f);
|
||||
float.IsNaN(timeline[1]).Should().BeTrue("a tick with the game not in front has no class");
|
||||
(await repo.FindInputSensorsAsync(without, Ct)).Select(static s => s.Series).Should().Equal("t_ms");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheAdvancedListNamesOnlySessionsRecordedWithTheOptionOnNewestFirst()
|
||||
{
|
||||
|
||||
@@ -269,7 +269,7 @@ public sealed class PartialSessionFileAdvancedTests : IDisposable
|
||||
}
|
||||
|
||||
/// <summary>One chunk as the format frames it: type, length, payload, then the IEEE CRC-32 of the first three.</summary>
|
||||
private static byte[] Chunk(uint type, byte[] payload)
|
||||
internal static byte[] Chunk(uint type, byte[] payload)
|
||||
{
|
||||
byte[] chunk = new byte[12 + payload.Length];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(chunk, type);
|
||||
@@ -289,7 +289,7 @@ public sealed class PartialSessionFileAdvancedTests : IDisposable
|
||||
return chunk;
|
||||
}
|
||||
|
||||
private static List<int> ChunkOffsets(byte[] file)
|
||||
internal static List<int> ChunkOffsets(byte[] file)
|
||||
{
|
||||
var offsets = new List<int>();
|
||||
for (int at = 0; at < file.Length; at += 12 + BitConverter.ToInt32(file, at + 4))
|
||||
@@ -300,5 +300,5 @@ public sealed class PartialSessionFileAdvancedTests : IDisposable
|
||||
return offsets;
|
||||
}
|
||||
|
||||
private static uint[] ChunkTypes(byte[] file) => [.. ChunkOffsets(file).Select(at => BitConverter.ToUInt32(file, at))];
|
||||
internal static uint[] ChunkTypes(byte[] file) => [.. ChunkOffsets(file).Select(at => BitConverter.ToUInt32(file, at))];
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Input;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Domain.Input;
|
||||
using FrameLedger.Domain.Sessions;
|
||||
using FrameLedger.Infrastructure.Recording;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Tests.Recording;
|
||||
|
||||
/// <summary>
|
||||
/// The <c>.partial</c> and the input readings (owner decisions D155-D163): a sample's reading survives the round trip
|
||||
/// with every controller it counts; with the option off the file is byte for byte what it was; a file cut at every byte
|
||||
/// still reads up to its last whole chunk; and a chunk that is not well formed ends the read.
|
||||
/// </summary>
|
||||
public sealed class PartialSessionFileInputTests : IDisposable
|
||||
{
|
||||
private static readonly DateTimeOffset _t0 = new(2026, 11, 14, 9, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static readonly InputDevice _xbox = new() { Id = 3, Family = ControllerFamily.Xbox, VendorId = ControllerCatalog.Microsoft, ProductId = 0x0B12, Connection = ControllerConnection.Wireless, XInputSlot = 2 };
|
||||
|
||||
private static readonly InputDevice _dualSense = new() { Id = 70_000, Family = ControllerFamily.PlayStation, VendorId = ControllerCatalog.Sony, ProductId = ControllerCatalog.DualSense, Connection = ControllerConnection.Bluetooth };
|
||||
|
||||
private static readonly InputDevice _steam = new() { Id = 5, Family = ControllerFamily.Xbox, VendorId = ControllerCatalog.Valve, ProductId = ControllerCatalog.SteamVirtualGamepad, IsVirtual = true, XInputSlot = 0 };
|
||||
|
||||
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-partial-input-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
public PartialSessionFileInputTests() => Directory.CreateDirectory(_dir);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(_dir, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static PartialHeader Header() => new()
|
||||
{
|
||||
SessionGuid = Guid.Parse("00000000-0000-0000-0000-0000000000b1"),
|
||||
StartedAt = _t0,
|
||||
QpcEpoch = 1_000_000,
|
||||
QpcFrequency = 10_000_000,
|
||||
GameId = 7,
|
||||
SnapshotId = 3,
|
||||
ExePath = @"C:\Games\Title\game.exe",
|
||||
Pid = 4242,
|
||||
Tier = CaptureTier.NotHooked,
|
||||
Mode = CaptureMode.Attach,
|
||||
TelemetryDescriptor = "l1+lhm",
|
||||
};
|
||||
|
||||
private static TelemetrySample Sample(long qpc, InputReading? input = null) => new(
|
||||
qpc,
|
||||
new GpuSample { TakenAt = _t0.AddSeconds(qpc / 10_000_000.0), Layer = TelemetryLayer.Lhm, TempCoreC = 60 },
|
||||
Input: input);
|
||||
|
||||
/// <summary>A reading with every field set to something a default would not be.</summary>
|
||||
private static InputReading Full() => new()
|
||||
{
|
||||
SpanMs = 1004,
|
||||
ObservedMs = 903,
|
||||
ForegroundMs = 802,
|
||||
ControllerMs = 401,
|
||||
KeyboardMouseMs = 200,
|
||||
BothMs = 101,
|
||||
IdleMs = 100,
|
||||
VirtualPad = true,
|
||||
Devices =
|
||||
[
|
||||
new InputDeviceReading(_xbox.Id, Connected: true, ActiveMs: 502, new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, 2), Connects: 1, Disconnects: 0),
|
||||
new InputDeviceReading(_dualSense.Id, Connected: false, ActiveMs: 0, new BatteryReading(BatteryState.Charging, BatteryScale.Percent, 100), Connects: 2, Disconnects: 3),
|
||||
new InputDeviceReading(_steam.Id, Connected: true, ActiveMs: 490, Battery: null, Connects: 0, Disconnects: 0),
|
||||
],
|
||||
Table = [_xbox, _dualSense, _steam],
|
||||
Health = new InputHealth
|
||||
{
|
||||
RawInputRegistered = true,
|
||||
XInputAvailable = true,
|
||||
LastInputAvailable = true,
|
||||
RawReports = 5_000_000_000,
|
||||
RawReportsUnread = 7,
|
||||
XInputReads = 1234,
|
||||
XInputSilent = 5,
|
||||
Slices = 10,
|
||||
ThreadCpuMs = 3,
|
||||
Faults = 1,
|
||||
},
|
||||
};
|
||||
|
||||
private static InputReading Quiet() => new() { SpanMs = 1000, ObservedMs = 1000, ForegroundMs = 1000, IdleMs = 1000, Health = new InputHealth { LastInputAvailable = true, Slices = 20 } };
|
||||
|
||||
[Fact]
|
||||
public void ASamplesReadingRoundTripsWithEveryControllerAndASampleWithoutOneHasNone()
|
||||
{
|
||||
string path = Path.Combine(_dir, "input.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000, Full()), Sample(1_200_000), Sample(1_300_000, Quiet())]);
|
||||
w.AppendSensors([Sample(1_400_000, Full() with { VirtualPad = false })]);
|
||||
}
|
||||
|
||||
PartialSession p = PartialSessionFile.Read(path)!;
|
||||
|
||||
p.Truncated.Should().BeFalse();
|
||||
p.Sensors.Should().HaveCount(4);
|
||||
p.Sensors[0].Input.Should().BeEquivalentTo(Full(), static o => o.WithStrictOrdering());
|
||||
p.Sensors[0].Input!.Table[1].Model.Should().Be("DualSense", "a controller is what its two ids say, and they travel with the reading");
|
||||
p.Sensors[1].Input.Should().BeNull("a tick the reader took no slice in carries none, and is not given the last one's");
|
||||
p.Sensors[2].Input.Should().BeEquivalentTo(Quiet());
|
||||
p.Sensors[3].Input!.VirtualPad.Should().BeFalse();
|
||||
PartialSessionFileAdvancedTests.ChunkTypes(File.ReadAllBytes(path)).Should().Equal(1u, 8u, 11u, 8u, 11u);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithTheOptionOffTheFileIsByteForByteWhatItWasBeforeTheReadingExisted()
|
||||
{
|
||||
string off = Path.Combine(_dir, "off.partial");
|
||||
string on = Path.Combine(_dir, "on.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(off, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000), Sample(1_200_000)]);
|
||||
w.AppendNote(_t0, "end");
|
||||
}
|
||||
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(on, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000, Quiet()), Sample(1_200_000)]);
|
||||
w.AppendNote(_t0, "end");
|
||||
}
|
||||
|
||||
byte[] offBytes = File.ReadAllBytes(off);
|
||||
byte[] onBytes = File.ReadAllBytes(on);
|
||||
PartialSessionFileAdvancedTests.ChunkTypes(offBytes).Should().Equal(1u, 8u, 6u);
|
||||
PartialSessionFileAdvancedTests.ChunkTypes(onBytes).Should().Equal(1u, 8u, 11u, 6u);
|
||||
int inputChunk = PartialSessionFileAdvancedTests.ChunkOffsets(onBytes)[2];
|
||||
int inputLength = 12 + BitConverter.ToInt32(onBytes, inputChunk + 4);
|
||||
onBytes.AsSpan(0, inputChunk).ToArray().Should().Equal(offBytes.AsSpan(0, inputChunk).ToArray(), "the sensor chunk does not change when a reading rides beside it");
|
||||
onBytes.AsSpan(inputChunk + inputLength).ToArray().Should().Equal(offBytes.AsSpan(inputChunk).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AKillAtEveryByteOffsetYieldsExactlyTheReadingsWhoseChunkWasComplete()
|
||||
{
|
||||
string path = Path.Combine(_dir, "cut.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000, Full()), Sample(1_200_000, Quiet())]);
|
||||
w.AppendSensors([Sample(1_300_000, Full())]);
|
||||
}
|
||||
|
||||
byte[] whole = File.ReadAllBytes(path);
|
||||
List<int> starts = PartialSessionFileAdvancedTests.ChunkOffsets(whole);
|
||||
PartialSessionFileAdvancedTests.ChunkTypes(whole).Should().Equal(1u, 8u, 11u, 8u, 11u);
|
||||
int[] ends = [.. starts.Skip(1), whole.Length];
|
||||
|
||||
for (int cut = ends[0]; cut <= whole.Length; cut++)
|
||||
{
|
||||
PartialSession p = PartialSessionFile.Parse(whole.AsSpan(0, cut))!;
|
||||
int complete = ends.Count(e => e <= cut);
|
||||
|
||||
p.Sensors.Should().HaveCount(complete >= 4 ? 3 : complete >= 2 ? 2 : 0, $"cut at {cut}, {complete} complete chunk(s)");
|
||||
p.Sensors.Count(static s => s.Input is not null).Should().Be(complete >= 5 ? 3 : complete >= 3 ? 2 : 0, $"cut at {cut}: a reading arrives with its own chunk and never before it");
|
||||
p.Truncated.Should().Be(cut != whole.Length && !ends.Contains(cut), $"cut at {cut}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnInputChunkThatIsNotWellFormedEndsTheReadLikeAnyKnownChunkThatIsNot()
|
||||
{
|
||||
string path = Path.Combine(_dir, "bad.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000, Quiet())]);
|
||||
}
|
||||
|
||||
byte[] file = File.ReadAllBytes(path);
|
||||
int at = PartialSessionFileAdvancedTests.ChunkOffsets(file)[2];
|
||||
byte[] good = file.AsSpan(at + 8, BitConverter.ToInt32(file, at + 4)).ToArray();
|
||||
byte[] head = file[..at];
|
||||
|
||||
byte[][] bad =
|
||||
[
|
||||
[],
|
||||
[1, 0],
|
||||
good[..^1], // a sample cut short
|
||||
[.. good, 0], // a byte too many
|
||||
[2, 0, 0, 0, .. good[4..]], // two samples declared, one there
|
||||
[.. good[..^1], 1], // a controller declared and not there
|
||||
];
|
||||
|
||||
foreach (byte[] payload in bad)
|
||||
{
|
||||
PartialSession p = PartialSessionFile.Parse([.. head, .. PartialSessionFileAdvancedTests.Chunk(type: 11, payload)])!;
|
||||
|
||||
p.Truncated.Should().BeTrue($"a payload of {payload.Length} byte(s)");
|
||||
p.Sensors.Should().ContainSingle().Which.Input.Should().BeNull();
|
||||
}
|
||||
|
||||
PartialSessionFile.Parse([.. head, .. PartialSessionFileAdvancedTests.Chunk(type: 11, good)])!.Sensors[0].Input.Should().BeEquivalentTo(Quiet(), "the same chunk, whole");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AReadingWhoseSampleIsNotInTheFileBelongsToNoTickAndIsLeftOut()
|
||||
{
|
||||
string source = Path.Combine(_dir, "source.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(source, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(9_999_999, Quiet())]);
|
||||
}
|
||||
|
||||
string path = Path.Combine(_dir, "orphan.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000)]);
|
||||
}
|
||||
|
||||
byte[] other = File.ReadAllBytes(source);
|
||||
byte[] orphan = other[PartialSessionFileAdvancedTests.ChunkOffsets(other)[2]..];
|
||||
|
||||
PartialSession p = PartialSessionFile.Parse([.. File.ReadAllBytes(path), .. orphan])!;
|
||||
|
||||
p.Truncated.Should().BeFalse();
|
||||
p.Sensors.Should().ContainSingle().Which.Input.Should().BeNull();
|
||||
}
|
||||
|
||||
/// <summary>A later build may know a maker, a connection or a battery state this one has no name for: it reads as "do not know", and the rest of the reading is kept.</summary>
|
||||
[Fact]
|
||||
public void AValueThisBuildHasNoNameForReadsAsUnknownAndTheRestIsKept()
|
||||
{
|
||||
string path = Path.Combine(_dir, "later.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000, Full() with { Devices = [Full().Devices[0]], Table = [_xbox] })]);
|
||||
}
|
||||
|
||||
byte[] file = File.ReadAllBytes(path);
|
||||
int at = PartialSessionFileAdvancedTests.ChunkOffsets(file)[2];
|
||||
byte[] payload = file.AsSpan(at + 8, BitConverter.ToInt32(file, at + 4)).ToArray();
|
||||
int device = payload.Length - 23;
|
||||
payload[device + 4] = 200; // the family
|
||||
payload[device + 9] = 201; // the connection
|
||||
payload[device + 16] = 202; // the battery's state
|
||||
payload[device + 17] = 203; // and its scale
|
||||
|
||||
InputReading reading = PartialSessionFile.Parse([.. file[..at], .. PartialSessionFileAdvancedTests.Chunk(type: 11, payload)])!.Sensors[0].Input!;
|
||||
|
||||
reading.Table[0].Family.Should().Be(ControllerFamily.Other);
|
||||
reading.Table[0].Connection.Should().Be(ControllerConnection.Unknown);
|
||||
reading.Devices[0].Battery.Should().Be(new BatteryReading(BatteryState.Unknown, BatteryScale.None, 2));
|
||||
reading.Devices[0].ActiveMs.Should().Be(502);
|
||||
reading.Table[0].XInputSlot.Should().Be(2);
|
||||
}
|
||||
|
||||
/// <summary>A controller the reading counts and does not describe cannot be written whole, and is left out; ids past sixteen bits are held to them.</summary>
|
||||
[Fact]
|
||||
public void AControllerWithNoDescriptionIsLeftOutAndOutOfRangeValuesAreHeld()
|
||||
{
|
||||
var wide = new InputDevice { Id = 9, VendorId = 0x12345, ProductId = -4, XInputSlot = 300 };
|
||||
var reading = new InputReading
|
||||
{
|
||||
Devices =
|
||||
[
|
||||
new InputDeviceReading(404, Connected: true, ActiveMs: 10, Battery: null, Connects: 0, Disconnects: 0),
|
||||
new InputDeviceReading(9, Connected: true, ActiveMs: 20, new BatteryReading(BatteryState.Discharging, BatteryScale.Percent, 900), Connects: 70_000, Disconnects: -1),
|
||||
],
|
||||
Table = [wide],
|
||||
};
|
||||
string path = Path.Combine(_dir, "held.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000, reading)]);
|
||||
}
|
||||
|
||||
InputReading back = PartialSessionFile.Read(path)!.Sensors[0].Input!;
|
||||
|
||||
back.Devices.Should().ContainSingle().Which.Should().Be(
|
||||
new InputDeviceReading(9, Connected: true, ActiveMs: 20, new BatteryReading(BatteryState.Discharging, BatteryScale.Percent, 255), Connects: 65_535, Disconnects: 0));
|
||||
back.Table.Should().ContainSingle().Which.Should().BeEquivalentTo(wide with { VendorId = 65_535, ProductId = 0, XInputSlot = 255 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user