Compare commits

...
Author SHA1 Message Date
poli0981andClaude Fable 5.1 6b51515dca feat(vklayer): vkQueuePresentKHR intercepted -- the layer owns the ring, records every present, and stops itself on the present path (P1 item 3, §S2 part three)
In a process both gates admitted, the layer creates the same ring the Overlay
would -- fl_shm_host.h is now the one home of the DACL, the name, the mapping
and the handshake for BOTH capture sides (the Overlay calls it too) -- at the
first vkCreateDevice, writes one record per present (api = Vulkan, output size
from vkCreateSwapchainKHR's imageExtent, no PRESENT_ARGS because the call has
none) and forwards everything. One ring per process: the first creator owns it,
the other stays inert AND forwarding -- the first fixture run measured
VK_ERROR_DEVICE_LOST when the layer had registered no next pointer, so the next
pointers now come before the ring and the ring failing only ever means
"observe nothing".

§S2 part three lands with it, on the present path (the layer owns no thread):
unhookRequested -> UNHOOKED within one present; guardTicks not advancing for the
07_IPC deadline -> UNHOOKED; pauseRequested -> no record, still forwarded.
"Stops" is passthrough forever with the reason on the mapping. Proven by a fake
loader chain (ctest fl_vklayer) and a 1.5 s test-only flavour of the DLL
(fl_vklayer_supervision: ticks every 600 ms keep it alive past the deadline,
1.8 s without one stops it).

Real loader: hook-harness --vulkan --hold-presenting N (vulkan-1 via
LoadLibraryW, hidden window, exit 77 = cannot run here) and ctest
fl_vklayer_real, which points the loader at the build tree's manifest through
VK_ADD_IMPLICIT_LAYER_PATH -- measured honoured by 1.4.357 with no registry --
and skips on CI: 241 records in 4 s. vklayer-blastradius.ps1 hand-run, green.

Launch mode: a target that mapped vulkan-1.dll is the layer's --
Reason::kTargetIsVulkanLayered (26): the full guard runs, nothing is injected,
the host attaches to the layer's ring with launch mode's budget. Vulkan WINS
over a D3D runtime beside it, because the NVIDIA Vulkan ICD maps dxgi + d3d12
itself and presents through a DXGI chain (measured: the injected Overlay
recorded 295 DXGI presents of a Vulkan swapchain). The CaptureHost's launch
hands the process the layer's environment (VkLayerLaunchEnvironment: manifest
under %LOCALAPPDATA%\FrameLedger\vklayer, enable variable, enable-list line for
the session) and stages FrameLedger.VkLayer.dll beside itself.

Docs: 17_HOOK_ENGINE §Vulkan + Presentation row, 20_OPEN_QUESTIONS §S2 ✅ /
§S24 / §S29(d), 04_CAPTURE, 12_BUILD, spike-notes §2 (two measurements),
legal/ACCURACY.md + its two copies, README, DISCLAIMER §2, 15_ROADMAP, HANDOFF,
CHANGELOG.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 19:25:45 +07:00
poli0981andClaude Fable 5.1 f61d35f7f6 feat(injector): launch mode as "inject late" -- the guard waits for a presentation runtime, then runs in full (P1 item 2, §S1 / §S13(c)) (#139)
A CREATE_SUSPENDED target has loaded nothing and EnumProcessModulesEx fails
against it (§S1, measured), so launch mode cannot be create -> guard -> inject
-> resume. Built shape: start -> the guard WAITS -> the full guard -> inject.

Guard: GuardedInjectWhenReady(pid, dll, timeoutMs) / ABI FlGuardedInjectWhenReady
polls the target every 50 ms through the module seam -- matching no blocklist;
a failing enumeration is "not yet", never a pass -- until dxgi+d3d11/d3d12,
opengl32 or vulkan-1 is mapped, then runs GuardedInjectImpl unchanged. Two new
reasons end the poll with nothing injected: LaunchTargetExited (24) and
LaunchNoPresentationRuntime (25). ctest fl_guard [launch], five cases: injects
on the first enumeration showing the runtime and not one before; exit-first and
budget-out each answer their own reason; anti-cheat mapped beside the runtime is
the full scan's refusal; the real seam against hook-harness injects in 15 ms.

Overlay: FlWriterState.dxgiPresentsBeforeHook @60 -- GetLastPresentCount at the
first hooked present on the first hooked chain, i.e. presents that ran before
the hook was in; 0xFFFFFFFF until a present is seen, set BEFORE the present
hooks go in (the first placement, after them, lost the race to an 8 ms
presenter -- caught by the fixture). Took the last reserved word; no layout
bump; the writer state now has no slack.

CaptureHost: `launch --exe <path> [--args "..."] [--seconds n]`; ProcessLauncher
(handle held from birth, FRAMELEDGER_ENABLE_VK_LAYER=1; the host never
terminates what it launched); CaptureLoop.RunLaunchedAsync sharing the gate,
attach and drain with attach mode; HookRequest.WaitForPresentationRuntimeMs
routes the same gate through IAntiCheatGuard.GuardedInjectWhenReadyAsync (the
port's fourth method, primitives only); the report prints the wait and the
before-hook count (LaunchNote). NoSecondMatcherTests 3 -> 4 as a reviewed act.

Docs: 04_CAPTURE §Launch mode (the shape, why not CREATE_SUSPENDED, what it
measures), 01_ARCHITECTURE, 19_SAFETY item 1, 20_OPEN_QUESTIONS §S1 ◐ /
§S13(c) ✅ / §S24, 17_HOOK_ENGINE, 15_ROADMAP, HANDOFF, spike-notes, CHANGELOG.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 17:42:01 +07:00
poli0981andClaude Fable 5.1 627995068d feat(overlay): the LoadLibrary detour -- lazy-install wake within milliseconds + the in-process anti-cheat stop (P1 item 1, §S6) (#138)
kernelbase.dll!LoadLibraryExW is patched from InitThread after the present hooks
(17_HOOK_ENGINE §DLL entry step 3). The body calls the original first, skips
data-file / resource mappings, reads the mapped module's own file name into a
stack buffer and compares its base name against two fixed tables:

- FL_HOOK_INVENTORY + FL_RUNTIME_CENSUS: a match bumps a saturating 15-bit wake
  count and signals the watchdog's new auto-reset event, so the lazy installers
  run within milliseconds of the module rather than on the next 1 Hz tick.
  Measured in ctest fl_guard [loader]: 94 ms against a 500 ms bound.
- the compiled floor's MODULE families (fl_ac_floor.generated.h, prefix,
  case-insensitive, allocation-free): a match CASes the family's 1-based index
  into earlyStopFamily; MayObserve or the watchdog, whichever is first, calls
  StopObserving(FL_STATUS_STOPPED_BLOCKLISTED). ctest fl_guard [S6]: a decoy
  named EasyAntiCheat_fl_fixture.dll loaded 2.5 s in stops the Overlay with the
  index the test computes from the same table, unhookRequested still 0,
  writeIndex frozen.

The detour installs nothing inline (§H2). Exact names only: the fragment and
signer tiers stay the host's 30 s scan, so the Disclaimer's window is unchanged
(19_SAFETY §During a session, the in-process half).

FlWriterState gains loaderSignals @56 and earlyStopFamily @58 from reserved[]
(no layout bump; mirror + fl-layout-dump updated). hook-harness gains
--load-after-ms N PATH. The CaptureHost reads both words (Consume/EarlyStop.cs):
"loader detour:" and "EARLY STOP" report lines, the family named from the staged
rules file, SessionEndReason.WriterStoppedBlocklisted -> exit 5.

Docs: 17_HOOK_ENGINE §DLL entry + the one system-module hook row, 19_SAFETY,
20_OPEN_QUESTIONS §S6 ✅ / §S24 / §H2, 15_ROADMAP P1, HANDOFF, CHANGELOG.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 09:46:03 +00:00
poli0981andClaude Fable 5.1 c5932cc115 P0 closing sweep — criterion 1 amended, criterion 2 met; §S19(c) and §S23-6 closed by a gate each, §S29(d) on a CI measurement, six deferrals written (#137)
* docs+tools: P0's closing sweep -- criterion 1 amended, criterion 2 met; §S19(c) and §S23-6 closed by a gate each, §S29(d) pre-committed on a CI measurement, six items deferred with rationale

The owner's "theo bảng" (2026-09-06). Criterion 1: the quality preset reads N/A on every
title by measurement (tags carry no size or preset on D3D12, NVIDIA's override fields are
the override's, XeSS is closed by licence) and an honest N/A is the correct value rule 7
asks for; upscaler, render->output, FG factor and RT verified against nine titles' menus.
Criterion 2: §S24 counts zero S-items against it, with S23-2 (a GitHub setting) outside
any PR.

- §S19(c): rules-validate gains canary 3 -- the shipped document mutated to action
  "allow" and to signerField "CN" must be rejected by the schema (proven red by loosening
  the const in a temp copy). The policy is code; the fields exist so the data cannot say
  otherwise.
- §S23-6: legal/ACCURACY.md is the one accuracy block, embedded verbatim in README.md
  and DISCLAIMER.md §4 between markers; tools/accuracy-check.ps1 (build.ps1 gate, four
  self-test cases both directions) fails on drift, missing markers or an empty source.
  The block is rewritten to 2026-09-06 truth (the old §4 still said frame generation and
  ray tracing had no hook).
- §S29(d): ci.yml prints a Vulkan runtime census; rows pre-committed -- present: the
  blast-radius script becomes a CI step; absent: deferred on that measurement.
- Deferred with rationale in the entry and phase in §S24: S6 and S2 part three (P1),
  S23-3 (P3), S4 signing, S20 feed half, S14 store-id half (P4).
- 15_ROADMAP and HANDOFF: P0 closed, P1 starts.

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

* docs: §S29(d)'s census read off the sweep run -- loader present, vulkaninfo and ICD absent; deferred on that measurement with the reopen condition written

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 09:07:04 +00:00
poli0981andClaude Fable 5.1 42e15c9dbd feat(guard): the signer half -- "name fragment AND not signed by a known vendor", under a compiled-in bound; -SkipIntegration dropped from CI (§S19(b) row G1) (#136)
Since 2026-08-05 the guard refused FrameLedger's own test host on CI: a .NET host
loads System.Security.Cryptography.ProtectedData.dll, `protect` is a heuristic
fragment, and the signer conjunct was unwired. fl-probe-signer's three legs (dev box,
CI, the owner's adapters-disabled run) all read the same: the embedded signature
verifies offline with O=Microsoft Corporation in ~2-4 ms and no verdict changes
without a network. The owner chose the bound (option 1) on 2026-09-06.

- Sources::ModuleSignerOrganisation (fl_guard_sources.cpp, never fl_ac_rules.cpp):
  WinVerifyTrust WTD_CHOICE_FILE under WTD_REVOKE_NONE | WTD_CACHE_ONLY_URL_RETRIEVAL |
  WTD_SAFER_FLAG, then the signing certificate's subject O= -- fixed buffers, no
  allocation; kFailed for everything short of a verified, readable organisation.
- IsCompiledTrustedSigner: the five organisations compiled in; IsTrustedSigner now
  requires the rules file AND the binary, so a rules push can narrow and never widen.
- ModuleSinkFn: after the ours exemption, a fragment-matching module signed by a
  trusted organisation returns keep-looking (the load-order fail-open stays closed);
  the target is judged like its ancestors; everything else latches SuspiciousUnsigned.
- hook-harness --load PATH; fl_guard proves both directions against the real seams
  (the NuGet blocker allowed and the Overlay injected; our own unsigned Overlay under
  a `protect` name outside the guard's directory refused, by name) plus nine fake-seam
  cases (both lists, the target, kFailed, missing seam, pathless, load order, exact-hit
  precedence). The catalog half stays deferred with its rationale.
- ci.yml runs ./build.ps1 check with no switches: the nine Category=Integration cases
  are in the merge gate. The switch stays in build.ps1, loud.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 15:25:11 +07:00
poli0981andClaude Fable 5.1 1d72021a8a docs: the signer probe's two remaining legs read -- CI (rows G3/G4/G5 do not fire) and adapters-disabled (every verdict unchanged, row G1); the bound is what remains (#135)
The CI leg, off the new ci.yml step: the runner's NuGet copy of the blocker verifies
embedded/offline in 3.47 ms with O= Microsoft Corporation; mskeyprotect.dll is catalog-only;
cryptnet.dll loads under the offline flags; canary TRUST_E_NOSIGNATURE. The
adapters-disabled leg, the owner's run: every verdict unchanged, faster (2.14 ms), the
blocker's subject now CN=.NET with the same O= -- signerField "O" confirmed on a subject
class it had never met. Row G1 reads. The trustedSigners allow-widening bound is the
owner's decision and is asked for beside the reading.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 08:01:59 +00:00
poli0981andClaude Fable 5.1 bed369b21c ci: the signer probe's CI leg, printed -- §S19(b) rows G3/G4/G5 were never readable (#134)
ctest fl_signer_probe passes on a regular expression and prints nothing for a passing
test, so the CI leg §S19(b) pre-committed rows for was never in any log; and the native
tests run before dotnet restore, so a cold runner may not even have the NuGet copy the
probe searches first. ci.yml now runs the probe as its own step after the gate
(continue-on-error: a measurement, not a gate). HANDOFF's Separable item carries the
sequence: this leg, the owner's adapters-disabled leg, the owner's allow-widening bound,
then the guard PR that drops -SkipIntegration.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 07:41:06 +00:00
poli0981andClaude Fable 5.1 7dbfb5cb6f feat(capturehost): the FG N/A and the upscaler N/A carry their witnesses -- Hell Is Us at XeSS + XeSS-FG, and 7c item 4's string change (#133)
Hell Is Us at XeSS + XeSS-FG (2026-09-06): no Streamline token on that plugin at XeSS, so
nothing counted, and the report printed a bare "N/A (a hook ran ...)" while the driver's FG
word, the tags, the ffx census, the module census and the executable's strings all had
something to say. The N/A now prints the same exclusion clauses as rung 3; the upscaler N/A
says libxess.dll is loaded and XeSS cannot be hooked or declared under Intel's licence, so
the N/A is by policy, not by ignorance. Rune Factory at FSR + FSR FG printed the
pre-committed 7b line verbatim on the same run; Cronos at XeSS read none by count.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 14:27:45 +07:00
poli0981andClaude Fable 5.1 8cf3d6f3eb feat(capturehost): rung 3 by elimination, and the executable file as the census's second witness -- HANDOFF 7b / §H11, the owner's choice over "return native" (#132)
- `frame generation: Active (technology not identified)` now prints every exclusion the
  session can make: not DLSS-G when the driver's FG word reports no feature created and no
  HUD-less / UI tag was sent (or "not excluded" without the driver's answer), no FSR
  frame-generation dispatch reached a hooked module, the frame-generation runtime modules
  the census names or that none is loaded, and the SDK strings the executable carries.
  Never a vendor named as measured (XeFG cannot be hooked or declared by licence; a
  compiled-in FSR 3 has no module), and the line says a frame generator compiled into the
  executable would read the same.
- ExecutableMarkerScan reads the exe FILE on disk once after the session (chunked with
  overlap, hits capped; ffxFsr3, ffxFrameInterpolation, xefgSwapChain move the sentence;
  FidelityFX, ffxFsr2, NVSDK_NGX, xessD3D12 are printed for the reader) and the report
  prints `executable markers:`. With no module loaded and a frame-generation-capable
  string in the file, the Presented qualifier reads MAY include generated frames instead
  of cannot -- the sentence that was wrong in the dangerous direction on Rune Factory.
- Consumer only; no hook-path change. 8 new cases; one superseded expectation updated.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 06:36:12 +00:00
poli0981andClaude Fable 5.1 237765dede docs: the AMD half of 7c complete on Lies of P; the Intel licence re-checked and unchanged; identity by elimination proposed for XeFG (#131)
Lies of P at FSR 3.1 + FSR FG on #129: Fsr3 / FsrFg / 59.77 -> 119.55 (x2 FG) / 2560x1440 ->
2560x1440, presents/frame 2.00, frames/upscale-drained 1.00, unseen 0, the NVIDIA driver's
word saying nothing was created. The owner called the AMD half done.

Intel: LICENSE.txt and inc/xess/xess.h re-fetched 2026-09-06 -- Intel Simplified Software
License, unchanged; the reversal condition has not fired. Intel's README says XeSS-FG runs
on non-Intel GPUs with SM 6.4, so an XeFG session is measurable here. §H11 carries the
in-policy proposal: identity by elimination, labelled, never XeFg as a measured identity.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 06:16:19 +00:00
poli0981andClaude Fable 5.1 7cc4efc8e2 docs: §H5's DLSS / DLSS-G question closed on Cronos with frame generation on -- the 2.8.0 pacer bypass is Dying Light: The Beast's, not the SDK's (#130)
Cronos: The New Dawn demo (Streamline 2.8.0, UE) with FG on: 86.8 -> 172.72 (x1.99 FG),
unseen=0 over 10,063 samples, DlssG with the driver agreeing, upscaler Dlss driver-reported.
Every measured NVIDIA title now prints the rule-6 trio or a counted none; the owner closed
the item. HANDOFF 7a struck; the next item is the owner's pick from 7b / 7c.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 05:36:54 +00:00
poli0981andClaude Fable 5.1 a55be828cd feat(capturehost): the driver's FG word beside the frame-generation line, and a counted-but-refused session says so -- §H5 rows N1-N4 landed (#129)
The owner's run on #128: N3 held (Lies of P with upscaling OFF reads SR 0x5, CREATED clear),
N1 prints `Dlss (driver-reported ...)` on Lies of P, Expedition 33, Hell Is Us and the new
Cronos demo, N2 prints agreement on Onimusha and DL:TB, and a DL:TB session at FSR + DLSS-G
read SR 0x205 (created, not evaluated) and correctly claimed nothing.

One correction from the run's own readings: the FG word is NOT blind to Streamline DLSS-G.
It read CREATED | EVALUATE on every x4 session, changing between readings as the feature
came up; the morning's INITIALIZED | DLL_EXISTS was an early reading. The multiplier bits
stay clear at x4, so the word is an identity witness: printed beside `frame generation:`
as agreement or a printed disagreement, promoted to `DlssG (driver-reported ...)` only where
the count is active and no tag named the technology. The count is never the driver's.

And the FSR + DLSS-G session exposed a wrong qualifier: 4,415 tokens, 8,174 DXGI-counted
presents, a factor refused for uniformity, and the line said "no evaluation was observed".
It now says the factor was counted and refused, that DXGI counted presents this hook never
saw so the Displayed rate is above the printed number, and that the number is neither
Native nor Displayed.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 12:06:32 +07:00
poli0981andClaude Fable 5.1 f7c700acb8 feat(capturehost): the super-resolution identity from the NVIDIA driver where no hook can see it -- the driver-reported rung (#128)
Owner decision 2026-09-06 ("noi probe de bat dau"). Three NGX-direct titles printed
`upscaler: N/A` on every capture while the driver's per-process NGX word
(NvAPI_NGX_GetNGXOverrideState) reads CREATED | EVALUATE for them without an override.

- fl-probe-nvapi --ngx-state prints one machine line (NGXSTATE status=... sr=0x... ...)
  after its human output; the capture host stages the probe beside itself.
- NgxDriverProbe spawns it beside every module snapshot (out of process, no injection);
  NgxDriverState parses and merges the readings (last answered word is the state, a
  change between readings is printed, an earlier answer outranks a later silence).
- The report prints `NVIDIA driver NGX state:` in the runtime block; the `upscaler:` line
  reads `Dlss (driver-reported: ... not counted by this hook)` when no hook named one,
  prints agreement or a disagreement (printed, not resolved) beside a hook's Dlss, and
  the driver's attributed negative beside an N/A.
- Identity only, each limit measured: no quality/preset (override fields), no ratio
  (scalingRatio 0 even under an override), no FG mode/multiplier (the FG word is blind
  to Streamline DLSS-G).
- §H5 pre-commits rows N1-N4; N3 (DLSS OFF) withdraws the rung if the bit stays set.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 03:26:23 +00:00
poli0981andClaude Fable 5.1 ec181de07d docs: the NVAPI NGX-state probe measured on three running titles -- SR identity is driver-reported without an override; the FG word does not see DLSS-G (#127)
Hell Is Us (no override, DLSS-G x4 running), Expedition 33 (NVIDIA-app override ON, FG off)
and Lies of P (no override): CREATED | EVALUATE on the SR word on both no-override titles;
the FG word reads INITIALIZED | DLL_EXISTS beside a x4 DLSS-G session; frameGenerationCount
is 0 everywhere (the override target, not the multiplier); scalingRatio is 0 even under the
override. §H5 states what a driver-reported rung may and may not claim and the negative
still owed (DLSS off in the menu); HANDOFF 7a's START HERE moves to that decision.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 02:51:39 +00:00
poli0981andClaude Fable 5.1 d670824058 feat(capturehost): the withheld none narrowed to sessions where DXGI's counter was not read -- §H5 Leg 0 landed (#126)
The owner's morning run on #125: DL:TB at DLSS FG x4 printed the rule-6 trio from the
DXGI-counted Displayed (70.52 -> 282.08 (x4 FG), 12,387 presents DXGI-counted, DlssG),
then twice with frame generation OFF: census unchanged (sl.dlss_g.dll is a startup-time
load), presents = tokens, unseen = 0 over 3,659 / 4,519 samples, and the report withheld
`none` exactly as the gate's cost paragraph pre-committed. Expedition 33 FG off: none by
count, tag census 0.

The DXGI counter is the discriminator the gate lacked -- on the 2.8.0 shape the pacer's
presents are DXGI presents on the hooked chain -- so a counted none beside a READ counter
with zero unseen prints as none with "DXGI's own present counter agrees: 0 unseen over N
hooked present(s)"; it is withheld only when the counter was not read, with the reason
saying so; a writer state that counted unseen presents the records do not carry is refused
as a contradiction. Every other title prints the counter beside none as a second witness.
CLAUDE.md rule 6 carries the amendment; 03_METRICS, §H5, spike-notes §9, HANDOFF updated.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 09:09:55 +07:00
poli0981andClaude Fable 5.1 61dc4c4036 feat(overlay): Displayed counted by DXGI where the hook cannot count it -- §H5 row P1-DXGI landed, twice (#125)
The owner's run on #124 read 2.90 and 2.95 presents per hooked present that DXGI counted
on the same chain and the inline patches never saw (Dying Light: The Beast, Streamline
2.8.0, DLSS FG x4), against 0.00 on Streamline 2.7.3 (Hell Is Us x3.86) and 2.10.3 (the
Onimusha: Way of the Sword demo x3.67), whose generated frames come through the patched
bodies. So 2.8.0's pacer is the odd one, and the pre-committed action is built:

- FlFrameRecord.dxgiUnseen @52 (first byte of v3's reserved word, no offset moved, no
  layout bump) under FL_MEASURED_DXGI_PRESENTS; mirror, fl-layout-dump and asserts follow.
- FgWindow counts Displayed = hooked + sum(dxgiUnseen): in the rule-6 trio, presents/batch
  and the uniformity buckets, never in a frame-time distribution. The report prints
  "Displayed is DXGI-COUNTED" on its own line whenever the sum is above zero. A saturated
  byte is refused; a byte under a clear bit is an honesty violation.
- A present the hook SAW and declined (a paused session) is not unseen: every declined
  present bumps an epoch that invalidates the chain's last reading. The paused-session
  integration case caught the first record after a resume claiming the whole pause (0x55).
- The "sl.interposer + sl.common must be loaded on >= 2.8" lead is closed by the 2.10.3
  title, which injects, tags on the frame route and counts like 2.7.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 16:18:12 +00:00
poli0981andClaude Fable 5.1 ef7d657f9d feat(overlay): DXGI's own present counter against the hook's -- the in-process half of §H5 Leg 1 (#124)
On every hooked present the Overlay now reads IDXGISwapChain::GetLastPresentCount on
the chain it just saw (rule 4: the object FindOrAdd already calls GetDesc on; no new
hook) and publishes dxgiPresentSamples / dxgiPresentsUnseen on the watchdog tick
(FlWriterState @48/@52 from reserved[], no layout bump; mirror, fl-layout-dump and
the offset asserts follow). The report prints the ratio with its reading and the
withheld qualifier says which side of DXGI the generated presents fall on. §H5 carries
the rows written before the run (P1-DXGI / P3-DXGI / P5-DXGI). The harness's own
presents are the negative control (fl_guard [fg]: zero unseen); the positive cannot
be fixtured. hook-harness --probe-frames prints the call's cost (12.4 ns on WARP).

The owner's lead -- Streamline >= 2.8 needs sl.interposer.dll and sl.common.dll loaded
before injection succeeds -- was checked against the interposer source: the DXGI proxy
is identical at 2.7.32 and 2.8.0, and injection into DL:TB already succeeds. The
unknown is where the closed pacer presents, which is what this counter asks DXGI.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 14:48:49 +00:00
poli0981andClaude Fable 5.1 5656707733 feat(capturehost): a stall diagnostic placed against FrameLedger's own touches on the target (#123)
The owner saw Cyberpunk 2077 fall to 1 FPS for about a second under capture and the report
could say nothing about whose it was. The loop now records the QPC moment of every guard scan
and module snapshot (CaptureResult.TouchQpc, the records' own clock), and StallReport prints
the three longest present-to-present intervals with their session time and the nearest host
touch: inside or within 1 s -> FrameLedger is a SUSPECT, re-run on the 30 s cadence; far away ->
not ours. Counts intervals at or over 100 ms; calls itself a diagnostic, not 03_METRICS' stutter.
Four cases pin the placement. No Overlay change.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 13:29:46 +00:00
poli0981andClaude Fable 5.1 a34d9e3cd2 docs: the tag route measured -- DlssG on six of six Streamline titles; DL:TB's scaling-input tag arrives with no size (7a closed by the census) (#122)
The owner's evening run on #121: `frame generation: DlssG` on Hell Is Us (x4, twice), Expedition
33 (x1.97), Wukong (x4), Rune Factory (x3.98) and Cyberpunk; every Streamline title tags the
DLSS-G inputs through a route this build hooks (UE + Cyberpunk 2.7.1 globally, DL:TB 2.8 via
slSetTagForFrame). DL:TB's census shows a scaling-in tag on the frame route with UpscalerParams
still 0 -- no size on the tag -- closing 7a's last question at no layout cost. Cyberpunk's factor
was refused on a mixed session (bucket 1 at 3.0 vs 1.67, tokens/batch 2.97), as designed.
Recorded in spike-notes §9, §H5 and HANDOFF 7a; the one NVIDIA gap left is `upscaler: N/A` on
the NGX-direct titles (the --ngx-state probe).

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 20:07:48 +07:00
poli0981andClaude Fable 5.1 1a326337f2 feat(overlay): DLSS Frame Generation named from the tags the title sends -- slTagCensus per route, FL_FG_DLSS_G on a present that drained a HUD-less / UI tag (Streamline DLSS-G guide §5.0) (#121)
Every NVIDIA title measured on 2026-09-05 had the count right and the technology unnamed
(`Active (technology not identified)`): kFeatureDLSS_G is never evaluated through the export
the identity hook owns. The Streamline docs (v2.8.0 / main) give the in-policy answer: the
DLSS-G programming guide §5.0 requires a frame-generating title to tag the HUD-less colour and
UI buffers every frame through slSetTag / slSetTagForFrame / slEvaluateFeature's inputs -- the
three routes this build already hooks and read ONE tag type from.

- The two tag detours and the local walk record every tag's TYPE (rule 4: the same argument,
  zero new hooks) into a per-present word and a session word; a HUD-less or UI tag drained by a
  present marks it FL_FG_DLSS_G; FlWriterState.slTagCensus (took reserved[0], additive, no
  layout bump; fl-layout-dump + ShmLayout.cs mirror) says which types arrived on which route.
- The consumer's rule: the count decides `none`, identity decides the name. An active count
  beside the mark prints `frame generation: DlssG`; a counted 1.0 beside it prints `none` with
  the inputs noted (a title may feed the inputs with the feature off); the withheld shape (§H5)
  keeps its N/A and says the title is feeding frame generation. FsrFg keeps precedence. The
  report prints `Streamline tag census: global=[...] frame=[...] local=[...]`.
- slDLSSGGetState -- the API the guide §14.0 names for the presented count -- is REFUSED, with
  the reason in 03_METRICS: `numFramesActuallyPresented` is "since the last slDLSSGGetState
  call", so every call resets the plugin's counter a title may read for its own FPS display,
  and the header marks it not thread safe.
- Fixtures: `--sl-tag-dlssg-inputs` sends the DLSS-G list through either global export with no
  kFeatureDLSS_G evaluation; two injected cases assert the mark on every record and the census
  on the global/frame route and not the local one; the existing tag cases assert its absence
  (a scaling-input tag alone must not read as frame generation). Six consumer cases.
- Docs: 03_METRICS §FG (identity source + the refusal), 17_HOOK_ENGINE rows, §H5 (the docs
  reading and the per-title pre-commitment for the next run), HANDOFF 7a, CHANGELOG.

Hook-path overhead: the tag detours now walk every tag (bounded at 64) instead of returning at
the first scaling input, one relaxed fetch_or per list; RecordPresent gains one exchange(0).
hook-harness --probe-cost on this build: unhooked 3162.2 / hooked 3162.9 ns per present, delta
0.7 ns (budget 1000 ns).

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 11:29:12 +00:00
poli0981andClaude Fable 5.1 fcc15a0894 fix(capturehost): the render -> output window under frame generation; fl-probe-nvapi --ngx-state <pid> (the driver's per-process DLSS feedback), and the owner's 11-capture run recorded (#120)
The owner's run on #118 + #119 (eleven captures, seven titles, DLSS or FG on everywhere):
§H11 B1 and B1-off landed (Cyberpunk at FSR 3: `Fsr3`, `FsrFg`, x2, frames/upscale-drained
1.01; FG off: `Fsr3`, `none`), DL:TB's counter read ~300 against our 76.7 (reading (a) with its
number; PresentMon leg still owed), and on every NVIDIA title the COUNT is right while the
IDENTITY is what this build cannot say (DLSS on the NGX-direct UE titles, DLSS-G everywhere).

- Fixed: `render -> output` printed N/A on every FG-on capture two lines under its own raw
  `render WxH` block. UpscaleExtent keyed its window on the params bit, which rides on one
  present in N under frame generation, so ClaimedSuffixStart found no clean window; it now keys
  on the identity bit (per-record once live). Two cases pin the FG shape and the refused
  intermittent-identity shape; the Cyberpunk FSR 3 consumer case asserts the line.
- Added: `fl-probe-nvapi --ngx-state <pid>` prints NvAPI_NGX_GetNGXOverrideState's raw words and
  every decoded feedback bit (SR/RR/FG: DLL_LOADED, CREATED, EVALUATE, FG_MODE, FG_MULTI_FRAME,
  ...; scalingRatio, performanceMode, frameGenerationCount/Mode). Out of process, MIT NVAPI, no
  hook. Smoke-tested: driver 616.64 answers the call, NVAPI_DATA_NOT_FOUND for a non-NGX
  process. Whether the bits are populated for a game with no NVIDIA-app override is the owner's
  next measurement; §H5 frames the decision it opens (a driver-reported rung, the owner's call).
- Docs: §H5 (counter, the three shapes, the probe and the decision), §H11 (B rows landed, the
  extent defect), spike-notes §9 (the run's table), HANDOFF 7a (START HERE next), CHANGELOG.

Hook-path overhead: none -- no Overlay code changed.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 15:41:16 +07:00
poli0981andClaude Fable 5.1 ee718c3380 feat(overlay): the FSR 3.0 host route -- ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale as a fifth AMD target, vendored from fsr3-v3.0.4 (not v1.1.4) (#119)
Cyberpunk 2077 at FSR 3 upscales through the FSR 3.0 HOST DLL's named export while its frame
generation goes through the 1.1.x monolith's ffxDispatch, so the leaf-only build printed
`upscaler: N/A` beside `FsrFg` (20_OPEN_QUESTIONS §H11, 2026-09-04).

- One row, the host's UPSCALE, under the same family and publish point as the four ffx-api rows
  (PublishFfxFamilyIfWhole waits for a loaded host as it waits for a loaded leaf), keyed by module
  in the installer's ffx arm with its own trampoline and latch. Rule 4: renderSize of the
  descriptor the title passed and nothing else; offsetof(renderSize) is pinned to the literal 1256
  so a re-vendoring that moved it fails to compile. Identity FSR3 as a fact.
- ffxFsr3DispatchFrameGeneration is deliberately not a row: the monolith generates on the one
  title, the count is Streamline's, and the host's FG export fires per GENERATED batch. The
  reversal condition is pre-committed in §H11.
- The headers are vendored from tag fsr3-v3.0.4, NOT the v1.1.4 three documents named: the shipped
  module exports exactly 3.0.4's twelve ffxFsr3* names, 1.1.4 declares fifteen and appends fields
  after renderSize, and at 3.0.4 ffx_types.h includes <stdint.h> only (no <mutex>; ten files, no
  ffx_message.h). Separate directory (root LICENSE.txt is MIT verbatim, inline grants) with its
  own license-check §2e; every blob sha checked against the upstream tree. The two FidelityFX
  trees both define FfxFrameGenerationConfig, so the 3.0.4 header is included inside a namespace.
- Fixtures: the ffx_fsr3_x64.dll stub (hookinventory-check Pass C's second positive control),
  harness topologies fsr3host / fsr3host+mono, an [ffx] injected case at K = 1 (the row's
  double-count control) and K in {1, 4} beside the monolith, fl_ffx_resolve extended, and a
  consumer case for Cyberpunk's shape.
- Docs corrected in place (18_GPU_VENDOR_APIS, HANDOFF 7c, 20_OPEN_QUESTIONS §H11 with rows
  B1-B4 owed, 03_METRICS, 17_HOOK_ENGINE, spike-notes, 12_BUILD, THIRD_PARTY_NOTICES).

Hook-path overhead: the detour is on a once-per-application-frame call, not on the present path;
its body is the UPSCALE arm of ObserveFfxDispatch verbatim (one null check, two relaxed stores,
one fetch_add). hook-harness --probe-cost on this build: unhooked 300.3 ns / hooked 301.2 ns per
present, delta 0.8 ns (budget 1000 ns).

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 03:36:43 +00:00
poli0981andClaude Fable 5.1 315aa4b0dd feat(capturehost): runtime-module versions in the report, and a counted none withheld on Streamline 2.8 with sl.dlss_g.dll loaded (§H5 case 3) (#118)
Dying Light: The Beast (Streamline 2.8.0) read presents = tokens five times with DLSS Frame
Generation ON; the owner's reading on 2026-09-05 settled it as §H5 reading (a): the title runs
at DLSS x4, the frames this hook records are the native ones, and the generated presents never
reach the Present bodies the Overlay patches. The report printed `frame generation: none` on a
generating title, which is the affirmative negative rule 6 forbids.

- The capture host takes an out-of-process module snapshot beside every guard scan
  (Process.Modules + the file's version resource; no game memory, no layout change, nothing on
  the present path) and prints one `module:` line per census-named module with version + path.
- MeasuredFacts withholds `none` when sl.dlss_g.dll -- the Streamline plugin that would be doing
  the presenting, NOT nvngx_dlssg.dll, which every validated `none` also has loaded -- is in the
  census beside an interposer at or above 2.8.0 (or one whose version could not be read). The
  report falls through to Presented FPS with a qualifier: this number counts APPLICATION frames;
  the Displayed rate is unknown. Every validated `none` (Cyberpunk off/x3/x4 on 2.7.1,
  Expedition 33 and Lies of P FG off) is byte-identical; eight consumer cases pin it.
- §H5 records the reading verbatim, the RT-census corroboration (97.1% RT-active at DLSS x4 vs
  54.6% at FSR FG x2), the interim gate and its cost, and the owner's session pre-committed
  before it runs (DL:TB FG off / x4, Cyberpunk MFG x4, PresentMon elevated beside each) with
  rows P1-P6 and the second-present-sink candidates.

Hook-path overhead: none -- no Overlay code changed.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 10:06:04 +07:00
poli0981andClaude Fable 5.1 c8ad18b232 docs: 7a on Dying Light: The Beast closes as measured N/A; DLSS Frame Generation on Streamline 2.8 is its own session (owner decision) (#117)
The 00:53 capture on the #116 build still carried no render size on either
global-tag route with both rows live and the whole-resource fallback in, so the
quality byte and the render size are N/A on this title, honestly. The fifth
DLSS-FG-on run read presents = tokens again; §H5 case 3's candidate is handled
in a separate session and PR, starting from the pre-committed discriminator.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 18:11:38 +00:00
poli0981andClaude Fable 5.1 bc5b458ded feat(overlay): a whole-resource scaling-input tag yields the size the Resource declares, on every tag route (#116)
Dying Light: The Beast at DLSS still published no extent on the #115 build with
both tag rows live, so the title tags with a zero extent ("use the entire
resource") or not on this route at all. TagSize in fl_sl_inputs.h reads the
extent first and, when zero, the tagged sl::Resource's own width/height —
GUID-checked, from the argument the hooked API received — shared by the local
walk and both global-tag detours. A Resource declaring no size stays the honest
unknown. Unit cases, --sl-tag-whole-resource, and an injected case through the
2.8 export asserting the exact size on every record.

Doc-only beside it: 20_OPEN_QUESTIONS §H5 gets its case-3 candidate — every
DL:TB DLSS run had DLSS Frame Generation on per the owner and every one read
presents = tokens, so the computed `none` may be a rule-6 false negative on
Streamline 2.8; the discriminator (the owner's counter) is pre-committed.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 00:48:40 +07:00
poli0981andClaude Fable 5.1 59d26fa7f1 feat(overlay): the slSetTagForFrame row — Streamline 2.8's frame-based tags reach the params family, published when whole (#115)
Dying Light: The Beast at DLSS (SL 2.8.0) read Dlss identity on every batch and
UpscalerParams on none across three captures: 2.8 deprecates slSetTag for
slSetTagForFrame and the only params row hooked the deprecated export. A second
row on the same family, picked by symbol through constants the inventory header
binds to its rows; the family is published once every tag export the loaded
interposer has is patched, because publishing on the first row measured 38 of 41
records claiming params on the fixture (the ffx leaves' #110 defect again).

tools/vendor-exports.ps1 unions exports across every copy of a module name and
lists every version seen — the first-copy merge had hidden the 2.8 export behind
2.7.4 — and docs/vendor-exports.json is regenerated.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 17:10:02 +00:00
poli0981andClaude Fable 5.1 f9436c095f docs(ffx): row R6 ran — the loader row carries DL:TB and KCD2 at 1×; Wukong's FSR upscaling reads as compiled in (#112)
* docs(ffx): row R6 ran on #111 — the loader row carries Dying Light: The Beast and KCD2 at 1x; Wukong's FSR upscaling reads as compiled in

Dying Light: The Beast at FSR + FSR frame generation printed FSR (3.1 or 4) / FsrFg /
70.49 -> 140.9 (x2) with frames/upscale-drained 1.01, and KCD2 at FSR the identity with
none by count at 1.00 -- both through the loader row, once, which is the K = 1 control
the fixtures run confirmed on a real title. Wukong at FSR with frame generation off read
silent at the monolith and the loader alike while the monolith sat in the census: FSR
upscaling compiled into its UE plugin (Rune Factory's shape) with the 1.1.x monolith
loaded for frame generation and idle, is the reading that fits every number. Owed:
Wukong with FSR frame generation ON, expecting the Cyberpunk shape.

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

* docs(ffx): Wukong has no FSR frame generation — it is the second statically linked title, and nothing more is owed on AMD identity

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 15:38:39 +00:00
poli0981andClaude Fable 5.1 428df7f8cd feat(capturehost): the render -> output line is computed — modal extent, 03_METRICS' ratio, render scale, and a SETTINGS MOVED flag (#113)
Every real-title run since 2026-08-15 printed the raw sizes two lines above "N/A (the
ratio is not computed yet)". UpscaleExtent takes the MODAL (render, output) tuple over
the records that claim both FL_MEASURED_UPSCALER_PARAMS and FL_MEASURED_OUTPUT_RES --
both bits, not just the values, so a value without its bit stays the writer's defect
rather than being averaged in -- and the line prints the two measured sizes,
sqrt((outW*outH)/(renW*renH)), its reciprocal as a render-scale percentage, the record
counts, and SETTINGS MOVED when the window held more than one tuple. Modal rather than
mean, because averaging across a settings change is the classic way a benchmark number
stops meaning anything; the count of distinct tuples is what says it happened, until
P2's segmenter cuts the session.

No preset name is derived from the ratio. Whether "58% ~ Balanced" may appear beside a
measured field is HANDOFF item 7a's owner decision, and the quality byte stays what the
writer measured -- 0xFF on every title so far, which on the ffx-api route is the true
value: the dispatch carries no quality mode. The line hands the owner the number the
decision is about; a test pins that it prints no preset name.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 15:28:34 +00:00
poli0981andClaude Fable 5.1 c876bbdf71 fix(capturehost): a candidate with no main module yet is unreadable, not absent — the resolver test's "visible" now means readable (#114)
TargetResolverTests.OneInstanceResolves went red on the hosted runner twice in one hour
(2026-09-04, on two unrelated PRs) with TargetNotRunning about a process the test had
just shown was enumerable. A freshly started process can be in GetProcessesByName's
snapshot before its image is mapped; Process.MainModule is then null, and CollectMatches
skipped it without counting it -- narrowing the set exactly the way its own comment says
"could not look" must not. The null-image case is now counted as unreadable, like a
process we lack the rights to read, so the honest answer at that instant is
TargetAmbiguous and never a false TargetNotRunning. WaitUntilAllVisible waits for
MainModule to be readable rather than for the process to appear, because that is the
state the positive cases are about; three consecutive local runs green.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 22:06:08 +07:00
132 changed files with 15447 additions and 555 deletions

No files matched your search

+46 -17
View File
@@ -92,25 +92,21 @@ jobs:
# not part of `build.ps1 check`: it mutates HKCU, and a CI runner is the
# wrong place to be registering machine-wide Vulkan layers.
# -SkipIntegration, and the reason is a MEASURED property of the hard gate
# rather than CI being awkward.
#
# The drain end-to-end tests inject the Overlay into hook-harness, which
# makes the TEST HOST the target's parent — and §S16 puts a target's
# ancestors in the scan set. A .NET host can load
# System.Security.Cryptography.ProtectedData.dll, whose name contains the
# heuristic fragment `protect`, so the guard refuses our own harness with
# SuspiciousUnsigned. Measured here on 2026-08-05; it passes on a dev box
# whose test host happens not to load that assembly, which is why CI is the
# machine that found it.
#
# That is the guard behaving as specified. The defect is §S19(b) — the
# fragment matching a benign, widely-loaded Microsoft assembly — and fixing
# it is a guard change with its own PR, not something to work around here.
# Until then these run locally and CI says out loud that it skipped them.
# NO -SkipIntegration, since 2026-09-06, and the reason it was here is worth
# keeping: the drain end-to-end tests inject the Overlay into hook-harness,
# which makes the TEST HOST the target's parent — §S16 puts ancestors in the
# scan set — and a .NET host loads System.Security.Cryptography.ProtectedData.dll,
# whose name carries the heuristic fragment `protect`. From 2026-08-05 the
# guard refused our own harness here with SuspiciousUnsigned, and CI said out
# loud that it skipped nine cases. §S19(b)'s signer half now verifies that
# module's embedded signature offline and reads O=Microsoft Corporation, so
# the refusal is gone for the reason 19_SAFETY always gave ("fragment AND not
# signed by a known vendor"), and the nine cases are in the merge gate. The
# switch still exists in build.ps1 for a developer who must, and it skips
# loudly; CI is no longer a place it is passed.
- name: Quality gate
shell: pwsh
run: ./build.ps1 check -SkipIntegration
run: ./build.ps1 check
env:
CI: 'true'
@@ -135,6 +131,39 @@ jobs:
# from `git diff`, so a shallow checkout cannot silently produce a short
# list — and the script refuses an EMPTY list rather than reading it as
# "no src/ changes, therefore fine".
# THE SIGNER PROBE'S CI LEG, printed. `ctest fl_signer_probe` runs inside the
# gate and passes on a regular expression, so its ANSWERS never reach this
# log — and §S19(b)'s rows G3/G4/G5 are pre-committed for exactly this
# machine's copy of the blocker. Run here, AFTER the gate, because the gate's
# restore is what fills the NuGet cache the probe searches first. A
# measurement, not a gate: continue-on-error so a surprise (row G6) is
# printed rather than turned into a red that hides it. Reading the row off
# the table is a separate PR (the probe says so itself).
- name: Signer probe (§S19(b) CI leg — measurement, not a gate)
if: always()
continue-on-error: true
shell: pwsh
run: ./build/native/x64-release/tools/fl-probe-signer/fl-probe-signer.exe
# §S29(d)'s pre-committed measurement: can tools/vklayer-blastradius.ps1 run
# HERE? It needs a Vulkan loader and vulkaninfo.exe, which ship with a GPU
# driver's runtime, not with Windows. A census, printed, never a gate: if the
# runner has them, the next PR wires the script as a step (the runner is
# disposable, so registering an implicit layer under HKCU is acceptable
# here where it is not on a dev box); if it does not, (d) is deferred on a
# measured rationale rather than an assumed one.
- name: Vulkan runtime census (§S29(d) — measurement, not a gate)
if: always()
continue-on-error: true
shell: pwsh
run: |
foreach ($f in 'C:\Windows\System32\vulkan-1.dll', 'C:\Windows\System32\vulkaninfo.exe') {
Write-Host ("{0}: {1}" -f $f, (Test-Path $f))
}
$cmd = Get-Command vulkaninfo.exe -ErrorAction SilentlyContinue
Write-Host ("vulkaninfo.exe on PATH: {0}" -f ($(if ($cmd) { $cmd.Source } else { 'no' })))
Write-Host ("HKLM:\SOFTWARE\Khronos\Vulkan\Drivers present: {0}" -f (Test-Path 'HKLM:\SOFTWARE\Khronos\Vulkan\Drivers'))
- name: Changelog
if: github.event_name == 'pull_request'
shell: pwsh
+339 -2
View File
@@ -19,6 +19,333 @@ GitHub release body, so a missing section will mean an empty release note.
### Added
- **P1 item 3 — the Vulkan layer intercepts `vkQueuePresentKHR` (2026-09-06; `20_OPEN_QUESTIONS` §S2 ✅).**
In a process both gates admitted, the layer creates the same ring the Overlay would (`fl_shm_host.h`,
now the one home of the DACL / name / handshake for both capture sides; one ring per process, first
creator owns it) at the first `vkCreateDevice`, writes one record per present (`api` = Vulkan, output
size from `vkCreateSwapchainKHR`'s `imageExtent`, no `PRESENT_ARGS` because the call has none), and
forwards everything — including when the ring is not its own, which the first fixture run proved
necessary. §S2 part three lands with it: `unhookRequested` and the 07_IPC tick deadline both stop the
layer on the present path (passthrough with the reason on the mapping), proven by a fake loader chain
(ctest `fl_vklayer`) and a 1.5 s test-only flavour of the DLL (`fl_vklayer_supervision`). The harness
gains `--vulkan --hold-presenting N` (real loader via `LoadLibraryW`, hidden window, exit 77 = cannot
run here) and ctest `fl_vklayer_real` drives it through the real loader with `VK_ADD_IMPLICIT_LAYER_PATH`
— measured honoured by loader 1.4.357 with no registry — skipping on CI. Launch mode classifies a
Vulkan-only target as the layer's (`TargetIsVulkanLayered` = 26: full guard, nothing injected, attach to
the layer's ring) and the CaptureHost hands the launched process the layer's environment
(`VkLayerLaunchEnvironment`: manifest, enable variable, enable-list line for the session).
- **P1 item 2 — launch mode, built as "inject late" (2026-09-06; `20_OPEN_QUESTIONS` §S1 ◐, §S13(c) ✅).**
The guard gains `FlGuardedInjectWhenReady(pid, dll, timeoutMs)`: it polls the launched target through
the module seam — matching no blocklist — until a presentation runtime is mapped, then runs every
check and injects exactly as `FlGuardedInject` does; a target that exits first or maps no runtime in
the budget answers the new `LaunchTargetExited` / `LaunchNoPresentationRuntime` with nothing injected
(ctest `fl_guard` `[launch]`, five cases incl. the real seam against `hook-harness`). The CaptureHost
gains `launch --exe <path> [--args "…"] [--seconds n]` (`ProcessLauncher`: handle held from birth,
`FRAMELEDGER_ENABLE_VK_LAYER=1`; the host never terminates what it launched), routed through the same
gate by `HookRequest.WaitForPresentationRuntimeMs`, with `IAntiCheatGuard.GuardedInjectWhenReadyAsync`
as the port's fourth method. The Overlay publishes `FlWriterState.dxgiPresentsBeforeHook` @60 — DXGI's
count of presents before the first hooked one, the early-init cost §S1 deferred on — from the last
reserved word (no layout bump; the writer state now has no slack), and the report prints it beside the
measured wait. `04_CAPTURE` §Launch mode carries the shape and why it is not `CREATE_SUSPENDED`.
- **P1 item 1 — the `LoadLibrary` detour, both jobs (2026-09-06).** The Overlay patches
`kernelbase.dll!LoadLibraryExW` after its present hooks (`17_HOOK_ENGINE` §DLL entry step 3): a module
the hook inventory or runtime census names **wakes the watchdog** through an auto-reset event, so the
lazy installers run within milliseconds of the module instead of on the next 1 Hz tick (94 ms measured
against a 500 ms bound); a module matching the compiled anti-cheat floor's MODULE families **stops the
Overlay from inside** with the new `FL_STATUS_STOPPED_BLOCKLISTED`, on the next present or watchdog
iteration — `20_OPEN_QUESTIONS` §S6 ✅, `19_SAFETY` §During a session's in-process half (exact names
only; fragment and signer stay the host's 30 s scan, so the Disclaimer's window is unchanged). The
detour installs nothing inline (§H2), calls the original first, and skips data-file / resource loads.
Two `FlWriterState` words from `reserved[]` (`loaderSignals` @56, `earlyStopFamily` @58; no layout
bump), `hook-harness --load-after-ms N PATH`, two real-Overlay ctest cases (`[loader]`, `[S6]`), and
the CaptureHost's `loader detour:` / `EARLY STOP` report lines, `SessionEndReason.WriterStoppedBlocklisted`
(exit 5) with the family named from the staged rules file.
- **P0 closed — the closing sweep (owner: "theo bảng", 2026-09-06).** Exit criterion 1 is met with
the quality preset amended to an honest `N/A` by measurement; criterion 2 is met with §S24 counting
zero S-items against it. Three items closed by a gate each: **§S19(c)** — `rules-validate` gains a
third canary proving the schema rejects `action: "allow"` and `signerField: "CN"`, so the policy is
code and the data cannot say otherwise; **§S23-6** — the accuracy blocks are one text,
`legal/ACCURACY.md`, embedded verbatim in `README.md` and `legal/DISCLAIMER.md` §4 and gated by
`tools/accuracy-check.ps1` (self-tested both directions), and rewritten to 2026-09-06 truth (the old
§4 still said frame generation and ray tracing had no hook); **§S29(d)** — `ci.yml` prints a Vulkan
runtime census, and the blast-radius script runs as a CI step the day a runner has a loader, deferred
on that measurement until then. Six items deferred with their rationale written and their phase named:
S6 and S2 part three (P1), S23-3 (P3), S4 signing, S20 feed half and S14's store-id half (P4).
`15_ROADMAP` and `HANDOFF` now say P1 starts.
- **The guard's signer half — the other conjunct of "name fragment AND not signed by a known vendor" —
and the nine integration cases in the merge gate (§S19(b) row G1; owner's bound decision 2026-09-06).**
Since 2026-08-05 the guard refused FrameLedger's own test host on CI because a .NET host loads
`System.Security.Cryptography.ProtectedData.dll` and `protect` is a heuristic fragment, and CI skipped
the drain, pause, drop and capture-host end-to-end cases. `fl-probe-signer`'s three legs (dev box, CI,
the owner's adapters-disabled run) all read the same: the embedded signature verifies offline with
`O=Microsoft Corporation`, ~2–4 ms, no verdict changing without a network. So `Sources` gained
`ModuleSignerOrganisation` — `WinVerifyTrust` under `WTD_REVOKE_NONE | WTD_CACHE_ONLY_URL_RETRIEVAL`,
then the certificate's `O=` — and the module sink trusts a fragment-matching module only when that
organisation is on the rules file's `trustedSigners` AND on the list compiled into the binary
(`IsCompiledTrustedSigner`: the data may narrow, never widen). A trusted module keeps the scan
looking; the target is judged like its ancestors; no signature, an invalid one, an unreadable `O=`, a
null path or seam, a failing seam, one list without the other — all refuse. The catalog half stays
deferred with its rationale. `hook-harness --load` proves both directions against the real seams
(the NuGet blocker allowed; our own unsigned Overlay under a `protect` name refused, by name); nine
fake-seam cases pin the decision. `ci.yml` runs `./build.ps1 check` with no switches; the switch stays
in `build.ps1`, loud. `19_SAFETY`, §S19(b), §S29(a), `13_CI_CD`, `12_BUILD`, `HANDOFF` and the rules
file's own comment carry it.
- **Rung 3 by elimination, and the executable file as the census's second witness (HANDOFF 7b / §H11,
owner's choice 2026-09-06).** `frame generation: Active (technology not identified)` now prints every
exclusion the session can make beside it — not DLSS-G when the NVIDIA driver's FG word reports no feature
created and no HUD-less / UI tag was sent (or "not excluded" when the driver did not answer), no FSR
frame-generation dispatch reached a hooked module, the frame-generation runtime modules the census names
or that none is loaded, and the SDK strings the executable carries — never a vendor named as measured, and
it says a frame generator compiled into the executable would read the same. The capture host scans the
executable FILE on disk once after the session (`ExecutableMarkerScan`: `ffxFsr3`, `ffxFrameInterpolation`,
`xefgSwapChain` and the non-FG strings for the reader; chunked with overlap, hits capped) and prints
`executable markers:`; when a frame-generation-capable string is in the file and no module was loaded, the
Presented qualifier reads *MAY include generated frames* instead of *cannot* — the sentence that was wrong
in the dangerous direction on Rune Factory and Wukong. A marker is never identity. Intel's licence was
re-checked the same day and is unchanged; XeSS-FG runs on non-Intel GPUs, so an XeFG session measures this.
- **The super-resolution identity from the NVIDIA driver, where no hook can see it — the driver-reported
rung (owner decision 2026-09-06).** Three NGX-direct titles printed `upscaler: N/A` on every capture
while the driver's per-process NGX word (`NvAPI_NGX_GetNGXOverrideState`, R570+, MIT NVAPI) reads
`CREATED | EVALUATE` for them — measured 2026-09-06 without an NVIDIA-app override. The capture host now
spawns `fl-probe-nvapi --ngx-state <pid>` beside every module snapshot (the probe gained one machine line,
`NGXSTATE status=… sr=0x… …`, and is staged beside the host), merges the readings (`NgxDriverState`: the
last answered word is the state, a change between readings is printed), prints `NVIDIA driver NGX state:`
in the runtime block, and the `upscaler:` line reads `Dlss (driver-reported: … not counted by this hook)`
when no hook named one. Identity only, each limit measured: no quality or preset (override fields), no
ratio (`scalingRatio` is 0 even under an override), no frame-generation multiplier (`FG_MODE` /
`FG_MULTI_FRAME` stay clear at ×4). **The FG word follows DLSS-G too, corrected on the first run's own
readings:** `CREATED | EVALUATE` on every ×4 session, changing between readings as the feature came up, so
it is printed beside `frame generation:` as agreement or a printed disagreement, and promoted to
`DlssG (driver-reported …)` only where the count is active and no tag named the technology — the count is
never the driver's. Owner's run (§H5 rows N1–N4): the negative held (`CREATED` clear with upscaling off),
four NGX-direct titles now print `Dlss (driver-reported …)`, two hooked titles print agreement, and an
FSR + DLSS-G session read `SR 0x205` (created, not evaluated) and correctly claimed nothing. Beside a hook's `Dlss` the driver's word prints as agreement or as a
disagreement printed rather than resolved; beside an `N/A` with the bit clear it prints the driver's
negative. `20_OPEN_QUESTIONS` §H5 pre-commits rows N1–N4, and N3 — DLSS switched off — withdraws the rung
if the bit stays set. `03_METRICS` §Upscaling, `05_DETECTION`, `18_GPU_VENDOR_APIS` carry it.
### Changed
- **The FG `N/A` and the upscaler `N/A` carry their witnesses.** Hell Is Us at XeSS + XeSS-FG (2026-09-06):
no Streamline token on that plugin at XeSS, so nothing counted, and the report printed a bare *N/A (a hook
ran …)* while the driver's FG word, the tags, the ffx census, the module census and the executable's own
strings all had something to say. The N/A now prints the same exclusion clauses as rung 3 (*what this
session can still say: not DLSS-G (…); …; the frame-generation runtime(s) loaded: …; the executable itself
carries xefgSwapChain*), and the upscaler N/A says *libxess.dll is loaded, and XeSS cannot be hooked or
declared under Intel's licence … by policy, not by ignorance* — HANDOFF 7c item 4's string change. Rune
Factory at FSR + FSR FG printed the pre-committed 7b line verbatim on the same run.
- **A counted session whose factor was refused no longer reads "no evaluation was observed".** DL:TB at FSR
upscaling + DLSS Frame Generation (2026-09-06): 4,415 tokens, 8,174 DXGI-counted presents, `DlssG` from
the tags, factor refused because bucket 8 of 8 read 1.96 against 2.85 — and the Presented qualifier said
a runtime was loaded and nothing was seen. It now says frame generation was counted and its factor
refused, that DXGI counted presents this hook never saw so the Displayed rate is above the printed
number, and that the number is neither Native nor Displayed.
- **The withheld `none` is narrowed to sessions where DXGI's counter was not read (§H5 Leg 0 landed).**
The owner's morning run on the DXGI-counted build printed the rule-6 trio on Dying Light: The Beast
(`Native 70.52 -> Displayed 282.08 (x4 FG)`, 12,387 presents DXGI-counted, `DlssG`) and then ran the
title twice with frame generation OFF: census unchanged (`sl.dlss_g.dll` is a startup-time load),
presents = tokens, `unseen=0` over thousands of samples, and the report withheld `none` exactly as the
gate's cost paragraph pre-committed. The counter is the discriminator the gate lacked — on that shape
the pacer's presents are DXGI presents on the hooked chain — so a counted `none` beside a READ counter
with zero unseen now prints as `none`, with *"DXGI's own present counter agrees: 0 unseen over N hooked
present(s)"* on the line; it is withheld only when the counter was not read, with the reason saying so.
A writer state that counted unseen presents the records do not carry is refused as a contradiction.
On every other title the counter is printed beside `none` as a second witness. CLAUDE.md rule 6 carries
the amendment; three cases changed sides and four are new.
### Added
- **Displayed FPS counted by DXGI where the hook cannot count it — the 2.8.0 pacer's presents.** The
owner's run on the DXGI counter landed `20_OPEN_QUESTIONS` §H5 row P1-DXGI twice: Dying Light: The
Beast at DLSS Frame Generation ×4 on Streamline 2.8.0 reads 2.90 and 2.95 presents per hooked present
that DXGI counted on the same chain and the inline patches never saw, while Streamline 2.7.3 (Hell Is
Us, ×3.86) and 2.10.3 (the Onimusha: Way of the Sword demo, ×3.67) read 0.00 — their generated frames
come through the patched bodies. So the record now carries `dxgiUnseen` (@52, from the reserved word,
under `FL_MEASURED_DXGI_PRESENTS`, no layout bump; mirror and `fl-layout-dump` follow), and the
consumer's window counts `Displayed = hooked + Σ dxgiUnseen` — in the rule-6 trio, in `presents/batch`
and in the uniformity buckets, never in a frame-time distribution — printing *"Displayed is
DXGI-COUNTED"* on its own line whenever the sum is above zero, because that number is a count DXGI
made rather than this hook. `none` withdraws on that title by count; a saturated byte is refused like
a saturated `fgEvaluations`; a byte under a clear bit is an honesty violation. A present the hook SAW and
declined — a paused session — is not an unseen present: every declined present bumps an epoch that
invalidates the chain's last reading, which the paused-session integration case caught (the first record
after a resume claimed the whole pause, 0x55, before the guard). On every other title
the window is byte-identical (five cases pin it; the injected `[fg]` case checks the byte is claimed
and zero on the harness). `03_METRICS` §Displayed may be DXGI-COUNTED carries the rule.
- **DXGI's own present counter against the hook's, in the writer state and the report.** On the one shape
where `none` is withheld (Streamline ≥ 2.8 with `sl.dlss_g.dll` loaded, Dying Light: The Beast), the
open question was whether the closed pacer's generated presents reach DXGI through a body the inline
patches miss or are displayed below DXGI. The Overlay now reads `IDXGISwapChain::GetLastPresentCount`
on every hooked present of the chain it just saw (rule 4: the same object `GetDesc` is already read
from) and publishes `dxgiPresentSamples` and `dxgiPresentsUnseen` (`FlWriterState @48/@52`, from
`reserved[]`, no layout bump; mirror, `fl-layout-dump` and the offset asserts updated). The report prints
`DXGI present counter: unseen=M over samples=N (r unseen per hooked present)` with the reading, and the
withheld qualifier says which side of DXGI the generated presents fall on. `20_OPEN_QUESTIONS` §H5
carries the rows written before the run: r ≈ 3 at ×4 means the generated presents ARE DXGI presents
and the next PR labels a DXGI-counted Displayed rate; r ≈ 0 means below DXGI and only the kernel and
vendor reads remain. The harness's presents are the negative control (`fl_guard` `[fg]`: zero unseen);
the positive cannot be fixtured. `hook-harness --probe-frames` now prints the call's cost.
- **A stall diagnostic in the report, placed against FrameLedger's own touches on the target.** The
owner saw Cyberpunk 2077 fall to 1 FPS for about a second under capture (2026-09-05) and the report
could say nothing about whose it was. The capture host now records the QPC moment of every guard scan
and module snapshot (`CaptureResult.TouchQpc`, the records' own clock), and `StallReport` prints the
three longest present-to-present intervals with their session time and the nearest host touch: a
touch inside or within 1 s names FrameLedger a SUSPECT and asks for a longer run on the 30 s cadence;
a far one says *not ours*. It counts intervals at or over 100 ms and calls itself a diagnostic — it is
not `03_METRICS`' stutter, which P2's calculators own. Four cases pin the placement.
- **DLSS Frame Generation is NAMED, from the tags the title already sends.** On every NVIDIA title measured
the count was right and the technology unnamed — `Active (technology not identified)` on Cyberpunk at
MFG ×3 and on the three UE titles at ×4 — because `kFeatureDLSS_G` is never evaluated through the export
the identity hook owns. Streamline's DLSS-G programming guide §5.0 requires a title running frame
generation to tag the HUD-less colour and UI buffers every frame through `slSetTag` /
`slSetTagForFrame` / `slEvaluateFeature`'s inputs — the three tag routes this build already hooks and
read one tag type from. The detours now record every tag's TYPE (rule 4: the same argument), a
HUD-less or UI tag drained by a present marks it `FL_FG_DLSS_G`, and `FlWriterState.slTagCensus` (took
`reserved[0]`, no layout bump) says which types arrived on which route for the session; the report
prints it as `Streamline tag census: global=[…] frame=[…] local=[…]`. **Identity only:** the consumer's
rule is the count decides `none`, identity decides the name — an active count beside the mark prints
`frame generation: DlssG`; a counted 1.0 beside it prints `none` with the inputs noted; the withheld
shape (§H5) keeps its N/A and says the title is feeding frame generation. Two injected cases send the
DLSS-G list through each global export with no `kFeatureDLSS_G` evaluation and assert the mark on every
record and the census on the right route; the existing tag cases assert its absence. `slDLSSGGetState`
— the API the guide names for the presented count — is refused and the reason recorded in `03_METRICS`:
the call resets the plugin's counter a title may read for its own FPS display, and the header marks it
not thread safe.
### Changed
- **The tag route is measured on real titles** (docs): the owner's evening run on #121 read `frame generation:
DlssG` on Hell Is Us, Expedition 33, Wukong, Rune Factory and Cyberpunk — every Streamline title tags the
DLSS-G inputs through a route this build hooks — and Dying Light: The Beast's census shows the title tags its
scaling input through `slSetTagForFrame` with no size, which closes HANDOFF 7a's last question without a
layout bump. `spike-notes` §9 carries the table; §H5 records the pre-commitment as landed.
### Fixed
- **`render -> output` prints under frame generation.** `UpscaleExtent` keyed its window on the
params bit, which the writer publishes only on the present that drained a dispatch or tag — one
in N under frame generation — so `ClaimedSuffixStart`'s clean-suffix rule found no window and every
FG-on capture since 2026-08-16 read `N/A` two lines under its own raw `render WxH` block
(Cyberpunk at FSR 3 + FG, 2026-09-05, was the one that made it visible; the earlier "not computed
yet" wording had hidden it). The window is now the identity suffix, which is per-record once the
family is live, and every record inside it carrying both sizes counts. Two cases pin the FG shape
and the refused intermittent-identity shape; the Cyberpunk FSR 3 consumer case now asserts the line.
### Added
- **`fl-probe-nvapi --ngx-state <pid>`: what the NVIDIA driver says about one process's DLSS
features.** The owner's eleven-capture run on 2026-09-05 (`spike-notes` §9) left one NVIDIA gap in
one sentence — the count is right on every title and the identity is what this build cannot say:
DLSS on the four NGX-direct UE titles, DLSS-G everywhere, and the hidden presents on Streamline
2.8. The NGX SDK is licence-blocked; `NvAPI_NGX_GetNGXOverrideState` (NVAPI, MIT, vendored, R570+)
takes a process id and returns the driver's own feedback bits for SR / RR / FG plus the scaling
ratio, quality mode and frame-generation count, out of process. The probe prints the raw words and
every decoded bit so the owner's run against a running title measures whether the bits are
populated without an NVIDIA-app override, before any report line is built on it. §H5 carries the
decision that answer opens (a *driver-reported* rung in `03_METRICS`, the owner's call).
- **The FSR 3.0 host route: a fifth AMD target, `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale`.**
Cyberpunk 2077 at FSR 3 upscales through the FSR 3.0 **host** DLL's named export while its frame
generation goes through the 1.1.x monolith's `ffxDispatch`, so the leaf-only build printed
`upscaler: N/A` beside `FsrFg` (§H11, 2026-09-04). The host is hooked at its own export with its own
trampoline and latch, keyed by module in the installer, under the same family and publish point as
the four ffx-api rows (`PublishFfxFamilyIfWhole` waits for a loaded host as it waits for a loaded
leaf); its UPSCALE feeds the same drain word — identity `FSR3` as a fact, `renderSize` as the
extent, the count when neither Streamline nor a PREPARE has spoken. Rule 4: `renderSize` of the
descriptor the title passed and nothing else; the offset is pinned to a literal (1256).
`ffxFsr3DispatchFrameGeneration` is deliberately not a row, with the reversal condition
pre-committed in §H11. **The headers are vendored from tag `fsr3-v3.0.4`, not the `v1.1.4` three
documents named**: the shipped module's twelve `ffxFsr3*` exports match 3.0.4 exactly, 1.1.4
declares fifteen and appends fields after `renderSize`, and at 3.0.4 `ffx_types.h` reaches no
`<mutex>` at all (ten files, no `ffx_message.h`; `src/native/third_party/fidelityfx-fsr3/`, root
`LICENSE.txt` MIT verbatim, `license-check.ps1` §2e per file, blob shas checked against upstream).
The two FidelityFX trees share one struct name, so the 3.0.4 header is included inside a
namespace. Fixtures: the `ffx_fsr3_x64.dll` stub (Pass C's second positive control), harness
topologies `fsr3host` / `fsr3host+mono`, an `[ffx]` injected case at K = 1 (the row's double-count
control) and K ∈ {1, 4} beside the monolith, and a consumer case for Cyberpunk's shape. Owed: the
owner's acceptance run, rows B1–B4 in §H11.
- **The report names the loaded vendor runtimes with their FILE versions, and a counted `none` is
WITHHELD on the one shape measured to be wrong.** Dying Light: The Beast (Streamline 2.8.0) read
`presents = tokens` five times with DLSS Frame Generation ON, and the owner's reading on 2026-09-05
settled which way to read it: the title runs at DLSS ×4, the frames this hook records are the
native ones, and the generated presents never reach the `Present` bodies the Overlay patches
(`20_OPEN_QUESTIONS` §H5 case 3, realised). The census could not have said so — it records module
NAMES, and Cyberpunk 2077 on 2.7.1 reads ×3.99 through the same hook — so the capture host now takes
an out-of-process module snapshot beside every guard scan (`Process.Modules` + the file's version
resource, the same documented module list the guard already enumerates; no game memory, no layout
change, nothing on the present path) and prints one `module:` line per census-named module with
version and path. `MeasuredFacts` withholds `none` when `sl.dlss_g.dll` — the Streamline plugin that
would be doing the presenting, NOT `nvngx_dlssg.dll`, which every validated `none` also has loaded —
is in the census beside an interposer at or above 2.8.0 (or one whose version could not be read), and
the report falls through to `Presented FPS` with a qualifier that says the number counts APPLICATION
frames and that the Displayed rate is unknown. Every validated `none` (Cyberpunk off / ×3 / ×4,
Expedition 33 and Lies of P with frame generation off) is byte-identical, and eight cases pin that.
The gate is interim: §H5 pre-commits the owner's session (DL:TB FG off / FG ×4, Cyberpunk MFG ×4,
PresentMon elevated beside each) and the row on which it is withdrawn.
- **A whole-resource tag now yields the size the tagged `sl::Resource` declares.** Streamline
documents a zero `extent` as "use the entire resource"; a title tagging that way stated the
render size nowhere the Overlay read, and Dying Light: The Beast (SL 2.8.0) still published no
extent on the `slSetTagForFrame` build with both tag rows live. `TagSize` in `fl_sl_inputs.h`
reads the extent first and, when it is zero, the Resource's own `width/height` — GUID-checked,
from the argument the hooked API received, on the local walk and both global-tag detours alike,
so the three routes cannot disagree about what a tag says. A Resource declaring no size is
still the honest unknown. Unit cases cover the shape, precedence of a non-zero extent over the
Resource, a Resource that fails the GUID check and a half-declared size; the harness tags in
that shape under `--sl-tag-whole-resource` and an injected case asserts the exact size arrives
on every record through the 2.8 export.
### Changed
- **7a on Dying Light: The Beast closes as measured `N/A`** (docs): the 00:53 capture on the
whole-resource build still carried no render size on either global-tag route, so the quality
byte and the render size are `N/A` on this title, honestly, and the derived-label decision
applies to the titles that print the line. The DLSS-FG-on `presents = tokens` result is now
five for five; by owner decision it is handled in its own session and PR (`HANDOFF` 7a, §H5).
- **`20_OPEN_QUESTIONS` §H5 has a candidate title for case 3.** Dying Light: The Beast at DLSS
with DLSS Frame Generation on read `presents = tokens` on four captures (the same title with
FSR FG read ×2; Cyberpunk on Streamline 2.7.1 read ×3.99), so the report printed `frame
generation: none` on a generating title. The two readings the record cannot separate and the
discriminator — the owner's counter — are pre-committed there.
- **A row for `sl.interposer.dll!slSetTagForFrame`, Streamline 2.8's frame-based tag entry
point.** Dying Light: The Beast ships Streamline 2.8.0, which deprecates `slSetTag` in favour of
`slSetTagForFrame` (the frame token first, then the same tag list); the title published `Dlss`
identity on every batch across three captures and the params bit on none, because the only
params row hooked the deprecated export. The new detour hands the list to the same tag walk, has
its own trampoline, and is selected by SYMBOL
through a constant the inventory header binds to its row with a `static_assert` — Pass B forbids
the literal anywhere else. **The params family is published when whole**, once every tag export
the loaded interposer has is patched — a 2.7 interposer is whole with `slSetTag` alone, a 2.8 one
needs both — because the first cut published it on the first row and the frame-based fixture
measured 38 of 41 records claiming params, the ffx leaves' install-window defect from #110
again. The stub exports it, the harness tags through it under `--sl-tag-for-frame`, and a Catch2
case asserts the exact tagged extent arrives on every record with `slSetTag` never called.
- **`tools/vendor-exports.ps1` unions exports across every copy of a module name** and lists every
distinct version seen, instead of recording the first copy the walk reached. With `sl.interposer.dll`
installed as 2.7.1 and 2.8.0 side by side, whether the oracle contained `slSetTagForFrame`
depended on directory order; `docs/vendor-exports.json` is regenerated (ten interposer copies,
eight versions from 1.5.6 to 2.10.3).
- **The report's `render -> output` line is computed, not "not computed yet".** Every real-title
run since 2026-08-15 printed the raw sizes two lines above an N/A. `UpscaleExtent` takes the
MODAL (render, output) tuple over the records that claim both `FL_MEASURED_UPSCALER_PARAMS` and
`FL_MEASURED_OUTPUT_RES`, and the line prints the two measured sizes, `03_METRICS` §Upscaling's
`sqrt((outW×outH)/(renW×renH))`, the reciprocal as a render-scale percentage, the record counts,
and a **SETTINGS MOVED** flag when the window held more than one tuple — modal rather than mean,
because averaging across a settings change is the classic way a benchmark number stops meaning
anything. Cyberpunk's 1485×835 at 2560×1440 reads `1.72x (58% render scale)`. **No preset name is
derived from it**: whether a label such as "≈ Balanced" may appear beside a measured field is
HANDOFF item 7a's owner decision, and the quality byte stays what the writer measured.
- **The SDK 2.x loader is the fourth AMD row, because three loader-shipping titles read silent
behind the leaf-only build.** The owner's run on #110 (thirteen captures, nine titles, one launch
each) landed rows A1–A3 exactly as pre-committed — Lies of P `Fsr3` / `FsrFg` / `118.98 → 238.02
@@ -41,8 +368,16 @@ GitHub release body, so a missing section will mean an empty release note.
3.0 route; and **Rune Factory: Guardians of Azuma is HANDOFF 7b's statically linked title** — the
monolith ships beside it and is never loaded, yet the Streamline token count still read
`59.99 → 119.95 (×2 FG)`, so the ceiling for such a title is the trio with the vendor missing, not
Presented FPS alone. Owed: the three loader titles against §H11 row R6. `20_OPEN_QUESTIONS` §H11
carries the run table; `HANDOFF` 7b/7c and `spike-notes` §9 carry the corrections.
Presented FPS alone. **Row R6 ran the same night on this build:** Dying Light: The Beast at FSR +
FSR FG printed `FSR (3.1 or 4 …)` / `FsrFg` / `70.49 → 140.9 (×2 FG)` with `frames/upscale-drained`
1.01, and KCD2 at FSR the identity with `none` at 1.00 — the loader row carries both, once, which
is the K = 1 control confirmed on a real title. Wukong at FSR with FG off read silent at the
monolith and the loader alike with the monolith loaded, and offers no FSR frame generation at
all: FSR upscaling compiled into its UE plugin (Rune Factory's shape), the monolith shipped and
loaded for nothing this hook sees — the second static title, and nothing more is owed on AMD
identity beyond the FSR 3.0 host route.
`20_OPEN_QUESTIONS` §H11 carries the run tables; `HANDOFF` 7b/7c and `spike-notes` §9 carry the
corrections.
- **AMD identity is measured through the ffx-api leaves, and the first non-NVIDIA vendor
reaches the record.** HANDOFF item 7c. Lies of P at FSR 3.1 + frame generation printed
@@ -260,6 +595,8 @@ GitHub release body, so a missing section will mean an empty release note.
### Fixed
- **A candidate with no main module yet is counted as unreadable, not dropped as absent.** `TargetResolverTests.OneInstanceResolves` went red on the hosted runner twice in one hour on 2026-09-04 with `TargetNotRunning` about a process the test had just shown was enumerable: a freshly started process can be in the snapshot before its image is mapped, `Process.MainModule` is then null, and the resolver skipped it without counting it — narrowing the set exactly the way its own comment says "could not look" must not. It is now counted like a process we lack the rights to read (so the answer is `TargetAmbiguous`, never a false `TargetNotRunning`), and the test's "visible" wait means readable, not merely enumerated.
- **Two review checklists were boxes that could not fail**, in `19_SAFETY` §Review checklist and in
the pull-request template: *"Is there a Tier-2 degradation path if the hook is unavailable?"*
Under a two-rung ladder the answer is always yes. Replaced with something falsifiable — does the
+4
View File
@@ -18,6 +18,10 @@ A C++ DLL (`FrameLedger.Overlay.dll`) is injected into games the user explicitly
6. **FPS display rule (product requirement):** wherever FPS is shown and Frame Generation is active, show *Native FPS*, *Displayed FPS*, and the FG factor together (`62 → 118 FPS (×1.9 FG)`). Never a single inflated number. See `docs/03_METRICS.md`.
> **Amended 2026-09-03 (owner decision).** When frame generation is *not measured* — `FL_MEASURED_FG` clear, which is every title on today's writer — the one number that may stand alone is **Presented FPS** (`presents / D`), with a mandatory qualifier from the **runtime census** (`FlWriterState.runtimeCensus`): "no frame-generation runtime was loaded, so this cannot include in-process generated frames" or "a frame-generation runtime is loaded and nothing was observed — this MAY include generated frames". The word "Native" never appears alone. **The census never produces `none`**: a statically linked FSR has no module to see, and a census-`none` there would be exactly the inflated number this rule forbids.
>
> **Amended 2026-09-05.** A counted `none` (`presents = application frames`) is **withheld** — Presented FPS with a third qualifier, "this number counts application frames; the Displayed rate is unknown" — on the one shape measured to produce a false `none`: Streamline ≥ 2.8.0 with `sl.dlss_g.dll` loaded (Dying Light: The Beast, five captures, DLSS FG ×4 per the owner). `docs/03_METRICS.md` §Frame Generation carries the key and why it is the Streamline plugin rather than `nvngx_dlssg.dll`; `20_OPEN_QUESTIONS` §H5 carries the session that keeps or withdraws it.
>
> **Amended 2026-09-06 (Leg 0 landed): narrowed, not withdrawn.** `sl.dlss_g.dll` is a startup-time load on that title (frame generation off, census unchanged, twice), and the same morning's ×4 capture measured the discriminator the gate lacked: the 2.8.0 pacer's generated presents are DXGI presents on the hooked chain (§H5 row P1-DXGI), counted through `dxgiUnseen` into `Native 70.52 → Displayed 282.08 (×4 FG)`. So a counted `none` beside a READ `IDXGISwapChain::GetLastPresentCount` with zero unseen is `none`, printed with DXGI's agreement; it is withheld only when the counter was not read.
7. **RT / PT / RR are tri-state** (`Yes` / `No` / `N/A`) with manual override. They are now *measured*, not guessed — but where measurement is genuinely impossible, the honest answer is still `N/A`. Never fabricate `Yes`.
> **Amended 2026-08-20 with the PR that wrote the hooks, per the owner ruling of 2026-08-14.** This rule named *"inline RayQuery without DXIL scan"* as one of the impossible cases, and that conflated two questions. **Whether rays are being traced is measurable** — `BuildRaytracingAccelerationStructure` is called by RayQuery titles and by `DispatchRays` titles alike, which is why both hooks exist and why the `No` branch requires the AS-build hook to have been *installed*. What needs a DXIL scan is **classifying the technique as RayQuery**, and that stays `N/A`. So the impossible cases are: naming the technique, and path-tracing classification, which has no API-level signature at all (`03_METRICS` §RT/PT/RR — a confidence score that may only ever *suggest*).
+37 -21
View File
@@ -4,28 +4,44 @@
> No telemetry. No accounts. All data stays on your machine.
> ⚠ **Accuracy note — 2026-08-05. This README describes the finished product; the software
> is pre-alpha and most of what follows is not built yet.** Added because every other
> user-facing document here carries such a note and this one — the first thing anyone
> reads — carried none, while `legal/DISCLAIMER.md` had already been through two rounds of
> exactly this correction.
<!-- accuracy-block:begin -->
> ⚠ **What FrameLedger actually measures today — 2026-09-06.** The software is pre-alpha: the
> measurement path exists as an injected Direct3D 11/12 component and an **unshipped** capture
> host that drives the guard loop and prints a report; there is no Agent loop, no storage, no
> charts, no library import, no UI and no installer yet.
>
> **What actually works today:** frame boundaries, frame times and output resolution, from
> a Direct3D 11/12 present hook, written into shared memory and read back by the Agent's
> ring reader. Plus, for titles that go through NVIDIA Streamline, **which upscaler is
> executing** and **whether Ray Reconstruction is running with it** — identity only, not the
> quality preset and not the render resolution. The anti-cheat guard runs all of its
> pre-injection checks and refuses.
> - **Frame times and output resolution:** measured, from the present hook, for injected D3D11/12
> titles, and for Vulkan titles **launched through FrameLedger** (the layer intercepts
> `vkQueuePresentKHR` since 2026-09-06; a Vulkan title already running when FrameLedger attaches is
> not observed). OpenGL/D3D9 intercept nothing yet.
> - **Which upscaler is running:** measured from the API the game calls — DLSS (with Ray
> Reconstruction Yes/No) through NVIDIA Streamline; FSR 2/3.x/4 through AMD's shipped DLLs; DLSS on
> titles that bypass Streamline is reported from the NVIDIA driver's own per-process record,
> labelled *driver-reported*. Intel XeSS is **not** read (its SDK licence forbids it) and reads
> `N/A` by policy; an upscaler compiled into the game executable reads `N/A`.
> - **Quality preset:** `N/A` everywhere. No route this software may use exposes it.
> - **Render → output resolution:** measured where the vendor's own call carries the size (AMD
> dispatches, some Streamline titles); `N/A` where it does not (NVIDIA-direct titles, most
> Direct3D 12 Streamline titles).
> - **Frame generation:** the Displayed rate is counted from presents — including, on one title,
> presents DXGI counted that the hook could not — and the Native rate from the vendor's own
> per-frame calls where the title makes them. Identity: DLSS-G and FSR-FG named from the calls
> the game makes; anything else (XeSS-FG, a generator compiled into the game) is reported *by
> elimination* and never named. Where no per-frame call exists the Native rate is `N/A`.
> - **Ray tracing:** Yes/No measured from DXR dispatches and acceleration-structure builds on
> Direct3D 12; the technique and path tracing are `N/A`.
> - **Not measured at all:** video memory, shader-compilation stutter, PC latency (Reflex), HDR.
> - **Safety:** every pre-injection check runs before injection, including the signed-by-a-known-
> vendor half of the suspicious-module rule (since 2026-09-06), and the unshipped capture host
> re-runs them every 30 s and stops the capture on refusal. No shipped component drives that loop
> yet. There is no override anywhere.
>
> **What does not yet exist**, and is written above in the present tense: every bullet
> under *What makes it different* except output resolution and upscaler identity — no
> quality preset, render resolution, frame generation, ray tracing, VRAM, shader-stutter or
> Reflex hook has been written. The capture side says so in its own data rather than defaulting to "none"
> (`docs/03_METRICS.md`, CLAUDE.md rules 6 and 7). There is also no storage, no charts, no
> library import, no UI and no installer.
>
> The two rows that describe **safety behaviour** are qualified where they sit, rather than
> here, because that is where a reader checking their own risk will look.
> Where a value is not measured it reads `N/A`; the software never substitutes an estimate.
<!-- accuracy-block:end -->
> The rows below that describe **safety behaviour** are qualified where they sit, rather than
> here, because that is where a reader checking their own risk will look. What this README
> describes beyond the block above is the finished product; the block is what exists.
## What makes it different
@@ -52,7 +68,7 @@ FrameLedger is built to keep that risk small and to be honest about it:
| Safeguard | |
|---|---|
| **Off by default** | Injection is disabled for every game until you enable it individually, after a consent prompt |
| **Hard refusal** | Known anti-cheat/anti-tamper components are detected before injection and every 30 s during a session. Detected ⇒ FrameLedger refuses, or stops capturing at the next scan — so up to 30 s can pass before it reacts to anti-cheat that loads mid-session. For Direct3D/OpenGL that means hooks are removed; for Vulkan it means the layer goes passthrough, because a layer cannot leave the loader chain of a running game. **There is no override — not in settings, not in a config file, not on the command line**<br><br>⚠ **Half of this is built.** The *pre-injection* refusal is real and runs every documented check. The **in-session re-scan does not run at all**: the component inside the game removes its hooks within one frame of being told to, and within 65 s if it stops hearing from the scanner — but nothing yet drives the scanner during a session, so nothing ever tells it. `legal/DISCLAIMER.md` §2 states this in full. The Vulkan layer additionally intercepts nothing yet, so there is no Vulkan capture to stop. |
| **Hard refusal** | Known anti-cheat/anti-tamper components are detected before injection and every 30 s during a session. Detected ⇒ FrameLedger refuses, or stops capturing at the next scan — so up to 30 s can pass before it reacts to anti-cheat that loads mid-session. For Direct3D/OpenGL that means hooks are removed; for Vulkan it means the layer goes passthrough, because a layer cannot leave the loader chain of a running game. **There is no override — not in settings, not in a config file, not on the command line**<br><br>⚠ **Half of this is built.** The *pre-injection* refusal is real and runs every documented check. The **in-session re-scan does not run at all**: the component inside the game removes its hooks within one frame of being told to, and within 65 s if it stops hearing from the scanner — but nothing yet drives the scanner during a session, so nothing ever tells it. `legal/DISCLAIMER.md` §2 states this in full. For a Vulkan title the stop is the layer's own: it checks the scanner's counter on every present and goes passthrough within one present of the stop flag, or after 65 s without a scan — a title that has stopped presenting is not stopped by that deadline, and presents nothing to be observed either. |
| **No evasion, ever** | FrameLedger does not hide, rename, obfuscate, or disguise itself. It keeps its real name, real exports, and version info. It is meant to be plainly visible to any security software that looks. This is an architectural rule, not a setting |
| **Read-only** | It never reads or writes game memory, never modifies game behavior, never touches saves or input, and never changes GPU clocks, fans, or power limits |
| **Always a way out** | FrameLedger refuses rather than pushes through. When the guard finds anti-cheat, or the hook fails, or you have not enabled a game, it **stops** — and records the session anyway: start, end, duration, whatever hardware sensors your machine provides, and the reason there is nothing else. Every measured value reads `N/A`; it never estimates one.<br><br>**The way out is that it does not inject, not that it measures another way.** An earlier version of this row promised a no-injection measurement mode. It was designed around Intel PresentMon, that was dropped on 2026-08-27 after measurement, and no replacement was chosen — so **frame times require hooking**. Said in this row rather than a footnote because the row is in the SAFETY table, and a reader deciding whether to enable a game needs the real alternative, not a comfortable one |
+22 -10
View File
@@ -29,18 +29,18 @@ param(
# Excludes tests traited Category=Integration -- today, the drain end-to-end
# cases, which inject the Overlay into hook-harness.
#
# CI PASSES THIS AND A DEVELOPER MUST NOT. The reason is a MEASURED property of
# the hard gate, not flakiness: §S16 puts the injecting process's ancestors in
# the scan set, so the test host is scanned, and a .NET host can load
# System.Security.Cryptography.ProtectedData.dll -- which contains the
# heuristic fragment `protect`. The guard then refuses our own harness with
# SuspiciousUnsigned. That is the gate working exactly as specified;
# 20_OPEN_QUESTIONS §S19(b) is the defect, and it is a guard change with its
# own PR rather than something to paper over here.
# NOBODY PASSES THIS ANY MORE, and it is kept so that the day someone must, the
# skip is loud. CI passed it from 2026-08-05 to 2026-09-06 for a MEASURED reason:
# §S16 puts the injecting process's ancestors in the scan set, a .NET test host
# loads System.Security.Cryptography.ProtectedData.dll (heuristic fragment
# `protect`), and the guard refused our own harness with SuspiciousUnsigned.
# 20_OPEN_QUESTIONS §S19(b)'s signer half now verifies that module's embedded
# signature offline (O=Microsoft Corporation, on the compiled-in bound), so the
# refusal is gone for the reason the heuristic always stated, and CI runs
# `./build.ps1 check` with no switches — the same command a developer runs.
#
# It skips LOUDLY, because a suite that quietly stops running one class is how
# a gate rots. Whatever CI does, `./build.ps1 check` with no switches runs
# everything.
# a gate rots.
[switch]$SkipIntegration
)
@@ -405,6 +405,18 @@ function Invoke-ProjectGates {
# It found a defect in its own filter on its first run: a whitespace-only path
# is truthy in PowerShell, so the empty-list refusal was unreachable for that
# input.
# §S23-6: the accuracy blocks are one text in legal/ACCURACY.md; a copy that
# drifted is red. Self-test first, both directions, so the gate is seen to work.
Write-Step 'accuracy-check'
$accuracyTool = Join-Path $repo 'tools/accuracy-check.ps1'
if (Test-Path $accuracyTool) {
Invoke-Checked 'accuracy-check (self-test)' { & $accuracyTool -SelfTest }
Invoke-Checked 'accuracy-check' { & $accuracyTool }
}
else {
Skip-Gate 'accuracy-check' 'tools/accuracy-check.ps1 not implemented yet'
}
Write-Step 'changelog-check'
$changelogTool = Join-Path $repo 'tools/changelog-check.ps1'
if (Test-Path $changelogTool) {
+5
View File
@@ -66,6 +66,11 @@ watcher sees tracked exe launch
**Launch mode (preferred when FrameLedger starts the game):** `CreateProcess(CREATE_SUSPENDED)` → guard → inject → `ResumeThread`. This catches swapchain creation and early upscaler init, which attach mode can miss. Attach mode remains for games launched from Steam/GOG directly.
> **Built 2026-09-06 as start → the guard waits for a presentation runtime → the full guard → inject**
> (`FlGuardedInjectWhenReady`, P1 item 2), because a suspended target has loaded nothing for the module
> scan to read (`20_OPEN_QUESTIONS` §S1). What it costs is measured by the session itself:
> `FlWriterState.dxgiPresentsBeforeHook`. `04_CAPTURE` §Launch mode carries the shape.
Guard re-runs every 30 s for the life of the session; anti-cheat appearing late ⇒ clean unhook (`19_SAFETY` §During a session).
## Lifecycle
+125 -3
View File
@@ -77,6 +77,41 @@ This is the metric the rewrite exists for. Resolution ladder, highest confidence
published `presents / tokens` at or below 1.05 over a uniform window (§The source, below).
Never from a hook that merely saw nothing (rung 0), and never from the census.
> ### Displayed may be DXGI-COUNTED — measured 2026-09-05 on Dying Light: The Beast
>
> `F_disp = presents observed by the hook` (§Counting, below) assumed every present reaches the
> `Present` / `Present1` bodies the Overlay inline-patches. On Streamline 2.8.0 with DLSS Frame
> Generation ×4 it does not: the hook timed 4,392 presents while `IDXGISwapChain::GetLastPresentCount`,
> read on the same chain at every hooked present, moved by 17,133 — **2.90 unseen presents per hooked
> one** (2.95 on the second capture) — against **0.00** on Streamline 2.7.3 (Hell Is Us, ×3.86) and
> 2.10.3 (the Onimusha demo, ×3.67), where the generated presents come through the patched bodies. So
> the record carries `dxgiUnseen` (@52, under `FL_MEASURED_DXGI_PRESENTS`) and the consumer's window
> counts
>
> ```
> F_disp = hooked presents + Σ dxgiUnseen (DXGI-COUNTED when the sum is > 0)
> ```
>
> **When the sum is above zero the report says so on its own line — "Displayed is DXGI-COUNTED" —
> because the number is then a count DXGI made, on the hooked chain, of presents this hook never
> timed.** It may stand in the rule-6 trio and in `presents/batch`; it may NOT stand in a frame-time
> distribution, which has no timestamps for those presents. The uniformity buckets take the same
> numerator, so a session whose pacer stopped mid-way refuses exactly as one whose tokens stopped. A
> saturated byte (255) is refused like a saturated `fgEvaluations`, and a present the hook saw and
> declined (a paused session) is not unseen — the resume's first record differences nothing.
>
> **Landed 2026-09-06 (`spike-notes` §9): `Native FPS: 70.52 -> Displayed FPS: 282.08 (x4 FG) over 16516
> present(s)` on Dying Light: The Beast, 12,387 of them DXGI-counted, `frame generation: DlssG`** — the
> rule-6 trio on the title that could not print it. **And the counter decides `none` on that shape.**
> Leg 0 the same morning (frame generation off, twice) read presents = tokens with `unseen=0` over 3,659
> and 4,519 samples, census unchanged (`sl.dlss_g.dll` is a startup-time load), so the withheld gate is
> narrowed rather than withdrawn: a counted `none` beside a READ counter with zero unseen prints as
> `none` with DXGI's agreement on the line; only a session where the counter was not read withholds.
> A writer state that counted unseen presents the records do not carry is a contradiction and is
> refused as neither. `20_OPEN_QUESTIONS` §H5 keeps the
> rows this landed on; which body the 2.8.0 pacer presents through is unlocalised and does not need
> to be for the count.
>
> **RUNG 2 IS CONDITIONAL ON THE VENDOR, measured 2026-08-20, and this list read as
> though it were not.** `--track_frame_type` is a **beta** option in PresentMon 2.5.1
> and its own help says it *"requires application and/or driver instrumentation using
@@ -234,8 +269,42 @@ F_app = Σ fgEvaluations (APPLICATION frames, counted at the
> Streamline batch is an application frame on that title — with a second count rather than an
> oracle.
>
> **And one shape on which the counted `none` is WITHHELD, measured 2026-09-04/05.** Dying Light:
> The Beast ships Streamline **2.8.0**; five captures at DLSS with DLSS Frame Generation ON read
> `presents = tokens` (1.00), and the owner's reading settled it: the title runs at ×4, the frames
> this hook records are the native ones, the generated presents never reach the `Present` bodies
> the Overlay patches (`20_OPEN_QUESTIONS` §H5 case 3). On that shape the count is right about the
> application frames and wrong about the presents, and a `none` computed from it is the affirmative
> negative this document forbids. So the consumer withholds `none` — and prints **Presented FPS** with
> a qualifier saying the number counts *application* frames and the Displayed rate is unknown — when
> `sl.dlss_g.dll` is in the census beside an interposer whose **file version** (read out of process by
> the capture host, never by the hook) is ≥ 2.8.0 or unreadable. **The key is the Streamline plugin,
> not `nvngx_dlssg.dll`:** every validated `none` above has the NGX module loaded and the plugin bit
> clear, so the gate leaves each of them byte-identical. It is interim: §H5 pre-commits the session
> that keeps, narrows or withdraws it.
>
> **What `fgMode` still is.** Identity — `DLSS_G` when a `kFeatureDLSS_G` evaluation drained,
> `UNKNOWN` otherwise — from the evaluate detour, unchanged. A factor ≥ 1.5 with `UNKNOWN`
> `UNKNOWN` otherwise — from the evaluate detour, unchanged. **And since 2026-09-05, `DLSS_G` when the
> present drained a HUD-less or UI tag** (`kBufferTypeHUDLessColor`, `kBufferTypeUIColorAndAlpha`,
> `kBufferTypeUIAlpha`) on any of the three tag routes the Overlay already hooks: Streamline's DLSS-G
> programming guide §5.0 requires a title running frame generation to tag those buffers every frame, and
> nothing else a title evaluates through Streamline that generates frames consumes them. Read off the
> argument of an API already hooked (rule 4), zero new hooks — the identity `kFeatureDLSS_G` evaluations
> were supposed to give and gave on no measured title. **Identity only.** A title may tag the inputs with
> frame generation switched off in its menu, so the consumer's rule is: **the count decides `none`,
> identity decides the name** — an active count beside the mark prints `DlssG`; a counted 1.0 beside it
> prints `none` with the inputs noted; the withheld shape (§H5) keeps its N/A with the tags reported in
> the census line — narrowed 2026-09-06 to sessions where DXGI's counter was not read (§Displayed may be
> DXGI-COUNTED). `FsrFg` keeps precedence over the count, because a drained FRAMEGENERATION dispatch
> is a generated batch. `FlWriterState.slTagCensus` carries which types arrived on which route for the
> session (`fl_shm.h` §slTagCensus).
>
> **Refused, with the reason written:** `slDLSSGGetState`, the API the DLSS-G guide §14.0 names for
> "the actual number of frames presented". Its `numFramesActuallyPresented` is *"the number of frames
> presented since the last `slDLSSGGetState` call"* — the call RESETS the plugin's counter, so a
> measurement tool calling it would corrupt the very number a title reads for its own FPS display; and
> `sl_dlss_g.h` marks it *"NOT thread safe"*. Observing is the whole posture; a query with a side
> effect on the host is not observing. A factor ≥ 1.5 with `UNKNOWN`
> identity is *frame generation active, technology not identified*, which on a UE5 title with
> both Streamline and FidelityFX loaded is the honest answer.
@@ -269,8 +338,13 @@ F_app = Σ fgEvaluations (APPLICATION frames, counted at the
> the first** is 7c's own rule, and this is it.
>
> The acceptance table for the owner's three launches is pre-committed in `20_OPEN_QUESTIONS` §H11.
> What this route does NOT reach: the FSR 3.0 host DLLs (`ffx_fsr3_x64.dll`, named exports, deferred
> to their own PR), statically linked FSR (§Scope decisions), and Intel (closed at the census).
> What this route does NOT reach: statically linked FSR (§Scope decisions) and Intel (closed at the
> census). **The FSR 3.0 host DLL is reached since 2026-09-05** — a fifth AMD target,
> `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale` (Cyberpunk 2077's copy; named export, its own
> descriptor, tag `fsr3-v3.0.4`), whose UPSCALE feeds the same drain word: identity `FSR3` as a
> fact, `renderSize` as the extent, and the count from its upscales when neither Streamline nor a
> PREPARE has ever spoken. On Cyberpunk the count stays Streamline's and `FsrFg` stays the
> monolith's; the host adds the identity the leaf-only build printed as `N/A`.
> **MEASURED 2026-08-15, AND IT CHANGES WHAT THIS SECTION CAN PROMISE.** On the one title
> measured — Cyberpunk 2077, SL 2.7.1 — `slEvaluateFeature(kFeatureDLSS_G)` is **never
@@ -349,6 +423,22 @@ rung identified the mode — only the *identification* comes from the ladder.
**Display rule (product requirement, CLAUDE.md rule 6):** wherever FPS appears and FG is active, render `"{native} → {displayed} FPS (×{factor} FG)"`. Cards show Native large, Displayed + factor secondary. Charts default to Native with a Displayed toggle. Exports contain all three.
**Rung 3's line carries its exclusions (2026-09-06, `HANDOFF` 7b / §H11).** `Active (technology not
identified)` is printed *by elimination among what this session saw*: not DLSS-G when the NVIDIA
driver's FG word reports no feature created and no HUD-less / UI tag was sent (or "not excluded"
when the driver did not answer); no FSR frame-generation dispatch reached a hooked module; the
frame-generation runtime modules the census names, or that none is loaded; and the vendor SDK
strings the executable FILE carries. Never a vendor named as measured — XeFG cannot be hooked or
declared (licence), a compiled-in FSR 3 has no module — and the line says a frame generator compiled
into the executable would read the same.
**And the census's "cannot include generated frames" is now second-witnessed by the executable
file (2026-09-06).** A frame generator compiled into the exe loads no module (Rune Factory, Wukong),
so the capture host scans the executable on disk for the SDK strings (`ffxFsr3`,
`ffxFrameInterpolation`, `xefgSwapChain`, and the non-FG ones for the reader) and the clear-census
qualifier reads *MAY include generated frames* when a frame-generation-capable marker is in the
file. A marker is code or a symbol name in the file, never proof it ran, and never an identity.
**And when FG is not measured (2026-09-03):** render the one number as **Presented FPS** —
`144 FPS` with a qualifier chip chosen by the census above, never the word "Native", never
a factor, never `—` (which means `none`, a measured negative). The chip is muted when no
@@ -393,6 +483,38 @@ From the upscaler hooks we get, per frame:
Tier 2 has none of this: `upscaler = unknown`, ratio `N/A`.
> ### The driver-reported rung — owner decision 2026-09-06, identity only
>
> Three NGX-direct titles (Lies of P, Hell Is Us, Expedition 33) evaluate DLSS super resolution through
> a path no hook of this build sees, and printed `upscaler: N/A` on every capture. The NVIDIA driver
> keeps per-process bookkeeping of the feature — `NvAPI_NGX_GetNGXOverrideState` (R570+, MIT NVAPI,
> `18_GPU_VENDOR_APIS` L3) returns a feedback word per feature — and **measured 2026-09-06 (driver
> 616.64) its `CREATED | EVALUATE` bits are set for a process with NO NVIDIA-app override** on both
> no-override titles (`20_OPEN_QUESTIONS` §H5). So the capture host probes it out of process beside
> each module snapshot (`fl-probe-nvapi --ngx-state <pid>`, no injection, no consent), and the
> `upscaler:` line has a rung between the hooks and `N/A`:
>
> ```
> upscaler: Dlss (driver-reported: the NVIDIA driver reports an NGX super-resolution feature created
> and evaluated in this process - not counted by this hook)
> ```
>
> **What it may claim: the vendor and the feature, attributed to the driver.** What it may NOT claim,
> each one measured: a quality (`performanceMode` / `renderPreset` are populated only under an
> NVIDIA-app override and are then the OVERRIDE's values), a ratio or render size (`scalingRatio` is
> 0 even under the override), a frame-generation multiplier (`FG_MODE` / `FG_MULTI_FRAME` stay clear
> and `frameGenerationCount` is 0 at ×4 — it is the override target). **Corrected the same day, on the
> loop's own readings:** the FG word DOES follow DLSS-G once the feature exists — `CREATED | EVALUATE`
> on Hell Is Us, Onimusha and DL:TB at ×4, the word CHANGING between the session's readings; the
> morning's `INITIALIZED | DLL_EXISTS` was read before creation. So the FG word is a second witness
> for the DLSS-G IDENTITY, printed beside `frame generation:` as agreement or a printed disagreement,
> and promoted to `DlssG (driver-reported: …)` only where the count is active and no tag named the
> technology. The COUNT is never the driver's. A hook's name always outranks it, and
> beside a hook's name the driver's word is printed as agreement, or as a disagreement *printed rather
> than resolved*. Beside an `N/A` with the bit clear it prints the driver's negative, attributed, which
> says nothing about FSR or XeSS. **The negative is owed** (§H5): a title with DLSS switched off should
> read the bit clear; if it does not, the rung is withdrawn.
## RT / PT / RR — evidence-based tri-state
Tri-state `Yes | No | N/A` per session with `source` (`measured | manual | inherited`).
+39 -1
View File
@@ -77,6 +77,35 @@ which makes the notification more important than it was, not less.
**Launch mode (preferred).** User starts the game from FrameLedger (or FrameLedger is set as the launch wrapper): `CreateProcess(CREATE_SUSPENDED)` → guard → inject → `ResumeThread`. Catches swapchain creation and upscaler init, which attach mode can miss entirely — a game that creates its DLSS feature during startup will otherwise report `upscaler = unknown` for the whole session.
> **Built 2026-09-06 (P1 item 2) as "inject late", which is the only shape §S1 left possible, and the
> sentence above is kept as the intent it does not quite describe.** A `CREATE_SUSPENDED` target has
> loaded nothing and the module scan *fails* against it (`ERROR_PARTIAL_COPY`, §S1 measured), so the guard
> cannot run before the loader has. The built order is **start → the guard WAITS → inject**: the host
> starts the consented executable (`ProcessLauncher`: working directory beside the exe,
> `FRAMELEDGER_ENABLE_VK_LAYER=1` in its environment for the Vulkan layer, the handle held from birth so
> the pid cannot recycle), then asks the guard through its new waiting entry, `FlGuardedInjectWhenReady`,
> which polls the loader every 50 ms — through the module seam, matching **no** blocklist — until
> `dxgi.dll` with `d3d11.dll` or `d3d12.dll`, or `opengl32.dll`, or `vulkan-1.dll` is mapped, and *then*
> runs every check and injects exactly as attach mode does. The poll decides **when** the full scan runs,
> never whether it passes. A target that exits first, or maps no runtime inside the budget (60 s in the
> host), answers `LaunchTargetExited` / `LaunchNoPresentationRuntime` with nothing injected; a launcher
> that spawns the real game and quits lands on the first, and re-electing the descendant is the Agent's
> (P2, §Process watcher). **The host never terminates what it launched**: any refusal after the start
> leaves the title running unhooked, which is Tier 2.
>
> **What it measures about itself, which is the input §S1 deferred on.** The report prints the wait
> (`launch: the guard injected N ms after the process was started`) and `FlWriterState.dxgiPresentsBeforeHook`
> — DXGI's own count, read at the first hooked present on the first hooked chain, of presents completed
> before the hook was in. **0 means nothing ran unhooked on that chain**; N is the early-init cost, per
> title, from the title itself. On `hook-harness` (device at startup, presenting every 8 ms) the real-seam
> fixture injects within one poll and reports the ~1 s of presents the fixture ran before asking — a
> measurement of the fixture, not a bound on a title. What launch mode can *never* see is anything before
> its own injection, and a swapchain created before the runtime-mapped poll fired is exactly that; the
> number says how much.
>
> The CaptureHost's verb is `launch --exe <path> [--args "<game's own arguments>"] [--seconds <n>]`; the
> consent record, the gate and the payload are the ones `capture` uses, reached one process later.
**Attach mode.** Game launched from Steam/GOG/Epic normally; watcher sees it, guard runs, inject. Feature hooks install late, so early-init facts may be missed; the Overlay compensates by re-reading state on the first `EvaluateFeature` call it does observe, and the session is flagged `late_attach = true` so the UI can note that startup-time settings may be incomplete.
Steam users can also set FrameLedger as a launch option wrapper; documented in the UI rather than automated (never modify a user's Steam config for them).
@@ -176,7 +205,16 @@ Idle → Detected(pid) → Guarded → Injecting → Capturing → Finalizing
**Vulkan sessions do not pass through `Injecting`.** The layer is loaded by the
Vulkan loader when the Agent launches an opted-in game, so the path is
`Detected(pid) → Guarded → Capturing`, skipping injection entirely. This is
`Detected(pid) → Guarded → Capturing`, skipping injection entirely.
> **Built 2026-09-06 (P1 item 3), through launch mode.** The guard's waiting entry classifies the
> launched target by what it mapped: `vulkan-1.dll` with no D3D or OpenGL runtime runs the **full** guard
> and, on a pass, injects nothing — `TargetIsVulkanLayered`, which the loop reads as "attach to the
> layer's ring" with launch mode's budget (the ring appears at the title's first `vkCreateDevice`). The
> CaptureHost's `launch` gives the process the layer's environment (`VkLayerLaunchEnvironment`:
> `VK_ADD_IMPLICIT_LAYER_PATH`, the enable variable, the enable-list line for the session); a D3D title
> ignores all of it. One ring per process, the first creator owns it (`fl_shm_host.h`). Attach mode on a
> running Vulkan title stays Tier 2: only a launch can set the loader's environment. This is
stated because the state machine above, read literally, meant the 30 s guard
re-scan — which `19_SAFETY` calls the most important runtime behaviour in the
capture layer — was not specified to run for Vulkan at all. It runs for **every
+1 -1
View File
@@ -18,7 +18,7 @@ Derived in the Agent from the record stream; the mapping is in `03_METRICS`. Sum
| Graphics API + swapchain format, buffer count, swap effect, flags | `CreateSwapChain*` / present hooks |
| Present mode (flip / blt / independent flip) | swapchain desc + `presentFlags` + `syncInterval` |
| HDR output | `SetColorSpace1` |
| Upscaler identity + quality preset | NGX / Streamline / FFX / XeSS create+evaluate calls |
| Upscaler identity + quality preset | NGX / Streamline / FFX / XeSS create+evaluate calls — **or, when no hook saw one, the NVIDIA driver's per-process NGX word, out of process and attributed (`03_METRICS` §Upscaling, the driver-reported rung, 2026-09-06): identity only, never the preset** |
| Render resolution vs output resolution (incl. mid-session changes) | upscaler parameter reads + `ResizeBuffers` |
| Frame Generation mode + factor | NGX/SL/FFX FG feature evaluation, then cadence — **Tier 1 only**. ~~then (Tier 2 only) PresentMon `FrameType`~~ retired (§S31 row P2), and Tier 2 no longer produces frames to run cadence over either |
| Ray Tracing active | AS builds + `DispatchRays` (both, to catch inline RayQuery) |
+7 -5
View File
@@ -24,11 +24,11 @@ Targets:
- `FrameLedger.VkLayer` → `FrameLedger.VkLayer.dll` + `VkLayer_FRAMELEDGER_overlay.json`
- `FrameLedger.Injector` → **static lib only.** There is no `FrameLedger.Injector.exe` and none ships (`20_OPEN_QUESTIONS` §S9, decided 2026-08-02). A standalone `LoadLibraryW` injector that users can run is a path into a game process that the guard does not stand in front of — a bypass, and a bad look for a project whose position is "we refuse where we are not welcome". The Agent links the static lib; the guard owns the chokepoint inside it (§S13(b)), so there is no callable entry point that skips the gate. Manual testing uses `hook-harness`, never a real game (§Debugging).
- `FrameLedger.Overlay.Tests` → Catch2 unit tests (ring buffer, record layout, fault filter, seqlock) **and the guard's fail-closed matrix** (`14_TESTING` §Safety-guard tests) — the guard is native, so its tests are too
- `hook-harness` → the dummy **D3D11 + D3D12** app, WARP + composition swapchain so it runs headless on CI (`17_HOOK_ENGINE` §Test harness). D3D12 is device → command queue → swapchain, which is the acquisition asymmetry a D3D11-only fixture cannot exercise. Vulkan and OpenGL modes to follow as those hooks land.
- `hook-harness` → the dummy **D3D11 + D3D12** app, WARP + composition swapchain so it runs headless on CI (`17_HOOK_ENGINE` §Test harness). D3D12 is device → command queue → swapchain, which is the acquisition asymmetry a D3D11-only fixture cannot exercise. ~~Vulkan and OpenGL modes to follow as those hooks land.~~ **`--vulkan --hold-presenting N` since 2026-09-06 (P1 item 3):** a real swapchain on a hidden window through the real loader, reached by `LoadLibraryW("vulkan-1.dll")` so only the vendored headers are needed and CI (no loader) still builds it; exit 77 = cannot run here, which the ctest reads as SKIP. OpenGL to follow.
- `fl-probe-hookprofile` → build-profile probes for `/guard:cf` and `-D_HAS_EXCEPTIONS=0` (`20_OPEN_QUESTIONS` §H1/§H3)
- `fl-probe-guard` → measures the Windows APIs the guard is built on, unelevated (`spike-notes.md` §1). Not the guard, and takes no injection rights.
- `fl_stub_sl_interposer` → `sl.interposer.dll`, and `fl_stub_sl_common` → `sl.common.dll` (`src/native/tools/vendor-stubs/`). **Fixtures, never shipped**, built under `FL_BUILD_TOOLS`; nothing `12_BUILD` publishes references them. They export the **measured** vendor names from `docs/vendor-exports.json` so the Overlay's symbol resolution is observable, and the second is a **decoy** exporting the same name from a different module — without it, "we resolve module-scoped" is a property no test can falsify. Their **output filenames are the vendor's and their version blocks are ours**: `fl_add_version_resource` takes the real filename so a file called `sl.interposer.dll` in our build tree still says plainly that it is FrameLedger's, which `19_SAFETY` requires of everything we build.
- `fl_stub_ffx_dx12` → `amd_fidelityfx_dx12.dll`, `fl_stub_ffx_upscaler` → `amd_fidelityfx_upscaler_dx12.dll`, `fl_stub_ffx_fg` → `amd_fidelityfx_framegeneration_dx12.dll` — the three AMD **leaves** — and `fl_stub_ffx_loader` → `amd_fidelityfx_loader_dx12.dll`, a **forwarding stand-in** bound to the two 2.x leaves through their FrameLedger-named *direct* entry — the way the real loader was measured to bypass the leaves' exports — so `--hold-presenting-ffx` can push every dispatch through a loader that is hooked along with the leaves and prove the count reads 1× (2026-09-04). Same rules as the Streamline stubs: fixtures, never shipped, vendor filenames with our version blocks.
- `fl_stub_ffx_dx12` → `amd_fidelityfx_dx12.dll`, `fl_stub_ffx_upscaler` → `amd_fidelityfx_upscaler_dx12.dll`, `fl_stub_ffx_fg` → `amd_fidelityfx_framegeneration_dx12.dll` — the three AMD **leaves** — and `fl_stub_ffx_loader` → `amd_fidelityfx_loader_dx12.dll`, a **forwarding stand-in** bound to the two 2.x leaves through their FrameLedger-named *direct* entry — the way the real loader was measured to bypass the leaves' exports — so `--hold-presenting-ffx` can push every dispatch through a loader that is hooked along with the leaves and prove the count reads 1× (2026-09-04). Same rules as the Streamline stubs: fixtures, never shipped, vendor filenames with our version blocks. `fl_stub_ffx_fsr3_host` → `ffx_fsr3_x64.dll` (2026-09-05): the FSR 3.0 **host** facade, exporting the four names `SpeaksFsr3Host` probes for through the vendored `fsr3-v3.0.4` header's own `FFX_API`; `--ffx-topology fsr3host|fsr3host+mono` drives it, and `hookinventory-check` Pass C reads it as the export parser's second positive control.
- **`fl_fidelityfx_headers`** → an INTERFACE target over the five vendored FidelityFX ffx-api headers (`src/native/third_party/fidelityfx/`, tag v2.3.0, MIT by exception). Three include directories because upstream's headers include each other by relative path; include directories only and nothing to link — no `.lib` is vendored — and `hookinventory-check` Pass C reads the Overlay's export table because `ffx_api.h` declares its entry points `__declspec(dllexport)` unconditionally.
- **`fl_streamline_headers`** → an INTERFACE target over the vendored MIT Streamline headers (`src/native/third_party/streamline/`). Include directories only, **never linked**: `SL_API` entry points are `extern "C"` imports, and linking one would make `sl.interposer.dll` a load-time dependency of `FrameLedger.Overlay.dll`, which would stop the Overlay loading in every game that ships no Streamline — in the loader, before any of our code runs, with no message anywhere.
@@ -183,6 +183,7 @@ document the app displays for acceptance (FR-11) is a defect, not a template.
11. **`tools/hookinventory-check.ps1`** — three passes: A resolves every vendor symbol the Overlay names against `docs/vendor-exports.json`, B sweeps for stray literals, C reads the BUILT Overlay's import table and asserts it imports no vendor module. C skips loudly under `-SkipNative`. **Missing from this list until 2026-08-28**, which is §R10 happening again
12. **`tools/package-closure-check.ps1`** — both halves: the self-test (5 cases, 4 of which must go RED) **and** a live pass over this repository. It walks the transitive `ProjectReference` closure of the two publish roots below and fails on anything outside the allowlist, naming the reference edge. `FrameLedger.CaptureHost` is an injecting entry point kept out of the package by construction, and `20_OPEN_QUESTIONS` §S27 is closed on exactly that basis
13. `tools/license-check.ps1` — asserts every vendored third-party has a licence copy in `legal/licenses/`, and that no Intel IGCL / AMD ADLX material has appeared in the tree
13b. `tools/accuracy-check.ps1 -SelfTest`, then live — the accuracy block is ONE text (`legal/ACCURACY.md`) embedded verbatim in `README.md` and `legal/DISCLAIMER.md` §4; a copy that drifted, a copy with no markers, or an empty source is red. Four self-test cases, both directions (§S23-6, 2026-09-06)
14. `tools/changelog-check.ps1 -SelfTest` — nine cases, five expected RED. The live half needs a pull request's changed-file list and is supplied by `ci.yml`
15. `tools/resx-audit` — **skipped loudly; it does not exist, and no `.resx` file does either**
16. **struct-mirror** — reads this run's `.trx` and fails when `ShmLayoutMirrorTests` did not execute, so deleting the mirror test is red as well as breaking it
@@ -196,9 +197,10 @@ document the app displays for acceptance (FR-11) is a defect, not a template.
> list of what `check` does was missing 40% of it, which is worse than having no list: a reader
> plans against it. `13_CI_CD.md` repeats the struct-mirror claim and is corrected with it.
CI runs the identical script (`13_CI_CD`), **with `-SkipIntegration`** — so a green CI is not
evidence for anything touching the managed drain, and `./build.ps1 check` with no switches is what a
developer runs before pushing.
CI runs the identical script (`13_CI_CD`) with no switches since 2026-09-06 — `-SkipIntegration` was
CI's from 2026-08-05 until §S19(b)'s signer half removed the refusal behind it — so a green CI is now
evidence for the managed drain too, and `./build.ps1 check` with no switches is what a developer runs
before pushing.
**Gates skip loudly.** A gate whose tool is not installed (no `cl.exe`) or not
yet written prints `SKIPPED`, is listed again in the summary, and the run ends
+3 -2
View File
@@ -8,8 +8,9 @@ FrameLedger uses the **`poli0981/.github` ops repo** where its templates fit, an
### `ci.yml` — push to `main` + all PRs · **repo-local**
- `runs-on: windows-latest`, .NET SDK pinned by `global.json` via `actions/setup-dotnet`, MSVC via `ilammy/msvc-dev-cmd`, NuGet cached.
- Single step of substance: **`./build.ps1 check -SkipIntegration`** — the same script a developer runs before pushing. The gate list lives in `12_BUILD` §Local quality gate, **once**, rather than being restated here where it goes stale.
- **`-SkipIntegration` is the one place local and CI deliberately differ**, and the reason is a measured property of the hard gate rather than flakiness: §S16 puts the injecting process's ancestors in the scan set, a .NET test host can load `System.Security.Cryptography.ProtectedData.dll`, and the guard's `protect` fragment then refuses our own harness (§S19(b)). So a green CI is **not** evidence for anything touching the managed drain or the capture host's end-to-end behaviour.
- Single step of substance: **`./build.ps1 check`** — the same script, with the same switches (none), a developer runs before pushing. The gate list lives in `12_BUILD` §Local quality gate, **once**, rather than being restated here where it goes stale.
- ~~**`-SkipIntegration` is the one place local and CI deliberately differ**~~ — **gone since 2026-09-06.** From 2026-08-05 CI passed it for a measured reason: §S16 puts the injecting process's ancestors in the scan set, a .NET test host loads `System.Security.Cryptography.ProtectedData.dll`, and the guard's `protect` fragment refused our own harness (§S19(b)). The signer half now verifies that module's embedded signature offline and reads `O=Microsoft Corporation` on the compiled-in bound, so the nine `Category=Integration` cases run here, and a green CI IS evidence for the managed drain and the capture host's end-to-end behaviour. The switch remains in `build.ps1`, loud, for a developer who must.
- **Signer probe step** (2026-09-06): `fl-probe-signer` runs as its own step after the gate — `continue-on-error`, a measurement and not a gate — because `ctest fl_signer_probe` passes on a regular expression and prints nothing, so §S19(b)'s CI leg was never readable from the log. Its answers are read off this step.
- Uploads coverage artifacts.
- **Changelog gate**, on pull requests only: the changed-file list comes from GitHub's own view of the PR — not `git diff`, so a shallow checkout cannot silently produce a short one — and an empty list is refused rather than read as "no `src/` changes". It is a **step of the required `check` job** and deliberately not a job of its own: `main`'s required contexts are exactly `check` and the two `analyze` jobs, so a new job would go red while the merge button stayed green, which is what already makes `Rules / validate` advisory (§S23-2).
+17 -1
View File
@@ -22,6 +22,11 @@ Findings written to `docs/spike-notes.md`. Nothing in P1 starts until the exit c
>
> **Re-read 2026-09-04:** item 7 ✅ (the FG factor is measured, §S31 row P1), item 8's L2 half is written and measured (§M5 row R1), and exit criterion 1 reads **4 of 5** on Cyberpunk 2077 — the quality preset is the one value left, and `HANDOFF` item 7 carries the three things the next session does.
>
> **P0 CLOSED 2026-09-06 (owner).** Criterion 1 met with the quality preset amended to an
> honest `N/A` (`spike-notes` §Exit criteria carries why); criterion 2 met — §S24 counts zero
> S-items against it, with 🚫 S23-2 outside any PR. The measurement path this phase exists to
> prove runs end to end in an unshipped capture host, on nine titles. **P1 starts.**
>
> The 08-06 block below is kept and is now wrong in one specific clause — it says the writer
> *"records `measuredMask = FL_MEASURED_OUTPUT_RES | FL_MEASURED_PRESENT_ARGS` and nothing
> else"*. It records upscaler identity, upscaler params, frame-generation counts and ray
@@ -264,7 +269,7 @@ Findings written to `docs/spike-notes.md`. Nothing in P1 starts until the exit c
*(The former items 7 "Vulkan layer" and 8 "Guard prototype" are now items 1 and 0. §R1/§R2 are folded in, not pending.)*
**Exit criteria:** a throwaway build records a real session from a real offline game reporting *correct* upscaler, quality preset, render→output resolution, FG factor and RT state — verified against the game's own settings menu.
**Exit criteria:** a throwaway build records a real session from a real offline game reporting *correct* upscaler, quality preset, render→output resolution, FG factor and RT state — verified against the game's own settings menu. *(Met 2026-09-06; the preset is an honest `N/A` by measurement — `spike-notes` §Exit criteria.)*
> **The FPS-impact criterion moves to the end of P1** (`20_OPEN_QUESTIONS` §R4,
> decided 2026-08-02). "Records a real session" with an Agent CPU/RSS budget
@@ -279,6 +284,17 @@ Findings written to `docs/spike-notes.md`. Nothing in P1 starts until the exit c
## P1 — Native core (1.5 weeks)
`FrameLedger.Overlay` proper: hook installation for D3D11/12/9/OGL, feature hooks, ring writer, fault policy, unhook path, native logging. `FrameLedger.Injector` with launch + attach modes. Struct mirror + Catch2 tests. Vulkan layer to parity — `vkQueuePresentKHR` plus the in-layer supervision check §S2 gates on it.
> **P1 item 1 landed 2026-09-06: the `LoadLibrary` detour** (`kernelbase!LoadLibraryExW`; wake for lazily
> loaded runtimes + §S6's in-process anti-cheat stop, `FL_STATUS_STOPPED_BLOCKLISTED`), measured in
> ctest `fl_guard` `[loader]` / `[S6]`. Order for the rest, as proposed and accepted: **2** the Injector's
> launch mode (§S13(c), §S1's deferred input) — **landed 2026-09-06 as "inject late"**
> (`FlGuardedInjectWhenReady`, the CaptureHost `launch` verb, `dxgiPresentsBeforeHook` as the cost meter;
> `04_CAPTURE` §Launch mode); **3** the Vulkan layer to `vkQueuePresentKHR` with §S2's
> in-layer supervision and a harness Vulkan mode — **landed 2026-09-06** (`layer.cpp` capture side,
> `fl_shm_host.h` shared with the Overlay, `hook-harness --vulkan`, ctest `fl_vklayer*`, launch mode's
> `TargetIsVulkanLayered` branch; §S2 ✅, §S29(d)'s assertion now a ctest that skips on CI); **4** the
> unhook path, native logging, D3D9 / OpenGL.
> **The guard already shipped, in P0.** This line used to read "the guard,
> complete and fully tested — it ships before the first real injection, not
> after", which was the correct ordering stated in the wrong phase: P0 items 1
+43 -5
View File
@@ -32,6 +32,31 @@ The injected DLL. Its whole job: install hooks, write 64-byte records into a rin
1. Open/create shared memory `Local\FrameLedger.Ring.<pid>`; write the handshake header (layout version, build id, pid, api=unknown).
2. `MH_Initialize()`.
3. Resolve which graphics APIs are present (`GetModuleHandleW` on `d3d11.dll`, `d3d12.dll`, `dxgi.dll`, `opengl32.dll`) — and register a `LoadLibrary` hook so APIs loaded **later** still get hooked (many games load D3D12 lazily). **The `LoadLibrary` hook must not install hooks inline:** it runs under the loader lock, and MinHook suspends all threads to patch, which deadlocks against any thread waiting on that lock. It enqueues the request and signals the init thread, which installs outside the lock (`20_OPEN_QUESTIONS` §H2).
> **Built 2026-09-06 (P1 item 1), with two differences from the sentence above.** The detour is on
> `kernelbase.dll!LoadLibraryExW` — the one body every `LoadLibrary*` variant of `kernel32` reaches —
> and it is installed **after** the present hooks, from `InitThread`, outside any loader lock. It
> **enqueues nothing**: the module's real file name (`GetModuleFileNameW` on the handle the original
> returned, into a stack buffer — never the caller's string, which may be relative or an API set) is
> compared against two fixed tables and the detour then does one of two things, both a single store
> plus `SetEvent` on the watchdog's auto-reset wake event. **(a)** A name that is in `FL_HOOK_INVENTORY`
> or `FL_RUNTIME_CENSUS` bumps a saturating 15-bit wake count and wakes the watchdog, whose next
> iteration runs the same lazy installers it always ran — so the install happens on the watchdog
> thread, as before, but **within milliseconds of the module rather than on the next 1 Hz tick**
> (measured in ctest `fl_guard` `[loader]`: 94 ms from the module appearing to the hook family being
> published, against a 500 ms bound that discriminates the wake from the tick). **(b)** A name that
> matches a MODULE family of the compiled anti-cheat floor (`fl_ac_floor.generated.h`, the same table
> the guard carries — prefix, case-insensitive, allocation-free) records the family's 1-based index in
> `earlyStopFamily` and wakes the watchdog; the **present path** stops the Overlay on its next
> `MayObserve` and the **watchdog** stops it on its next iteration, whichever comes first, with the new
> status `FL_STATUS_STOPPED_BLOCKLISTED` (= 4) — `19_SAFETY` §During a session, the in-process half;
> `20_OPEN_QUESTIONS` §S6. The words are `FlWriterState.loaderSignals` @56 (bit 15 = installed, bits
> 0..14 = wake count) and `earlyStopFamily` @58, both carved from `reserved[]` so the layout version did
> not move. The original is always called first and its result returned untouched, and
> `LOAD_LIBRARY_AS_DATAFILE` / `_EXCLUSIVE` / `AS_IMAGE_RESOURCE` loads are skipped — no code runs from
> them and the loader does not list them. Body under `FL_HOOK_GUARD`, no allocation, no lock, no
> logging (rule 5). Exercised by `hook-harness --load-after-ms N PATH` (up to four), against the real
> Overlay in a real target, both jobs.
4. Install present hooks for what exists (below).
5. Install feature hooks (upscaler / RT / PSO) lazily — the first time their module appears.
6. Publish `status = ready` in the handshake block.
@@ -126,6 +151,12 @@ Every hook must be listed here with a purpose. Anything not on this list is not
> so a shipped hook missing from here is invisible to every gate. Flip the row **and this
> banner** in the same PR that builds a hook.
### The one system-module detour — a hook, and the asymmetry stated
| Hook | Purpose |
|---|---|
| ✅ `kernelbase.dll!LoadLibraryExW` (2026-09-06, P1 item 1) | The wake for lazily loaded runtimes and the in-process anti-cheat stop — §DLL entry step 3 above carries the mechanism. **Rule 4:** it reads one argument the API was given (`flags`) and one property of a handle the loader just returned to *its own caller* (the module file name); nothing of the game's. **It is the only hook on a system module, and it is deliberately not in `FL_HOOK_INVENTORY`:** that table is *vendor* symbols resolved by name and gated by `hookinventory-check` against `vendor-exports.json`, and `LoadLibraryExW` is neither vendor nor uncertain. It is listed here instead so the table above and this row together are the whole inventory. It **never** installs, uninstalls or patches anything itself (§H2) |
### Watchdog observations — not hooks, and listed here so nobody mistakes them for one
| Observation | Mechanism | Rule 4 | Why |
@@ -135,13 +166,13 @@ Every hook must be listed here with a purpose. Anything not on this list is not
### Presentation
| Hook | Purpose |
|---|---|
| ✅ `IDXGISwapChain::Present`, `Present1` | Frame boundary, QPC, sync interval, present flags. **`DXGI_PRESENT_TEST` calls are dropped without a record** — the occlusion probe submits nothing, and a minimised game emits a stream of them (`07_IPC` §Protocol rules) |
| ✅ `IDXGISwapChain::Present`, `Present1` | Frame boundary, QPC, sync interval, present flags. **`DXGI_PRESENT_TEST` calls are dropped without a record** — the occlusion probe submits nothing, and a minimised game emits a stream of them (`07_IPC` §Protocol rules). **Since 2026-09-05 the hook also reads `IDXGISwapChain::GetLastPresentCount` on the chain it just saw** (rule 4: the same COM object `FindOrAdd` already calls `GetDesc` on, no new hook) and publishes `dxgiPresentSamples` / `dxgiPresentsUnseen` — DXGI's count of presents on that chain that this hook never saw, the in-process half of `20_OPEN_QUESTIONS` §H5 Leg 1. One virtual call per hooked present, costed by `hook-harness --probe-frames`. **And per record since the same night: `dxgiUnseen` @52 under `FL_MEASURED_DXGI_PRESENTS`**, so the consumer's window counts `Displayed = hooked + unseen` per bucket (`03_METRICS` §Displayed may be DXGI-COUNTED) — measured 2.90 / 2.95 on DL:TB at Streamline 2.8.0, 0 on 2.7.3 and 2.10.3. **And since 2026-09-06 (P1 item 2) the same read, at the FIRST hooked present on the first hooked chain, is published once as `FlWriterState.dxgiPresentsBeforeHook` @60** — DXGI's count of presents that ran before the hook was in, launch mode's cost meter (`20_OPEN_QUESTIONS` §S1); 0xFFFFFFFF until a present is seen, set before the present hooks go in |
| ✅ `IDXGISwapChain::ResizeBuffers` · ⏳ `ResizeTarget` | Output resolution changes mid-session. `ResizeBuffers` re-reads the swapchain description *after* the original returns; `ResizeTarget` is not hooked |
| ⏳ `IDXGISwapChain::SetFullscreenState` | Fullscreen ↔ borderless transitions |
| ⏳ `IDXGISwapChain3::SetColorSpace1` | HDR output detection. **`IDXGISwapChain3`, not 4** — 4 adds only `SetHDRMetaData` (`20_OPEN_QUESTIONS` §H9). Unbuilt, which is why `colorSpace` reads `NOT_REPORTED` and `FL_MEASURED_HDR` stays clear. **When it is built, the writer must initialise `colorSpace = FL_COLOR_SPACE_SDR` at swapchain identification** — an SDR title never calls `SetColorSpace1`, so "hook live, no call" would otherwise sit at `NOT_REPORTED` forever and HDR's definite `No` would be unreachable. DXGI documents G22/Rec.709 as the default, which makes SDR a *measured* default rather than an affirmative negative |
| ⏳ `IDXGIFactory::CreateSwapChain*` | Capture swapchain desc (format, buffer count, swap effect, flags) at creation. Unbuilt — the swapchain description is currently read on demand in the present hook via `GetDesc` |
| ⏳ `wglSwapBuffers` | OpenGL titles. Unbuilt, and deliberately not attempted before `hook-harness` has an OpenGL mode: the hook is small (a flat export, no vtable) but shipping an unexercised hook into a game process is not something this project does. Measured 2026-08-05: `opengl32!wglSwapBuffers` is a `jmp` thunk (`E9 <rel32>`) into the vendor ICD, which is already mapped before the first call |
| ⏳ Vulkan `vkQueuePresentKHR` | via layer, not hook (below). Unbuilt — P1, and §S2's in-layer supervision check lands with it. The layer today loads, gates and self-scans, and intercepts nothing |
| ✅ Vulkan `vkQueuePresentKHR` (2026-09-06, P1 item 3) | via layer, not hook (below). Frame boundary and QPC, one record per present; `vkCreateSwapchainKHR` / `vkDestroySwapchainKHR` intercepted beside it for the output size (`imageExtent`, the API's own argument — rule 4). **No `FL_MEASURED_PRESENT_ARGS`**: `vkQueuePresentKHR` carries no sync interval and no flags, which is why that bit exists. §S2's in-layer supervision check landed with it, on the present path. Measured under the real loader on the harness's `--vulkan` mode: 241 records in 4 s, status READY, `apiMask` = Vulkan (ctest `fl_vklayer_real`) |
### Upscaling / frame generation (the accuracy problem this rewrite exists to solve)
| Hook | Yields |
@@ -149,10 +180,11 @@ Every hook must be listed here with a purpose. Anything not on this list is not
| NGX: `NVSDK_NGX_D3D11/D3D12/VULKAN_CreateFeature`, `EvaluateFeature`, `ReleaseFeature` | Which NGX feature is *actually created and evaluated per frame*: SuperSampling (DLSS), RayReconstruction (DLSS-D), FrameGeneration (DLSS-G) |
| NGX parameter accessors (`NVSDK_NGX_Parameter_SetI/GetI/SetUI`) — **exported by `sl.common.dll` only; see below** | `Width`/`Height` (render) vs `OutWidth`/`OutHeight` (output), `PerfQualityValue` (quality preset), sharpness |
| ✅ Streamline: `slEvaluateFeature` · ⏳ `slInit`, `slSetFeatureLoaded`, `slSetConstants`, `slGetFeatureRequirements` | Feature set actually active when the game goes through SL rather than NGX directly (`kFeatureDLSS`, `DLSS_G`, `DLSS_RR`, `Reflex`, `NIS`). **Built 2026-08-09**, identity only: one MinHook detour on `sl.interposer.dll!slEvaluateFeature`, resolved **module-scoped** and installed lazily by the watchdog. Sets `FL_MEASURED_UPSCALER` + `FL_HOOK_UPSCALER_IDENTITY`; decodes `kFeatureDLSS`/`kFeatureNIS` and reports `FL_UPSCALER_UNKNOWN` for anything else. **Never `FL_UPSCALER_NONE`** — a Streamline-only writer cannot see FFX, XeSS or NGX-direct, and `NONE` is the only one of the three states that may be aggregated as a negative |
| ✅ Streamline: `slSetTag` | The **global** resource tags, where a title states the size of the buffer it is upscaling *from*: `kBufferTypeScalingInputColor`'s extent → `renderW/H`. **Built 2026-08-15** (`FL_HOOK_UPSCALER_PARAMS`), and it is an ALTERNATIVE to the local tags in `slEvaluateFeature`'s `inputs`, not a layer over them — `sl_core_api.h:258` says global and local tags "do NOT interact", so a title using one yields nothing from the other and both are read. Published only on a frame where an evaluation was also seen, because a tag is viewport state that outlives any one frame. This row was MISSING from this table while the hook shipped, which is the gap the banner above now names |
| ✅ **FidelityFX ffx-api: `ffxDispatch` on the FOUR modules a game calls** — `amd_fidelityfx_dx12.dll` (SDK 1.1.x monolith), `amd_fidelityfx_upscaler_dx12.dll`, `amd_fidelityfx_framegeneration_dx12.dll`, **and `amd_fidelityfx_loader_dx12.dll`** (added the evening of 2026-09-04: three loader-shipping titles at FSR produced zero dispatches at any leaf export, so the loader is where their calls arrive) · ⏳ FSR 3.0 host route `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale` / `ffxFsr3DispatchFrameGeneration` · ~~`ffxFsr2ContextCreate`~~ · ~~`ffxCreateContext`~~ | **Built 2026-09-04** (`HANDOFF` item 7c). One observer behind three trampolines reads the DESCRIPTOR the title passed — head type first, body only after the type matched a constant from the vendored MIT headers (`third_party/fidelityfx/`, tag v2.3.0): **UPSCALE** → identity (`FSR3` from the monolith, `FSR_UNVERSIONED` from the 2.x upscaler DLL, which hosts FSR 3.1 and FSR 4 behind one type) + `renderSize` → `renderW/H` (quality and sharpness `0xFF`: the dispatch carries neither) + one COUNT; **PREPARE / PREPARE_V2** → `frameID` counted on a *new* index only — this vendor's `slGetNewFrameToken`, the `fgEvaluations` producer once a title has ever prepared, with the UPSCALE count as the fallback for a title that never does; **FRAMEGENERATION** → `fgMode = FSR_FG` on that present. Rule 4: the argument of the API we hooked, never `context`, `pNext`, a command list or a resource. **Why all four:** a UE5 title ships the two leaves with no loader and calls their exports; a loader-shipping title calls the loader's export and the signed loader reaches its providers through an object, not the leaves' exports (measured: Dying Light: The Beast, KCD2, Wukong). The morning's "never the loader" rested on the export tables alone and was reversed by the run. What guards against a loader that DID re-enter a leaf's export is the K = 1 control with all four hooked and the consumer's `frames/upscale-drained`, both of which read 2× in that case. `ffxCreateContext` is deliberately NOT a row — nothing it carries fills a field the dispatch does not, and its honest family would collide with `slEvaluateFeature`'s under the installer's equality binding. The family is compound (`IDENTITY \| PARAMS \| FG_EVALUATIONS`), pinned by `static_assert`s that also bind the leaf table to the rows both ways and refuse the loader as a row. Streamline keeps precedence for the count once it has ever issued a token, so every §S31-validated title is byte-identical. Second count: the consumer prints `frames/upscale-drained`, the AMD `tokens/batch`. **FSR 3.0** (Cyberpunk's `ffx_fsr3_x64.dll`, named exports) is its own later PR — ten host headers from tag v1.1.4, and one title here to test on |
| ✅ Streamline: `slSetTag` — **and, since 2026-09-05, every tag's TYPE** (`slTagCensus`; a HUD-less / UI tag marks the present `FL_FG_DLSS_G`, rule 4: the same argument) | The **global** resource tags, where a title states the size of the buffer it is upscaling *from*: `kBufferTypeScalingInputColor`'s extent → `renderW/H` — **or, since 2026-09-05, the size the tagged `sl::Resource` declares when the extent is zero** (`TagSize` in `fl_sl_inputs.h`, shared by all three tag routes; GUID-checked; a Resource declaring no size is still the honest unknown). **Built 2026-08-15** (`FL_HOOK_UPSCALER_PARAMS`), and it is an ALTERNATIVE to the local tags in `slEvaluateFeature`'s `inputs`, not a layer over them — `sl_core_api.h:258` says global and local tags "do NOT interact", so a title using one yields nothing from the other and both are read. Published only on a frame where an evaluation was also seen, because a tag is viewport state that outlives any one frame. This row was MISSING from this table while the hook shipped, which is the gap the banner above now names |
| ✅ Streamline: `slSetTagForFrame` — **and every tag's TYPE, as above** | The same global tags through **Streamline 2.8's frame-based entry point**, which deprecates `slSetTag`: `(const FrameToken&, const ViewportHandle&, const ResourceTag*, uint32_t, CommandBuffer*)` — the token first, then exactly `slSetTag`'s list, handed to the same tag walk. **Built 2026-09-04** (`FL_HOOK_UPSCALER_PARAMS`, its own trampoline; the family is now **published when whole** — once every tag export the loaded interposer has is patched — because publishing on the first row entitled records the second was not yet producing, 38 of 41 on the fixture: the ffx leaves' #110 defect again, fixed the same way). Measured need: Dying Light: The Beast (SL 2.8.0) published `Dlss` identity on every batch and the params bit on none across three captures, because a 2.8 title that tags per frame never calls the deprecated export. The token is not read; the frame count stays with `slGetNewFrameToken`. The installer picks this detour by SYMBOL (`kSymbolSlSetTagForFrame`, bound to the row by `static_assert`), not by family, since the two rows share a family bit and differ in signature |
| ✅ **FidelityFX ffx-api: `ffxDispatch` on the FOUR modules a game calls** — `amd_fidelityfx_dx12.dll` (SDK 1.1.x monolith), `amd_fidelityfx_upscaler_dx12.dll`, `amd_fidelityfx_framegeneration_dx12.dll`, **and `amd_fidelityfx_loader_dx12.dll`** (added the evening of 2026-09-04: three loader-shipping titles at FSR produced zero dispatches at any leaf export, so the loader is where their calls arrive) · ⏳ FSR 3.0 host route `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale` / `ffxFsr3DispatchFrameGeneration` · ~~`ffxFsr2ContextCreate`~~ · ~~`ffxCreateContext`~~ | **Built 2026-09-04** (`HANDOFF` item 7c). One observer behind three trampolines reads the DESCRIPTOR the title passed — head type first, body only after the type matched a constant from the vendored MIT headers (`third_party/fidelityfx/`, tag v2.3.0): **UPSCALE** → identity (`FSR3` from the monolith, `FSR_UNVERSIONED` from the 2.x upscaler DLL, which hosts FSR 3.1 and FSR 4 behind one type) + `renderSize` → `renderW/H` (quality and sharpness `0xFF`: the dispatch carries neither) + one COUNT; **PREPARE / PREPARE_V2** → `frameID` counted on a *new* index only — this vendor's `slGetNewFrameToken`, the `fgEvaluations` producer once a title has ever prepared, with the UPSCALE count as the fallback for a title that never does; **FRAMEGENERATION** → `fgMode = FSR_FG` on that present. Rule 4: the argument of the API we hooked, never `context`, `pNext`, a command list or a resource. **Why all four:** a UE5 title ships the two leaves with no loader and calls their exports; a loader-shipping title calls the loader's export and the signed loader reaches its providers through an object, not the leaves' exports (measured: Dying Light: The Beast, KCD2, Wukong). The morning's "never the loader" rested on the export tables alone and was reversed by the run. What guards against a loader that DID re-enter a leaf's export is the K = 1 control with all four hooked and the consumer's `frames/upscale-drained`, both of which read 2× in that case. `ffxCreateContext` is deliberately NOT a row — nothing it carries fills a field the dispatch does not, and its honest family would collide with `slEvaluateFeature`'s under the installer's equality binding. The family is compound (`IDENTITY \| PARAMS \| FG_EVALUATIONS`), pinned by `static_assert`s that also bind the leaf table to the rows both ways and refuse the loader as a row. Streamline keeps precedence for the count once it has ever issued a token, so every §S31-validated title is byte-identical. Second count: the consumer prints `frames/upscale-drained`, the AMD `tokens/batch`. **FSR 3.0 — BUILT 2026-09-05 as a fifth AMD target:** `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale` (Cyberpunk's copy; named export, its own descriptor, vendored from tag **`fsr3-v3.0.4`** — the tag whose twelve `ffxFsr3*` declarations match the shipped module, not the `v1.1.4` first named). Rule 4: the detour reads `renderSize` of the descriptor the title passed and nothing else — never the context, a resource or the command list; the offset is pinned to a literal (1256) so a re-vendoring that moved it fails to compile. Same family and publish point as the four rows (`PublishFfxFamilyIfWhole` waits for a loaded host too), keyed by module in the installer; identity `FSR3` as a fact. `ffxFsr3DispatchFrameGeneration` is deliberately not a row (§H11 carries the reversal condition); the `ffx_fsr3upscaler_x64.dll` leaf is the pre-committed alternative if the facade reads silent (row B2) — never both, or `frames/upscale-drained` reads 2.00 |
| XeSS: `xessD3D12CreateContext`, `xessD3D12Init`, `xessD3D12Execute` | `outputResolution`, `qualitySetting`, XeSS version; `xess_fg` variants for XeFG |
| ✅ **Application frames per present** (`fgEvaluations`) — **`sl.interposer.dll!slGetNewFrameToken` since 2026-09-03** | Native vs Displayed frame counts at Tier 1 — see `03_METRICS` §Frame Generation. **The producer is the frame-token export**: Streamline hands a title one token per application frame and the title must ask; the detour counts distinct tokens between two presents (pointer changes, nothing dereferenced), `FL_HOOK_FG_EVALUATIONS` is its family, and it installs on every Streamline 2 title including the ones that evaluate nothing through `slEvaluateFeature`. Rule 4: the out-parameter of an API we hooked. Premise and its gate in `03_METRICS`; pre-committed table in `20_OPEN_QUESTIONS` §S31. *The row as it stood before:* ~~NGX/SL/FFX/XeSS FG feature evaluations per present. **Built 2026-08-15 for Streamline, and MEASURED TO YIELD NOTHING ON THAT ROUTE**~~ — `slEvaluateFeature(kFeatureDLSS_G)` is never called by Cyberpunk 2077 (0 across ~14,000 batches, four FG settings), so this row installs, is honest, and counts zero; see `docs/HANDOFF.md` item 3. Built on the detour that was already there: `kFeatureDLSS_G` contributes to a saturating COUNT in the same word the feature bits live in (`fl_sl_seen.h`) rather than to a bit, because a bit collapses several evaluations between two presents into one — and under multi-frame generation that is the common case, not the edge. The row's family is therefore compound (`FL_HOOK_UPSCALER_IDENTITY \| FL_HOOK_FG_EVALUATIONS`), pinned by a `static_assert` because `hookinventory-check` reads that column as an opaque identifier. **Counts EVALUATIONS, not generated frames** — the 2026-08-14 owner ruling; the multiplier lives in `sl::DLSSGOptions`, which is only reachable by the route §2b refused. ~~Non-NVIDIA FG vendors are **deferred with a written rationale**: `amd_fidelityfx_framegeneration_dx12.dll` 3.1.5 exports only the five generic `ffx*` entry points, identical to five sibling modules, so identity is in the arguments and we have no headers~~ — **AMD has a producer since 2026-09-04** (the FidelityFX row above: the PREPARE dispatch's `frameID`, or the UPSCALE count on a title that never prepares, feeds `fgEvaluations` when Streamline has never issued a token); Intel stays at the census (`20_OPEN_QUESTIONS` §Scope decisions, by licence); the FSR 3.0 host DLLs are deferred to their own PR |
| ✅ **Application frames per present** (`fgEvaluations`) — **`sl.interposer.dll!slGetNewFrameToken` since 2026-09-03** | Native vs Displayed frame counts at Tier 1 — see `03_METRICS` §Frame Generation. **The producer is the frame-token export**: Streamline hands a title one token per application frame and the title must ask; the detour counts distinct tokens between two presents (pointer changes, nothing dereferenced), `FL_HOOK_FG_EVALUATIONS` is its family, and it installs on every Streamline 2 title including the ones that evaluate nothing through `slEvaluateFeature`. Rule 4: the out-parameter of an API we hooked. Premise and its gate in `03_METRICS`; pre-committed table in `20_OPEN_QUESTIONS` §S31. *The row as it stood before:* ~~NGX/SL/FFX/XeSS FG feature evaluations per present. **Built 2026-08-15 for Streamline, and MEASURED TO YIELD NOTHING ON THAT ROUTE**~~ — `slEvaluateFeature(kFeatureDLSS_G)` is never called by Cyberpunk 2077 (0 across ~14,000 batches, four FG settings), so this row installs, is honest, and counts zero; see `docs/HANDOFF.md` item 3. Built on the detour that was already there: `kFeatureDLSS_G` contributes to a saturating COUNT in the same word the feature bits live in (`fl_sl_seen.h`) rather than to a bit, because a bit collapses several evaluations between two presents into one — and under multi-frame generation that is the common case, not the edge. The row's family is therefore compound (`FL_HOOK_UPSCALER_IDENTITY \| FL_HOOK_FG_EVALUATIONS`), pinned by a `static_assert` because `hookinventory-check` reads that column as an opaque identifier. **Counts EVALUATIONS, not generated frames** — the 2026-08-14 owner ruling; the multiplier lives in `sl::DLSSGOptions`, which is only reachable by the route §2b refused. ~~Non-NVIDIA FG vendors are **deferred with a written rationale**: `amd_fidelityfx_framegeneration_dx12.dll` 3.1.5 exports only the five generic `ffx*` entry points, identical to five sibling modules, so identity is in the arguments and we have no headers~~ — **AMD has a producer since 2026-09-04** (the FidelityFX row above: the PREPARE dispatch's `frameID`, or the UPSCALE count on a title that never prepares, feeds `fgEvaluations` when Streamline has never issued a token); Intel stays at the census (`20_OPEN_QUESTIONS` §Scope decisions, by licence); the FSR 3.0 host DLL's UPSCALE (`ffxFsr3ContextDispatchUpscale`, since 2026-09-05) counts like an ffx-api UPSCALE when neither Streamline nor a PREPARE has spoken |
> `GetFrameStatistics().PresentCount` is **not** in this inventory and must not be
> re-added as an FG signal. It counts presents the application submitted through
@@ -351,6 +383,12 @@ is not something this loader supports.
> admin. Registering under HKCU (below) is the less common choice and the better
> one: no elevation, and per-user scope.
- Intercepts `vkQueuePresentKHR`, `vkCreateSwapchainKHR`, `vkCmdTraceRaysKHR`, `vkCmdBuildAccelerationStructuresKHR`, `vkCreateGraphicsPipelines`.
> **Built 2026-09-06 (P1 item 3): the first two, plus `vkDestroySwapchainKHR`; the three feature entries are still ⏳.** How the capture side works, stated once:
> - **The ring is the same ring.** `fl_shm_host.h` (header-only, in `FrameLedger.Shm`) now holds the user-only DACL, the `Local\FrameLedger.Ring.<pid>` name, the mapping and the handshake for **both** capture sides; the Overlay calls it too. **One ring per process: whichever side creates the mapping first owns it, the other sees `ERROR_ALREADY_EXISTS` and stays inert** — and stays *forwarding*: the layer registers every device's next pointers before it tries the ring, because a hook with nothing to forward to failed the application's present (measured, `VK_ERROR_DEVICE_LOST` on the harness, the first time the Overlay got there first). That is also why the launch-mode guard **does not inject a presenter that mapped `vulkan-1.dll`** (`Reason::kTargetIsVulkanLayered`, `fl_guard.cpp`) — with or without a D3D runtime beside it, because **an NVIDIA Vulkan ICD maps `dxgi.dll` + `d3d12.dll` itself and presents the Vulkan swapchain through a DXGI flip chain** (measured on the harness's `--vulkan` mode: classified as D3D, the injected Overlay recorded 295 DXGI presents of a Vulkan swapchain and the layer forwarded into nothing). The layer is the capture side for anything that maps the Vulkan loader; a D3D title that happens to is the rarer shape and the one this rule gets wrong.
> - **It comes up at the first admitted `vkCreateDevice`**, never at load and never at `vkCreateInstance`, so a process either gate refused never has a mapping with its pid on it. Init is not a hook path; the present hook is, and it follows the Overlay's rules — SEH-guarded, allocation-free, lock-free, three faults → `SELF_DISABLED`.
> - **§S2 part three, the in-layer supervision, runs on the present path**, because the layer may not own a thread (the loader owns its mapping). `guardTicks` not advancing for `FL_GUARD_TICK_DEADLINE_MS` → `FL_STATUS_UNHOOKED`; `unhookRequested` → the same within one present; `pauseRequested` → no record, still forwarded. "Stops" means **passthrough forever with the reason on the mapping** — a layer cannot leave a running game's loader chain. A title that stops presenting is not stopped by the deadline, and has nothing to be observed either. Proven with a test-only flavour of the DLL whose deadline is 1.5 s (`fl_vklayer_shortdeadline`, never shipped; ctest `fl_vklayer_supervision`).
> - **No registry for the operator host.** Loader 1.4.357 honours `VK_ADD_IMPLICIT_LAYER_PATH` (measured 2026-09-06, `spike-notes` §2): the CaptureHost's `launch` writes a manifest under `%LOCALAPPDATA%\FrameLedger\vklayer`, points the launched process at it, sets the enable variable and adds the image name to the enable-list for the session — discoverable by that process alone, gone when it ends. The Agent's HKCU registration (`12_BUILD`) is unchanged and remains P2's.
- The layer respects the same guard, in two steps at init: it checks the enable-list, and it scans **its own process** against the anti-cheat blocklist. Either one saying no means fully passthrough. **A layer is machine-wide by nature — these checks are mandatory, not optional.**
- The self-scan uses the **same matcher and the same rules file as the injection guard** (`fl_ac_rules.h`, compiled into both targets). Not a copy: a layer with its own blocklist would be a second matcher that can disagree with the first. Every uncertainty — rules unreadable, malformed, enumeration failed, a truncated list — resolves to passthrough, which is the opposite polarity from the injection guard and the same principle: leave the host alone.
- Registered only while at least one Vulkan game has hooking enabled; unregistered on uninstall (Velopack hook) and when the last such game is disabled. **Never at install time** — `12_BUILD` §The Vulkan layer is not registered at install time.
+19 -3
View File
@@ -105,6 +105,7 @@ Still resolve **entry points defensively at runtime**: `nvapi64.dll` may be abse
| Memory | `NvAPI_GPU_GetMemoryInfoEx` — **not `NvAPI_GPU_GetMemoryInfo`**, which this table named until 2026-08-05. The vendored headers mark it `__nvapi_deprecated_function` ("deprecated in release 520"), so under `/W4 /WX` a call to it fails the native build |
| **Throttle reasons** | `NvAPI_GPU_GetPerfDecreaseInfo` — not available from L1 or L2 |
| Driver version | `NvAPI_SYS_GetDriverAndBranchVersion` |
| **NGX per-process state** | `NvAPI_NGX_GetNGXOverrideState` (R570+) — the driver's feedback word per DLSS feature for a PID, read OUT OF PROCESS by `fl-probe-nvapi --ngx-state` and, since 2026-09-06, by the capture host beside each module snapshot. Measured: the SR word's `CREATED \| EVALUATE` is set without an NVIDIA-app override; the FG word follows DLSS-G once created (`CREATED \| EVALUATE` at ×4, corrected the same day — the first reading was blind because it was early), the multiplier bits stay clear; `scalingRatio` is 0 even under an override. Identity only, SR and FG (`03_METRICS` §Upscaling) |
| **Reflex / PC latency** | `NvAPI_D3D_GetLatency` → per-frame sim/render/present/driver/GPU timestamps; hooking `NvAPI_D3D_SetSleepMode` / `SetLatencyMarker` in the Overlay tells us the game enabled Reflex (`17_HOOK_ENGINE`) |
Reflex latency is the single strongest reason L3 exists — it is genuinely unavailable anywhere else.
@@ -135,10 +136,21 @@ Read off the upstream repository through the GitHub API, not from memory:
header of interest carries the same grant inline — the `ffx-api/include/ffx_api/` set and the
FSR 3.0 host API under `sdk/include/FidelityFX/host/`. None of step 2's needles appear. **This
paragraph said "vendor from this tag", and its own reversal condition fired the same day** —
see the third bullet. The host API is still only here: `main` dropped `ffx_fsr3.h`, so the FSR
see the third bullet. ~~The host API is still only here: `main` dropped `ffx_fsr3.h`, so the FSR
3.0 route (Cyberpunk's `ffx_fsr3_x64.dll`, named exports) vendors from `v1.1.4` when it is built,
and its closure is **ten** files, not the nine first listed — `ffx_interface.h` includes
`ffx_message.h` — with `<mutex>`/`<shared_mutex>` reached through `ffx_types.h`.
`ffx_message.h` — with `<mutex>`/`<shared_mutex>` reached through `ffx_types.h`.~~ **Wrong tag,
corrected 2026-09-05 when the route was built.** Cyberpunk's `ffx_fsr3_x64.dll` exports twelve
`ffxFsr3*` names (`vendor-exports.json`), which is exactly tag **`fsr3-v3.0.4`**'s declaration
list; `v1.1.4` declares fifteen and appends `upscaleSize`, `flags` and `frameID` to
`FfxFsr3DispatchUpscaleDescription` *after* `renderSize` — a detour typed against it would read
the wrong bytes off the module the title ships. At `fsr3-v3.0.4` the root `LICENSE.txt` is MIT
verbatim, every header carries the grant inline, and **`ffx_types.h` includes `<stdint.h>` and
nothing else** — the `<mutex>` block exists only from 1.1.x behind `#ifndef FFX_MUTEX`. The
closure is ten files with **no `ffx_message.h`** (nine host headers plus
`gpu/fsr3upscaler/ffx_fsr3upscaler_resources.h`). Vendored at
`src/native/third_party/fidelityfx-fsr3/` in its own directory because the licence *shape*
differs from `v2.3.0`'s exception list; `license-check.ps1` §2e asserts it per file.
- **`main` == tag `v2.3.0`** (`60f4ea81`, "AMD FSR SDK 2.3.0", 2026-06-24) is a different shape:
its `docs/license.md` is a **binary-only, no-reverse-engineering** default licence that
"applies to all files except as noted below", followed by an MIT exception list of 845 paths.
@@ -187,7 +199,11 @@ refused the same day (delegated by the owner, decided 2026-09-04).** It declares
reads no argument, but installing it inline-patches Intel's code inside the game process, and
the same licence forbids *"any modification"*; the census is the answer NGX got and Intel gets
the same one. Reversal condition: Intel publishing the headers under a licence that clears the
checklist, at which point this paragraph is re-run, not argued around.
checklist, at which point this paragraph is re-run, not argued around. **Re-run 2026-09-06 against
<https://raw.githubusercontent.com/intel/xess/main/LICENSE.txt> and `inc/xess/xess.h`: unchanged** —
the same licence, the same three needles, the same header banner. Not fired. Intel's README does
state that XeSS-FG runs on *"non-Intel GPUs with SM 6.4 support"*, so an XeFG session is measurable
on the NVIDIA dev box even though nothing in it may be hooked or declared.
### Checklist before adding any vendor SDK
+38
View File
@@ -50,6 +50,13 @@ Implemented in `FrameLedger.Injector` and reached from managed code through a th
> against a suspended target (§S1). Neither is "no modules found". The read
> handle rights above are confirmed sufficient for every target this call can
> legitimately reach.
>
> **Launch mode (2026-09-06, P1 item 2) does not weaken this.** `FlGuardedInjectWhenReady` polls
> the same enumeration to learn *when* the launched target has mapped a presentation runtime, and a
> failing enumeration there means "not yet" — the poll continues. That is not a pass: the poll
> matches nothing against the blocklist, and the injection happens only after check 1 has run in
> full, with the enumeration succeeding, exactly as in attach mode. A launched target that never
> becomes scannable is never injected (`LaunchNoPresentationRuntime`).
> **Which processes get scanned: the game's own subtree.** `04_CAPTURE`
> §The guard writes `Check(pid)` — singular — while `04_CAPTURE` §Process
> watcher says the capture target is a *descendant* elected from a ppid
@@ -502,6 +509,23 @@ the entire driver stack read as untrusted, and combined with the `guard` and
theoretical one. A signature that is absent, invalid, or simply could not be
checked stays untrusted and refuses — that direction is deliberate.
> **Wired 2026-09-06, the EMBEDDED half only, under a compiled-in bound** (`20_OPEN_QUESTIONS`
> §S19(b), row G1: the CI leg and the owner's adapters-disabled leg both left every verdict
> unchanged). `Sources::ModuleSignerOrganisation` verifies a fragment-matching module's embedded
> Authenticode signature with `WinVerifyTrust` under `WTD_REVOKE_NONE | WTD_CACHE_ONLY_URL_RETRIEVAL`
> — no CRL or OCSP fetch, measured rather than assumed — and only then reads the subject `O=`. The
> guard trusts it only if the organisation is on the rules file's `trustedSigners` **and** on the list
> compiled into the binary (`IsCompiledTrustedSigner`): the rules file may narrow that list and may
> never widen it, so a rules push cannot widen the hard gate — the boundary of what the gate trusts is
> code, as it is for the launcher list. A trusted module keeps the scan looking; it never stops it, so
> an untrusted module loaded after it is still judged. It applies to the injection target as well as
> to its ancestors — a game that loads a Microsoft-signed key-protection provider is the false refusal
> this half exists to remove. **Fail-closed rows:** no embedded signature (catalog-only system
> binaries such as `mskeyprotect.dll` — the `CryptCATAdmin*` half is deferred with its own rationale),
> an invalid signature, an unreadable `O=`, a null path, a null or failing seam, an organisation on
> one list but not the other — every one is untrusted and refuses. Cost: ~2–4 ms per verified module,
> reached only on a fragment hit, inside the 30 s loop.
### During a session
Re-run **every pre-injection check** every 30 s, for **every Tier-1 session —
@@ -561,6 +585,20 @@ injected or layered**.
**Be honest about the window.** A 30 s poll means anti-cheat can be loaded for up to 30 s before we react — the unhook is immediate *once detected*, not immediate in absolute terms. Consent and disclaimer wording must say "within 30 seconds", never "immediately" (`legal/DISCLAIMER.md` §2). Whether to shrink the window, or to detect the load directly via the `LoadLibrary` hook `17_HOOK_ENGINE` §DLL entry **specifies** for lazily-loaded graphics DLLs, is `20_OPEN_QUESTIONS` §S6.
> **The in-process half exists since 2026-09-06 (P1 item 1), and the sentence above stays true because
> of what it does NOT cover.** The Overlay's `LoadLibrary` detour compares every module the loader maps
> mid-session against the **compiled floor's MODULE families — the exact prefix names, and nothing
> else** — and stops the Overlay from inside on a match (`FL_STATUS_STOPPED_BLOCKLISTED`; `17_HOOK_ENGINE`
> §DLL entry step 3), within one present or one watchdog iteration. That is the same set the Agent's
> guard matches by name. **The fragment tier and the signer tier are not in the detour**, on purpose: a
> substring scan is not allocation-free in a hook body under the loader lock, and `WinVerifyTrust` from
> inside a game process is out of the question — so a module the floor knows only by a fragment, or only
> by its signer, is still caught by **this host's 30 s scan and by nothing sooner**. The disclosure
> therefore does not change: "within 30 seconds" remains the promise; the exact-name case is now usually
> much faster, and the report says which happened (`EARLY STOP` naming the family, or the host's own
> stop). Modules loaded **before** the Overlay attached are the pre-injection scan's, as always. The
> detour supplements the poll; it replaces nothing (§S6's own ruling).
> **This sentence used to say the hook "already exists and is currently unused", which was false.** Corrected 2026-08-04: the Overlay installs no hooks at all — `dllmain.cpp` exports one function and nothing in the tree calls `MH_CreateHook` outside a probe. §S6 is therefore downstream of the whole P1 hook layer, not "the cheapest available improvement to the most important behavior in the product". A reader planning work off this paragraph was being told a mechanism was sitting there ready.
### Elevated / protected targets
+750 -27
View File
@@ -30,7 +30,7 @@ Rules for this document:
| — | **No `v1 → v2` migration** | Nothing shipped, so no such database exists. `0001_init.sql` creates the current schema |
| — | ~~**Multi-process titles are refused as `TargetAmbiguous` in v1**~~ — **the Chromium case is RESOLVED the same day (2026-09-03), by the vendor's own label** | Chromium-based runtimes — NW.js, Electron, RPG Maker MV/MZ, a large share of the VN catalogue — run several processes from ONE image path (browser, renderer, GPU), and *Flower in Us* refused as `TargetAmbiguous`. The presenting process is Chromium's GPU process, which owns no window, so "the one with the window" and "the parent" were both wrong picks. **What resolves it:** Chromium marks that process with `--type=gpu-process` on its own command line. `TargetResolver` now reads each candidate's command line through `NtQueryInformationProcess(ProcessCommandLineInformation)` — **served by the kernel, no `ReadProcessMemory`, no PEB walk, `PROCESS_QUERY_LIMITED_INFORMATION` only**, which is the rule-4 line `HeldProcessHandle` already draws — and resolves only when **exactly one** readable candidate carries the flag as a whole argument. Two GPU processes (two instances), none, or any unreadable candidate still refuse. §S27 is untouched: consent is keyed on the path, every candidate is that path, the guard scans the pid chosen, and `--pid` stays forbidden. **Measured the same evening, and the first rule did not fire:** *Flower in Us* runs **six** processes — browser, `crashpad-handler`, three `utility`, `renderer` — and **no `--type=gpu-process` at all**. NW.js runs the GPU **in-process, in the browser**, which is the one process Chromium leaves untyped. Second rule added: exactly one untyped candidate, every other candidate typed, no GPU process ⇒ the browser is the target; two untyped candidates are two instances and refuse. The refusal line now prints the tree (`browser=1, renderer=1, utility=3, …`) so the next unknown shape is data rather than a bare `TargetAmbiguous`. **Still unmeasured:** whether the Overlay loads and sees presents inside that browser process |
| — | **Intel XeSS / XeFG identity is closed at the census — no hook on any `libxess*.dll` export** (decided 2026-09-04, delegated by the owner) | The XeSS SDK failed `18_GPU_VENDOR_APIS` §Checklist (Intel Simplified Software License: binary-only grant, no reverse engineering, termination; headers forbid copying), so no declaration may be vendored or re-declared. The signature-free counter that seemed to survive that — an assembly thunk on a named export — still inline-patches Intel's code inside the game process, which the same licence forbids as *modification*; it would also be the only entry outside `FL_HOOK_GUARD` and a second build language, for identity alone. An Intel title therefore reports upscaler `NOT_REPORTED` and, with `libxess_fg.dll` in the census, Presented FPS under rule 6's *"MAY include generated frames"* qualifier — honest, and the same answer NGX-direct got. **Reversal condition:** Intel relicenses the headers so the checklist clears; then §H11's AMD route applies to Intel verbatim |
| — | **A title whose upscaler or frame generation is compiled into its executable is Presented FPS + the census's qualifier, in attach mode, and that is the ceiling for IDENTITY** (recorded 2026-09-04; **one such title found the same evening**) | No module for the census, no export for the inventory: nothing by name. What survives static linking is behaviour on interfaces we hook — the FSR3 frame-generation proxy swapchain at *creation* (launch mode only, §S1 deferred) and queue-side cadence with no vendor name on it. ~~**No installed title has this shape**~~ — **Rune Factory: Guardians of Azuma has it**: `amd_fidelityfx_dx12.dll` ships beside the executable and is never loaded (the census has no AMD module), FSR frame generation is on, and the report read `59.99 → 119.95 (×2 FG)`, *technology not identified* — because on a UE5 title **Streamline's frame token is requested whether or not NVIDIA's features are the ones running**, so the application-frame COUNT survives static linking even though the identity cannot. The ceiling is therefore lower than this row first said: the trio with an unidentified technology, not Presented FPS alone (§H11's run table). Identity for such a title stays out of reach by name |
| — | **A title whose upscaler or frame generation is compiled into its executable is Presented FPS + the census's qualifier, in attach mode, and that is the ceiling for IDENTITY** (recorded 2026-09-04; **two such titles found the same night — Rune Factory, and Black Myth: Wukong for its upscaling, which ships and loads the 1.1.x monolith and never dispatches to it**) | No module for the census, no export for the inventory: nothing by name. What survives static linking is behaviour on interfaces we hook — the FSR3 frame-generation proxy swapchain at *creation* (launch mode only, §S1 deferred) and queue-side cadence with no vendor name on it. ~~**No installed title has this shape**~~ — **Rune Factory: Guardians of Azuma has it**: `amd_fidelityfx_dx12.dll` ships beside the executable and is never loaded (the census has no AMD module), FSR frame generation is on, and the report read `59.99 → 119.95 (×2 FG)`, *technology not identified* — because on a UE5 title **Streamline's frame token is requested whether or not NVIDIA's features are the ones running**, so the application-frame COUNT survives static linking even though the identity cannot. The ceiling is therefore lower than this row first said: the trio with an unidentified technology, not Presented FPS alone (§H11's run table). Identity for such a title stays out of reach by name |
| — | ~~**Tier 2 requires an elevated Agent**~~ | **CLOSED 2026-08-28 by the two-rung ladder.** The requirement came from Windows restricting ETW trace sessions; there is no ETW rung, so **no capture tier needs elevation**. Elevation is optional everywhere and buys exactly two things (CPU temperatures via PawnIO, attaching to elevated targets — ADR-9). An unelevated Agent whose Tier-1 attempt fails lands on Tier 2, which is what every unhooked session lands on regardless of privilege |
---
@@ -73,28 +73,28 @@ or it becomes the next stale status claim this file exists to record.
| **S28** | ✅ **resolved 2026-08-05** | The guard's entry points share process-wide statics; a concurrent call cleared the blocklist mid-match and every check fell through to `Allow`. Reproduced by CI, not argued |
| **S27** | ✅ **resolved, and restated 2026-08-06** | The chokepoint is the anti-cheat gate, not the consent gate. It was closed by *not building* a capture host; item 1 built one, and the ✅ survives on the clause that was always load-bearing — **no injecting entry point on any SHIPPED binary**. `FrameLedger.CaptureHost` is unpublished, and `tools/package-closure-check.ps1` makes that a gate rather than a fact about today's csproj. `HookRequest` is get-only behind one factory, so this entry's own rejected synthesis no longer compiles |
| S12 | 🅓 **deferred, rationale written** | Cautious mode → v1.1; it disabled nothing in v1. *(Marked ✅ until 2026-08-27 — same disposition, different glyph.)* |
| **S1** | 🅓 **deferred, rationale written** | Owner decision 2026-08-05. Deciding input — a title loading a presentation runtime lazily — is not on this machine |
| **S13(c)** | 🅓 **deferred, rationale written** | Same decision as S1; (a) and (b) were already settled |
| **S1** | ◐ **launch mode built as "inject late" 2026-09-06 (P1 item 2); the cost is now measured per title** | `FlGuardedInjectWhenReady` polls until a presentation runtime is mapped, then runs the full guard; `dxgiPresentsBeforeHook` and the reported wait are the input the 2026-08-05 deferral lacked. The ruling "inject late vs. no launch mode" is answered by construction — inject late exists — and whether it is *preferred* per title is what the numbers decide |
| **S13(c)** | ✅ **salvageable, and salvaged 2026-09-06** | The externally observable proxy the entry proposed is what was built; the missing input is produced by every launched session |
| **S19(b)** | 🅓 **deferred, rationale written — and MEASURED** | CI 2026-08-05: the fragment fires on `System.Security.Cryptography.ProtectedData.dll` loaded by a .NET **test host**, i.e. inside a real scan set in the launch-mode arrangement — refusing our own injection. The entry's "plausible and unmeasured" is superseded; the deferral rationale (a `CryptCATAdmin*` PR doing network I/O inside the hard gate, NFR-10) still stands. *(Marked 🔴 until 2026-08-27. The measurement belongs in this cell, not in the marker — a glyph that means "deferred" and a glyph that means "open defect" cannot be the same one in a table audited by counting.)* |
| **S14** | ◐ **exe half wired 2026-08-05** | Owner decision 2026-08-05: wire it, empty list, unresolvable identity refuses. The **store-id half is blocked** on the platform metadata extractors and cannot be reached through the guard ABI by design |
| **S14** | 🅓 **exe half wired 2026-08-05; store-id half deferred to P4, rationale written 2026-09-06** | The store-id half's only in-policy route is P4's platform metadata extractors feeding a guard-side resolver; a resolver with no extractor would refuse every title. No title is blocked by store id today because none is listed |
| **S23-1** | ✅ **resolved 2026-08-05** | `FlGuardBuildId` gives the Agent a build id of its own, and `ShmHandshakeValidator` performs the comparison `07_IPC` and `04_CAPTURE` both specify. Every refusal path is driven, including **both ids empty** — the shape the feature shipped in, where `"" == ""` reported `Ok` for every process on the machine |
| **S23-4** | ✅ **resolved 2026-08-05** | `19_SAFETY` §During a session said "the module scan and the driver scan"; `EvaluateImpl` runs four. Reworded to "every pre-injection check" so it cannot go stale when a check is added, with the two omissions named — `services` is the only tier measured firing on real anti-cheat, and the pre-scan is the only one touching the filesystem |
| **S2 part three** | ⏳ **open, sequenced** | In-layer supervision lands with `vkQueuePresentKHR` (P1). Building it sooner would be a predicate whose wrong answer changes nothing observable |
| **S4 signing** | ⏳ **open, residual accepted** | HTTPS authenticates the host, not the content. Recorded rather than closed — needs a rationale written or a decision |
| **S6** | ❓ **open, disposition undecided** | Owner: work, or deferral-with-rationale? See the correction block under §S6 for what #40–#44 changed and what it does not |
| **S2 part three** | ✅ **built 2026-09-06 (P1 item 3)** | In-layer supervision on the present path, landed with `vkQueuePresentKHR`; `unhookRequested` and the tick deadline both stop the layer (passthrough with the reason on the mapping), proven by a fake loader chain and a 1.5 s test-only flavour of the DLL |
| **S4 signing** | 🅓 **deferred to P4, rationale written 2026-09-06** | Signing is a property of the feed and there is no feed (§S20); every rules file today shipped inside a release whose checksum attests it. The P4 decision (compiled-in key, detached signature, fail-closed) is written in the entry |
| **S6** | ✅ **built 2026-09-06 (P1 item 1)** | The detour on `kernelbase!LoadLibraryExW` stops the Overlay from inside on an exact-floor MODULE match, within one present or one watchdog iteration, and wakes the lazy installers within milliseconds for an inventoried module; measured against the real Overlay in ctest `fl_guard` `[loader]`/`[S6]`. Exact names only — fragment and signer stay the host's 30 s scan, so the disclosure does not change |
| **S19(a)** | ✅ **resolved 2026-08-05** | `gameguard` could never fire — `guard` subsumed it. Removed; `rules-validate` now fails when any fragment contains another, so the class cannot return. Zero coverage lost: nProtect has its own named module family |
| **S19(c)** | ❓ **open, disposition undecided** | `signerField` and `action` are schema-`required` and parsed by nobody. Costing `action` honestly means first deciding `warn`/`allow` may exist, and CLAUDE.md rule 2 says they may not |
| **S19(c)** | ✅ **resolved 2026-09-06** | The fields are constants the schema pins and the guard never reads, because the policy is code by CLAUDE.md rule 2 and `19_SAFETY`; `rules-validate` now proves the schema rejects `action: "allow"` and `signerField: "CN"` (canary 3), so the data cannot say otherwise |
| **S19(d) residual** | ✅ **resolved 2026-08-05** | A second canary, **derived from the shipped document** rather than hand-written, carries `nameFragments: []` and must be rejected. The entry's stated consequence was overstated and is corrected in place: the generated floor would not have disappeared, `gen-ac-floor.ps1` hard-errors and the native build fails — what was unguarded is the *schema* half |
| **S20 feed half** | ❓ **open, disposition undecided** | **FR-7.3 is unmet**: a rules edit reaches no installed machine until a release |
| **S23-3** | ⏳ **open, sequenced** | `08_UI`'s refusal notice is wrong in the commonest case; needs to reach `08_UI` and the `Safety_*` keys before any UI exists (P3) |
| **S20 feed half** | 🅓 **deferred to P4, rationale written 2026-09-06** | **FR-7.3 stays unmet and written as unmet**: the fetch needs a shipped Agent, §S4's signing and the privacy policy's rows, all P4; until then a rules edit ships with the next release, checksum-attested |
| **S23-3** | 🅓 **deferred to P3, rationale written 2026-09-06** | `08_UI`'s refusal notice is wrong in the commonest case; the requirement reaches `08_UI` and the `Safety_*` keys in the PR that creates the first refusal UI — a string with no view would read as done |
| **S23-5** | ✅ **resolved 2026-08-05** | Closed the way §S23-4 closed the same class — by **removing** the restatement, not correcting it — and `rules-validate` now fails when any `$comment` enumerates checks again. The rule's own first version was scoped to the wrong object and could not fire; it now walks every `$comment` and fails if it finds none |
| **S23-6** | ◐ **partly closed** | `license-check` now binds `THIRD_PARTY_NOTICES` bidirectionally — the first real gate over anything in `legal/`. The **accuracy blocks remain hand-maintained prose that nothing verifies**, and `DISCLAIMER.md`'s went stale a second time on 2026-08-05 |
| **S23-6** | ✅ **closed 2026-09-06** | `license-check` binds `THIRD_PARTY_NOTICES` bidirectionally, and the accuracy blocks are now ONE text — `legal/ACCURACY.md`, embedded verbatim in `README.md` and `DISCLAIMER.md` §4, gated by `tools/accuracy-check.ps1` (self-tested both directions). Truth stays a human's job; drift between copies no longer is |
| **S23-2** | 🚫 **owner only — no PR can close it** | `Rules / validate` is **not** a required status check on `main`. **Re-verified against the live branch protection 2026-08-05**, not repeated from the entry: `required_status_checks.contexts` is exactly `["check", "analyze (csharp, none)", "analyze (cpp, manual)"]` (`strict: true`, `enforce_admins: true`, `required_linear_history: true`). The `validate` job is path-filtered and `pull_request`-only, so a red removal check does not block the merge button. **The gate that exists to make the anti-cheat blocklist un-removable is advisory.** This is a branch-protection setting |
| **S29** | 🔴 **open, new 2026-08-05 — five ✅ and two ◐, counted off the glyphs below on 2026-08-20** | (a) ◐ **CORRECTED**: the honesty assertion *is* in the merge gate, natively (`fl_guard`, 20.58 s on CI); only the **managed** drain is ungated, and §S19(b) is **not** a prerequisite of the feature hooks — the original claim was wrong and had been used to re-order the work. **Sharpened 2026-08-06:** fixing §S19(b) alone would still gate nothing, because `build.ps1`'s `-SkipIntegration` applies `--filter 'Category!=Integration'` and excludes the class *before* the guard is ever asked. Two independent mechanisms produce one absence, and `ci.yml` must drop the switch too; (b) ✅ `fl_vtable_indices` now pins the Overlay's indices through a shared header; (c) ✅ **closed 2026-08-06 by deleting `ShouldUnhookAsync`** — zero production callers, strictly weaker than `ScanOnceAsync`, and inverted in polarity; the gate's public instance surface is now pinned to `{StartAsync}`; (d) ◐ `vklayer-blastradius` case 3 is now an assertion, but the script still runs only by hand; (e) ✅ **closed 2026-08-06 host-side**, with a held process handle and a classifier that takes no elapsed-time parameter, so a frozen `writeIndex` can never end a session; (f) ✅ **closed 2026-08-20**: the normative contradiction between CLAUDE.md rule 7 and `03_METRICS` about inline RayQuery is settled the way the entry proposed — AS-build activity proves ray tracing is happening, *naming the technique* is what needs a DXIL scan — and rule 7 is amended in the PR that wrote the hooks. Its second half closes with it: `FL_MEASURED_RT` now has a producer (both command-list detours, installed off the game's own device), so all three conjuncts of the `No` branch are live and **`Yes` and `No` are both reachable for the first time**, proved by injection in both directions; (g) ✅ the present-only writer claimed `FL_MEASURED_OUTPUT_RES` unconditionally, including on records with no size |
| **S29** | 🅓 **six ✅ and one 🅓 on 2026-09-06 — nothing 🔴 remains** | (a) ✅ **closed 2026-09-06**: the managed drain is in the merge gate — §S19(b)'s signer half removed the refusal and `ci.yml` dropped `-SkipIntegration` in the same PR, both mechanisms at once, as the sharpening below said they had to be. *(History: ◐ CORRECTED — the honesty assertion *was* in the merge gate natively (`fl_guard`, 20.58 s on CI); only the **managed** drain was ungated, and §S19(b) was **not** a prerequisite of the feature hooks. Sharpened 2026-08-06: fixing §S19(b) alone would still have gated nothing, because `build.ps1`'s `-SkipIntegration` applied `--filter 'Category!=Integration'` before the guard was ever asked.)* (b) ✅ `fl_vtable_indices` now pins the Overlay's indices through a shared header; (c) ✅ **closed 2026-08-06 by deleting `ShouldUnhookAsync`** — zero production callers, strictly weaker than `ScanOnceAsync`, and inverted in polarity; the gate's public instance surface is now pinned to `{StartAsync}`; (d) 🅓 **deferred 2026-09-06 on a measurement** — `ci.yml` now prints a Vulkan runtime census, and the script runs as a CI step the day a runner has a loader; until then it stays hand-run before any layer PR, with the P1 Vulkan entry as the reminder (the pre-commitment in the entry covers both rows); (e) ✅ **closed 2026-08-06 host-side**, with a held process handle and a classifier that takes no elapsed-time parameter, so a frozen `writeIndex` can never end a session; (f) ✅ **closed 2026-08-20**: the normative contradiction between CLAUDE.md rule 7 and `03_METRICS` about inline RayQuery is settled the way the entry proposed — AS-build activity proves ray tracing is happening, *naming the technique* is what needs a DXIL scan — and rule 7 is amended in the PR that wrote the hooks. Its second half closes with it: `FL_MEASURED_RT` now has a producer (both command-list detours, installed off the game's own device), so all three conjuncts of the `No` branch are live and **`Yes` and `No` are both reachable for the first time**, proved by injection in both directions; (g) ✅ the present-only writer claimed `FL_MEASURED_OUTPUT_RES` unconditionally, including on records with no size |
| **S30** | ✅ **closed 2026-08-15** | Answered on the title that raised it: with Ray Reconstruction on, Cyberpunk 2077 evaluates `kFeatureDLSS_RR` on every application frame and `kFeatureDLSS` **not once**, so RR was doing the upscaling and the decode had no arm for it. Evidence rather than inference: `renderW/H` are published only on a frame that drained an evaluation and read 1485×835 = 0.58 × 2560×1440, so the scaling-input tag arrives ON the RR evaluation. Two further defects fell out — the pre-committed decision table had two holes, and the fix contaminated the census that found it (it derived the id from the decoded byte) |
| **S31** | ✅ **resolved 2026-09-04 — row P1, and `tokens/batch = 1.00`** | Is a drained Streamline batch an application frame? **Yes.** The `slGetNewFrameToken` count (#103, #105) reads 1.00 / 2.99 / 3.99 against Cyberpunk's own off / ×3 / ×4 and 4.00 on Hell Is Us, and on every leg with batches the two counts agree to the frame. Two independent per-frame API counts are the oracle four instruments could not be. `fg_factor` is published; `none` is reachable by counting. *(The row as it stood while open:)* ◐ **row P2, 2026-08-27 — the ORACLE is retired, the QUESTION is not** | Is a drained Streamline batch an application frame? The PresentMon 2.x `FrameType` test, with its decision table pre-committed BEFORE the run and `tools/frametype-oracle.ps1` producing the input as two dimensionless ratios. **Two obstacles measured before it could be run**: the console binary will not start a trace session unelevated on the dev box (exit 6; the account is in neither Administrators nor Performance Log Users, and the running shared service does not help), and `--track_frame_type` is a **beta** option whose own help says it needs application or driver instrumentation of the Intel-PresentMon provider — so it may be as unavailable as `fl-baseline-probe` proved to be. Two of the table's six rows retire it outright. Blocks HANDOFF item 3's producer decision |
| **H11** | ◐ **AMD ffx-api BUILT and RUN 2026-09-04 (A1–A3 accepted; the loader row added the same evening after three loader titles read silent); Intel closed at the census by licence; FSR 3.0 host route deferred to its own PR** | XeFG and FSR3-FG identity. The AMD half is measured on nine titles: the three ffx-api leaves AND the SDK 2.x loader are hooked (the loader turned out to be the game's entry on loader-shipping titles, with the leaves silent behind it), the vendored MIT headers (tag v2.3.0) decode the dispatch descriptor, and rows A1–A3 landed as pre-committed. Owed: the three loader titles again, against row R6. Intel's SDK failed the licence checklist, so XeSS/XeFG stay at the census (§Scope decisions). `ffx_fsr3_x64.dll` (FSR 3.0, Cyberpunk only here) needs ten host headers from tag v1.1.4 and is deferred with that costing written |
| **H11** | ◐ **AMD ffx-api BUILT and RUN 2026-09-04 (A1–A3 accepted; the loader row added the same evening after three loader titles read silent); Intel closed at the census by licence; FSR 3.0 host route deferred to its own PR** | XeFG and FSR3-FG identity. The AMD half is measured on nine titles: the three ffx-api leaves AND the SDK 2.x loader are hooked (the loader turned out to be the game's entry on loader-shipping titles, with the leaves silent behind it), the vendored MIT headers (tag v2.3.0) decode the dispatch descriptor, and rows A1–A3 landed as pre-committed and **R6 closed on Dying Light: The Beast and KCD2 the same night** (`FSR (3.1 or 4 …)` / `FsrFg` / ×2 / 1.01 and `none` / 1.00 through the loader row). Wukong's FSR upscaling is compiled in (Rune Factory's shape; the title has no FSR frame generation), so nothing more is owed on the AMD half; the FSR 3.0 host route is the one deferred piece Intel's SDK failed the licence checklist, so XeSS/XeFG stay at the census (§Scope decisions). `ffx_fsr3_x64.dll` (FSR 3.0, Cyberpunk only here) ~~needs ten host headers from tag v1.1.4 and is deferred with that costing written~~ **built 2026-09-05** from tag `fsr3-v3.0.4` (the docs' `v1.1.4` was the wrong tag: twelve exports match 3.0.4, not 1.1.4's fifteen, and 1.1.4's descriptor appends fields after `renderSize`); one row, the host's UPSCALE; **rows B1–B4 owed** (below) |
~~**Six items are ❓ and one is 🚫.**~~ **Recounted 2026-08-05: TWELVE items block
exit criterion 2, not seven, and the undercount came from reading only the ❓ rows.**
@@ -134,6 +134,16 @@ the recount becomes the next thing that needs recounting.
> the question* rather than by a decision to stop asking it, since S30. ❓ three, ⏳ three,
> ◐ two, 🔴 one, plus 🚫 S23-2. The list above moved in the same edit as this count.
>
> **ZERO on 2026-09-06 — exit criterion 2 reads as met, with one item outside any PR.** The
> owner's closing sweep ("theo bảng"): S19(c) and S23-6 resolved by a gate each, S29 down to
> one 🅓 on a pre-committed measurement, and six items deferred with their rationale written
> in the entry and their phase named in this table — S6 and S2 part three to P1, S23-3 to P3,
> S4 signing, S20 feed half and S14's store-id half to P4. ❓ zero, ⏳ zero, ◐ zero, 🔴 zero.
> **What remains is 🚫 S23-2**, a branch-protection setting only the owner can change; it is
> not resolved and not deferred, it is outside what a PR can do, and the criterion's own
> wording does not reach it. The bullet list above is history as of 2026-09-04 and is left as
> it stood; this paragraph is the current count.
>
> **STILL TEN on 2026-08-27, for the third consecutive movement.** S31 moved from ❓ to ◐,
> so ❓ goes four to three and ◐ goes two to three. **The number has now stayed at ten across
> three different changes**, and that is worth saying out loud precisely because a reader
@@ -291,7 +301,13 @@ refuter told to default to *refuted*. The ledger drift it found is fixed in the
that records this. What follows is the residue: things that need code, recorded so
the next session finds them by reading.
**(a) ◐ The honesty contract is in the merge gate — natively. The MANAGED half is not.**
**(a) ✅ The honesty contract is in the merge gate — natively, and since 2026-09-06 the MANAGED half too.**
> **Closed 2026-09-06 by §S19(b)'s signer half and the same PR's `ci.yml` change.** The .NET
> test host still loads `System.Security.Cryptography.ProtectedData.dll`; the guard now verifies
> its embedded signature offline, reads `O=Microsoft Corporation` on the compiled-in bound, and
> keeps looking. `ShmDrainIntegrationTests`, `CaptureHostEndToEndTests` and the LHM hardware case
> run in CI under `./build.ps1 check` with no switches. The entry below is the history.
> **This entry was WRONG when it was written on 2026-08-05, and the correction
> matters because the wrong version was used to re-order the work.** It claimed the
@@ -401,6 +417,38 @@ layers) and needs `vulkaninfo` on `PATH`. So the assertion only fires when someo
runs it by hand. Nothing reminds them, and a loader upgrade is exactly when it
would matter.
> #### Disposition 2026-09-06, pre-committed on a measurement the same PR takes
>
> The "wrong place" argument inverts on a hosted runner: it is disposable, so an implicit
> layer registered under its `HKCU` harms nothing, and it IS the place a loader upgrade
> would be noticed. What decides is whether the runner has a Vulkan loader and
> `vulkaninfo.exe` at all — they ship with a GPU driver's runtime, not with Windows.
> `ci.yml` now prints a **Vulkan runtime census** (`vulkan-1.dll`, `vulkaninfo.exe`, the
> ICD registry key) as a measurement step. **Rows:** present → the next PR runs
> `vklayer-blastradius.ps1` as a CI step and (d) closes ✅; absent → (d) is 🅓 **deferred on
> that measurement**: the script stays hand-run before any layer PR (`HANDOFF` §Traps), and
> the reminder is the P1 Vulkan entry that cannot land without running it. Either row ends
> S29 as an S-item; the count below is written for the absent row and corrected if the
> census says otherwise.
>
> **2026-09-06 (P1 item 3): the assertion now lives in a ctest, and it no longer needs the registry.**
> `fl_vklayer_real` starts the harness's `--vulkan` mode with `VK_ADD_IMPLICIT_LAYER_PATH` pointed at the
> build tree's manifest and the enable variable set, and asserts the loader mapped the layer and the layer
> recorded the presents — on every dev-box build, with no HKCU write and nothing left behind. It SKIPS
> where there is no loader or no presentable device, which is CI's row; the census still decides (d)'s
> CI leg. `vklayer-blastradius.ps1` remains the hand-run check of the *unset-variable* case (it was run
> before this PR, green), and the loader-upgrade reminder is now the ctest rather than a HANDOFF trap.
>
> **Read 2026-09-06 off the sweep PR's run (`windows-latest`): `vulkan-1.dll` PRESENT in
> System32, `vulkaninfo.exe` absent (not in System32, not on PATH), no ICD registry key.** The
> absent row: **🅓 deferred on that measurement.** The loader is there but nothing to drive it
> with and nothing for it to drive — `vulkaninfo.exe` ships with a GPU driver's runtime, and
> without an ICD `vkCreateInstance` fails before the layer question is fully asked. The script
> stays hand-run before any layer PR. **Reopen condition, written now:** a Vulkan mode of
> `hook-harness` (unwritten, `12_BUILD` §Targets) could replace `vulkaninfo.exe` as the driver,
> and whether the loader's layer discovery and `enable_environment` behaviour is observable
> with no ICD is one measurement away — the P1 Vulkan entry is where it is taken.
**(e) ✅ The reader cannot tell a dead target from a quiet one — closed 2026-08-06,
host-side, with no ABI change.**
@@ -1206,7 +1254,32 @@ is still no fault-policy test at all**, so the fix has no regression net. The
vehicle is the blocker, not the assertions; `src/native/tests/CMakeLists.txt`
records both rejected approaches and why.
### S1 · The guard is structurally blind in launch mode
### S1 ◐ · The guard is structurally blind in launch mode — **launch mode built as "inject late", 2026-09-06 (P1 item 2)**
> **Built, and the deferral's missing input is now something every launched session produces.**
> The guard gained `GuardedInjectWhenReady(pid, dll, timeoutMs)` (ABI `FlGuardedInjectWhenReady`): it
> polls the target every 50 ms through the module seam — a `Collected::kFailed` (the suspended /
> still-in-loader `ERROR_PARTIAL_COPY`) is "not yet", never a pass — until `dxgi.dll` with
> `d3d11.dll`/`d3d12.dll`, or `opengl32.dll`, or `vulkan-1.dll` is mapped, then runs `GuardedInjectImpl`
> in full. The poll matches nothing against the blocklist; it chooses WHEN the guard runs and nothing
> about whether it passes. Two new reasons end the poll with nothing injected: `LaunchTargetExited`
> (24) and `LaunchNoPresentationRuntime` (25). The CaptureHost's `launch` verb starts the consented
> executable itself (`ProcessLauncher`, `FRAMELEDGER_ENABLE_VK_LAYER=1`, handle held from birth) and
> routes the same gate through `HookRequest.WaitForPresentationRuntimeMs`; it never terminates what it
> launched. Measured, ctest `fl_guard` `[launch]`: the fake-driven poll injects on the first
> enumeration that shows the runtime and not one before (7 polls, ~300 ms), a target that exits first
> and a budget that runs out each answer their own reason, anti-cheat mapped beside the runtime is the
> full scan's refusal, and the real-seam case against `hook-harness` injects within one poll (15 ms).
>
> **The number nobody had:** `FlWriterState.dxgiPresentsBeforeHook` @60 — DXGI's `GetLastPresentCount`
> at the first hooked present on the first hooked chain, i.e. presents that ran before the hook was in
> (0xFFFFFFFF = the hook never saw a present). With the reported wait (`launch: the guard injected N ms
> after the process was started`) that is the early-init cost §S13(c) said needed a lazily loading title:
> it now comes from every title, on every launched session. **What the numbers decide is whether launch
> mode is *preferred* for a given title, not whether it exists.** The 2026-08-05 rationale stands as
> written below; what it deferred is now measurable rather than argued. Owed: the first real-title launch
> (the owner's next captures), which will also be the first look at a launcher-first title landing on
> `LaunchTargetExited` and needing the Agent's descendant election (P2).
> **§S1 does not gate the Vulkan path.** Added 2026-08-03, because "launch mode
> is blocked by §S1 anyway" was being used as a reason to deprioritise §S18 and
@@ -1275,7 +1348,7 @@ still lacks.
> `opengl32` or `vulkan-1` lazily rather than at startup. The owner supplies real
> fixtures on request; this one has not been found on this machine.
### S2 ◐ · The Vulkan layer has no guard — **both halves done; mid-session unhook still open**
### S2 ✅ · The Vulkan layer has no guard — **both halves done; part three built 2026-09-06 (P1 item 3)**
An implicit layer is machine-wide and loads **before** anything of ours runs, so
the injection guard cannot cover it: no module scan, no driver scan, no
@@ -1333,6 +1406,29 @@ ctest that always skips is a gate that cannot fail.
### ◐ Part three: mid-session guard inside a layered process — decided, half built
> #### ✅ Built 2026-09-06 (P1 item 3), in the PR that added the present hook — as the deferral below said it would be
>
> The layer intercepts `vkQueuePresentKHR` (+ `vkCreateSwapchainKHR` / `vkDestroySwapchainKHR`), owns the
> same ring the Overlay would (`fl_shm_host.h`, one per process) and runs the in-layer check **on the
> present path**: `unhookRequested` → `UNHOOKED` within one present; `guardTicks` not advancing for the
> 07_IPC deadline → `UNHOOKED`; `pauseRequested` → no record, still forwarded. "Stops" is passthrough forever
> with the reason on the mapping. Driven end to end by a fake loader chain (ctest `fl_vklayer`), the deadline
> proven with a 1.5 s test-only flavour of the DLL (`fl_vklayer_supervision`: ticks every 600 ms keep it
> alive past the deadline, 1.8 s without one stops it), and the real loader + the harness's `--vulkan` mode
> on the dev box (`fl_vklayer_real`, 241 records in 4 s; skips on CI, which has no loader). `17_HOOK_ENGINE`
> §Vulkan carries the shape. **The residual below is unchanged** and the Disclaimer's wording with it.
>
> #### 🅓 Deferred to P1, rationale written 2026-09-06
>
> The decision is taken (below: supervision is the Agent's job; a layer that cannot confirm
> supervision goes inert) and half of it is built. The other half is the in-layer check that
> reads `guardTicks` — and it has nothing to run on until `vkQueuePresentKHR` is intercepted,
> which is P1 (`15_ROADMAP` §P1: *"Vulkan layer to parity — `vkQueuePresentKHR` plus the
> in-layer supervision check §S2 gates on it"*). Building the predicate now would be one
> whose wrong answer changes nothing observable, the defect class this file records. Cost of
> waiting: none a user can see — the layer intercepts nothing, so there is no Vulkan capture
> to stop.
**The mechanism is decided.** The layer does NOT re-scan on its own after init.
Four options were pressure-tested (2026-08-02); the reasons the other three lost
are worth keeping, because each looks reasonable until costed:
@@ -1383,12 +1479,13 @@ process in the §S16 scan set — and the capture side would then keep observing
"the Overlay keeps writing (harmless)" on heartbeat loss described an
unsupervised hooked process as harmless.
**◐ The in-layer half is deliberately NOT built yet, and this stays open.**
**~~◐ The in-layer half is deliberately NOT built yet, and this stays open.~~ ✅ Built 2026-09-06, see the top of this part.**
The layer intercepts nothing — `vkQueuePresentKHR` is P1 — so a `ShouldObserve()`
today would be a predicate whose wrong answer *in either direction* changes
nothing observable. That is a gate on something that does not exist, which is the
defect class this file keeps recording. It lands in the PR that adds the present
hook, where a fake loader chain can drive it end to end.
hook, where a fake loader chain can drive it end to end. *(It did: `MayObserve()` in
`layer.cpp`, ctest `fl_vklayer` / `fl_vklayer_supervision`.)*
**Residual, to state rather than discover:** even once built, the mid-session
*driver* case is invisible from inside a layered process, and a layer cannot
@@ -1434,6 +1531,16 @@ override with a timer on it.
host, not the content. The rules above let a compromised feed be *rejected* but
not a genuine one *proven*. Residual risk, recorded rather than closed.
> #### 🅓 Deferred to P4, rationale written 2026-09-06
>
> Signing is a property of the feed, and there is no feed (§S20's feed half, deferred to
> P4 in the same sweep): every rules file on every machine today shipped inside a build
> whose SHA-256 is published, so the content IS attested, by the release. The decision that
> belongs to P4 — a compiled-in public key and a detached signature over the rules file,
> verified before validate-then-replace, with the same fail-closed polarity as the rest of
> the feed rules — is written here so the feed cannot ship without it. Residual until then:
> none beyond the release checksum, because nothing fetches.
### S5 ✅ · `detection-rules.json` schema — **closed**
`rules/detection-rules.schema.json` (JSON Schema 2020-12) now fixes the shape,
@@ -1501,6 +1608,10 @@ prologue) cannot produce a figure that generalises.
> entry proposes (resume, then poll until the target has mapped a presentation
> runtime *and* the scan passes *and* the blocklist is clean) remains the only
> candidate design for "inject late". It is unbuilt, not rejected.
>
> > **✅ Built 2026-09-06 (P1 item 2), exactly that proxy** — `FlGuardedInjectWhenReady`, §S1 carries
> > the mechanism and the measurements. "Salvageable" is answered yes; the cost of injecting late is
> > reported by the session itself (`dxgiPresentsBeforeHook`, and the wait).
### S15 ✅ · The four consequences of putting the guard in C++ (§S13(a)) — **closed**
@@ -2181,6 +2292,80 @@ admits it has no data for (Ricochet, VAC). Three refuters agreed.
> **Nothing under `FrameLedger.Injector` changed with the probe**, deliberately. This
> is a measurement, and reading a row off the table is a separate PR — including the
> row that says build nothing.
>
> **THE CI LEG WAS NEVER READABLE, found 2026-09-06 when it was finally looked for.**
> `ctest fl_signer_probe` passes on `BLOCKER: (FOUND|NOT PRESENT)` and ctest prints nothing
> for a passing test, so eleven days of green CI carried none of the probe's answers — the
> leg rows G3/G4/G5 are written for was "run" in the sense that a binary exited 0. And the
> native tests run BEFORE `dotnet restore` in `build.ps1`, so on a cold runner the NuGet
> copy the probe searches first may not exist yet at ctest time. `ci.yml` now runs the probe
> as its own step AFTER the gate (`continue-on-error`, a measurement and not a gate), and the
> answers are read off that step's log. **Owner-only, still unrun:** the adapters-disabled
> leg (rows G1/G2 — a network setting, not a PR), and the allow-widening bound that no row
> can lift (below). The recommendation for the bound, so the owner decides between two
> written options rather than one: **bound `trustedSigners` by a compiled-in allowlist the
> data file can only intersect** — the boundary of what the gate trusts stays code, exactly
> as `19_SAFETY` ruled for the launcher list, and it needs no branch-protection change; the
> alternative, making `Rules / validate` a required check, is §S23-2 and is the owner's
> GitHub setting, not a file in this repository.
>
> **THE CI LEG, READ 2026-09-06 off the new step (run on `ci/signer-probe-leg`, `windows-latest`,
> the probe reporting `elevated: yes` — the runner is an administrator; the dev-box leg was
> unelevated).** The blocker at the runner's NuGet cache (`system.security.cryptography.protecteddata`
> 6.0.0, `lib/net6.0`): embedded/offline **`ERROR_SUCCESS`, 3.47 ms, `O= Microsoft Corporation`**,
> no catalog; `mskeyprotect.dll` `TRUST_E_NOSIGNATURE` / catalog `ERROR_SUCCESS`; `kernel32.dll` both;
> cold 3.45 ms, warm 3.53 ms; `cryptnet.dll` newly loaded under the offline flags, as on the dev box;
> the canary `TRUST_E_NOSIGNATURE`; the probe's own verdict *"G1 is a CANDIDATE"*. **So G3 does not
> fire (the `O=` premise holds on CI's copy), G4 does not fire (CI's copy is embedded-signed), G5 does
> not fire (3.5 ms).** What is left before G1 can be read is exactly the two owner-only legs above:
> adapters disabled (G1 against G2), and the bound.
>
> **THE ADAPTERS-DISABLED LEG, the owner's run, 2026-09-06 (dev box, elevated; reported in answer
> to the request to run it with every adapter off — if it was not, this paragraph is withdrawn
> and the leg is unrun).** Every verdict UNCHANGED against `spike-notes` §1: `kernel32.dll`
> embedded `ERROR_SUCCESS` / catalog `ERROR_SUCCESS`; `mskeyprotect.dll` embedded
> `TRUST_E_NOSIGNATURE` / catalog `ERROR_SUCCESS`; the blocker embedded `ERROR_SUCCESS`, no
> catalog, **`O= Microsoft Corporation`**; canary `TRUST_E_NOSIGNATURE`; `cryptnet.dll` still
> mapped under the offline flags and still not evidence of a request. Faster than the online run
> (2.14 ms cold, 2.15 ms warm; 2.97 / 2.13 ms on the system binaries), which is what an offline
> cache-only path should look like. **One detail worth its line:** the blocker's subject now reads
> `CN=.NET` where the August copy read `CN=Microsoft Windows` — the NuGet copy was re-staged with a
> different certificate — and `O=` is the same on both, which is the `signerField: "O"` decision
> confirmed on a subject class it was never measured against. **Row G1 reads.** The embedded half
> alone, offline, clears the CI refusal; the `CryptCATAdmin*` catalog half is deferred with its own
> rationale (it reaches `mskeyprotect.dll`, which is not on the path to the merge gate, and it is
> the `CatRoot` walk §S19(b) priced). **What still stops the build is the bound**, above — the
> owner's, and asked for beside this reading.
>
> #### ✅ BUILT 2026-09-06 — the embedded half, on row G1, under the compiled-in bound (owner: option 1)
>
> **The owner chose the bound the same afternoon: a compiled-in allowlist the rules file may only
> intersect.** `IsCompiledTrustedSigner` in `fl_ac_rules.cpp` names the five organisations the shipped
> rules name, and `IsTrustedSigner` now requires BOTH lists — a rules push that adds `"Evil Corp"`
> widens nothing, which is one assertion in `fl_guard`. `Sources` gained
> `ModuleSignerOrganisation`: `WinVerifyTrust(WTD_CHOICE_FILE)` under `WTD_REVOKE_NONE |
> WTD_CACHE_ONLY_URL_RETRIEVAL | WTD_SAFER_FLAG`, and only after `ERROR_SUCCESS` the signing
> certificate's subject `O=` through `CryptQueryObject` — the probe's shape with fixed buffers, in
> `fl_guard_sources.cpp` (never `fl_ac_rules.cpp`, which the Vulkan layer compiles: wintrust and
> crypt32 stay out of every Vulkan process). `ModuleSinkFn` asks it after the ours exemption and
> BEFORE latching: a trusted module returns *keep looking*, exactly as the exemption does, so the
> load-order fail-open this entry predicted is closed by the same structure — and it applies to the
> TARGET too, because a game loading a Microsoft-signed key-protection provider is the false refusal
> the half exists to remove. **The fail-closed row, added:** no embedded signature (every catalog-only
> system binary — `mskeyprotect.dll` by design), an invalid one, an unreadable `O=`, a null path, a null
> seam, a seam that fails, an organisation on one list but not the other — all untrusted, all refuse.
> The catalog half stays deferred: it reaches only modules that are not on the path to the merge gate,
> and it is the `CatRoot` walk this entry priced.
>
> **Proved in both directions, against the real seams:** `hook-harness --load <dll>` puts a named module
> into the target before the guard looks. The NuGet copy of the CI blocker → **Allowed**, Overlay
> injected (skipped loudly on a machine with no NuGet cache; the managed integration cases are the gate
> that cannot skip it). Our own unsigned Overlay copied under a `protect`-bearing name outside the
> guard's directory → **SuspiciousUnsigned**, naming it, nothing injected. Nine fake-seam cases pin the
> decision (both lists, the target, kFailed, missing seam, pathless, load order, exact-hit precedence).
> **And `-SkipIntegration` is gone from `ci.yml` in the same PR**: the nine `Category=Integration`
> cases are in the merge gate for the first time since 2026-08-05, and CI runs the same
> `./build.ps1 check` a developer does. The switch stays in `build.ps1`, loud, for whoever must.
**(c) `signerField` and `action` are required by the schema and parsed by
nobody.** Both are `required` in `detection-rules.schema.json`, both carry
@@ -2203,6 +2388,17 @@ configurable and never was; the field that would express it has no consumer.
> `warn_and_refuse` — a predicate whose answer changes nothing observable, which
> is the defect class this file exists to record. Wiring it means first deciding
> that `warn` or `allow` may exist, and CLAUDE.md rule 2 says they may not.
>
> #### ✅ Resolved 2026-09-06 — the consumer is the validator, and the policy is code by rule
>
> Decided the way the paragraph above costs it: `warn` and `allow` do not exist (CLAUDE.md
> rule 2), and the signer field is `O=` by measurement (`19_SAFETY`), so neither field is
> for the guard to read — they exist so that the DATA cannot claim otherwise. What was
> missing was the thing that makes that true: `rules-validate` now carries a third canary
> that mutates the shipped document to `action: "allow"` and to `signerField: "CN"` and
> requires the schema to reject both. Delete either `const` and the gate goes red. The
> guard's hardcoded refusal is the specification, and `IsCompiledTrustedSigner` (§S19(b))
> made the other half of the heuristic code-bounded the same day.
**(d) ◐ The fragment list has unreconciled copies — more than three. The runtime
hole is CLOSED.** `rules/detection-rules.json`, `guard_test.cpp` (the inline
@@ -2363,6 +2559,14 @@ disproved:
with validate-then-replace; none of it exists. So **FR-7.3 is unmet**: anti-cheat
entries cannot reach a machine on their own schedule, only with a release. A
rules edit still changes nothing on any installed machine until the next build.
> **🅓 Deferred to P4, rationale written 2026-09-06.** The feed is the product's one
> permitted outbound request after the release check (CLAUDE.md rule 8), and it needs
> three things P0 does not have: a shipped Agent to run it in, the signing §S4 defers to
> the same phase, and the privacy policy's rows that describe it (`legal/PRIVACY_POLICY.md`
> already flags them as describing a request the software does not make). Until then a
> rules edit reaches a machine with the next release, whose checksum attests it — a slower
> delivery, not a weaker gate. FR-7.3 stays unmet and stays written as unmet.
- **No binary/data handshake inside the guard.** `ParseRules` still walks only the
`anticheat` subtree and never reads `schemaVersion` or `rulesVersion`. Teaching
it to refuse an unknown version would be a second machine-wide refusal lever
@@ -2782,7 +2986,7 @@ required contexts are exactly `check`, `analyze (csharp, none)` and
the gate that exists to make the anti-cheat blocklist un-removable is advisory.
Fixing it is a branch-protection change, i.e. the owner's, not a code change.
**3. `08_UI` describes a refusal notice that is wrong in the commonest case.** It
**3. 🅓 Deferred to P3, rationale written 2026-09-06 — `08_UI` describes a refusal notice that is wrong in the commonest case.** *(The requirement below must reach `08_UI` and the `Safety_*` keys in the PR that creates the first refusal UI, and not before: there is no UI to be wrong in yet, and a `.resx` string with no view is the kind of fix that reads as done. The spike log carries the measurement; this line is the reminder.)* It
promises "the specific signal named in plain language". Measured (`spike-notes`
§13): while any Easy Anti-Cheat title is running, **every** target — including a
freshly spawned, unrelated process — refuses with `BlockedService` naming
@@ -2868,6 +3072,15 @@ gate.
> four-going-on-five unimplemented promises, and now this file's bundling audit —
> remain hand-maintained prose that nothing verifies. A gate over one table is not
> a gate over `legal/`.
>
> **✅ Closed 2026-09-06, by making there be one block.** `legal/ACCURACY.md` is the single
> statement of what the software measures, dated; `README.md` and `legal/DISCLAIMER.md` §4
> embed it verbatim between markers, and `tools/accuracy-check.ps1` — a `build.ps1` gate with
> a four-case self-test, both directions — fails when any copy differs from the source, when
> a copy has no markers, or when the source is empty. What the gate does NOT do is decide
> whether the block is true; that stays with whoever changes the Overlay or the capture host,
> and the block's own comment says so. The block was rewritten to 2026-09-06 truth in the same
> PR (the previous §4 note still said frame generation and ray tracing had no hook).
### S14 ◐ · Pre-injection check 3 is **unwired**, and has no "cannot determine" state
@@ -2925,6 +3138,13 @@ nothing.
> "fix" (2) by widening the ABI.** The route is the metadata extractors plus a
> guard-side resolver, which is its own PR and its own fail-closed matrix row.
>
> **🅓 The store-id half is deferred to P4, rationale written 2026-09-06.** Its only
> in-policy route is the platform metadata extractors (Steam/GOG/Epic/itch — P4's library
> import) feeding a guard-side resolver, and a resolver with no extractor behind it would
> refuse every title (an unresolved id refuses, by the matrix). The executable half is
> wired and proven red; the data for both halves is empty by decision. Cost of waiting:
> none — no title is blocked by store id today because none is listed.
>
> Proven red: disarming the matcher makes the guard **allow** a blocked
> executable, and the test asserts `kBlockedExecutable` specifically rather than
> "it refused" — which is indistinguishable from the four refusals the guard
@@ -2967,9 +3187,32 @@ Two decisions, both the owner's:
Until both are answered the inertness is recorded in the data's own `$comment`
and beside check 3, rather than being inferable only from two empty arrays.
### S6 · The 30 s scan window is the weakest part of the most important behavior
### S6 ✅ · The 30 s scan window is the weakest part of the most important behavior — **the in-process half built 2026-09-06 (P1 item 1)**
Now disclosed honestly in the Disclaimer and README. The open question is whether
> **Built, as the deferral below said it would be: one detour, both jobs.** `kernelbase.dll!LoadLibraryExW`
> is patched from `InitThread` after the present hooks; the body calls the original first, skips
> data-file / resource mappings, reads the mapped module's own file name into a stack buffer and compares
> its base name (a) against `FL_HOOK_INVENTORY` + `FL_RUNTIME_CENSUS` — a match bumps a 15-bit wake count
> and signals the watchdog's auto-reset event, so the lazy installers run **within milliseconds** rather
> than on the next 1 Hz tick — and (b) against the compiled floor's MODULE families (prefix, case-
> insensitive, the generated table the guard itself carries; zero allocation) — a match CASes the family's
> 1-based index into `earlyStopFamily`, and the present path (`MayObserve`) or the watchdog, whichever is
> first, calls `StopObserving(FL_STATUS_STOPPED_BLOCKLISTED)`. It supplements the poll and replaces
> nothing; it installs nothing inline (§H2). **Measured**, real Overlay in a real target (ctest `fl_guard`):
> a late `sl.interposer.dll` hooked **94 ms** after it appeared (bound 500 ms, which the tick alone cannot
> meet more than half the time); a decoy copied to `EasyAntiCheat_fl_fixture.dll` and loaded 2.5 s in
> stopped the Overlay with `earlyStopFamily` equal to the index the test computed from the same generated
> table, `unhookRequested` still 0, and `writeIndex` frozen thereafter. The CaptureHost reads both words
> (`Consume/EarlyStop.cs`), ends the session as `WriterStoppedBlocklisted` (exit 5, the safety-stop code)
> and names the family from the staged rules file.
>
> **What it does not do, stated so the disclosure stays honest:** the fragment tier and the signer tier
> are not in the detour, so a module the floor knows only that way waits for the host's 30 s scan; the
> Disclaimer's "within 30 seconds" is unchanged. **Owed:** the real-game leg of §H2 — a title that loads
> D3D12 or Streamline lazily, hooked through the wake rather than the tick — which the next captures
> report via the `loader detour:` line (`woke the watchdog N time(s)`).
Now disclosed honestly in the Disclaimer and README. The open question ~~is~~ was whether
to shrink it.
> **"Already installs" was false, and it changed how this item read.** Corrected
@@ -3010,6 +3253,17 @@ acceptable in that hook under the no-allocation rule (it should be), and a
decision on whether it supplements or replaces the poll. Supplements — the poll
also catches modules loaded before we hooked.
> #### 🅓 Deferred to P1, rationale written 2026-09-06 (owner: "theo bảng")
>
> The mechanism is a `LoadLibrary` hook inside the Overlay raising the control-block flag
> the moment a blocklisted module name loads, supplementing the 30 s poll. It is specified
> (`17_HOOK_ENGINE` §DLL entry, deferred install per §H2) and it needs the P1 hook layer's
> `LoadLibrary` detour to hang on — the same detour lazily loaded graphics DLLs need — so
> building it in P0 would mean building that detour twice. The cost of waiting is the one
> the Disclaimer already discloses: up to 30 s between a mid-session load and the stop.
> Not closed: the name comparison in that hook must be against the compiled floor
> families and allocation-free, and it supplements the poll rather than replacing it.
### S7 ✅ · Guard handle rights and WOW64 — **closed**
Measured unelevated 2026-08-02 by `src/native/tools/fl-probe-guard` (ctest
@@ -3127,7 +3381,355 @@ lazily, which is the case the hook exists for. Until then, keep the rule and do
not let anyone "simplify" it back to an inline install on the grounds that the
probe never showed a deadlock.
### H5 ◐ · Proxy swapchains defeat the dummy-vtable assumption
> **The deferred path is built and exercised in a fixture (2026-09-06, P1 item 1 — §S6).** The detour
> signals an auto-reset event the watchdog waits on with its 1 s timeout; it never calls MinHook.
> ctest `fl_guard` `[loader]` loads `sl.interposer.dll` into a presenting harness 2.3 s after start and
> sees the hook family within 94 ms, wake count ≥ 1, no fault, no stop. **Still owed, unchanged:** the
> real-game leg — a title that pulls Streamline or D3D12 in lazily, hooked through the wake — which the
> `loader detour:` report line will show as a non-zero wake count with the family present from the first
> bucket.
### H5 ✅ · Proxy swapchains defeat the dummy-vtable assumption — **the DLSS / DLSS-G question closed 2026-09-06 (owner)**
> **CLOSED 2026-09-06, 12:17, on Cronos: The New Dawn demo with frame generation ON (`spike-notes` §9).**
> The second Streamline 2.8.0 title, UE: `Native FPS: 86.8 -> Displayed FPS: 172.72 (x1.99 FG)`,
> `unseen=0 over samples=10063`, `frame generation: DlssG — the NVIDIA driver agrees`, `upscaler: Dlss
> (driver-reported)`, RT Yes. **So the pacer that bypasses the patched `Present` bodies is Dying Light:
> The Beast's integration, not SDK 2.8.0's** — 2.8.0 on UE presents its generated frames through the body
> the inline patches cover, exactly as 2.7.x and 2.10.x do. Every measured title now prints the rule-6 trio
> or a counted `none`, on NVIDIA through one of three producers: the hooked bodies (Cyberpunk, Hell Is Us,
> Expedition 33, Wukong, Rune Factory, Onimusha, Cronos), DXGI's own counter where the hook cannot count
> (DL:TB), or a withheld `N/A` only when that counter was never read. Identity comes from the tags (DLSS-G)
> and the hooks, and from the driver's per-process word where no hook can see it (the NGX-direct titles),
> with the negative measured. **What stays unlocalised and is not needed for any number the report
> prints:** which body DL:TB's pacer reaches. The owner closed the item on this reading; the sub-items
> below are its history.
> ### CASE 3 HAS A CANDIDATE TITLE — Dying Light: The Beast, Streamline 2.8.0, DLSS Frame Generation ON, 2026-09-05
>
> **The numbers.** Five 58 s captures at DLSS with DLSS Frame Generation on (the owner's
> setting, confirmed after the runs): `presents = tokens = batches` on every one —
> 4706 / 4258 / 4560 / 4311 / 3441 — so the report printed `FPS: 80.41 / 72.73 / 77.69 /
> 73.64 / 58.87` and **`frame generation: none`**, with `sl.dlss_g.dll` and `nvngx_dlssg.dll`
> (310.6) in the census. The fifth ran on the #116 build, 2026-09-05 00:53. **Owner decision
> the same night: a separate session and a separate PR own this; nothing below is started
> until the discriminator has a reading.**
> **The same title with FSR frame generation on** read presents 8255 against 4129 tokens
> (×2, the loader row, §H11 R6). **Cyberpunk 2077 on Streamline 2.7.1 with the same DLSS-G
> generation (310.8), same GPU,** read presents 13706 against 3439 tokens (×3.99) on 2026-09-03.
>
> **What that means, stated as the two readings the record cannot separate.** Either (a)
> Streamline 2.8's DLSS-G presents its generated frames on a path the class-vtable hook on
> `Present`/`Present1` does not see — case 3 of this entry, realised, with the application
> frames still counted by `slGetNewFrameToken` and the generated ones simply absent — or (b)
> the title was not generating in those runs despite the setting. **The discriminator is the
> owner's counter reading**: an in-game or Steam frame counter near 2× our `FPS:` line is (a);
> one near our line is (b). It is pre-committed here so the next run answers it rather than
> being read into whichever reading is more comfortable.
>
> **Why this is a rule-6 exposure and not a curiosity.** `none` there is computed —
> `presents == application frames` — and under reading (a) that equality holds *because*
> the generated presents are missing, so the report states the absence of frame generation on
> a title that is generating. The consumer cannot tell this from a real off. Until the
> discriminator runs, a `none` on a Streamline 2.8 title with DLSS-G in the census is a
> **count**, not a verdict, and `03_METRICS` §FG has no wording for that case yet. This is the
> §H5 outcome the entry was written to fear, on a newer Streamline than the one that measured
> it not happening; whether the fix is a wording, a census-version gate (the interposer's file
> version is ours to read — it is a module in our process, not game memory), or a second
> present sink is the owner's decision after the reading. **What is NOT in doubt:** the
> Streamline tag row (`slSetTagForFrame`, #115) is unrelated — this is about presents.
>
> ### THE READING, 2026-09-05 — reading (a), and what landed on it
>
> The owner, verbatim: *"Trong game là DLSS X 4, steam đã hiện dlss, frame ghi nhận được
> native/frame gốc chưa frame gen."* — the title is at DLSS ×4 (multi-frame generation), the Steam
> overlay shows DLSS, and the frames this hook records are the native ones, before frame
> generation. That is reading **(a)**: case 3 realised on Streamline 2.8.0. The numeric counter
> value was not part of the reading and is the first thing the session below writes down.
>
> **The record already corroborated it, in a field nobody had read for this purpose.** The RT
> census on the DLSS ×4 runs reads **97.1 % of all presents RT-active**; the same title with FSR
> frame generation ×2 reads **54.6 %** — generated presents carry no ray-tracing work, so at ×2
> half of them are RT-silent. A window in which every present carries RT work is a window that
> holds no generated presents. Both readings of the count predicted that; only the owner's
> reading says which.
>
> **What landed (PR-A1, C# only, nothing on the present path):**
>
> - The capture host takes an **out-of-process module snapshot** beside every guard scan —
> `Process.Modules`, the loader's list through documented PSAPI, the same read the guard
> already performs on every target — and the file's version resource on the path it names.
> The report prints one `module:` line per census-named module (version, path). The census
> cannot carry a version without a layout change; this can, at no cost in the hook.
> - `MeasuredFacts` **withholds `none`** when `sl.dlss_g.dll` is in the census beside an
> interposer whose file version is ≥ 2.8.0 or could not be read, and the report prints
> `Presented FPS` with a qualifier: the number counts APPLICATION frames; whether frames were
> generated, and the Displayed rate, are unknown. **The key is the Streamline plugin, not
> `nvngx_dlssg.dll`:** every validated `none` on this machine — Cyberpunk off / ×3 / ×4 at 2.7.1
> (census `0x5793D`), Expedition 33 and Lies of P with frame generation off — has the NGX
> module loaded and the plugin bit CLEAR; every DL:TB run (`0x25F0F` / `0x25F4F`) has it SET.
> The gate leaves each validated result byte-identical, and eight consumer cases pin that.
> - **Cost, pre-committed:** DL:TB at DLSS with frame generation **off** also reads withheld if
> the plugin is a startup-time load on this title. Leg 0 below measures which.
>
> **The session, pre-committed before it runs.** One owner session, one launch per leg, the
> capture host as built plus **PresentMon 2.5.1 console, elevated, concurrently** (it is retired
> as a shipped rung — §S31 row P2 — and is still the one instrument on this box that counts
> presents from the kernel's side; on Cyberpunk it counted every generated present at the same
> rate as this hook), plus the title's own FPS counter and the Steam overlay counter read by
> eye mid-capture and written down **as numbers**. Read off our report: `FPS:` / `Presented FPS`,
> `FG counts` (`presents=`, `tokens=`, `streams=`), the `module:` lines. Read off PresentMon:
> rows over span, the number of distinct `SwapChainAddress` values, `PresentRuntime` and
> `PresentMode`.
>
> | Leg | Title / setting | What it settles |
> |---|---|---|
> | 0 | DL:TB, DLSS, DLSS FG **off** | whether `sl.dlss_g.dll` is in the census with FG off (per-setting vs startup); ours ≈ PresentMon ≈ counter ≈ 1× |
> | 1 | DL:TB, DLSS, DLSS FG **×4** | the discriminating leg |
> | 2 | Cyberpunk 2077, DLSS, MFG ×4 (Streamline 2.7.1) | control on the same build: ours ≈ PresentMon ≈ 4× tokens, `x3.99 FG` printed, `module: sl.interposer.dll 2.7.1.0`, plugin bit clear |
>
> **Leg 1, the counter half, READ 2026-09-05** (owner's run on #118, `dyinglightbeast-141045`):
> DLSS FG ×4, our line `Presented FPS: 76.7` with `none` withheld exactly as built, the title's own
> counter **~300** — 3.9× ours. Reading (a) now has its number. The same day's `-105050` run read
> 93.24 on the same shape. **Still owed from this table:** the PresentMon leg beside it (which
> decides P1 against P3, i.e. whether the generated presents are kernel-visible at all), Leg 0
> (whether `sl.dlss_g.dll` is a startup load), and Leg 2's control. Also the same day, Cyberpunk
> at DLSS + RR + MFG ×3 read `62.86 → 187.49 (×2.98 FG)`, `frame generation: Active (technology not
> identified)` — the count is right and the technology is unnamed, because `kFeatureDLSS_G` is
> never evaluated through the export this build hooks; and the four UE titles at DLSS read
> `upscaler: N/A` (Lies of P, Hell Is Us, Expedition 33, Wukong: NGX-direct super-resolution, the
> Streamline interposer loaded and idle for it). **These three shapes — hidden presents on SL 2.8,
> an unnamed DLSS-G, and an unnamed NGX-direct DLSS — are one question with one candidate answer
> that is not a hook:** `NvAPI_NGX_GetNGXOverrideState` (NVAPI, MIT, vendored; R570+) takes a
> PROCESS ID and returns the driver's own feedback bits per feature — SR / RR / FG each with
> `DLL_LOADED`, `CREATED`, `EVALUATE`, `FG_MODE`, `FG_MULTI_FRAME` — plus `scalingRatio`,
> `performanceMode` (the quality mode), `renderPreset`, `frameGenerationCount` and
> `frameGenerationMode`. Out of process, from the driver's bookkeeping, whatever route the title
> took to NGX. **Unmeasured, and measured before anything is built on it:** whether the bits are
> populated for a process with no NVIDIA-app override configured (the API's name says "override"),
> and whether `frameGenerationCount` is the title's multiplier or only an override target.
> `fl-probe-nvapi --ngx-state <pid>` prints the raw words and every decoded bit; the owner runs it
> against Lies of P (DLSS, no FG), Hell Is Us (DLSS + FG ×4), Dying Light: The Beast (DLSS FG ×4)
> and Cyberpunk (MFG), each while the title runs — no capture, no injection, no consent needed.
> **The decision it opens is the owner's:** a driver-reported fact is neither a hooked argument
> (rule 4) nor a static hint (`05_DETECTION`); if the probe answers, `03_METRICS` needs a
> *driver-reported* rung with its own wording ("reported by the NVIDIA driver, not counted"), and
> the rule-6 pair on the hidden-presents shape could then read *application frames counted ×
> multiplier reported* — labelled as such, never as a measured Displayed.
>
> **MEASURED 2026-09-06 morning, three titles, driver 616.64 (`spike-notes` §9): the bits ARE populated
> without an override, for super resolution only.**
>
> | Title (override?) | SR feedback | RR feedback | FG feedback | ratio / mode / preset / fgCount |
> |---|---|---|---|---|
> | Hell Is Us (none), DLSS + **DLSS-G ×4 running** | `0x80605` INITIALIZED DLL_EXISTS **CREATED EVALUATE** ERR_NOT_FOUND | INITIALIZED DLL_EXISTS ERR_NOT_FOUND | `0x5` INITIALIZED DLL_EXISTS — **no CREATED / EVALUATE / FG_MODE** | 0 / 0 / 0 / 0 |
> | Expedition 33 (NVIDIA-app override ON), FG off | `0x8067F` … ENABLED DLL_LOADED DLL_SELECTED PRESET PERF_MODE **CREATED EVALUATE** ERR_NOT_FOUND | INITIALIZED DLL_EXISTS ERR_NOT_FOUND | `0x1F` INITIALIZED ENABLED DLL_EXISTS DLL_LOADED DLL_SELECTED | 0 / **2** / **11** / 0 |
> | Lies of P (none), DLSS, no FG | `0x605` INITIALIZED DLL_EXISTS **CREATED EVALUATE** | INITIALIZED ERR_FAILED ERR_NOT_FOUND | INITIALIZED ERR_FAILED ERR_NOT_FOUND | 0 / 0 / 0 / 0 |
>
> Four readings. **(1) `CREATED | EVALUATE` on the SR word is set on both no-override titles** — the
> driver keeps per-process bookkeeping of the NGX super-resolution feature whatever route the title took,
> which is exactly the identity `upscaler: N/A` lacks on the NGX-direct titles (all three print it). **(2)
> The FG word does NOT reflect DLSS-G activity:** Hell Is Us was generating at ×4 through Streamline
> (`83.21 → 332.82 (×4 FG)`, `DlssG`, the same session) and its FG word says INITIALIZED | DLL_EXISTS and
> nothing more — the word tracks the override machinery's DLL, not the plugin's evaluations. Frame
> generation stays with the tags and the count. **(3) `frameGenerationCount` is 0 on every title,
> including the one at ×4 — it is the override target the header names, never the title's multiplier**,
> so the "application frames counted × multiplier reported" pair above has no producer and is dropped.
> **(4) `scalingRatio` is 0 everywhere, override included; `performanceMode` / `renderPreset` are
> populated only under the override (E33: 2 / 11) and are then the OVERRIDE's values, not the title's** —
> so this route gives an identity and nothing about the render size or quality. `ERR_NOT_FOUND` sits
> beside CREATED | EVALUATE on two titles and is absent on the third; the header does not say what it
> refers to (a DRS profile, most likely), and it is not read as anything.
>
> **What a driver-reported rung may therefore claim — the owner's decision, not yet built:** on a
> session where every hook says `upscaler: N/A`, `Dlss (driver-reported: the NVIDIA driver reports an
> NGX super-resolution feature created and evaluated in this process — not counted by this hook)`. It
> may name the vendor and the feature; it may not state a quality, a ratio, a render size, a frame
> generation mode or a multiplier. On a hooked-identity session (Cyberpunk, DL:TB, Onimusha) the word
> is a consistency check the report prints beside the hooked name. **Owed before it is built — the
> negative:** the probe on Lies of P or Hell Is Us with DLSS switched OFF in the menu, expected
> `CREATED` clear; a rung that has only ever seen the positive would be the census's mistake again.
> Plumbing when decided: the probe already builds against `fl_nvapi`; the capture host would call it
> beside each module snapshot (out of process, no consent needed) or, if it goes in-process, through
> `Infrastructure` only (CLAUDE.md: no P/Invoke elsewhere).
>
> **BUILT 2026-09-06, on the owner's decision ("nối probe để bắt đầu").** The capture host spawns
> `fl-probe-nvapi --ngx-state <pid>` beside every module snapshot (the probe prints one machine line,
> `NGXSTATE status=… sr=0x… …`, and is staged beside the host by the project file), merges the readings
> (the last answered word is the state; a change between readings is printed, never averaged) and
> prints `NVIDIA driver NGX state:` in the runtime block. `03_METRICS` §Upscaling carries the rung and
> its limits. **Pre-committed, read off the next run:**
>
> | Row | Title / setting | Expected | Else |
> |---|---|---|---|
> | **N1** | Lies of P, Hell Is Us, Expedition 33 at DLSS | `upscaler: Dlss (driver-reported: …)` | a `CREATED \| EVALUATE` word beside `N/A` is a parser or plumbing defect — localise |
> | **N2** | Cyberpunk, DL:TB, Onimusha (hooked `Dlss`) | `upscaler: Dlss — the NVIDIA driver agrees …` | a disagreement WARNING is printed as such; it is not resolved by preferring either |
> | **N3** | **the negative, still owed:** Lies of P with DLSS switched OFF in the menu | `CREATED` clear → `upscaler: N/A (…) — the NVIDIA driver reports no NGX super-resolution feature created …` | `CREATED \| EVALUATE` still set with DLSS off → **the rung is withdrawn** (the bit is a session-lifetime latch, not a state) and the line goes back to N/A |
> | **N4** | a title at FSR / XeSS with no NGX feature | `Fsr3` / `N/A` with the driver's negative beside it | `CREATED` set on a title with no DLSS in its menu → withdraw |
>
> Lies of P has no DLSS Frame Generation (owner, 2026-09-06), which is why its FG word reads
> `ERR_FAILED ERR_NOT_FOUND`: nothing to load.
>
> **LANDED 2026-09-06, 10:39–11:36 (`spike-notes` §9): N1, N2 and N3 as pre-committed, N4 in a shape the
> row did not foresee, and one correction.** N3 first, because it decides: the standalone probe on Lies of
> P with upscaling OFF read `SR 0x5` — `CREATED` clear — and with DLSS on `0x605`; **the rung stands.** N1:
> Lies of P, Expedition 33, Hell Is Us and the new Cronos: The New Dawn demo all print
> `upscaler: Dlss (driver-reported: …)` where they printed `N/A`. N2: Onimusha and DL:TB print
> `upscaler: Dlss — the NVIDIA driver agrees`. N4 arrived as DL:TB at **FSR upscaling + DLSS Frame
> Generation**: `upscaler: FSR (3.1 or 4 …)`, `2560x1440 -> 2560x1440`, `SR 0x205` — CREATED without
> EVALUATE, so the driver's word correctly does NOT claim DLSS beside FSR (the rung needs both bits).
> **The correction:** the FG word is NOT blind to DLSS-G. It read `CREATED | EVALUATE` on Hell Is Us,
> Onimusha and DL:TB at ×4, and *"the words CHANGED between readings"* on all three — the morning's
> `INITIALIZED | DLL_EXISTS` on Hell Is Us was a first reading taken before the feature came up.
> `FG_MODE` / `FG_MULTI_FRAME` stay clear and `fgCount` is 0 at ×4, so it names the feature and never the
> multiplier: printed beside `frame generation:` as agreement, promoted to `DlssG (driver-reported)` only
> where the count is active and no tag named the technology. Also on this run: Cronos is a **second
> Streamline 2.8.0 title** (UE, FG off, `sl.dlss_g.dll` absent from its census — per-setting there — `FPS
> 105.01`, `none` with DXGI agreeing); its FG-on capture would say whether the 2.8.0 pacer bypass is the
> SDK's or Techland's. And the FSR + DLSS-G session's factor was refused (bucket 8 of 8 at 1.96 against
> 2.85 — the guard working) while the qualifier said *"no evaluation was observed"* beside 4,415 tokens; the
> qualifier now says the factor was counted and refused, and that DXGI counted 8,174 presents this hook
> never saw so the Displayed rate is above the printed one.
>
> **The last row, 12:17 — Cronos with frame generation ON: `86.8 → 172.72 (×1.99 FG)`, `unseen=0`, `DlssG`
> with the driver agreeing.** The 2.8.0 pacer bypass is Techland's, not the SDK's. Closed above.
>
> ### THE STREAMLINE DOCS, READ 2026-09-05 (v2.8.0 and main), AND WHAT THEY CHANGED
>
> The owner asked for the vendor's own guides before any rewrite. Three things in them decide this item.
>
> 1. **DLSS-G presents through the "SL pacer"** (DLSS-G guide §14.1): an asynchronous presentation
> mechanism, with *"specialized hardware to delay the image after Present() has been called"* and a
> note that `MsBetweenPresents` in third-party tools *"indicates when the internal Present() call has
> happened"*. So the generated frames ARE presented by internal `Present()` calls on 2.7.1 — which is
> what this hook counts on Cyberpunk — and whether 2.8's pacer on Blackwell still reaches the body we
> patch is exactly what Leg 1's PresentMon half measures. The docs do not say; they say FrameView 16.1
> is the recommended tool because it reads `MsBetweenDisplayChange`, i.e. the display side.
> 2. **`slDLSSGGetState` is the documented way to get the presented count** (§14.0: `actualFPS = myFPS *
> state.numFramesActuallyPresented`) — and it is **refused here**, with the reason in `03_METRICS` §FG:
> the header defines the field as *"number of frames presented since the last `slDLSSGGetState` call"*,
> so every call RESETS the plugin's counter, and a title that reads it for its own FPS display would
> read our calls' remainder. It is also marked *"NOT thread safe"*. A measurement that alters the
> host's measurement is not observing.
> 3. **§5.0 "Tag all required resources": DLSS-G requires the HUD-less and UI buffers to be tagged every
> frame** through `slSetTag` / `slSetTagForFrame` / `slEvaluateFeature`'s inputs — the three routes this
> build already hooks and read ONE tag type from. **Built the same day:** every tag's type is recorded
> (`FlWriterState.slTagCensus`, per route), a HUD-less or UI tag drained by a present marks it
> `FL_FG_DLSS_G`, and the consumer names `DlssG` beside an active count. Identity, not a count: the
> count still decides `none`, so a title tagging the inputs with the feature off prints `none` with the
> inputs noted, and the withheld shape keeps its N/A.
>
> **Pre-committed for the next run, per title:** Cyberpunk at DLSS + MFG → `frame generation: DlssG`,
> tag census `global=[depth, mvec, hudless, ui-color-alpha, …]` (2.7.1 tags globally; the scaling input
> arrives locally). Hell Is Us / Expedition 33 / Wukong at DLSS + FG ×4 → `DlssG` **if** the UE Streamline
> plugin tags through the exports (their `UpscalerParams = 0` says no scaling-input tag arrived, which is
> consistent with NGX-direct super-resolution and says nothing about the DLSS-G inputs); if the census
> reads `global=[-] frame=[-] local=[-]` on those titles, they tag through neither export and the identity
> stays `Active (technology not identified)` honestly. DL:TB at DLSS FG ×4 → the census line says whether
> the title feeds DLSS-G through a route this build sees; the qualifier then says *"FEEDING frame
> generation"* beside the withheld count. Lies of P at DLSS (no Streamline tokens at all) → unchanged:
> the super-resolution identity on NGX-direct titles is what the NVAPI probe above is for.
>
> **LANDED 2026-09-05 evening, on the owner's run on #121 (`spike-notes` §9):** `frame generation: DlssG` on
> Hell Is Us (×4, twice), Expedition 33 (×1.97), Wukong (×4), Rune Factory (×3.98) and Cyberpunk — every
> Streamline title tags the DLSS-G inputs through a route this build hooks (the UE plugin and Cyberpunk 2.7.1
> globally, DL:TB 2.8 through `slSetTagForFrame`), so the identity is measured six of six and *"technology
> not identified"* is gone from all of them. DL:TB's withheld line now says *"FEEDING frame generation"*
> beside the count it cannot make; its census also shows a `scaling-in` tag on the frame route with
> `UpscalerParams` still 0 — the tag carries no size on this title, which closes 7a's last question without
> the layout bump it was thought to need. Cyberpunk's factor was refused on that run (bucket 1 at 3.0 against
> 1.67 overall, `tokens/batch 2.97`): a mixed session, refused as designed rather than averaged. **What is
> left on NVIDIA is one thing: `upscaler: N/A` on the NGX-direct titles** — the probe above.
>
> **BUILT 2026-09-05, late — A1.7 promoted from "not in A1" to the in-process half of Leg 1.** The owner
> read that Streamline ≥ 2.8 "needs `sl.interposer.dll` and `sl.common.dll` loaded before an injection
> succeeds". Checked against the source, not the claim: the interposer's DXGI proxy
> (`source/core/sl.interposer/d3d12/dxgiSwapchain.cpp`) is **byte-for-byte the same file at v2.7.32 and
> v2.8.0** — plugins' before-hooks receive `m_base` and may `skip` the base call, exactly as before — and
> 2.8's `sl.common` gains `resourceTaggingForFrame.cpp` (the `slSetTagForFrame` route #121 already hooks).
> Injection into DL:TB already succeeds (every capture there has `streams=1`, a full `runtime census`, a
> tag census), so "loaded before injection" is a launcher's problem, not this hook's. What 2.8 does NOT
> show is where its closed `sl.dlss_g` pacer presents. So the Overlay now asks DXGI itself: on every hooked
> present it reads `IDXGISwapChain::GetLastPresentCount` on the chain it just saw (rule 4: the same object
> `FindOrAdd` already calls `GetDesc` on) and publishes two words on the 1 Hz watchdog —
> `dxgiPresentSamples` (hooked presents that read it) and `dxgiPresentsUnseen` (presents DXGI counted
> between two hooked ones, beyond the one seen). The report prints
> `DXGI present counter: unseen=M over samples=N (r unseen per hooked present)` and the withheld qualifier
> carries the reading. The harness's own presents are the negative control (`fl_guard` `[fg]`:
> `unseen == 0`, `samples >= drained`); the positive cannot be fixtured — nothing in this repo presents
> through a body the inline patches miss — which is why the rows below are written before the run.
> Cost: one virtual call per hooked present, measured by `hook-harness --probe-frames` (number in the PR
> body); `--probe-cost` is the empty-detour floor and does not include it.
>
> Leg 1's in-process rows, read off the new line on a DL:TB DLSS FG ×4 capture (r = unseen / samples):
>
> | Row | Reading | Meaning | Action |
> |---|---|---|---|
> | **P1-DXGI** | r ≈ 3 (×4) — `unseen ≈ 3 × samples` | the pacer presents on the SAME chain through a body the inline patches do not cover; the generated presents ARE DXGI presents | the next PR promotes `Displayed = hooked + unseen`, labelled **DXGI-counted** (a count DXGI made, not this hook), `presents/batch` from it, and `none` withdraws by count; the pacer's entry is then localised (a second `CDXGISwapChain` class, or a path that bypasses `Present`'s body) at leisure |
> | **P3-DXGI** | r ≈ 0 | DXGI counted nothing this hook did not: the generated frames are displayed below DXGI (driver pacing / flip metering) or on an object this hook never saw | the withheld wording stays; no in-process sink exists; only PresentMon (kernel) and the NVAPI corroboration remain, and if PresentMon also reads 1× the frames never were kernel presents |
> | **P5-DXGI** | 0 < r < 2.5, or r ≠ 0 with `streams > 1` | a mixed path or a second chain | stop and localise; the number is printed, never averaged into a factor |
> | **P2/P4** | r ≈ 0 with ours ≈ 4× tokens, or the count itself moved | as the kernel rows say: not generating, or the title changed | the kernel rows above decide |
>
> **LANDED 2026-09-05 night, on the owner's run on #124 (`spike-notes` §9): row P1-DXGI, twice.** DL:TB at
> DLSS FG ×4 read `unseen=12204 over samples=4136 (2.95)` at 21:56 and `unseen=12741 over samples=4392
> (2.90)` at 22:06 — DXGI counted 3.9× the presents this hook did, on the SAME chain, which is the owner's
> ~300 against ours ~75 from the afternoon, now measured in-process. The two controls read 0.00: Hell Is Us
> (Streamline **2.7.3**, `79.89 → 308.14 (×3.86)` through the patched bodies, 18,207 samples) and the
> owner's new title, the **Onimusha: Way of the Sword demo on Streamline 2.10.3** (`60.04 → 220.33
> (×3.67)`, `DlssG`, `upscaler: Dlss`, 12,914 samples, 0 unseen). So **2.8.0's pacer is the odd one** —
> 2.7.x before it and 2.10.x after it present the generated frames through `Present`'s body — and the
> "`sl.interposer.dll` + `sl.common.dll` must be loaded on ≥ 2.8" lead is closed by 2.10.3, which injects,
> tags on the frame route and counts exactly like 2.7. **The pre-committed action is built:** the record
> carries `dxgiUnseen` (@52, `FL_MEASURED_DXGI_PRESENTS`), the window counts `Displayed = hooked +
> unseen` and prints *"Displayed is DXGI-COUNTED"* on its own line, `presents/batch` takes the same
> numerator, and `none` withdraws on DL:TB by count (`03_METRICS` §Displayed may be DXGI-COUNTED). Expected
> on DL:TB's next capture: the trio at ≈ ×3.9 with the label, no withheld line, `frame generation: DlssG`.
> Which body the 2.8.0 pacer reaches stays unlocalised, as the row said.
>
> **LANDED 2026-09-06 morning, on the owner's run on #125 (`spike-notes` §9): the promotion, and Leg 0.**
> DL:TB at DLSS FG ×4 (07:31): `Native FPS: 70.52 -> Displayed FPS: 282.08 (x4 FG) over 16516 present(s)`,
> *"Displayed is DXGI-COUNTED: 12387 of those present(s)"*, `unseen=12483 over samples=4202 (2.97)`,
> `frame generation: DlssG`, uniform across every bucket, no withheld line — the trio rule 6 asks for, on
> the title that could not print it. **Leg 0, twice (07:45, 07:55): frame generation OFF**, census still
> `0x25F0F` — `sl.dlss_g.dll` is a **startup-time load**, the cost paragraph's fear measured true —
> presents = tokens, `unseen=0 over samples=3659` and `4519`, tag census `0x23600` (depth, mvec,
> scaling-in, scaling-out, other: **no hudless / UI tag with FG off**, so the DLSS-G identity is
> per-setting on this title too), and the report withheld `none` exactly as pre-committed. **The gate is
> narrowed rather than withdrawn:** DXGI's counter is the discriminator it lacked — the 2.8.0 pacer's
> presents are DXGI presents on this chain (P1-DXGI), so a counted 1.0 beside a READ counter with zero
> unseen is `none`, printed with DXGI's agreement; withheld only when the counter was not read. Control:
> Expedition 33 FG off (Streamline 2.7.30) reads `FPS: 85.86`, `none` by count, tag census `0x0` — the UE
> plugin sends no tags at all with FG off.
>
> Leg 1's rows (ours = `presents / span`; PM = PresentMon rows / span; C = the counter; ≈ = within 5 %):
>
> | Row | Reading | Meaning | Action |
> |---|---|---|---|
> | **P1** | PM ≈ 4× ours, C ≈ PM | generated presents reach the kernel on a path **outside** the `CDXGISwapChain::Present/Present1` bodies the Overlay inline-patches — case 3 realised | gate stays; a second present sink is costed (candidates below) and the route is the owner's; PresentMon's `SwapChainAddress` count says whether it is a second chain (2 addresses against our `streams=1`) or the same chain by another entry (1) |
> | **P2** | PM ≈ ours ≈ C ≈ 1× | the title was not generating despite the setting | **withdraw the gate** (keep the `module:` lines); `none` was right; case 3 stays unrealised; the owner checks the setting |
> | **P3** | PM ≈ ours ≈ 1×, C ≈ 4× | frames displayed without a kernel-visible present per frame (driver pacing / flip metering), or the counter reports a target rather than a measurement | keep the wording ("Displayed unknown"); no in-process or kernel sink would help; only a vendor read could corroborate |
> | **P4** | ours ≈ 4× tokens on the rerun | the five earlier runs were not generating, or the title changed — compare the `module:` versions and the exe fingerprint against the 00:53 run | withdraw the gate; localise what changed |
> | **P5** | PM ≈ 2×, or two `SwapChainAddress` values with ours `streams=1` | a second chain or a mixed path | stop and localise before deciding |
> | **P6** | elevation refused / a leg unrun | nothing measured | not a result — P2 is not inferred from silence |
>
> Leg 0's own row: if `sl.dlss_g.dll` is **absent** with FG off, the census bit is per-setting on
> this title and the gate is sharper than its cost paragraph feared (consider dropping the version
> conjunct); if present, the interim cost stands as written. **Landed 2026-09-06: PRESENT, twice** —
> and the cost stood for one morning, because the DXGI counter (above) narrowed the gate the same day.
>
> **Second-present-sink candidates for P1 / P5, one line each, none chosen:** MinHook inline
> patches on the `gdi32.dll` D3DKMT thunks (`D3DKMTPresent`, `D3DKMTPresentMultiPlaneOverlay3`,
> `D3DKMTSubmitPresentToHwQueue`) — in-process, no elevation, argument reads only, but
> semi-documented structs that move between Windows builds and more patched bytes on the most
> anti-cheat-sensitive path; an ETW `Microsoft-Windows-DxgKrnl` consumer in the capture host
> (what PresentMon reads) — exact per-pid kernel count, costs **elevation**, which is §G's Tier-2
> question re-entering; an `IDXGIFactory2::CreateSwapChain*` hook (`17_HOOK_ENGINE` ⏳) — sees a
> second chain at creation only, i.e. launch mode (§S1); in-hook `IDXGISwapChain::GetLastPresentCount`
> sampling — a same-chain localiser only, and a hot-path virtual call with two reserved words
> behind it. NVAPI has no present count outside present barrier; `NvAPI_NGX_GetNGXOverrideState`
> (R570, by PID) reports the driver's DLSS override state and multi-frame target, which is
> corroboration rather than a count — an optional `fl-probe-nvapi --ngx-state <pid>` reading on
> Legs 2 then 1, never a gate input.
> ### NARROWED, NOT CLOSED — five real-title captures, 2026-08-15
>
@@ -3302,7 +3904,57 @@ turns a would-be STL throw into `__fastfail`, which SEH cannot intercept
(`spike-notes.md` §H3). The "no throwing STL in hook paths" rule is therefore
load-bearing rather than stylistic.
### H11 ◐ · XeFG and FSR3-FG identity — **AMD built 2026-09-04 through the ffx-api leaves; Intel closed by licence; FSR 3.0 host route deferred**
### H11 ◐ · XeFG and FSR3-FG identity — **AMD built 2026-09-04 through the ffx-api leaves, complete 2026-09-06; Intel closed by licence; FSR 3.0 host route built 2026-09-05**
> **2026-09-06: the AMD half is complete on its oracle** — Lies of P at FSR 3.1 + FSR FG on the #129 build
> prints `Fsr3` / `FsrFg` / `59.77 → 119.55 (×2 FG)` / `2560x1440 -> 2560x1440` with `presents/frame=2.00`,
> `frames/upscale-drained=1.00`, `unseen=0` and the NVIDIA driver's word saying nothing was created
> (`spike-notes` §9); the owner called it done. **Intel, re-checked the same day: the licence has not
> changed** (`18_GPU_VENDOR_APIS` §Intel), so nothing in `libxess*.dll` may be hooked or declared, and the
> signature-free thunk stays refused. **What is left in policy for an XeFG session, proposed and not yet
> built — identity BY ELIMINATION, labelled as such:** frame generation is COUNTED by the Streamline token
> (UE titles request it whatever the FG vendor — measured on Rune Factory's compiled-in FSR) or by DXGI's
> counter; DLSS-G is EXCLUDED by the NVIDIA driver's FG word (no feature created) and by the absence of the
> HUD-less / UI tags; FSR-FG through a shipped DLL is EXCLUDED by the ffx census (no FRAMEGENERATION dispatch
> at any hooked module); the frame-generation runtime the census names is `libxess_fg.dll`. The line would
> read `Active (technology not identified) — by elimination among the runtimes loaded: not DLSS-G (the
> NVIDIA driver reports no NGX frame-generation feature), no FSR dispatch reached a hooked module, and the
> frame-generation runtime present is libxess_fg.dll; a frame generator compiled into the executable would
> read the same`. Never `XeFg` as a measured identity; never a render extent. Intel's README says XeSS-FG
> runs on non-Intel GPUs with SM 6.4, so DL:TB / Hell Is Us / Cronos / Expedition 33 with XeSS FG on are
> the sessions that measure it, and the pre-commitment is the last clause: the wording must survive the
> one static title (Rune Factory at FSR FG) reading the same way.
>
> **BUILT 2026-09-06 (owner: "build cả hai"), with the executable-file scan beside it.** `FgModePrinted`
> carries the elimination sentence on every rung-3 line; `ExecutableMarkerScan` reads the exe on disk once
> after the session and the clear-census qualifier says MAY when a frame-generation-capable SDK string is in
> the file. Expected on an XeFG session (DL:TB / Hell Is Us / Cronos / Expedition 33 with XeSS FG on):
> the trio or a Presented line from the token or DXGI count, and `frame generation: Active (technology not
> identified) — by elimination …: not DLSS-G (…), no FSR frame-generation dispatch …; the frame-generation
> runtime(s) loaded: libxess_fg.dll …`. Expected on Rune Factory at FSR FG: the same shape with *"no
> frame-generation runtime module is loaded at all; the executable itself carries ffxFsr3, …"*. Neither
> prints a vendor as measured.
>
> **LANDED 2026-09-06, 13:45–14:02 (`spike-notes` §9).** **Rune Factory at FSR + FSR FG** reads exactly the
> pre-committed line: `30.05 → 60.05 (×2 FG)` from the Streamline token, `unseen=0` (the compiled-in FSR 3
> presents through the patched body), `frame generation: Active (technology not identified) — by elimination
> …: not DLSS-G (…); no FSR frame-generation dispatch …; the frame-generation runtime(s) loaded:
> nvngx_dlssg.dll; the executable itself carries ffxFsr3, ffxFrameInterpolation — …` — 7b at its ceiling, the
> Steam overlay showing FG where the report shows the count. **Hell Is Us at XeSS + XeSS-FG** (the owner:
> the Steam overlay could not show FG there): `Presented FPS: 186.47`, **`tokens=0`** — this plugin version
> requests no Streamline token at XeSS, where it did at DLSS — so no count and no factor; `unseen=0`, so
> XeFG presents its generated frames through the patched body and the 186 IS the Displayed rate; the driver's
> words clear; the file carries `xefgSwapChain ×13`. The FG line read the bare *"N/A (a hook ran …)"* and the
> upscaler N/A named "a vendor this build does not decode" — both now carry their witnesses: the N/A prints
> the same exclusion clauses (*the frame-generation runtime(s) loaded: nvngx_dlssg.dll, libxess_fg.dll, …;
> the executable itself carries xefgSwapChain*), and the upscaler line says *libxess.dll is loaded, and XeSS
> cannot be hooked or declared under Intel's licence … N/A here by policy, not by ignorance* (7c item 4's
> string change, done). **Cronos at XeSS** (no FG option): `FPS: 110.02`, `none` by count with DXGI agreeing
> — this plugin requests the token at XeSS. **The ceiling for XeFG on a title that requests no token:**
> Displayed measured, Native unknown, vendor by elimination — there is no in-policy application-frame
> producer for XeFG (the token is the plugin's choice; the XeFG API cannot be hooked; the ffx census is
> silent by construction), and the report says so rather than inventing one.
>
> **BUILT, 2026-09-04, the AMD half — and the deferral's own rule was kept: header first, decode
> second, never from observation.** `HANDOFF` item 7c. The FidelityFX headers cleared the
@@ -3344,7 +3996,7 @@ load-bearing rather than stylistic.
> | **Hell Is Us**, FSR, FG off | same | same | `none` | `FPS: 104.18` | 1.00 |
> | **Expedition 33**, FSR upscale + **DLSS frame generation ×3** | UE5, two leaves | `FSR (3.1 or 4 …)`, 1707×961 | `Active (technology not identified)` — no FRAMEGENERATION dispatch, no Streamline token; the count came from the UPSCALE dispatches | `67.51 → 200.66 (×2.97 FG)` | 1.00 (fg-dispatch/frame 0.00) |
> | **Expedition 33**, FSR, FG off | same | same | `none` | `FPS: 85.12` | 1.00 |
> | **Cyberpunk 2077**, FSR 3 + FG | FSR 3.0 host DLLs for upscaling, the **1.1.x monolith for frame generation** | `N/A` (upscale is `ffx_fsr3upscaler_x64.dll`, the deferred route) — render 1506×847 from PREPARE | `FsrFg` (4261 generated batches) | `72.93 → 145.76 (×2)` | — (no UPSCALE dispatch; count = Streamline tokens 4266) |
> | **Cyberpunk 2077**, FSR 3 + FG | FSR 3.0 host DLLs for upscaling, the **1.1.x monolith for frame generation** | `N/A` (upscale is through the FSR 3.0 host DLLs, unhooked on this build; **the host row landed 2026-09-05 — rows B1–B4 below**) — render 1506×847 from PREPARE | `FsrFg` (4261 generated batches) | `72.93 → 145.76 (×2)` | — (no UPSCALE dispatch; count = Streamline tokens 4266) |
> | **Dying Light: The Beast**, FSR + **FSR FG** | loader + two leaves | `N/A` | `N/A` — **zero dispatches at any leaf export** | `Presented 146.54`, WARNING | census: no FSR identity, no FSR_FG |
> | **KCD2**, FSR (×2 runs) | loader + upscaler leaf | `N/A` | `N/A` — zero leaf dispatches | `Presented 58.8`, cannot-include shape (no FG runtime) | — |
> | **Black Myth: Wukong**, FSR | monolith + loader 2.1.0 | `N/A` | `none` (Streamline tokens = presents) — zero leaf dispatches | `FPS: 41.11` | — |
@@ -3381,11 +4033,82 @@ load-bearing rather than stylistic.
> title Streamline's token is there even when the upscaler and FG are AMD's, so the application-frame
> count survives static linking. The identity does not, and cannot.
>
> **Still deferred, with the costing written:** the FSR 3.0 host route — `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale`
> **ROW R6 RUN, 2026-09-04 night, on #111 (one launch each):**
>
> | Title / setting | `upscaler` | `frame generation` | Trio | `frames/upscale-drained` | Verdict |
> |---|---|---|---|---|---|
> | **Dying Light: The Beast**, FSR + FSR FG | `FSR (3.1 or 4 …)`, 1505×847 | `FsrFg` | `70.49 → 140.9 (×2 FG)` | **1.01** (fg-dispatch/frame 0.99) | **R6-accept** — the loader row carries the title the leaf rows could not, at 1×, no double count |
> | **KCD2**, FSR | `FSR (3.1 or 4 …)`, 1505×847 | `none` by count (3523 / 3523) | `FPS: 59.97` | **1.00** | **R6-accept** |
> | **Black Myth: Wukong**, FSR (×2 runs; **the title has no FSR frame-generation option**) | `N/A` | `none` (Streamline tokens = presents) | `FPS: 39.15 / 90.64` | — (no dispatch at the monolith OR the loader) | **not R6 at all** — Rune Factory's shape, see below |
>
> Two of the three loader titles are closed on the first rerun, and the K = 1 control the fixtures
> run is confirmed by a real title: with all four modules hooked, DL:TB's loader route counts
> once. **Wukong is a different shape**: `amd_fidelityfx_dx12.dll` is *loaded* (it is in the census)
> and *never dispatched to*, with the loader silent too, while FSR upscaling is on and Streamline's
> tokens equal the presents. That is Rune Factory's shape with one difference — the monolith is in
> the process — and the reading that fits every number is **FSR upscaling compiled into the UE
> plugin (static, as Rune Factory's) with the 1.1.x monolith loaded for FSR frame generation and
> idle while FG is off.** ~~The leg that tests it is Wukong with FSR frame generation ON~~ —
> **the owner reports the title offers no FSR frame generation at all**, so the monolith is loaded
> for nothing this hook can see (a plugin that ships it and never dispatches to it), and **Wukong
> joins Rune Factory in §Scope decisions' static row**: FSR upscaling compiled into the UE plugin,
> identity out of reach by name, the application-frame count carried by Streamline's token. Nothing
> is owed on it.
>
> ~~**Still deferred, with the costing written:** the FSR 3.0 host route — `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale`
> / `ffxFsr3DispatchFrameGeneration`, named exports, no struct decode for identity — needs ten
> host headers from tag `v1.1.4` (`main` dropped `ffx_fsr3.h`), whose closure reaches
> `<mutex>`/`<shared_mutex>` through `ffx_types.h`, for exactly one installed title (Cyberpunk 2077,
> whose default here is DLSS). Its own PR, with Cyberpunk switched to FSR 3 as the oracle.
> whose default here is DLSS). Its own PR, with Cyberpunk switched to FSR 3 as the oracle.~~
>
> ### THE FSR 3.0 HOST ROUTE IS BUILT, 2026-09-05 — and the costing above named the wrong tag
>
> **`fsr3-v3.0.4`, not `v1.1.4`.** Read off the upstream tags: Cyberpunk's `ffx_fsr3_x64.dll`
> exports twelve `ffxFsr3*` names, which is exactly `fsr3-v3.0.4`'s declaration list; `v1.1.4`
> declares fifteen (adds `ContextGetGpuMemoryUsage`, `ContextDispatchFrameGenerationPrepare`,
> `GetEffectVersion`) and its `FfxFsr3DispatchUpscaleDescription` appends `upscaleSize`, `flags`
> and `frameID` **after `renderSize`** — a detour typed against it would read the wrong bytes off
> the module the title ships. The prefix through `renderSize` is identical across 3.0.3 / 3.0.4 /
> 1.1.4 and is the only field read; `dllmain.cpp` pins its offset to a literal. And **`<mutex>` is
> not in the closure at all** at this tag — `ffx_types.h` includes `<stdint.h>` only; the mutex block
> exists only from 1.1.x. Ten files, no `ffx_message.h`, vendored at
> `src/native/third_party/fidelityfx-fsr3/` (root `LICENSE.txt` = MIT verbatim, inline grants;
> `license-check.ps1` §2e).
>
> **One row, the same family.** `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale` feeds the ffx-api
> drain word: identity `FSR3` as a fact (the 3.0 host hosts nothing else), `renderSize` as the
> extent, and the UPSCALE count when neither Streamline nor a PREPARE has ever spoken. Published by
> `PublishFfxFamilyIfWhole`, which now waits for a loaded host as it waits for a loaded leaf.
> `ffxFsr3DispatchFrameGeneration` is **not** a row: on the one title the monolith generates
> (4261 batches) and the count is Streamline's, and the host's FG export fires per *generated*
> batch. **Reversal, pre-committed:** it becomes a row only on a title reading
> `Active (technology not identified)` with `FL_CENSUS_FFX_FSR3` set and no monolith in the census.
> Fixtures: the `ffx_fsr3_x64.dll` stub (Pass C's second positive control), harness topologies
> `fsr3host` and `fsr3host+mono`, and a `[ffx]` injected case at K = 1 (the double-count control
> for the row) and K ∈ {1, 4} beside the monolith.
>
> **Acceptance, pre-committed — Cyberpunk 2077 (runbook title 3), one launch per leg:**
>
> | Row | Leg / reading | Verdict |
> |---|---|---|
> | **B1** | FSR 3 + FSR FG: `upscaler: Fsr3`; `render 1506x847 -> 2560x1440` with **one** distinct extent (the host's `renderSize` and the monolith's PREPARE agree); `frame generation: FsrFg`; `≈73 → ≈146 (×2 FG)` from tokens; `frames/upscale-drained = 1.00`, `fg-dispatch/frame = 1.00`; `module: ffx_fsr3_x64.dll (no version resource)` | accept |
> | **B1-off** | FSR 3, FG off: `Fsr3`, `none` by count, `frames/upscale-drained = 1.00` | accept |
>
> **B1 and B1-off LANDED, 2026-09-05 (owner's run on #119, `cyberpunk2077-105954` and `-135728`):**
> FSR 3 + FG → `upscaler: Fsr3`, `render 1506x847 upscaler=Fsr3 on 4332 record(s)` (one tuple),
> `frame generation: FsrFg`, `74.31 → 148.56 (×2 FG)`, `frames/upscale-drained = 1.01`,
> `fg-dispatch/frame = 1.00`, `module: ffx_fsr3_x64.dll (no version resource)`; FSR 3 with FG off →
> `Fsr3`, `none` by count (4919 = 4919), `frames/upscale-drained = 1.00`,
> `render -> output: 1506x847 -> 2560x1440 = 1.7x (59% render scale)`. B2–B4 did not fire. **One
> defect the run exposed, in the consumer:** the FG-on leg printed `render -> output: N/A` two lines
> under its own raw block — `UpscaleExtent` keyed its window on the params bit, which under frame
> generation rides on one present in N, so `ClaimedSuffixStart`'s clean-suffix rule found no
> window; it now keys on the identity bit (per-record once live) and counts every record inside
> that carries both sizes. Every FG-on capture since 2026-08-16 had been reading `N/A` there; the
> earlier "not computed yet" wording had hidden it.
> | **B2** | `upscale-drained = 0` with `ffx_fsr3_x64.dll` in the census and FSR on — the game calls `ffx_fsr3upscaler_x64.dll` directly and the facade is silent | add the upscaler-DLL row (`ffxFsr3UpscalerContextDispatch`, ten `FfxResource`s, its own offset pin) **instead** — never both |
> | **B3** | `frames/upscale-drained ≈ 2.00` | two upscale contexts per frame or a re-entered dispatch — investigate before publishing (mirrors R4) |
> | **B4** | `SETTINGS MOVED: 2 distinct extents` | the host and the PREPARE disagree on the input size; print both, do not average |
>
> *The banner as it stood on the morning of 2026-09-04:* **The deferral has a next step, and it is `HANDOFF` item 7c.** The Streamline
> work built every tool this needs — module-scoped inventory rows, types-only vendoring with a
@@ -3396,7 +4119,7 @@ load-bearing rather than stylistic.
> entry names and nobody had made: **run the licence checklist on the FidelityFX and XeSS SDK
> headers.** ~~Both are published under MIT~~ — **run 2026-09-04, and the sentence struck was
> wrong about Intel.** FidelityFX at tag `v1.1.4` is MIT root-and-inline and is clear to vendor
> types-only; the XeSS SDK is the Intel Simplified Software License (binary-only grant,
> types-only (as is `fsr3-v3.0.4`, the tag the host route actually vendored on 2026-09-05); the XeSS SDK is the Intel Simplified Software License (binary-only grant,
> no-reverse-engineering, termination) and its headers say they may not be copied without
> Intel's permission, so step 3 binds and XeSS stays where NGX is. `18_GPU_VENDOR_APIS` §Vendor
> SDKs carries both decisions with the evidence. **So 7c is AMD only.** The one thing that
+184 -17
View File
@@ -31,7 +31,22 @@ and traps**. It deliberately carries **no status**.
## Where P0 actually stands
Two exit criteria remain (`spike-notes.md` §Exit criteria). Do not re-derive them
**P0 is closed (owner, 2026-09-06).** Both criteria read as met in `spike-notes.md`
§Exit criteria — criterion 1 with the quality preset amended to an honest `N/A`,
criterion 2 with §S24 counting zero S-items against it (🚫 S23-2 is a GitHub setting
outside any PR). **What comes next is P1** (`15_ROADMAP` §P1): the Overlay proper —
hook installation for D3D11/12/9/OGL, the `LoadLibrary` detour that §S6's early stop
and lazily loaded runtimes both hang on, unhook path, native logging; the Injector's
launch mode (§S13(c), §S1's deferred input); the Vulkan layer to `vkQueuePresentKHR`
with §S2's in-layer supervision. **P1 item 1 — the `LoadLibrary` detour — landed 2026-09-06
(§S6 ✅); item 2, launch mode, landed the same day as "inject late" (§S1 ◐, §S13(c) ✅ —
`04_CAPTURE` §Launch mode); item 3, the Vulkan layer to `vkQueuePresentKHR` with §S2's in-layer
supervision, landed the same day (§S2 ✅; `17_HOOK_ENGINE` §Vulkan); next is item 4 — the unhook
path, native logging, D3D9 / OpenGL.** The ~~three~~ ~~two~~ one P1-deferred S-item (~~S6~~, ~~S2 part three~~, and
the hand-run blast-radius script behind S29(d)) are the reminders. The text below is
P0's history and stays as it stood.
Two exit criteria ~~remain~~ were the gate (`spike-notes.md` §Exit criteria). Do not re-derive them
from memory:
1. **A throwaway build records a real session** from a real offline game reporting
@@ -197,7 +212,8 @@ own PR with its own rule-4 justification.
watchdog thread runs once a second. No `LoadLibrary` hook is needed for P0 — which
keeps §S6 genuinely separable. The Overlay has **no** module-resolution machinery
today (`GetProcAddress`/`GetModuleHandle` appear nowhere), so that helper is part of
the real cost.
the real cost. *(2026-09-06: the detour exists now — P1 item 1 — and it still only
WAKES that thread; the installers did not move. `17_HOOK_ENGINE` §DLL entry step 3.)*
- `tools/hookinventory-check.ps1`: every symbol the Overlay resolves by name must
appear in `vendor-exports.json`. **No drift exists today** — a refuter resolved every
inventory symbol against all 34 measured modules — so write it as prevention and do
@@ -265,8 +281,14 @@ It is the route `17_HOOK_ENGINE` reads as natural, and it fails five ways:
1. It needs an "indirect" inventory class, which becomes an **unconditional escape hatch
from `hookinventory-check` Pass A** — its oracle would be "a `PFun_*` exists in a
vendored header", and `sl_core_api.h:63` declares `PFun_slSetTagForFrame` for a symbol
**zero measured modules export**. Any name the headers declare could be laundered past
the gate.
~~zero measured modules export~~. Any name the headers declare could be laundered past
the gate. *(2026-09-04: `slSetTagForFrame` IS now exported — by `sl.interposer.dll` 2.8.0,
which Dying Light: The Beast ships — and it entered the inventory the ordinary way, as a row
Pass A checks against the measured oracle. The argument stands: the point was never that
this one symbol was fictional, it was that a header-declared oracle cannot tell the two
apart. The oracle itself needed a fix to see it: `tools/vendor-exports.ps1` took the FIRST
copy of each module name, and with 2.7.1 and 2.8.0 both installed the row's verdict
depended on directory order. It unions across copies now and lists every version seen.)*
2. A second MinHook install site **reopens the install-after-stop window**
`dllmain.cpp:643-646` exists to close.
3. MinHook v1.3.4 has **no function-length oracle for a runtime-returned address**, so a
@@ -684,7 +706,15 @@ FG factor and RT state are measured against the titles' own menus. What follows
owner's list for the next session, in the order the dependencies run, each with what makes
it fail on unmodified `main` — because a criterion already true on `main` is decoration.
#### 7a. The quality preset — the last value criterion 1 lacks
#### ~~7a. The quality preset — the last value criterion 1 lacks~~ — **CLOSED 2026-09-06 (owner): DLSS / DLSS-G done on every measured title**
*Closed on the Cronos FG-on capture (`20_OPEN_QUESTIONS` §H5 head, `spike-notes` §9): the trio or a counted
`none` on every NVIDIA title through the hooked bodies, DXGI's counter where the hook cannot count (DL:TB —
that title's integration, not SDK 2.8.0's), and the driver-reported identity where no hook can see it, with
its negative measured. The quality preset itself stays `0xFF` / N/A everywhere — the override fields are
the override's, the tags carry no size on D3D12 — and the owner closed the item on that. What follows is
the history.*
*Fails on `main` because:* every real title measured reads `upscalerQuality = 0xFF`.
Cyberpunk 2077 never chains `sl::DLSSOptions`, so 0xFF there is the title's truth; **Alan Wake
@@ -694,7 +724,15 @@ Cyberpunk 2077 never chains `sl::DLSSOptions`, so 0xFF there is the title's trut
`quality=` off the `render … quality=… upscaler=…` line. If it reads the preset, criterion 1
is 5 of 5 on that title and this item is a spike-notes entry. If it reads 0xFF too, the
Streamline options route yields nothing on either measured title, and the decision below is
live.
live. *(Runbook title 12 is Alan Wake 2 as of 2026-09-04; Epic may update the executable on
launch, so launch first and grant after.)*
- **The input to that decision is on the report now** (2026-09-04): `render -> output` prints the
two measured sizes, `03_METRICS`' ratio and the render-scale percentage — Cyberpunk reads
`1485x835 -> 2560x1440 = 1.72x (58% render scale)` — plus a **SETTINGS MOVED** flag when the
window held more than one tuple. It prints **no preset name**; that is the decision below,
still the owner's. Every FSR title measured on 2026-09-04 also reads `0xFF` for the quality
byte, and on that route it is the true value rather than a gap: the ffx-api dispatch carries
no quality mode at all, so the derived label is the only route to a preset name for AMD too.
- **The decision, if 0xFF everywhere:** `renderW/H ÷ outputW/H` is *exact* (Cyberpunk: 1485×835
at 2560×1440 = 0.58, which IS DLSS Balanced, and the menu agreed), and DLSS's preset ratios
are documented constants (DLAA 1.0, Quality 0.667, Balanced 0.58, Performance 0.5, Ultra
@@ -706,6 +744,79 @@ Cyberpunk 2077 never chains `sl::DLSSOptions`, so 0xFF there is the title's trut
call, and if built, the byte stays 0xFF and the report says *derived*.
- **Do not** reach for `slDLSSSetOptions` via `slGetFeatureFunction`: §2b refused it on five
grounds that have not changed, and NGX-direct `NVSDK_NGX_Parameter_GetUI` is licence-blocked.
- **Alan Wake 2 did not run on 2026-09-04** (the owner tried every workaround; the title is
broken on this machine), so the measurement moved to **Dying Light: The Beast at DLSS**, the
first Streamline title measured whose batches carry `kFeatureDLSS` — identity `Dlss` on 4,575
of 4,575 batches. It read `UpscalerParams = 0` on three captures, because DL:TB ships
**Streamline 2.8.0, which deprecates `slSetTag` for `slSetTagForFrame`**, and only the
deprecated export had a row. The `slSetTagForFrame` row exists as of this entry (#115) —
**and the rerun on it still read `UpscalerParams = 0` with both rows live**, so the title
tags with a zero extent or not on this route at all. The next build reads the size the
tagged `sl::Resource` declares when the extent is zero (`TagSize`, every route); one more
DL:TB DLSS capture on it is ~~owed~~ **ran 2026-09-05 00:53 (#116 build): `N/A` stands** —
params 0 of 3523 with both rows live and the fallback in. The route yields nothing on this
title; the honest answer is `N/A`, and 7a on DL:TB is closed on that. What would reopen it
is a tag-route census (calls per export, zero-extent seen, Resource-size seen), which needs
a layout bump and is not worth one for a preset byte. The derived-label decision above is
unchanged and applies to the titles that do print the line.
- **Separately, and more important than the preset:** every DL:TB DLSS run (five, the last at
00:53 on the #116 build) had DLSS Frame Generation ON per the owner, and every one read
`presents = tokens`, `frame generation: none`. That is `20_OPEN_QUESTIONS` §H5 case 3's
candidate title. **Owner decision 2026-09-05: this is its own session and its own PR.** Read
§H5 first; the discriminator (the owner's counter beside our `FPS:` line) is pre-committed
there and is the first thing that session asks for. Nothing in FG counting changes before
that reading. **The reading came the same day and the first PR landed on it** — the owner:
the title runs at DLSS ×4, the frames we record are the native ones (§H5, verbatim). The
capture host now prints each census-named module's file version and withholds `none` on
that shape (`03_METRICS` §Frame Generation; the key is `sl.dlss_g.dll`, not
`nvngx_dlssg.dll`). **What is next is the owner's session pre-committed in §H5** — DL:TB with
DLSS FG off and ×4, Cyberpunk MFG ×4 as the control, PresentMon elevated beside each, the
counter's NUMBER written down — and the row it lands on decides whether the gate stays, a
second present sink is costed (§H5 lists the candidates; the route is the owner's), or the
gate is withdrawn. Nothing in the hook changes before that row. **The counter half of Leg 1
is read (2026-09-05): ~300 against our 76.7, reading (a) with its number; the PresentMon half
is still owed.** And the owner's eleven-capture run the same day (`spike-notes` §9) put the
remaining NVIDIA gap in one sentence: the COUNT is right on every title and the IDENTITY is
what this build cannot say — DLSS on the NGX-direct UE titles, DLSS-G everywhere. **The identity half landed 2026-09-05 from the Streamline docs** (DLSS-G guide §5.0: the HUD-less / UI tags a
frame-generating title MUST send, through exports already hooked): `frame generation: DlssG` is expected on
Cyberpunk at MFG and on the UE titles at ×4 on the next run, with the new `Streamline tag census:` line saying
which route carried the tags — and DL:TB's census line says whether that title feeds DLSS-G through a route
this build sees. `slDLSSGGetState` was refused (`03_METRICS` §FG: it resets the plugin's own counter).
~~**START HERE next:** `fl-probe-nvapi --ngx-state <pid>` against a running Lies of P, Hell Is Us, DL:TB
and Cyberpunk (no capture, no injection) — the super-resolution identity on NGX-direct titles is still the
gap the tags cannot close.~~ **RAN 2026-09-06 on Hell Is Us, Expedition 33 and Lies of P (§H5, `spike-notes`
§9): `CREATED | EVALUATE` on the SR word without an override on both no-override titles — the identity
exists in the driver's bookkeeping; the FG word does not see DLSS-G at ×4; `frameGenerationCount` is the
override target, `scalingRatio` is 0 even under an override.** ~~**START HERE next: the owner decides the
driver-reported rung (§H5 says exactly what it may claim: `Dlss (driver-reported …)` on a session where
every hook says N/A, nothing about quality, ratio or FG), and the negative is owed first — the probe on
Lies of P with DLSS switched OFF, expected `CREATED` clear.**~~ **Decided and BUILT 2026-09-06: the capture
host probes the driver beside every module snapshot and the `upscaler:` line has the driver-reported rung
(`03_METRICS` §Upscaling). START HERE next: the owner's run — §H5 rows N1–N4, and N3 (Lies of P with DLSS
OFF) is the one that keeps or withdraws the rung — LANDED 2026-09-06 midday: N3 read `CREATED` clear with
upscaling off, N1 prints `Dlss (driver-reported …)` on four NGX-direct titles, N2 prints agreement on two,
and the FG word turned out to follow DLSS-G too (identity, never the multiplier). START HERE next: Cronos
(a second Streamline 2.8.0 title, UE) with frame generation ON — does the 2.8.0 pacer bypass the patched
bodies there too (`DXGI present counter` ≈ 3) or is it Techland's (0)? — ANSWERED 12:17: Cronos FG on reads
`86.8 → 172.72 (×1.99 FG)` with `unseen=0`; the bypass is Techland's. Item closed; the next item is the
owner's pick from 7b / 7c below.** **The tag route LANDED on the owner's evening run (`spike-notes` §9): `DlssG` on
six of six Streamline titles, and DL:TB's census shows its scaling-input tag arrives with no size, which
closes 7a's last question.** If the driver's per-process NGX feedback is
populated without an NVIDIA-app override, the identity question has a producer that is not a
hook and the owner decides whether `03_METRICS` gains a *driver-reported* rung (§H5 says what
that rung may and may not claim). If it is not populated, the answer stays `N/A` and the
session goes back to the PresentMon leg. **The in-process half of that leg LANDED (2026-09-05,
night): DL:TB at DLSS FG ×4 read 2.90 and 2.95 unseen presents per hooked one on the same chain —
§H5 row P1-DXGI — while Streamline 2.7.3 (Hell Is Us) and 2.10.3 (the Onimusha demo) read 0.00, so
2.8.0's pacer is the one that bypasses the patched bodies. The record now carries `dxgiUnseen` and
the window counts `Displayed = hooked + unseen`, labelled DXGI-COUNTED (`03_METRICS`); DL:TB's next
capture is expected to print the trio at ≈ ×3.9 with that label and no withheld line — LANDED
2026-09-06: `70.52 → 282.08 (×4 FG)`, DXGI-COUNTED 12,387, `DlssG`. Leg 0 the same morning (FG off,
twice) showed the plugin is a startup-time load and the report withheld as pre-committed, so the
gate is now narrowed to sessions where the DXGI counter was not read; a read counter with zero
unseen prints `none` with DXGI's agreement.** The
"sl.common must be loaded on 2.8" lead is closed by the 2.10.3 title, which injects and counts like
2.7 (§H5).
#### 7b. Titles whose upscaler or frame generation is compiled into the executable
@@ -729,7 +840,15 @@ hole; it does not close it.
title cannot give. **The honest ceiling for a statically linked title in attach mode is
Presented FPS with the census's qualifier** — which is what ships today, with the hole named.
- **The only cheap improvement is wording**, and it is already in: the qualifier says
*statically linked FSR3-FG … outside what this can see*. If a title is found, the first PR is
*statically linked FSR3-FG … outside what this can see*. **Built 2026-09-06, two steps past that
(owner's choice over "return native", which rule 6 forbids):** the executable FILE is scanned on
disk after the session for the vendor SDK strings, and a frame-generation-capable one flips the
clear-census sentence from *cannot* to *MAY*; and the rung-3 line prints its exclusions (the
driver's FG word, the tags, the ffx census, the module census, the file's markers). The ceiling
for a title that is both compiled-in and token-less stays Presented FPS + that qualifier. **LANDED
2026-09-06 14:02: Rune Factory at FSR + FSR FG prints the pre-committed line verbatim (§H11); 7b is at its
ceiling and closed.** Hell Is Us at XeSS + XeSS-FG the same run: no token, so Displayed measured (186.47,
0 unseen) and Native unknown — the N/A now carries its witnesses, and that is the XeFG ceiling too. If a title is found, the first PR is
a `spike-notes` row and a `20_OPEN_QUESTIONS` §Scope entry with the measured shape, not code.
- ~~**Measured 2026-09-04: no such title is installed.**~~ **Found the same evening, by running
rather than by scanning: Rune Factory: Guardians of Azuma.** The scan was right that every FSR
@@ -739,9 +858,21 @@ hole; it does not close it.
token is requested on that UE5 title regardless, so the count read `59.99 → 119.95 (×2 FG)`,
*technology not identified* — the trio, with the vendor missing. Identity by name stays out of
reach; §Scope decisions carries the corrected row. A disk scan cannot find this shape; a
capture with the census line can.
capture with the census line can. **Black Myth: Wukong is the second** — its FSR upscaling
dispatches to neither the loaded monolith nor the loader, and it offers no FSR frame generation.
#### ~~7c. AMD and Intel identity, measured rather than inferred~~ — **AMD LANDED 2026-09-04 and re-confirmed complete 2026-09-06 on Lies of P; Intel closed by licence (re-checked 2026-09-06, unchanged)**
*2026-09-06, 12:46: Lies of P at FSR 3.1 + FSR FG prints `Fsr3` / `FsrFg` / `59.77 → 119.55 (×2 FG)` /
`2560x1440 -> 2560x1440` with every count agreeing (`spike-notes` §9) — acceptance step 5 in full, beside
the DXGI counter (0 unseen) and the NVIDIA driver's word (nothing created). The owner called the AMD half
done. Intel: the licence was re-fetched the same day — Intel Simplified Software License, October 2022,
binary-only, "nor any modification", termination; the header banner still forbids copying — so the
reversal condition has not fired and the census stays the answer. What is new: Intel's own README says
XeSS-FG runs on non-Intel GPUs with SM 6.4, so an XeFG session IS capturable on this box (DL:TB, Hell Is
Us, Cronos, Expedition 33 ship `libxess_fg.dll`), and the proposal on the table is identity BY ELIMINATION,
labelled — see `20_OPEN_QUESTIONS` §H11's 2026-09-06 note.*
#### ~~7c. AMD and Intel identity, measured rather than inferred~~ — **AMD LANDED 2026-09-04; Intel closed; the owner's three launches are owed**
**Do not start here.** The three ffx-api leaves are hooked, the FidelityFX headers are vendored
at tag **`v2.3.0`** (not the `v1.1.4` step 1 below names — its own reversal condition fired:
@@ -775,10 +906,25 @@ corrections to the entry below, each of which changed what got built:**
`FsrFg` / ×2 on Hell Is Us), Expedition 33 showed the mixed-vendor shape (FSR upscale + DLSS FG ×3
→ *active, technology not identified* at ×2.97), Cyberpunk at FSR 3 split across two AMD
generations, and **Rune Factory turned out to be 7b's statically linked title** with the Streamline
token count still reading ×2. **Owed after the loader row lands:** Dying Light: The Beast at
FSR + FSR FG, KCD2 at FSR, Wukong at FSR — against row R6. **The FSR 3.0 host route
token count still reading ×2. **Row R6 ran the same night on #111:** Dying Light: The Beast at
FSR + FSR FG printed `FSR (3.1 or 4 …)` / `FsrFg` / `70.49 → 140.9 (×2)` with the counts agreeing
at 1.01, KCD2 at FSR printed the identity and `none` by count at 1.00 — the loader row carries
both, once. **Wukong at FSR read silent at the monolith AND the loader with the monolith loaded**:
FSR upscaling compiled into its UE plugin (Rune Factory's shape) with the monolith loaded and
unused — ~~owed: Wukong with FSR frame generation ON~~ **the title has no FSR frame-generation
option (owner, same night)**, so Wukong is the second static title and nothing is owed on it. ~~**The FSR 3.0 host route
(`ffx_fsr3_x64.dll`, step 3 below) is deferred to its own PR** — ten host headers from `v1.1.4`;
Cyberpunk at FSR 3 is its oracle and already prints `FsrFg` from the monolith beside it.
Cyberpunk at FSR 3 is its oracle and already prints `FsrFg` from the monolith beside it.~~
**BUILT 2026-09-05, and the tag was not `v1.1.4`.** Cyberpunk's module exports exactly
`fsr3-v3.0.4`'s twelve `ffxFsr3*` names; 1.1.4 appends fields after `renderSize` and declares
three exports the module lacks. One row — `ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale`,
the same family and publish point as the ffx-api rows, keyed by module in the installer —
reads `renderSize` and nothing else; `ffxFsr3DispatchFrameGeneration` is deliberately not a
row (the monolith generates on the one title; §H11 pre-commits the reversal). **What is owed
is the owner's acceptance run**, rows B1–B4 in §H11: Cyberpunk at FSR 3 + FG must print
`upscaler: Fsr3` with one extent agreeing between the host and the monolith's PREPARE, and
`frames/upscale-drained = 1.00`; B2 (facade silent, `upscale-drained = 0`) is the pre-committed
condition for adding the `ffx_fsr3upscaler_x64.dll` row instead — never both.
<details>
<summary>The entry as it stood, kept for the reasoning it carries</summary>
@@ -801,7 +947,7 @@ exports `xessD3D12Init` / `xessD3D12Execute` and XeFG `xefgSwapChainD3D12InitFro
ffx_framegeneration.h, dx12/ffx_api_dx12.h, vk/ffx_api_vk.h}` for the 3.1 facade the
installed titles call, and `sdk/include/FidelityFX/host/{ffx_fsr3.h, ffx_fsr3upscaler.h,
ffx_frameinterpolation.h, ffx_opticalflow.h, ffx_types.h, ffx_error.h, ffx_interface.h,
ffx_util.h, ffx_assert.h}` for the FSR 3.0 host API. Do not take `main`: it is SDK 2.x under
ffx_util.h, ffx_assert.h}` for the FSR 3.0 host API *(2026-09-05: vendored from **`fsr3-v3.0.4`**, not `v1.1.4` — the tag whose declarations match the module Cyberpunk ships; see the banner above)*. Do not take `main`: it is SDK 2.x under
a binary-only `docs/license.md` that excepts these headers as MIT only by an 845-line list.
Extend `hookinventory-check` Pass C's forbidden-import list with `amd_fidelityfx_*.dll` /
`ffx_*.dll` in the same PR — the Streamline lesson, one vendor over. *Intel XeSS SDK*:
@@ -828,8 +974,10 @@ exports `xessD3D12Init` / `xessD3D12Execute` and XeFG `xefgSwapChainD3D12InitFro
same five names, and the plugin modules are called by the facade, not by the game — an
unscoped hook would count each dispatch twice, straight into `fg_factor`.
3. **AMD 3.0 (`ffx_fsr3_x64.dll`, Cyberpunk's copy):** named exports, no struct decode needed —
`ffxFsr3ContextDispatchUpscale` for identity and extent, `ffxFsr3DispatchFrameGeneration`
once per application frame.
`ffxFsr3ContextDispatchUpscale` for identity and extent, ~~`ffxFsr3DispatchFrameGeneration`
once per application frame~~ *(built 2026-09-05 without the FG row: on the one title the
monolith generates and the count is Streamline's; the host's FG export fires per generated
batch and is not a count producer. §H11 carries the reversal condition.)*
4. **Intel — closed at the census (step 1).** No hook on any `libxess*.dll` export. The
report line for an Intel title is what the writer already produces: upscaler
`NOT_REPORTED`, and if `libxess_fg.dll` is in the census, Presented FPS with the *"MAY
@@ -870,6 +1018,25 @@ feature hooks — §S29(a) said it was and was wrong; see below. What it buys is
> drop the switch as well. Anyone costing this as "fix the signer half" is costing
> half of it.
**Picked up 2026-09-06 (the owner's next item after item 7).** The sequence, with what
each step needs, so nothing here is started out of order:
1. **The CI leg, made readable** (2026-09-06, this PR): the probe's ctest printed nothing,
so `ci.yml` runs `fl-probe-signer` as its own step after the gate and the answers land in
the log. Rows G3/G4/G5 are read off the next run on `main`.
2. ~~**The adapters-disabled leg — owner-only, a network setting.** Same three subjects,
`ctest fl_signer_probe` (or the exe) with every network adapter disabled, compare the
verdicts with `spike-notes` §1. Unchanged → G1; any change → G2 and the route retires.~~
**RUN 2026-09-06 by the owner: every verdict unchanged — row G1 (§S19(b)).**
3. ~~**The allow-widening bound — owner-only, a decision no PR may take (§S19(b)).**~~ **DECIDED
2026-09-06: option 1, the compiled-in allowlist `trustedSigners` may only intersect.**
4. ~~**Then the PR:** …~~ **BUILT 2026-09-06 (§S19(b) ✅ BUILT):** `ModuleSignerOrganisation` in
`fl_guard_sources.cpp`, `IsCompiledTrustedSigner` as the bound, the trusted module keeps the
scan looking, every failure refuses, the catalog half deferred with its rationale, both
directions proved against the real seams through `hook-harness --load`, and `-SkipIntegration`
dropped from `ci.yml`. **The Separable item is closed**: the nine integration cases are in the
merge gate, and CI runs the command a developer runs.
### ~~§M5 — **START HERE**~~ — MEASURED 2026-09-03, row R1, and the head moves
**Do not start here.** `LhmTelemetrySource` exists, `probe-lhm` ran unelevated and elevated,
@@ -1081,8 +1248,8 @@ diagnosis*.
needle containing `` `blockedExecutables` `` silently became something else, `.Replace`
matched nothing, the file was unchanged — and the validator correctly passed. Print
the mutated text before validating.
- **`./build.ps1 check` with no switches** after every PR. CI runs `-SkipIntegration`,
so a green CI is not evidence for anything touching the managed drain.
- **`./build.ps1 check` with no switches** after every PR. ~~CI runs `-SkipIntegration`,~~ CI runs the same since 2026-09-06,
so a green CI is evidence for the managed drain too (§S19(b) BUILT).
- **A canary that does not compile is not a canary, and this repo's analyzers make that
easy to hit.** Removing a call to prove a gate goes red can leave a constructor
parameter unread — `CS9113` under `TreatWarningsAsErrors` — so the build fails, the
+272 -10
View File
@@ -312,8 +312,20 @@ offline retires the route, and §S19(b)'s row G2 says so before the run.
yields no organisation — so a green result discriminates rather than merely running.
`fl-baseline-probe` was retired by exactly this class of test.
**Not measured here:** the CI leg (a different machine stages a different copy), and
the adapters-disabled leg. Both have pre-committed rows. An unrun leg is unrun.
~~**Not measured here:** the CI leg (a different machine stages a different copy), and
the adapters-disabled leg. Both have pre-committed rows. An unrun leg is unrun.~~
**The CI leg, 2026-09-06** (the ctest printed nothing for eleven days; `ci.yml` now runs the
probe as a step): `windows-latest`, elevated. Blocker copy from the runner's NuGet cache,
6.0.0, embedded/offline `ERROR_SUCCESS` 3.47 ms, `O= Microsoft Corporation`, no catalog;
`mskeyprotect.dll` embedded `TRUST_E_NOSIGNATURE`, catalog `ERROR_SUCCESS`; `kernel32.dll`
both; cold 3.45 / warm 3.53 ms; `cryptnet.dll` newly loaded under the offline flags; canary
`TRUST_E_NOSIGNATURE`; *"G1 is a CANDIDATE"*. Rows G3, G4, G5 do not fire.
**The adapters-disabled leg, the owner's run, 2026-09-06** (dev box, elevated): every verdict
unchanged — `kernel32.dll` both `ERROR_SUCCESS`; `mskeyprotect.dll` embedded `TRUST_E_NOSIGNATURE`,
catalog `ERROR_SUCCESS`; the blocker embedded `ERROR_SUCCESS`, `O= Microsoft Corporation`, subject
now `CN=.NET` (the August copy read `CN=Microsoft Windows`; same `O=`); cold 2.14 / warm 2.15 ms;
`cryptnet.dll` mapped; canary `TRUST_E_NOSIGNATURE`. **Row G1 reads**; the bound decision is the
owner's before anything is built.
### Still open
@@ -323,6 +335,9 @@ the adapters-disabled leg. Both have pre-committed rows. An unrun leg is unrun.
loads a presentation runtime lazily, and the only local fixtures are
`hook-harness` (creates D3D at startup) and a 2D GOG prologue. A number from
those would not generalise, which is worse than recording it as unmeasured.
*(2026-09-06: built as "inject late" — P1 item 2 — and the number now comes
from every launched session, as `dxgiPresentsBeforeHook` plus the reported
wait. `20_OPEN_QUESTIONS` §S1.)*
### ✅ Signer field for the unknown-but-suspicious heuristic — **`O=`, not `CN=`**
@@ -428,6 +443,31 @@ the same shape as defects found elsewhere in this project:
The unambiguous signal is the loader printing `Insert instance layer` /
`Inserted device layer` with our name and DLL path.
### ✅ `VK_ADD_IMPLICIT_LAYER_PATH` is honoured, and it needs no registry (2026-09-06, P1 item 3)
Measured against the same loader 1.4.357 with `vulkaninfo --summary` and `VK_LOADER_DEBUG=layer`: with
`VK_ADD_IMPLICIT_LAYER_PATH` pointed at the build tree's `FrameLedger.VkLayer` directory and
`FRAMELEDGER_ENABLE_VK_LAYER=1`, the loader prints `Insert instance layer "VK_LAYER_FRAMELEDGER_overlay"
(…\FrameLedger.VkLayer.dll)` and `Inserted device layer …` — the unambiguous signal above — with nothing
under `HKCU` or `HKLM`, and `vulkaninfo` exits 0 with the layer inert (no enable-list entry for it). The
first run's `grep … | head` cut the log before the `Insert` lines and read as "found, not inserted"; the
lines are at the instance-creation point, ~850 lines in. So the operator host launches Vulkan titles with
no registration at all, and the real-loader ctest (`fl_vklayer_real`) does the same: the harness's
`--vulkan` mode presented 241 frames in 4 s on a hidden 240-wide window and the layer recorded every one.
### ✅ On NVIDIA a Vulkan swapchain presents through DXGI — and the DXGI hook sees it (2026-09-06)
Found by the first end-to-end run of `launch` on the harness's `--vulkan` mode: the guard's poll saw
`dxgi.dll` + `d3d12.dll` (the fixture imports d3d11/dxgi; but the NVIDIA Vulkan ICD `nvoglv64` maps them
too) and injected the Overlay, whose `Present` hook then recorded **295 DXGI presents in 5 s with
`apiMask = D3D12` and DXGI's counter agreeing (248 samples, 0 unseen)** — the Vulkan swapchain's own
presents, made by the driver on an internal DXGI flip-model chain. So on this driver the injected Overlay
*can* measure a Vulkan title's presents; that is a driver property, not a portable one (AMD's and Intel's
WSI need not do it), which is why the layer stays the capture side. Two consequences landed: the
launch-mode guard now classifies **any** process that mapped `vulkan-1.dll` as the layer's, and the
harness's `--vulkan` mode maps the loader before anything else so the fixture looks like a real Vulkan
title to the first poll.
### ✅ The in-layer blocklist scan — §S2's second half
The layer scans its own process at init and goes fully passthrough on any hit,
@@ -1702,7 +1742,7 @@ one launch per capture, consent granted after launch. Exit codes and full report
| Expedition 33 | upscaler 4.0.2 + frame generation 3.1.5, **no loader** | UE5: the plugin's built-in loader calls the leaves directly |
| Hell Is Us | upscaler **4.0.3** + frame generation **4.0.0** under `Plugins/FSR/Source/fidelityfx-sdk/Kits/FidelityFX/signedbin/`, **no loader** | UE5, SDK 2.1.x |
| Red Dead Redemption 2 | `ffx_fsr2_api_x64.dll` + `_dx12_` + `_vk_` | FSR 2, dynamic |
| Cyberpunk 2077 (also) | `ffx_fsr3_x64.dll`, `ffx_backend_dx12_x64.dll`, `ffx_frameinterpolation_x64.dll`, `ffx_fsr3upscaler_x64.dll`, `ffx_opticalflow_x64.dll` | FSR 3.0 host DLLs, named exports — the deferred route |
| Cyberpunk 2077 (also) | `ffx_fsr3_x64.dll`, `ffx_backend_dx12_x64.dll`, `ffx_frameinterpolation_x64.dll`, `ffx_fsr3upscaler_x64.dll`, `ffx_opticalflow_x64.dll` | FSR 3.0 host DLLs, named exports — ~~the deferred route~~ hooked 2026-09-05 at the host facade (`ffxFsr3ContextDispatchUpscale`, tag `fsr3-v3.0.4`: the module's twelve exports match that tag, not `v1.1.4`) |
Every module in the ffx-api family exports the same five names and nothing else
(`vendor-exports.json`) — which the morning read as "the loader can only reach a leaf through
@@ -1718,13 +1758,226 @@ one launch per capture, consent granted after launch. Exit codes and full report
and `none` by count with FG off; **Hell Is Us** `FSR (3.1 or 4 …)` / `FsrFg` / ×2 / 1.00, and
`none` with FG off; **Expedition 33** FSR upscale under DLSS FG ×3 → `×2.97`, *technology not
identified*, count from UPSCALE dispatches (no PREPARE, no token); **Cyberpunk** at FSR 3: the FSR
3.0 host DLLs upscale (`upscaler: N/A`, deferred route) while the 1.1.x monolith generates
3.0 host DLLs upscale (`upscaler: N/A` on that build; the host row landed 2026-09-05, §H11 B1 owed) while the 1.1.x monolith generates
(`FsrFg`, 4261 batches, ×2); **Dying Light: The Beast** (FSR + FSR FG), **KCD2** (FSR) and
**Wukong** (FSR): **zero dispatches at any leaf export**, `upscaler: N/A` — the loader-row
reversal; **Rune Factory** (FSR FG): no AMD module in the census, `59.99 → 119.95 (×2)` from
Streamline tokens, *technology not identified* — 7b's statically linked title, with the count
surviving and the identity not. **Owed after the loader row:** the three loader titles again,
against row R6.
surviving and the identity not. **Row R6, same night, on #111:** DL:TB FSR + FSR FG →
`FSR (3.1 or 4 …)` / `FsrFg` / `70.49 → 140.9 (×2)` / 1.01 and KCD2 FSR → identity + `none` /
1.00, both through the loader row at 1×; Wukong FSR (×2 runs) → silent at monolith and loader
with the monolith loaded, and the title has no FSR frame-generation option — FSR upscaling
compiled in (Rune Factory's shape), the monolith shipped and loaded for nothing this hook sees.
- **2026-09-04, late: Dying Light: The Beast at DLSS, three captures (23:31 / 23:39 / 23:43), for
7a after Alan Wake 2 would not run.** The first Streamline title measured whose batches carry
`kFeatureDLSS`: `upscaler: Dlss` on 4720/4783, 4271/4345 and 4575/4657 records, `FPS 80.41 /
72.73 / 77.69`, every batch identified, RT measured on ~98% of presents. **`UpscalerParams`
0 of N on all three**, `render -> output: N/A`, quality byte never published. Cause, measured
with dumpbin: DL:TB ships `sl.interposer.dll` **2.8.0**, which exports `slSetTagForFrame`
(Cyberpunk's 2.7.1 does not); `sl.h` marks `slSetTag` deprecated in its favour, and a 2.8 title
tagging per frame never calls the export the only params row hooked. The oracle had hidden it:
`vendor-exports.ps1` recorded the FIRST `sl.interposer.dll` found (2.7.4.0), so the 2.8 export
was absent from `docs/vendor-exports.json` until the tool unioned across copies (ten copies,
eight distinct versions from 1.5.6 to 2.10.3). All three runs read `frame generation: none`
with presents = tokens = batches; **which of the three had DLSS Frame Generation on is the
owner's to say** — if any did, `none` there is the §H5 false negative on a title where the FG
runtime (`sl.dlss_g.dll`) is in the census, and it is a finding about DLSS-G on SL 2.8, not
about the tag row. Row added; rerun owed.
- **2026-09-05 00:19, DL:TB at DLSS again, on the #115 build** (the payload is the CaptureHost
bin's `FrameLedger.Overlay.dll`, rebuilt 00:17): `Dlss` 4331/4401, `FPS 73.64`, and
**`UpscalerParams` still 0 of 4401** with the params family live — which, under
publish-when-whole, means BOTH tag rows were patched. So the title either tags the scaling
input with a **zero extent** ("use the entire resource") or tags it nowhere we hook. The
zero-extent reading is the one the record can still act on: `sl::Resource` carries its own
`width/height` (mandatory only on Vulkan, so filled or not on D3D12 at the title's choice),
and `TagSize` in `fl_sl_inputs.h` now reads them when the extent is zero — on every route,
local and both global — GUID-checked, from the argument the hooked API received. If the
next run prints a `render -> output` line, that was the shape; if not, the title does not
state the size on this route at all and the honest line stays `N/A`.
- **2026-09-05 00:53, DL:TB at DLSS on the #116 build (payload rebuilt 00:51): `N/A` stands.**
`Dlss` 3460/3523, `FPS 58.87`, **`UpscalerParams` 0 of 3523**, both tag rows live, the
whole-resource fallback in. So on this title the scaling-input tag reaches neither global
export with a size in either place, or does not reach them at all — the record cannot
separate those two, and that is the one thing left to instrument if 7a is ever reopened on
this title (a tag-route census: calls seen per export, zero-extent seen, Resource-size seen —
a record bit or a writer-state word, so a layout bump). **7a on DL:TB closes as measured
`N/A`** for the quality byte and the render size; the derived label has no input here and
stays the owner's decision for the titles that do print the line (Cyberpunk).
`frame generation: none` again with presents = tokens = 3441 and DLSS FG on — the fifth
such run, §H5.
- **And the owner's answer to the FG question: all four DLSS runs had DLSS Frame Generation
ON.** `presents = tokens` on every one, against ×2 with FSR FG on the same title and ×3.99
on Cyberpunk (SL 2.7.1, DLSS-G 310.8) — recorded in `20_OPEN_QUESTIONS` §H5 as case 3's
candidate, with the discriminator (the owner's counter reading) pre-committed there.
- **2026-09-05, the owner's run on #118 + #119 — eleven captures, seven titles, every one with
DLSS or frame generation on**, the first with the `module:` lines (interposer versions read off
the files: DL:TB 2.8.0, Cyberpunk 2.7.1, Hell Is Us 2.7.3, Expedition 33 2.7.30, Wukong 2.7.4;
`_nvngx.dll` 32.0.16.1664 from the driver store on every NVIDIA title):
| Title / setting | What printed | Reading |
|---|---|---|
| **Cyberpunk 2077**, FSR 3 + FSR FG | `upscaler: Fsr3` (host route, 4332 records at 1506×847), `FsrFg`, `74.31 → 148.56 (×2)`, `frames/upscale-drained 1.01` | **§H11 B1 accepted** |
| **Cyberpunk 2077**, FSR 3, FG off | `Fsr3`, `none` by count 4919/4919, `1506x847 -> 2560x1440 = 1.7x (59%)` | **B1-off accepted** |
| **Cyberpunk 2077**, DLSS + RR + MFG ×3 | `Dlss` (via RR, 3704 batches), `62.86 → 187.49 (×2.98)`, `Active (technology not identified)`, `render 1707x960` on 3677 records | count right, DLSS-G unnamed (`kFeatureDLSS_G` never evaluated) |
| **Dying Light: The Beast**, DLSS FG ×4 (twice) | `Presented FPS 76.7` / `93.24`, **`none` WITHHELD** with the §H5 qualifier, `sl.interposer.dll 2.8.0.0` named | **owner's counter ~300 = 3.9× ours** — reading (a) with its number |
| **Hell Is Us**, DLSS + FG ×4 (twice) | `82.23 → 328.98 (×4)`, `Active (technology not identified)`, `upscaler: N/A`; the first run refused the factor (bucket 2.25 vs 3.65 — 53 unfocused ticks) | NGX-direct SR, Streamline tokens still count |
| **Expedition 33**, DLSS + FG (twice) | `54.9 → 218.38 (×3.98)`, `Active (technology not identified)`, `upscaler: N/A` | same shape |
| **Black Myth: Wukong**, DLSS + FG ×4 | `55.39 → 221.53 (×4)`, `Active (technology not identified)`, `upscaler: N/A`, `sl.dlss_g.dll 2.7.4.0` loaded | same shape; the plugin bit is set on a 2.7 title, and the gate correctly did not fire (factor active) |
| **Lies of P**, DLSS, no FG (owner) | `Presented FPS 59.77`, WARNING naming `amd_fidelityfx_dx12.dll`, `upscaler: N/A`, `tokens=0` | NGX-direct SR with no Streamline at all: nothing this build hooks fires |
Two things the run found beyond the rows. **A consumer defect:** `render -> output: N/A` on every
FG-on capture — Cyberpunk at FSR 3 + FG printed it two lines under `render 1506x847 on 4332
record(s)` — because `UpscaleExtent` keyed its window on the params bit, which under frame
generation rides on one present in N; fixed the same day (identity-bit window). **And the shape
of what is left:** on every NVIDIA title measured the *count* is right and the *identity* is
what this build cannot say — DLSS on four NGX-direct titles, DLSS-G on all of them — because
the NGX SDK is licence-blocked and `kFeatureDLSS_G` is never evaluated through the export the
Streamline hook owns. `20_OPEN_QUESTIONS` §H5 carries the one candidate that is not a hook
(`NvAPI_NGX_GetNGXOverrideState`, by PID) and the probe that measures it before anything is
built on it.
- **2026-09-05 evening, the owner's run on #121 (the tag route) — eight captures, six titles, every one at DLSS**
**with frame generation on**, the first with the `Streamline tag census:` line. The pre-commitment in
`20_OPEN_QUESTIONS` §H5 landed on every title that goes through Streamline:
| Title / setting | `frame generation:` | Trio | Tag census (route: types) |
|---|---|---|---|
| **Hell Is Us**, DLSS + FG ×4 (twice) | **`DlssG`** | `38.5 → 154.04 (×4)`, `81.41 → 325.58 (×4)` | global: depth, mvec, hudless, ui-color-alpha, backbuffer, other |
| **Expedition 33**, DLSS + FG ×2 | **`DlssG`** | `75.95 → 149.83 (×1.97)` | global: same set |
| **Black Myth: Wukong**, DLSS + FG ×4 | **`DlssG`** | `47.99 → 191.89 (×4)` | global: depth, mvec, hudless, ui-color-alpha, backbuffer |
| **Rune Factory**, DLSS + FG ×4 | **`DlssG`** | `128.85 → 513.02 (×3.98)` | global: same as Hell Is Us |
| **Cyberpunk 2077**, DLSS + RR + MFG | **`DlssG`**, `upscaler: Dlss`, `1707x960 -> 2560x1440 = 1.5x (67%)` | **factor refused** — bucket 1 of 8 reads 3.0 against 1.67 overall; `tokens/batch 2.97` | global: depth, mvec, hudless, scaling-in, scaling-out, other (no UI tag) |
| **Dying Light: The Beast**, DLSS FG ×4 | N/A (`none` withheld, §H5) + *"it is FEEDING frame generation"* | `Presented FPS 67.13` | **frame** (`slSetTagForFrame`): depth, mvec, hudless, scaling-in, scaling-out, ui-color-alpha, other |
Three readings. **The identity is measured on six of six Streamline titles** — the UE Streamline plugin tags
the DLSS-G inputs globally (`slSetTag`) on every UE title, Cyberpunk on 2.7.1 tags globally too, DL:TB on 2.8
tags through `slSetTagForFrame` — so `Active (technology not identified)` is gone from every one of them,
and `upscaler: N/A` on the UE titles is now the ONLY NVIDIA gap (NGX-direct super-resolution, the NVAPI
probe's job). **DL:TB's 7a question is answered by the census, at no layout cost**: the title DOES tag
`kBufferTypeScalingInputColor`, through the 2.8 export, and `UpscalerParams` is still 0 of 4030 — so the tag
carries neither an extent nor a Resource size, which is exactly the shape #116 named and could not see; the
`N/A` there is the title's truth. **Cyberpunk's refusal is the guard working**: `tokens/batch 2.97` with
`presents/batch 4.97` and bucket 1 at 3.0 is a session whose state changed after the first eighth — tokens
kept flowing while Ray Reconstruction stopped being evaluated, which is what a menu or a pause does — and the
report refused the session-level number rather than averaging two configurations (the 2026-08-16 alt-tab
lesson). The owner's settings for that run are recorded when known; the earlier 14:01 run at MFG ×3 read
`×2.98` with `tokens/batch 1.00` on the same title.
- **2026-09-05 night, the owner's run on #124 (the DXGI present counter) — DL:TB twice, Hell Is Us, and a
new title, the Onimusha: Way of the Sword demo on Streamline 2.10.3.** `20_OPEN_QUESTIONS` §H5 row
P1-DXGI landed on the first title and both controls read zero:
| Title / Streamline | Trio or Presented | `DXGI present counter:` | `frame generation:` |
|---|---|---|---|
| **Dying Light: The Beast**, 2.8.0, DLSS FG ×4 (21:56) | `Presented FPS 69.99` (withheld) | `unseen=12204 over samples=4136 (2.95)` | N/A (withheld) + *FEEDING* |
| **Dying Light: The Beast**, 2.8.0, DLSS FG ×4 (22:06) | `Presented FPS 73.19` (withheld) | `unseen=12741 over samples=4392 (2.90)` | same |
| **Hell Is Us**, 2.7.3, DLSS + FG ×4 | `79.89 → 308.14 (×3.86)` | `unseen=0 over samples=18207` | `DlssG` |
| **Onimusha: Way of the Sword demo**, **2.10.3**, DLSS + FG | `60.04 → 220.33 (×3.67)` | `unseen=0 over samples=12914` | `DlssG`, `upscaler: Dlss`, RT Yes (27.1 %) |
The 2.8.0 pacer presents on the hooked chain through a body the inline patches do not cover; 2.7.3 and
2.10.3 present through the body they do. The owner's "`sl.interposer.dll` + `sl.common.dll` must be
loaded on ≥ 2.8" lead is closed by the 2.10.3 title: it injects, tags on the frame route (`depth, mvec,
hudless, scaling-in, scaling-out, ui-color-alpha, backbuffer, other`) and counts like 2.7. Onimusha's
`render -> output: N/A` with `UpscalerParams 0/13014` is DL:TB's shape again — the frame-route tags carry
no size on D3D12, where `sl::Resource` declares none. The PR after #124 turns the 2.8.0 reading into a
DXGI-COUNTED Displayed (`03_METRICS` §Displayed may be DXGI-COUNTED).
- **2026-09-06 morning, the owner's run on #125 — DL:TB three times (frame generation on, then off twice)
and Expedition 33 with frame generation off.** The promotion landed and §H5's Leg 0 answered:
| Title / setting | Line | `DXGI present counter:` | `frame generation:` |
|---|---|---|---|
| **Dying Light: The Beast**, DLSS FG ×4 (07:31) | `Native FPS: 70.52 -> Displayed FPS: 282.08 (x4 FG) over 16516 present(s)` + *Displayed is DXGI-COUNTED: 12387* | `unseen=12483 over samples=4202 (2.97)` | **`DlssG`** |
| **Dying Light: The Beast**, DLSS, FG **off** (07:45) | `Presented FPS 75.52` (withheld) | `unseen=0 over samples=4519` | N/A (withheld) — census still `0x25F0F`, tags `0x23600` (no hudless / UI) |
| **Dying Light: The Beast**, DLSS, FG **off** (07:55) | `Presented FPS 61.14` (withheld) | `unseen=0 over samples=3659` | same |
| **Expedition 33**, FG off (Streamline 2.7.30) | `FPS: 85.86` | `unseen=0 over samples=5063` | `none` by count; tag census `0x0` |
Two readings. **The trio is printed on the title that could not print it**, from a count DXGI made
(12,387 presents this hook never timed), and it is the number the owner's own counter showed (~300 at
×4 against ~75 native). **Leg 0: `sl.dlss_g.dll` is a startup-time load** — the census cannot tell FG
off from FG on, exactly the cost the gate pre-committed — but the DXGI counter can (0 unseen with FG
off, 2.9–3.0 with it on), so the gate is narrowed to sessions where the counter was not read, and the
two FG-off captures above print `none` with DXGI's agreement on the next build. Also visible: with FG
off DL:TB sends no hudless / UI tag and the UE plugin sends no tags at all, so the DLSS-G identity is
per-setting on both.
- **2026-09-06, 09:20–09:35, the NVAPI probe against three running titles (`fl-probe-nvapi --ngx-state
<pid>`, driver 616.64), each beside a capture on the #126 build.** The question §H5 opened on 2026-09-05 —
are the driver's per-process NGX feedback bits populated without an NVIDIA-app override? — is answered
YES for super resolution and NO for frame generation:
| Title / override / capture beside it | SR | RR | FG | `scalingRatio` / `performanceMode` / `renderPreset` / `frameGenerationCount` |
|---|---|---|---|---|
| **Hell Is Us**, no override, `83.21 → 332.82 (×4 FG)` `DlssG`, `upscaler: N/A` | `0x80605` CREATED EVALUATE (+ INITIALIZED DLL_EXISTS ERR_NOT_FOUND) | INITIALIZED DLL_EXISTS ERR_NOT_FOUND | `0x5` INITIALIZED DLL_EXISTS only | 0 / 0 / 0 / 0 |
| **Expedition 33**, override ON, FG off, `FPS: 79.4` `none` (DXGI agrees), `upscaler: N/A` | `0x8067F` CREATED EVALUATE ENABLED DLL_LOADED DLL_SELECTED PRESET PERF_MODE (+ …) | INITIALIZED DLL_EXISTS ERR_NOT_FOUND | `0x1F` INITIALIZED ENABLED DLL_EXISTS DLL_LOADED DLL_SELECTED | 0 / 2 / 11 / 0 |
| **Lies of P**, no override, `Presented FPS 59.89`, `upscaler: N/A` | `0x605` CREATED EVALUATE (+ INITIALIZED DLL_EXISTS) | INITIALIZED ERR_FAILED ERR_NOT_FOUND | INITIALIZED ERR_FAILED ERR_NOT_FOUND | 0 / 0 / 0 / 0 |
The SR word carries the identity the hooks cannot see on these three titles; the FG word does not see
DLSS-G running at ×4 (it tracks the override machinery's DLL, not the plugin), `frameGenerationCount` is
the override target and not the multiplier, and `scalingRatio` is 0 even under the override. §H5 carries
what a driver-reported rung may and may not claim, and the negative still owed (DLSS off in the menu).
Also on this run: Expedition 33 with FG off now prints `none` with *DXGI's own present counter agrees:
0 unseen over 4774* (#126), and Lies of P's `Presented FPS` keeps its "MAY include generated frames"
qualifier because `amd_fidelityfx_dx12.dll` is loaded there — the census cannot say `none` and the
token count is 0 on that title, so that line is right as printed.
- **2026-09-06, 10:39–11:36, the owner's run on #128 (the driver-reported rung) — §H5 rows N1–N4 and one
correction.** The standalone probe first: Lies of P with upscaling OFF reads `SR 0x5` (CREATED clear), with
DLSS on `0x605` — N3 keeps the rung. Then the captures:
| Title / setting | `upscaler:` | `NVIDIA driver NGX state:` SR / RR / FG | FG line |
|---|---|---|---|
| **Lies of P**, DLSS (no override) | **`Dlss (driver-reported: …)`** | `0x605` / `0x90001` / `0x90001` | N/A (no FG in this title) |
| **Expedition 33**, override ON, FG off | **`Dlss (driver-reported: …)`** | `0x8067F` (mode 2, preset 11) / `0x80005` / `0x1F` | `none`, DXGI agrees |
| **Hell Is Us**, DLSS + FG ×4 | **`Dlss (driver-reported: …)`** | `0x80605` / `0x80005` / **`0x605`** (CHANGED between readings) | `81.32 → 321.73 (×3.96)`, `DlssG` |
| **Onimusha demo**, SL 2.10.3, DLSS + FG | `Dlss — the NVIDIA driver agrees` | `0x605` / `0x5` / **`0x605`** (CHANGED) | `59.99 → 235.47 (×3.93)`, `DlssG` |
| **Dying Light: The Beast**, DLSS + FG ×4 | `Dlss — the NVIDIA driver agrees` | `0x605` / `0x90001` / **`0x605`** (CHANGED) | `39.63 → 158.5 (×4)` DXGI-COUNTED, `DlssG` |
| **Cronos: The New Dawn demo** (new; UE, **SL 2.8.0**), DLSS, FG off | **`Dlss (driver-reported: …)`** | `0x80605` / `0x80005` / `0x5` | `FPS 105.01`, `none`, DXGI agrees; RT Yes |
| **Dying Light: The Beast**, **FSR upscaling + DLSS FG** | `FSR (3.1 or 4 …)`, `2560x1440 -> 2560x1440` | **`0x205`** (CREATED, not EVALUATE) / `0x90001` / `0x605` | `DlssG` from the tags; factor REFUSED (bucket 8 of 8 at 1.96 vs 2.85); DXGI 1.80 unseen / present |
Three readings. **The rung works as written and its negative held.** **The FG word is not blind** — the
morning's Hell Is Us reading was taken before the feature came up, and every ×4 session's loop readings
show `CREATED | EVALUATE` with the word changing mid-session; the multiplier bits never set, so it is an
identity witness and is now printed beside `frame generation:`. **`SR 0x205` on the FSR session is the
word telling the truth finely**: DLSS was created at some point (the title initialises it) and not
evaluated, and the rung's two-bit key keeps it from claiming DLSS beside FSR. The FSR + DLSS-G session
also exposed a wrong qualifier ("no evaluation was observed" beside 4,415 tokens and a refused factor),
fixed the same day. Cronos is a second Streamline 2.8.0 title; its FG-on capture is the one that says
whether the pacer bypass measured on DL:TB belongs to SDK 2.8.0 or to that title.
- **2026-09-06, 12:17, Cronos: The New Dawn demo with frame generation ON — the row that closed §H5's
DLSS / DLSS-G question.** Streamline 2.8.0, UE: `Native FPS: 86.8 -> Displayed FPS: 172.72 (x1.99 FG)`
over 9,948 presents, `unseen=0 over samples=10063`, tag census `frame=[depth, mvec, hudless,
ui-color-alpha, backbuffer, other]`, `frame generation: DlssG — the NVIDIA driver agrees`, `upscaler: Dlss
(driver-reported)`, RT Yes. The 2.8.0 SDK presents its generated frames through the body the inline
patches cover; the bypass measured on Dying Light: The Beast is that title's integration. With this row
every measured NVIDIA title prints the rule-6 trio or a counted `none`, and the owner closed the item.
- **2026-09-06, 12:46, Lies of P at FSR 3.1 + FSR frame generation, on the #129 build — §H11 row A1 again,
now with every witness on the page.** `upscaler: Fsr3`, `render -> output: 2560x1440 -> 2560x1440 = 1x` on
3,538 records, `frame generation: FsrFg`, `Native FPS: 59.77 -> Displayed FPS: 119.55 (x2 FG)` over 7,042
presents; the ffx census `upscale-drained=3518 fg-dispatch-drained=3518 frames=3520`, `presents/frame=2.00`,
`frames/upscale-drained=1.00`; `DXGI present counter: unseen=0 over samples=7096` (the FSR 3.1 pacer presents
through the patched body); the NVIDIA driver's word `SR 0x5` / `FG 0x90001` — nothing created, so the
driver-reported rung correctly says nothing beside an AMD identity. The census names only
`amd_fidelityfx_dx12.dll` (the 3.1 monolith Lies of P calls) — the AMD half of 7c is complete on its oracle.
Same run, Rune Factory at DLSS + FG ×4: `125.45 → 498.51 (×3.97)`, `Dlss (driver-reported)`, `DlssG` with the
driver agreeing — the 7b title on its NVIDIA path.
- **2026-09-06, 13:45–14:02, the owner's run on #132 (rung 3 by elimination + the executable scan): Cronos at
XeSS (no FG option), Hell Is Us at XeSS + XeSS-FG, Rune Factory at FSR + FSR FG.**
| Title / setting | Line | `frame generation:` | `executable markers:` |
|---|---|---|---|
| **Cronos**, XeSS, no FG | `FPS: 110.02`, `none` by count, DXGI agrees | `None` | ffxFrameInterpolation ×1, NVSDK_NGX ×112, xefgSwapChain ×13 |
| **Hell Is Us**, XeSS + **XeSS-FG** | `Presented FPS: 186.47`, **`tokens=0`**, `unseen=0` | N/A — no token on this plugin at XeSS; witnesses: not DLSS-G, no FSR dispatch, runtimes nvngx_dlssg + libxess_fg + amd FG, file carries xefgSwapChain | same set |
| **Rune Factory**, FSR + **FSR FG** (compiled in) | `30.05 → 60.05 (×2 FG)` from the token, `unseen=0` | `Active (technology not identified) — by elimination …; the executable itself carries ffxFsr3, ffxFrameInterpolation` | ffxFsr3 ×13, ffxFrameInterpolation ×9, NVSDK_NGX ×112 |
Three readings. Rune Factory is the pre-committed 7b line, verbatim. XeFG presents through the patched
body (0 unseen) so its Displayed rate is measured; its Native is not, because Hell Is Us's plugin requests
no Streamline token at XeSS (it does at DLSS, and Cronos's does at XeSS) — the count producer is the
plugin's choice, and nothing in policy replaces it. The Steam overlay could not show FG on that session
either. The upscaler N/A on both XeSS titles now names Intel's licence as the reason (7c item 4).
## 10 · Telemetry layering
@@ -2178,16 +2431,25 @@ produced no false refusal on any real install.
`15_ROADMAP` §P0. Nothing in P1 starts until all are met.
- [ ] A throwaway build records a real session from a real offline game
- [x] A throwaway build records a real session from a real offline game
reporting **correct** upscaler, quality preset, render → output
resolution, FG factor and RT state — verified against the game's own
settings menu.
settings menu. **Met 2026-09-06 with one amendment, the owner's:** the
quality preset reads `N/A` on every title, by measurement — Streamline's tags
carry no size or preset on Direct3D 12, NVIDIA's override fields are the
override's, XeSS is closed by licence — and an honest `N/A` where measurement
is impossible is the *correct* value CLAUDE.md rule 7 asks for. Upscaler,
render → output (where the vendor's call carries it), FG factor and RT state
are verified against the menus of nine titles (§9). The owner closed 7a on
this reading and closed P0 on it here.
- [x] **Moved to the end of P1** (§R4, decided 2026-08-02) — ~~measured game FPS
impact under 0.5%~~. As written it imported P2's drain, aggregate and
recorder paths; the harness-level per-present cost stayed in P0 and is
measured in §3 (8.4 ns).
- [ ] Every S-series item in `20_OPEN_QUESTIONS.md` resolved, or explicitly
deferred with a written rationale.
- [x] Every S-series item in `20_OPEN_QUESTIONS.md` resolved, or explicitly
deferred with a written rationale. **Met 2026-09-06** (§S24: zero counted
against it). 🚫 S23-2 is a branch-protection setting outside any PR and is
recorded as such, not as met.
- [x] M3 and M4 answered **before** any NVAPI or LHM code is written — both
CLEAR, §0 above.
+253 -72
View File
@@ -8,6 +8,9 @@
"amd_fidelityfx_denoiser_dx12.dll": {
"exportCount": 5,
"version": "1.0.1.0",
"versions": [
"1.0.1.0"
],
"exports": [
"ffxConfigure",
"ffxCreateContext",
@@ -20,6 +23,9 @@
"amd_fidelityfx_dx12.dll": {
"exportCount": 5,
"version": "1.0.1.41314",
"versions": [
"1.0.1.41314"
],
"exports": [
"ffxConfigure",
"ffxCreateContext",
@@ -27,11 +33,16 @@
"ffxDispatch",
"ffxQuery"
],
"copiesFound": 7
"copiesFound": 6
},
"amd_fidelityfx_loader_dx12.dll": {
"exportCount": 5,
"version": "2.1.0.450",
"versions": [
"2.1.0.450",
"1.0.2.44888",
"2.2.0.0"
],
"exports": [
"ffxConfigure",
"ffxCreateContext",
@@ -39,11 +50,16 @@
"ffxDispatch",
"ffxQuery"
],
"copiesFound": 3
"copiesFound": 4
},
"libxess_dx11.dll": {
"exportCount": 51,
"version": "2.0.2.68",
"versions": [
"2.0.2.68",
"2.0.1.41",
"2.0.2.53"
],
"exports": [
"INTC_D3D11_XessCreateContext",
"INTC_D3D11_XessDestroyContext",
@@ -97,15 +113,68 @@
"xessSetVelocityScale",
"xessStartDump"
],
"copiesFound": 5
"copiesFound": 6
},
"libxess_fg.dll": {
"exportCount": 31,
"exportCount": 78,
"version": "1.3.1.68",
"versions": [
"1.3.1.68",
"1.3.1.78",
"1.2.2.118",
"1.2.0.87"
],
"exports": [
"?xefgDebugLogMessage@@YAXPEB_W@Z",
"INTC_D3D11_XessCreateContext",
"INTC_D3D11_XessDestroyContext",
"INTC_D3D11_XessExecute",
"INTC_D3D11_XessForceLegacyScaleFactors",
"INTC_D3D11_XessGetExposureMultiplier",
"INTC_D3D11_XessGetInitParams",
"INTC_D3D11_XessGetInputResolution",
"INTC_D3D11_XessGetIntelXeFXVersion",
"INTC_D3D11_XessGetJitterScale",
"INTC_D3D11_XessGetOptimalInputResolution",
"INTC_D3D11_XessGetProfilingData",
"INTC_D3D11_XessGetVelocityScale",
"INTC_D3D11_XessGetVersion",
"INTC_D3D11_XessInit",
"INTC_D3D11_XessIsOptimalDriver",
"INTC_D3D11_XessSelectNetworkModel",
"INTC_D3D11_XessSetExposureMultiplier",
"INTC_D3D11_XessSetJitterScale",
"INTC_D3D11_XessSetLoggingCallback",
"INTC_D3D11_XessSetVelocityScale",
"INTC_D3D12_GetApplicationInfo",
"INTC_D3D12_GetGpuCrashDumpBufferInfo",
"INTC_D3D12_GpuCrashDumpOnCommandListCreate",
"INTC_D3D12_GpuCrashDumpOnCommandListDestroy",
"INTC_D3D12_GpuCrashDumpOnDeviceDestroy",
"INTC_D3D12_RegisterDriverCallbacks",
"xefgAILGetDecision",
"xefgAILGetVersion",
"xefgAILSetAppXeFGVersion",
"xefgD3D12BuildPipelines",
"xefgD3D12CreateContext",
"xefgD3D12Execute",
"xefgD3D12GetInitParams",
"xefgD3D12GetProfilingData",
"xefgD3D12GetResourcesToDump",
"xefgD3D12Init",
"xefgDebugLog",
"xefgDebugLogMessage",
"xefgDestroyContext",
"xefgGetContextParameterP",
"xefgGetPipelineBuildStatus",
"xefgGetProperties",
"xefgGetVersion",
"xefgSelectTechnique",
"xefgSetColorSpace",
"xefgSetContextParameterF",
"xefgSetLoggingCallback",
"xefgSetSceneChangeThreshold",
"xefgStartDump",
"xefgSwapChainD3D12BuildPipelines",
"xefgSwapChainD3D12CreateContext",
"xefgSwapChainD3D12GetInitializationParameters",
@@ -135,11 +204,17 @@
"xefgSwapChainSetUiCompositionState",
"xefgSwapChainTagFrameConstants"
],
"copiesFound": 5
"copiesFound": 6
},
"libxess.dll": {
"exportCount": 72,
"version": "2.0.2.68",
"versions": [
"2.0.2.68",
"2.0.1.41",
"1.1.0.21",
"2.0.2.53"
],
"exports": [
"INTC_D3D11_XessCreateContext",
"INTC_D3D11_XessDestroyContext",
@@ -217,8 +292,16 @@
"copiesFound": 10
},
"nvngx_dlss.dll": {
"exportCount": 59,
"exportCount": 62,
"version": "310,6,0,0",
"versions": [
"310,6,0,0",
"310,8,0,0",
"2,3,11,0",
"2,2,10,0",
"310,3,0,0",
"310,5,0,0"
],
"exports": [
"NGX_SNIPPETS_GetRequiredDriverSupport",
"NVSDK_NGX_CUDA_CreateFeature",
@@ -228,6 +311,7 @@
"NVSDK_NGX_CUDA_Init",
"NVSDK_NGX_CUDA_Init_Ext",
"NVSDK_NGX_CUDA_Init_Ext1",
"NVSDK_NGX_CUDA_Init1",
"NVSDK_NGX_CUDA_PopulateParameters_Impl",
"NVSDK_NGX_CUDA_ReleaseFeature",
"NVSDK_NGX_CUDA_Shutdown",
@@ -263,7 +347,9 @@
"NVSDK_NGX_GetDriverVersionEx",
"NVSDK_NGX_GetGPUArchitecture",
"NVSDK_NGX_GetSnippetVersion",
"NVSDK_NGX_SetInfoCallback",
"NVSDK_NGX_SetOverrideStatusCallback",
"NVSDK_NGX_SetTelemetryCallback",
"NVSDK_NGX_SetTelemetryEvaluateCallback",
"NVSDK_NGX_VULKAN_CreateFeature",
"NVSDK_NGX_VULKAN_CreateFeature1",
@@ -283,8 +369,14 @@
"copiesFound": 15
},
"nvngx_dlssd.dll": {
"exportCount": 59,
"exportCount": 61,
"version": "310,6,0,0",
"versions": [
"310,6,0,0",
"310,7,129,0",
"310,3,0,0",
"310,5,0,0"
],
"exports": [
"NGX_SNIPPETS_GetRequiredDriverSupport",
"NVSDK_NGX_CUDA_CreateFeature",
@@ -294,6 +386,7 @@
"NVSDK_NGX_CUDA_Init",
"NVSDK_NGX_CUDA_Init_Ext",
"NVSDK_NGX_CUDA_Init_Ext1",
"NVSDK_NGX_CUDA_Init1",
"NVSDK_NGX_CUDA_PopulateParameters_Impl",
"NVSDK_NGX_CUDA_ReleaseFeature",
"NVSDK_NGX_CUDA_Shutdown",
@@ -329,6 +422,7 @@
"NVSDK_NGX_GetDriverVersionEx",
"NVSDK_NGX_GetGPUArchitecture",
"NVSDK_NGX_GetSnippetVersion",
"NVSDK_NGX_SetInfoCallback",
"NVSDK_NGX_SetOverrideStatusCallback",
"NVSDK_NGX_SetTelemetryEvaluateCallback",
"NVSDK_NGX_VULKAN_CreateFeature",
@@ -349,14 +443,21 @@
"copiesFound": 8
},
"nvngx_dlssg.dll": {
"exportCount": 50,
"exportCount": 52,
"version": "310,6,0,0",
"versions": [
"310,6,0,0",
"310,8,0,0",
"310,3,0,0",
"310,5,2,0"
],
"exports": [
"NVSDK_NGX_CUDA_CreateFeature",
"NVSDK_NGX_CUDA_EvaluateFeature",
"NVSDK_NGX_CUDA_GetScratchBufferSize",
"NVSDK_NGX_CUDA_Init",
"NVSDK_NGX_CUDA_Init_Ext",
"NVSDK_NGX_CUDA_PopulateParameters_Impl",
"NVSDK_NGX_CUDA_ReleaseFeature",
"NVSDK_NGX_CUDA_Shutdown",
"NVSDK_NGX_D3D11_CreateFeature",
@@ -387,6 +488,7 @@
"NVSDK_NGX_GetDriverVersionEx",
"NVSDK_NGX_GetGPUArchitecture",
"NVSDK_NGX_GetSnippetVersion",
"NVSDK_NGX_SetInfoCallback",
"NVSDK_NGX_SetOverrideStatusCallback",
"NVSDK_NGX_SetTelemetryEvaluateCallback",
"NVSDK_NGX_VULKAN_CreateFeature",
@@ -403,11 +505,21 @@
"NVSDK_NGX_VULKAN_Shutdown",
"NVSDK_NGX_VULKAN_Shutdown1"
],
"copiesFound": 11
"copiesFound": 10
},
"sl.common.dll": {
"exportCount": 60,
"version": "2,7,4,0",
"versions": [
"2,7,4,0",
"2,7,1,0",
"2,8,0,0",
"2,7,30,0",
"2,7,3,0",
"1.5.6.0",
"2,10,3,0",
"2,7,0,0"
],
"exports": [
"DllMain",
"NVSDK_NGX_D3D11_AllocateParameters",
@@ -470,20 +582,40 @@
"NVSDK_NGX_VULKAN_Shutdown1",
"slGetPluginFunction"
],
"copiesFound": 11
"copiesFound": 10
},
"sl.dlss_g.dll": {
"exportCount": 2,
"version": "2,7,4,0",
"versions": [
"2,7,4,0",
"2,7,1,0",
"2,8,0,0",
"2,7,30,0",
"2,7,3,0",
"1.5.6.0",
"2,10,3,0",
"2,7,0,0"
],
"exports": [
"DllMain",
"slGetPluginFunction"
],
"copiesFound": 11
"copiesFound": 10
},
"sl.interposer.dll": {
"exportCount": 261,
"exportCount": 269,
"version": "2,7,4,0",
"versions": [
"2,7,4,0",
"2,7,1,0",
"2,8,0,0",
"2,7,30,0",
"2,7,3,0",
"1.5.6.0",
"2,10,3,0",
"2,7,0,0"
],
"exports": [
"CreateDXGIFactory",
"CreateDXGIFactory1",
@@ -502,18 +634,26 @@
"slAllocateResources",
"slEvaluateFeature",
"slFreeResources",
"slGetFeatureConfiguration",
"slGetFeatureFunction",
"slGetFeatureRequirements",
"slGetFeatureSettings",
"slGetFeatureVersion",
"slGetHooks",
"slGetNativeInterface",
"slGetNewFrameToken",
"slGetNumHooks",
"slInit",
"slIsFeatureEnabled",
"slIsFeatureLoaded",
"slIsFeatureSupported",
"slSetConstants",
"slSetD3DDevice",
"slSetFeatureConstants",
"slSetFeatureEnabled",
"slSetFeatureLoaded",
"slSetTag",
"slSetTagForFrame",
"slSetVulkanInfo",
"slShutdown",
"slUpgradeInterface",
@@ -747,29 +887,49 @@
"vkWaitForFences",
"vkWaitSemaphores"
],
"copiesFound": 11
"copiesFound": 10
},
"sl.pcl.dll": {
"exportCount": 2,
"version": "2,7,4,0",
"versions": [
"2,7,4,0",
"2,7,1,0",
"2,8,0,0",
"2,7,30,0",
"2,7,3,0",
"2,10,3,0",
"2,7,0,0"
],
"exports": [
"DllMain",
"slGetPluginFunction"
],
"copiesFound": 9
},
"sl.reflex.dll": {
"exportCount": 2,
"version": "2,7,4,0",
"versions": [
"2,7,4,0",
"2,7,1,0",
"2,8,0,0",
"2,7,30,0",
"2,7,3,0",
"1.5.6.0",
"2,10,3,0",
"2,7,0,0"
],
"exports": [
"DllMain",
"slGetPluginFunction"
],
"copiesFound": 10
},
"sl.reflex.dll": {
"exportCount": 2,
"version": "2,7,4,0",
"exports": [
"DllMain",
"slGetPluginFunction"
],
"copiesFound": 11
},
"ffx_backend_dx12_x64.dll": {
"exportCount": 21,
"version": null,
"versions": [],
"exports": [
"?ffxFrameInterpolationUiComposition@@YAHPEBUFfxPresentCallbackDescription@@@Z",
"ffxAssertReport",
@@ -798,6 +958,7 @@
"ffx_frameinterpolation_x64.dll": {
"exportCount": 8,
"version": null,
"versions": [],
"exports": [
"ffxAssertReport",
"ffxAssertSetPrintingCallback",
@@ -813,6 +974,7 @@
"ffx_fsr3_x64.dll": {
"exportCount": 17,
"version": null,
"versions": [],
"exports": [
"ffxAssertReport",
"ffxAssertSetPrintingCallback",
@@ -837,6 +999,7 @@
"ffx_fsr3upscaler_x64.dll": {
"exportCount": 15,
"version": null,
"versions": [],
"exports": [
"ffxAssertReport",
"ffxAssertSetPrintingCallback",
@@ -859,6 +1022,7 @@
"ffx_opticalflow_x64.dll": {
"exportCount": 10,
"version": null,
"versions": [],
"exports": [
"?ffxOpticalflowResourceIsNull@@YA_NUFfxResource@@@Z",
"ffxAssertReport",
@@ -876,45 +1040,52 @@
"sl.dlss_d.dll": {
"exportCount": 2,
"version": "2,7,1,0",
"versions": [
"2,7,1,0",
"2,7,0,0"
],
"exports": [
"DllMain",
"slGetPluginFunction"
],
"copiesFound": 3
"copiesFound": 2
},
"sl.dlss.dll": {
"exportCount": 2,
"version": "2,7,1,0",
"versions": [
"2,7,1,0",
"2,8,0,0",
"1.5.6.0",
"2,7,0,0"
],
"exports": [
"DllMain",
"slGetPluginFunction"
],
"copiesFound": 5
"copiesFound": 4
},
"sl.nis.dll": {
"exportCount": 2,
"version": "2,7,1,0",
"versions": [
"2,7,1,0",
"2,8,0,0"
],
"exports": [
"DllMain",
"slGetPluginFunction"
],
"copiesFound": 3
"copiesFound": 2
},
"amd_fidelityfx_framegeneration_dx12.dll": {
"exportCount": 5,
"version": "3.1.5.44888",
"exports": [
"ffxConfigure",
"ffxCreateContext",
"ffxDestroyContext",
"ffxDispatch",
"ffxQuery"
"versions": [
"3.1.5.44888",
"4.0.0.604",
"4.0.0.0"
],
"copiesFound": 3
},
"amd_fidelityfx_upscaler_dx12.dll": {
"exportCount": 5,
"version": "4.0.2.44888",
"exports": [
"ffxConfigure",
"ffxCreateContext",
@@ -924,9 +1095,32 @@
],
"copiesFound": 4
},
"amd_fidelityfx_upscaler_dx12.dll": {
"exportCount": 5,
"version": "4.0.2.44888",
"versions": [
"4.0.2.44888",
"4.0.3.604",
"4.1.0.0"
],
"exports": [
"ffxConfigure",
"ffxCreateContext",
"ffxDestroyContext",
"ffxDispatch",
"ffxQuery"
],
"copiesFound": 5
},
"nvngx_deepdvc.dll": {
"exportCount": 36,
"exportCount": 37,
"version": "310,2,0,0",
"versions": [
"310,2,0,0",
"310,1,0,0",
"310,3,0,0",
"310,5,2,0"
],
"exports": [
"NvOptimusEnablementCuda",
"NVSDK_NGX_D3D11_CreateFeature",
@@ -953,6 +1147,7 @@
"NVSDK_NGX_GetSnippetVersion",
"NVSDK_NGX_PopulateParameters",
"NVSDK_NGX_SetInfoCallback",
"NVSDK_NGX_SetOverrideStatusCallback",
"NVSDK_NGX_SetTelemetryEvaluateCallback",
"NVSDK_NGX_VULKAN_CreateFeature",
"NVSDK_NGX_VULKAN_CreateFeature1",
@@ -965,20 +1160,27 @@
"NVSDK_NGX_VULKAN_Shutdown",
"NVSDK_NGX_VULKAN_Shutdown1"
],
"copiesFound": 6
"copiesFound": 5
},
"sl.deepdvc.dll": {
"exportCount": 2,
"version": "2,7,30,0",
"versions": [
"2,7,30,0",
"2,7,3,0",
"2,8,0,0",
"2,10,3,0"
],
"exports": [
"DllMain",
"slGetPluginFunction"
],
"copiesFound": 6
"copiesFound": 5
},
"ffx_fsr2_api_dx12_x64.dll": {
"exportCount": 8,
"version": null,
"versions": [],
"exports": [
"ffxAssertReport",
"ffxAssertSetPrintingCallback",
@@ -994,6 +1196,7 @@
"ffx_fsr2_api_vk_x64.dll": {
"exportCount": 11,
"version": null,
"versions": [],
"exports": [
"ffxAssertReport",
"ffxAssertSetPrintingCallback",
@@ -1012,6 +1215,7 @@
"ffx_fsr2_api_x64.dll": {
"exportCount": 11,
"version": null,
"versions": [],
"exports": [
"ffxAssertReport",
"ffxAssertSetPrintingCallback",
@@ -1027,39 +1231,13 @@
],
"copiesFound": 1
},
"amd_fidelityfx_vk.dll": {
"exportCount": 5,
"version": "1.0.1.42386",
"exports": [
"ffxConfigure",
"ffxCreateContext",
"ffxDestroyContext",
"ffxDispatch",
"ffxQuery"
],
"copiesFound": 1
},
"sl.directsr.dll": {
"exportCount": 2,
"version": "2,11,1,0",
"exports": [
"DllMain",
"slGetPluginFunction"
],
"copiesFound": 1
},
"sl.nvperf.dll": {
"exportCount": 2,
"version": "2,11,1,0",
"exports": [
"DllMain",
"slGetPluginFunction"
],
"copiesFound": 1
},
"_nvngx.dll": {
"exportCount": 75,
"version": "32.0.16.1088",
"version": "32.0.16.1664",
"versions": [
"32.0.16.1664",
"32.0.16.1656"
],
"exports": [
"NVSDK_NGX_CUDA_AllocateParameters",
"NVSDK_NGX_CUDA_CreateFeature",
@@ -1137,11 +1315,14 @@
"NVSDK_NGX_VULKAN_Shutdown",
"NVSDK_NGX_VULKAN_Shutdown1"
],
"copiesFound": 1
"copiesFound": 2
},
"nvngx.dll": {
"exportCount": 59,
"version": "30.0.14.9516",
"versions": [
"30.0.14.9516"
],
"exports": [
"NVSDK_NGX_CUDA_AllocateParameters",
"NVSDK_NGX_CUDA_CreateFeature",
@@ -1203,7 +1384,7 @@
"NVSDK_NGX_VULKAN_Shutdown",
"NVSDK_NGX_VULKAN_Shutdown1"
],
"copiesFound": 1
"copiesFound": 2
}
}
}
+45
View File
@@ -0,0 +1,45 @@
<!--
THE ONE ACCURACY BLOCK. Embedded verbatim in README.md and legal/DISCLAIMER.md
between the two HTML-comment markers named `accuracy-block:begin` and
`accuracy-block:end` (spelled out in tools/accuracy-check.ps1 — not here, because a
literal marker inside this comment would end the comment early), and that gate
fails the build when any copy differs from this file
(20_OPEN_QUESTIONS §S23-6: the accuracy blocks were hand-maintained prose that
nothing verified, and DISCLAIMER's went stale four times in one direction and once
in the other). Whether the sentences below are TRUE is still a human's job — the
gate only makes there be one place to get them wrong. Re-read this file in the PR
that changes what FrameLedger.Overlay or the capture host does; date the change.
HTML comments are not part of the block.
-->
> ⚠ **What FrameLedger actually measures today — 2026-09-06.** The software is pre-alpha: the
> measurement path exists as an injected Direct3D 11/12 component and an **unshipped** capture
> host that drives the guard loop and prints a report; there is no Agent loop, no storage, no
> charts, no library import, no UI and no installer yet.
>
> - **Frame times and output resolution:** measured, from the present hook, for injected D3D11/12
> titles, and for Vulkan titles **launched through FrameLedger** (the layer intercepts
> `vkQueuePresentKHR` since 2026-09-06; a Vulkan title already running when FrameLedger attaches is
> not observed). OpenGL/D3D9 intercept nothing yet.
> - **Which upscaler is running:** measured from the API the game calls — DLSS (with Ray
> Reconstruction Yes/No) through NVIDIA Streamline; FSR 2/3.x/4 through AMD's shipped DLLs; DLSS on
> titles that bypass Streamline is reported from the NVIDIA driver's own per-process record,
> labelled *driver-reported*. Intel XeSS is **not** read (its SDK licence forbids it) and reads
> `N/A` by policy; an upscaler compiled into the game executable reads `N/A`.
> - **Quality preset:** `N/A` everywhere. No route this software may use exposes it.
> - **Render → output resolution:** measured where the vendor's own call carries the size (AMD
> dispatches, some Streamline titles); `N/A` where it does not (NVIDIA-direct titles, most
> Direct3D 12 Streamline titles).
> - **Frame generation:** the Displayed rate is counted from presents — including, on one title,
> presents DXGI counted that the hook could not — and the Native rate from the vendor's own
> per-frame calls where the title makes them. Identity: DLSS-G and FSR-FG named from the calls
> the game makes; anything else (XeSS-FG, a generator compiled into the game) is reported *by
> elimination* and never named. Where no per-frame call exists the Native rate is `N/A`.
> - **Ray tracing:** Yes/No measured from DXR dispatches and acceleration-structure builds on
> Direct3D 12; the technique and path tracing are `N/A`.
> - **Not measured at all:** video memory, shader-compilation stutter, PC latency (Reflex), HDR.
> - **Safety:** every pre-injection check runs before injection, including the signed-by-a-known-
> vendor half of the suspicious-module rule (since 2026-09-06), and the unshipped capture host
> re-runs them every 30 s and stops the capture on refusal. No shipped component drives that loop
> yet. There is no override anywhere.
>
> Where a value is not measured it reads `N/A`; the software never substitutes an estimate.
+38 -3
View File
@@ -6,6 +6,8 @@
> ⚠ **Accuracy audit — re-checked 2026-08-14, a FOURTH time, after PR #64. SIX statements below describe behaviour the software does not yet fully have**, and they are flagged here rather than quietly reworded because a document the user accepts must not over-promise.
>
> **A FIFTH time, 2026-09-06, and the mechanism changed rather than the count.** Every drift this block records came from the same cause: the sentence about what the software measures lived in three places and was re-read in none of them. It now lives in **one** — `legal/ACCURACY.md`, embedded verbatim in §4 below and in `README.md`, and `tools/accuracy-check.ps1` fails the build when a copy differs from the source (`20_OPEN_QUESTIONS` §S23-6). The bullets below are the history of the four drifts and are kept as history; the block in §4 is the current statement, dated.
>
> **The fourth drift is the first one that ran the other way, and that is the finding.** Every previous re-count found this document claiming *more* than the software did. #64 landed the upscaler identity hook and this block went on saying "there is no upscaler hook anywhere in the software" — an under-claim, in the one file whose failure mode everybody was watching for in the opposite direction. It went unnoticed for five days for exactly that reason: a reviewer checking whether `legal/` over-promises reads a sentence like that and moves on. **Re-reading this block means checking both directions.**
>
> **The re-count was overdue and this block's own rule is what says so.** The last line of this block requires whoever changes what `FrameLedger.Overlay` does to re-read it. #48 changed exactly that — the Overlay now drops `DXGI_PRESENT_TEST` presents without recording them — and this block was not re-read. That is the second time the rule has been broken since it was written, and both breaches were invisible from inside the PR that caused them.
@@ -16,7 +18,7 @@
>
> - ~~§1's *"what it observes: … presentation, upscaling, ray tracing, pipeline creation"* and §4's *"upscaling, frame-generation and ray-tracing state are read from the parameters the game passes to those APIs"* — **only the presentation path is intercepted.** There is no upscaler hook, no frame-generation hook, no ray-tracing hook and no pipeline hook anywhere in the software.~~ **FALSE SINCE #64, corrected 2026-08-14 — the fourth drift, and this one is the block's own subject.** An **upscaler hook exists**: one detour on `sl.interposer.dll!slEvaluateFeature`, module-scoped, reading one argument. It measures **which upscaler is running** (DLSS, NIS, or `unknown` — never "none") and, for Streamline titles, **whether Ray Reconstruction is active**, which is a `Yes`/`No` the software now publishes. What still does not exist: quality preset, render resolution, frame generation, ray tracing, pipeline. The capture side states all of that in its own data on every frame rather than defaulting to "none", so nothing false is *recorded*; what over-promised was this document, in the direction of under-claiming rather than over-claiming — which is the safer direction and is still wrong. Both sentences are qualified where they sit.
> - §2's *"and every 30 seconds afterwards … it stops at the next scan"* — the pre-injection guard is real and refuses. The **receiving half is implemented**: an injected D3D title removes its hooks within one frame of the stop flag being set. The **sending half is still missing, and the missing part is narrower than this block used to say.** Both the write path (`ShmRingReader.PublishGuardResult`, which maps the shared memory and advances the field) and the read path exist in shipped code and are tested; what does not exist is a production caller that runs the loop between them. A missing loop, not a missing subsystem — and the user-facing consequence is identical: **no re-scan runs and no stop is ever sent.**
> - §2's *"waits **65 seconds** before concluding that contact is lost"* — **the deadline now has a reader, and since 2026-08-05 it runs whether or not the game is presenting.** For one day it was evaluated only on a present, so a title that had hung or been alt-tabbed never reached it — the exact case the mechanism was specified for. A watchdog inside the injected component now checks once a second regardless. Two qualifications remain: it covers **injected Direct3D titles only**, because the Vulkan layer intercepts nothing yet, and **the 65-second value itself is not covered by a test** — the stop is proven to fire, but a suite that runs on every build cannot wait 65 seconds, so what is verified is the mechanism, not the number.
> - §2's *"waits **65 seconds** before concluding that contact is lost"* — **the deadline now has a reader, and since 2026-08-05 it runs whether or not the game is presenting.** For one day it was evaluated only on a present, so a title that had hung or been alt-tabbed never reached it — the exact case the mechanism was specified for. A watchdog inside the injected component now checks once a second regardless. Two qualifications remain: for **Vulkan titles the check runs on each present rather than once a second** — the layer may not own a thread, so a Vulkan title that has stopped presenting is not stopped by the deadline (and presents nothing to be observed) — and **the 65-second value itself is not covered by a test** — the stop is proven to fire, but a suite that runs on every build cannot wait 65 seconds, so what is verified is the mechanism, not the number.
> - §3's *"automatically stops injecting into a game that crashes shortly after injection twice"* — the only trace of this anywhere is a `hook_crash_count` column in a schema for which no `.sql` file exists. There is no design for it.
> - §1's *"Only FrameLedger's own component is ever loaded"* — **narrower than it sounds, and the qualification is now in §1 itself.** The check is a directory test: the payload must resolve into FrameLedger's own install directory. It does not compare a filename, a version or any content, deliberately — a name check would be defeated by any DLL that borrowed the name. A published self-contained build puts several hundred files in that directory.
>
@@ -44,7 +46,7 @@ Install it somewhere only you can write to, and verify the published SHA-256 che
**What it observes:** arguments the game passes to graphics APIs we intercept (presentation, upscaling, ray tracing, pipeline creation) and video-memory usage reported by the graphics runtime.
> **Today that list is two items long: presentation and upscaling** — and the upscaling half is *identity only*. The software can say which upscaler is executing, and whether Ray Reconstruction is active alongside it; it cannot yet say at what quality preset or at what render resolution. No ray-tracing or pipeline hook exists yet, and video-memory usage is not read. The list describes what the software is designed to observe, and the boundary — API arguments and nothing else — holds for all of it. See the accuracy audit at the top.
> **What of that list is observed today is stated once, in §4 below** (the block `legal/ACCURACY.md` carries, dated). The list here describes what the software is designed to observe, and the boundary — API arguments and nothing else — holds for all of it.
**What it never does:** read or write the game's memory outside those API arguments; read save files, input, chat, or network traffic; modify game behavior; hide itself from any security software; or install a kernel driver of its own.
@@ -89,7 +91,40 @@ Software running inside another process can, in principle, destabilize it. Frame
Frame timing is derived from high-resolution timestamps taken at the moment the game presents each frame; upscaling, frame-generation and ray-tracing state are read from the parameters the game passes to those APIs. This is substantially more accurate than inferring settings from files on disk, but **no measurement is guaranteed to be exact**:
> **Frame timing is measured today, and so are two of the settings.** Which upscaler is executing, and whether Ray Reconstruction is running with it, are read from the arguments the game passes — for titles that go through Streamline. **The rest are not measured at all yet**: quality preset, render resolution, frame generation and ray tracing have no hook behind them. Where a value has not been measured the software marks it as unmeasured rather than reporting a zero, so it will read `N/A` and never a confident wrong answer — including for a title whose upscaler runs by a route this hook cannot see, which reports `unknown` rather than "none". See the accuracy audit at the top.
<!-- accuracy-block:begin -->
> ⚠ **What FrameLedger actually measures today — 2026-09-06.** The software is pre-alpha: the
> measurement path exists as an injected Direct3D 11/12 component and an **unshipped** capture
> host that drives the guard loop and prints a report; there is no Agent loop, no storage, no
> charts, no library import, no UI and no installer yet.
>
> - **Frame times and output resolution:** measured, from the present hook, for injected D3D11/12
> titles, and for Vulkan titles **launched through FrameLedger** (the layer intercepts
> `vkQueuePresentKHR` since 2026-09-06; a Vulkan title already running when FrameLedger attaches is
> not observed). OpenGL/D3D9 intercept nothing yet.
> - **Which upscaler is running:** measured from the API the game calls — DLSS (with Ray
> Reconstruction Yes/No) through NVIDIA Streamline; FSR 2/3.x/4 through AMD's shipped DLLs; DLSS on
> titles that bypass Streamline is reported from the NVIDIA driver's own per-process record,
> labelled *driver-reported*. Intel XeSS is **not** read (its SDK licence forbids it) and reads
> `N/A` by policy; an upscaler compiled into the game executable reads `N/A`.
> - **Quality preset:** `N/A` everywhere. No route this software may use exposes it.
> - **Render → output resolution:** measured where the vendor's own call carries the size (AMD
> dispatches, some Streamline titles); `N/A` where it does not (NVIDIA-direct titles, most
> Direct3D 12 Streamline titles).
> - **Frame generation:** the Displayed rate is counted from presents — including, on one title,
> presents DXGI counted that the hook could not — and the Native rate from the vendor's own
> per-frame calls where the title makes them. Identity: DLSS-G and FSR-FG named from the calls
> the game makes; anything else (XeSS-FG, a generator compiled into the game) is reported *by
> elimination* and never named. Where no per-frame call exists the Native rate is `N/A`.
> - **Ray tracing:** Yes/No measured from DXR dispatches and acceleration-structure builds on
> Direct3D 12; the technique and path tracing are `N/A`.
> - **Not measured at all:** video memory, shader-compilation stutter, PC latency (Reflex), HDR.
> - **Safety:** every pre-injection check runs before injection, including the signed-by-a-known-
> vendor half of the suspicious-module rule (since 2026-09-06), and the unshipped capture host
> re-runs them every 30 s and stops the capture on refusal. No shipped component drives that loop
> yet. There is no override anywhere.
>
> Where a value is not measured it reads `N/A`; the software never substitutes an estimate.
<!-- accuracy-block:end -->
- Frame timing: typically better than 0.05% error; hardware sensors carry their own accuracy limits (±1–2 °C is normal).
- 1% Low and 0.1% Low are statistical and are hidden when the sample size is insufficient.
+2
View File
@@ -57,6 +57,7 @@ Telemetry is layered so no proprietary vendor licence is ever required (`docs/18
| **DXGI + Windows performance counters (PDH)** | Vendor-neutral baseline: utilisation, VRAM, adapter identity | Windows OS APIs | n/a |
| **NVIDIA Streamline headers** (`sl.h`, its eight-file include closure, and `sl_dlss.h`) | Declarations only — `sl::Feature`, the `kFeature*` ids and `PFun_slEvaluateFeature` — so the Overlay's upscaler hook has the vendor's own signature instead of a hand-written guess. **Types and `decltype` only: never linked**, or `sl.interposer.dll` would become a load-time dependency and the Overlay would fail to load in every game that ships no Streamline | **MIT** — <https://github.com/NVIDIA-RTX/Streamline>, `main`, 2026-08-09 | **Vendored 2026-08-09** at `src/native/third_party/streamline/`: `license.txt` and ten headers. **`sl_nvperf.h` is excluded** — the same `license.txt` carries a second, proprietary "NSight Perf SDK License, Version 2023.3" block naming `sl_nvperf.h` and `sl_nvperf.dll`. **All of `external/` is excluded** — upstream's `external/ngx-sdk/` is the RTX SDKs Licence. `license-check.ps1` asserts both exclusions and the grant text |
| **AMD FidelityFX SDK headers** (`ffx_api.h`, `ffx_api_types.h`, `ffx_upscale.h`, `ffx_framegeneration.h`, `ffx_framegeneration_api_types.h`) | Declarations only — `ffxApiHeader::type`, the `FFX_API_*_DESC_TYPE_*` values, `ffxDispatchDescUpscale::renderSize`, the frame-generation `Prepare` descriptors' `frameID` and `PfnFfxDispatch` — so the Overlay's AMD hook decodes the dispatch descriptor by the vendor's own layout instead of a guess. **Types only: never linked**, and the Overlay defines none of the names the header declares `dllexport` (`hookinventory-check` Pass C reads its export table) | **MIT, by exception** — <https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK> tag `v2.3.0` (`60f4ea81`, 2026-06-24). Upstream's `docs/license.md` is a binary-only default licence followed by an MIT exception list; on 2026-09-04 that list named all 845 files in the tree, these five among them, and each header carries the grant in its own banner | **Vendored 2026-09-04** at `src/native/third_party/fidelityfx/`: `license.md` verbatim (exception list included) and five headers in upstream's `Kits/FidelityFX/…` layout. **No `signedbin/`, no `.lib`, no source, no `dx12/` backend headers** (no consumer yet). `license-check.ps1` §2d asserts every vendored path is on the exception list and every header carries the grant |
| **AMD FidelityFX SDK 3.0 host headers** (`ffx_fsr3.h` and its nine-file include closure: `ffx_interface.h`, `ffx_fsr3upscaler.h`, `ffx_frameinterpolation.h`, `ffx_opticalflow.h`, `ffx_assert.h`, `ffx_types.h`, `ffx_error.h`, `ffx_util.h`, `gpu/fsr3upscaler/ffx_fsr3upscaler_resources.h`) | Declarations only — `FfxFsr3DispatchUpscaleDescription::renderSize` and the type of `ffxFsr3ContextDispatchUpscale` — so the Overlay's hook on the FSR 3.0 **host** DLL (`ffx_fsr3_x64.dll`, Cyberpunk 2077's copy, which upscales through named exports rather than the ffx-api facade) reads the render extent by the vendor's own layout. **Types and `decltype` only: never linked**, and the Overlay defines none of the names the header declares `dllexport` (`hookinventory-check` Pass C reads its export table; the `ffx_fsr3_x64.dll` fixture in `tools/vendor-stubs` is that parser's second positive control) | **MIT** — <https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK> tag `fsr3-v3.0.4` (`55ff22bb`). The root `LICENSE.txt` at that tag is the MIT grant verbatim and every header carries it inline — a different licence *shape* from the `v2.3.0` row above, which is why it is a separate directory and `license-check.ps1` §2e rather than §2d. The tag is the one whose declarations match the module the title ships (twelve `ffxFsr3*` exports); `v1.1.4`, which the docs first named, declares three more and appends fields to the dispatch descriptor | **Vendored 2026-09-05** at `src/native/third_party/fidelityfx-fsr3/`: `LICENSE.txt` verbatim and ten headers in upstream's `sdk/include/FidelityFX/…` layout, each blob sha checked against the upstream tree. **No backends, no `.cpp`, no shaders, no samples.** `license-check.ps1` §2e asserts the root grant and every header's banner, file by file. Same MIT text as the row above, so `legal/licenses/fidelityfx-MIT.txt` is the notice for both |
| NVIDIA **NGX** / **Streamline**, AMD **FidelityFX**, Intel **XeSS** **runtimes** (the DLLs themselves) | Not loaded, not linked, not redistributed. We observe the calls a *game* makes to the copies it ships (`docs/17_HOOK_ENGINE.md`). Unchanged by the row above, which vendors **headers** and no runtime | — | **No vendor upscaler code is distributed by FrameLedger** |
### GPL-3.0 compatibility
@@ -98,5 +99,6 @@ All product names, logos, and brands are property of their respective owners and
- [ ] MPL-2.0 source-availability note points to upstream LibreHardwareMonitor repository
- [x] LHM checked for MPL-2.0 Exhibit B on any depended-upon file — clear as of 0.9.6 / commit `3d331e33`, 2026-08-02
- [x] **AMD FidelityFX headers are vendored** (2026-09-04) — five headers, MIT **by exception**: `license-check.ps1` §2d asserts each vendored path against the exception list inside the vendored `license.md` and each header's own banner, file by file. No binary, no source
- [x] **AMD FidelityFX SDK 3.0 host headers are vendored** (2026-09-05) — ten headers at tag `fsr3-v3.0.4`, MIT at the root **and** inline: `license-check.ps1` §2e asserts the root grant and every header's banner, file by file, in a directory of its own because the licence shape differs from the row above. No binary, no source, no shaders
- [x] **NVAPI is vendored** (2026-08-05) and all nine headers carry their `SPDX-License-Identifier: MIT` blocks unmodified — asserted file by file, not sampled. `license-check.ps1` enforces that this line and the table agree with the filesystem, **in both directions**: vendoring the material while the table still said "Not yet" failed the build, which is how this row came to be flipped
- [ ] No Intel IGCL or AMD ADLX material anywhere in the tree (CI grep, see `docs/13_CI_CD.md`)
+6
View File
@@ -189,6 +189,12 @@
"19_SAFETY: name fragment AND not signed by a known vendor => warn-and-refuse.",
"",
"trustedSigners are matched against the certificate subject's O= field, NOT CN=.",
"",
"BOUNDED BY CODE (owner decision 2026-09-06, 20_OPEN_QUESTIONS S19(b)): the guard trusts an",
"organisation only if it is on THIS list AND on the list compiled into FrameLedger.Guard.dll",
"(IsCompiledTrustedSigner). Adding a name here that the binary does not know widens nothing;",
"widening is a reviewed code change. Removing a name here narrows, which data may do.",
"",
"Measured 2026-08-02 on Windows 11 26300, and the two fields genuinely differ:",
" kernel32.dll CN='Microsoft Windows' O='Microsoft Corporation'",
" nvapi64.dll CN='Microsoft Windows Hardware Compatibility Publisher' O='Microsoft Corporation'",
@@ -31,15 +31,27 @@ namespace FrameLedger.Application.AntiCheat;
public sealed class HookRequest
{
private HookRequest(int targetPid, string payloadPath, bool hookEnabled, DateTimeOffset? consentedAt,
string? blockedReason)
string? blockedReason, int waitForPresentationRuntimeMs)
{
TargetPid = targetPid;
PayloadPath = payloadPath;
HookEnabled = hookEnabled;
ConsentedAt = consentedAt;
BlockedReason = blockedReason;
WaitForPresentationRuntimeMs = waitForPresentationRuntimeMs;
}
/// <summary>
/// Launch mode's budget: how long the guard may wait for the target to map a presentation runtime
/// before injecting. Zero — the default, and attach mode — asks the guard to inject now.
/// </summary>
/// <remarks>
/// It cannot widen what is injected or skip a check: a positive value routes the request through
/// <see cref="IAntiCheatGuard.GuardedInjectWhenReadyAsync"/>, which runs the same full scan later
/// rather than a smaller one sooner.
/// </remarks>
public int WaitForPresentationRuntimeMs { get; }
/// <summary>The process to inject into.</summary>
public int TargetPid { get; }
@@ -75,17 +87,20 @@ public sealed class HookRequest
/// <param name="observed">The executable as it is on disk right now.</param>
/// <param name="targetPid">The process to inject into.</param>
/// <param name="payloadPath">The Overlay, resolved beside the guard (§S22).</param>
/// <param name="waitForPresentationRuntimeMs">Launch mode's budget; zero is attach mode.</param>
public static HookRequest FromConsent(
GameConsentRecord record, ExecutableFingerprint observed, int targetPid, string payloadPath)
GameConsentRecord record, ExecutableFingerprint observed, int targetPid, string payloadPath,
int waitForPresentationRuntimeMs = 0)
{
ArgumentException.ThrowIfNullOrWhiteSpace(payloadPath);
ArgumentOutOfRangeException.ThrowIfNegative(waitForPresentationRuntimeMs);
// A record nobody stored has enabled nothing and consented to nothing. Checked first so the
// fields below are never read off a default value.
if (!record.IsFromStore)
{
return new HookRequest(targetPid, payloadPath, hookEnabled: false, consentedAt: null,
blockedReason: null);
blockedReason: null, waitForPresentationRuntimeMs);
}
// A TIMESTAMP IS NOT CONSENT. games.hook_consent_at is a bare DateTime, so a record could carry
@@ -106,6 +121,7 @@ public sealed class HookRequest
consentedAt = null;
}
return new HookRequest(targetPid, payloadPath, record.HookEnabled, consentedAt, record.BlockedReason);
return new HookRequest(targetPid, payloadPath, record.HookEnabled, consentedAt, record.BlockedReason,
waitForPresentationRuntimeMs);
}
}
@@ -76,6 +76,11 @@ public sealed class HookedCaptureGate(IAntiCheatGuard guard)
return AntiCheatVerdict.Refused(AntiCheatRefusalReason.PreviouslyBlocked, "previously blocked", blocked);
}
return await _guard.GuardedInjectAsync(request.TargetPid, request.PayloadPath, ct).ConfigureAwait(false);
// Launch mode is the same gate reached through the guard's WAITING entry: the consent checks
// above are identical, and what differs is only WHEN the guard's full scan runs (P1 item 2).
return request.WaitForPresentationRuntimeMs > 0
? await _guard.GuardedInjectWhenReadyAsync(request.TargetPid, request.PayloadPath,
request.WaitForPresentationRuntimeMs, ct).ConfigureAwait(false)
: await _guard.GuardedInjectAsync(request.TargetPid, request.PayloadPath, ct).ConfigureAwait(false);
}
}
@@ -36,6 +36,23 @@ public interface IAntiCheatGuard
/// </summary>
ValueTask<AntiCheatVerdict> GuardedInjectAsync(int targetPid, string payloadPath, CancellationToken ct = default);
/// <summary>
/// Launch mode (P1 item 2). Wait — up to <paramref name="timeoutMs"/> — until the target has mapped a
/// presentation runtime, then run every check and inject exactly as <see cref="GuardedInjectAsync"/>
/// does. The wait decides WHEN the guard runs and nothing about whether it passes.
/// </summary>
/// <remarks>
/// <c>20_OPEN_QUESTIONS</c> §S1: a target held at its first instruction has loaded nothing, so the
/// module scan cannot run before the loader has. The guard therefore polls the loader's own answer
/// (through the module seam, matching no blocklist) and runs in full the moment a runtime is there. A
/// target that exits first, or never maps one, refuses with
/// <see cref="AntiCheatRefusalReason.LaunchTargetExited"/> /
/// <see cref="AntiCheatRefusalReason.LaunchNoPresentationRuntime"/>. The caller launched and holds
/// the process; the guard creates and terminates nothing.
/// </remarks>
ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath, int timeoutMs,
CancellationToken ct = default);
/// <summary>
/// Check 4 asked before anything is launched: does this game directory ship
/// anti-cheat? Answers FR-2.2's question — whether the hooking toggle may be
@@ -1,5 +1,7 @@
using System.Diagnostics;
using FrameLedger.Application.AntiCheat;
using FrameLedger.Application.Consent;
using FrameLedger.CaptureHost.Consume;
using FrameLedger.Domain.AntiCheat;
using FrameLedger.Domain.Consent;
using FrameLedger.Infrastructure.Ipc;
@@ -28,7 +30,10 @@ internal sealed class CaptureLoop(
ITargetResolver resolver,
Func<int, ITargetLiveness?> liveness,
Func<int, (ICaptureSink? Sink, ShmAttachRefusal Refusal)> attach,
CaptureOptions options)
CaptureOptions options,
Func<int, RuntimeModuleSet>? modules = null,
Func<int, NgxDriverState>? ngx = null,
Func<string, string, (int Pid, ITargetLiveness Alive)?>? launcher = null)
{
/// <summary>Start one session, or say why not.</summary>
/// <remarks>
@@ -81,24 +86,90 @@ internal sealed class CaptureLoop(
}
GameConsentRecord record = await store.FindAsync(normalisedExePath, ct).ConfigureAwait(false);
if (ConsentRefusal(record, observed) is SessionEndReason refused)
{
return new CaptureResult { Reason = refused };
}
return await SessionAsync(pid.Value, alive, record, observed!.Value, payloadPath, started: null, ct)
.ConfigureAwait(false);
}
/// <summary>Launch mode (P1 item 2): start the consented executable, then the same session.</summary>
/// <remarks>
/// <para>
/// <b>The process is started FIRST and consent is still the gate's, one process later.</b> Attach mode
/// resolves a pid before consent because a <see cref="HookRequest"/> needs one; here the pid is made
/// rather than found, and the operator asked for the game to start. A refusal of any kind — no
/// record, an anti-cheat hit, no runtime inside the budget — leaves the title running, unhooked,
/// which is the product's Tier 2: this host never terminates what it launched.
/// </para>
/// <para>
/// <b>The guard is reached through its waiting entry, with the loop's budget, and never the plain
/// one</b>: <see cref="HookRequest.WaitForPresentationRuntimeMs"/> is what routes it, and the wait is
/// measured here — from the start of the process to the guard's answer — because that number is
/// the cost <c>20_OPEN_QUESTIONS</c> §S1 deferred on. <c>FlWriterState.dxgiPresentsBeforeHook</c>
/// is its other half.
/// </para>
/// </remarks>
public async Task<CaptureResult> RunLaunchedAsync(string normalisedExePath, ExecutableFingerprint? observed,
string payloadPath, string arguments, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(normalisedExePath);
if (launcher is null)
{
throw new InvalidOperationException("this loop was built without a launcher; launch mode is unavailable");
}
var started = Stopwatch.StartNew();
(int Pid, ITargetLiveness Alive)? launched = launcher(normalisedExePath, arguments ?? string.Empty);
if (launched is null)
{
return new CaptureResult { Reason = SessionEndReason.LaunchCannotStart };
}
using ITargetLiveness alive = launched.Value.Alive;
GameConsentRecord record = await store.FindAsync(normalisedExePath, ct).ConfigureAwait(false);
if (ConsentRefusal(record, observed) is SessionEndReason refused)
{
return new CaptureResult { Reason = refused };
}
return await SessionAsync(launched.Value.Pid, alive, record, observed!.Value, payloadPath, started, ct)
.ConfigureAwait(false);
}
/// <summary>The two refusals the loop makes itself, before the gate (see <see cref="RunAsync"/>'s remarks).</summary>
private static SessionEndReason? ConsentRefusal(GameConsentRecord record, ExecutableFingerprint? observed)
{
if (record.PreScanUnverified)
{
return new CaptureResult { Reason = SessionEndReason.PreScanCouldNotVerify };
return SessionEndReason.PreScanCouldNotVerify;
}
if (observed is null)
{
return new CaptureResult { Reason = SessionEndReason.ExecutableUnreadable };
}
return observed is null ? SessionEndReason.ExecutableUnreadable : null;
}
HookRequest request = HookRequest.FromConsent(record, observed.Value, pid.Value, payloadPath);
/// <summary>Gate, attach, drain — shared by both modes; <paramref name="started"/> non-null is launch mode.</summary>
private async Task<CaptureResult> SessionAsync(int pid, ITargetLiveness alive, GameConsentRecord record,
ExecutableFingerprint observed, string payloadPath, Stopwatch? started, CancellationToken ct)
{
int waitMs = started is null ? 0 : checked((int)options.LaunchWaitBudget.TotalMilliseconds);
HookRequest request = HookRequest.FromConsent(record, observed, pid, payloadPath, waitMs);
AntiCheatVerdict verdict = await gate.StartAsync(request, ct).ConfigureAwait(false);
if (!verdict.IsAllowed)
TimeSpan? launchWait = started?.Elapsed;
// THE ONE VERDICT THAT IS NEITHER: the guard passed and injected nothing because the target
// presents through Vulkan, where the implicit layer is the capture side (P1 item 3). The ring
// to attach to is the layer's, and it appears at the title's first vkCreateDevice -- which is
// why the attach budget is launch mode's, not the 5 s an already-injected Overlay gets.
bool layered = verdict.Reason == AntiCheatRefusalReason.TargetIsVulkanLayered;
if (!verdict.IsAllowed && !layered)
{
return new CaptureResult { Reason = RefusalOf(verdict.Reason), Verdict = verdict };
return new CaptureResult { Reason = RefusalOf(verdict.Reason), Verdict = verdict, LaunchWait = launchWait };
}
(ICaptureSink? sink, ShmAttachRefusal refusal) = await AttachAsync(pid.Value, ct).ConfigureAwait(false);
TimeSpan attachBudget = layered ? options.LaunchWaitBudget : options.AttachBudget;
(ICaptureSink? sink, ShmAttachRefusal refusal) = await AttachAsync(pid, attachBudget, ct).ConfigureAwait(false);
if (sink is null)
{
return new CaptureResult
@@ -106,12 +177,14 @@ internal sealed class CaptureLoop(
Reason = SessionEndReason.AttachRefused,
Verdict = verdict,
AttachRefusal = refusal,
LaunchWait = launchWait,
};
}
using (sink)
{
return await DrainAsync(pid.Value, alive, sink, verdict, ct).ConfigureAwait(false);
CaptureResult result = await DrainAsync(pid, alive, sink, verdict, ct).ConfigureAwait(false);
return result with { LaunchWait = launchWait };
}
}
@@ -120,6 +193,8 @@ internal sealed class CaptureLoop(
AntiCheatRefusalReason.HookNotEnabled => SessionEndReason.RefusedHookNotEnabled,
AntiCheatRefusalReason.ConsentMissing => SessionEndReason.RefusedConsentMissing,
AntiCheatRefusalReason.PreviouslyBlocked => SessionEndReason.RefusedPreviouslyBlocked,
AntiCheatRefusalReason.LaunchTargetExited => SessionEndReason.LaunchTargetExited,
AntiCheatRefusalReason.LaunchNoPresentationRuntime => SessionEndReason.LaunchNoPresentationRuntime,
_ => SessionEndReason.RefusedByGuard,
};
@@ -133,10 +208,11 @@ internal sealed class CaptureLoop(
/// middle one is transient. Every other refusal is terminal, and retrying one
/// would turn a clear answer into a timeout.
/// </remarks>
private async Task<(ICaptureSink? Sink, ShmAttachRefusal Refusal)> AttachAsync(int pid, CancellationToken ct)
private async Task<(ICaptureSink? Sink, ShmAttachRefusal Refusal)> AttachAsync(int pid, TimeSpan budget,
CancellationToken ct)
{
ShmAttachRefusal refusal = ShmAttachRefusal.NotEvaluated;
DateTimeOffset deadline = DateTimeOffset.UtcNow + options.AttachBudget;
DateTimeOffset deadline = DateTimeOffset.UtcNow + budget;
while (DateTimeOffset.UtcNow < deadline)
{
(ICaptureSink? sink, refusal) = attach(pid);
@@ -158,11 +234,15 @@ internal sealed class CaptureLoop(
var records = new List<FlFrameRecord>();
var gaps = new List<ulong>();
var focus = new FocusTally();
SessionEndReason end = await SuperviseAsync(pid, alive, sink, supervisor, records, gaps, focus, ct)
var loaded = new ModuleTally(modules, ngx);
SessionEndReason end = await SuperviseAsync(pid, alive, sink, supervisor, records, gaps, focus, loaded, ct)
.ConfigureAwait(false);
return new CaptureResult
{
RuntimeModules = loaded.Set,
NgxDriver = loaded.Ngx,
TouchQpc = loaded.TouchQpc,
Reason = end,
Verdict = verdict,
AttachRefusal = ShmAttachRefusal.Ok,
@@ -213,12 +293,11 @@ internal sealed class CaptureLoop(
/// </remarks>
private async Task<SessionEndReason> SuperviseAsync(int pid, ITargetLiveness alive, ICaptureSink sink,
GuardSupervisor supervisor, List<FlFrameRecord> records, IList<ulong> gaps, FocusTally focus,
CancellationToken ct)
ModuleTally loaded, CancellationToken ct)
{
var buffer = new FlFrameRecord[512];
bool mayContinue = await supervisor.ScanOnceAsync(pid, ct).ConfigureAwait(false);
sink.PublishGuardResult(supervisor.CompletedEvaluations, supervisor.UnhookRequested);
bool mayContinue = await ScanAsync(pid, sink, supervisor, loaded, ct).ConfigureAwait(false);
DateTimeOffset nextScan = DateTimeOffset.UtcNow + options.ScanInterval;
DateTimeOffset attachSettledAt = DateTimeOffset.UtcNow + options.AttachBudget;
@@ -250,7 +329,7 @@ internal sealed class CaptureLoop(
{
try
{
mayContinue = await supervisor.ScanOnceAsync(pid, ct).ConfigureAwait(false);
mayContinue = await ScanAsync(pid, sink, supervisor, loaded, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
@@ -258,13 +337,16 @@ internal sealed class CaptureLoop(
break;
}
sink.PublishGuardResult(supervisor.CompletedEvaluations, supervisor.UnhookRequested);
nextScan = DateTimeOffset.UtcNow + options.ScanInterval;
}
await Task.Delay(options.DrainInterval, ct).ConfigureAwait(false);
}
// ONE LAST SNAPSHOT before the last drain, so a module that loaded after the final scan is
// still named; on TargetExited it reads nothing, which the tally counts rather than hides.
loaded.Take(pid);
// ONE LAST DRAIN ON EVERY PATH, including the faulted one — that is the whole point of catching
// the mid-loop throw rather than letting it leave the method. Then let go promptly: holding the
// section keeps the named object alive, and a recycled pid's Overlay would hit
@@ -273,6 +355,57 @@ internal sealed class CaptureLoop(
return Conclude(end, faulted, mayContinue);
}
/// <summary>One guard scan: evaluate, publish the supervisor's own count, then snapshot the modules.</summary>
/// <remarks>
/// <b>The module snapshot rides beside the guard scan, never on its own cadence.</b> The scan is
/// the moment this host already enumerates the target's modules, and a vendor runtime that loads
/// late (a title enabling frame generation from its menu) is caught by the next scan the way the
/// Overlay's watchdog catches it on the next tick. The scan's exception propagates: the caller
/// decides whether a throw ends the session or only the supervision.
/// </remarks>
private static async Task<bool> ScanAsync(int pid, ICaptureSink sink, GuardSupervisor supervisor,
ModuleTally loaded, CancellationToken ct)
{
bool mayContinue = await supervisor.ScanOnceAsync(pid, ct).ConfigureAwait(false);
sink.PublishGuardResult(supervisor.CompletedEvaluations, supervisor.UnhookRequested);
loaded.Take(pid);
return mayContinue;
}
/// <summary>
/// Accumulates module snapshots and the driver's NGX word; a loop built without a source takes none.
/// The NGX probe rides on the same touch as the snapshot: out of process, and the moment a title that
/// enabled DLSS from its menu is caught by the next scan, exactly as a late-loading module is.
/// </summary>
private sealed class ModuleTally(Func<int, RuntimeModuleSet>? source, Func<int, NgxDriverState>? ngxSource)
{
public RuntimeModuleSet Set { get; private set; } = RuntimeModuleSet.Empty;
public NgxDriverState Ngx { get; private set; } = NgxDriverState.NotRun;
/// <summary>
/// When this host touched the target — a guard scan just completed, and the module snapshot
/// is about to run — as QPC ticks (<see cref="System.Diagnostics.Stopwatch.GetTimestamp"/> is
/// QueryPerformanceCounter on Windows, the clock the records carry). Recorded whether or not a
/// snapshot source exists, because it is the stall diagnostic's alibi, not the snapshot's.
/// </summary>
public List<long> TouchQpc { get; } = [];
public void Take(int pid)
{
TouchQpc.Add(System.Diagnostics.Stopwatch.GetTimestamp());
if (source is not null)
{
Set = Set.Merge(source(pid));
}
if (ngxSource is not null)
{
Ngx = Ngx.Merge(ngxSource(pid));
}
}
}
/// <summary>
/// Turns the loop's exit condition into the reason a caller sees.
/// </summary>
@@ -14,4 +14,11 @@ internal sealed record CaptureOptions
/// <summary>Zero means "until the target exits".</summary>
public TimeSpan MaxDuration { get; init; } = TimeSpan.Zero;
/// <summary>
/// Launch mode: how long the guard may wait for the launched target to map a presentation runtime
/// before it gives up with <c>LaunchNoPresentationRuntime</c>. A launcher that sits on its window
/// past this is a launcher, and the descendant election is the Agent's (P2).
/// </summary>
public TimeSpan LaunchWaitBudget { get; init; } = TimeSpan.FromSeconds(60);
}
@@ -1,3 +1,4 @@
using FrameLedger.CaptureHost.Consume;
using FrameLedger.Domain.AntiCheat;
using FrameLedger.Shared;
@@ -44,4 +45,30 @@ internal sealed record CaptureResult
/// configured for ×2.
/// </remarks>
public long ForegroundTicks { get; init; }
/// <summary>
/// The census-named modules the target had loaded, with their file versions, merged over every
/// snapshot the loop took beside a guard scan. <see cref="RuntimeModuleSet.Empty"/> when the loop
/// had no snapshot source.
/// </summary>
public RuntimeModuleSet RuntimeModules { get; init; } = RuntimeModuleSet.Empty;
/// <summary>
/// The NVIDIA driver's per-process NGX word, probed out of process beside each module snapshot and merged.
/// <see cref="NgxDriverState.NotRun"/> when the loop had no probe.
/// </summary>
public NgxDriverState NgxDriver { get; init; } = NgxDriverState.NotRun;
/// <summary>
/// QPC timestamps of every moment this host touched the target's process — a guard scan
/// completing, followed by the module snapshot — in the records' own clock, so a stall in the
/// frame stream can be checked against what FrameLedger itself was doing at that moment.
/// </summary>
public IReadOnlyList<long> TouchQpc { get; init; } = [];
/// <summary>
/// Launch mode only: from the process being started to the guard's answer — the wait for a
/// presentation runtime plus the full scan and the injection. Null in attach mode.
/// </summary>
public TimeSpan? LaunchWait { get; init; }
}
@@ -0,0 +1,117 @@
using System.Text;
using FrameLedger.CaptureHost.Consume;
namespace FrameLedger.CaptureHost.Capture;
/// <summary>
/// Streams the executable file from disk once and counts the vendor SDK strings in it.
/// </summary>
/// <remarks>
/// Chunked with an overlap of the longest marker, so a string straddling two reads is still one hit — a test
/// pins that with a tiny chunk. ASCII, case-sensitive: these are symbol prefixes and product names as the
/// SDKs spell them. Per-marker hits are capped so a file that repeats a string cannot make the scan slow to
/// describe. Every failure is an <see cref="ExecutableMarkers.Error"/>, never a throw into the loop.
/// </remarks>
internal static class ExecutableMarkerScan
{
private const int _defaultChunkBytes = 4 * 1024 * 1024;
private const int _hitCap = 1000;
/// <summary>
/// The strings, what they belong to, and whether that SDK can generate frames. Only the last column moves the
/// census's sentence; the rest are printed for the reader.
/// </summary>
private static readonly (string Name, string Vendor, bool FgCapable)[] _table =
[
("FidelityFX", "AMD FidelityFX", false),
("ffxFsr2", "AMD FSR 2 API", false),
("ffxFsr3", "AMD FSR 3 API (upscaler and frame interpolation)", true),
("ffxFrameInterpolation", "AMD FSR 3 frame interpolation", true),
("NVSDK_NGX", "NVIDIA NGX SDK (the static half; DLSS-G still needs nvngx_dlssg.dll)", false),
("xessD3D12", "Intel XeSS SDK", false),
("xefgSwapChain", "Intel XeSS-FG SDK", true),
];
public static ExecutableMarkers Scan(string exePath) => Scan(exePath, _defaultChunkBytes);
public static ExecutableMarkers Scan(string exePath, int chunkBytes)
{
ArgumentOutOfRangeException.ThrowIfLessThan(chunkBytes, 64);
int[] hits = new int[_table.Length];
byte[][] needles = [.. _table.Select(t => Encoding.ASCII.GetBytes(t.Name))];
int overlap = needles.Max(n => n.Length) - 1;
long scanned;
try
{
scanned = ScanFile(exePath, chunkBytes, needles, overlap, hits);
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException)
{
return new ExecutableMarkers([], 0, e.Message);
}
List<ExecutableMarker> markers = [];
for (int i = 0; i < _table.Length; i++)
{
markers.Add(new ExecutableMarker(_table[i].Name, _table[i].Vendor, _table[i].FgCapable, hits[i]));
}
return new ExecutableMarkers(markers, scanned, null);
}
private static long ScanFile(string exePath, int chunkBytes, byte[][] needles, int overlap, int[] hits)
{
using FileStream f = new(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
byte[] buffer = new byte[overlap + chunkBytes];
int carried = 0;
long scanned = 0;
while (true)
{
int read = f.Read(buffer, carried, chunkBytes);
if (read == 0)
{
break;
}
scanned += read;
int length = carried + read;
CountIn(buffer.AsSpan(0, length), needles, hits, carried);
// Carry the tail so a marker split across two reads is seen once, on the next pass.
carried = Math.Min(overlap, length);
Buffer.BlockCopy(buffer, length - carried, buffer, 0, carried);
}
return scanned;
}
/// <summary>
/// Count each needle in <paramref name="window"/>. A hit is counted only if it does not lie wholly inside
/// the carried prefix (<paramref name="carried"/> bytes), which the previous pass already counted.
/// </summary>
private static void CountIn(ReadOnlySpan<byte> window, byte[][] needles, int[] hits, int carried)
{
for (int n = 0; n < needles.Length; n++)
{
ReadOnlySpan<byte> needle = needles[n];
int at = 0;
while (hits[n] < _hitCap)
{
int found = window[at..].IndexOf(needle);
if (found < 0)
{
break;
}
int start = at + found;
if (start + needle.Length > carried)
{
hits[n]++;
}
at = start + 1;
}
}
}
}
@@ -0,0 +1,66 @@
using System.ComponentModel;
using System.Diagnostics;
using FrameLedger.CaptureHost.Consume;
namespace FrameLedger.CaptureHost.Capture;
/// <summary>
/// Runs <c>fl-probe-nvapi --ngx-state &lt;pid&gt;</c> beside this host and parses its machine line.
/// </summary>
/// <remarks>
/// <para>
/// <b>Out of process, on purpose.</b> The probe links <c>nvapi64.lib</c> (MIT, vendored) and asks the driver about
/// a pid; nothing is injected, nothing in the target is touched, no consent is involved. Spawning the tool this
/// repo already builds keeps the native layer reachable only through what is already there (CLAUDE.md: no
/// P/Invoke outside <c>Infrastructure</c>) — the day the shipped Agent wants this fact, it goes through
/// <c>Infrastructure</c> as a native call, not through a child process.
/// </para>
/// <para>
/// The probe is staged beside the host by the project file the way the Overlay payload is; a missing binary is
/// an outcome the report prints, never an exception the loop sees.
/// </para>
/// </remarks>
internal static class NgxDriverProbe
{
private const string _probeFileName = "fl-probe-nvapi.exe";
private static readonly TimeSpan _budget = TimeSpan.FromSeconds(5);
public static string ProbePath => Path.Combine(AppContext.BaseDirectory, _probeFileName);
public static NgxDriverState Run(int pid) => Run(pid, ProbePath);
public static NgxDriverState Run(int pid, string probePath)
{
if (!File.Exists(probePath))
{
return NgxDriverState.Of(NgxProbeOutcome.ProbeMissing, probePath);
}
try
{
using var probe = new Process();
probe.StartInfo = new ProcessStartInfo(probePath)
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
};
probe.StartInfo.ArgumentList.Add("--ngx-state");
probe.StartInfo.ArgumentList.Add(pid.ToString(System.Globalization.CultureInfo.InvariantCulture));
probe.Start();
string output = probe.StandardOutput.ReadToEnd();
if (!probe.WaitForExit((int)_budget.TotalMilliseconds))
{
probe.Kill();
return NgxDriverState.Of(NgxProbeOutcome.ProbeFailed, "the probe did not exit within " + _budget.TotalSeconds + " s");
}
return NgxDriverState.Parse(output);
}
catch (Exception e) when (e is Win32Exception or InvalidOperationException or IOException)
{
return NgxDriverState.Of(NgxProbeOutcome.ProbeFailed, e.Message);
}
}
}
@@ -0,0 +1,87 @@
using System.ComponentModel;
using System.Diagnostics;
using FrameLedger.Infrastructure.Io;
namespace FrameLedger.CaptureHost.Capture;
/// <summary>
/// Launch mode's first step: start the consented executable and hold it from birth.
/// </summary>
/// <remarks>
/// <para>
/// <b>Not <c>CREATE_SUSPENDED</c>, and the spec's sentence is why.</b> <c>04_CAPTURE</c> §Launch mode
/// wrote <i>create suspended → guard → inject → resume</i>, and <c>20_OPEN_QUESTIONS</c> §S1 measured
/// that a suspended target has loaded nothing: <c>EnumProcessModulesEx</c> fails against it, so the guard
/// cannot run before the loader has. The built shape is <i>create → guard WAITS for a presentation
/// runtime → inject</i> (<c>FlGuardedInjectWhenReady</c>), and nothing in it needs the process held at
/// its first instruction. What the launch buys instead: the pid is ours before any code runs, the handle
/// is held from the start so it cannot recycle under us (§S29(e)), and the Vulkan layer's
/// <c>enable_environment</c> is set — which only the launching process can do (<c>17_HOOK_ENGINE</c>
/// §Vulkan). The layer still gates on its own enabled-list; the variable alone enables nothing.
/// </para>
/// <para>
/// <b>This host never terminates what it launched.</b> A refusal after the launch — no consent, an
/// anti-cheat hit, no runtime inside the budget — leaves the title running unhooked, exactly as the
/// product's Tier 2 does (duration and the reason, no measurement). The operator asked for the game to
/// start; the guard decides only whether FrameLedger goes into it.
/// </para>
/// </remarks>
internal static class ProcessLauncher
{
/// <summary>The Vulkan loader's enable variable for <c>VK_LAYER_FRAMELEDGER_overlay</c> (<c>17_HOOK_ENGINE</c> §Vulkan).</summary>
public const string VulkanLayerEnableVariable = "FRAMELEDGER_ENABLE_VK_LAYER";
/// <summary>Start <paramref name="exePath"/> with <paramref name="arguments"/>; null when it could not be started or pinned.</summary>
/// <param name="exePath">The consented executable.</param>
/// <param name="arguments">Its own command line, verbatim.</param>
/// <param name="environment">
/// Variables added to the child's environment — the Vulkan layer's, from
/// <c>VkLayerLaunchEnvironment</c>, when the layer is staged beside this host (P1 item 3).
/// </param>
public static (int Pid, ITargetLiveness Alive)? Start(string exePath, string arguments,
IReadOnlyDictionary<string, string>? environment = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(exePath);
var psi = new ProcessStartInfo(exePath, arguments ?? string.Empty)
{
UseShellExecute = false,
WorkingDirectory = Path.GetDirectoryName(exePath) ?? string.Empty,
};
psi.Environment[VulkanLayerEnableVariable] = "1";
foreach ((string name, string value) in environment ?? new Dictionary<string, string>(StringComparer.Ordinal))
{
psi.Environment[name] = value;
}
Process? process;
try
{
process = Process.Start(psi);
}
catch (Exception e) when (e is Win32Exception or InvalidOperationException or IOException)
{
return null;
}
if (process is null)
{
return null;
}
using (process)
{
// The same pin attach mode takes, taken here before anything else looks at the pid. The
// liveness OWNS the handle from here; the caller disposes it with the session (CA2000 is
// satisfied by that transfer, stated rather than suppressed).
HeldProcessHandle? held = HeldProcessHandle.TryOpen(process.Id);
if (held is null)
{
return null;
}
ITargetLiveness alive = new ProcessTargetLiveness(held, process.Id);
return (process.Id, alive);
}
}
}
@@ -0,0 +1,81 @@
using System.ComponentModel;
using System.Diagnostics;
using FrameLedger.CaptureHost.Consume;
namespace FrameLedger.CaptureHost.Capture;
/// <summary>
/// One out-of-process look at which census-named modules the target has loaded, and what
/// version each file on disk carries.
/// </summary>
/// <remarks>
/// <para>
/// <b>Consumer-side, deliberately.</b> The writer could read the same thing on its watchdog, but
/// that costs <c>version.dll</c> as an import of the injected DLL, an allocation per module, and
/// a packed word per module in <c>FlWriterState.reserved[]</c> — twenty bytes for up to twenty
/// names does not fit. Out here it is <see cref="Process.Modules"/>, which is the loader's
/// list through documented PSAPI, plus <see cref="FileVersionInfo"/> on the path it names.
/// </para>
/// <para>
/// <b>Never throws.</b> A target that is protected, elevated, or already gone yields an
/// unreadable snapshot with whatever was collected before the failure; the loop records that
/// rather than ending the session over a diagnostic.
/// </para>
/// </remarks>
internal static class RuntimeModuleSnapshot
{
public static RuntimeModuleSet Take(int pid, IReadOnlyCollection<string> fileNames)
{
ArgumentNullException.ThrowIfNull(fileNames);
var found = new List<RuntimeModuleInfo>();
try
{
using Process target = Process.GetProcessById(pid);
foreach (ProcessModule module in target.Modules)
{
using (module)
{
if (module.ModuleName is not { } name || module.FileName is not { } path)
{
continue;
}
if (!fileNames.Contains(name, StringComparer.OrdinalIgnoreCase))
{
continue;
}
found.Add(Describe(name, path));
}
}
return new RuntimeModuleSet(found, Snapshots: 1, Unreadable: 0);
}
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or ArgumentException
or NotSupportedException)
{
return new RuntimeModuleSet(found, Snapshots: 1, Unreadable: 1);
}
}
/// <summary>
/// The fixed-part version numbers, not the string: Streamline stamps its string as
/// <c>2,8,0,0</c>, and a module with no version resource at all — Cyberpunk's
/// <c>ffx_fsr3_x64.dll</c> — has neither, which is reported as null rather than as 0.0.0.0.
/// </summary>
private static RuntimeModuleInfo Describe(string name, string path)
{
try
{
FileVersionInfo info = FileVersionInfo.GetVersionInfo(path);
Version? parsed = info.FileVersion is null
? null
: new Version(info.FileMajorPart, info.FileMinorPart, info.FileBuildPart, info.FilePrivatePart);
return new RuntimeModuleInfo(name, path, info.FileVersion, parsed);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return new RuntimeModuleInfo(name, path, null, null);
}
}
}
@@ -56,6 +56,7 @@ internal static class SessionEndClassifier
{
FlStatus.Unhooked => weLatchedTheUnhook ? SessionEndReason.SafetyUnhook : SessionEndReason.SupervisionLost,
FlStatus.SelfDisabled => SessionEndReason.WriterSelfDisabled,
FlStatus.StoppedBlocklisted => SessionEndReason.WriterStoppedBlocklisted,
FlStatus.Init when attachSettled => SessionEndReason.WriterNeverInstalledHooks,
_ => SessionEndReason.Running,
};
@@ -32,6 +32,14 @@ internal enum SessionEndReason
/// <summary>Three hook faults; the Overlay went dormant on its own.</summary>
WriterSelfDisabled,
/// <summary>
/// The Overlay's <c>LoadLibrary</c> detour saw a module the compiled anti-cheat floor
/// names arrive mid-session and stopped the Overlay from inside, before this host's
/// 30 s scan could (<c>19_SAFETY</c> §During a session, the in-process half; §S6).
/// <c>FlWriterState.EarlyStopFamily</c> names which family.
/// </summary>
WriterStoppedBlocklisted,
/// <summary>
/// The handshake was published and <c>status</c> never left <c>INIT</c>, which
/// means MinHook failed: the ring will never move.
@@ -99,4 +107,19 @@ internal enum SessionEndReason
/// <summary>The ring could not be attached to, and the refusal was not retryable.</summary>
AttachRefused,
/// <summary>Launch mode: the executable could not be started, or the new process could not be pinned.</summary>
LaunchCannotStart,
/// <summary>
/// Launch mode: the guard was waiting for a presentation runtime and the target exited first
/// (<see cref="Domain.AntiCheat.AntiCheatRefusalReason.LaunchTargetExited"/>). Nothing was injected.
/// </summary>
LaunchTargetExited,
/// <summary>
/// Launch mode: the budget ran out with no presentation runtime mapped
/// (<see cref="Domain.AntiCheat.AntiCheatRefusalReason.LaunchNoPresentationRuntime"/>). Nothing was injected.
/// </summary>
LaunchNoPresentationRuntime,
}
@@ -94,8 +94,19 @@ internal sealed class TargetResolver : ITargetResolver
// A process we cannot read is NOT a match — "could not look" must not widen the set —
// but it is counted below so it cannot narrow one either.
string? image = p.MainModule?.FileName;
if (image is not null
&& string.Equals(ExecutableIdentity.Normalise(image), normalisedExePath,
if (image is null)
{
// A process that is in the snapshot with NO main module yet -- it exists and has
// not finished mapping its image. Measured on the hosted runner 2026-09-04, twice
// in one hour, on a single freshly started instance: the resolver skipped it here
// without counting it and answered TargetNotRunning about a process it had just
// enumerated. "Could not look" must not narrow the set, and that includes this
// shape; it is counted like a process we lack the rights to read.
unreadable++;
continue;
}
if (string.Equals(ExecutableIdentity.Normalise(image), normalisedExePath,
StringComparison.OrdinalIgnoreCase))
{
matches.Add(p.Id);
+19 -3
View File
@@ -22,7 +22,7 @@ namespace FrameLedger.CaptureHost;
internal sealed record CommandLine
{
/// <summary>Every option this host accepts. A test pins it.</summary>
public static readonly string[] AcceptedOptions = ["--exe", "--seconds"];
public static readonly string[] AcceptedOptions = ["--exe", "--seconds", "--args"];
public Verb Verb { get; init; }
@@ -48,6 +48,16 @@ internal sealed record CommandLine
/// </remarks>
public int Seconds { get; init; }
/// <summary>
/// The command line handed to the executable <c>launch</c> starts, verbatim. Empty by default.
/// </summary>
/// <remarks>
/// It names nothing about injection: the payload is still the Overlay beside this binary, the target
/// is still the consented executable, and the guard still collects its own evidence. What it changes
/// is what the GAME sees, which is the operator's business and not this host's.
/// </remarks>
public string Arguments { get; init; } = string.Empty;
public string? Error { get; init; }
public static CommandLine Parse(string[] args)
@@ -58,11 +68,12 @@ internal sealed record CommandLine
if (verb == Verb.None)
{
return new CommandLine { Error = "usage: consent list | consent grant --exe <path> | consent revoke --exe <path> | capture --exe <path> [--seconds <n>] | probe-lhm [--seconds <n>]" };
return new CommandLine { Error = "usage: consent list | consent grant --exe <path> | consent revoke --exe <path> | capture --exe <path> [--seconds <n>] | launch --exe <path> [--args \"<string>\"] [--seconds <n>] | probe-lhm [--seconds <n>]" };
}
string? exe = null;
int seconds = 0;
string arguments = string.Empty;
for (int i = 0; i < args.Length; i++)
{
if (args[i].StartsWith("--", StringComparison.Ordinal))
@@ -91,6 +102,10 @@ internal sealed record CommandLine
return new CommandLine { Error = "'--seconds' needs a positive whole number" };
}
}
else if (string.Equals(option, "--args", StringComparison.Ordinal))
{
arguments = value;
}
else
{
exe = value;
@@ -105,7 +120,7 @@ internal sealed record CommandLine
return new CommandLine { Error = "--exe <path> is required" };
}
return new CommandLine { Verb = verb, ExePath = exe, Seconds = seconds };
return new CommandLine { Verb = verb, ExePath = exe, Seconds = seconds, Arguments = arguments };
}
private static Verb VerbOf(string[] args) => args switch
@@ -114,6 +129,7 @@ internal sealed record CommandLine
["consent", "grant", ..] => Verb.ConsentGrant,
["consent", "revoke", ..] => Verb.ConsentRevoke,
["capture", ..] => Verb.Capture,
["launch", ..] => Verb.Launch,
["probe-lhm", ..] => Verb.ProbeLhm,
_ => Verb.None,
};
@@ -36,6 +36,13 @@ internal static class CensusNames
(FlRuntimeCensus.AmdFfxDx12, "amd_fidelityfx_dx12.dll"),
];
/// <summary>
/// Every module FILE name the census can answer for — the <c>a / b</c> pairs above split into
/// their members — so a module snapshot asks about exactly the set the census names.
/// </summary>
public static IReadOnlyList<string> ModuleFileNames { get; } =
_names.SelectMany(n => n.Name.Split(" / ", StringSplitOptions.RemoveEmptyEntries)).ToArray();
/// <summary>Comma-separated module names for the set family bits; <c>-</c> when none.</summary>
public static string Describe(FlRuntimeCensus bits)
{
@@ -0,0 +1,83 @@
using System.Globalization;
using System.Text.Json;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// The Overlay's <c>LoadLibrary</c> detour, as the report reads it: whether the detour is in, how often it woke
/// the watchdog for a module the inventory or census names, and — when the Overlay stopped itself — which
/// anti-cheat family the module that arrived matched (<c>fl_shm.h</c> §loaderSignals / earlyStopFamily,
/// <c>19_SAFETY</c> §During a session, the in-process half; §S6).
/// </summary>
internal static class EarlyStop
{
private const ushort _installedBit = 0x8000;
private const ushort _countMask = 0x7FFF;
/// <summary>The seed rules file staged beside this host (<c>FrameLedger.Rules.targets</c>).</summary>
public static string StagedRulesPath => Path.Combine(AppContext.BaseDirectory, "rules", "detection-rules.json");
/// <summary>
/// The family name behind a 1-based index into <c>anticheat.modules</c> of the rules file — the same order
/// <c>gen-ac-floor.ps1</c> emits the compiled floor's MODULE families in, which is what the Overlay indexes.
/// Null when the file cannot be read or the index is outside it; never a guess.
/// </summary>
public static string? FamilyName(int index, string rulesPath)
{
if (index <= 0)
{
return null;
}
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(rulesPath));
if (!doc.RootElement.TryGetProperty("anticheat", out JsonElement anticheat)
|| !anticheat.TryGetProperty("modules", out JsonElement modules)
|| modules.ValueKind != JsonValueKind.Array)
{
return null;
}
int i = 0;
foreach (JsonElement family in modules.EnumerateArray())
{
if (++i == index)
{
return family.TryGetProperty("family", out JsonElement name) ? name.GetString() : null;
}
}
return null;
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException)
{
return null;
}
}
/// <summary>The report's two lines: the detour's state always, the stop only when it happened.</summary>
public static IEnumerable<string> Describe(FlWriterState writer, string rulesPath)
{
bool installed = (writer.LoaderSignals & _installedBit) != 0;
int wakes = writer.LoaderSignals & _countMask;
yield return installed
? $" loader detour: installed (kernelbase!LoadLibraryExW); woke the watchdog {wakes.ToString(CultureInfo.InvariantCulture)} time(s) for a module the inventory or census names"
: " loader detour: NOT installed - late vendor modules wait for the 1 Hz tick, and the in-process anti-cheat stop is absent; the host's 30 s scan is the only stop";
if (writer.EarlyStopFamily == 0)
{
yield break;
}
string? name = FamilyName(writer.EarlyStopFamily, rulesPath);
yield return " EARLY STOP: the Overlay stopped ITSELF - a module matching anti-cheat family #"
+ writer.EarlyStopFamily.ToString(CultureInfo.InvariantCulture)
+ (name is null ? " (name not resolvable from the staged rules file)" : $" ({name})")
+ " loaded mid-session (19_SAFETY §During a session, the in-process half); status="
+ ((FlStatus)writer.Status).ToString()
+ ". This is the exact-name floor only; the fragment-and-signer tier is the host's scan";
}
}
@@ -0,0 +1,13 @@
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// One vendor marker looked for in the executable FILE on disk, and how many times it occurred.
/// </summary>
/// <param name="Name">The ASCII string searched for, case-sensitive — an API symbol prefix or a product name.</param>
/// <param name="Vendor">What the string belongs to, for the report.</param>
/// <param name="FgCapable">
/// True when the SDK the marker belongs to can generate frames — the only markers that move the
/// census's "cannot include generated frames" sentence to "MAY".
/// </param>
/// <param name="Hits">Occurrences in the file, capped; 0 means absent.</param>
internal sealed record ExecutableMarker(string Name, string Vendor, bool FgCapable, int Hits);
@@ -0,0 +1,65 @@
using System.Globalization;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// What the executable FILE carries of the vendor SDKs — read from disk, the way the fingerprint reads its size
/// and mtime, never from the process (CLAUDE.md rule 4 is about game memory; this is the file the user pointed at).
/// </summary>
/// <remarks>
/// <para>
/// <b>Why it exists (<c>HANDOFF</c> 7b, 2026-09-06).</b> A title with FSR 3 compiled into its executable loads
/// no vendor module, so the runtime census is empty and the Presented qualifier said *"this number cannot
/// include in-process generated frames"* — wrong in the dangerous direction, on a shape measured twice (Rune
/// Factory, Wukong). A marker in the file says the SDK's code or its symbol names are IN the executable. It does
/// not say the code ran: the qualifier moves from *cannot* to *MAY*, never to an identity.
/// </para>
/// <para>
/// <b>A marker is not identity, and a shipped-DLL title can carry the same strings</b> (a UE plugin's exe
/// references its plugin by name). So this is consulted only where the module census has nothing to say.
/// </para>
/// </remarks>
internal sealed record ExecutableMarkers(IReadOnlyList<ExecutableMarker> Markers, long BytesScanned, string? Error)
{
/// <summary>The loop was run without a scan.</summary>
public static readonly ExecutableMarkers NotScanned = new([], 0, null);
public bool Scanned => Error is null && BytesScanned > 0;
/// <summary>Markers found at least once.</summary>
public IEnumerable<ExecutableMarker> Present => Markers.Where(m => m.Hits > 0);
/// <summary>Markers found that belong to an SDK able to generate frames.</summary>
public IEnumerable<ExecutableMarker> FgCapablePresent => Present.Where(m => m.FgCapable);
public bool AnyFgCapable => FgCapablePresent.Any();
/// <summary>The names of the frame-generation-capable markers found, for a sentence.</summary>
public string FgCapableNames => string.Join(", ", FgCapablePresent.Select(m => m.Name));
/// <summary>The report's line: what was found, or why nothing was looked at.</summary>
public string Describe()
{
const string head = " executable markers (the exe FILE on disk, vendor SDK strings; presence is not identity): ";
if (Error is not null)
{
return head + "not scanned - " + Error;
}
if (BytesScanned == 0)
{
return head + "not scanned";
}
string size = (BytesScanned / (1024.0 * 1024.0)).ToString("0.0", CultureInfo.InvariantCulture);
List<ExecutableMarker> present = [.. Present];
if (present.Count == 0)
{
return head + $"none of {Markers.Count} marker(s) in {size} MB";
}
string list = string.Join(", ", present.Select(m =>
$"{m.Name} x{m.Hits.ToString(CultureInfo.InvariantCulture)} ({m.Vendor}{(m.FgCapable ? ", can generate frames" : "")})"));
return head + $"{list} in {size} MB";
}
}
@@ -110,7 +110,7 @@ internal sealed record FfxCensus
if (!SawAnything)
{
return " ffx dispatch census over " + N(Records) + " record(s): no UPSCALE or FRAMEGENERATION dispatch "
+ "reached an ffx-api leaf (no FSR identity, no FSR_FG mode)";
+ "reached an ffx-api leaf or the FSR 3.0 host facade (no FSR identity, no FSR_FG mode)";
}
var sb = new StringBuilder();
+105 -11
View File
@@ -61,6 +61,30 @@ internal sealed record FgWindow
/// <summary>Records whose count hit the byte's ceiling.</summary>
public required int Saturated { get; init; }
/// <summary>
/// Σ <c>dxgiUnseen</c> over the records that claim <see cref="FlMeasured.DxgiPresents"/>: presents DXGI
/// counted on the hooked chain that this hook never saw. 0 on every title measured except Dying Light:
/// The Beast on Streamline 2.8.0, where it is ≈ 3 × <see cref="Presents"/> at DLSS FG ×4 (§H5 row P1-DXGI).
/// </summary>
public required long DxgiUnseen { get; init; }
/// <summary>Records claiming <see cref="FlMeasured.DxgiPresents"/> — the byte's own denominator.</summary>
public required int DxgiClaiming { get; init; }
/// <summary>Records whose <c>dxgiUnseen</c> hit 255, the saturation sentinel; any means a refusal.</summary>
public required int DxgiSaturated { get; init; }
/// <summary>
/// The presents the window counts as DISPLAYED: the ones this hook timed plus the ones DXGI counted on the
/// same chain and this hook never saw. Equal to <see cref="Presents"/> on every title where DXGI and the hook
/// agree, and the numerator of <see cref="Factor"/>, <see cref="DisplayedFps"/> and
/// <see cref="PresentsPerBatch"/> — never of a frame-time distribution, which has no timestamps for them.
/// </summary>
public long DisplayedPresents => Presents + DxgiUnseen;
/// <summary>True when Displayed is a count DXGI made rather than this hook — the report must say so.</summary>
public bool DxgiCounted => DxgiUnseen > 0;
/// <summary>How many records carried 0, 1, 2 … evaluations. Index is the value.</summary>
public required IReadOnlyList<int> Histogram { get; init; }
@@ -86,11 +110,11 @@ internal sealed record FgWindow
/// <summary><c>presents / Σ evaluations</c>, or null.</summary>
public double? Factor =>
Refusal is null && Evaluations > 0 ? Presents / (double)Evaluations : null;
Refusal is null && Evaluations > 0 ? DisplayedPresents / (double)Evaluations : null;
/// <summary><c>F_disp</c> over this window's own intervals.</summary>
public double? DisplayedFps =>
Refusal is null && Seconds > 0 && Presents > 1 ? (Presents - 1) / Seconds : null;
Refusal is null && Seconds > 0 && DisplayedPresents > 1 ? (DisplayedPresents - 1) / Seconds : null;
/// <summary><c>F_app</c>, counted rather than derived.</summary>
public double? NativeFps => Refusal is null && Seconds > 0 ? Evaluations / Seconds : null;
@@ -129,7 +153,7 @@ internal sealed record FgWindow
/// <see cref="BatchRefusal"/>; it is never published as <c>fg_factor</c>, and
/// <see cref="Factor"/> stays keyed on counted evaluations.
/// </remarks>
public double? PresentsPerBatch => Batches > 0 ? Presents / (double)Batches : null;
public double? PresentsPerBatch => Batches > 0 ? DisplayedPresents / (double)Batches : null;
/// <summary>
/// Why <see cref="PresentsPerBatch"/> may not be read as one configuration's number, or
@@ -178,6 +202,9 @@ internal sealed record FgWindow
Unidentified = 0,
Streams = 0,
Saturated = 0,
DxgiUnseen = 0,
DxgiClaiming = 0,
DxgiSaturated = 0,
Histogram = [],
BucketFactors = [],
BatchFactors = [],
@@ -205,6 +232,7 @@ internal sealed record FgWindow
int batches = 0;
int unidentified = 0;
int saturated = 0;
(long dxgiUnseen, int dxgiClaiming, int dxgiSaturated) = TallyDxgi(all, start);
for (int i = start; i < all.Count; i++)
{
@@ -242,6 +270,9 @@ internal sealed record FgWindow
Unidentified = unidentified,
Streams = streams.Count,
Saturated = saturated,
DxgiUnseen = dxgiUnseen,
DxgiClaiming = dxgiClaiming,
DxgiSaturated = dxgiSaturated,
Histogram = histogram,
BucketFactors = BucketsOf(all, start, EvaluationWeight),
BatchFactors = BucketsOf(all, start, BatchWeight),
@@ -249,6 +280,34 @@ internal sealed record FgWindow
};
}
/// <summary>
/// Σ <c>dxgiUnseen</c>, the records claiming it, and the ones at the 255 sentinel — the DXGI half of
/// the tally, in its own pass because it is its own measurement (<c>fl_shm.h</c> §dxgiUnseen).
/// </summary>
private static (long Unseen, int Claiming, int Saturated) TallyDxgi(IReadOnlyList<FlFrameRecord> all, int start)
{
long unseen = 0;
int claiming = 0;
int saturated = 0;
for (int i = start; i < all.Count; i++)
{
FlFrameRecord r = all[i];
if (!((FlMeasured)r.MeasuredMask).HasFlag(FlMeasured.DxgiPresents))
{
continue;
}
claiming++;
unseen += r.DxgiUnseen;
if (r.DxgiUnseen == byte.MaxValue)
{
saturated++;
}
}
return (unseen, claiming, saturated);
}
/// <summary>
/// Per-bucket <c>presents ÷ weight</c> in time order, or empty when the window is too
/// short. One slicing, two weights.
@@ -276,23 +335,53 @@ internal sealed record FgWindow
int lo = start + (int)((long)n * b / _buckets);
int hi = start + (int)((long)n * (b + 1) / _buckets);
long sigma = 0;
long displayed = 0;
for (int i = lo; i < hi; i++)
{
sigma += weight(all[i]);
displayed += 1 + Unseen(all[i]);
}
factors.Add(sigma > 0 ? (hi - lo) / (double)sigma : double.PositiveInfinity);
// The SAME numerator the window publishes: a DXGI-counted present belongs to the
// bucket of the hooked present that read it, so a session where the 2.8 pacer
// stopped mid-way fails uniformity exactly as one where tokens stopped would.
factors.Add(sigma > 0 ? displayed / (double)sigma : double.PositiveInfinity);
}
return factors;
}
/// <summary><c>dxgiUnseen</c> where the record claims it, else 0 — an unclaimed byte is nobody's count.</summary>
private static long Unseen(FlFrameRecord r) =>
((FlMeasured)r.MeasuredMask).HasFlag(FlMeasured.DxgiPresents) ? r.DxgiUnseen : 0L;
/// <summary>The first reason a factor may not be published, or null.</summary>
/// <remarks>
/// Ordered so the most specific cause is named. Every one of these is a number this
/// consumer would otherwise have printed as a measurement.
/// </remarks>
private static string? RefusalFor(FgWindow w)
{
if (RefusalForRecordSet(w) is string aboutTheRecords)
{
return aboutTheRecords;
}
if (w.Evaluations == 0)
{
return "no application-frame token was counted in the window (slGetNewFrameToken, or an ffx-api "
+ "PREPARE / UPSCALE dispatch) — a data gap, "
+ "and treating it as 'no frame generation' is how fg_factor becomes 1.0";
}
return RefusalForRatio(w);
}
/// <summary>
/// Facts about the record SET that refuse a factor before anything is divided: attribution, and the
/// two saturation sentinels.
/// </summary>
private static string? RefusalForRecordSet(FgWindow w)
{
// ATTRIBUTION FIRST, AND THE ORDER IS THE FIX. These two are facts about the record
// set and hold whether or not anything was counted — but they used to sit BELOW the
@@ -319,14 +408,19 @@ internal sealed record FgWindow
+ "saturation sentinel rather than a count — dividing by it would report a floor";
}
if (w.Evaluations == 0)
if (w.DxgiSaturated > 0)
{
return "no application-frame token was counted in the window (slGetNewFrameToken, or an ffx-api "
+ "PREPARE / UPSCALE dispatch) — a data gap, "
+ "and treating it as 'no frame generation' is how fg_factor becomes 1.0";
return $"{w.DxgiSaturated} record(s) hit the dxgiUnseen ceiling of 255, which is a saturation "
+ "sentinel rather than a count — DXGI counted more presents than the byte can carry";
}
string? nonUniform = NonUniform(w.BucketFactors, w.Presents / (double)w.Evaluations, w.Presents,
return null;
}
/// <summary>The refusals that need the ratio itself: uniformity, then the unnameable band.</summary>
private static string? RefusalForRatio(FgWindow w)
{
string? nonUniform = NonUniform(w.BucketFactors, w.DisplayedPresents / (double)w.Evaluations, w.Presents,
"the frame-generation state");
if (nonUniform is not null)
{
@@ -346,7 +440,7 @@ internal sealed record FgWindow
// What is still refused is the band between: a steady 1.05–1.5 is not a configuration
// any vendor ships, and a window that mixed states would usually have failed the
// uniformity check above. Naming it would be guessing.
double factor = w.Presents / (double)w.Evaluations;
double factor = w.DisplayedPresents / (double)w.Evaluations;
return factor > NoneCeiling && factor < ActiveThreshold
? $"presents/tokens = {factor.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)} sits "
+ $"between the `none` ceiling ({NoneCeiling.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)}) "
@@ -405,7 +499,7 @@ internal sealed record FgWindow
+ "so a batch belonging to one stream can be drained by another's present";
}
return NonUniform(w.BatchFactors, w.Presents / (double)w.Batches, w.Presents,
return NonUniform(w.BatchFactors, w.DisplayedPresents / (double)w.Batches, w.Presents,
"the presents-per-batch ratio");
}
@@ -0,0 +1,29 @@
using System.Globalization;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// Launch mode's cost, as the report reads it: how long the guard waited before it injected, and how many
/// presents DXGI had already counted on the first hooked chain when the hook saw its first one — the number
/// <c>20_OPEN_QUESTIONS</c> §S1 said nobody had.
/// </summary>
internal static class LaunchNote
{
/// <summary>One line when the session was launched, and one line always.</summary>
public static IEnumerable<string> Describe(TimeSpan? launchWait, FlWriterState writer)
{
if (launchWait is TimeSpan wait)
{
yield return " launch: the guard injected "
+ ((long)wait.TotalMilliseconds).ToString(CultureInfo.InvariantCulture)
+ " ms after the process was started (it waited for a presentation runtime to map, then ran every check)";
}
yield return writer.DxgiPresentsBeforeHook == FlWriterState.DxgiPresentsBeforeHookNotRead
? " presents before the first hooked present: not read (the hook saw no present)"
: " presents before the first hooked present: "
+ writer.DxgiPresentsBeforeHook.ToString(CultureInfo.InvariantCulture)
+ " (DXGI's count on the first hooked chain; 0 means nothing ran unhooked on it -- §S1's number)";
}
}
@@ -89,6 +89,93 @@ internal sealed record MeasuredFacts
/// <summary>The string <see cref="FgMode"/> carries for rung 3: active, vendor not identified.</summary>
public const string FgActiveUnidentified = "Active (technology not identified)";
/// <summary>The prefix <see cref="FgMode"/> carries when a counted 1.0 is NOT allowed to become <c>none</c>.</summary>
public const string FgNoneWithheldPrefix = "N/A (`none` withheld — ";
/// <summary>
/// The Streamline interposer version from which a counted 1.0 beside a loaded DLSS-G plugin is
/// withheld from <c>none</c>: Dying Light: The Beast ships 2.8.0 and measured that shape five times.
/// </summary>
public static readonly Version StreamlineNoneWithheldFrom = new(2, 8, 0);
/// <summary>
/// Why a counted <c>none</c> was not published, or null when it was. <c>20_OPEN_QUESTIONS</c> §H5 case 3.
/// </summary>
/// <remarks>
/// <para>
/// <b>The shape, measured five times on Dying Light: The Beast (Streamline 2.8.0, 2026-09-04/05):</b>
/// DLSS Frame Generation ON in the title's menu, <c>presents = tokens</c> on every capture, and the
/// report printed <c>frame generation: none</c>. The owner's reading on 2026-09-05: the title runs at
/// DLSS ×4, the Steam overlay shows DLSS, and the frames this hook records are the native ones. So
/// on that shape the count is right about the application frames and wrong about the presents —
/// the generated ones never reach the <c>Present</c> bodies the Overlay patches — and a <c>none</c>
/// computed from it is the affirmative negative CLAUDE.md rule 6 forbids.
/// </para>
/// <para>
/// <b>Keyed on <c>sl.dlss_g.dll</c>, the Streamline plugin that would be doing the presenting — NOT on
/// <c>nvngx_dlssg.dll</c>.</b> Every validated <c>none</c> on this machine has the plugin bit CLEAR:
/// Cyberpunk 2077 off / ×3 / ×4 on Streamline 2.7.1 (census <c>0x5793D</c>, <c>nvngx_dlssg.dll</c>
/// loaded, ×3.99 visible to this hook), Expedition 33 and Lies of P with frame generation off
/// (<c>0x27945</c>-shaped words). Every Dying Light: The Beast run has it SET (<c>0x25F0F</c> /
/// <c>0x25F4F</c>). A key on <c>nvngx_dlssg.dll</c> would have turned three validated results into
/// warnings; this key leaves every one of them byte-identical.
/// </para>
/// <para>
/// <b>And on the interposer's version, read from the file, ≥ 2.8.0.</b> A 2.7 title that loads the
/// plugin keeps <c>none</c> — it is what Cyberpunk would be if it loaded it. A plugin loaded beside
/// an interposer whose version could not be read is withheld with its own reason: an N/A over a
/// <c>none</c> this consumer cannot discriminate.
/// </para>
/// <para>
/// <b>Narrowed 2026-09-06, on Leg 0.</b> The plugin IS a startup-time load on Dying Light: The Beast
/// (frame generation off, census unchanged, twice), so the cost paragraph's fear was measured true —
/// and the same morning's ×4 capture measured the discriminator the gate lacked: the 2.8.0 pacer's
/// generated presents are DXGI presents on the hooked chain (§H5 row P1-DXGI, 2.90–2.97 per hooked
/// present, <c>70.52 → 282.08 (×4)</c> counted through <c>dxgiUnseen</c>). So a counted 1.0 beside a
/// READ counter is what it says: DXGI itself counted no present this hook did not. <c>none</c> is
/// withheld on this shape only when the counter was not read at all.
/// </para>
/// </remarks>
public string? NoneWithheld { get; init; }
/// <summary>
/// What DXGI's own present counter said beside a counted <c>none</c>, or null when it was not read. On the
/// Streamline 2.8.0 shape this is the discriminator the gate lacked (Leg 0, 2026-09-06); on every other
/// title it is a second witness printed beside the count.
/// </summary>
public string? NoneBesideDxgi { get; init; }
/// <summary>The Streamline interposer's file version, when a module snapshot saw it.</summary>
public Version? InterposerVersion { get; init; }
/// <summary>
/// <see cref="FlWriterState.SlTagCensus"/>: which Streamline buffer types the title tagged, on which route.
/// </summary>
public uint SlTagCensus { get; init; }
/// <summary>
/// <see cref="FlWriterState.DxgiPresentsUnseen"/>: presents DXGI's own counter recorded on the hooked chain(s)
/// between two consecutive hooked presents, beyond the one the hook saw.
/// </summary>
public uint DxgiPresentsUnseen { get; init; }
/// <summary><see cref="FlWriterState.DxgiPresentSamples"/>: hooked presents on which DXGI's counter was read.</summary>
public uint DxgiPresentSamples { get; init; }
/// <summary>
/// Unseen presents per hooked present, or null before the counter was read. <c>0</c> means DXGI counted nothing this
/// hook did not; <c>≈ N−1</c> beside a withheld count is a frame-generation pacer presenting on the hooked chain
/// through a body the inline patches do not cover — i.e. the generated presents ARE DXGI presents.
/// </summary>
public double? DxgiUnseenPerHookedPresent => DxgiPresentSamples > 0 ? DxgiPresentsUnseen / (double)DxgiPresentSamples : null;
/// <summary>
/// The title tagged a HUD-less or UI buffer through Streamline on some route — the inputs only DLSS Frame
/// Generation consumes (DLSS-G programming guide §5.0). Identity, never a count: the title is FEEDING frame
/// generation, and whether frames were generated is still the count's verdict.
/// </summary>
public bool DlssgInputsTagged => (FlSlTagRoute.Any(SlTagCensus) & FlSlTagType.DlssgInputs) != FlSlTagType.None;
/// <summary>Null when <see cref="FlMeasured.Upscaler"/> is clear or the value is UNKNOWN.</summary>
public string? Upscaler { get; init; }
@@ -103,6 +190,177 @@ internal sealed record MeasuredFacts
/// </remarks>
public bool UpscalerHookRan { get; init; }
/// <summary>The driver's per-process NGX word, merged over the session; <see cref="NgxDriverState.NotRun"/> without a probe.</summary>
public NgxDriverState NgxDriver { get; init; } = NgxDriverState.NotRun;
/// <summary>The string the <c>upscaler:</c> line carries when the identity is the driver's word and not a hook's.</summary>
public const string UpscalerDlssDriverReported =
"Dlss (driver-reported: the NVIDIA driver reports an NGX super-resolution feature created and evaluated in "
+ "this process - not counted by this hook; 03_METRICS §Upscaling, the driver-reported rung)";
/// <summary>
/// <c>03_METRICS</c> §Upscaling, the driver-reported rung (owner decision 2026-09-06): when NO hook named an
/// upscaler and the driver says an NGX super-resolution feature was created and evaluated in this process,
/// the identity is DLSS, attributed to the driver. Null whenever a hook answered, or the driver did not.
/// </summary>
/// <remarks>
/// Identity and nothing else. Measured 2026-09-06 on Hell Is Us, Expedition 33 and Lies of P: the bits are
/// set without an NVIDIA-app override; <c>scalingRatio</c> is 0 even with one; <c>performanceMode</c> and
/// <c>renderPreset</c> are the override's values; the FG word is blind to Streamline DLSS-G. So this may name
/// the vendor and the feature and may not state a quality, a ratio, a render size or a frame-generation mode.
/// The negative is owed: a title with DLSS switched off should read the bit clear, and until it is measured
/// this rung has only ever seen the positive — §H5 pre-commits its withdrawal if the bit stays set.
/// </remarks>
public string? UpscalerDriverReported => Upscaler is null && NgxDriver.SrCreatedAndEvaluated ? UpscalerDlssDriverReported : null;
/// <summary>What the executable FILE carries of the vendor SDKs; <see cref="ExecutableMarkers.NotScanned"/> without a scan.</summary>
public ExecutableMarkers Markers { get; init; } = ExecutableMarkers.NotScanned;
/// <summary>The string <see cref="FgMode"/> carries when the count is active, no tag named the technology, and the driver did.</summary>
public const string FgDlssGDriverReported =
"DlssG (driver-reported: the NVIDIA driver reports an NGX frame-generation feature created and evaluated in this "
+ "process - the identity only; the count above is the record)";
/// <summary>
/// The FG line as printed: the resolved mode, promoted to <see cref="FgDlssGDriverReported"/> only on the one shape
/// where the count is active and no tag named the technology (<c>03_METRICS</c>: identity decides the name, the
/// count decides <c>none</c> — the driver's word is a second identity source, never a count).
/// </summary>
public string? FgModePrinted
{
get
{
if (!string.Equals(FgMode, FgActiveUnidentified, StringComparison.Ordinal))
{
return FgMode;
}
return NgxDriver.FgCreatedAndEvaluated ? FgDlssGDriverReported : FgActiveUnidentified + " — " + FgByElimination();
}
}
/// <summary>
/// The rung-3 line with every exclusion this session can make written beside it — never a vendor named as
/// measured. <c>HANDOFF</c> 7b / §H11, 2026-09-06: a frame generator this build cannot see (XeFG by licence, a
/// compiled-in FSR 3 by construction) still leaves witnesses — the driver's FG word, the tags, the ffx census,
/// the module census and the executable's own strings — and the reader gets all of them, labelled.
/// </summary>
private string FgByElimination() => "by elimination among what this session saw: " + FgWitnesses();
/// <summary>
/// The FG line when a hook ran and no evaluation was counted — the N/A, with the same witnesses beside it
/// (Hell Is Us at XeSS + XeSS-FG, 2026-09-06: no Streamline token on that plugin version, so no count, while
/// the driver, the tags, the ffx census, the module census and the file all still had something to say).
/// </summary>
public string FgNotEvaluatedPrinted =>
"N/A (a hook ran and saw no frame-generation evaluation — see the FG counts above); what this session can "
+ "still say: " + FgWitnesses();
/// <summary>
/// The clauses every FG line without a measured vendor carries: the driver's FG word and the tags against
/// DLSS-G, the ffx census against a shipped-DLL FSR-FG, the module census, and the executable's strings.
/// </summary>
private string FgWitnesses()
{
string tags = DlssgInputsTagged
? "HUD-less / UI tags WERE sent through Streamline"
: "no HUD-less / UI tag was sent through Streamline";
string dlssg = NgxDriver.Outcome == NgxProbeOutcome.Answered
? "not DLSS-G (the NVIDIA driver reports no NGX frame-generation feature created, and " + tags + ")"
: "DLSS-G not excluded (the NVIDIA driver did not answer; " + tags + ")";
string runtimes = FgRuntimesLoaded == FlRuntimeCensus.None
? "no frame-generation runtime module is loaded at all"
: "the frame-generation runtime(s) loaded: " + CensusNames.Describe(FgRuntimesLoaded);
string exe = Markers.AnyFgCapable
? "; the executable itself carries " + Markers.FgCapableNames
: "";
return dlssg + "; no FSR frame-generation dispatch reached a hooked module; " + runtimes + exe
+ " — a frame generator compiled into the executable would read the same, and nothing here is a "
+ "measured vendor identity";
}
/// <summary>
/// <c>HANDOFF</c> 7c item 4, the string change it asked for: an XeSS session reads <c>N/A</c> here by policy.
/// Null unless no hook and no driver named the upscaler and <c>libxess.dll</c> is in the census.
/// </summary>
public string? XessByLicenceNote =>
Upscaler is null && UpscalerDriverReported is null && RuntimeCensus.HasFlag(FlRuntimeCensus.LibXess)
? "libxess.dll is loaded, and XeSS cannot be hooked or declared under Intel's licence (18_GPU_VENDOR_APIS "
+ "§Intel), so an XeSS session reads N/A here by policy, not by ignorance — and the module's presence "
+ "is not identity: Cyberpunk loads it at DLSS"
: null;
/// <summary>
/// What the driver's FG word adds beside the FG line — agreement with a tagged DLSS-G, a disagreement printed
/// rather than resolved, or the bare fact beside a count that read <c>none</c> — or null when it says nothing.
/// </summary>
/// <remarks>
/// Corrected 2026-09-06 midday: the morning's reading called this word blind to Streamline DLSS-G; the captures
/// beside the loop read <c>CREATED | EVALUATE</c> on every ×4 session (Hell Is Us, Onimusha, DL:TB), the word
/// changing between readings as the feature came up. Identity only — the multiplier bits stay clear at ×4.
/// </remarks>
public string? FgDriverNote
{
get
{
if (NgxDriver.Outcome != NgxProbeOutcome.Answered)
{
return null;
}
bool created = NgxDriver.FgCreatedAndEvaluated;
bool dlssg = FgMode is not null && FgMode.StartsWith(nameof(FlFgMode.DlssG), StringComparison.Ordinal);
if (dlssg)
{
return created
? "the NVIDIA driver agrees: an NGX frame-generation feature was created and evaluated in this process"
: "WARNING: the NVIDIA driver reports NO NGX frame-generation feature created in this process while the "
+ "tags named DLSS-G - a disagreement, printed rather than resolved";
}
return created
? "the NVIDIA driver reports an NGX frame-generation feature created and evaluated in this process "
+ "(driver-reported identity; the count above is the record and is not changed by it)"
: null;
}
}
/// <summary>
/// What the driver's word adds beside a hook's identity — agreement, a disagreement printed rather than
/// resolved, or the driver's negative beside an N/A — or null when the driver did not answer.
/// </summary>
public string? UpscalerDriverNote
{
get
{
if (NgxDriver.Outcome != NgxProbeOutcome.Answered)
{
return null;
}
bool created = NgxDriver.SrCreatedAndEvaluated;
if (Upscaler is null)
{
return created
? null
: "the NVIDIA driver reports no NGX super-resolution feature created in this process (driver-reported; "
+ "it says nothing about FSR or XeSS)";
}
if (string.Equals(Upscaler, nameof(FlUpscaler.Dlss), StringComparison.Ordinal))
{
return created
? "the NVIDIA driver agrees: an NGX super-resolution feature was created and evaluated in this process"
: "WARNING: the NVIDIA driver reports NO NGX super-resolution feature created in this process while the "
+ "hook named DLSS - a disagreement, printed rather than resolved";
}
return created
? "the NVIDIA driver also reports an NGX super-resolution feature created and evaluated in this process"
: null;
}
}
/// <summary>Whether a hook capable of naming the frame-generation mode was live.</summary>
public bool FgHookRan { get; init; }
@@ -132,8 +390,24 @@ internal sealed record MeasuredFacts
public bool CensusInconsistent =>
!CensusRan && (RuntimeCensus & ~FlRuntimeCensus.Ran) != FlRuntimeCensus.None;
/// <summary>Null, because <c>renderW/H</c> are always 0 and the ratio would divide by zero.</summary>
public double? UpscaleRatio { get; init; }
/// <summary>
/// The dominant render → output extent over the records that claim <see cref="FlMeasured.UpscalerParams"/>
/// and carry an output size, or null when no record carried both.
/// </summary>
/// <remarks>
/// <b>The ratio is <c>03_METRICS</c> §Upscaling's own formula — <c>sqrt((outW×outH)/(renW×renH))</c>
/// — and nothing more.</b> A preset NAME derived from it ("58% ≈ Balanced") is HANDOFF item 7a's
/// owner decision and is deliberately not printed here: the quality byte stays what the writer
/// measured (<c>0xFF</c> on every title so far), and this line says what the title rendered at,
/// which is a measurement, beside the ratio, which is arithmetic on two measurements. The modal
/// tuple rather than a mean, because averaging across a settings change is the classic way a
/// benchmark number stops meaning anything; <see cref="UpscaleExtent.DistinctGroups"/> says
/// whether one happened.
/// </remarks>
public UpscaleExtent? Extent { get; init; }
/// <summary><c>sqrt((outW×outH)/(renW×renH))</c> of the dominant extent, or null.</summary>
public double? UpscaleRatio => Extent?.Ratio;
public Tri RayTracing { get; init; }
@@ -169,7 +443,8 @@ internal sealed record MeasuredFacts
/// overstates the factor. <see cref="FgWindow"/> owns that decision and its refusals.
/// </remarks>
public static MeasuredFacts From(IReadOnlyList<FlFrameRecord> stream, FlWriterState writer,
long qpcFrequency, long totalGaps, long totalDropped, FgWindow? fg = null)
long qpcFrequency, long totalGaps, long totalDropped, FgWindow? fg = null, RuntimeModuleSet? modules = null,
NgxDriverState? ngx = null, ExecutableMarkers? markers = null)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(qpcFrequency);
@@ -186,23 +461,32 @@ internal sealed record MeasuredFacts
var entitled = EntitledBy((FlHookFamily)writer.HooksInstalledMask);
int violations = stream.Count(r => !IsHonest(r, entitled));
var census = (FlRuntimeCensus)writer.RuntimeCensus;
string? withheld = fg?.IsNone == true ? WithholdNone(census, modules, writer) : null;
return new MeasuredFacts
{
PresentsObserved = stream.Count,
SecondsObserved = seconds,
Fg = fg,
FgMode = FgModeOf(stream) ?? (fg?.IsNone == true ? FgNone : fg?.IsActive == true ? FgActiveUnidentified : null),
FgMode = ResolveFgMode(FgModeOf(stream), fg, withheld),
NoneWithheld = withheld,
NoneBesideDxgi = fg?.IsNone == true && withheld is null ? DxgiBesideNone(writer) : null,
InterposerVersion = modules?.VersionOf(_slInterposerFileName),
SlTagCensus = writer.SlTagCensus,
DxgiPresentsUnseen = writer.DxgiPresentsUnseen,
DxgiPresentSamples = writer.DxgiPresentSamples,
UpscalerHookRan = RecordWindow.ClaimedSuffixStart(
stream, static r => ((FlMeasured)r.MeasuredMask).HasFlag(FlMeasured.Upscaler)) < stream.Count,
FgHookRan = RecordWindow.ClaimedSuffixStart(
stream, static r => ((FlMeasured)r.MeasuredMask).HasFlag(FlMeasured.Fg)) < stream.Count,
RuntimeCensus = (FlRuntimeCensus)writer.RuntimeCensus,
RuntimeCensus = census,
// Still a deliberate absence: renderW/H are 0 unless a params hook ran, and the
// ratio would divide by zero. See the property doc.
UpscaleRatio = null,
Extent = UpscaleExtent.From(stream),
Upscaler = UpscalerOf(stream),
NgxDriver = ngx ?? NgxDriverState.NotRun,
Markers = markers ?? ExecutableMarkers.NotScanned,
RayTracing = RayTracingOf(stream, writer),
RayReconstruction = RayReconstructionOf(stream),
Hdr = HdrOf(stream),
@@ -248,7 +532,7 @@ internal sealed record MeasuredFacts
var allowed = FlMeasured.None;
if (hooks.HasFlag(FlHookFamily.Present))
{
allowed |= FlMeasured.OutputRes | FlMeasured.PresentArgs;
allowed |= FlMeasured.OutputRes | FlMeasured.PresentArgs | FlMeasured.DxgiPresents;
}
if (hooks.HasFlag(FlHookFamily.UpscalerIdentity))
@@ -319,6 +603,13 @@ internal sealed record MeasuredFacts
return false;
}
// dxgiUnseen has no in-band sentinel either — 0 is DXGI agreeing with the hook — so a
// value under a clear bit is the same defect as an unclaimed count.
if (!mask.HasFlag(FlMeasured.DxgiPresents) && r.DxgiUnseen != 0)
{
return false;
}
// fgEvaluations has no in-band sentinel — 0 is a real count — so only the mask bit
// can say whether anyone counted. Added here to keep this in step with the native
// twin in guard_test.cpp, which HANDOFF item 3 will make load-bearing.
@@ -343,6 +634,99 @@ internal sealed record MeasuredFacts
return mask.HasFlag(FlMeasured.Rt) || ((FlRtFlags)r.RtFlags == FlRtFlags.None && r.DispatchRaysVolume == 0);
}
private const string _slInterposerFileName = "sl.interposer.dll";
/// <summary>The string <see cref="FgMode"/> carries when the count said <c>none</c> while DLSS-G inputs were tagged.</summary>
public const string FgNoneInputsTagged =
"None (DLSS-G inputs were tagged through Streamline; the count says every present carried an application frame)";
/// <summary>
/// Identity and count, combined by one rule: <b>the count decides <c>none</c>, identity decides the name.</b>
/// </summary>
/// <remarks>
/// <para>
/// Until 2026-09-05 identity won outright, which was right for the identities the writer could produce:
/// <c>FsrFg</c> lands only on a present that drained a FRAMEGENERATION dispatch (a generated batch, a fact
/// about generation), and <c>DlssG</c> from a <c>kFeatureDLSS_G</c> evaluation never landed at all. Now
/// <c>DlssG</c> also lands on a present that drained a HUD-less or UI tag — the title FEEDING frame
/// generation, which a title may do with the feature switched off in its menu. So a counted 1.0 beside a
/// <c>DlssG</c> mark is <c>none</c> with the inputs noted, never <c>DlssG</c>; an active count beside it is
/// <c>DlssG</c>, named for the first time on the titles that never evaluate the feature; and a withheld
/// count (§H5) keeps its N/A, with the tags reported beside it in the census line.
/// </para>
/// <para><c>FsrFg</c> keeps precedence over the count: a generated batch drained is a generated batch.</para>
/// </remarks>
private static string? ResolveFgMode(string? identity, FgWindow? fg, string? withheld)
{
bool dlssg = string.Equals(identity, nameof(FlFgMode.DlssG), StringComparison.Ordinal);
if (fg?.IsNone == true && withheld is null && (identity is null || dlssg))
{
return dlssg ? FgNoneInputsTagged : FgNone;
}
if (fg?.IsNone == true && withheld is not null && (identity is null || dlssg))
{
return FgNoneWithheldPrefix + withheld + ")";
}
return identity ?? (fg?.IsActive == true ? FgActiveUnidentified : null);
}
/// <summary>
/// The one shape on which a counted 1.0 may not be published as <c>none</c> — see
/// <see cref="NoneWithheld"/> for the measurement and the choice of key.
/// </summary>
private static string? WithholdNone(FlRuntimeCensus census, RuntimeModuleSet? modules, FlWriterState writer)
{
if (!census.HasFlag(FlRuntimeCensus.Ran) || !census.HasFlag(FlRuntimeCensus.SlDlssG))
{
return null;
}
// THE DISCRIMINATOR, since Leg 0 (2026-09-06): DXGI's own counter on the hooked chain. The
// 2.8.0 pacer's generated presents ARE DXGI presents there (§H5 row P1-DXGI), so a counter that
// was read and saw nothing unseen is DXGI saying what the count says. A counter that was read
// and DID see presents while the count still sits at 1.0 is a contradiction between two words
// of the same writer — the records should have carried them — and is refused as such.
if (writer.DxgiPresentSamples > 0)
{
return writer.DxgiPresentsUnseen == 0
? null
: $"DXGI's present counter read {writer.DxgiPresentsUnseen} present(s) this hook never saw over "
+ $"{writer.DxgiPresentSamples} hooked present(s) while the records carry none of them — the writer "
+ "state and the records disagree, and neither may be read as `none`";
}
const string notRead = "DXGI's present counter was not read this session, and on Streamline 2.8.0 the DLSS-G "
+ "pacer's generated presents are DXGI presents this hook never sees (20_OPEN_QUESTIONS "
+ "§H5 row P1-DXGI), so a 1.0 cannot be told from generation";
Version? v = modules?.VersionOf(_slInterposerFileName);
if (v is null)
{
return "sl.dlss_g.dll (Streamline's DLSS Frame Generation plugin) is loaded, sl.interposer.dll's file "
+ "version could not be read, and " + notRead;
}
return v >= StreamlineNoneWithheldFrom
? $"sl.dlss_g.dll (Streamline's DLSS Frame Generation plugin) is loaded on sl.interposer.dll {v}; " + notRead
: null;
}
/// <summary>DXGI's counter as a second witness beside a counted <c>none</c>; null when it was not read.</summary>
private static string? DxgiBesideNone(FlWriterState writer)
{
if (writer.DxgiPresentSamples == 0)
{
return null;
}
string samples = writer.DxgiPresentSamples.ToString(System.Globalization.CultureInfo.InvariantCulture);
return writer.DxgiPresentsUnseen == 0
? $"DXGI's own present counter agrees: 0 unseen over {samples} hooked present(s)"
: $"DXGI's own present counter read {writer.DxgiPresentsUnseen.ToString(System.Globalization.CultureInfo.InvariantCulture)} "
+ $"unseen over {samples} hooked present(s), inside the `none` ceiling";
}
/// <summary>Which frame-generation technology ran, or null. NEVER the string "none".</summary>
/// <remarks>
/// <c>03_METRICS</c>'s ladder ends "otherwise <c>fg_mode = none</c>", and rung 0 — added
@@ -0,0 +1,165 @@
using System.Globalization;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// The NVIDIA driver's own per-process NGX bookkeeping — <c>NvAPI_NGX_GetNGXOverrideState</c>, read out of
/// process by <c>fl-probe-nvapi --ngx-state</c> beside each module snapshot — merged over a session.
/// </summary>
/// <remarks>
/// <para>
/// <b>A driver-reported fact, and the report says so wherever it uses one.</b> It is neither a hooked argument
/// (CLAUDE.md rule 4) nor a static hint (<c>05_DETECTION</c>): the driver says a feature was created and
/// evaluated in this process, and this host repeats that with the attribution. What it may stand in for is
/// the super-resolution IDENTITY on a session where no hook saw an evaluation (<c>03_METRICS</c> §Upscaling,
/// the driver-reported rung, owner decision 2026-09-06). What it may not stand in for: a quality, a ratio, a
/// render size, a frame-generation mode or a multiplier — measured 2026-09-06 to be override fields or blind.
/// </para>
/// <para>
/// The last ANSWERED reading is the state; <see cref="Readings"/> counts probe runs, <see cref="Answered"/> the
/// ones the driver answered, and <see cref="Changed"/> whether two answered readings disagreed on a mask — a
/// title switching DLSS on mid-session would show as a change, and the report prints it rather than averaging.
/// </para>
/// </remarks>
internal sealed record NgxDriverState(
NgxProbeOutcome Outcome,
ulong Sr,
ulong Rr,
ulong Fg,
double ScalingRatio,
uint PerformanceMode,
uint RenderPreset,
uint FgCount,
uint FgPreset,
uint FgMode,
uint Driver,
int Readings,
int Answered,
bool Changed,
string? Detail)
{
/// <summary>The loop was built without a probe.</summary>
public static readonly NgxDriverState NotRun = new(NgxProbeOutcome.NotRun, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, false, null);
/// <summary>The one reading this host acts on: the driver says an NGX super-resolution feature ran here.</summary>
public bool SrCreatedAndEvaluated =>
Outcome == NgxProbeOutcome.Answered && (Sr & NgxOverrideFlags.CreatedAndEvaluated) == NgxOverrideFlags.CreatedAndEvaluated;
/// <summary>The driver says an NGX frame-generation feature ran here — an IDENTITY witness, never a count.</summary>
public bool FgCreatedAndEvaluated =>
Outcome == NgxProbeOutcome.Answered && (Fg & NgxOverrideFlags.CreatedAndEvaluated) == NgxOverrideFlags.CreatedAndEvaluated;
/// <summary>One outcome with no masks — a probe that did not answer, and why.</summary>
public static NgxDriverState Of(NgxProbeOutcome outcome, string? detail) =>
NotRun with { Outcome = outcome, Readings = 1, Detail = detail };
/// <summary>
/// The machine line the probe prints (<c>NGXSTATE status=… sr=0x… …</c>), or a <see cref="NgxProbeOutcome.ProbeFailed"/>
/// when nothing in <paramref name="output"/> is one. Every other line of the probe's output is for a human.
/// </summary>
public static NgxDriverState Parse(string output)
{
ArgumentNullException.ThrowIfNull(output);
foreach (string raw in output.Split('\n'))
{
string line = raw.Trim();
if (!line.StartsWith("NGXSTATE ", StringComparison.Ordinal))
{
continue;
}
Dictionary<string, string> kv = new(StringComparer.Ordinal);
foreach (string token in line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Skip(1))
{
int eq = token.IndexOf('=', StringComparison.Ordinal);
if (eq > 0)
{
kv[token[..eq]] = token[(eq + 1)..];
}
}
return FromFields(kv, line);
}
return Of(NgxProbeOutcome.ProbeFailed, "the probe printed no NGXSTATE line");
}
private static NgxDriverState FromFields(Dictionary<string, string> kv, string line)
{
string status = kv.GetValueOrDefault("status", "");
if (string.Equals(status, "ANSWERED", StringComparison.Ordinal))
{
try
{
return new NgxDriverState(NgxProbeOutcome.Answered, Hex(kv["sr"]), Hex(kv["rr"]), Hex(kv["fg"]),
double.Parse(kv["ratio"], CultureInfo.InvariantCulture), U(kv["mode"]), U(kv["preset"]),
U(kv["fgcount"]), U(kv["fgpreset"]), U(kv["fgmode"]), U(kv["driver"]), 1, 1, false, null);
}
catch (Exception e) when (e is KeyNotFoundException or FormatException or OverflowException)
{
return Of(NgxProbeOutcome.ProbeFailed, "an NGXSTATE line this host could not read: " + line);
}
}
return status switch
{
"UNANSWERED" => Of(NgxProbeOutcome.Unanswered, "NvAPI " + kv.GetValueOrDefault("nvapi", "?")),
"DEGRADED" => Of(NgxProbeOutcome.Degraded, "NvAPI_Initialize " + kv.GetValueOrDefault("nvapi", "?")),
_ => Of(NgxProbeOutcome.ProbeFailed, "an NGXSTATE status this host does not know: " + status),
};
}
private static ulong Hex(string v) =>
ulong.Parse(v.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? v[2..] : v, NumberStyles.HexNumber,
CultureInfo.InvariantCulture);
private static uint U(string v) => uint.Parse(v, CultureInfo.InvariantCulture);
/// <summary>Fold a later reading in: an answered one becomes the state, any one counts.</summary>
public NgxDriverState Merge(NgxDriverState later)
{
ArgumentNullException.ThrowIfNull(later);
if (Outcome == NgxProbeOutcome.NotRun)
{
return later;
}
int readings = Readings + later.Readings;
int answered = Answered + later.Answered;
if (later.Outcome != NgxProbeOutcome.Answered)
{
// An earlier answer outranks a later silence: the driver's words do not expire, and a
// probe that failed once mid-session says nothing about what it had already read.
return Outcome == NgxProbeOutcome.Answered
? this with { Readings = readings }
: later with { Readings = readings, Answered = answered };
}
bool changed = Changed || (Outcome == NgxProbeOutcome.Answered && (Sr != later.Sr || Rr != later.Rr || Fg != later.Fg));
return later with { Readings = readings, Answered = answered, Changed = changed };
}
/// <summary>The report's line: the three words decoded, the override fields named as such, the caveats measured.</summary>
public string Describe()
{
string head = " NVIDIA driver NGX state (NvAPI_NGX_GetNGXOverrideState, out of process): ";
return Outcome switch
{
NgxProbeOutcome.NotRun => head + "not probed",
NgxProbeOutcome.ProbeMissing => head + "probe not found - " + Detail,
NgxProbeOutcome.ProbeFailed => head + "probe failed - " + Detail,
NgxProbeOutcome.Degraded => head + "no usable NVIDIA driver on this machine (" + Detail + ")",
NgxProbeOutcome.Unanswered => head + $"the driver did not answer for this process over {Readings} probe(s) ({Detail}) - "
+ "not an NVIDIA-rendered process, a driver older than R570, or the API refusing the caller",
_ => head + $"answered {Answered} of {Readings} probe(s){(Changed ? ", and the words CHANGED between readings" : "")}"
+ $"; driver {Driver / 100}.{Driver % 100:00}\n"
+ $" SR 0x{Sr:X} [{NgxOverrideFlags.Describe(Sr)}] RR 0x{Rr:X} [{NgxOverrideFlags.Describe(Rr)}] "
+ $"FG 0x{Fg:X} [{NgxOverrideFlags.Describe(Fg)}]\n"
+ $" override fields: scalingRatio={ScalingRatio.ToString("0.0000", CultureInfo.InvariantCulture)} "
+ $"performanceMode={PerformanceMode} renderPreset={RenderPreset} fgCount={FgCount} fgPreset={FgPreset} fgMode={FgMode} "
+ "- the OVERRIDE's values when an NVIDIA-app override is set, zero otherwise (measured 2026-09-06); "
+ "the SR and FG words name a feature the driver saw created and evaluated - identity, never a count or a multiplier "
+ "(FG_MODE / FG_MULTI_FRAME stay clear and fgCount is 0 at x4)",
};
}
}
@@ -0,0 +1,79 @@
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// The bits of <c>NV_NGX_DLSS_OVERRIDE_BITFIELD</c> (vendored <c>nvapi.h</c>, R570+), as the driver reports them per
/// process through <c>NvAPI_NGX_GetNGXOverrideState</c>. Constants rather than a <c>[Flags]</c> enum because the
/// masks are 64-bit words the probe prints raw, and a word is what the parser keeps.
/// </summary>
/// <remarks>
/// <b>Measured 2026-09-06 (driver 616.64, <c>20_OPEN_QUESTIONS</c> §H5):</b> <see cref="Created"/> and
/// <see cref="Evaluate"/> on the super-resolution word are set for a process with NO NVIDIA-app override
/// (Hell Is Us, Lies of P), and CLEAR on Lies of P with upscaling switched off — the negative that keeps the rung.
/// <b>The frame-generation word follows DLSS-G too, once the feature exists</b> — the morning's
/// <see cref="Initialized"/> | <see cref="DllExists"/> on Hell Is Us was read before creation; the captures beside
/// the loop read <see cref="Created"/> | <see cref="Evaluate"/> on Hell Is Us, Onimusha and Dying Light: The Beast at
/// ×4, with the word CHANGING between the session's readings. <see cref="FgMode"/> and <see cref="FgMultiFrame"/>
/// stay clear at ×4 and <c>frameGenerationCount</c> is 0, so the word names the feature and never the multiplier.
/// </remarks>
internal static class NgxOverrideFlags
{
public const ulong Initialized = 1UL << 0;
public const ulong Enabled = 1UL << 1;
public const ulong DllExists = 1UL << 2;
public const ulong DllLoaded = 1UL << 3;
public const ulong DllSelected = 1UL << 4;
public const ulong Preset = 1UL << 5;
public const ulong PerfMode = 1UL << 6;
public const ulong ScalingRatio = 1UL << 7;
public const ulong OptimalSettings = 1UL << 8;
public const ulong Created = 1UL << 9;
public const ulong Evaluate = 1UL << 10;
public const ulong FgMode = 1UL << 13;
public const ulong SrDlaaMode = 1UL << 14;
public const ulong FgMultiFrame = 1UL << 15;
public const ulong ErrFailed = 1UL << 16;
public const ulong ErrDenied = 1UL << 17;
public const ulong ErrDrs = 1UL << 18;
public const ulong ErrNotFound = 1UL << 19;
public const ulong ErrDllLoad = 1UL << 20;
/// <summary>The two bits that together say "this feature ran in this process": created, and evaluated.</summary>
public const ulong CreatedAndEvaluated = Created | Evaluate;
private static readonly (ulong Bit, string Name)[] _names =
[
(Initialized, "INITIALIZED"), (Enabled, "ENABLED"), (DllExists, "DLL_EXISTS"), (DllLoaded, "DLL_LOADED"),
(DllSelected, "DLL_SELECTED"), (Preset, "PRESET"), (PerfMode, "PERF_MODE"), (ScalingRatio, "SCALING_RATIO"),
(OptimalSettings, "OPTIMAL_SETTINGS"), (Created, "CREATED"), (Evaluate, "EVALUATE"), (FgMode, "FG_MODE"),
(SrDlaaMode, "SR_DLAA_MODE"), (FgMultiFrame, "FG_MULTI_FRAME"), (ErrFailed, "ERR_FAILED"),
(ErrDenied, "ERR_DENIED"), (ErrDrs, "ERR_DRS"), (ErrNotFound, "ERR_NOT_FOUND"), (ErrDllLoad, "ERR_DLL_LOAD"),
];
/// <summary>The probe's own spelling of a word's bits, unknown bits printed as hex so nothing is dropped.</summary>
public static string Describe(ulong mask)
{
if (mask == 0)
{
return "-";
}
List<string> parts = [];
ulong seen = 0;
foreach ((ulong bit, string name) in _names)
{
if ((mask & bit) != 0)
{
parts.Add(name);
seen |= bit;
}
}
ulong unknown = mask & ~seen;
if (unknown != 0)
{
parts.Add("0x" + unknown.ToString("X", System.Globalization.CultureInfo.InvariantCulture));
}
return string.Join(' ', parts);
}
}
@@ -0,0 +1,23 @@
namespace FrameLedger.CaptureHost.Consume;
/// <summary>What one run of <c>fl-probe-nvapi --ngx-state</c> came back with.</summary>
internal enum NgxProbeOutcome
{
/// <summary>The loop was built without a probe, or the probe never ran.</summary>
NotRun,
/// <summary>The driver answered for this pid; the masks are the driver's.</summary>
Answered,
/// <summary>NvAPI answered but not for this pid: not NVIDIA-rendered, an old driver, or the API refusing the caller.</summary>
Unanswered,
/// <summary>No usable NVIDIA driver on this machine.</summary>
Degraded,
/// <summary>The probe binary was not beside this host.</summary>
ProbeMissing,
/// <summary>The probe could not be started, timed out, or printed nothing this host understands.</summary>
ProbeFailed,
}
@@ -0,0 +1,10 @@
namespace FrameLedger.CaptureHost.Consume;
/// <summary>One vendor runtime module the loader reported in the target, with its file version.</summary>
/// <remarks>
/// <b>The version is read from the FILE on disk, never from the process.</b> The only thing read
/// out of the target is the loader's module list — the same documented read the anti-cheat guard
/// performs on every target before injecting — and the path it names is then opened as a file.
/// CLAUDE.md rule 4 is untouched: no game memory, no vendor object, no hook.
/// </remarks>
internal sealed record RuntimeModuleInfo(string FileName, string Path, string? FileVersion, Version? Parsed);
@@ -0,0 +1,51 @@
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// The census-named modules a session's target had loaded, with versions, merged over every
/// snapshot the loop took.
/// </summary>
/// <remarks>
/// <para>
/// <b>Why this exists.</b> <c>FlWriterState.runtimeCensus</c> says a module of a NAME was loaded and
/// nothing else. Dying Light: The Beast and Cyberpunk 2077 both load a Streamline interposer; one
/// ships 2.8.0 and the other 2.7.1, and <c>20_OPEN_QUESTIONS</c> §H5 case 3 turns on exactly that
/// difference. The census cannot carry it without a layout change; this can, from outside the
/// process, at no cost on the present path.
/// </para>
/// <para>
/// <b>First seen wins per name.</b> A module that unloads and reloads between snapshots keeps its
/// first version; the report is about what the session ran, not about the last thing the loader
/// said. <see cref="Snapshots"/> and <see cref="Unreadable"/> are counted rather than folded into
/// one flag, because a target that exits before the final snapshot makes that snapshot fail
/// without making the earlier ones wrong.
/// </para>
/// </remarks>
internal sealed record RuntimeModuleSet(IReadOnlyList<RuntimeModuleInfo> Modules, int Snapshots, int Unreadable)
{
public static RuntimeModuleSet Empty { get; } = new([], 0, 0);
/// <summary>
/// The parsed file version of <paramref name="fileName"/>, or null when the module was never
/// seen or carries no version resource.
/// </summary>
public Version? VersionOf(string fileName) => Find(fileName)?.Parsed;
public RuntimeModuleInfo? Find(string fileName) =>
Modules.FirstOrDefault(m => string.Equals(m.FileName, fileName, StringComparison.OrdinalIgnoreCase));
/// <summary>This set, then <paramref name="later"/>'s modules that this one did not already name.</summary>
public RuntimeModuleSet Merge(RuntimeModuleSet later)
{
ArgumentNullException.ThrowIfNull(later);
var merged = new List<RuntimeModuleInfo>(Modules);
foreach (RuntimeModuleInfo m in later.Modules)
{
if (!merged.Exists(x => string.Equals(x.FileName, m.FileName, StringComparison.OrdinalIgnoreCase)))
{
merged.Add(m);
}
}
return new RuntimeModuleSet(merged, Snapshots + later.Snapshots, Unreadable + later.Unreadable);
}
}
@@ -46,35 +46,33 @@ internal static class SessionReport
sb.Append(" Native FPS: ").Append(Num(w.NativeFps))
.Append(" -> Displayed FPS: ").Append(Num(w.DisplayedFps))
.Append(" (x").Append(Num(w.Factor)).Append(" FG)")
.Append(" over ").Append(Count(w.Presents)).AppendLine(" present(s)");
.Append(" over ").Append(Count(w.DisplayedPresents)).AppendLine(" present(s)");
if (w.DxgiCounted)
{
// A COUNT DXGI MADE, NOT THIS HOOK, and the line says so before anyone reads the
// trio: those presents have no timestamps here, so they may stand in a rate and
// a factor and never in a frame-time distribution (03_METRICS §Counting).
sb.Append(" Displayed is DXGI-COUNTED: ").Append(Count(w.DxgiUnseen))
.Append(" of those present(s) were counted by IDXGISwapChain::GetLastPresentCount on the hooked ")
.Append("chain and never reached this hook (").Append(Count(w.Presents))
.AppendLine(" hooked) — a count DXGI made, not this hook; 20_OPEN_QUESTIONS §H5 row P1-DXGI");
}
}
else if (facts.Fg?.IsNone == true)
else if (facts.Fg?.IsNone == true && facts.NoneWithheld is null)
{
// THE THIRD SHAPE, reachable since 2026-09-04: 08_UI's bare `144 FPS`. No pair, no
// factor, no qualifier — the count measured that every present carried an
// application frame, which is the one negative this report may state outright.
FgWindow w = facts.Fg;
sb.Append(" FPS: ").Append(Num(w.NativeFps))
.Append(" over ").Append(Count(w.Presents)).AppendLine(" present(s)");
sb.Append(" frame generation: none — ").Append(Count(w.Evaluations))
.Append(" application frame(s) counted (slGetNewFrameToken, or an ffx-api PREPARE / UPSCALE dispatch) against ")
.Append(Count(w.Presents))
.AppendLine(" present(s); every present carried an application frame");
//
// UNLESS IT IS WITHHELD. On Streamline 2.8 with sl.dlss_g.dll loaded the same count read
// 1.00 five times while the title was generating (§H5 case 3), so that shape falls
// through to the Presented line and its qualifier says why. MeasuredFacts owns the
// decision; this branch only honours it.
AppendNone(sb, facts.Fg, facts);
}
else
{
// PRESENTED FPS, the name for the one number that stands alone (03_METRICS §Core
// definitions, 2026-09-03). Numerically it is Displayed FPS; the name changes because
// "Displayed" is half of a pair, and printing half a pair invites the reader to supply
// the other half. The qualifier under it is mandatory, and which one is printed is the
// census's whole job.
sb.Append(" Presented FPS: ").Append(Num(facts.DisplayedFps))
.Append(" over ").Append(Count(facts.PresentsObserved)).AppendLine(" present(s)");
sb.Append(" ").AppendLine(FgQualifier(facts));
if (facts.Fg?.Refusal is not null)
{
sb.Append(" no FG factor: ").AppendLine(facts.Fg.Refusal);
}
AppendPresented(sb, facts);
}
AppendFgDiagnostics(sb, facts.Fg);
@@ -84,6 +82,41 @@ internal static class SessionReport
return sb.ToString().TrimEnd();
}
/// <summary>The bare number and the counted negative, with DXGI's counter beside it when it was read.</summary>
private static void AppendNone(StringBuilder sb, FgWindow w, MeasuredFacts facts)
{
sb.Append(" FPS: ").Append(Num(w.NativeFps))
.Append(" over ").Append(Count(w.Presents)).AppendLine(" present(s)");
sb.Append(" frame generation: none — ").Append(Count(w.Evaluations))
.Append(" application frame(s) counted (slGetNewFrameToken, or an ffx-api PREPARE / UPSCALE dispatch) against ")
.Append(Count(w.Presents))
.Append(" present(s); every present carried an application frame")
.AppendLine(facts.NoneBesideDxgi is string dxgi ? "; " + dxgi : "");
}
/// <summary>
/// PRESENTED FPS, the name for the one number that stands alone (03_METRICS §Core definitions,
/// 2026-09-03). Numerically it is Displayed FPS; the name changes because "Displayed" is half of
/// a pair, and printing half a pair invites the reader to supply the other half. The qualifier
/// under it is mandatory, and which one is printed is the census's whole job.
/// </summary>
private static void AppendPresented(StringBuilder sb, MeasuredFacts facts)
{
sb.Append(" Presented FPS: ").Append(Num(facts.DisplayedFps))
.Append(" over ").Append(Count(facts.PresentsObserved)).AppendLine(" present(s)");
sb.Append(" ").AppendLine(FgQualifier(facts));
if (facts.NoneWithheld is not null)
{
sb.AppendLine(" frame generation: NOT stated — the FG counts below are the record; the discriminator "
+ "is the title's own counter beside this line (§H5)");
}
if (facts.Fg?.Refusal is not null)
{
sb.Append(" no FG factor: ").AppendLine(facts.Fg.Refusal);
}
}
/// <summary>Defects in the DATA, each attributed to where it came from, never averaged in.</summary>
private static void AppendWarnings(StringBuilder sb, MeasuredFacts facts)
{
@@ -119,6 +152,40 @@ internal static class SessionReport
/// </remarks>
private static string FgQualifier(MeasuredFacts facts)
{
// THE WITHHELD SHAPE COMES FIRST, because the WARNING below it reads in the wrong
// direction for this case. "MAY include generated frames; read it as Displayed" is right
// when nothing was counted; here the count says the presents ARE the application frames
// and the generated ones are the number nobody has. Displayed is what is unknown.
if (facts.NoneWithheld is not null)
{
return "WARNING: the count read presents = application frames (1.00) and `none` is WITHHELD — "
+ facts.NoneWithheld
+ ". 20_OPEN_QUESTIONS §H5 case 3: on this shape the generated presents may never reach the "
+ "Present bodies this hook patches, so this number counts APPLICATION frames; whether frames were "
+ "generated, and the Displayed rate, are unknown. Read it as the application-frame rate, never "
+ "as Displayed"
+ (facts.DlssgInputsTagged
? ". The title tagged DLSS-G inputs (HUD-less / UI) through Streamline this session — it is "
+ "FEEDING frame generation, which is the identity; the count is still what it is"
: "");
}
// A COUNTED SESSION WHOSE FACTOR WAS REFUSED is not "no evaluation was observed". Measured
// 2026-09-06 on DL:TB at FSR + DLSS-G: 4,415 tokens, 8,174 DXGI-counted presents, the tags naming
// DLSS-G, and the factor refused because the last bucket read 1.96 against 2.85 — and this line
// said a runtime was loaded and nothing was seen. The number is every hooked present over a
// session that held more than one configuration, and it is neither Native nor Displayed.
if (facts.Fg is { Refusal: not null, Evaluations: > 0 } counted)
{
return "WARNING: frame generation was counted (" + Count(counted.Evaluations) + " application-frame token(s)"
+ (counted.DxgiCounted
? ", and DXGI counted " + Count(counted.DxgiUnseen) + " present(s) this hook never saw, so the "
+ "Displayed rate is ABOVE this number"
: "")
+ ") and its factor is REFUSED — see `no FG factor` below — so this number is every hooked present "
+ "over a session that did not hold one configuration; read it as neither Native nor Displayed";
}
if (!facts.CensusRan)
{
return "frame generation: NOT measured, and the runtime census did not run — this number is presents, "
@@ -132,9 +199,29 @@ internal static class SessionReport
+ "Displayed, not Native";
}
return CensusClearQualifier(facts);
}
/// <summary>The qualifier when no frame-generation module was loaded — the executable file decides its verb.</summary>
private static string CensusClearQualifier(MeasuredFacts facts)
{
// THE CENSUS IS CLEAR, and the executable file is the second witness (HANDOFF 7b). A frame
// generator compiled into the exe loads no module — Rune Factory and Wukong, measured — so
// "cannot include" was wrong there in the dangerous direction. The on-disk scan cannot say the
// code ran; it can say the sentence may not exclude it.
if (facts.Markers.AnyFgCapable)
{
return "WARNING: no known frame-generation runtime MODULE was loaded, but the executable itself carries "
+ facts.Markers.FgCapableNames + " — a frame generator compiled into the executable is outside what "
+ "the module census sees, so this number MAY include generated frames; read it as Displayed, not Native";
}
return "frame generation: not measured — no known frame-generation runtime was loaded in this process, "
+ "so this number cannot include in-process generated frames (statically linked FSR3-FG and "
+ "driver-level AFMF are outside what this can see)";
+ "driver-level AFMF are outside what this can see"
+ (facts.Markers.Scanned
? "; the executable carries none of the frame-generation SDK strings this host scans for)"
: ")");
}
/// <summary>The per-session facts, each with the reason behind its N/A.</summary>
@@ -154,20 +241,38 @@ internal static class SessionReport
// can tell that apart from a title driving DLSS through a path we do not hook — Black Myth:
// Wukong loads sl.interposer.dll, runs DLSS-G, and calls it never — so the line names all
// three rather than picking the one that flatters the hook.
sb.Append(" upscaler: ").AppendLine(facts.Upscaler
// A hook's name first; else the driver's word, attributed (03_METRICS §Upscaling, the
// driver-reported rung); else the two N/As. The driver's note rides beside whichever printed.
sb.Append(" upscaler: ").Append(facts.Upscaler
?? facts.UpscalerDriverReported
?? (facts.UpscalerHookRan
? "N/A (an upscaler hook ran — Streamline's slEvaluateFeature and/or an ffx-api leaf's ffxDispatch — "
+ "and no evaluation this build decodes arrived: "
+ "upscaling is off in this title's settings, or it runs through a path this build does not "
+ "hook — measured on 3 of 5 Streamline titles — or a vendor this build does not decode)"
: NoHookRan("upscaler", facts.CensusRan, facts.UpscalerRuntimesLoaded)));
sb.Append(" render -> output: ").AppendLine(facts.UpscaleRatio is null
? "N/A (the ratio is not computed yet; the raw sizes are above)"
: Num(facts.UpscaleRatio));
sb.Append(" frame generation: ").AppendLine(facts.FgMode
if (facts.UpscalerDriverNote is string driver)
{
sb.Append(" — ").Append(driver);
}
if (facts.XessByLicenceNote is string xess)
{
sb.Append(" — ").Append(xess);
}
sb.AppendLine();
sb.Append(" render -> output: ").AppendLine(RenderToOutput(facts.Extent));
sb.Append(" frame generation: ").Append(facts.FgModePrinted
?? (facts.FgHookRan
? "N/A (a hook ran and saw no frame-generation evaluation — see the FG counts above)"
? facts.FgNotEvaluatedPrinted
: NoHookRan("frame-generation", facts.CensusRan, facts.FgRuntimesLoaded)));
if (facts.FgDriverNote is string fgDriver)
{
sb.Append(" — ").Append(fgDriver);
}
sb.AppendLine();
sb.Append(" ray tracing: ").AppendLine(facts.RayTracing.ToString());
sb.Append(" ray reconstruction: ").AppendLine(facts.RayReconstruction.ToString());
sb.Append(" path tracing: ").AppendLine(facts.PathTracing.ToString());
@@ -213,6 +318,7 @@ internal static class SessionReport
// record 0 while this one starts after the lazy-install prefix — and the resulting rate
// moved across 78.6-83 on window choice alone, ten times the residual that draft quoted.
sb.Append(" FG counts: presents=").Append(Count(w.Presents))
.Append(" dxgi-unseen=").Append(Count(w.DxgiUnseen))
.Append(" batches=").Append(Count(w.Batches))
.Append(" tokens=").Append(Count(w.Evaluations))
.Append(" streams=").Append(Count(w.Streams))
@@ -307,6 +413,25 @@ internal static class SessionReport
}
}
/// <summary>
/// The extent line: two measured sizes, the ratio <c>03_METRICS</c> defines over them, and
/// whether the window ran at one tuple. Never a preset name — that is HANDOFF 7a's owner call.
/// </summary>
private static string RenderToOutput(UpscaleExtent? e)
{
if (e is null)
{
return "N/A (no record carried both a render size and an output size)";
}
string line = $"{e.RenderW}x{e.RenderH} -> {e.OutputW}x{e.OutputH} = {Num(e.Ratio)}x "
+ $"({e.RenderScalePercent.ToString("0", CultureInfo.InvariantCulture)}% render scale) "
+ $"on {Count(e.Records)} of {Count(e.Measured)} record(s)";
return e.DistinctGroups > 1
? line + $" — SETTINGS MOVED: {Count(e.DistinctGroups)} distinct extents in the window, this is the dominant one"
: line;
}
private static string Num(double? v) =>
v is null ? "N/A" : v.Value.ToString("0.##", CultureInfo.InvariantCulture);
@@ -0,0 +1,55 @@
using System.Text;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// The Streamline buffer-type names behind <see cref="FlWriterState.SlTagCensus"/> bits, per route, for the report.
/// </summary>
/// <remarks>
/// Display only, like <see cref="CensusNames"/>. The authority is <c>FlSlTagType</c> in <c>fl_shm.h</c>; this
/// copy exists so a real-title run can say <i>which</i> buffers the title tagged on <i>which</i> route rather than
/// print a bit number — the input to §H5's question of whether a title feeds DLSS Frame Generation through the
/// exports this build hooks.
/// </remarks>
internal static class SlTagCensusNames
{
private static readonly (FlSlTagType Bit, string Name)[] _names =
[
(FlSlTagType.Depth, "depth"),
(FlSlTagType.MotionVectors, "mvec"),
(FlSlTagType.Hudless, "hudless"),
(FlSlTagType.ScalingInput, "scaling-in"),
(FlSlTagType.ScalingOutput, "scaling-out"),
(FlSlTagType.UiColorAlpha, "ui-color-alpha"),
(FlSlTagType.UiAlpha, "ui-alpha"),
(FlSlTagType.Backbuffer, "backbuffer"),
(FlSlTagType.Other, "other"),
];
/// <summary>Comma-separated names for one route's bits; <c>-</c> when none.</summary>
public static string Describe(FlSlTagType bits)
{
var sb = new StringBuilder();
foreach ((FlSlTagType bit, string name) in _names)
{
if (bits.HasFlag(bit))
{
if (sb.Length > 0)
{
sb.Append(", ");
}
sb.Append(name);
}
}
return sb.Length == 0 ? "-" : sb.ToString();
}
/// <summary>The whole census, one bracket per route.</summary>
public static string DescribeRoutes(uint census) =>
$"global=[{Describe(FlSlTagRoute.Of(census, FlSlTagRoute.Global))}] "
+ $"frame=[{Describe(FlSlTagRoute.Of(census, FlSlTagRoute.Frame))}] "
+ $"local=[{Describe(FlSlTagRoute.Of(census, FlSlTagRoute.Local))}]";
}
@@ -0,0 +1,146 @@
using System.Globalization;
using System.Text;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// The longest present-to-present intervals in a stream, each placed against the moments this host
/// touched the target — so "the game dropped to 1 FPS for a second" can be read as ours or not ours.
/// </summary>
/// <remarks>
/// <para>
/// <b>Why this exists.</b> The owner saw Cyberpunk 2077 fall to 1 FPS for about a second under capture
/// (2026-09-05) and the report had nothing to say about it: no frame-time statistic is computed by this
/// throwaway (P2's calculators own them), and nothing correlated a gap with what FrameLedger was doing.
/// FrameLedger touches the target at known moments — the guard's 30 s re-scan enumerates its modules,
/// and the module snapshot reads the same list beside it — and the records carry QPC, the same clock
/// <see cref="System.Diagnostics.Stopwatch.GetTimestamp"/> reads. So a stall can be placed: within a
/// touch window it is a suspect; far from every touch it is the title's own (a shader compile, a
/// level stream, a menu).
/// </para>
/// <para>
/// <b>Not a stutter metric.</b> <c>03_METRICS</c> defines stutter against a rolling median with edge
/// rules and a sufficiency floor, and this prints none of that. It prints the few longest raw
/// intervals and where they sit, which is a diagnostic, and it says so.
/// </para>
/// </remarks>
internal sealed record StallReport
{
/// <summary>One long interval: where it starts in the session, how long it is, and the nearest touch.</summary>
internal sealed record Stall(double AtSeconds, double Milliseconds, double? NearestTouchSeconds)
{
/// <summary>A touch inside the interval or within <see cref="TouchWindowSeconds"/> of it is a suspect.</summary>
public bool NearATouch => NearestTouchSeconds is double d && Math.Abs(d) <= TouchWindowSeconds;
}
/// <summary>How far a host touch may be from a stall and still be named beside it.</summary>
public const double TouchWindowSeconds = 1.0;
/// <summary>Intervals at or above this are counted as stalls — ten presents' worth at 100 FPS.</summary>
public const double StallThresholdMs = 100.0;
public required IReadOnlyList<Stall> Longest { get; init; }
public required int OverThreshold { get; init; }
public required int Intervals { get; init; }
public required int Touches { get; init; }
public static StallReport From(IReadOnlyList<FlFrameRecord> stream, long qpcFrequency, IReadOnlyList<long> touchQpc,
int keep = 3)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(touchQpc);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(qpcFrequency);
var stalls = new List<Stall>();
int over = 0;
int intervals = 0;
if (stream.Count > 1)
{
long origin = (long)stream[0].Qpc;
var candidates = new List<(long StartQpc, long DeltaQpc)>();
for (int i = 1; i < stream.Count; i++)
{
long delta = (long)stream[i].Qpc - (long)stream[i - 1].Qpc;
if (delta <= 0)
{
continue; // a torn or reordered record; the drain reports gaps separately
}
intervals++;
if (delta * 1000.0 / qpcFrequency >= StallThresholdMs)
{
over++;
}
candidates.Add(((long)stream[i - 1].Qpc, delta));
}
foreach ((long startQpc, long deltaQpc) in candidates.OrderByDescending(c => c.DeltaQpc).Take(keep))
{
double at = (startQpc - origin) / (double)qpcFrequency;
double ms = deltaQpc * 1000.0 / qpcFrequency;
double? nearest = null;
foreach (long t in touchQpc)
{
// Distance from the touch to the interval [start, start + delta]: 0 when inside.
double d = t < startQpc ? (t - startQpc) / (double)qpcFrequency
: t > startQpc + deltaQpc ? (t - (startQpc + deltaQpc)) / (double)qpcFrequency
: 0.0;
if (nearest is null || Math.Abs(d) < Math.Abs(nearest.Value))
{
nearest = d;
}
}
stalls.Add(new Stall(at, ms, nearest));
}
}
return new StallReport { Longest = stalls, OverThreshold = over, Intervals = intervals, Touches = touchQpc.Count };
}
/// <summary>The report lines. A diagnostic, and it names itself as one.</summary>
public string Describe()
{
if (Intervals == 0)
{
return " stalls: no interval to read (fewer than two presents)";
}
var sb = new StringBuilder();
sb.Append(" stalls (diagnostic, not 03_METRICS' stutter): ").Append(Num(OverThreshold))
.Append(" interval(s) of ").Append(Num(Intervals)).Append(" at or over ")
.Append(Ms(StallThresholdMs)).Append("; host touches (guard scan + module snapshot): ").Append(Num(Touches));
foreach (Stall s in Longest)
{
sb.AppendLine();
sb.Append(" longest: ").Append(Ms(s.Milliseconds)).Append(" at t=").Append(Sec(s.AtSeconds)).Append(" — ");
if (s.NearestTouchSeconds is not double d)
{
sb.Append("no host touch recorded");
}
else if (s.NearATouch)
{
sb.Append("A HOST TOUCH ").Append(d == 0 ? "INSIDE the interval" : (Math.Abs(d).ToString("0.00", CultureInfo.InvariantCulture) + " s "
+ (d < 0 ? "before" : "after") + " it"))
.Append(" — FrameLedger is a SUSPECT for this one; re-run with a longer --seconds and see whether it recurs on the 30 s cadence");
}
else
{
sb.Append("nearest host touch ").Append(Math.Abs(d).ToString("0.0", CultureInfo.InvariantCulture)).Append(" s away — not ours");
}
}
return sb.ToString();
}
private static string Num(long v) => v.ToString(CultureInfo.InvariantCulture);
private static string Ms(double v) => v.ToString("0.#", CultureInfo.InvariantCulture) + " ms";
private static string Sec(double v) => v.ToString("0.00", CultureInfo.InvariantCulture) + " s";
}
@@ -0,0 +1,120 @@
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// The render → output extent a session ran at, taken as the MODAL tuple over the records
/// that claim <see cref="FlMeasured.UpscalerParams"/> and carry an output size.
/// </summary>
/// <remarks>
/// <para>
/// <b>Two measurements, one piece of arithmetic.</b> <c>renderW/H</c> come off the upscaler's own
/// dispatch (Streamline's scaling-input tag, or the ffx-api descriptor's <c>renderSize</c>) and
/// <c>outputW/H</c> off the swapchain the present hook read; the ratio is <c>03_METRICS</c>
/// §Upscaling's <c>sqrt((outW×outH)/(renW×renH))</c>, and the render scale is its reciprocal as
/// a percentage. Measured on Cyberpunk 2077 at <c>DLSS = Balanced</c>: 1485×835 against 2560×1440
/// is 1.72× and 58%, which is a number a writer that hardcoded a plausible resolution could not
/// have produced.
/// </para>
/// <para>
/// <b>Modal, not mean, and the count of distinct tuples is published beside it.</b> Averaging
/// across a settings change or a dynamic-resolution swing is the classic way a benchmark number
/// stops meaning anything (<c>03_METRICS</c> §Upscaling, segments); until P2's segmenter cuts the
/// session, the throwaway consumer reports the tuple most records ran at and says how many others
/// it saw.
/// </para>
/// </remarks>
internal sealed record UpscaleExtent
{
public required ushort RenderW { get; init; }
public required ushort RenderH { get; init; }
public required ushort OutputW { get; init; }
public required ushort OutputH { get; init; }
/// <summary>Records that ran at exactly this tuple.</summary>
public required int Records { get; init; }
/// <summary>Records in the window that carried both sizes, whatever their tuple.</summary>
public required int Measured { get; init; }
/// <summary>Distinct (render, output) tuples in the window. More than 1 means the settings moved.</summary>
public required int DistinctGroups { get; init; }
/// <summary><c>sqrt((outW×outH)/(renW×renH))</c>.</summary>
public double Ratio => Math.Sqrt((double)OutputW * OutputH / ((double)RenderW * RenderH));
/// <summary>The per-axis render scale as a percentage — <c>100 / Ratio</c>.</summary>
public double RenderScalePercent => 100.0 / Ratio;
/// <summary>The dominant extent over the identity-claiming window, or null when no record in it carried both sizes.</summary>
/// <remarks>
/// <b>The window is the IDENTITY suffix, not the params suffix — measured 2026-09-05 on every
/// frame-generation run.</b> The writer publishes <see cref="FlMeasured.UpscalerParams"/> only on
/// the present that DRAINED a dispatch or tag, which under frame generation is one present in N;
/// the other N−1 carry the identity bit and an honest zero. <see cref="RecordWindow.ClaimedSuffixStart"/>
/// demands a clean suffix in which every record claims the bit, so keyed on params it returned
/// "no window" for every FG-on capture — Cyberpunk at FSR 3 + FG printed <c>render -> output: N/A</c>
/// two lines under its own raw block reading <c>render 1506x847 on 4332 record(s)</c>, and the
/// 2026-09-04 build's "not computed yet" wording had hidden it. The identity bit IS per-record once
/// its family is live (both routes set it on every present), so it is the install window; inside
/// it, every record that carries both sizes counts, whichever present it landed on.
/// </remarks>
public static UpscaleExtent? From(IReadOnlyList<FlFrameRecord> stream)
{
ArgumentNullException.ThrowIfNull(stream);
int start = RecordWindow.ClaimedSuffixStart(
stream, static r => ((FlMeasured)r.MeasuredMask).HasFlag(FlMeasured.Upscaler));
if (start == stream.Count)
{
// No identity window: fall back to the params bit itself, which is what a
// params-only writer would publish per record.
start = RecordWindow.ClaimedSuffixStart(
stream, static r => ((FlMeasured)r.MeasuredMask).HasFlag(FlMeasured.UpscalerParams));
}
if (start == stream.Count)
{
return null;
}
var groups = new Dictionary<(ushort, ushort, ushort, ushort), int>();
int measured = 0;
for (int i = start; i < stream.Count; i++)
{
FlFrameRecord r = stream[i];
var mask = (FlMeasured)r.MeasuredMask;
// BOTH bits, not just the values: a value set while its bit is clear is the writer's
// defect (IsHonest counts it), and this must not quietly average it in.
if (!mask.HasFlag(FlMeasured.UpscalerParams) || !mask.HasFlag(FlMeasured.OutputRes)
|| r.RenderW == 0 || r.RenderH == 0 || r.OutputW == 0 || r.OutputH == 0)
{
continue;
}
measured++;
(ushort, ushort, ushort, ushort) key = (r.RenderW, r.RenderH, r.OutputW, r.OutputH);
groups[key] = groups.GetValueOrDefault(key) + 1;
}
if (measured == 0)
{
return null;
}
KeyValuePair<(ushort, ushort, ushort, ushort), int> modal = groups.MaxBy(static g => g.Value);
return new UpscaleExtent
{
RenderW = modal.Key.Item1,
RenderH = modal.Key.Item2,
OutputW = modal.Key.Item3,
OutputH = modal.Key.Item4,
Records = modal.Value,
Measured = measured,
DistinctGroups = groups.Count,
};
}
}
@@ -83,4 +83,37 @@
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Rules.targets" />
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Overlay.targets" />
<!--
fl-probe-nvapi.exe beside the host, the way the Overlay is: NgxDriverProbe spawns it
by absolute path from AppContext.BaseDirectory and reports ProbeMissing rather than
searching. Warn-not-fail for the same reason the Overlay targets do: build.ps1 runs
the native build first. UNSHIPPED with this host; the Agent would call NVAPI through
Infrastructure, not a child process.
-->
<PropertyGroup>
<FlNativeProbeDir>$(MSBuildThisFileDirectory)..\..\build\native\x64-release\tools\fl-probe-nvapi\</FlNativeProbeDir>
</PropertyGroup>
<ItemGroup>
<None Include="$(FlNativeProbeDir)fl-probe-nvapi.exe" Condition="Exists('$(FlNativeProbeDir)fl-probe-nvapi.exe')">
<Link>fl-probe-nvapi.exe</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<!--
The Vulkan implicit layer beside the host (P1 item 3). `launch` writes a manifest pointing at THIS
copy and hands the launched process VK_ADD_IMPLICIT_LAYER_PATH, so the layer is discoverable only by
that process: no registry, nothing machine-wide (VkLayerLaunchEnvironment). Warn-not-fail like the
others: build.ps1 runs the native build first, and a missing DLL is reported by `launch` itself.
-->
<PropertyGroup>
<FlVkLayerDir>$(MSBuildThisFileDirectory)..\..\build\native\x64-release\FrameLedger.VkLayer\</FlVkLayerDir>
</PropertyGroup>
<ItemGroup>
<None Include="$(FlVkLayerDir)FrameLedger.VkLayer.dll" Condition="Exists('$(FlVkLayerDir)FrameLedger.VkLayer.dll')">
<Link>FrameLedger.VkLayer.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
+139 -20
View File
@@ -10,6 +10,7 @@
// flag on a shipped one.
using System.Diagnostics;
using System.Globalization;
using FrameLedger.Application.AntiCheat;
using FrameLedger.Application.Consent;
using FrameLedger.Application.Rules;
@@ -22,6 +23,7 @@ using FrameLedger.Infrastructure.AntiCheat;
using FrameLedger.Infrastructure.Io;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Infrastructure.Rules;
using FrameLedger.Infrastructure.Vulkan;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost;
@@ -68,6 +70,7 @@ internal static class Program
Verb.ConsentGrant => await GrantAsync(store, cmd.ExePath!).ConfigureAwait(false),
Verb.ConsentRevoke => await RevokeAsync(store, cmd.ExePath!).ConfigureAwait(false),
Verb.Capture => await CaptureAsync(store, cmd.ExePath!, cmd.Seconds).ConfigureAwait(false),
Verb.Launch => await LaunchAsync(store, cmd.ExePath!, cmd.Arguments, cmd.Seconds).ConfigureAwait(false),
Verb.ProbeLhm => LhmProbe.Run(cmd.Seconds == 0 ? LhmProbe.DefaultSeconds : cmd.Seconds),
_ => _exitUsage,
};
@@ -130,20 +133,57 @@ internal static class Program
return outcome is ConsentWriteOutcome.Written or ConsentWriteOutcome.NotFound ? _exitOk : _exitRefused;
}
// §S22: the payload must resolve into the directory the GUARD's own code was loaded from,
// compared by file id. There is no way to name a different one, which is the point.
private static string Payload => Path.Combine(AppContext.BaseDirectory, "FrameLedger.Overlay.dll");
private static async Task<int> CaptureAsync(FileGameConsentStore store, string exePath, int seconds)
{
string normalised = ExecutableIdentity.Normalise(exePath);
ExecutableFingerprint? observed = ExecutableIdentity.Read(exePath);
// §S22: the payload must resolve into the directory the GUARD's own code was loaded from,
// compared by file id. There is no way to name a different one, which is the point.
string payload = Path.Combine(AppContext.BaseDirectory, "FrameLedger.Overlay.dll");
CaptureResult result = await BuildLoop(store, seconds)
.RunAsync(normalised, observed, payload).ConfigureAwait(false);
.RunAsync(normalised, observed, Payload).ConfigureAwait(false);
return await ConcludeAsync(store, normalised, observed, result).ConfigureAwait(false);
}
/// <summary>Launch mode: the same loop, entered by starting the executable rather than finding it.</summary>
/// <remarks>
/// The Vulkan layer rides on the launch (P1 item 3): the process gets <c>VK_ADD_IMPLICIT_LAYER_PATH</c> and
/// the enable variable, and its image name goes on the layer's enable-list for the session -- no registry,
/// nothing machine-wide, removed when the session ends. A D3D title ignores all of it; a Vulkan title is
/// observed by the layer and the guard injects nothing (<c>TargetIsVulkanLayered</c>).
/// </remarks>
private static async Task<int> LaunchAsync(FileGameConsentStore store, string exePath, string arguments,
int seconds)
{
string normalised = ExecutableIdentity.Normalise(exePath);
ExecutableFingerprint? observed = ExecutableIdentity.Read(exePath);
using var vulkan = VkLayerLaunchEnvironment.Prepare(normalised,
Path.Combine(AppContext.BaseDirectory, "FrameLedger.VkLayer.dll"));
HostConsole.Line(vulkan.ManifestPath is null
? "vulkan layer: NOT staged beside this host - a Vulkan title will present unobserved"
: $"vulkan layer: {vulkan.ManifestPath} (via {VkLayerLaunchEnvironment.ImplicitLayerPathVariable}; " +
$"enable-list entry '{vulkan.ImageName}' for this session)");
CaptureResult result = await BuildLoop(store, seconds, (exe, args) => ProcessLauncher.Start(exe, args, vulkan.Variables))
.RunLaunchedAsync(normalised, observed, Payload, arguments).ConfigureAwait(false);
return await ConcludeAsync(store, normalised, observed, result).ConfigureAwait(false);
}
private static async Task<int> ConcludeAsync(FileGameConsentStore store, string normalised,
ExecutableFingerprint? observed, CaptureResult result)
{
HostConsole.Line($"session: {result.Reason}");
if (result.Verdict.Reason != Domain.AntiCheat.AntiCheatRefusalReason.Allow)
if (result.Verdict.Reason == Domain.AntiCheat.AntiCheatRefusalReason.TargetIsVulkanLayered)
{
HostConsole.Line(" capture side: the Vulkan implicit layer - the guard passed and nothing was injected " +
"(one ring per process; 17_HOOK_ENGINE §Vulkan)");
}
else if (result.Verdict.Reason != Domain.AntiCheat.AntiCheatRefusalReason.Allow)
{
HostConsole.Line($" verdict: {result.Verdict.Reason} {result.Verdict.Family} {result.Verdict.Signal}");
}
@@ -155,7 +195,9 @@ internal static class Program
if (result.Records.Count > 0)
{
Report(result);
// The exe FILE on disk, after the session so the read never overlaps the launch: the
// second witness for a frame generator compiled into the executable (HANDOFF 7b).
Report(result, ExecutableMarkerScan.Scan(normalised));
}
return result.Reason switch
@@ -163,15 +205,15 @@ internal static class Program
SessionEndReason.TargetExited => _exitOk,
SessionEndReason.Running => _exitOk,
SessionEndReason.TargetNotRunning or SessionEndReason.TargetAmbiguous
or SessionEndReason.TargetCannotBePinned => _exitTargetNotResolved,
or SessionEndReason.TargetCannotBePinned or SessionEndReason.LaunchCannotStart => _exitTargetNotResolved,
SessionEndReason.AttachRefused => _exitAttachRefused,
SessionEndReason.SafetyUnhook or SessionEndReason.SupervisionLost
or SessionEndReason.SupervisionFaulted => _exitStoppedForSafety,
or SessionEndReason.SupervisionFaulted or SessionEndReason.WriterStoppedBlocklisted => _exitStoppedForSafety,
_ => _exitRefused,
};
}
private static void Report(CaptureResult result)
private static void Report(CaptureResult result, ExecutableMarkers markers)
{
IReadOnlyList<FlFrameRecord> dominant = StreamSegmenter.DominantStream(result.Records);
IReadOnlyList<Segment> segments = StreamSegmenter.Segment(result.Records);
@@ -183,12 +225,16 @@ internal static class Program
// and refuses outright when the span holds more than one stream.
FgWindow fg = FgWindow.From(result.Records, Stopwatch.Frequency);
MeasuredFacts facts = MeasuredFacts.From(
dominant, result.WriterState, Stopwatch.Frequency, result.TotalGaps, result.TotalDropped, fg);
dominant, result.WriterState, Stopwatch.Frequency, result.TotalGaps, result.TotalDropped, fg,
result.RuntimeModules, result.NgxDriver, markers);
HostConsole.Line($" guard ticks published: {result.GuardTicksPublished}");
HostConsole.Line($" records: {result.Records.Count} ({dominant.Count} on the dominant stream), " +
$"{segments.Count} segment(s), gaps {result.TotalGaps}, dropped {result.TotalDropped}");
HostConsole.Line(FocusNote(result));
// The longest raw intervals, placed against the moments this host touched the target: the
// owner saw a one-second drop to 1 FPS under capture and nothing here could say whose it was.
HostConsole.Line(StallReport.From(dominant, Stopwatch.Frequency, result.TouchQpc).Describe());
// WHICH HOOKS THE WRITER ACTUALLY INSTALLED, and it is not cosmetic.
//
@@ -201,14 +247,9 @@ internal static class Program
int withParams = dominant.Count(r => ((FlMeasured)r.MeasuredMask).HasFlag(FlMeasured.UpscalerParams));
HostConsole.Line($" hooks installed: {(FlHookFamily)result.WriterState.HooksInstalledMask}" +
$" apiMask=0x{result.WriterState.ApiMask:X} rtTier={result.WriterState.RtTier}");
// The census, raw and named, beside the hooks: a real-title run has to be able to say
// which module names the loader answered for, not just which qualifier was chosen.
var census = (FlRuntimeCensus)result.WriterState.RuntimeCensus;
HostConsole.Line($" runtime census: 0x{result.WriterState.RuntimeCensus:X} ran={census.HasFlag(FlRuntimeCensus.Ran)} " +
$"fg=[{CensusNames.Describe(census & FlRuntimeCensusFamilies.Fg)}] " +
$"upscaler=[{CensusNames.Describe(census & FlRuntimeCensusFamilies.Upscaler)}]");
PrintCensus(result, markers);
HostConsole.Line(WriterNote(result));
PrintWriterAndLoader(result);
HostConsole.Line($" records carrying Upscaler={withUpscaler}/{dominant.Count} " +
$"UpscalerParams={withParams}/{dominant.Count} " +
$"(a value below the total means the hook came up mid-session, not that it never did)");
@@ -232,6 +273,65 @@ internal static class Program
HostConsole.Line(SessionReport.Render(facts));
}
/// <summary>
/// The census, raw and named, beside the hooks — a real-title run has to be able to say which
/// module names the loader answered for, not just which qualifier was chosen — and then the same
/// modules with their FILE versions and paths, from outside the process: the census cannot tell
/// 2.7.1 from 2.8.0, and §H5 case 3 turns on exactly that. A path under the driver store rather
/// than the game directory is how a DLSS override shows up here.
/// </summary>
private static void PrintCensus(CaptureResult result, ExecutableMarkers markers)
{
var census = (FlRuntimeCensus)result.WriterState.RuntimeCensus;
HostConsole.Line($" runtime census: 0x{result.WriterState.RuntimeCensus:X} ran={census.HasFlag(FlRuntimeCensus.Ran)} " +
$"fg=[{CensusNames.Describe(census & FlRuntimeCensusFamilies.Fg)}] " +
$"upscaler=[{CensusNames.Describe(census & FlRuntimeCensusFamilies.Upscaler)}]");
PrintRuntimeModules(result.RuntimeModules);
// The driver's own word on this process, out of process: the super-resolution identity the
// hooks cannot see on NGX-direct titles (03_METRICS §Upscaling, the driver-reported rung).
HostConsole.Line(result.NgxDriver.Describe());
HostConsole.Line(markers.Describe());
// Which Streamline buffer types the title tagged, on which route: the identity half of
// frame generation (fl_shm.h §slTagCensus). A DLSS-G title tags hudless and UI every
// frame; a super-resolution-only title tags neither.
HostConsole.Line($" Streamline tag census: 0x{result.WriterState.SlTagCensus:X} " +
SlTagCensusNames.DescribeRoutes(result.WriterState.SlTagCensus));
// DXGI's own present counter against this hook's, on the hooked chain(s): the in-process
// answer to whether a pacer's generated presents are DXGI presents this hook misses (§H5).
HostConsole.Line(DxgiCounterNote(result.WriterState));
}
/// <summary>DXGI's counter against ours, and what a ratio means; never a count of anything by itself.</summary>
private static string DxgiCounterNote(FlWriterState writer)
{
if (writer.DxgiPresentSamples == 0)
{
return " DXGI present counter: not read (no hooked present sampled it)";
}
double per = writer.DxgiPresentsUnseen / (double)writer.DxgiPresentSamples;
string reading = writer.DxgiPresentsUnseen == 0
? "DXGI counted nothing this hook did not: frame generation was off, or whatever generates frames on this title presents below DXGI or on another object"
: per >= 0.5
? "DXGI counted presents this hook never saw on the SAME chain - a pacer presenting through a body the inline patches do not cover; the generated presents ARE DXGI presents here and Displayed above is DXGI-counted from them"
: "a few presents reached DXGI outside this hook - too few for a pacer, read the number rather than the ratio";
return $" DXGI present counter: unseen={writer.DxgiPresentsUnseen} over samples={writer.DxgiPresentSamples} " +
$"({per.ToString("0.00", CultureInfo.InvariantCulture)} unseen per hooked present) - {reading}";
}
/// <summary>One line per census-named module the target had loaded, version and path beside it.</summary>
private static void PrintRuntimeModules(RuntimeModuleSet modules)
{
HostConsole.Line($" runtime modules: {modules.Modules.Count} of {CensusNames.ModuleFileNames.Count} " +
$"census-named modules resolved over {modules.Snapshots} snapshot(s), " +
$"{modules.Unreadable} unreadable");
foreach (RuntimeModuleInfo m in modules.Modules.OrderBy(m => m.FileName, StringComparer.OrdinalIgnoreCase))
{
string version = m.Parsed?.ToString() ?? "(no version resource)";
HostConsole.Line($" module: {m.FileName} {version} {m.Path}");
}
}
/// <summary>Which vendor dispatches actually arrived, one census per vendor route.</summary>
/// <remarks>
/// The Streamline census is §S30's "print them first". The AMD census is the second count
@@ -245,7 +345,8 @@ internal static class Program
}
/// <summary>The loop and its four collaborators, wired the only way this host allows.</summary>
private static CaptureLoop BuildLoop(FileGameConsentStore store, int seconds)
private static CaptureLoop BuildLoop(FileGameConsentStore store, int seconds,
Func<string, string, (int Pid, ITargetLiveness Alive)?>? launcher = null)
{
var guard = new NativeAntiCheatGuard();
return new CaptureLoop(
@@ -272,7 +373,10 @@ internal static class Program
// --seconds is an operator taking a bounded measurement, and CaptureLoop
// already honoured MaxDuration -- nothing could set it.
MaxDuration = seconds > 0 ? TimeSpan.FromSeconds(seconds) : TimeSpan.Zero,
});
},
pid => RuntimeModuleSnapshot.Take(pid, CensusNames.ModuleFileNames),
NgxDriverProbe.Run,
launcher ?? ((exe, args) => ProcessLauncher.Start(exe, args)));
}
/// <summary>
@@ -325,6 +429,21 @@ internal static class Program
return " cause: the record is present, enabled and matching — so the refusal came from elsewhere";
}
/// <summary>The writer's own line, then the LoadLibrary detour's (installed / woke / EARLY STOP).</summary>
private static void PrintWriterAndLoader(CaptureResult result)
{
HostConsole.Line(WriterNote(result));
foreach (string line in EarlyStop.Describe(result.WriterState, EarlyStop.StagedRulesPath))
{
HostConsole.Line(line);
}
foreach (string line in LaunchNote.Describe(result.LaunchWait, result.WriterState))
{
HostConsole.Line(line);
}
}
/// <summary>
/// The two numbers that separate "nothing happened" from "something went wrong".
/// </summary>
+7
View File
@@ -9,6 +9,13 @@ internal enum Verb
ConsentRevoke,
Capture,
/// <summary>
/// Launch mode (P1 item 2): start the consented executable, hold it, and let the guard inject the
/// moment it has mapped a presentation runtime. The same consent record, the same gate, the same
/// payload; only WHEN the full scan runs differs.
/// </summary>
Launch,
/// <summary>
/// §M5's instrument: open LibreHardwareMonitor GPU-only, print the raw sensor tree
/// and the mapped sample for a few seconds, and name the pre-committed row it landed on.
@@ -170,4 +170,31 @@ public enum AntiCheatRefusalReason
/// watchlist resurrecting the game after <c>hook_enabled</c> was forced to 0.
/// </remarks>
PreviouslyBlocked = 23,
/// <summary>
/// Launch mode (P1 item 2): the guard was waiting for the launched target to map a presentation
/// runtime and the target exited first. Nothing was injected.
/// </summary>
/// <remarks>
/// A launcher that spawned the real game and quit is the ordinary cause (the descendant election is
/// the Agent's, P2); a crash is the other. <c>20_OPEN_QUESTIONS</c> §S1 / §S13(c).
/// </remarks>
LaunchTargetExited = 24,
/// <summary>
/// Launch mode: the budget ran out and the target had mapped no presentation runtime — a 2D title,
/// or a launcher still sitting on its window. Nothing was injected.
/// </summary>
LaunchNoPresentationRuntime = 25,
/// <summary>
/// Launch mode, the Vulkan branch (P1 item 3): the target mapped <c>vulkan-1.dll</c> and no D3D or OpenGL
/// runtime, the FULL guard passed, and nothing was injected on purpose — a Vulkan title is captured by the
/// implicit layer, and one process carries one ring (<c>fl_shm_host.h</c>).
/// </summary>
/// <remarks>
/// Not an allow — the Overlay is not in the target — and not a refusal either: the host reads it as
/// "attach to the layer's ring". <c>CaptureLoop</c> is the one place that distinction is made.
/// </remarks>
TargetIsVulkanLayered = 26,
}
@@ -64,6 +64,11 @@ public sealed class NativeAntiCheatGuard : IAntiCheatGuard
[DllImport(_guardDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void FlGuardedInject(uint targetPid, string dllPath, out FlGuardResult result);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_guardDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void FlGuardedInjectWhenReady(uint targetPid, string dllPath, uint timeoutMs,
out FlGuardResult result);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_guardDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void FlStaticPreScan(string gameDirectory, out FlGuardResult result);
@@ -128,6 +133,20 @@ public sealed class NativeAntiCheatGuard : IAntiCheatGuard
}, ct);
}
/// <inheritdoc />
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath, int timeoutMs,
CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(payloadPath);
ArgumentOutOfRangeException.ThrowIfNegative(timeoutMs);
return RunAsync(() =>
{
FlGuardedInjectWhenReady(checked((uint)targetPid), payloadPath, checked((uint)timeoutMs),
out FlGuardResult r);
return AntiCheatVerdict.FromNative(r.Reason, r.Family, r.Signal);
}, ct);
}
/// <inheritdoc />
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
CancellationToken ct = default)
@@ -0,0 +1,187 @@
using System.Text;
using System.Text.Json;
namespace FrameLedger.Infrastructure.Vulkan;
/// <summary>
/// What a launched process needs for the Vulkan implicit layer to observe it, and nothing else on the machine to:
/// the loader's <c>VK_ADD_IMPLICIT_LAYER_PATH</c> pointed at a directory holding our manifest, the manifest's
/// <c>enable_environment</c> variable set, and the process image name on the layer's enable-list.
/// </summary>
/// <remarks>
/// <para>
/// <b>No registry.</b> <c>12_BUILD</c> §The Vulkan layer is not registered at install time makes registration a
/// deliberate, later act of the Agent, kept only while a Vulkan game has hooking enabled. The unshipped host
/// does not need it at all: loader 1.4.357 honours <c>VK_ADD_IMPLICIT_LAYER_PATH</c> (measured 2026-09-06,
/// <c>spike-notes</c> §2), so the layer is discoverable ONLY by the process this host starts — a smaller blast
/// radius than an HKCU registration, and gone when the variable is. The Agent's registration path (P2) is
/// unchanged by this.
/// </para>
/// <para>
/// <b>The enable-list is written here because this host stands in for the Agent</b>, which
/// <c>17_HOOK_ENGINE</c> §The enable-list names as its sole writer. One line, the lowercased image name, added
/// only when absent and removed on dispose only when this object added it. An entry somebody else wrote is
/// left exactly as found.
/// </para>
/// <para>
/// <b>Without a staged layer DLL nothing is written and no variable is set</b>: a manifest pointing at a file
/// that is not there would make the loader log an error into the game for no benefit.
/// </para>
/// </remarks>
public sealed class VkLayerLaunchEnvironment : IDisposable
{
/// <summary>The manifest's <c>enable_environment</c> variable (<c>17_HOOK_ENGINE</c> §Vulkan).</summary>
public const string EnableVariable = "FRAMELEDGER_ENABLE_VK_LAYER";
/// <summary>The loader's additional implicit-layer search path, honoured without any registration.</summary>
public const string ImplicitLayerPathVariable = "VK_ADD_IMPLICIT_LAYER_PATH";
/// <summary>The layer's name, as the manifest and the loader log carry it.</summary>
public const string LayerName = "VK_LAYER_FRAMELEDGER_overlay";
private const string _manifestFileName = "VkLayer_FRAMELEDGER_overlay.json";
private static readonly JsonSerializerOptions _manifestOptions = new() { WriteIndented = true };
private readonly bool _addedEnableListEntry;
private readonly string? _writtenManifest;
private bool _disposed;
private VkLayerLaunchEnvironment(string directory, string imageName, string enableListPath, string? manifest,
bool addedEntry, IReadOnlyDictionary<string, string> variables)
{
Directory = directory;
ImageName = imageName;
EnableListPath = enableListPath;
_writtenManifest = manifest;
_addedEnableListEntry = addedEntry;
Variables = variables;
}
/// <summary>The product's per-user layer directory: <c>%LOCALAPPDATA%\FrameLedger\vklayer</c>.</summary>
public static string DefaultDirectory => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FrameLedger", "vklayer");
/// <summary>The directory the loader is pointed at, which also holds the enable-list.</summary>
public string Directory { get; }
/// <summary>The lowercased process image name written to the enable-list.</summary>
public string ImageName { get; }
/// <summary>The enable-list this object wrote to (or would have).</summary>
public string EnableListPath { get; }
/// <summary>The manifest written for this launch, or null when the layer DLL was not staged.</summary>
public string? ManifestPath => _writtenManifest;
/// <summary>Variables to add to the launched process's environment; empty when the layer is not staged.</summary>
public IReadOnlyDictionary<string, string> Variables { get; }
/// <summary>
/// Prepare the environment for launching <paramref name="exePath"/> with the layer at
/// <paramref name="layerDllPath"/>; <paramref name="directory"/> defaults to <see cref="DefaultDirectory"/>.
/// </summary>
public static VkLayerLaunchEnvironment Prepare(string exePath, string layerDllPath, string? directory = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(exePath);
ArgumentException.ThrowIfNullOrWhiteSpace(layerDllPath);
string dir = directory ?? DefaultDirectory;
#pragma warning disable CA1308 // the enable-list's format is LOWERCASED image names (17_HOOK_ENGINE §The enable-list)
string image = Path.GetFileName(exePath).ToLowerInvariant();
#pragma warning restore CA1308
string enableList = Path.Combine(dir, "enabled.txt");
if (!File.Exists(layerDllPath))
{
return new VkLayerLaunchEnvironment(dir, image, enableList, manifest: null, addedEntry: false,
new Dictionary<string, string>(StringComparer.Ordinal));
}
System.IO.Directory.CreateDirectory(dir);
bool added = AddEnableListEntry(enableList, image);
string manifest = Path.Combine(dir, _manifestFileName);
File.WriteAllText(manifest, ManifestJson(Path.GetFullPath(layerDllPath)), new UTF8Encoding(false));
var variables = new Dictionary<string, string>(StringComparer.Ordinal)
{
[EnableVariable] = "1",
[ImplicitLayerPathVariable] = dir,
};
return new VkLayerLaunchEnvironment(dir, image, enableList, manifest, added, variables);
}
/// <summary>The manifest, with the DLL's absolute path — the shape <c>VkLayer_FRAMELEDGER_overlay.json.in</c> generates.</summary>
internal static string ManifestJson(string libraryPath)
{
var doc = new
{
file_format_version = "1.2.0",
layer = new
{
name = LayerName,
type = "GLOBAL",
library_path = libraryPath,
api_version = "1.4.357",
implementation_version = "1",
description = "FrameLedger performance capture (opt-in per game; passthrough otherwise)",
enable_environment = new Dictionary<string, string>(StringComparer.Ordinal) { [EnableVariable] = "1" },
disable_environment = new Dictionary<string, string>(StringComparer.Ordinal) { ["DISABLE_FRAMELEDGER_VK_LAYER"] = "1" },
},
};
return JsonSerializer.Serialize(doc, _manifestOptions);
}
/// <summary>True when the entry was added; false when it was already there.</summary>
private static bool AddEnableListEntry(string enableList, string image)
{
List<string> lines = File.Exists(enableList) ? [.. File.ReadAllLines(enableList)] : [];
if (lines.Any(l => string.Equals(l.Trim(), image, StringComparison.OrdinalIgnoreCase)))
{
return false;
}
lines.Add(image);
File.WriteAllText(enableList, string.Join('\n', lines) + '\n', new UTF8Encoding(false));
return true;
}
/// <summary>Remove exactly what <see cref="Prepare"/> added.</summary>
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
try
{
if (_addedEnableListEntry && File.Exists(EnableListPath))
{
List<string> kept = [.. File.ReadAllLines(EnableListPath)
.Where(l => !string.Equals(l.Trim(), ImageName, StringComparison.OrdinalIgnoreCase))];
if (kept.Count == 0)
{
File.Delete(EnableListPath);
}
else
{
File.WriteAllText(EnableListPath, string.Join('\n', kept) + '\n', new UTF8Encoding(false));
}
}
if (_writtenManifest is not null && File.Exists(_writtenManifest))
{
File.Delete(_writtenManifest);
}
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{
// Leaving a line or a manifest behind grants nothing: the layer still gates on the enable
// variable, which only a launch sets. Stated rather than thrown from a Dispose.
}
}
}
+110 -5
View File
@@ -76,6 +76,13 @@ public enum FlStatus : uint
/// <summary>Three hook faults; see <c>17_HOOK_ENGINE</c> §Fault policy.</summary>
SelfDisabled = 2,
Unhooked = 3,
/// <summary>
/// A module matching the anti-cheat floor compiled into the Overlay loaded mid-session and the Overlay
/// stopped itself (<c>19_SAFETY</c> §During a session, the in-process half; §S6). Which family:
/// <see cref="FlWriterState.EarlyStopFamily"/>.
/// </summary>
StoppedBlocklisted = 4,
}
/// <summary>Bits in <see cref="FlWriterState.ApiMask"/>, and the value of <see cref="FlFrameRecord.Api"/>.</summary>
@@ -289,6 +296,51 @@ public enum FlRuntimeCensus : uint
AmdFfxDx12 = 1u << 18,
}
/// <summary>
/// Mirror of <c>FlSlTagType</c>: the Streamline buffer types the tag detours and the local inputs walk record, as
/// bits within one route's field of <see cref="FlWriterState.SlTagCensus"/>.
/// </summary>
/// <remarks>
/// <b>The identity half of frame generation, from an argument already hooked.</b> Streamline's DLSS-G programming
/// guide §5.0 requires a title running DLSS Frame Generation to tag the HUD-less colour and UI buffers every frame
/// through <c>slSetTag</c> / <c>slSetTagForFrame</c> / <c>slEvaluateFeature</c>'s inputs; a title running
/// super-resolution alone never tags them. So <see cref="DlssgInputs"/> tagged says the title is FEEDING frame
/// generation — identity, never a count: whether frames were generated stays the count's verdict.
/// </remarks>
[Flags]
public enum FlSlTagType : uint
{
None = 0,
Depth = 1u << 0,
MotionVectors = 1u << 1,
Hudless = 1u << 2,
ScalingInput = 1u << 3,
ScalingOutput = 1u << 4,
UiColorAlpha = 1u << 5,
UiAlpha = 1u << 6,
Backbuffer = 1u << 7,
Other = 1u << 8,
/// <summary>Mirror of <c>FL_SL_TAG_DLSSG_INPUTS</c>: the buffers only DLSS Frame Generation consumes.</summary>
DlssgInputs = Hudless | UiColorAlpha | UiAlpha,
}
/// <summary>Mirror of the <c>FL_SL_TAG_ROUTE_*</c> shifts and the per-route width.</summary>
public static class FlSlTagRoute
{
public const int TypeBits = 9;
public const uint TypeMask = (1u << TypeBits) - 1u;
public const int Global = 0;
public const int Frame = TypeBits;
public const int Local = 2 * TypeBits;
/// <summary>The <see cref="FlSlTagType"/> bits one route contributed to a census word.</summary>
public static FlSlTagType Of(uint census, int route) => (FlSlTagType)((census >> route) & TypeMask);
/// <summary>The union of every route's bits.</summary>
public static FlSlTagType Any(uint census) => Of(census, Global) | Of(census, Frame) | Of(census, Local);
}
/// <summary>The two groups of <see cref="FlRuntimeCensus"/>, mirroring <c>FL_CENSUS_FG_FAMILIES</c> and <c>FL_CENSUS_UPSCALER_FAMILIES</c>.</summary>
public static class FlRuntimeCensusFamilies
{
@@ -408,7 +460,14 @@ public enum FlMeasured : ushort
/// </summary>
FgCounts = 1 << 10,
// Bits 11-15 reserved. Writers leave them zero; readers IGNORE them rather than validating them as
/// <summary>
/// <c>dxgiUnseen</c> (2026-09-05, <c>20_OPEN_QUESTIONS</c> §H5 row P1-DXGI): the present hook read
/// <c>IDXGISwapChain::GetLastPresentCount</c> at this present and at the previous hooked present on the
/// same chain, so the byte is a measurement, a zero included. Clear on a chain's first hooked present.
/// </summary>
DxgiPresents = 1 << 11,
// Bits 12-15 reserved. Writers leave them zero; readers IGNORE them rather than validating them as
// zero. That does NOT make a future field bump-free — recordSize and layoutVersion are compared
// first, so an old reader refuses a new writer outright.
}
@@ -495,8 +554,44 @@ public unsafe struct FlWriterState
/// <summary><see cref="FlRuntimeCensus"/> bits. Watchdog-published, OR-only. Took <c>reserved[0]</c> on 2026-09-03.</summary>
public uint RuntimeCensus;
/// <summary>Must be zero; room for additive fields.</summary>
public fixed uint Reserved[5];
/// <summary>
/// <see cref="FlSlTagType"/> bits per route (<see cref="FlSlTagRoute"/>): which Streamline buffer types the
/// title tagged, on which of the three tag routes. Watchdog-published, OR-only. Took <c>reserved[0]</c> on
/// 2026-09-05 the way <see cref="RuntimeCensus"/> took it — additive, no layout bump.
/// </summary>
public uint SlTagCensus;
/// <summary>
/// Presents DXGI's own counter (<c>IDXGISwapChain::GetLastPresentCount</c>) recorded between two consecutive
/// hooked presents on the same chain, beyond the one the hook saw — presents that reached DXGI through a body
/// the inline patches do not cover. Watchdog-published. Took <c>reserved[0]</c> on 2026-09-05.
/// </summary>
public uint DxgiPresentsUnseen;
/// <summary>Hooked presents on which the DXGI counter was read. Took <c>reserved[1]</c> on 2026-09-05.</summary>
public uint DxgiPresentSamples;
/// <summary>
/// The <c>LoadLibrary</c> detour's word: bit 15 = installed; bits 0..14 = how many times a module the hook
/// inventory or the runtime census names was loaded and the watchdog woken for it.
/// </summary>
public ushort LoaderSignals;
/// <summary>
/// 0 = none; else the 1-based index, among the compiled floor's MODULE families in rules order, of the
/// family whose value matched a module loaded mid-session. Paired with <see cref="FlStatus.StoppedBlocklisted"/>.
/// </summary>
public ushort EarlyStopFamily;
/// <summary>
/// DXGI's count of presents the first hooked chain had completed before this hook saw one — how many
/// presents ran unhooked, launch mode's own cost meter. <see cref="DxgiPresentsBeforeHookNotRead"/> (all
/// bits set) means the hook never saw a present.
/// </summary>
public uint DxgiPresentsBeforeHook;
/// <summary>The value <see cref="DxgiPresentsBeforeHook"/> carries until the first hooked present.</summary>
public const uint DxgiPresentsBeforeHookNotRead = 0xFFFFFFFF;
// WHY THE COUNTERS ARE PUBLISHED AT 1 Hz AND NOT ACCUMULATED HERE PER FRAME: this struct is
// region 2, which the Overlay writes on the present path, and the regions are separate cache lines
@@ -536,7 +631,7 @@ public unsafe struct FlControlBlock
/// <summary>Region 4 — the ring. Exactly 64 bytes, no implicit padding.</summary>
[StructLayout(LayoutKind.Sequential, Size = 64)]
public struct FlFrameRecord
public unsafe struct FlFrameRecord
{
/// <summary>Present entry timestamp.</summary>
public ulong Qpc;
@@ -626,8 +721,18 @@ public struct FlFrameRecord
/// <summary>0 = unavailable.</summary>
public uint ReflexLatencyUs;
/// <summary>
/// Presents DXGI's own counter recorded on this record's chain since the previous hooked present, beyond
/// that one — the per-present form of <see cref="FlWriterState.DxgiPresentsUnseen"/>, under
/// <see cref="FlMeasured.DxgiPresents"/>. Measured 2.90 / 2.95 per hooked present on Dying Light: The
/// Beast (Streamline 2.8.0, DLSS FG ×4) and 0 on Streamline 2.7.3 and 2.10.3 titles, so on that shape
/// the generated presents ARE DXGI presents and the consumer counts <c>Displayed = hooked + this</c>,
/// labelled DXGI-COUNTED. Saturates at 255, which the consumer refuses as a sentinel.
/// </summary>
public byte DxgiUnseen;
/// <summary>Must be zero. Slack, so the next addition does not start from none.</summary>
public uint Reserved;
public fixed byte Reserved[3];
/// <summary>
/// Seqlock counter. Monotonic per slot and NEVER reset, so a full lap of the ring always changes it —
@@ -230,6 +230,17 @@ enum class ParseResult : std::uint8_t {
// with a signer check; a fragment alone never refuses (19_SAFETY: "name
// fragment AND not signed by a known vendor").
[[nodiscard]] bool HasSuspiciousFragment(const Rules& rules, const char* moduleName) noexcept;
// THE BOUND (owner decision 2026-09-06, §S19(b)). Once the signer half is wired,
// `trustedSigners` is a live allow-widening surface: a rules push that adds a
// publisher widens the hard gate, and `Rules / validate` is not a required check.
// So the data file may only INTERSECT a list compiled into this binary — the
// boundary of what the gate trusts is code, exactly as 19_SAFETY ruled for the
// launcher list. Widening it is a reviewed PR, never a data change.
[[nodiscard]] bool IsCompiledTrustedSigner(const char* signerOrganisation) noexcept;
// True only when BOTH the rules file and the compiled-in list name the
// organisation (full, case-insensitive equality on the certificate subject's O=).
[[nodiscard]] bool IsTrustedSigner(const Rules& rules, const char* signerOrganisation) noexcept;
// Local AppData, resolved from the SHELL rather than from the environment.
@@ -152,6 +152,31 @@ enum class Reason : std::uint8_t {
kConsentMissing,
kPreviouslyBlocked,
// LAUNCH MODE (P1 item 2; 20_OPEN_QUESTIONS §S1 / §S13(c)): the guard was asked
// to inject AS SOON AS the target had mapped a presentation runtime, and it
// never did. A CREATE_SUSPENDED target has loaded nothing and
// EnumProcessModulesEx fails against it with ERROR_PARTIAL_COPY (§S1, measured),
// so launch mode cannot be create -> guard -> inject -> resume. It is create ->
// resume -> POLL until dxgi+d3d11/d3d12, opengl32 or vulkan-1 is mapped -> the
// full guard -> inject. These two are the poll's own ends: the process exited
// first (a launcher that spawned the real game and quit -- the Agent's election,
// P2 -- or a crash), or the budget ran out with no runtime mapped (a 2D title, or
// a launcher still sitting on its window). Nothing was injected in either case.
kLaunchTargetExited,
kLaunchNoPresentationRuntime,
// LAUNCH MODE, the Vulkan branch (P1 item 3). The launched target mapped
// vulkan-1.dll (with or without a D3D runtime beside it -- an NVIDIA Vulkan
// ICD maps dxgi + d3d12 itself, measured), the full guard PASSED, and
// nothing was injected on purpose: a Vulkan title is captured by the implicit
// layer the loader mapped into it (17_HOOK_ENGINE §Vulkan), and one process
// carries ONE ring -- an Overlay injected beside the layer would find the
// mapping already there and stay inert, or win the race and leave the layer
// inert with nothing to hook (fl_shm_host.h). Allowed() is false because the
// DLL is NOT loaded in the target; the host reads this as "attach to the
// layer's ring", not as a refusal.
kTargetIsVulkanLayered,
// NOT A REASON. The count, so appending above it updates the exported
// FlGuardReasonCount by construction.
//
@@ -307,6 +332,34 @@ struct Sources {
// caller has to be able to distinguish them.
Collected (*ModuleIsOurOwn)(const wchar_t* modulePath, bool* isOurs) = nullptr;
// §S19(b) — WHO SIGNED this module, from its EMBEDDED Authenticode signature,
// verified OFFLINE (row G1, read 2026-09-06 after the CI leg and the owner's
// adapters-disabled leg both left every verdict unchanged).
//
// kOk writes the signing certificate's subject `O=` into `out` — the field
// 19_SAFETY §Blocklist seed names, measured on drivers, launchers and a NuGet
// assembly whose CN changed between copies while its O= did not. The guard
// then pairs it with the fragment tier: a fragment-matching module signed by
// an organisation on the TRUSTED list keeps the scan looking; anything else
// latches SuspiciousUnsigned, which is now literally what it says.
//
// kFailed is every other outcome and MEANS NOT TRUSTED: no embedded signature
// (the catalog-signed system binaries — mskeyprotect.dll — land here by
// design, the CryptCATAdmin* half being deferred with its own rationale), an
// invalid one, a certificate whose O= could not be read, a buffer too small,
// a null path. The polarity is ModuleIsOurOwn's: a seam that fails must never
// widen what is allowed.
//
// OFFLINE BY FLAG, measured rather than assumed: WTD_REVOKE_NONE and
// WTD_CACHE_ONLY_URL_RETRIEVAL, under which the probe's verdicts did not
// change with every adapter disabled. cryptnet.dll still maps; no request is
// made. NFR-10 and CLAUDE.md rule 8 are what that measurement protects.
//
// Reached only on a fragment hit, which on a measured machine is approximately
// never — ~2-4 ms per verified module, inside a 30 s loop, on a scan set that
// three real titles left empty.
Collected (*ModuleSignerOrganisation)(const wchar_t* modulePath, char* out, std::size_t cap) = nullptr;
// §S22 — is the DLL we were asked to inject one of OUR OWN binaries?
//
// The guard gated the target and nothing gated the payload. Every check
@@ -380,6 +433,18 @@ struct Sources {
// a way into a game process that never consulted a single genuine signal.
[[nodiscard]] Verdict GuardedInject(std::uint32_t targetPid, const wchar_t* dllPath) noexcept;
// LAUNCH MODE. Poll `targetPid` -- every 50 ms, up to `timeoutMs` -- until it has
// mapped a presentation runtime (dxgi.dll with d3d11.dll or d3d12.dll, or
// opengl32.dll, or vulkan-1.dll: the earliest externally observable moment at which
// a swapchain can exist), then run GuardedInject in full. The poll reads module
// names through the same seam the module scan uses and matches NOTHING against the
// blocklist: it decides WHEN the guard runs, never WHETHER it passes. A target that
// exits first, or never maps a runtime inside the budget, is refused with
// kLaunchTargetExited / kLaunchNoPresentationRuntime and nothing is injected.
// 04_CAPTURE §Launch mode; 20_OPEN_QUESTIONS §S1 / §S13(c).
[[nodiscard]] Verdict GuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath,
std::uint32_t timeoutMs) noexcept;
// Evaluate the guard WITHOUT injecting. Exists for the 30 s in-session re-scan
// (19_SAFETY §During a session), which must reach a verdict on a process it is
// already inside and has nothing to inject. Deliberately cannot be used to
@@ -402,6 +467,8 @@ struct Sources {
[[nodiscard]] Verdict EvaluateWithSources(std::uint32_t targetPid, const Sources& sources) noexcept;
[[nodiscard]] Verdict GuardedInjectWithSources(std::uint32_t targetPid, const wchar_t* dllPath,
const Sources& sources) noexcept;
[[nodiscard]] Verdict GuardedInjectWhenReadyWithSources(std::uint32_t targetPid, const wchar_t* dllPath,
std::uint32_t timeoutMs, const Sources& sources) noexcept;
#endif
// Human-readable reason, for logs and for mapping to resx keys.
@@ -55,6 +55,17 @@ FL_GUARD_ABI void FlGuardEvaluate(std::uint32_t targetPid, FlGuardResult* out);
// in evidence — the guard collects its own.
FL_GUARD_ABI void FlGuardedInject(std::uint32_t targetPid, const wchar_t* dllPath, FlGuardResult* out);
// LAUNCH MODE (P1 item 2). Wait -- polling every 50 ms, up to `timeoutMs` -- until
// `targetPid` has mapped a presentation runtime, then run every check and inject
// exactly as FlGuardedInject does. The wait decides WHEN the guard runs and
// nothing about whether it passes: the poll matches no blocklist and the full scan
// runs once the runtime is there. A target that exits first, or never maps a
// runtime inside the budget, answers LaunchTargetExited / LaunchNoPresentationRuntime
// with nothing injected. The caller launches and holds the process; this never
// creates or terminates one (04_CAPTURE §Launch mode, 20_OPEN_QUESTIONS §S1).
FL_GUARD_ABI void FlGuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
FlGuardResult* out);
// Check 4 against a directory, before anything is launched (FR-2.2). ADVISORY:
// it answers "may this game's hooking toggle be offered at all", and gates
// nothing. The same scan runs inside FlGuardEvaluate and FlGuardedInject
@@ -636,6 +636,26 @@ bool HasSuspiciousFragment(const Rules& rules, const char* moduleName) noexcept
return false;
}
// The five organisations the shipped rules name, measured on this machine's
// binaries (spike-notes §1: WHQL re-signing leaves O= intact, so both GPU vendors'
// drivers read as Microsoft; their own launchers read as themselves). Adding one is
// a code change with a review, which is the whole point of the list being here.
constexpr const char* kCompiledTrustedSigners[] = {
"Microsoft Corporation", "NVIDIA Corporation", "Valve Corp.", "Intel Corporation", "Advanced Micro Devices, Inc.",
};
bool IsCompiledTrustedSigner(const char* signerOrganisation) noexcept {
if (signerOrganisation == nullptr || signerOrganisation[0] == '\0') {
return false;
}
for (const char* s : kCompiledTrustedSigners) {
if (IEquals(signerOrganisation, s)) {
return true;
}
}
return false;
}
bool IsTrustedSigner(const Rules& rules, const char* signerOrganisation) noexcept {
// A signature that is absent, invalid, or simply could not be checked is
// NOT trusted. The caller passes nullptr for all three, and they all land
@@ -643,6 +663,11 @@ bool IsTrustedSigner(const Rules& rules, const char* signerOrganisation) noexcep
if (signerOrganisation == nullptr || signerOrganisation[0] == '\0') {
return false;
}
// The bound first: an organisation the binary does not know cannot be made
// trusted by the data file, whatever the file says.
if (!IsCompiledTrustedSigner(signerOrganisation)) {
return false;
}
for (std::size_t i = 0; i < rules.trustedSignerCount; ++i) {
// Full comparison, never a prefix or substring: a substring signer rule
// is a forgery surface, because "NVIDIA Corporation Ltd" would match
@@ -247,6 +247,33 @@ bool ModuleIsExempt(const MatchState& st, const wchar_t* modulePath) noexcept {
return st.sources->ModuleIsOurOwn(modulePath, &ours) == Collected::kOk && ours;
}
// §S19(b) — is this fragment-matching module signed by a TRUSTED organisation?
//
// The other half of 19_SAFETY's heuristic ("name fragment AND not signed by a
// known vendor"), wired 2026-09-06 on row G1. Every clause fails towards refusing:
//
// - a null seam does not suppress (Sources members default to nullptr);
// - a module whose path we could not obtain cannot be verified;
// - anything but kOk from the seam is "could not tell", which is untrusted;
// - the organisation must be on BOTH the rules list and the compiled-in bound
// (IsTrustedSigner) — full equality, never a substring.
//
// Unlike ModuleIsExempt this applies to the TARGET too: a game that loads a
// Microsoft-signed key-protection provider is exactly the false refusal the
// signer half exists to remove. Reached only after the fragment matched, so the
// ~2-4 ms verification is not on the ordinary path.
bool ModuleIsTrustedSigned(const MatchState& st, const wchar_t* modulePath) noexcept {
if (st.sources == nullptr || st.sources->ModuleSignerOrganisation == nullptr || modulePath == nullptr ||
st.rules == nullptr) {
return false;
}
char org[kMaxValueLen] = {};
if (st.sources->ModuleSignerOrganisation(modulePath, org, sizeof(org)) != Collected::kOk) {
return false;
}
return IsTrustedSigner(*st.rules, org);
}
// Check 1's sink. The ordering here is the whole of §S22(b).
bool ModuleSinkFn(void* ctx, const char* name, const wchar_t* modulePath) noexcept {
auto* st = static_cast<MatchState*>(ctx);
@@ -274,6 +301,13 @@ bool ModuleSinkFn(void* ctx, const char* name, const wchar_t* modulePath) noexce
if (ModuleIsExempt(*st, modulePath)) {
return true;
}
// TRUSTED SIGNER: the same KEEP LOOKING, for the same reason. A trusted module
// must never STOP the scan, or a genuinely suspicious module loaded after it
// is never recorded — the load-order fail-open the paragraph above describes,
// reachable through this clause exactly as through the exemption.
if (ModuleIsTrustedSigned(*st, modulePath)) {
return true;
}
st->sawSuspicious = true;
strncpy_s(st->suspicious, name, _TRUNCATE);
// Still not a stop: an EXACT blocklist hit later in the same process outranks
@@ -484,6 +518,12 @@ const char* ReasonName(Reason r) noexcept {
return "RulesMalformed";
case Reason::kRulesIncomplete:
return "RulesIncomplete";
case Reason::kLaunchTargetExited:
return "LaunchTargetExited";
case Reason::kLaunchNoPresentationRuntime:
return "LaunchNoPresentationRuntime";
case Reason::kTargetIsVulkanLayered:
return "TargetIsVulkanLayered";
case Reason::kCount:
break; // not a reason; falls through to the guard below
}
@@ -655,12 +695,120 @@ Verdict GuardedInjectImpl(std::uint32_t targetPid, const wchar_t* dllPath, const
return v;
}
// ---------------------------------------------------------------------------
// Launch mode (P1 item 2) -- WHEN the guard runs, never WHETHER it passes.
// ---------------------------------------------------------------------------
// The poll's one question: has the target mapped a presentation runtime yet? Read
// through Sources::EnumerateModules -- the module scan's own seam -- so a test can
// drive it and so the answer comes from the loader rather than from a guess about
// the title. The sink looks for five system names and MATCHES NOTHING AGAINST THE
// BLOCKLIST; the verdict is GuardedInjectImpl's, run in full once the answer is
// yes. An enumeration that fails is "not yet" here rather than a refusal, because
// ERROR_PARTIAL_COPY is exactly what a target still inside its loader returns
// (§S1), and the refusal, if one is due, is the full scan's to make.
struct RuntimeProbe {
bool dxgi = false;
bool d3d = false;
bool gl = false;
bool vk = false;
};
bool RuntimeSinkFn(void* ctx, const char* name, const wchar_t*) noexcept {
auto* p = static_cast<RuntimeProbe*>(ctx);
if (p == nullptr || name == nullptr) {
return false;
}
if (_stricmp(name, "dxgi.dll") == 0) {
p->dxgi = true;
} else if (_stricmp(name, "d3d11.dll") == 0 || _stricmp(name, "d3d12.dll") == 0) {
p->d3d = true;
} else if (_stricmp(name, "opengl32.dll") == 0) {
p->gl = true;
} else if (_stricmp(name, "vulkan-1.dll") == 0) {
p->vk = true;
}
return true;
}
// What the target presents through, as far as the loader can say. kVulkan is the
// branch the guard must NOT inject (Reason::kTargetIsVulkanLayered), and IT WINS
// over a D3D runtime mapped beside it. Measured 2026-09-06 on the harness's
// Vulkan mode under an NVIDIA driver: the Vulkan ICD itself maps dxgi.dll and
// d3d12.dll and presents the Vulkan swapchain through a DXGI chain, so "vulkan-1
// beside d3d12" is what EVERY Vulkan title looks like there -- treating it as D3D
// injected the Overlay, which owned the ring, and left the layer forwarding into
// nothing. A process does not map vulkan-1.dll unless it uses Vulkan; a D3D title
// that happens to is the rarer shape and the one this rule gets wrong.
enum class PresentationRuntime : std::uint8_t { kNone, kD3dOrOpenGl, kVulkan };
PresentationRuntime FindPresentationRuntime(const Sources& s, std::uint32_t pid) noexcept {
if (s.EnumerateModules == nullptr) {
return PresentationRuntime::kNone;
}
RuntimeProbe p;
if (s.EnumerateModules(pid, &RuntimeSinkFn, &p) == Collected::kFailed) {
return PresentationRuntime::kNone; // still in its loader, or unreadable -- the full scan refuses the latter
}
if (p.vk) {
return PresentationRuntime::kVulkan;
}
return ((p.dxgi && p.d3d) || p.gl) ? PresentationRuntime::kD3dOrOpenGl : PresentationRuntime::kNone;
}
Verdict GuardedInjectWhenReadyImpl(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
const Sources& sources) noexcept {
// SYNCHRONIZE only: this handle exists to notice an exit and for nothing else.
HANDLE proc = OpenProcess(SYNCHRONIZE, FALSE, targetPid);
if (proc == nullptr) {
return Refuse(Reason::kProcessUnreadable, nullptr, "could not open the launched target to wait on it");
}
constexpr DWORD kPollMs = 50;
const ULONGLONG start = GetTickCount64();
Verdict v; // fail-closed default, like every Verdict
for (;;) {
if (WaitForSingleObject(proc, 0) == WAIT_OBJECT_0) {
v = Refuse(Reason::kLaunchTargetExited, nullptr,
"the target exited before it mapped a presentation runtime; nothing was injected");
break;
}
const PresentationRuntime runtime = FindPresentationRuntime(sources, targetPid);
if (runtime == PresentationRuntime::kD3dOrOpenGl) {
v = GuardedInjectImpl(targetPid, dllPath, sources);
break;
}
if (runtime == PresentationRuntime::kVulkan) {
// The FULL guard still runs -- a Vulkan title with anti-cheat is refused
// by name exactly as a D3D one is -- and on a pass nothing is injected.
v = EvaluateImpl(targetPid, sources);
if (v.Allowed()) {
v = Refuse(Reason::kTargetIsVulkanLayered, nullptr,
"the guard passed; the target presents through Vulkan, where the implicit layer is the "
"capture side, so nothing was injected");
}
break;
}
if (GetTickCount64() - start >= timeoutMs) {
v = Refuse(Reason::kLaunchNoPresentationRuntime, nullptr,
"no presentation runtime was mapped within the launch budget; nothing was injected");
break;
}
Sleep(kPollMs);
}
CloseHandle(proc);
return v;
}
} // namespace
Verdict Evaluate(std::uint32_t targetPid) noexcept {
return EvaluateImpl(targetPid, SystemSources());
}
Verdict GuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs) noexcept {
return GuardedInjectWhenReadyImpl(targetPid, dllPath, timeoutMs, SystemSources());
}
Verdict GuardedInject(std::uint32_t targetPid, const wchar_t* dllPath) noexcept {
return GuardedInjectImpl(targetPid, dllPath, SystemSources());
}
@@ -673,6 +821,11 @@ Verdict EvaluateWithSources(std::uint32_t targetPid, const Sources& sources) noe
Verdict GuardedInjectWithSources(std::uint32_t targetPid, const wchar_t* dllPath, const Sources& sources) noexcept {
return GuardedInjectImpl(targetPid, dllPath, sources);
}
Verdict GuardedInjectWhenReadyWithSources(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
const Sources& sources) noexcept {
return GuardedInjectWhenReadyImpl(targetPid, dllPath, timeoutMs, sources);
}
#endif
} // namespace fl::guard
@@ -40,6 +40,14 @@ void FlGuardedInject(std::uint32_t targetPid, const wchar_t* dllPath, FlGuardRes
Fill(out, fl::guard::GuardedInject(targetPid, dllPath));
}
void FlGuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
FlGuardResult* out) {
if (!Usable(out)) {
return;
}
Fill(out, fl::guard::GuardedInjectWhenReady(targetPid, dllPath, timeoutMs));
}
void FlStaticPreScan(const wchar_t* gameDirectory, FlGuardResult* out) {
if (!Usable(out)) {
return;
@@ -25,7 +25,17 @@
#include <tlhelp32.h>
#include <winsvc.h>
// clang-format off
// ORDER IS LOAD-BEARING (fl-probe-signer found it): <mscat.h> is not needed here,
// but <wintrust.h> and <softpub.h> still want <wincrypt.h>'s types first.
#include <wincrypt.h>
#include <wintrust.h>
#include <softpub.h>
// clang-format on
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "wintrust.lib")
#pragma comment(lib, "crypt32.lib")
namespace fl::guard {
namespace {
@@ -670,6 +680,99 @@ Collected FileIsOurOwnImpl(const wchar_t* dllPath, bool* isOurs) noexcept {
return Collected::kOk;
}
// §S19(b) — the EMBEDDED signer half, offline. The shape fl-probe-signer measured,
// with the probe's std::string and std::vector replaced by fixed buffers: the guard
// allocates nothing.
//
// Two calls, and the order is the contract: WinVerifyTrust decides whether the
// signature is VALID (chain, digest, policy) and only then is the certificate read
// for its O=. Reading the subject first would report an organisation off a
// signature nobody verified — a forged O= is exactly one CryptQueryObject away.
LONG VerifyEmbeddedOffline(const wchar_t* path) noexcept {
WINTRUST_FILE_INFO fi{};
fi.cbStruct = sizeof(fi);
fi.pcwszFilePath = path;
WINTRUST_DATA wd{};
wd.cbStruct = sizeof(wd);
wd.dwUIChoice = WTD_UI_NONE;
wd.fdwRevocationChecks = WTD_REVOKE_NONE;
wd.dwUnionChoice = WTD_CHOICE_FILE;
wd.pFile = &fi;
wd.dwStateAction = WTD_STATEACTION_VERIFY;
wd.dwProvFlags = WTD_SAFER_FLAG | WTD_CACHE_ONLY_URL_RETRIEVAL;
GUID action = WINTRUST_ACTION_GENERIC_VERIFY_V2;
const LONG r = WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE), &action, &wd);
wd.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE), &action, &wd);
return r;
}
// The signing certificate's subject O=, into a caller buffer. False on anything
// short of a readable, non-empty, ASCII-representable organisation.
bool ReadSignerOrganisation(const wchar_t* path, char* out, std::size_t cap) noexcept {
HCERTSTORE store = nullptr;
HCRYPTMSG msg = nullptr;
DWORD enc = 0;
DWORD ctype = 0;
DWORD fmt = 0;
if (!CryptQueryObject(CERT_QUERY_OBJECT_FILE, path, CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
CERT_QUERY_FORMAT_FLAG_BINARY, 0, &enc, &ctype, &fmt, &store, &msg, nullptr)) {
return false;
}
bool ok = false;
DWORD need = 0;
// Fixed, generous, and refused when exceeded: a signer info larger than this is
// not a shape any vendor certificate produces, and "could not read" is untrusted.
alignas(16) unsigned char buf[16384];
if (CryptMsgGetParam(msg, CMSG_SIGNER_INFO_PARAM, 0, nullptr, &need) && need > 0 && need <= sizeof(buf) &&
CryptMsgGetParam(msg, CMSG_SIGNER_INFO_PARAM, 0, buf, &need)) {
auto* si = reinterpret_cast<CMSG_SIGNER_INFO*>(buf);
CERT_INFO ci{};
ci.Issuer = si->Issuer;
ci.SerialNumber = si->SerialNumber;
PCCERT_CONTEXT cert = CertFindCertificateInStore(store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0,
CERT_FIND_SUBJECT_CERT, &ci, nullptr);
if (cert != nullptr) {
wchar_t org[512]{};
const DWORD n = CertGetNameStringW(cert, CERT_NAME_ATTR_TYPE, 0, const_cast<char*>(szOID_ORGANIZATION_NAME),
org, static_cast<DWORD>(sizeof(org) / sizeof(org[0])));
if (n > 1) {
// The rules compare ASCII (IEquals); a signer whose O= does not
// survive the narrowing is not one the list can name, so it fails.
const int written = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, org, -1, out,
static_cast<int>(cap), nullptr, nullptr);
ok = written > 1;
if (!ok && cap > 0) {
out[0] = '\0';
}
}
CertFreeCertificateContext(cert);
}
}
if (msg != nullptr) {
CryptMsgClose(msg);
}
if (store != nullptr) {
CertCloseStore(store, 0);
}
return ok;
}
Collected ModuleSignerOrganisationImpl(const wchar_t* modulePath, char* out, std::size_t cap) noexcept {
if (modulePath == nullptr || out == nullptr || cap == 0) {
return Collected::kFailed;
}
out[0] = '\0';
if (VerifyEmbeddedOffline(modulePath) != ERROR_SUCCESS) {
return Collected::kFailed;
}
return ReadSignerOrganisation(modulePath, out, cap) ? Collected::kOk : Collected::kFailed;
}
} // namespace
Sources SystemSources() noexcept {
@@ -685,6 +788,9 @@ Sources SystemSources() noexcept {
// Both identity seams, one implementation — see fl_guard.h §TWO SEAMS.
s.ModuleIsOurOwn = &FileIsOurOwnImpl;
s.PayloadIsOurOwn = &FileIsOurOwnImpl;
// §S19(b), the embedded half only. The catalog half is a deferral with a
// written rationale, not a gap nobody noticed.
s.ModuleSignerOrganisation = &ModuleSignerOrganisationImpl;
return s;
}
@@ -25,8 +25,15 @@ add_library(FrameLedger.Overlay SHARED src/dllmain.cpp)
# and third_party/fidelityfx/README.md: an Overlay that imports a vendor module
# fails to load in every game that ships no such module, in the loader, silently.
# hookinventory-check Pass C reads the built DLL's import AND export tables.
# fl_ac_floor: the anti-cheat MODULE families compiled into the guard, now also into
# the Overlay for the LoadLibrary detour's early stop (§S6). Types only from
# fl_ac_rules.h -- nothing of fl_ac_rules.cpp is compiled here, and the Overlay
# links neither wintrust nor the rules parser.
target_include_directories(FrameLedger.Overlay PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../FrameLedger.Injector/include")
add_dependencies(FrameLedger.Overlay fl_ac_floor_gen)
target_link_libraries(FrameLedger.Overlay PRIVATE fl_ac_floor)
target_link_libraries(FrameLedger.Overlay PRIVATE FrameLedger.Shm fl_dxgi_vtable fl_native_flags fl_hostile_env_flags minhook
fl_streamline_headers fl_fidelityfx_headers
fl_streamline_headers fl_fidelityfx_headers fl_fsr3_host_headers
Advapi32 d3d11 d3d12 dxgi)
set_target_properties(FrameLedger.Overlay PROPERTIES OUTPUT_NAME "FrameLedger.Overlay")
@@ -202,6 +202,38 @@ static_assert(kFamilyFfxDispatch != kFamilyEvaluateFeature &&
"InstallByFamily binds a row by EQUALITY on this value -- a collision would hand a Streamline detour "
"body to an AMD export, which is the neighbour's-body defect the installer exists to stop");
// --- AMD FidelityFX, the FSR 3.0 HOST API (2026-09-05, the route HANDOFF 7c deferred) ---
//
// Cyberpunk 2077 at FSR 3 upscales through ffx_fsr3_x64.dll's NAMED exports -- the
// SDK 1.0.x host API, tag fsr3-v3.0.4 -- while its frame generation goes through the
// 1.1.x monolith's ffxDispatch above. Measured 2026-09-04: `FsrFg` printed, `upscaler:
// N/A`. One row, ffxFsr3ContextDispatchUpscale, whose descriptor carries renderSize
// at an offset the vendored header vouches for; identity is FSR3 as a fact (the 3.0
// host hosts nothing else) and the UPSCALE count feeds the SAME drain word the
// ffx-api rows feed.
//
// THE SAME FAMILY VALUE AS THE ffx-api ROWS, ON PURPOSE. The row's UPSCALE goes into
// g_ffxSeen's count, which RecordPresent drains into fgEvaluations when Streamline has
// never issued a token and no PREPARE ever arrived -- so a row claiming IDENTITY|PARAMS
// alone would feed a field its family does not entitle, and every record on a
// host-only title would be an honesty violation. The installer's ffx arm binds on the
// family and then keys on the MODULE (FfxLeafOf for the four ffxDispatch modules, this
// name for the host), exactly as the params arm keys on the symbol -- so the equality
// collision the asserts above forbid between DIFFERENT detour bodies is not one here:
// one family, one publish point (PublishFfxFamilyIfWhole), one live latch.
//
// ffxFsr3DispatchFrameGeneration IS NOT A ROW. On the one title that ships the host
// DLLs, frame generation is dispatched through the monolith's ffxDispatch (4261
// FRAMEGENERATION batches, 2026-09-04) and the count comes from Streamline tokens; the
// host's FG export fires per GENERATED batch, so it is not a count producer either.
// It becomes a row only if a title appears generating through the host DLL with no
// monolith in the census -- `Active (technology not identified)` beside
// FL_CENSUS_FFX_FSR3. Pre-committed in 20_OPEN_QUESTIONS §H11.
inline constexpr uint32_t kFamilyFsr3Host = kFamilyFfxDispatch;
static_assert(kFamilyFsr3Host == kFamilyFfxDispatch,
"one family, one publish point, one live latch: the host row shares the ffx-api rows' drain word and "
"must share their claims, or fgEvaluations would be fed by a row that does not claim FG_EVALUATIONS");
// The leaves, in the order dllmain's per-leaf trampoline and latch arrays are indexed.
enum FfxLeaf : uint32_t {
kFfxLeafMonolith = 0, // amd_fidelityfx_dx12.dll -- SDK 1.1.x, FSR 3.1 only
@@ -279,14 +311,60 @@ inline int FfxLeafOf(const wchar_t* module) noexcept {
// because Pass A's parser reads literals; the static_asserts under the table bind
// these spellings to kFfxLeafModules in both directions, so neither list can gain or
// lose a module alone.
// TWO ROWS, ONE FAMILY, TWO DETOURS -- the params family has a second row since
// 2026-09-04. Streamline 2.8 (Dying Light: The Beast ships 2.8.0) deprecates slSetTag
// in favour of slSetTagForFrame, which takes the frame token first and the same tag
// list after; a 2.8 title that tags per frame never calls slSetTag, and the first
// title measured on 2.8 published DLSS identity on 4,575 of 4,575 batches with
// UpscalerParams on ZERO of them. The two rows share the family bit because they
// produce the same fields from the same ResourceTag list; the installer tells them
// apart by SYMBOL (kSymbolSlSetTagForFrame below), never by family, because their
// signatures differ and the neighbour's body would read a FrameToken as a viewport.
// And the family is published WHEN WHOLE -- once every one of these two symbols the
// loaded interposer exports is patched -- not on the first row: published on the
// first, it entitled records the second row was not yet producing (measured 38 of
// 41 on the frame-based fixture), which is the ffx leaves' defect from #110 again.
#define FL_HOOK_INVENTORY(X) \
X(L"sl.interposer.dll", "slEvaluateFeature", fl::inventory::kFamilyEvaluateFeature) \
X(L"sl.interposer.dll", "slSetTag", fl::FL_HOOK_UPSCALER_PARAMS) \
X(L"sl.interposer.dll", "slSetTagForFrame", fl::FL_HOOK_UPSCALER_PARAMS) \
X(L"sl.interposer.dll", "slGetNewFrameToken", fl::FL_HOOK_FG_EVALUATIONS) \
X(L"amd_fidelityfx_dx12.dll", "ffxDispatch", fl::inventory::kFamilyFfxDispatch) \
X(L"amd_fidelityfx_upscaler_dx12.dll", "ffxDispatch", fl::inventory::kFamilyFfxDispatch) \
X(L"amd_fidelityfx_framegeneration_dx12.dll", "ffxDispatch", fl::inventory::kFamilyFfxDispatch) \
X(L"amd_fidelityfx_loader_dx12.dll", "ffxDispatch", fl::inventory::kFamilyFfxDispatch)
X(L"amd_fidelityfx_loader_dx12.dll", "ffxDispatch", fl::inventory::kFamilyFfxDispatch) \
X(L"ffx_fsr3_x64.dll", "ffxFsr3ContextDispatchUpscale", fl::inventory::kFamilyFsr3Host)
// The FSR 3.0 host module and the one symbol dllmain's ffx arm keys on for it. Named
// constants HERE, for the reason kModuleSlInterposer gives below, and bound to the
// table so the row and the arm cannot drift apart.
inline constexpr const wchar_t* kModuleFfxFsr3Host = L"ffx_fsr3_x64.dll";
inline constexpr const char* kSymbolFfxFsr3DispatchUpscale = "ffxFsr3ContextDispatchUpscale";
// The module and the two symbols dllmain's params arm keys on: the frame-based
// symbol picks the detour, and all three name what "whole" means when the family is
// published. Named constants HERE, because Pass B forbids the symbol literals
// anywhere else in the Overlay -- and bound to the table below, so a row and the
// arm that installs it cannot drift apart.
inline constexpr const wchar_t* kModuleSlInterposer = L"sl.interposer.dll";
inline constexpr const char* kSymbolSlSetTag = "slSetTag";
inline constexpr const char* kSymbolSlSetTagForFrame = "slSetTagForFrame";
constexpr bool InventoryHasRow(const wchar_t* module, const char* symbol) noexcept {
#define FL_ROW_HAS(mod, sym, family) \
if (SameW(mod, module) && SameA(sym, symbol)) { \
return true; \
}
FL_HOOK_INVENTORY(FL_ROW_HAS)
#undef FL_ROW_HAS
return false;
}
static_assert(InventoryHasRow(kModuleSlInterposer, kSymbolSlSetTag),
"the params arm keys on slSetTag by this constant, and the table no longer has that row");
static_assert(InventoryHasRow(kModuleSlInterposer, kSymbolSlSetTagForFrame),
"the params arm keys on slSetTagForFrame by this constant, and the table no longer has that row");
static_assert(InventoryHasRow(kModuleFfxFsr3Host, kSymbolFfxFsr3DispatchUpscale),
"the ffx arm keys on the FSR 3.0 host row by these constants, and the table no longer has that row");
// THE LEAF TABLE AND THE ROWS ARE BOUND TO EACH OTHER AT COMPILE TIME, BOTH WAYS.
// A leaf without a row would be a trampoline slot nothing installs into; a row
@@ -336,6 +414,13 @@ static_assert(AnyRowNames(kFfxLoaderModule),
"amd_fidelityfx_loader_dx12.dll is the game's entry on a loader-shipping title (Dying Light: The "
"Beast, KCD2, Wukong measured 2026-09-04: zero dispatches at any leaf export while FSR ran), so "
"without a row those titles read N/A");
// The host is NOT a leaf: it has no ffxDispatch, its own detour body, its own latch.
// FfxLeafOf returning -1 for it is what routes the installer's ffx arm to the host
// branch, so a leaf-table entry for it would hand the host the ffxDispatch trampoline.
static_assert(FfxLeafOfExact(kModuleFfxFsr3Host) < 0,
"the FSR 3.0 host facade is not an ffxDispatch leaf; the installer keys it by module name");
static_assert(!FfxDispatchRowExistsFor(kModuleFfxFsr3Host),
"the host exports no ffxDispatch; a row claiming one would resolve nothing and install nothing");
// Does this module speak the Streamline 2 ABI the vendored headers describe?
//
@@ -405,6 +490,24 @@ inline bool SpeaksFfxApi(HMODULE h) noexcept {
GetProcAddress(h, "ffxQuery") != nullptr && GetProcAddress(h, "ffxDispatch") != nullptr;
}
// Does this module speak the FSR 3.0 HOST ABI the vendored fsr3-v3.0.4 headers describe?
//
// A NAME CHECK, like SpeaksFfxApi's, on four of the twelve ffxFsr3* names the shipped
// module exports (docs/vendor-exports.json): the create, the one export hooked, the
// frame-generation dispatch and SkipPresent -- the last two being the 3.0 host's own
// and exported by no ffx-api module, so a 1.1.x monolith of the wrong NAME cannot pass.
// Deliberately not a generation check: 3.0.3, 3.0.4 and 1.1.4 share the descriptor
// prefix through renderSize, which is the only field read, and dllmain pins that
// offset at compile time; a name a later generation ADDS is not evidence the field
// moved. Probe-only names, never resolved into a row, never called; this file because
// Pass B exempts exactly this file.
inline bool SpeaksFsr3Host(HMODULE h) noexcept {
return h != nullptr && GetProcAddress(h, "ffxFsr3ContextCreate") != nullptr &&
GetProcAddress(h, "ffxFsr3ContextDispatchUpscale") != nullptr &&
GetProcAddress(h, "ffxFsr3DispatchFrameGeneration") != nullptr &&
GetProcAddress(h, "ffxFsr3SkipPresent") != nullptr;
}
inline bool SpeaksExpectedAbi(const wchar_t* module, HMODULE h) noexcept {
if (module == nullptr) {
return false;
@@ -412,6 +515,9 @@ inline bool SpeaksExpectedAbi(const wchar_t* module, HMODULE h) noexcept {
if (_wcsicmp(module, L"sl.interposer.dll") == 0) {
return SpeaksStreamline2(h);
}
if (_wcsicmp(module, kModuleFfxFsr3Host) == 0) {
return SpeaksFsr3Host(h);
}
// THE AMD ARM, by leaf name, for the same reason the Streamline arm is by name:
// the loader also exports all five and is not a leaf, so a prefix test would
// approve a module the inventory deliberately does not hook.
@@ -23,6 +23,7 @@
#define FRAMELEDGER_FL_SL_INPUTS_H
#include <cstdint>
#include <fl_shm.h>
#include <sl.h>
// AFTER sl.h, deliberately: sl_dlss.h has NO includes of its own -- verified on
// the upstream file, its closure is empty -- and relies on sl.h having been
@@ -51,11 +52,43 @@ inline constexpr uint32_t kMaxInputs = 32;
// frozen game with our DLL in it.
inline constexpr uint32_t kMaxChain = 8;
// Which FlSlTagType bit a Streamline BufferType maps to. Every type maps to SOMETHING
// -- FL_SL_TAG_OTHER for the ones the census does not name -- so a tag list of any
// content leaves a mark, and "no bits" can only mean "no tags".
inline constexpr uint32_t TagTypeBit(sl::BufferType type) noexcept {
switch (type) {
case sl::kBufferTypeDepth:
return fl::FL_SL_TAG_DEPTH;
case sl::kBufferTypeMotionVectors:
return fl::FL_SL_TAG_MOTION_VECTORS;
case sl::kBufferTypeHUDLessColor:
return fl::FL_SL_TAG_HUDLESS;
case sl::kBufferTypeScalingInputColor:
return fl::FL_SL_TAG_SCALING_INPUT;
case sl::kBufferTypeScalingOutputColor:
return fl::FL_SL_TAG_SCALING_OUTPUT;
case sl::kBufferTypeUIColorAndAlpha:
return fl::FL_SL_TAG_UI_COLOR_ALPHA;
case sl::kBufferTypeUIAlpha:
return fl::FL_SL_TAG_UI_ALPHA;
case sl::kBufferTypeBackbuffer:
return fl::FL_SL_TAG_BACKBUFFER;
default:
return fl::FL_SL_TAG_OTHER;
}
}
static_assert(TagTypeBit(sl::kBufferTypeHUDLessColor) == fl::FL_SL_TAG_HUDLESS, "the DLSS-G input maps to its bit");
static_assert(TagTypeBit(static_cast<sl::BufferType>(9999)) == fl::FL_SL_TAG_OTHER, "an unknown type still marks");
struct ScanResult {
uint16_t renderW = 0;
uint16_t renderH = 0;
bool found = false;
// Every readable ResourceTag's type, as FlSlTagType bits -- the local route's
// contribution to FlWriterState::slTagCensus and to the per-present DLSS-G mark.
uint32_t tagTypes = 0;
// The vendor's own DLSSMode value, or 0xFF for "a hook ran and could not
// tell". NEVER 0: fl_shm.h has no in-band "not measured" for
// upscalerQuality, so 0 would publish DLSSMode::eMaxPerformance -- "DLSS
@@ -105,6 +138,41 @@ inline bool IsReadableResourceTag(const sl::BaseStructure* s) noexcept {
return IsReadable<sl::ResourceTag>(s);
}
// The size a scaling-input tag states, from EITHER of the two places the vendor
// struct can carry it. Shared by the local walk below and by the global-tag detours
// (slSetTag, slSetTagForFrame), so the three routes cannot disagree about what a
// tag says.
//
// 1. `extent` -- "the area of the tagged resource to use". Set by titles that
// render into a buffer larger than the render resolution (dynamic resolution
// on an output-sized target). Cyberpunk 2077 sets it: 1485x835.
// 2. `resource->width/height` when the extent is ZERO. sl_core_types.h documents a
// zero extent as "using the entire resource" and the Resource's own size as
// "MANDATORY only when using Vulkan" -- so on D3D12 it MAY be filled and may not
// be, and a filled one is the title's statement of the buffer's size, which for a
// whole-resource tag IS the render resolution. Both are fields of the argument
// the hooked API received (CLAUDE.md rule 4), nothing is dereferenced beyond the
// struct the title passed, and the Resource is GUID-checked the way every other
// Streamline structure is before a field is read.
//
// A tag with neither is the honest unknown fl_shm.h already defines for renderW/H:
// reported as not-found rather than as a resolution of zero. Measured need: Dying
// Light: The Beast (SL 2.8.0) published DLSS identity on every batch and no extent
// from either global-tag route on four captures; the whole-resource shape is the
// remaining reading the record can distinguish, and this is how it is tested.
inline bool TagSize(const sl::ResourceTag& tag, uint32_t& w, uint32_t& h) noexcept {
w = tag.extent.width;
h = tag.extent.height;
if (w == 0 || h == 0) {
if (!IsReadable<sl::Resource>(tag.resource)) {
return false;
}
w = tag.resource->width;
h = tag.resource->height;
}
return w != 0 && h != 0 && w <= 0xFFFFu && h <= 0xFFFFu;
}
// Find the extent a title tagged as the upscaler's INPUT colour buffer.
//
// kBufferTypeScalingInputColor is the render target the upscaler reads, so its
@@ -114,9 +182,10 @@ inline bool IsReadableResourceTag(const sl::BaseStructure* s) noexcept {
// A ZERO EXTENT IS NOT AN ERROR AND NOT A MEASUREMENT. sl_core_types.h documents
// `extent` as "the area of the tagged resource to use (if using the entire
// resource leave as null)", and it is a value member defaulting to all-zero. So
// a title tagging whole resources yields 0, which is the in-band unknown
// fl_shm.h already defines for renderW/H. Reported as not-found rather than as
// a resolution of zero.
// a title tagging whole resources yields 0 from the extent -- and TagSize then
// reads the Resource's own declared size, which is the in-band unknown fl_shm.h
// already defines for renderW/H when the title left that zero too. Reported as
// not-found rather than as a resolution of zero.
inline ScanResult FindScalingInputExtent(const sl::BaseStructure** inputs, uint32_t numInputs) noexcept {
ScanResult out;
if (inputs == nullptr || numInputs == 0) {
@@ -142,17 +211,18 @@ inline ScanResult FindScalingInputExtent(const sl::BaseStructure** inputs, uint3
// property of the title rather than of what it is doing.
if (IsReadableResourceTag(s)) {
const auto* tag = static_cast<const sl::ResourceTag*>(s);
out.tagTypes |= TagTypeBit(tag->type);
if (tag->type == sl::kBufferTypeScalingInputColor && !out.found) {
const uint32_t w = tag->extent.width;
const uint32_t h = tag->extent.height;
if (w != 0 && h != 0 && w <= 0xFFFFu && h <= 0xFFFFu) {
uint32_t w = 0;
uint32_t h = 0;
if (TagSize(*tag, w, h)) {
out.renderW = static_cast<uint16_t>(w);
out.renderH = static_cast<uint16_t>(h);
out.found = true;
}
// Otherwise a whole-resource tag, or a size that cannot be a
// render target. Keep looking: a title may chain several tags
// and only one of them carries an extent.
// Otherwise a whole-resource tag whose Resource states no size,
// or a size that cannot be a render target. Keep looking: a title
// may chain several tags and only one of them carries a size.
}
} else if (IsReadable<sl::DLSSOptions>(s) && !out.qualityFound) {
// `mode` is the FIRST member of DLSSOptions and has been since
+595 -165
View File
@@ -42,16 +42,23 @@
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <fl_ac_rules.h>
#include <fl_d3d12_vtable.h>
#include <fl_dxgi_vtable.h>
#include <fl_hook_inventory.h>
#include <fl_ring.h>
#include <fl_rt_accum.h>
#include <fl_shm.h>
#include <fl_shm_host.h>
#include <fl_sl_inputs.h>
#include <fl_sl_seen.h>
#include <MinHook.h>
#include <sddl.h>
// Its own block, below the sorted one, because it needs Family/Group/MatchKind
// from fl_ac_rules.h and clang-format sorts each block independently. Types plus
// the generated floor table only -- for the LoadLibrary detour's early stop; nothing
// of the rules parser is compiled into the Overlay.
#include <fl_ac_floor.generated.h>
// Vendored MIT headers, for TYPES ONLY -- never linked, and no vendor function's
// address is ever taken in evaluated code. See
@@ -71,6 +78,19 @@
#include <ffx_api.h>
#include <ffx_framegeneration.h>
#include <ffx_upscale.h>
// The FSR 3.0 HOST API (tag fsr3-v3.0.4), the same rule again, for exactly two things:
// FfxFsr3DispatchUpscaleDescription::renderSize and the type of the one export hooked.
// FFX_API is __declspec(dllexport) with no switch at all at that tag; nothing here
// defines or takes the address of a name, so nothing is exported, and Pass C's
// forbidden-export pattern already covers ffxFsr3*. A separate tree from ffx-api's
// (third_party/fidelityfx-fsr3/README.md), INCLUDED INSIDE A NAMESPACE: the two trees
// each define a struct named FfxFrameGenerationConfig, and wrapping the include is the
// one way to keep both headers verbatim in one TU. Legal C++: the entry points keep
// their C linkage, so fsr3host::ffxFsr3ContextDispatchUpscale names the same function
// the module exports, and every struct read here is still the vendor's declaration.
namespace fsr3host {
#include <FidelityFX/host/ffx_fsr3.h>
} // namespace fsr3host
using namespace fl;
@@ -81,134 +101,15 @@ void* g_base = nullptr;
fl::RingWriter g_writer;
HANDLE g_initThread = nullptr;
// The mapping is created with a DACL granting ONLY the current user's SID, and
// lives in the session-scoped Local\ namespace (docs/07_IPC.md §Security). No
// Global\ object: it would need admin and would be visible across sessions for
// no benefit.
//
// Returns false rather than falling back to a default DACL. A mapping the whole
// machine can write is not a degraded version of this one -- the Agent's control
// block is in it, and unhookRequested is the safety stop.
bool BuildUserOnlySecurity(SECURITY_ATTRIBUTES& sa, PSECURITY_DESCRIPTOR& sd) noexcept {
sd = nullptr;
HANDLE token = nullptr;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
return false;
}
unsigned char buffer[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE]{};
DWORD got = 0;
const BOOL ok = GetTokenInformation(token, TokenUser, buffer, sizeof(buffer), &got);
CloseHandle(token);
if (!ok) {
return false;
}
LPWSTR sidText = nullptr;
const auto* user = reinterpret_cast<const TOKEN_USER*>(buffer);
if (!ConvertSidToStringSidW(user->User.Sid, &sidText)) {
return false;
}
// D:P = a protected DACL, so nothing is inherited in. One ACE, generic all,
// for us alone.
wchar_t sddl[256]{};
const int n = _snwprintf_s(sddl, _TRUNCATE, L"D:P(A;;GA;;;%ls)", sidText);
LocalFree(sidText);
if (n < 0) {
return false;
}
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, SDDL_REVISION_1, &sd, nullptr)) {
return false;
}
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = sd;
sa.bInheritHandle = FALSE;
return true;
}
// Local\FrameLedger.Ring.<pid>. Deliberately plain and identifiable: 19_SAFETY
// forbids obfuscated object names, because being visible to anti-cheat is the
// whole design posture.
bool MakeRingName(wchar_t* out, size_t cap, DWORD pid) noexcept {
return _snwprintf_s(out, cap, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", pid) >= 0;
}
// The ring host half -- the user-only DACL, the Local\FrameLedger.Ring.<pid> name,
// the mapping and the handshake -- lives in fl_shm_host.h since P1 item 3, SHARED
// with the Vulkan layer: one contract, one copy, for both capture sides.
bool CreateRing() noexcept {
SECURITY_ATTRIBUTES sa{};
PSECURITY_DESCRIPTOR sd = nullptr;
if (!BuildUserOnlySecurity(sa, sd)) {
return false;
}
wchar_t name[128]{};
if (!MakeRingName(name, 128, GetCurrentProcessId())) {
LocalFree(sd);
return false;
}
const size_t bytes = fl::FlShmSizeForCapacity(FL_SHM_DEFAULT_CAPACITY);
g_mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, static_cast<DWORD>(bytes >> 32),
static_cast<DWORD>(bytes & 0xFFFFFFFFu), name);
const DWORD err = GetLastError();
LocalFree(sd);
if (g_mapping == nullptr) {
return false;
}
// A pre-existing mapping under our own pid is not a mapping we understand:
// either a stale object or another writer. Refuse rather than share a ring
// with an unknown producer.
if (err == ERROR_ALREADY_EXISTS) {
CloseHandle(g_mapping);
g_mapping = nullptr;
return false;
}
g_base = MapViewOfFile(g_mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, bytes);
if (g_base == nullptr) {
CloseHandle(g_mapping);
g_mapping = nullptr;
return false;
}
return true;
return fl::shmhost::CreateRingMapping(g_mapping, g_base);
}
// Write-once at init, per docs/07_IPC.md §A + B. adapterLuid is deliberately
// left 0 = "not yet known": this runs two steps before any graphics module is
// resolved, and our own dummy device's adapter is not the game's (#36). It is
// published at first present, with the hook.
void PublishHandshake() noexcept {
auto* h = reinterpret_cast<FlShmHandshake*>(static_cast<unsigned char*>(g_base) + FL_SHM_HANDSHAKE_OFFSET);
h->recordSize = sizeof(FlFrameRecord);
h->capacity = FL_SHM_DEFAULT_CAPACITY;
h->pid = GetCurrentProcessId();
// FL_BUILD_ID comes from git describe at configure time (FrameLedger.Shm's
// CMakeLists). It had no producer at all until #36; without one the Agent's
// refuse-to-attach-on-mismatch compares "" with "" forever.
const char* build = FL_BUILD_ID;
size_t i = 0;
for (; i + 1 < sizeof(h->buildId) && build[i] != '\0'; ++i) {
h->buildId[i] = build[i];
}
h->buildId[i] = '\0';
LARGE_INTEGER qpc{};
QueryPerformanceCounter(&qpc);
h->qpcEpoch = static_cast<uint64_t>(qpc.QuadPart);
h->adapterLuid = 0;
// layoutVersion LAST, with a release fence in front of it. It is the field a
// reader validates first, so it must not become visible before the fields it
// vouches for. A reader that saw the version while capacity was still zero
// would compute a ring of no slots and read garbage.
std::atomic_thread_fence(std::memory_order_release);
std::atomic_ref<uint32_t> version{h->layoutVersion};
version.store(FL_SHM_LAYOUT_VERSION, std::memory_order_release);
fl::shmhost::PublishHandshake(g_base);
}
// ---------------------------------------------------------------------------
@@ -278,12 +179,18 @@ void NoteFault() noexcept {
// ---------------------------------------------------------------------------
constexpr size_t kMaxSwapChains = 16;
// The last GetLastPresentCount value read at a hooked present on this chain, and whether
// one has been read at all (fl_shm.h §dxgiPresentsUnseen). Per chain, because the
// counter is per chain.
struct SwapChainSlot {
void* ptr = nullptr;
uint32_t id = 0;
uint16_t outW = 0;
uint16_t outH = 0;
uint8_t api = FL_API_UNKNOWN;
bool haveDxgiCount = false;
uint32_t lastDxgiCount = 0;
uint32_t dxgiEpoch = 0; // g_dxgiEpoch when lastDxgiCount was read; a mismatch means presents went by unrecorded
};
// Ask the device whether it can ray-trace, once, and publish it as FlRtTier.
@@ -596,6 +503,12 @@ void StopObserving(uint32_t reason) noexcept {
// is the whole point of having one. What stays is the safety stop, because
// 07_IPC requires it within one frame and a one-second watchdog cannot promise
// that, and the pause check, which is inherently per-frame.
// The LoadLibrary detour's early stop (defined with the detour below; the present
// path reads it first): 0 = none; else 1-based index among the floor's MODULE
// families in rules order.
std::atomic<uint32_t> g_earlyStopFamily{0};
void PublishLoaderWords() noexcept;
bool MayObserve() noexcept {
if (g_observing.load(std::memory_order_acquire) == 0) {
return false;
@@ -612,6 +525,15 @@ bool MayObserve() noexcept {
return false;
}
// The IN-PROCESS stop, same path and same polarity: the LoadLibrary detour saw
// a module matching the compiled anti-cheat floor load. Published before the
// unhook so the reason is on the mapping whichever thread gets here first.
if (g_earlyStopFamily.load(std::memory_order_acquire) != 0u) {
PublishLoaderWords();
StopObserving(FL_STATUS_STOPPED_BLOCKLISTED);
return false;
}
// Pausing is not stopping: the Agent asked us to hold, and the supervision
// clock keeps running (in the watchdog), so a paused session still stops if
// the guard dies.
@@ -716,6 +638,18 @@ std::atomic<uint32_t> g_upscalerParamsLive{0};
using PFN_SlSetTag = ::PFun_slSetTag*;
PFN_SlSetTag g_origSlSetTag = nullptr;
// The frame-based twin (Streamline 2.8: slSetTag is deprecated in favour of it).
// Its own trampoline; and the two rows carry PATCHED flags of their own while the
// family keeps ONE published latch (g_upscalerParamsLive), because the family is
// published when whole -- PublishParamsFamilyIfWhole -- and not by whichever row
// installed first. InstallRow's latch would have done both jobs wrongly: shared, the
// first row would have claimed it and the second would never patch; separate, the
// first row would have published a family the second was not yet producing.
using PFN_SlSetTagForFrame = ::PFun_slSetTagForFrame*;
PFN_SlSetTagForFrame g_origSlSetTagForFrame = nullptr;
std::atomic<uint32_t> g_slSetTagPatched{0};
std::atomic<uint32_t> g_slSetTagForFramePatched{0};
// The application-frame count (HANDOFF item 3, decided 2026-09-03). Streamline
// hands a title one FrameToken per frame through slGetNewFrameToken, and a title
// has to ask for it -- so the number of DISTINCT tokens handed out between two
@@ -837,6 +771,40 @@ PFN_FfxDispatch g_origFfxDispatch[fl::inventory::kFfxLeafCount] = {};
std::atomic<uint32_t> g_ffxPatched[fl::inventory::kFfxLeafCount] = {};
std::atomic<uint32_t> g_ffxLive{0};
// --- The FSR 3.0 HOST API: ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale ----------
//
// The fifth AMD target, and NOT a leaf: a different export with a different signature,
// hooked at its own address with its own trampoline and latch, feeding the SAME drain
// word as the ffx-api UPSCALE arm -- so the count, the extent and the identity byte all
// flow through the paths above unchanged, and PublishFfxFamilyIfWhole is its publish
// point. Which source the last UPSCALE came from is recorded in g_ffxUpscaleLeaf as
// leaf + 1; the host takes the value past every leaf.
//
// WHAT IS READ (CLAUDE.md rule 4): renderSize of the descriptor the title passed, and
// nothing else -- never the context, never a resource, never the command list.
using PFN_FfxFsr3ContextDispatchUpscale = decltype(&fsr3host::ffxFsr3ContextDispatchUpscale);
PFN_FfxFsr3ContextDispatchUpscale g_origFfxFsr3DispatchUpscale = nullptr;
std::atomic<uint32_t> g_fsr3HostPatched{0};
constexpr uint32_t kFfxUpscaleSourceFsr3Host = fl::inventory::kFfxLeafCount + 1u;
static_assert(kFfxUpscaleSourceFsr3Host > fl::inventory::kFfxLeafCount,
"the host's source value must sit past every leaf's (leaf + 1) so the identity arm can tell them apart");
// THE ONE OFFSET THE HOST DETOUR DEPENDS ON, PINNED TO A LITERAL. commandList (8) +
// seven FfxResource (176 each: a pointer, the 32-byte description, the 4-byte state,
// 128 bytes of name, padded to 8) + jitterOffset (8) + motionVectorScale (8). The
// prefix through renderSize is identical at fsr3-v3.0.3, fsr3-v3.0.4 and v1.1.4 (1.1.4
// appends upscaleSize, flags and frameID AFTER it), and the literal is the point: a
// re-vendoring that moved the field fails here rather than reading the wrong bytes off
// a descriptor Cyberpunk's 3.0 module actually passed.
static_assert(sizeof(fsr3host::FfxDimensions2D) == 8u && offsetof(fsr3host::FfxDimensions2D, height) == 4u,
"FfxDimensions2D is two uint32_t");
static_assert(offsetof(fsr3host::FfxFsr3DispatchUpscaleDescription, renderSize) == 1256u,
"FfxFsr3DispatchUpscaleDescription::renderSize moved -- the vendored tag no longer matches the prefix "
"3.0.3 / 3.0.4 / 1.1.4 share, and the detour would read the wrong bytes");
static_assert(offsetof(fsr3host::FfxFsr3DispatchUpscaleDescription, renderSize) + sizeof(fsr3host::FfxDimensions2D) <=
sizeof(fsr3host::FfxFsr3DispatchUpscaleDescription),
"the field read must lie inside the descriptor");
// WHY THIS PERSISTS RATHER THAN BEING exchange(0)'d LIKE g_slSeen.
//
// g_slSeen answers "did an upscaler run THIS FRAME", so a sample that outlived
@@ -850,7 +818,214 @@ std::atomic<uint32_t> g_ffxLive{0};
// stands -- is handled at the consumer end in RecordPresent: renderW/H are only
// published on a frame where an evaluation was actually seen. Tag alone is never
// enough.
void NoteTags(const sl::ResourceTag* tags, uint32_t numTags) noexcept {
// WHICH TYPES the title tagged, on which route -- the identity half of frame
// generation (fl_shm.h §slTagCensus). Two words: the per-present one, drained with
// exchange(0) in RecordPresent like g_slSeen so a HUD-less tag cannot outlive the
// frame it was set for (Streamline's lifecycle for it is eValidUntilPresent), and the
// session one, OR-only, published by the watchdog like the runtime census.
std::atomic<uint32_t> g_slTagTypes{0};
std::atomic<uint32_t> g_slTagCensus{0};
// DXGI's own present counter against ours (fl_shm.h §dxgiPresentsUnseen): hook-local,
// watchdog-published, monotonic.
std::atomic<uint32_t> g_dxgiUnseen{0};
std::atomic<uint32_t> g_dxgiSamples{0};
// Whether FlWriterState::dxgiPresentsBeforeHook has been written: once, at the first
// hooked present, whichever chain it lands on.
std::atomic<bool> g_dxgiBeforeHookPublished{false};
// A PRESENT THIS HOOK SAW AND DECLINED TO RECORD IS NOT ONE IT NEVER SAW. While a
// session is paused (MayObserve false) the title keeps presenting and DXGI keeps
// counting, so the first record after the resume would otherwise claim the whole
// pause as unseen presents -- measured 0x55 on the paused-session integration case.
// Every declined present bumps this epoch; a slot whose last read is from an older
// epoch differences nothing and starts again. DXGI_PRESENT_TEST presents do not bump
// it: they do not move the counter (#35), so there is nothing to invalidate.
std::atomic<uint32_t> g_dxgiEpoch{0};
// ---------------------------------------------------------------------------
// THE LoadLibrary DETOUR (17_HOOK_ENGINE §DLL entry step 3; §H2; §S6). P1 item 1,
// 2026-09-06. Two jobs, one rule.
//
// The jobs: (a) a module the hook inventory or the runtime census names loaded
// AFTER init -- the watchdog is woken now instead of on its next 1 Hz tick, so
// the window in which a late vendor module's calls go unobserved shrinks from up
// to a second to milliseconds; (b) a module whose base name matches the
// anti-cheat floor compiled into this binary loaded mid-session -- the Overlay
// stops ITSELF on the next present or watchdog wake, the in-process half of
// 19_SAFETY §During a session, where the host's 30 s scan was the only half.
//
// The rule: the detour INSTALLS NOTHING AND UNHOOKS NOTHING INLINE. MinHook
// suspends every other thread to patch, and a LoadLibrary caller may hold the
// loader lock (a DllMain calling LoadLibrary is legal); suspending a thread that
// holds it, from a thread that then waits on it, is the deadlock §H2 names. So
// the detour reads a base name off the module the ORIGINAL returned, compares it
// against two fixed tables without allocating, stores two atomics, and signals an
// event. Everything that patches runs on the watchdog thread, outside the lock.
//
// kernelbase!LoadLibraryExW is the target because it is the funnel: LoadLibraryA,
// LoadLibraryW and LoadLibraryExA all reach it inside KernelBase, so one detour
// covers the four documented entry points. What it does NOT cover, stated:
// LdrLoadDll called directly (no measured title does), and delay-load thunks
// resolved before we attached (they went through it before we existed). The 1 Hz
// watchdog and the host's 30 s scan remain the backstops for both jobs.
//
// NOT an FL_HOOK_INVENTORY row: that table is (vendor module, exported symbol)
// and Pass A checks each row against measured vendor exports. This is a system
// module, and 17_HOOK_ENGINE §Hook inventory records the asymmetry beside the
// ray-tracing vtable slots, which are outside the table for the same reason.
// ---------------------------------------------------------------------------
using PFN_LoadLibraryExW = HMODULE(WINAPI*)(LPCWSTR, HANDLE, DWORD);
PFN_LoadLibraryExW g_origLoadLibraryExW = nullptr;
// Bit 15 = installed; bits 0..14 = wake-ups for inventoried modules (saturating).
constexpr uint32_t kLoaderInstalledBit = 0x8000u;
constexpr uint32_t kLoaderCountMask = 0x7FFFu;
std::atomic<uint32_t> g_loaderSignals{0};
// Auto-reset; the watchdog waits on it with its 1 s timeout, so a signal ends the
// wait early and a missing event (creation failed) degrades to the plain sleep.
HANDLE g_watchdogWake = nullptr;
const wchar_t* BaseNameOf(const wchar_t* path) noexcept {
const wchar_t* base = path;
for (const wchar_t* p = path; *p != L'\0'; ++p) {
if (*p == L'\\' || *p == L'/') {
base = p + 1;
}
}
return base;
}
wchar_t AsciiLower(wchar_t c) noexcept {
return (c >= L'A' && c <= L'Z') ? static_cast<wchar_t>(c + (L'a' - L'A')) : c;
}
// Case-insensitive ASCII compare of a wide base name against a narrow rule value:
// exact, or the value as a prefix. The rules are ASCII by schema, so a wide
// character outside ASCII simply never matches.
bool NameMatches(const wchar_t* base, const char* value, bool prefix) noexcept {
size_t i = 0;
for (; value[i] != '\0'; ++i) {
const wchar_t b = base[i];
if (b == L'\0' || AsciiLower(b) != AsciiLower(static_cast<wchar_t>(static_cast<unsigned char>(value[i])))) {
return false;
}
}
return prefix || base[i] == L'\0';
}
// The compiled floor's MODULE families, in order: the 1-based index of the first
// whose value matches, else 0. The same prefix/exact semantics the guard's
// MatchName applies to a base name, on the same generated table.
uint32_t MatchesFloorModule(const wchar_t* base) noexcept {
uint32_t index = 0;
for (const fl::guard::Family& f : fl::guard::generated::kFloorFamilies) {
if (f.group != fl::guard::Group::kModules) {
continue;
}
++index;
for (std::size_t v = 0; v < f.valueCount; ++v) {
if (NameMatches(base, f.values[v], f.match == fl::guard::MatchKind::kPrefix)) {
return index;
}
}
}
return 0;
}
// Does the inventory or the census name this module? A load of one of these is
// what the watchdog installs or counts on its next tick, so it is what wakes it.
bool ModuleIsInventoried(const wchar_t* base) noexcept {
#define FL_LOADER_NAME(mod, ...) \
if (_wcsicmp(base, mod) == 0) { \
return true; \
}
FL_HOOK_INVENTORY(FL_LOADER_NAME)
FL_RUNTIME_CENSUS(FL_LOADER_NAME)
#undef FL_LOADER_NAME
return false;
}
void WakeWatchdog() noexcept {
if (g_watchdogWake != nullptr) {
SetEvent(g_watchdogWake);
}
}
HMODULE WINAPI Hook_LoadLibraryExW(LPCWSTR name, HANDLE file, DWORD flags) noexcept {
// The original FIRST, always, and its result is returned untouched: this
// detour must be invisible to the loader's caller whatever happens below.
const HMODULE h = g_origLoadLibraryExW(name, file, flags);
FL_HOOK_GUARD({
// A data-file or resource mapping is not a module: no code runs from it
// and the loader does not list it, so neither job applies.
constexpr DWORD kNotAModule =
LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE;
if (h != nullptr && (flags & kNotAModule) == 0u && g_observing.load(std::memory_order_acquire) != 0) {
// The module's real file name, not the caller's string: a relative or
// API-set name resolves to whatever the loader mapped, and that is the
// name the guard would see.
wchar_t path[MAX_PATH]{};
if (GetModuleFileNameW(h, path, MAX_PATH) != 0) {
const wchar_t* base = BaseNameOf(path);
const uint32_t family = MatchesFloorModule(base);
if (family != 0u) {
uint32_t none = 0;
g_earlyStopFamily.compare_exchange_strong(none, family, std::memory_order_acq_rel);
WakeWatchdog();
} else if (ModuleIsInventoried(base)) {
uint32_t cur = g_loaderSignals.load(std::memory_order_relaxed);
while ((cur & kLoaderCountMask) < kLoaderCountMask &&
!g_loaderSignals.compare_exchange_weak(cur, cur + 1u, std::memory_order_relaxed)) {
}
WakeWatchdog();
}
}
}
})
return h;
}
// Installed AFTER the present hooks, from InitThread, outside any loader lock.
// Failure is not fatal and is visible: bit 15 stays clear, so the report can say
// the detour is absent and the two backstops are all there is.
bool InstallLoaderHook() noexcept {
const HMODULE kb = GetModuleHandleW(L"kernelbase.dll");
if (kb == nullptr) {
return false;
}
void* target = reinterpret_cast<void*>(GetProcAddress(kb, "LoadLibraryExW"));
if (target == nullptr) {
return false;
}
if (MH_CreateHook(target, reinterpret_cast<void*>(&Hook_LoadLibraryExW),
reinterpret_cast<void**>(&g_origLoadLibraryExW)) != MH_OK ||
MH_EnableHook(target) != MH_OK) {
return false;
}
g_loaderSignals.fetch_or(kLoaderInstalledBit, std::memory_order_release);
return true;
}
void PublishLoaderWords() noexcept {
if (g_state == nullptr) {
return;
}
std::atomic_ref<uint16_t> signals{g_state->loaderSignals};
std::atomic_ref<uint16_t> family{g_state->earlyStopFamily};
signals.store(static_cast<uint16_t>(g_loaderSignals.load(std::memory_order_relaxed)), std::memory_order_relaxed);
family.store(static_cast<uint16_t>(g_earlyStopFamily.load(std::memory_order_relaxed)), std::memory_order_relaxed);
}
void NoteTagTypes(uint32_t typeBits, uint32_t routeShift) noexcept {
if (typeBits == 0u) {
return;
}
g_slTagTypes.fetch_or(typeBits, std::memory_order_relaxed);
g_slTagCensus.fetch_or((typeBits & FL_SL_TAG_TYPE_MASK) << routeShift, std::memory_order_relaxed);
}
void NoteTags(const sl::ResourceTag* tags, uint32_t numTags, uint32_t routeShift) noexcept {
// A null list REMOVES tags (sl_core_api.h: "set to null to remove the
// specified tag"). Forgetting this is how renderW/H would latch a stale
// resolution across a settings change.
@@ -865,32 +1040,40 @@ void NoteTags(const sl::ResourceTag* tags, uint32_t numTags) noexcept {
constexpr uint32_t kMaxTags = 64;
const uint32_t n = numTags < kMaxTags ? numTags : kMaxTags;
// EVERY tag's TYPE is recorded, and only the scaling input's SIZE is read. The
// first version of this walked to the scaling input and returned, dropping every
// other tag on the floor -- and the HUD-less and UI tags it dropped are the ones
// that say a title is feeding DLSS Frame Generation (fl_shm.h §slTagCensus).
uint32_t types = 0;
bool extentDone = false;
for (uint32_t i = 0; i < n; ++i) {
const sl::ResourceTag& t = tags[i];
if (t.type != sl::kBufferTypeScalingInputColor) {
types |= fl::slinputs::TagTypeBit(t.type);
if (t.type != sl::kBufferTypeScalingInputColor || extentDone) {
continue;
}
// extent is by VALUE and defaults to all-zero, which the vendor header
// documents as "using the entire resource". That is the honest unknown
// fl_shm.h already defines for renderW/H, so it is stored as such rather
// than guessed at from the resource description -- which for D3D12 is
// itself unset (sl_core_types.h: mandatory only for Vulkan).
const uint64_t w = t.extent.width;
const uint64_t h = t.extent.height;
if (w == 0 || h == 0 || w > 0xFFFFu || h > 0xFFFFu) {
extentDone = true;
// The extent, or -- when the title tagged the whole resource -- the size the
// Resource itself declares; fl_sl_inputs.h's TagSize is the one reading of a
// tag all three routes share. Neither present is the honest unknown fl_shm.h
// already defines for renderW/H, stored as such rather than guessed.
uint32_t w = 0;
uint32_t h = 0;
if (!fl::slinputs::TagSize(t, w, h)) {
g_tagExtent.store(0, std::memory_order_release);
return;
continue;
}
g_tagExtent.store(w | (h << 16) | kTagValid, std::memory_order_release);
return;
g_tagExtent.store(static_cast<uint64_t>(w) | (static_cast<uint64_t>(h) << 16) | kTagValid,
std::memory_order_release);
}
NoteTagTypes(types, routeShift);
}
sl::Result STDMETHODCALLTYPE Hook_SlSetTag(const sl::ViewportHandle& viewport, const sl::ResourceTag* tags,
uint32_t numTags, sl::CommandBuffer* cmdBuffer) {
FL_HOOK_GUARD({
if (MayObserve()) {
NoteTags(tags, numTags);
NoteTags(tags, numTags, FL_SL_TAG_ROUTE_GLOBAL);
}
})
// ALWAYS exactly once, on every path including the fault path, with every
@@ -898,6 +1081,21 @@ sl::Result STDMETHODCALLTYPE Hook_SlSetTag(const sl::ViewportHandle& viewport, c
return g_origSlSetTag(viewport, tags, numTags, cmdBuffer);
}
// slSetTagForFrame: the FrameToken first, then the same list slSetTag takes. The
// token is not read -- the frame count comes from slGetNewFrameToken -- and the tag
// list is handed to the same NoteTags, because a per-frame tag and a viewport tag
// state the same thing about the input buffer. Forwarded exactly once on every path.
sl::Result STDMETHODCALLTYPE Hook_SlSetTagForFrame(const sl::FrameToken& frame, const sl::ViewportHandle& viewport,
const sl::ResourceTag* tags, uint32_t numTags,
sl::CommandBuffer* cmdBuffer) {
FL_HOOK_GUARD({
if (MayObserve()) {
NoteTags(tags, numTags, FL_SL_TAG_ROUTE_FRAME);
}
})
return g_origSlSetTagForFrame(frame, viewport, tags, numTags, cmdBuffer);
}
sl::Result STDMETHODCALLTYPE Hook_SlEvaluateFeature(sl::Feature feature, const sl::FrameToken& frame,
const sl::BaseStructure** inputs, uint32_t numInputs,
sl::CommandBuffer* cmdBuffer) {
@@ -959,6 +1157,8 @@ sl::Result STDMETHODCALLTYPE Hook_SlEvaluateFeature(sl::Feature feature, const s
// rather than to the viewport, so it cannot be older than the frame
// being measured.
const auto scan = fl::slinputs::FindScalingInputExtent(inputs, numInputs);
// Every tag TYPE the walk saw, on the local route (fl_shm.h §slTagCensus).
NoteTagTypes(scan.tagTypes, FL_SL_TAG_ROUTE_LOCAL);
if (scan.found) {
g_tagExtent.store(static_cast<uint64_t>(scan.renderW) | (static_cast<uint64_t>(scan.renderH) << 16) |
kTagValid,
@@ -1067,9 +1267,7 @@ static_assert(offsetof(ffxDispatchDescFrameGenerationPrepare, renderSize) + size
// The render extent, from an UPSCALE or PREPARE descriptor. Same packing and the same
// in-band unknown as NoteTags: a zero or absurd size clears the sample rather than
// publishing a resolution nobody rendered at.
void NoteFfxExtent(const FfxApiDimensions2D& size) noexcept {
const uint64_t w = size.width;
const uint64_t h = size.height;
void NoteFfxExtent(uint64_t w, uint64_t h) noexcept {
if (w == 0 || h == 0 || w > 0xFFFFu || h > 0xFFFFu) {
g_ffxExtent.store(0, std::memory_order_release);
return;
@@ -1077,6 +1275,10 @@ void NoteFfxExtent(const FfxApiDimensions2D& size) noexcept {
g_ffxExtent.store(w | (h << 16) | kTagValid, std::memory_order_release);
}
void NoteFfxExtent(const FfxApiDimensions2D& size) noexcept {
NoteFfxExtent(size.width, size.height);
}
void ObserveFfxDispatch(uint32_t leaf, const ffxDispatchDescHeader* desc) noexcept {
if (desc == nullptr) {
return;
@@ -1137,6 +1339,20 @@ ffxReturnCode_t Hook_FfxDispatchT(ffxContext* context, const ffxDispatchDescHead
return g_origFfxDispatch[Leaf](context, desc);
}
// The FSR 3.0 host detour: the UPSCALE arm of ObserveFfxDispatch, verbatim, on a
// descriptor of the host API's shape. Original called exactly once on every path.
fsr3host::FfxErrorCode Hook_FfxFsr3ContextDispatchUpscale(fsr3host::FfxFsr3Context* context,
const fsr3host::FfxFsr3DispatchUpscaleDescription* desc) {
FL_HOOK_GUARD({
if (MayObserve() && desc != nullptr) {
NoteFfxExtent(desc->renderSize.width, desc->renderSize.height);
g_ffxUpscaleLeaf.store(kFfxUpscaleSourceFsr3Host, std::memory_order_relaxed);
g_ffxSeen.fetch_add(fl::slseen::kCountOne, std::memory_order_relaxed);
}
})
return g_origFfxFsr3DispatchUpscale(context, desc);
}
void* FfxDispatchDetour(uint32_t leaf) noexcept {
switch (leaf) {
case fl::inventory::kFfxLeafMonolith:
@@ -1323,6 +1539,33 @@ void PublishRuntimeCensus() noexcept {
census.fetch_or(seen, std::memory_order_relaxed);
}
// The tag census, on the same tick and by the same rule: OR-only, from the
// process-local word the three tag routes accumulate into, so region 2 takes one
// write a second rather than one per tag list (fl_shm.h §slTagCensus).
// DXGI's counter against ours, published on the same tick. Monotonic, so a plain store
// of the hook-local value is the whole publish.
void PublishDxgiPresentCounters() noexcept {
if (g_state == nullptr) {
return;
}
std::atomic_ref<uint32_t> unseen{g_state->dxgiPresentsUnseen};
std::atomic_ref<uint32_t> samples{g_state->dxgiPresentSamples};
unseen.store(g_dxgiUnseen.load(std::memory_order_relaxed), std::memory_order_relaxed);
samples.store(g_dxgiSamples.load(std::memory_order_relaxed), std::memory_order_relaxed);
}
void PublishSlTagCensus() noexcept {
if (g_state == nullptr) {
return;
}
const uint32_t seen = g_slTagCensus.load(std::memory_order_relaxed);
if (seen == 0u) {
return;
}
std::atomic_ref<uint32_t> census{g_state->slTagCensus};
census.fetch_or(seen, std::memory_order_relaxed);
}
bool InstallRow(const wchar_t* module, const char* symbol, uint32_t family, void* detour, void** original,
std::atomic<uint32_t>& live) noexcept {
if (live.load(std::memory_order_acquire) != 0) {
@@ -1360,8 +1603,33 @@ bool InstallByFamily(const wchar_t* module, const char* symbol, uint32_t family)
reinterpret_cast<void**>(&g_origSlEvaluateFeature), g_upscalerIdentityLive);
}
if (family == static_cast<uint32_t>(fl::FL_HOOK_UPSCALER_PARAMS)) {
return InstallRow(module, symbol, family, reinterpret_cast<void*>(&Hook_SlSetTag),
reinterpret_cast<void**>(&g_origSlSetTag), g_upscalerParamsLive);
// TWO ROWS IN THIS FAMILY WITH DIFFERENT SIGNATURES, so the family alone would
// bind the wrong body to one of them. The symbol decides, through the constant
// the inventory header binds to its own row -- no literal here, which is what
// keeps hookinventory-check Pass B able to see every resolver in the Overlay.
//
// PATCHED WITHOUT PUBLISHING, as the ffx leaves are. The family is published by
// PublishParamsFamilyIfWhole once every row this interposer exports is in;
// published on the first row, it entitled records the second was not yet
// producing -- 38 of 41 records claiming params on the frame-based fixture.
const bool frameRow = fl::inventory::SameA(symbol, fl::inventory::kSymbolSlSetTagForFrame);
std::atomic<uint32_t>& patched = frameRow ? g_slSetTagForFramePatched : g_slSetTagPatched;
if (patched.load(std::memory_order_acquire) != 0) {
return true;
}
void* target = fl::inventory::ResolveScoped(module, symbol);
if (target == nullptr) {
return false; // not loaded, a generation without this export, or an ABI we do not speak
}
void* detour =
frameRow ? reinterpret_cast<void*>(&Hook_SlSetTagForFrame) : reinterpret_cast<void*>(&Hook_SlSetTag);
void** original =
frameRow ? reinterpret_cast<void**>(&g_origSlSetTagForFrame) : reinterpret_cast<void**>(&g_origSlSetTag);
if (!PatchTarget(target, detour, original)) {
return false;
}
patched.store(1, std::memory_order_release);
return true;
}
if (family == static_cast<uint32_t>(fl::FL_HOOK_FG_EVALUATIONS)) {
return InstallRow(module, symbol, family, reinterpret_cast<void*>(&Hook_SlGetNewFrameToken),
@@ -1380,12 +1648,29 @@ bool InstallByFamily(const wchar_t* module, const char* symbol, uint32_t family)
// on a 2.x title, so a family published on the first leaf entitles records the
// second leaf is not yet producing.
//
// A module the leaf table does not know installs NOTHING. fl_hook_inventory.h's
// static_asserts make that unreachable for the rows as written; this is the
// installer's safe direction for a row somebody adds later.
// A module the leaf table does not know is either the FSR 3.0 HOST -- its own
// export, its own body, its own latch, the same family and publish point -- or
// nothing: fl_hook_inventory.h's static_asserts make the latter unreachable for
// the rows as written, and installing nothing is the safe direction for a row
// somebody adds later.
const int leaf = fl::inventory::FfxLeafOf(module);
if (leaf < 0) {
return false;
if (_wcsicmp(module, fl::inventory::kModuleFfxFsr3Host) != 0) {
return false;
}
if (g_fsr3HostPatched.load(std::memory_order_acquire) != 0) {
return true;
}
void* target = fl::inventory::ResolveScoped(module, symbol);
if (target == nullptr) {
return false; // not loaded, or a module of the name that does not speak the 3.0 host ABI
}
if (!PatchTarget(target, reinterpret_cast<void*>(&Hook_FfxFsr3ContextDispatchUpscale),
reinterpret_cast<void**>(&g_origFfxFsr3DispatchUpscale))) {
return false;
}
g_fsr3HostPatched.store(1, std::memory_order_release);
return true;
}
const auto slot = static_cast<uint32_t>(leaf);
if (g_ffxPatched[slot].load(std::memory_order_acquire) != 0) {
@@ -1426,16 +1711,57 @@ void PublishFfxFamilyIfWhole() noexcept {
return; // loaded and not yet patched: the family is not whole
}
}
// The FSR 3.0 host is the fifth target under the same rule. On Cyberpunk it lives
// beside the 1.1.x monolith, and the family's FsrFg claim comes from the monolith
// while the identity comes from the host -- published on whichever patched first,
// the other's records would be entitled before they were produced (#110's window).
if (g_fsr3HostPatched.load(std::memory_order_acquire) != 0) {
anyPatched = true;
} else if (fl::inventory::IsModuleLoaded(fl::inventory::kModuleFfxFsr3Host)) {
return;
}
if (anyPatched) {
PublishHookFamily(fl::inventory::kFamilyFfxDispatch, g_ffxLive);
}
}
// Publish FL_HOOK_UPSCALER_PARAMS once EVERY TAG EXPORT THE LOADED INTERPOSER HAS is
// patched, and at least one is. "Has" is the export table, not the module list: a
// 2.7 interposer exports slSetTag alone and is whole with that one row patched; a
// 2.8 interposer exports both, and is whole only with both. Runs after the rows on
// every watchdog tick, so a row whose patch failed once holds the family back until
// it is in rather than letting the other row publish over it.
void PublishParamsFamilyIfWhole() noexcept {
if (g_upscalerParamsLive.load(std::memory_order_acquire) != 0) {
return;
}
struct Row {
const char* symbol;
std::atomic<uint32_t>* patched;
};
const Row rows[] = {{fl::inventory::kSymbolSlSetTag, &g_slSetTagPatched},
{fl::inventory::kSymbolSlSetTagForFrame, &g_slSetTagForFramePatched}};
bool anyPatched = false;
for (const Row& r : rows) {
if (r.patched->load(std::memory_order_acquire) != 0) {
anyPatched = true;
continue;
}
if (fl::inventory::ResolveScoped(fl::inventory::kModuleSlInterposer, r.symbol) != nullptr) {
return; // exported and not yet patched: the family is not whole
}
}
if (anyPatched) {
PublishHookFamily(static_cast<uint32_t>(fl::FL_HOOK_UPSCALER_PARAMS), g_upscalerParamsLive);
}
}
bool InstallUpscalerHooks() noexcept {
bool any = false;
#define FL_INSTALL_ROW(mod, sym, family) any = InstallByFamily(mod, sym, static_cast<uint32_t>(family)) || any;
FL_HOOK_INVENTORY(FL_INSTALL_ROW)
#undef FL_INSTALL_ROW
PublishParamsFamilyIfWhole();
PublishFfxFamilyIfWhole();
return any;
}
@@ -1599,7 +1925,13 @@ bool InstallRtHooks() noexcept {
// Overlay and was not in the Vulkan layer.
DWORD WINAPI WatchdogThread(LPVOID) noexcept {
for (;;) {
Sleep(kWatchdogIntervalMs);
// The 1 s tick, OR the LoadLibrary detour's wake -- whichever comes first.
// An event that failed to create degrades to the plain sleep.
if (g_watchdogWake != nullptr) {
WaitForSingleObject(g_watchdogWake, kWatchdogIntervalMs);
} else {
Sleep(kWatchdogIntervalMs);
}
if (g_observing.load(std::memory_order_acquire) == 0) {
return 0; // stopped by us or by a hook body; nothing left to decide
@@ -1614,18 +1946,32 @@ DWORD WINAPI WatchdogThread(LPVOID) noexcept {
return 0;
}
// The in-process stop, for a title that is NOT presenting (menu, hung,
// alt-tabbed) -- the case the present path cannot reach. Same order as the
// Agent's stop: before any install.
if (g_earlyStopFamily.load(std::memory_order_acquire) != 0u) {
PublishLoaderWords();
StopObserving(FL_STATUS_STOPPED_BLOCKLISTED);
return 0;
}
// The detour's words BEFORE the installers: a reader that sees the hook
// family appear must already be able to see the wake that caused it.
PublishLoaderWords();
// Lazy feature-hook installation. AFTER the two stops, never before: a
// tick that is going to unhook must not install anything first.
//
// THIS IS THE VEHICLE, AND IT IS WHY NO LoadLibrary HOOK IS NEEDED FOR
// P0. 17_HOOK_ENGINE §DLL entry step 5 installs feature hooks "the first
// time their module appears", and a game that loads Streamline lazily --
// most of them, since sl.interposer is pulled in at device creation --
// would be missed by a one-shot check at init. A LoadLibrary hook would
// catch it too, but it runs under the loader lock while MinHook suspends
// every thread to patch (§H2), so it must defer the work to a thread
// anyway. This thread already exists and already wakes once a second, so
// §S6 stays genuinely separable rather than becoming a prerequisite.
// THIS IS THE VEHICLE. 17_HOOK_ENGINE §DLL entry step 5 installs feature
// hooks "the first time their module appears", and a game that loads
// Streamline lazily -- most of them, since sl.interposer is pulled in at
// device creation -- would be missed by a one-shot check at init. The
// LoadLibrary detour (step 3, P1 item 1) does NOT install anything itself:
// it runs under the loader lock while MinHook suspends every thread to
// patch (§H2), so it only signals g_watchdogWake and the install still
// happens HERE, on this thread -- within milliseconds of the module rather
// than on the next tick. Through P0 the tick alone was the vehicle, which
// is why §S6 stayed separable rather than becoming a prerequisite.
//
// It RETRIES until it succeeds and latches only on SUCCESS. An
// install-attempted flag would give the module exactly one chance, at a
@@ -1641,6 +1987,9 @@ DWORD WINAPI WatchdogThread(LPVOID) noexcept {
// The census, on the same tick. After the installers so that a module which
// appeared this second is both hooked and counted in the same pass.
PublishRuntimeCensus();
PublishSlTagCensus();
PublishDxgiPresentCounters();
PublishLoaderWords();
// Supervision loss. guardTicks counts COMPLETED guard evaluations, not
// seconds, so a stalled guard loop stops it advancing even while the
@@ -1671,6 +2020,9 @@ DWORD WINAPI WatchdogThread(LPVOID) noexcept {
// lock, no logging (NFR-1, target <= 1 us; a bare vtable detour measured 8.4 ns).
void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
if (!MayObserve()) {
if ((flags & DXGI_PRESENT_TEST) == 0u) {
g_dxgiEpoch.fetch_add(1u, std::memory_order_relaxed); // see the declaration
}
return;
}
@@ -1705,6 +2057,41 @@ void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
SwapChainSlot* slot = FindOrAdd(sc);
PublishAdapterOnce(sc);
// DXGI'S OWN COUNT OF THIS CHAIN'S PRESENTS, read here on the object the title passed
// (the same class of read as GetDesc above), BEFORE this present is forwarded: the
// value is therefore the number of presents completed before this one, and the
// delta from the previous hooked present on the same chain is 1 + whatever DXGI
// counted that this hook never saw -- a pacer presenting through a body the inline
// patches do not cover. A delta of exactly 1 every time says DXGI saw nothing more
// than we did. DXGI_PRESENT_TEST presents are already filtered above and do not
// move this counter (measured, #35), so they cannot read as unseen presents.
bool dxgiDelta = false;
uint8_t dxgiUnseenHere = 0;
if (slot != nullptr) {
UINT dxgiCount = 0;
const uint32_t epoch = g_dxgiEpoch.load(std::memory_order_relaxed);
if (SUCCEEDED(sc->GetLastPresentCount(&dxgiCount))) {
if (slot->haveDxgiCount && slot->dxgiEpoch == epoch) {
const uint32_t delta = dxgiCount - slot->lastDxgiCount;
dxgiDelta = true;
if (delta > 1u) {
g_dxgiUnseen.fetch_add(delta - 1u, std::memory_order_relaxed);
dxgiUnseenHere = fl::slseen::SaturateToByte(delta - 1u);
}
} else if (!slot->haveDxgiCount && g_state != nullptr &&
!g_dxgiBeforeHookPublished.exchange(true, std::memory_order_relaxed)) {
// The FIRST hooked present: DXGI's count is the presents that ran before
// this hook was in (fl_shm.h §dxgiPresentsBeforeHook). One store, once.
std::atomic_ref<uint32_t> before{g_state->dxgiPresentsBeforeHook};
before.store(dxgiCount, std::memory_order_relaxed);
}
slot->lastDxgiCount = dxgiCount;
slot->dxgiEpoch = epoch;
slot->haveDxgiCount = true;
g_dxgiSamples.fetch_add(1u, std::memory_order_relaxed);
}
}
FlFrameRecord rec{};
rec.qpc = static_cast<uint64_t>(qpc.QuadPart);
rec.frameIndex = g_frameIndex++;
@@ -1746,6 +2133,14 @@ void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
const uint16_t haveOutputRes = (rec.outputW != 0 && rec.outputH != 0) ? FL_MEASURED_OUTPUT_RES : 0u;
rec.measuredMask = static_cast<uint16_t>(haveOutputRes | FL_MEASURED_PRESENT_ARGS);
// The per-present form of the DXGI counter read above (fl_shm.h §dxgiUnseen). The
// bit says a delta EXISTED -- a zero under it is DXGI agreeing with this hook, not
// silence -- which is why the first present of a chain claims nothing.
if (dxgiDelta) {
rec.dxgiUnseen = dxgiUnseenHere;
rec.measuredMask = static_cast<uint16_t>(rec.measuredMask | FL_MEASURED_DXGI_PRESENTS);
}
// --- Upscaler identity, and the three states it must keep apart ----------
//
// The counter is CONSUMED here, once per present, so the record describes
@@ -1754,6 +2149,10 @@ void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
// after the user turned it off mid-session, which is precisely the
// mid-session settings change 03_METRICS §Upscaling segments on.
const uint32_t seen = g_slSeen.exchange(0, std::memory_order_acq_rel);
// The tag TYPES set since the last present, on any route. ALWAYS drained, like the
// AMD word below: a HUD-less tag is valid until the frame it was set for is
// presented, and a word that outlived that frame would mark the wrong present.
const uint32_t tagged = g_slTagTypes.exchange(0, std::memory_order_acq_rel);
// The AMD word and count, drained beside the Streamline word and for the same
// reason. ALWAYS drained, whether or not anything below reads them: a count that
@@ -1807,18 +2206,21 @@ void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
// it, the honest byte is "FSR, version not named" (fl_shm.h
// §FL_UPSCALER_FSR_UNVERSIONED): FSR3 would be right on every non-RDNA4
// machine and a fabrication on one, and UNKNOWN would print the very N/A
// this arm exists to remove.
rec.upscaler = g_ffxUpscaleLeaf.load(std::memory_order_relaxed) == fl::inventory::kFfxLeafMonolith + 1u
// this arm exists to remove. The FSR 3.0 HOST (ffx_fsr3_x64.dll, Cyberpunk's
// copy) hosts FSR 3.0 and nothing else, so it is FSR3 as a fact too.
const uint32_t src = g_ffxUpscaleLeaf.load(std::memory_order_relaxed);
rec.upscaler = src == fl::inventory::kFfxLeafMonolith + 1u || src == kFfxUpscaleSourceFsr3Host
? static_cast<uint8_t>(FL_UPSCALER_FSR3)
: static_cast<uint8_t>(FL_UPSCALER_FSR_UNVERSIONED);
} else {
// UNKNOWN, AND NEVER `NONE`. FL_UPSCALER_NONE means "a hook ran and
// there was genuinely no upscaler" -- the one state fl_shm.h allows
// to be aggregated as a negative. This writer hooks Streamline and the
// ffx-api leaves and nothing else, so an XeSS, NGX-direct or FSR 3.0
// (ffx_fsr3_x64.dll) title evaluates its upscaler somewhere we are not
// looking -- and so does an FSR title on a present that drained no
// dispatch, which under frame generation is every generated present.
// to be aggregated as a negative. This writer hooks Streamline, the
// ffx-api leaves and the FSR 3.0 host facade and nothing else, so an XeSS
// or NGX-direct title, or an FSR 3.0 title calling ffx_fsr3upscaler_x64.dll
// directly, evaluates its upscaler somewhere we are not looking -- and so
// does an FSR title on a present that drained no dispatch, which under
// frame generation is every generated present.
// Reporting NONE would turn "we do not cover that vendor" into a measured
// fact about the title. UNKNOWN says the true thing: our coverage is short.
//
@@ -2000,6 +2402,17 @@ void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
mode = FL_FG_FSR_FG;
} else if (evals != 0u) {
mode = FL_FG_DLSS_G;
} else if ((tagged & FL_SL_TAG_DLSSG_INPUTS) != 0u) {
// THE TAGS SAY IT, since 2026-09-05. A HUD-less or UI buffer tagged through
// Streamline since the last present is an input to DLSS Frame Generation and
// to nothing else the title evaluates through Streamline that generates
// frames (fl_shm.h §slTagCensus; the DLSS-G programming guide §5.0 requires
// them). Read off the argument of an API already hooked, on whichever of the
// three tag routes the title uses -- which is what kFeatureDLSS_G evaluations
// were supposed to give and gave on no measured title. IDENTITY ONLY: whether
// frames were generated is still the consumer's verdict from the COUNT, and a
// count of 1.0 beside this mark prints `none` (inputs fed, nothing generated).
mode = FL_FG_DLSS_G;
}
rec.fgMode = mode;
rec.measuredMask = static_cast<uint16_t>(rec.measuredMask | FL_MEASURED_FG);
@@ -2227,6 +2640,16 @@ DWORD WINAPI InitThread(LPVOID) noexcept {
std::atomic_ref<uint32_t> status{g_state->status};
// "Not read" until the first hooked present, so a title that never presents is
// distinguishable from one whose first present the hook was in for. BEFORE the
// present hooks go in: a title presenting every 8 ms had its first hooked present
// between the install and a store placed after it, and the sentinel overwrote the
// measurement (caught by ctest fl_guard [launch] on the first run).
{
std::atomic_ref<uint32_t> before{g_state->dxgiPresentsBeforeHook};
before.store(0xFFFFFFFFu, std::memory_order_relaxed);
}
if (MH_Initialize() != MH_OK || !InstallPresentHooks()) {
// Hooking failed, so nothing will ever be recorded. Staying at INIT says
// exactly that; READY would be a claim about a capture side that does not
@@ -2246,6 +2669,13 @@ DWORD WINAPI InitThread(LPVOID) noexcept {
std::atomic_ref<uint32_t> hooks{g_state->hooksInstalledMask};
hooks.fetch_or(static_cast<uint32_t>(FL_HOOK_PRESENT), std::memory_order_relaxed);
// The watchdog's wake, created BEFORE the loader hook that signals it and before
// the thread that waits on it. Then the LoadLibrary detour -- non-fatal: without
// it the 1 Hz tick and the host's scan are the backstops, and bit 15 says so.
g_watchdogWake = CreateEventW(nullptr, FALSE, FALSE, nullptr);
InstallLoaderHook();
PublishLoaderWords();
status.store(FL_STATUS_READY, std::memory_order_release);
// AFTER the hooks, deliberately. The watchdog's only job is to take them out
+131 -7
View File
@@ -89,6 +89,12 @@ enum FlStatus : uint32_t {
FL_STATUS_READY = 1,
FL_STATUS_SELF_DISABLED = 2, // 3 hook faults; see 17_HOOK_ENGINE §Fault policy
FL_STATUS_UNHOOKED = 3,
// A module whose base name matches the anti-cheat floor compiled into the
// Overlay was loaded mid-session, and the Overlay stopped ITSELF -- the
// in-process half of 19_SAFETY §During a session (§S6, built 2026-09-06 as
// P1 item 1). FlWriterState::earlyStopFamily says which family. The host's
// 30 s scan remains the backstop and the only half that runs the signer tier.
FL_STATUS_STOPPED_BLOCKLISTED = 4,
};
// bits in FlWriterState::apiMask and FlFrameRecord::api
@@ -433,6 +439,52 @@ constexpr uint32_t FL_CENSUS_UPSCALER_FAMILIES = FL_CENSUS_SL_INTERPOSER | FL_CE
static_assert((FL_CENSUS_FG_FAMILIES & FL_CENSUS_UPSCALER_FAMILIES) == 0u, "a runtime is one kind or the other");
static_assert(((FL_CENSUS_FG_FAMILIES | FL_CENSUS_UPSCALER_FAMILIES) & FL_CENSUS_RAN) == 0u, "RAN is not a family");
// ---------------------------------------------------------------------------
// FlWriterState::slTagCensus — WHICH Streamline buffer types the title tagged, on
// WHICH route (2026-09-05, 20_OPEN_QUESTIONS §H5).
//
// WHY. The two global-tag detours (slSetTag, slSetTagForFrame) and the local walk
// through slEvaluateFeature's inputs read one tag type -- kBufferTypeScalingInputColor,
// for renderW/H -- and dropped every other tag on the floor. Streamline's DLSS-G
// programming guide §5.0 says a title running DLSS Frame Generation MUST tag the
// HUD-less colour and UI buffers every frame through exactly those calls; a title
// running super-resolution alone never tags them (they are inputs to nothing else the
// title evaluates through Streamline except Reflex 2's late warp, which generates no
// frames). So the types a title tags are a per-frame statement, from an argument of
// an API already hooked (CLAUDE.md rule 4), of WHICH Streamline feature it is
// feeding -- which is the identity `kFeatureDLSS_G` evaluations were supposed to
// give and never did on any measured title. The session word here says which types
// arrived on which route; the per-present half lands in fgMode (FL_FG_DLSS_G on a
// present that drained a HUD-less or UI tag) and the consumer combines it with the
// COUNT, which alone decides `none`.
//
// OR-only, watchdog-published from a process-local word, like runtimeCensus. Nine
// type bits per route, three routes. Took reserved[0] additively (no layout bump):
// a writer from before it is refused by the build-id handshake before any reader
// could see a 0 here, and 0 means "no tag of any type was seen".
// ---------------------------------------------------------------------------
enum FlSlTagType : uint32_t {
FL_SL_TAG_DEPTH = 1u << 0, // kBufferTypeDepth
FL_SL_TAG_MOTION_VECTORS = 1u << 1, // kBufferTypeMotionVectors
FL_SL_TAG_HUDLESS = 1u << 2, // kBufferTypeHUDLessColor -- a DLSS-G input
FL_SL_TAG_SCALING_INPUT = 1u << 3, // kBufferTypeScalingInputColor -- renderW/H's source
FL_SL_TAG_SCALING_OUTPUT = 1u << 4, // kBufferTypeScalingOutputColor
FL_SL_TAG_UI_COLOR_ALPHA = 1u << 5, // kBufferTypeUIColorAndAlpha -- a DLSS-G input
FL_SL_TAG_UI_ALPHA = 1u << 6, // kBufferTypeUIAlpha -- a DLSS-G input (newer SDKs)
FL_SL_TAG_BACKBUFFER = 1u << 7, // kBufferTypeBackbuffer
FL_SL_TAG_OTHER = 1u << 8, // any other BufferType
};
constexpr uint32_t FL_SL_TAG_TYPE_BITS = 9;
constexpr uint32_t FL_SL_TAG_TYPE_MASK = (1u << FL_SL_TAG_TYPE_BITS) - 1u;
// The routes, as bit-field shifts into slTagCensus.
constexpr uint32_t FL_SL_TAG_ROUTE_GLOBAL = 0; // slSetTag
constexpr uint32_t FL_SL_TAG_ROUTE_FRAME = FL_SL_TAG_TYPE_BITS; // slSetTagForFrame
constexpr uint32_t FL_SL_TAG_ROUTE_LOCAL = 2u * FL_SL_TAG_TYPE_BITS; // slEvaluateFeature's inputs
// The DLSS-G-only inputs: tagged, they say the title is feeding frame generation.
constexpr uint32_t FL_SL_TAG_DLSSG_INPUTS = FL_SL_TAG_HUDLESS | FL_SL_TAG_UI_COLOR_ALPHA | FL_SL_TAG_UI_ALPHA;
static_assert(3u * FL_SL_TAG_TYPE_BITS <= 32u, "three routes of type bits must fit the census word");
static_assert((FL_SL_TAG_DLSSG_INPUTS & ~FL_SL_TAG_TYPE_MASK) == 0u, "the DLSS-G inputs are type bits");
// bits in FlFrameRecord::measuredMask — which fields were MEASURED this frame.
//
// The zero-defaults elsewhere in the record are affirmative negatives:
@@ -522,13 +574,20 @@ enum FlMeasured : uint16_t {
// must be able to say so.
FL_MEASURED_FG_COUNTS = 1u << 10,
// bits 11-15 reserved. Writers leave them zero; readers must IGNORE them
// dxgiUnseen @52 (2026-09-05, 20_OPEN_QUESTIONS §H5 row P1-DXGI): the present hook
// read IDXGISwapChain::GetLastPresentCount at this present AND at the previous
// hooked present on the same chain, so the byte is a measurement -- a zero
// included. Clear on the first hooked present of every chain, where there is no
// previous value to difference against, and whenever the read failed.
FL_MEASURED_DXGI_PRESENTS = 1u << 11,
// bits 12-15 reserved. Writers leave them zero; readers must IGNORE them
// rather than validate them as zero.
//
// BE PRECISE ABOUT WHAT THAT BUYS, because the tempting claim is false: it
// does NOT mean a future field can be added without a layout bump. Any new
// field also needs a byte, and every byte of this record is allocated except
// `reserved` @52 -- and FlShmHandshake::recordSize plus the layout version are
// `reserved` @53..55 -- and FlShmHandshake::recordSize plus the layout version are
// compared before a reader looks at anything, so an old reader refuses a new
// writer outright and never gets as far as an unknown bit. What the reserve
// actually buys is that existing offsets do not move, which keeps the diff,
@@ -636,7 +695,52 @@ struct alignas(64) FlWriterState {
// before any reader could see a 0 here.
uint32_t runtimeCensus; // @40
uint32_t reserved[5]; // @44..63 must be zero; room for additive fields
// FlSlTagType bits per route (see the enum). Watchdog-published, OR-only. Took
// reserved[0] on 2026-09-05 the way runtimeCensus took it on 2026-09-03: additive,
// no layout bump, refused-before-read by the build-id handshake.
uint32_t slTagCensus; // @44
// DXGI'S OWN PRESENT COUNTER AGAINST THIS HOOK'S, on the hooked swapchain(s)
// (2026-09-05, 20_OPEN_QUESTIONS §H5 case 3). On every present the hook sees it
// reads IDXGISwapChain::GetLastPresentCount on the object the title passed -- the
// same class of read as GetDesc in FindOrAdd -- and compares it with the value at
// the previous hooked present on the same chain. Exactly one present (the previous
// hooked one) is expected in between; every present beyond that is one DXGI
// counted and this hook did not. A frame-generation pacer that presents on this
// chain through a body the inline patches do not cover shows up here; one that
// presents below DXGI, or on another object, does not. Hook-local counters,
// watchdog-published (the region-2 cache-line rule above). Took reserved[0..1],
// additive, no layout bump.
uint32_t dxgiPresentsUnseen; // @48 presents DXGI counted between two hooked presents, beyond the one seen
uint32_t dxgiPresentSamples; // @52 hooked presents on which the counter was read
// THE LoadLibrary DETOUR'S TWO WORDS (2026-09-06, P1 item 1; 17_HOOK_ENGINE §DLL
// entry step 3). The Overlay detours kernelbase!LoadLibraryExW -- the funnel every
// LoadLibrary* variant reaches -- and, never inline (§H2: MinHook suspends threads
// to patch, and the caller may hold the loader lock), only records what loaded and
// wakes the watchdog. Took reserved[0]; additive, no layout bump.
//
// loaderSignals: bit 15 = the detour is installed; bits 0..14 = how many times a
// module the hook inventory or the runtime census names was loaded and the
// watchdog was woken for it (saturating). A count of 0 with bit 15 set is a title
// that loaded every vendor module before we attached, which is the common case.
uint16_t loaderSignals; // @56
// earlyStopFamily: 0 = none; else the 1-based index, among the compiled floor's
// MODULE families in rules order, of the family whose value matched a module
// loaded mid-session. Set once (the first match wins) and status goes to
// FL_STATUS_STOPPED_BLOCKLISTED on the next present or watchdog wake.
uint16_t earlyStopFamily; // @58
// PRESENTS BEFORE THE FIRST HOOKED ONE (2026-09-06, P1 item 2 -- launch mode's
// own cost meter; 20_OPEN_QUESTIONS §S1 / §S13(c)). IDXGISwapChain::GetLastPresentCount
// as read at the FIRST present this hook saw, on the first chain it saw: DXGI's
// count of presents that chain had completed before we were there. 0 means the hook
// was in before the title's first present on that chain; N means N presents ran
// unhooked, which is the number §S1 said nobody had. 0xFFFFFFFF = not read (set at
// init; a title that never presents keeps it). Took the LAST reserved word --
// additive, no layout bump -- and the writer state now has NO slack: the next
// additive field is a layout bump.
uint32_t dxgiPresentsBeforeHook; // @60
// NOTE: there is deliberately no droppedRecords here. The writer has no
// reader index and cannot know whether the slot it overwrites was ever
@@ -767,7 +871,22 @@ struct alignas(64) FlFrameRecord {
// and layoutVersion are compared before a reader looks at anything, so an old
// reader refuses a new writer and never reaches an unknown field. What it buys
// is that existing offsets do not move, which keeps the next diff small.
uint32_t reserved; // @52
// @52 -- DXGI'S OWN COUNT OF THIS CHAIN'S PRESENTS SINCE THE PREVIOUS HOOKED ONE,
// beyond that one (2026-09-05, 20_OPEN_QUESTIONS §H5 row P1-DXGI). The per-present
// form of FlWriterState.dxgiPresentsUnseen: the delta of GetLastPresentCount between
// two consecutive hooked presents on the same chain, minus the one present the hook
// saw. Measured 2.90 and 2.95 per hooked present on Dying Light: The Beast
// (Streamline 2.8.0, DLSS Frame Generation x4) and 0 on every other title (Streamline
// 2.7.3 and 2.10.3 present their generated frames through the patched bodies) -- so
// on that shape the generated presents ARE DXGI presents, reaching a body the inline
// patches do not cover, and the consumer counts Displayed = hooked + this, labelled
// DXGI-COUNTED. Per record rather than per session so the consumer's uniformity
// buckets see it. SATURATES AT 255: a NUMERATOR, so a wrap would read low rather than
// high, but 255 is still a sentinel the consumer refuses rather than a count. Took the
// first byte of v3's reserved word; additive, no offset moved, no layout bump.
uint8_t dxgiUnseen; // @52
uint8_t reserved[3]; // @53..55 MUST BE ZERO
// Seqlock counter. Monotonic per slot and NEVER reset, so a full lap of
// the ring always changes it — otherwise a reader stalled exactly one lap
@@ -826,7 +945,12 @@ static_assert(offsetof(FlWriterState, hooksInstalledMask) == 28);
static_assert(offsetof(FlWriterState, rtStateObjectsCreated) == 32);
static_assert(offsetof(FlWriterState, rasterPsoCreated) == 36);
static_assert(offsetof(FlWriterState, runtimeCensus) == 40);
static_assert(offsetof(FlWriterState, reserved) == 44);
static_assert(offsetof(FlWriterState, slTagCensus) == 44);
static_assert(offsetof(FlWriterState, dxgiPresentsUnseen) == 48);
static_assert(offsetof(FlWriterState, dxgiPresentSamples) == 52);
static_assert(offsetof(FlWriterState, loaderSignals) == 56);
static_assert(offsetof(FlWriterState, earlyStopFamily) == 58);
static_assert(offsetof(FlWriterState, dxgiPresentsBeforeHook) == 60);
static_assert(offsetof(FlControlBlock, pauseRequested) == 0);
static_assert(offsetof(FlControlBlock, unhookRequested) == 4);
@@ -856,7 +980,8 @@ static_assert(offsetof(FlFrameRecord, upscalerSharpness) == 42);
static_assert(offsetof(FlFrameRecord, fgEvaluations) == 43);
static_assert(offsetof(FlFrameRecord, vramUsedMb) == 44);
static_assert(offsetof(FlFrameRecord, reflexLatencyUs) == 48);
static_assert(offsetof(FlFrameRecord, reserved) == 52);
static_assert(offsetof(FlFrameRecord, dxgiUnseen) == 52);
static_assert(offsetof(FlFrameRecord, reserved) == 53);
static_assert(offsetof(FlFrameRecord, seq) == 56);
static_assert(offsetof(FlFrameRecord, swapchainId) == 60);
@@ -872,7 +997,6 @@ static_assert(offsetof(FlFrameRecord, swapchainId) == 60, "07_IPC pins the paylo
static_assert(offsetof(FlFrameRecord, qpc) % 8 == 0);
static_assert(offsetof(FlFrameRecord, measuredMask) % 2 == 0);
static_assert(offsetof(FlFrameRecord, vramUsedMb) % 4 == 0);
static_assert(offsetof(FlFrameRecord, reserved) % 4 == 0);
static_assert(offsetof(FlFrameRecord, seq) % 4 == 0);
// The regions must not overlap, and the ring must stay 64-aligned.
@@ -0,0 +1,180 @@
// The capture side's HOST half of the shared-memory contract: create the one
// ring a process may carry, and publish the handshake a reader validates first.
//
// Header-only and shared by the two capture sides -- the injected Overlay and
// the Vulkan layer -- because 07_IPC says ONE ring per process, named
// Local\FrameLedger.Ring.<pid>, with ONE layout, ONE build id and ONE security
// descriptor, and two copies of that are two places for it to drift. It lived in
// FrameLedger.Overlay/src/dllmain.cpp until 2026-09-06 (P1 item 3), when the
// layer gained vkQueuePresentKHR and needed exactly the same thing.
//
// Not a hook path: this runs once, at init, on whichever thread creates the
// ring. It may allocate (LocalAlloc inside the SDDL conversion) and it may fail
// -- and every failure returns false, so the caller stays inert rather than
// sharing a ring it does not own.
//
// WHO OWNS THE RING WHEN BOTH SIDES ARE IN ONE PROCESS. A Vulkan title launched
// through the host has the layer mapped by the loader and could also receive the
// Overlay if the guard injected it; whichever creates the mapping FIRST owns it,
// and the other sees ERROR_ALREADY_EXISTS here and stays inert. That is the same
// rule the Overlay always had for a pre-existing mapping under its own pid --
// "either a stale object or another writer: refuse rather than share" -- and it
// is why the guard does not inject a Vulkan-only presenter at all
// (fl_guard.cpp, Reason::kTargetIsVulkanLayered).
#ifndef FRAMELEDGER_FL_SHM_HOST_H
#define FRAMELEDGER_FL_SHM_HOST_H
#include <windows.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <sddl.h>
#include "fl_shm.h"
#ifndef FL_BUILD_ID
#error "FL_BUILD_ID must be defined (FrameLedger.Shm's INTERFACE compile definition)"
#endif
namespace fl::shmhost {
// The mapping is created with a DACL granting ONLY the current user's SID, and
// lives in the session-scoped Local\ namespace (docs/07_IPC.md §Security). No
// Global\ object: it would need admin and would be visible across sessions for
// no benefit.
//
// Returns false rather than falling back to a default DACL. A mapping the whole
// machine can write is not a degraded version of this one -- the Agent's control
// block is in it, and unhookRequested is the safety stop.
inline bool BuildUserOnlySecurity(SECURITY_ATTRIBUTES& sa, PSECURITY_DESCRIPTOR& sd) noexcept {
sd = nullptr;
HANDLE token = nullptr;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
return false;
}
unsigned char buffer[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE]{};
DWORD got = 0;
const BOOL ok = GetTokenInformation(token, TokenUser, buffer, sizeof(buffer), &got);
CloseHandle(token);
if (!ok) {
return false;
}
LPWSTR sidText = nullptr;
const auto* user = reinterpret_cast<const TOKEN_USER*>(buffer);
if (!ConvertSidToStringSidW(user->User.Sid, &sidText)) {
return false;
}
// D:P = a protected DACL, so nothing is inherited in. One ACE, generic all,
// for us alone.
wchar_t sddl[256]{};
const int n = _snwprintf_s(sddl, _TRUNCATE, L"D:P(A;;GA;;;%ls)", sidText);
LocalFree(sidText);
if (n < 0) {
return false;
}
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, SDDL_REVISION_1, &sd, nullptr)) {
return false;
}
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = sd;
sa.bInheritHandle = FALSE;
return true;
}
// Local\FrameLedger.Ring.<pid>. Deliberately plain and identifiable: 19_SAFETY
// forbids obfuscated object names, because being visible to anti-cheat is the
// whole design posture.
inline bool MakeRingName(wchar_t* out, std::size_t cap, DWORD pid) noexcept {
return _snwprintf_s(out, cap, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", pid) >= 0;
}
// Create and map this process's ring. On success `mapping` and `base` are set;
// on any failure both stay null and nothing is left open.
inline bool CreateRingMapping(HANDLE& mapping, void*& base) noexcept {
mapping = nullptr;
base = nullptr;
SECURITY_ATTRIBUTES sa{};
PSECURITY_DESCRIPTOR sd = nullptr;
if (!BuildUserOnlySecurity(sa, sd)) {
return false;
}
wchar_t name[128]{};
if (!MakeRingName(name, 128, GetCurrentProcessId())) {
LocalFree(sd);
return false;
}
const std::size_t bytes = fl::FlShmSizeForCapacity(FL_SHM_DEFAULT_CAPACITY);
HANDLE h = CreateFileMappingW(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, static_cast<DWORD>(bytes >> 32),
static_cast<DWORD>(bytes & 0xFFFFFFFFu), name);
const DWORD err = GetLastError();
LocalFree(sd);
if (h == nullptr) {
return false;
}
// A pre-existing mapping under our own pid is not a mapping we understand:
// either a stale object or another writer. Refuse rather than share a ring
// with an unknown producer (see the file header for the two-capture-sides case).
if (err == ERROR_ALREADY_EXISTS) {
CloseHandle(h);
return false;
}
void* view = MapViewOfFile(h, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, bytes);
if (view == nullptr) {
CloseHandle(h);
return false;
}
mapping = h;
base = view;
return true;
}
// Write-once at init, per docs/07_IPC.md §A + B. adapterLuid is deliberately
// left 0 = "not yet known": on the Overlay this runs two steps before any
// graphics module is resolved, and our own dummy device's adapter is not the
// game's (#36); on the layer there is no adapter LUID to publish at all.
inline void PublishHandshake(void* base) noexcept {
auto* h = reinterpret_cast<FlShmHandshake*>(static_cast<unsigned char*>(base) + FL_SHM_HANDSHAKE_OFFSET);
h->recordSize = sizeof(FlFrameRecord);
h->capacity = FL_SHM_DEFAULT_CAPACITY;
h->pid = GetCurrentProcessId();
// FL_BUILD_ID comes from git describe at configure time (FrameLedger.Shm's
// CMakeLists). It had no producer at all until #36; without one the Agent's
// refuse-to-attach-on-mismatch compares "" with "" forever.
const char* build = FL_BUILD_ID;
std::size_t i = 0;
for (; i + 1 < sizeof(h->buildId) && build[i] != '\0'; ++i) {
h->buildId[i] = build[i];
}
h->buildId[i] = '\0';
LARGE_INTEGER qpc{};
QueryPerformanceCounter(&qpc);
h->qpcEpoch = static_cast<std::uint64_t>(qpc.QuadPart);
h->adapterLuid = 0;
// layoutVersion LAST, with a release fence in front of it. It is the field a
// reader validates first, so it must not become visible before the fields it
// vouches for. A reader that saw the version while capacity was still zero
// would compute a ring of no slots and read garbage.
std::atomic_thread_fence(std::memory_order_release);
std::atomic_ref<std::uint32_t> version{h->layoutVersion};
version.store(FL_SHM_LAYOUT_VERSION, std::memory_order_release);
}
} // namespace fl::shmhost
#endif // FRAMELEDGER_FL_SHM_HOST_H
@@ -30,6 +30,24 @@ target_link_libraries(FrameLedger.VkLayer PRIVATE
add_dependencies(FrameLedger.VkLayer fl_ac_floor_gen)
set_target_properties(FrameLedger.VkLayer PROPERTIES OUTPUT_NAME "FrameLedger.VkLayer")
# TEST-ONLY flavour: the same sources with the supervision deadline shortened
# from 65 s to 1.5 s, so ctest fl_vklayer can prove §S2 part three -- the
# in-layer stop when guardTicks stops advancing -- in seconds rather than
# minutes. Never shipped: no version resource, no manifest, a different file
# name, and 12_BUILD publishes only what the App/Agent projects stage. The
# shipped DLL keeps FL_GUARD_TICK_DEADLINE_MS, the one number 07_IPC pins.
add_library(fl_vklayer_shortdeadline SHARED
src/layer.cpp
../FrameLedger.Injector/src/fl_ac_rules.cpp
FrameLedger.VkLayer.def
)
target_include_directories(fl_vklayer_shortdeadline PRIVATE ../FrameLedger.Injector/include)
target_link_libraries(fl_vklayer_shortdeadline PRIVATE
FrameLedger.Shm fl_native_flags fl_hostile_env_flags fl_vulkan_headers fl_jsmn Shell32 Ole32 fl_ac_floor)
add_dependencies(fl_vklayer_shortdeadline fl_ac_floor_gen)
target_compile_definitions(fl_vklayer_shortdeadline PRIVATE FL_VKLAYER_TICK_DEADLINE_MS=1500u)
set_target_properties(fl_vklayer_shortdeadline PROPERTIES OUTPUT_NAME "FrameLedger.VkLayer.shortdeadline")
# Same requirement as the Overlay, and arguably sharper here: an implicit layer
# is machine-wide, so it can appear inside processes the user never associated
# with FrameLedger. It had better say who it is (docs/19_SAFETY).
+376 -4
View File
@@ -46,11 +46,14 @@
#include <vulkan/vk_layer.h>
#include <vulkan/vulkan.h>
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fl_ac_rules.h>
#include <fl_ring.h>
#include <fl_shm.h>
#include <fl_shm_host.h>
#include <psapi.h>
namespace fl::vklayer {
@@ -256,7 +259,356 @@ bool MustStayInert() noexcept {
}
// ---------------------------------------------------------------------------
// Loader interface. Everything forwards; nothing is observed.
// The capture side (P1 item 3): the ring, the present record, the stop.
//
// Created at the first vkCreateDevice of an ADMITTED process -- not at load, not
// at vkCreateInstance -- so a process the gates refused never has a mapping
// with its pid on it. Init is not a hook path; the present hook is, and it
// follows the Overlay's rules: SEH-guarded, allocation-free, lock-free, no
// logging, one record, forward.
// ---------------------------------------------------------------------------
bool ThisProcessIsEnabledCached();
// The supervision deadline. FL_VKLAYER_TICK_DEADLINE_MS exists so a TEST-ONLY
// flavour of this DLL (fl_vklayer_shortdeadline, never shipped) can prove the
// stop within seconds; the shipped layer uses the one number 07_IPC pins, the
// same the Overlay uses.
#ifndef FL_VKLAYER_TICK_DEADLINE_MS
#define FL_VKLAYER_TICK_DEADLINE_MS FL_GUARD_TICK_DEADLINE_MS
#endif
constexpr ULONGLONG kTickDeadlineMs = FL_VKLAYER_TICK_DEADLINE_MS;
HANDLE g_mapping = nullptr;
void* g_base = nullptr;
FlWriterState* g_state = nullptr;
FlControlBlock* g_control = nullptr;
fl::RingWriter g_writer;
std::atomic<uint32_t> g_observing{0};
std::atomic<uint32_t> g_captureState{0}; // 0 = not tried, 1 = live, 2 = failed (inert for good)
std::atomic<uint32_t> g_frameIndex{0};
std::atomic<uint32_t> g_lastTicks{0};
std::atomic<ULONGLONG> g_lastTickAt{0};
// Which device a queue belongs to is answered by the dispatch key: the loader
// gives a VkDevice and every VkQueue created from it the SAME first-pointer
// (the dispatch table), which is how every layer keys its per-device state.
inline void* DispatchKey(const void* dispatchable) noexcept {
return *reinterpret_cast<void* const*>(dispatchable);
}
struct DeviceSlot {
void* key = nullptr;
PFN_vkQueuePresentKHR present = nullptr;
PFN_vkCreateSwapchainKHR createSwapchain = nullptr;
PFN_vkDestroySwapchainKHR destroySwapchain = nullptr;
};
constexpr size_t kMaxDevices = 8;
DeviceSlot g_devices[kMaxDevices];
std::atomic<uint32_t> g_deviceCount{0};
bool HasDevice(void* key) noexcept {
const uint32_t n = g_deviceCount.load(std::memory_order_acquire);
for (uint32_t i = 0; i < n && i < kMaxDevices; ++i) {
if (g_devices[i].key == key) {
return true;
}
}
return false;
}
const DeviceSlot* FindDevice(void* key) noexcept {
const uint32_t n = g_deviceCount.load(std::memory_order_acquire);
for (uint32_t i = 0; i < n && i < kMaxDevices; ++i) {
if (g_devices[i].key == key) {
return &g_devices[i];
}
}
// A queue whose device we never registered (more than kMaxDevices, or a
// device created before the gates admitted us): forward through the first
// device's next pointer rather than through nothing.
return n != 0 ? &g_devices[0] : nullptr;
}
// Per-swapchain output size, keyed by the non-dispatchable handle; id 0 stays
// "unidentified" (fl_shm.h), exactly as the Overlay's table does.
struct SwapchainSlot {
std::atomic<uint64_t> handle{0};
uint32_t id = 0;
uint16_t w = 0;
uint16_t h = 0;
};
constexpr size_t kMaxSwapchains = 16;
SwapchainSlot g_swapchains[kMaxSwapchains];
std::atomic<uint32_t> g_nextSwapchainId{1};
const SwapchainSlot* FindSwapchain(VkSwapchainKHR sc) noexcept {
const uint64_t key = reinterpret_cast<uint64_t>(sc);
for (size_t i = 0; i < kMaxSwapchains; ++i) {
if (g_swapchains[i].handle.load(std::memory_order_acquire) == key) {
return &g_swapchains[i];
}
}
return nullptr;
}
void RememberSwapchain(VkSwapchainKHR sc, VkExtent2D extent) noexcept {
const uint64_t key = reinterpret_cast<uint64_t>(sc);
for (size_t i = 0; i < kMaxSwapchains; ++i) {
uint64_t none = 0;
if (g_swapchains[i].handle.compare_exchange_strong(none, ~0ull, std::memory_order_acq_rel)) {
g_swapchains[i].id = g_nextSwapchainId.fetch_add(1u, std::memory_order_relaxed);
g_swapchains[i].w = static_cast<uint16_t>(extent.width > 0xFFFFu ? 0u : extent.width);
g_swapchains[i].h = static_cast<uint16_t>(extent.height > 0xFFFFu ? 0u : extent.height);
g_swapchains[i].handle.store(key, std::memory_order_release); // visible LAST
return;
}
}
// Full: the present will carry id 0 = unidentified, never a wrong id.
}
void ForgetSwapchain(VkSwapchainKHR sc) noexcept {
const uint64_t key = reinterpret_cast<uint64_t>(sc);
for (size_t i = 0; i < kMaxSwapchains; ++i) {
uint64_t have = key;
if (g_swapchains[i].handle.compare_exchange_strong(have, 0ull, std::memory_order_acq_rel)) {
return;
}
}
}
// "Stops" = passthrough forever, with the reason on the mapping. There is no
// unhook: the loader owns the chain, and the Overlay's MH_DisableHook has no
// equivalent here. First reason wins, exactly as in the Overlay.
void StopObserving(uint32_t reason) noexcept {
uint32_t live = 1;
if (!g_observing.compare_exchange_strong(live, 0u, std::memory_order_acq_rel)) {
return;
}
if (g_state != nullptr) {
std::atomic_ref<uint32_t> status{g_state->status};
status.store(reason, std::memory_order_release);
}
}
LONG FlFilter(DWORD code) noexcept {
if (code == EXCEPTION_BREAKPOINT || code == EXCEPTION_SINGLE_STEP) {
return EXCEPTION_CONTINUE_SEARCH;
}
return EXCEPTION_EXECUTE_HANDLER;
}
void NoteFault() noexcept {
if (g_state == nullptr) {
return;
}
std::atomic_ref<uint32_t> faults{g_state->faultCount};
if (faults.fetch_add(1, std::memory_order_acq_rel) + 1 >= 3) {
StopObserving(fl::FL_STATUS_SELF_DISABLED); // 17_HOOK_ENGINE §Fault policy: three faults, dormant
}
}
// The present-path decision. Same order and same polarity as the Overlay's
// MayObserve, minus the LoadLibrary detour it has no equivalent of -- plus the
// supervision check that the Overlay runs on its watchdog and this layer cannot
// (§S2 part three). guardTicks counts COMPLETED guard evaluations, not seconds;
// "never advanced" and "stopped advancing" are the same state, and the clock
// starts when the mapping is published.
bool MayObserve() noexcept {
if (g_observing.load(std::memory_order_acquire) == 0u) {
return false;
}
if (g_control == nullptr) {
return true;
}
std::atomic_ref<uint32_t> unhook{g_control->unhookRequested};
if (unhook.load(std::memory_order_acquire) != 0u) {
StopObserving(fl::FL_STATUS_UNHOOKED);
return false;
}
std::atomic_ref<uint32_t> ticks{g_control->guardTicks};
const uint32_t now = ticks.load(std::memory_order_acquire);
const ULONGLONG t = GetTickCount64();
if (now != g_lastTicks.load(std::memory_order_relaxed)) {
g_lastTicks.store(now, std::memory_order_relaxed);
g_lastTickAt.store(t, std::memory_order_relaxed);
} else if (t - g_lastTickAt.load(std::memory_order_relaxed) >= kTickDeadlineMs) {
StopObserving(fl::FL_STATUS_UNHOOKED);
return false;
}
std::atomic_ref<uint32_t> paused{g_control->pauseRequested};
return paused.load(std::memory_order_relaxed) == 0u;
}
// Once, on the first admitted vkCreateDevice. Failure -- most likely the ring
// already existing because an Overlay got there first -- is final: the layer
// forwards and observes nothing, which is what an un-owned ring requires.
bool EnsureCapture() noexcept {
uint32_t expected = 0;
if (!g_captureState.compare_exchange_strong(expected, 3u, std::memory_order_acq_rel)) {
// 3 = in progress on another thread; treat as not yet live.
return g_captureState.load(std::memory_order_acquire) == 1u;
}
if (!fl::shmhost::CreateRingMapping(g_mapping, g_base)) {
g_captureState.store(2u, std::memory_order_release);
return false;
}
fl::shmhost::PublishHandshake(g_base);
g_state = reinterpret_cast<FlWriterState*>(static_cast<unsigned char*>(g_base) + FL_SHM_WRITER_OFFSET);
g_control = reinterpret_cast<FlControlBlock*>(static_cast<unsigned char*>(g_base) + FL_SHM_CONTROL_OFFSET);
if (!g_writer.Init(g_base, FL_SHM_DEFAULT_CAPACITY)) {
g_captureState.store(2u, std::memory_order_release);
return false;
}
g_lastTicks.store(0, std::memory_order_relaxed);
g_lastTickAt.store(GetTickCount64(), std::memory_order_relaxed);
{
std::atomic_ref<uint32_t> api{g_state->apiMask};
api.fetch_or(1u << fl::FL_API_VULKAN, std::memory_order_relaxed);
std::atomic_ref<uint32_t> hooks{g_state->hooksInstalledMask};
hooks.fetch_or(static_cast<uint32_t>(fl::FL_HOOK_PRESENT), std::memory_order_relaxed);
// No DXGI counter exists on this path; the word stays "not read".
std::atomic_ref<uint32_t> before{g_state->dxgiPresentsBeforeHook};
before.store(0xFFFFFFFFu, std::memory_order_relaxed);
std::atomic_ref<uint32_t> status{g_state->status};
status.store(fl::FL_STATUS_READY, std::memory_order_release);
}
g_observing.store(1u, std::memory_order_release);
g_captureState.store(1u, std::memory_order_release);
return true;
}
// RULE 4: `pPresentInfo` is the argument of the API we intercept, and the only
// thing read from it is which swapchain(s) it names -- to look up an output size
// WE recorded at creation. Nothing of the game's is dereferenced beyond that.
void RecordPresent(const VkPresentInfoKHR* info) noexcept {
if (!MayObserve()) {
return;
}
LARGE_INTEGER qpc{};
QueryPerformanceCounter(&qpc);
const SwapchainSlot* slot = nullptr;
if (info != nullptr && info->swapchainCount > 0u && info->pSwapchains != nullptr) {
slot = FindSwapchain(info->pSwapchains[0]);
}
FlFrameRecord rec{};
rec.qpc = static_cast<uint64_t>(qpc.QuadPart);
rec.frameIndex = g_frameIndex.fetch_add(1u, std::memory_order_relaxed);
rec.api = static_cast<uint8_t>(fl::FL_API_VULKAN);
if (slot != nullptr) {
rec.swapchainId = slot->id;
rec.outputW = slot->w;
rec.outputH = slot->h;
}
// vkQueuePresentKHR carries no sync interval and no present flags, which is
// exactly why FL_MEASURED_PRESENT_ARGS exists rather than being assumed
// (fl_shm.h); only the output size may be claimed, and only when there is one.
rec.measuredMask = (rec.outputW != 0u && rec.outputH != 0u) ? fl::FL_MEASURED_OUTPUT_RES : 0u;
g_writer.Publish(rec);
}
// SEH around OUR code only, never around the forward (the Overlay's rule: a
// game's fault inside the next layer must not be counted as ours). A separate
// function because __try cannot share a frame with objects that need unwinding.
void RecordPresentGuarded(const VkPresentInfoKHR* info) noexcept {
__try {
RecordPresent(info);
} __except (FlFilter(GetExceptionCode())) {
NoteFault();
}
}
VKAPI_ATTR VkResult VKAPI_CALL QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) {
const DeviceSlot* d = (queue != nullptr) ? FindDevice(DispatchKey(queue)) : nullptr;
RecordPresentGuarded(pPresentInfo);
if (d == nullptr || d->present == nullptr) {
return VK_ERROR_DEVICE_LOST; // unreachable by construction: we only hand out this hook for registered
// devices
}
return d->present(queue, pPresentInfo);
}
VKAPI_ATTR VkResult VKAPI_CALL CreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) {
const DeviceSlot* d = (device != nullptr) ? FindDevice(DispatchKey(device)) : nullptr;
if (d == nullptr || d->createSwapchain == nullptr) {
return VK_ERROR_DEVICE_LOST;
}
const VkResult r = d->createSwapchain(device, pCreateInfo, pAllocator, pSwapchain);
if (r == VK_SUCCESS && pCreateInfo != nullptr && pSwapchain != nullptr && *pSwapchain != VK_NULL_HANDLE) {
RememberSwapchain(*pSwapchain, pCreateInfo->imageExtent); // rule 4: the API's own argument
}
return r;
}
VKAPI_ATTR void VKAPI_CALL DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
const VkAllocationCallbacks* pAllocator) {
if (swapchain != VK_NULL_HANDLE) {
ForgetSwapchain(swapchain);
}
const DeviceSlot* d = (device != nullptr) ? FindDevice(DispatchKey(device)) : nullptr;
if (d != nullptr && d->destroySwapchain != nullptr) {
d->destroySwapchain(device, swapchain, pAllocator);
}
}
// After the next layer's vkCreateDevice succeeded in an admitted process: the
// ring (once) and this device's next-pointers, resolved through the chain's own
// GetDeviceProcAddr so we call whatever sits below us and never the loader's
// trampoline for ourselves.
void RegisterDevice(VkDevice device) noexcept {
if (device == nullptr || g_nextGetDeviceProcAddr == nullptr || HasDevice(DispatchKey(device))) {
return;
}
// THE NEXT POINTERS FIRST, UNCONDITIONALLY. Once GetDeviceProcAddr has handed
// out our hooks, every present on this device passes through them, and a hook
// with nothing to forward to would fail the application's present -- measured
// 2026-09-06 as VK_ERROR_DEVICE_LOST on the harness when an injected Overlay
// owned the ring and the layer had registered nothing. The ring failing to
// come up must only ever mean "observe nothing", never "forward nothing".
const uint32_t i = g_deviceCount.load(std::memory_order_acquire);
if (i >= kMaxDevices) {
return;
}
DeviceSlot& d = g_devices[i];
d.key = DispatchKey(device);
d.present = reinterpret_cast<PFN_vkQueuePresentKHR>(g_nextGetDeviceProcAddr(device, "vkQueuePresentKHR"));
d.createSwapchain =
reinterpret_cast<PFN_vkCreateSwapchainKHR>(g_nextGetDeviceProcAddr(device, "vkCreateSwapchainKHR"));
d.destroySwapchain =
reinterpret_cast<PFN_vkDestroySwapchainKHR>(g_nextGetDeviceProcAddr(device, "vkDestroySwapchainKHR"));
g_deviceCount.store(i + 1u, std::memory_order_release); // visible LAST
// Then the capture side, whose failure (an Overlay already owning the ring,
// most likely) leaves the hooks in place as pure forwarders.
EnsureCapture();
}
bool Active() noexcept {
return ThisProcessIsEnabledCached() && !MustStayInert();
}
// The three names we answer for, in an admitted process, from either proc-addr
// entry: applications and layers above us may fetch device functions through
// vkGetInstanceProcAddr as well.
PFN_vkVoidFunction OurDeviceFunction(const char* pName) noexcept {
if (std::strcmp(pName, "vkQueuePresentKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&QueuePresentKHR);
}
if (std::strcmp(pName, "vkCreateSwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&CreateSwapchainKHR);
}
if (std::strcmp(pName, "vkDestroySwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&DestroySwapchainKHR);
}
return nullptr;
}
// ---------------------------------------------------------------------------
// Loader interface. Everything forwards; an admitted process is also observed.
// ---------------------------------------------------------------------------
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetInstanceProcAddr(VkInstance instance, const char* pName);
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetDeviceProcAddr(VkDevice device, const char* pName);
@@ -309,7 +661,13 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physicalDevice, con
}
chain->u.pLayerInfo = chain->u.pLayerInfo->pNext;
return createDevice(physicalDevice, pCreateInfo, pAllocator, pDevice);
const VkResult r = createDevice(physicalDevice, pCreateInfo, pAllocator, pDevice);
// The capture side comes up HERE and only here: after the next layer built the
// device, and only in a process both gates admitted (P1 item 3).
if (r == VK_SUCCESS && pDevice != nullptr && Active()) {
RegisterDevice(*pDevice);
}
return r;
}
// Evaluated once, on first use. The enable-list decides what we INTERCEPT, not
@@ -339,8 +697,7 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetInstanceProcAddr(VkInstance instance
return (g_nextGetInstanceProcAddr != nullptr) ? g_nextGetInstanceProcAddr(instance, pName) : nullptr;
}
// Exactly the entry points needed to stay in the chain and forward.
// vkQueuePresentKHR is deliberately absent — see the file header.
// The entry points needed to stay in the chain and forward, then ours.
if (std::strcmp(pName, "vkGetInstanceProcAddr") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&GetInstanceProcAddr);
}
@@ -350,6 +707,10 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetInstanceProcAddr(VkInstance instance
if (std::strcmp(pName, "vkCreateDevice") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&CreateDevice);
}
// Past the gate: an admitted process gets our present / swapchain entries.
if (PFN_vkVoidFunction ours = OurDeviceFunction(pName); ours != nullptr) {
return ours;
}
if (g_nextGetInstanceProcAddr == nullptr) {
return nullptr;
}
@@ -363,6 +724,17 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetDeviceProcAddr(VkDevice device, cons
if (std::strcmp(pName, "vkGetDeviceProcAddr") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&GetDeviceProcAddr);
}
if (Active()) {
if (PFN_vkVoidFunction ours = OurDeviceFunction(pName); ours != nullptr) {
// A device that reached us here without passing through CreateDevice
// (created before the gates were consulted, or beyond the table) is
// registered now, so the hook we hand out always has a next pointer.
if (device != nullptr) {
RegisterDevice(device);
}
return ours;
}
}
if (g_nextGetDeviceProcAddr == nullptr) {
return nullptr;
}
+35
View File
@@ -26,6 +26,7 @@ target_include_directories(fl_guard_test PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedge
target_link_libraries(fl_guard_test PRIVATE FrameLedger.Shm fl_native_flags fl_jsmn Catch2::Catch2WithMain
Shell32 Ole32 fl_ac_floor)
add_dependencies(fl_guard_test fl_ac_floor_gen)
add_dependencies(fl_guard_test fl_stub_sl_common fl_stub_sl_interposer)
# /EHsc on the TEST BINARY only. Catch2 reports failures by throwing, and the
# top-level CMakeLists strips the compiler's default /EHsc so every target has
@@ -94,6 +95,12 @@ target_compile_definitions(fl_guard_test PRIVATE
FL_DXR_DISPATCH_W=${FL_DXR_DISPATCH_W}
FL_DXR_DISPATCH_H=${FL_DXR_DISPATCH_H}
FL_DXR_DISPATCH_D=${FL_DXR_DISPATCH_D}
# The Streamline stubs, for the LoadLibrary detour's late-load fixture (P1 item
# 1): sl.common is an inert decoy exporting nothing (also copied under an
# anti-cheat name for the early-stop case), sl.interposer is the module whose
# late arrival must be hooked within milliseconds rather than on the next tick.
FL_STUB_SL_COMMON=L"$<TARGET_FILE:fl_stub_sl_common>"
FL_STUB_SL_INTERPOSER=L"$<TARGET_FILE:fl_stub_sl_interposer>"
FL_OVERLAY_DLL=L"${FL_STAGED_OVERLAY}"
# The un-staged original, so a test can prove the check discriminates on
# DIRECTORY rather than on filename: same bytes, same name, wrong place.
@@ -103,6 +110,34 @@ add_dependencies(fl_guard_test hook-harness FrameLedger.Overlay fl_stage_overlay
add_test(NAME fl_guard COMMAND fl_guard_test)
# The Vulkan layer's capture side (P1 item 3), driven by a FAKE loader chain --
# no registry, no loader, no GPU -- so it is merge-gated. Three ctests, three
# processes, because one process carries one ring and each DLL flavour makes one.
# fl_ac_rules.cpp is compiled in for LocalAppDataDir / RulesFilePath, the same
# functions the layer reads through, so the files the test writes land exactly
# where the layer looks.
add_executable(fl_vklayer_test vklayer_test.cpp "${CMAKE_SOURCE_DIR}/FrameLedger.Injector/src/fl_ac_rules.cpp")
target_include_directories(fl_vklayer_test PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Injector/include")
target_link_libraries(fl_vklayer_test PRIVATE FrameLedger.Shm fl_native_flags fl_jsmn fl_vulkan_headers
Catch2::Catch2WithMain Shell32 Ole32 fl_ac_floor)
add_dependencies(fl_vklayer_test fl_ac_floor_gen FrameLedger.VkLayer fl_vklayer_shortdeadline hook-harness)
target_compile_options(fl_vklayer_test PRIVATE /EHsc)
target_compile_definitions(fl_vklayer_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
FL_VKLAYER_DLL=L"$<TARGET_FILE:FrameLedger.VkLayer>"
FL_VKLAYER_SHORTDEADLINE_DLL=L"$<TARGET_FILE:fl_vklayer_shortdeadline>"
# The directory the loader is pointed at through VK_ADD_IMPLICIT_LAYER_PATH:
# it holds the generated manifest beside the DLL.
FL_VKLAYER_MANIFEST_DIR=L"$<TARGET_FILE_DIR:FrameLedger.VkLayer>"
FL_HARNESS_EXE=L"$<TARGET_FILE:hook-harness>"
FL_REPO_RULES=L"${CMAKE_SOURCE_DIR}/../../rules/detection-rules.json"
)
add_test(NAME fl_vklayer COMMAND fl_vklayer_test "[vklayer]")
add_test(NAME fl_vklayer_supervision COMMAND fl_vklayer_test "[vklayer-deadline]")
# The real-loader leg SKIPS (Catch2 exit 4) where there is no Vulkan loader or no
# presentable device -- CI, per the §S29(d) census -- and runs on a dev box.
add_test(NAME fl_vklayer_real COMMAND fl_vklayer_test "[vklayer-real]")
set_tests_properties(fl_vklayer_real PROPERTIES SKIP_RETURN_CODE 4)
# Check 4's fail-closed matrix, as its own ctest name so a regression in the
# static pre-scan is legible in the ctest summary rather than buried in
# fl_guard's total. Same binary, selected by tag — duplicating the evidence
File diff suppressed because it is too large. Load diff
+559
View File
@@ -0,0 +1,559 @@
// The Vulkan layer's capture side (P1 item 3): vkQueuePresentKHR intercepted,
// the ring written, the in-layer supervision stop (§S2 part three) -- driven
// end to end by a FAKE loader chain, exactly as 20_OPEN_QUESTIONS §S2 said it
// would land: "in the PR that adds the present hook, where a fake loader chain
// can drive it end to end".
//
// Three ctests, three processes, because a process carries ONE ring and each
// flavour of the DLL creates one:
// [vklayer] the shipped DLL: records, forwarding, the unhook stop
// [vklayer-deadline] the short-deadline flavour: guardTicks stops -> the layer stops
// [vklayer-real] the REAL loader, the REAL harness (--vulkan), via
// VK_ADD_IMPLICIT_LAYER_PATH -- SKIPPED where there is no
// Vulkan loader or no presentable device (CI, §S29(d))
//
// The layer reads its enable-list and rules from the ONE product location under
// %LOCALAPPDATA% and there is deliberately no override (§S3), so this test writes
// its own image name into that enable-list and, when no rules file is installed,
// the repository seed -- and removes exactly what it added. It never touches an
// existing rules file.
#include <windows.h>
#include <vulkan/vk_layer.h>
#include <vulkan/vulkan.h>
#include <atomic>
#include <catch2/catch_test_macros.hpp>
#include <cstdio>
#include <cstring>
#include <fl_ac_rules.h>
#include <fl_shm.h>
#include <string>
namespace {
// ---------------------------------------------------------------------------
// The product's files: enable-list + rules, added and removed by this test.
// ---------------------------------------------------------------------------
struct ProductFiles {
std::wstring enableList;
std::string enableListBackup; // the previous contents, when there were any
bool hadEnableList = false;
std::wstring rules;
bool installedRules = false;
static std::wstring LocalAppData() {
wchar_t base[fl::guard::kMaxRulesPathLen]{};
REQUIRE(fl::guard::LocalAppDataDir(base, fl::guard::kMaxRulesPathLen));
return base;
}
static void EnsureDir(const std::wstring& dir) {
std::wstring cur;
for (size_t i = 0; i < dir.size(); ++i) {
cur += dir[i];
if ((dir[i] == L'\\' || i + 1 == dir.size()) && cur.size() > 3) {
CreateDirectoryW(cur.c_str(), nullptr);
}
}
}
static bool ReadAll(const std::wstring& path, std::string& out) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
return false;
}
char buf[4096];
DWORD n = 0;
out.clear();
while (ReadFile(h, buf, sizeof(buf), &n, nullptr) && n > 0) {
out.append(buf, n);
}
CloseHandle(h);
return true;
}
static bool WriteAll(const std::wstring& path, const std::string& text) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
return false;
}
DWORD n = 0;
const BOOL ok = WriteFile(h, text.data(), static_cast<DWORD>(text.size()), &n, nullptr);
CloseHandle(h);
return ok && n == text.size();
}
// Adds `imageName` to the enable-list (creating it if needed) and installs the
// repository seed rules when no rules file exists.
void Install(const char* imageName) {
const std::wstring base = LocalAppData();
const std::wstring dir = base + L"\\FrameLedger\\vklayer";
EnsureDir(dir);
enableList = dir + L"\\enabled.txt";
std::string existing;
hadEnableList = ReadAll(enableList, existing);
if (hadEnableList) {
enableListBackup = existing;
}
std::string text = existing;
if (!text.empty() && text.back() != '\n') {
text += '\n';
}
text += "# added by fl_vklayer_test, removed when it exits\n";
text += imageName;
text += '\n';
REQUIRE(WriteAll(enableList, text));
wchar_t rulesPath[fl::guard::kMaxRulesPathLen]{};
REQUIRE(fl::guard::RulesFilePath(rulesPath, fl::guard::kMaxRulesPathLen));
rules = rulesPath;
if (GetFileAttributesW(rulesPath) == INVALID_FILE_ATTRIBUTES) {
const std::wstring rulesDir = rules.substr(0, rules.find_last_of(L'\\'));
EnsureDir(rulesDir);
REQUIRE(CopyFileW(FL_REPO_RULES, rulesPath, TRUE));
installedRules = true;
}
}
~ProductFiles() {
if (!enableList.empty()) {
if (hadEnableList) {
WriteAll(enableList, enableListBackup);
} else {
DeleteFileW(enableList.c_str());
}
}
if (installedRules) {
DeleteFileW(rules.c_str());
}
}
};
std::string OwnImageName() {
char full[MAX_PATH]{};
REQUIRE(GetModuleFileNameA(nullptr, full, MAX_PATH) != 0);
const char* leaf = std::strrchr(full, '\\');
return leaf != nullptr ? leaf + 1 : full;
}
// ---------------------------------------------------------------------------
// The fake loader chain. Dispatchable handles are objects whose FIRST word is the
// dispatch key, which is what the loader guarantees and what the layer keys on;
// the device and its queue share one key, as they do under a real loader.
// ---------------------------------------------------------------------------
void* g_deviceKey = &g_deviceKey;
void* g_instanceKey = &g_instanceKey;
struct Dispatchable {
void* key;
};
Dispatchable g_instanceObj{g_instanceKey};
Dispatchable g_deviceObj{g_deviceKey};
Dispatchable g_queueObj{g_deviceKey};
std::atomic<int> g_forwardedPresents{0};
std::atomic<int> g_destroyed{0};
VkSwapchainKHR g_lastPresented = VK_NULL_HANDLE;
const VkSwapchainKHR kFakeSwapchain = reinterpret_cast<VkSwapchainKHR>(static_cast<uintptr_t>(0x1234));
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateInstance(const VkInstanceCreateInfo*, const VkAllocationCallbacks*,
VkInstance* pInstance) {
*pInstance = reinterpret_cast<VkInstance>(&g_instanceObj);
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateDevice(VkPhysicalDevice, const VkDeviceCreateInfo*,
const VkAllocationCallbacks*, VkDevice* pDevice) {
*pDevice = reinterpret_cast<VkDevice>(&g_deviceObj);
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeQueuePresent(VkQueue, const VkPresentInfoKHR* info) {
++g_forwardedPresents;
g_lastPresented = (info != nullptr && info->swapchainCount > 0) ? info->pSwapchains[0] : VK_NULL_HANDLE;
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateSwapchain(VkDevice, const VkSwapchainCreateInfoKHR*,
const VkAllocationCallbacks*, VkSwapchainKHR* out) {
*out = kFakeSwapchain;
return VK_SUCCESS;
}
VKAPI_ATTR void VKAPI_CALL FakeDestroySwapchain(VkDevice, VkSwapchainKHR, const VkAllocationCallbacks*) {
++g_destroyed;
}
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL FakeGetDeviceProcAddr(VkDevice, const char* name) {
if (std::strcmp(name, "vkQueuePresentKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeQueuePresent);
}
if (std::strcmp(name, "vkCreateSwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeCreateSwapchain);
}
if (std::strcmp(name, "vkDestroySwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeDestroySwapchain);
}
return nullptr;
}
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL FakeGetInstanceProcAddr(VkInstance, const char* name) {
if (std::strcmp(name, "vkCreateInstance") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeCreateInstance);
}
if (std::strcmp(name, "vkCreateDevice") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeCreateDevice);
}
return nullptr;
}
// The layer, driven as the loader would drive it: negotiate, create an instance
// through the chain, create a device through the chain, fetch the device entries.
struct DrivenLayer {
HMODULE dll = nullptr;
PFN_vkGetInstanceProcAddr gipa = nullptr;
PFN_vkGetDeviceProcAddr gdpa = nullptr;
VkInstance instance = nullptr;
VkDevice device = nullptr;
PFN_vkQueuePresentKHR present = nullptr;
PFN_vkCreateSwapchainKHR createSwapchain = nullptr;
PFN_vkDestroySwapchainKHR destroySwapchain = nullptr;
void Drive(const wchar_t* path) {
dll = LoadLibraryW(path);
REQUIRE(dll != nullptr);
auto negotiate = reinterpret_cast<PFN_vkNegotiateLoaderLayerInterfaceVersion>(
GetProcAddress(dll, "vkNegotiateLoaderLayerInterfaceVersion"));
REQUIRE(negotiate != nullptr);
VkNegotiateLayerInterface n{};
n.sType = LAYER_NEGOTIATE_INTERFACE_STRUCT;
n.loaderLayerInterfaceVersion = 2;
REQUIRE(negotiate(&n) == VK_SUCCESS);
gipa = n.pfnGetInstanceProcAddr;
gdpa = n.pfnGetDeviceProcAddr;
REQUIRE(gipa != nullptr);
REQUIRE(gdpa != nullptr);
VkLayerInstanceLink ilink{nullptr, &FakeGetInstanceProcAddr, nullptr};
VkLayerInstanceCreateInfo ici{};
ici.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
ici.function = VK_LAYER_LINK_INFO;
ici.u.pLayerInfo = &ilink;
VkInstanceCreateInfo ci{};
ci.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
ci.pNext = &ici;
auto createInstance = reinterpret_cast<PFN_vkCreateInstance>(gipa(nullptr, "vkCreateInstance"));
REQUIRE(createInstance != nullptr);
REQUIRE(createInstance(&ci, nullptr, &instance) == VK_SUCCESS);
REQUIRE(instance == reinterpret_cast<VkInstance>(&g_instanceObj));
VkLayerDeviceLink dlink{nullptr, &FakeGetInstanceProcAddr, &FakeGetDeviceProcAddr};
VkLayerDeviceCreateInfo dci{};
dci.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO;
dci.function = VK_LAYER_LINK_INFO;
dci.u.pLayerInfo = &dlink;
VkDeviceCreateInfo dc{};
dc.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
dc.pNext = &dci;
auto createDevice = reinterpret_cast<PFN_vkCreateDevice>(gipa(instance, "vkCreateDevice"));
REQUIRE(createDevice != nullptr);
REQUIRE(createDevice(nullptr, &dc, nullptr, &device) == VK_SUCCESS);
REQUIRE(device == reinterpret_cast<VkDevice>(&g_deviceObj));
present = reinterpret_cast<PFN_vkQueuePresentKHR>(gdpa(device, "vkQueuePresentKHR"));
createSwapchain = reinterpret_cast<PFN_vkCreateSwapchainKHR>(gdpa(device, "vkCreateSwapchainKHR"));
destroySwapchain = reinterpret_cast<PFN_vkDestroySwapchainKHR>(gdpa(device, "vkDestroySwapchainKHR"));
}
VkResult PresentOnce(VkSwapchainKHR sc) const {
uint32_t index = 0;
VkPresentInfoKHR info{};
info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
info.swapchainCount = 1;
info.pSwapchains = &sc;
info.pImageIndices = &index;
return present(reinterpret_cast<VkQueue>(&g_queueObj), &info);
}
};
struct OwnRing {
HANDLE mapping = nullptr;
void* base = nullptr;
fl::FlShmHandshake* hs = nullptr;
fl::FlWriterState* st = nullptr;
fl::FlControlBlock* ctl = nullptr;
const fl::FlFrameRecord* ring = nullptr;
bool Open() {
wchar_t name[128]{};
_snwprintf_s(name, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", GetCurrentProcessId());
mapping = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, name);
if (mapping == nullptr) {
return false;
}
base = MapViewOfFile(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (base == nullptr) {
return false;
}
auto* bytes = static_cast<unsigned char*>(base);
hs = reinterpret_cast<fl::FlShmHandshake*>(bytes + FL_SHM_HANDSHAKE_OFFSET);
st = reinterpret_cast<fl::FlWriterState*>(bytes + FL_SHM_WRITER_OFFSET);
ctl = reinterpret_cast<fl::FlControlBlock*>(bytes + FL_SHM_CONTROL_OFFSET);
ring = reinterpret_cast<const fl::FlFrameRecord*>(bytes + FL_SHM_RING_OFFSET);
return true;
}
~OwnRing() {
if (base != nullptr) {
UnmapViewOfFile(base);
}
if (mapping != nullptr) {
CloseHandle(mapping);
}
}
};
} // namespace
// ===========================================================================
TEST_CASE("the layer, driven by a fake loader chain, owns the ring and records every present it forwards",
"[vklayer]") {
ProductFiles files;
files.Install(OwnImageName().c_str()); // BEFORE the DLL loads: both gates are cached on first use
DrivenLayer layer;
layer.Drive(FL_VKLAYER_DLL);
REQUIRE(layer.present != nullptr);
CHECK(layer.present != &FakeQueuePresent); // ours, not the next layer's
REQUIRE(layer.createSwapchain != nullptr);
REQUIRE(layer.destroySwapchain != nullptr);
// The ring exists under OUR pid, with the handshake a reader validates first.
OwnRing r;
REQUIRE(r.Open());
CHECK(r.hs->layoutVersion == FL_SHM_LAYOUT_VERSION);
CHECK(r.hs->pid == GetCurrentProcessId());
CHECK(r.hs->recordSize == sizeof(fl::FlFrameRecord));
CHECK(r.st->status == fl::FL_STATUS_READY);
CHECK((r.st->apiMask & (1u << fl::FL_API_VULKAN)) != 0u);
CHECK((r.st->hooksInstalledMask & fl::FL_HOOK_PRESENT) != 0u);
CHECK(r.st->dxgiPresentsBeforeHook == 0xFFFFFFFFu); // no DXGI counter on this path: "not read"
// A swapchain created through us is remembered with its extent.
VkSwapchainCreateInfoKHR sci{};
sci.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
sci.imageExtent = VkExtent2D{1280u, 720u};
VkSwapchainKHR sc = VK_NULL_HANDLE;
REQUIRE(layer.createSwapchain(layer.device, &sci, nullptr, &sc) == VK_SUCCESS);
REQUIRE(sc == kFakeSwapchain);
// Presents: one record each, forwarded each, the record naming the chain and its size.
for (int i = 0; i < 5; ++i) {
++r.ctl->guardTicks;
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
}
CHECK(g_forwardedPresents.load() == 5);
CHECK(g_lastPresented == kFakeSwapchain);
CHECK(r.st->writeIndex == 5u);
const fl::FlFrameRecord& rec = r.ring[0];
CHECK(rec.api == static_cast<uint8_t>(fl::FL_API_VULKAN));
CHECK(rec.outputW == 1280u);
CHECK(rec.outputH == 720u);
CHECK(rec.swapchainId != 0u);
CHECK(rec.measuredMask == fl::FL_MEASURED_OUTPUT_RES); // and NOT PRESENT_ARGS: vkQueuePresentKHR has none
CHECK(r.ring[4].frameIndex == rec.frameIndex + 4u);
CHECK(r.ring[4].qpc > rec.qpc);
// A present on a chain we never saw is still recorded, as "unidentified", and forwarded.
const auto unknown = reinterpret_cast<VkSwapchainKHR>(static_cast<uintptr_t>(0x9999));
REQUIRE(layer.PresentOnce(unknown) == VK_SUCCESS);
CHECK(r.st->writeIndex == 6u);
CHECK(r.ring[5].swapchainId == 0u);
CHECK(r.ring[5].measuredMask == 0u);
// Destroyed through us: forgotten, and the next layer told.
layer.destroySwapchain(layer.device, sc, nullptr);
CHECK(g_destroyed.load() == 1);
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
CHECK(r.ring[6].swapchainId == 0u);
// Pause is not stop: no record, still forwarded, status untouched.
r.ctl->pauseRequested = 1;
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
CHECK(r.st->writeIndex == 7u);
CHECK(g_forwardedPresents.load() == 8);
CHECK(r.st->status == fl::FL_STATUS_READY);
r.ctl->pauseRequested = 0;
// THE SAFETY STOP: unhookRequested -> UNHOOKED within one present, writeIndex frozen,
// and every later present still forwarded -- "stops" is passthrough, never a broken app.
r.ctl->unhookRequested = 1;
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
CHECK(r.st->status == fl::FL_STATUS_UNHOOKED);
CHECK(r.st->writeIndex == 7u);
for (int i = 0; i < 3; ++i) {
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
}
CHECK(r.st->writeIndex == 7u);
CHECK(g_forwardedPresents.load() == 12);
CHECK(r.st->faultCount == 0u);
}
// ===========================================================================
TEST_CASE("§S2 part three: when guardTicks stops advancing the layer stops itself, and while it advances it does not",
"[vklayer-deadline]") {
// The short-deadline flavour (1.5 s instead of 65 s), same sources. The clock
// starts when the ring is published; ticks that keep coming keep it alive
// past the deadline, and ticks that stop end it -- on the present path, since
// the layer owns no thread (§S2).
ProductFiles files;
files.Install(OwnImageName().c_str());
DrivenLayer layer;
layer.Drive(FL_VKLAYER_SHORTDEADLINE_DLL);
REQUIRE(layer.present != nullptr);
OwnRing r;
REQUIRE(r.Open());
REQUIRE(r.st->status == fl::FL_STATUS_READY);
// Supervised: 2.4 s of presents with a tick every 600 ms -- past the 1.5 s deadline, still READY.
for (int i = 0; i < 4; ++i) {
++r.ctl->guardTicks;
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS);
Sleep(600);
}
++r.ctl->guardTicks;
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS);
CHECK(r.st->status == fl::FL_STATUS_READY);
const uint64_t recorded = r.st->writeIndex;
CHECK(recorded == 5u);
// Unsupervised: no tick for 1.8 s -> the next present stops the layer.
Sleep(1800);
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS);
CHECK(r.st->status == fl::FL_STATUS_UNHOOKED);
CHECK(r.st->writeIndex == recorded);
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS); // still forwarded
CHECK(g_forwardedPresents.load() == 7);
}
// ===========================================================================
namespace {
struct Child {
PROCESS_INFORMATION pi{};
~Child() {
if (pi.hProcess != nullptr) {
TerminateProcess(pi.hProcess, 0);
WaitForSingleObject(pi.hProcess, 3000);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
}
};
struct ChildRing {
HANDLE mapping = nullptr;
void* base = nullptr;
fl::FlWriterState* st = nullptr;
fl::FlControlBlock* ctl = nullptr;
const fl::FlFrameRecord* ring = nullptr;
~ChildRing() {
if (base != nullptr) {
UnmapViewOfFile(base);
}
if (mapping != nullptr) {
CloseHandle(mapping);
}
}
bool OpenFor(DWORD pid, HANDLE process, int waitMs) {
wchar_t name[128]{};
_snwprintf_s(name, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", pid);
const ULONGLONG until = GetTickCount64() + static_cast<ULONGLONG>(waitMs);
while (mapping == nullptr && GetTickCount64() < until) {
mapping = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, name);
if (mapping == nullptr) {
if (WaitForSingleObject(process, 0) != WAIT_TIMEOUT) {
return false; // the child is gone
}
Sleep(50);
}
}
if (mapping == nullptr) {
return false;
}
base = MapViewOfFile(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (base == nullptr) {
return false;
}
auto* bytes = static_cast<unsigned char*>(base);
st = reinterpret_cast<fl::FlWriterState*>(bytes + FL_SHM_WRITER_OFFSET);
ctl = reinterpret_cast<fl::FlControlBlock*>(bytes + FL_SHM_CONTROL_OFFSET);
ring = reinterpret_cast<const fl::FlFrameRecord*>(bytes + FL_SHM_RING_OFFSET);
return true;
}
};
} // namespace
TEST_CASE("the REAL loader maps the layer from VK_ADD_IMPLICIT_LAYER_PATH into the harness's Vulkan mode, and every "
"present is recorded",
"[vklayer-real]") {
// No registry: the loader honours VK_ADD_IMPLICIT_LAYER_PATH (measured 2026-09-06
// against 1.4.357, spike-notes §2), so the layer is discoverable ONLY by the
// process this test starts. Skipped honestly where there is no loader or no
// presentable device -- CI has neither (§S29(d)).
if (LoadLibraryW(L"vulkan-1.dll") == nullptr) {
SKIP("no Vulkan loader on this machine");
}
ProductFiles files;
files.Install("hook-harness.exe");
// Environment for the child: inherited from ours, so set, spawn, unset.
REQUIRE(SetEnvironmentVariableW(L"VK_ADD_IMPLICIT_LAYER_PATH", FL_VKLAYER_MANIFEST_DIR));
REQUIRE(SetEnvironmentVariableW(L"FRAMELEDGER_ENABLE_VK_LAYER", L"1"));
Child child;
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" --vulkan --hold-presenting 4";
STARTUPINFOW si{};
si.cb = sizeof(si);
const BOOL started = CreateProcessW(FL_HARNESS_EXE, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr,
nullptr, &si, &child.pi);
SetEnvironmentVariableW(L"VK_ADD_IMPLICIT_LAYER_PATH", nullptr);
SetEnvironmentVariableW(L"FRAMELEDGER_ENABLE_VK_LAYER", nullptr);
REQUIRE(started);
ChildRing r;
const bool ringUp = r.OpenFor(child.pi.dwProcessId, child.pi.hProcess, 15000);
if (!ringUp) {
DWORD code = 0;
WaitForSingleObject(child.pi.hProcess, 5000);
GetExitCodeProcess(child.pi.hProcess, &code);
if (code == 77u) {
SKIP("the harness found no presentable Vulkan device on this machine (exit 77)");
}
FAIL("the layer published no ring for the harness (harness exit " << code << ")");
}
// Keep it supervised while the harness presents, then read what it wrote.
for (int i = 0; i < 50; ++i) {
++r.ctl->guardTicks;
Sleep(100);
if (WaitForSingleObject(child.pi.hProcess, 0) != WAIT_TIMEOUT) {
break;
}
}
WaitForSingleObject(child.pi.hProcess, 10000);
DWORD code = 1;
GetExitCodeProcess(child.pi.hProcess, &code);
INFO("harness exit " << code << ", records " << r.st->writeIndex << ", status " << r.st->status);
CHECK(code == 0u);
CHECK(r.st->status == fl::FL_STATUS_READY);
CHECK(r.st->writeIndex >= 20u); // ~4 s at ~120/s minus device creation; a loose floor, not a rate claim
CHECK((r.st->apiMask & (1u << fl::FL_API_VULKAN)) != 0u);
CHECK(r.ring[0].api == static_cast<uint8_t>(fl::FL_API_VULKAN));
CHECK(r.ring[0].outputW != 0u);
CHECK((r.ring[0].measuredMask & fl::FL_MEASURED_OUTPUT_RES) != 0u);
CHECK(r.st->faultCount == 0u);
}
+28
View File
@@ -243,3 +243,31 @@ target_include_directories(fl_fidelityfx_headers SYSTEM INTERFACE
# declaration that exports nothing unless something DEFINES it. FrameLedger.Overlay
# must never define or take the address of one; hookinventory-check Pass C reads
# the built DLL's export table as well as its imports for exactly that.
# ---------------------------------------------------------------------------
# AMD FidelityFX SDK -- the FSR 3.0 HOST API headers (MIT) -- VENDORED, ten files,
# at tag fsr3-v3.0.4, in a directory of their own beside the ffx-api tree above.
#
# WHAT THIS BUYS. Cyberpunk 2077 upscales at FSR 3 through ffx_fsr3_x64.dll's NAMED
# exports rather than the ffx-api facade, so the row set above sees its frame
# generation (the 1.1.x monolith) and not its upscaler. ffxFsr3ContextDispatchUpscale
# takes a descriptor whose renderSize field is at an offset only the vendor's own
# header can vouch for; this target makes that read a declaration. The tag is the
# one whose declarations match the module the title SHIPS -- twelve ffxFsr3* exports,
# fsr3-v3.0.4's exact set -- not the v1.1.4 the docs first named, whose dispatch
# struct appends fields after renderSize and declares three exports the module lacks
# (third_party/fidelityfx-fsr3/README.md).
#
# A SEPARATE DIRECTORY BECAUSE THE LICENCE SHAPE DIFFERS: a root LICENSE.txt that IS
# the MIT grant, with every header carrying it inline -- not v2.3.0's exception list.
# tools/license-check.ps1 §2e asserts that per file; §2d would have walked past it.
#
# ONE INCLUDE DIRECTORY: the headers include each other as <FidelityFX/host/...>, so
# sdk/include is the root and upstream's layout is kept, unmodified.
add_library(fl_fsr3_host_headers INTERFACE)
target_include_directories(fl_fsr3_host_headers SYSTEM INTERFACE
"${CMAKE_CURRENT_SOURCE_DIR}/fidelityfx-fsr3/sdk/include"
)
# Never linked, same rule as above. FFX_API here is __declspec(dllexport) with no
# switch at all (ffx_types.h at this tag); the Overlay defines none of the names and
# Pass C's forbidden-export pattern (^ffx[A-Z]) already covers ffxFsr3*.
+19
View File
@@ -0,0 +1,19 @@
Copyright © 2023 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and /or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+124
View File
@@ -0,0 +1,124 @@
# AMD FidelityFX SDK — FSR 3.0 host API headers (vendored)
Copied from <https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK>, tag
**`fsr3-v3.0.4`** (commit `55ff22bb6981a9b9c087b9465101769fc0acd447`). **Ten headers and the
licence file.** A second vendoring directory beside `../fidelityfx/` (tag `v2.3.0`, the ffx-api
facade), because the two tags carry two different licence *shapes* and `tools/license-check.ps1`
asserts each per file: §2d walks `fidelityfx/Kits/` against the exception list inside its
`license.md`; **§2e walks this directory's `sdk/` against the root `LICENSE.txt`**, which at this
tag is the MIT grant verbatim, with every header carrying the same grant in its own banner.
## Why this tag — and why not `v1.1.4`, which three documents named
The one installed title that ships the FSR 3.0 **host** DLLs is Cyberpunk 2077
(`ffx_fsr3_x64.dll`, `ffx_fsr3upscaler_x64.dll`, `ffx_frameinterpolation_x64.dll`,
`ffx_opticalflow_x64.dll`, `ffx_backend_dx12_x64.dll`). `docs/vendor-exports.json` records
`ffx_fsr3_x64.dll` exporting **twelve** `ffxFsr3*` names: `ContextCreate`, `ContextDestroy`,
`ContextDispatchUpscale`, `ContextGenerateReactiveMask`, `DispatchFrameGeneration`,
`ConfigureFrameGeneration`, `GetJitterOffset`, `GetJitterPhaseCount`,
`GetRenderResolutionFromQualityMode`, `GetUpscaleRatioFromQualityMode`, `ResourceIsNull`,
`SkipPresent`. Read off the upstream tags through the GitHub API on 2026-09-05:
- **`fsr3-v3.0.4`** (and `fsr3-v3.0.3`) declares exactly those twelve. Its
`FfxFsr3DispatchUpscaleDescription` ends at `viewSpaceToMetersFactor`.
- **`v1.1.4`** declares fifteen — it adds `ContextGetGpuMemoryUsage`,
`ContextDispatchFrameGenerationPrepare` and `GetEffectVersion`, none of which the shipped
module exports — and its `FfxFsr3DispatchUpscaleDescription` appends `upscaleSize`, `flags`
and `frameID` **after `renderSize`**. A detour typed against 1.1.4 would read
`enableSharpening`/`sharpness` bytes as an output size on Cyberpunk's 3.0 module.
- The prefix through `renderSize` — `commandList`, seven `FfxResource`s, `jitterOffset`,
`motionVectorScale`, `renderSize` — is **identical** in 3.0.3, 3.0.4 and 1.1.4, and it is the
only field the Overlay reads. `dllmain.cpp` pins `offsetof(FfxFsr3DispatchUpscaleDescription,
renderSize)` to a literal so a re-vendoring that moved it fails to compile rather than reading
the wrong bytes.
So the declarations vendored are the ones the shipped module exports, and the corrections to
`docs/18_GPU_VENDOR_APIS.md`, `docs/HANDOFF.md` and `docs/20_OPEN_QUESTIONS.md` — all of which
said `v1.1.4` — landed with this directory.
## The include closure, measured — and `<mutex>` is not in it
Those same documents said the closure was "ten headers reaching `<mutex>` / `<shared_mutex>`
through `ffx_types.h`". That is true of **1.1.x**, where `ffx_types.h` includes them behind
`#ifndef FFX_MUTEX`. At `fsr3-v3.0.4` **`ffx_types.h` includes `<stdint.h>` and nothing else**,
and no file below pulls in the STL or `<windows.h>`:
```
ffx_fsr3.h
├── ffx_interface.h
│ ├── ffx_assert.h → ffx_types.h, ffx_util.h (→ ffx_types.h)
│ ├── ffx_types.h → <stdint.h>
│ └── ffx_error.h → ffx_types.h
├── ffx_fsr3upscaler.h → ffx_interface.h, ../gpu/fsr3upscaler/ffx_fsr3upscaler_resources.h (defines only)
├── ffx_frameinterpolation.h → ffx_interface.h
└── ffx_opticalflow.h → ffx_interface.h
```
Ten files, no `ffx_message.h` (that file exists at 1.1.x, not here). The Overlay is built with
`_HAS_EXCEPTIONS=0` and no C++ exceptions on hook paths; a closure with no STL in it has nothing
to audit for `throw`, which is the property the Streamline closure had to be measured for.
## `FFX_API` is `__declspec(dllexport)` unconditionally
`ffx_types.h` defines `FFX_API` as `__declspec(dllexport)` on every non-GCC compiler — there is
no import switch at this tag (the `FFX_BUILD_AS_DLL` switch arrives in 1.1.x). That is the same
hazard `ffx_api.h`'s `FFX_API_ENTRY` carries and it has the same answer: a declaration exports
nothing unless something *defines* it. `FrameLedger.Overlay` includes `ffx_fsr3.h` for types and
`decltype` only and defines none of the names; `tools/hookinventory-check.ps1` Pass C reads the
built DLL's export table (forbidden pattern `^ffx[A-Z]`) to keep that true, and the
`ffx_fsr3_x64.dll` fixture in `tools/vendor-stubs` — which *does* define four of them through the
vendor's own macro — is the parser's second positive control.
## Coexistence with `../fidelityfx/` in one translation unit
Both trees are included by `dllmain.cpp` and by `hook-harness`. Measured at the first build: the
type names are disjoint (`FfxApiResource` / `FfxApiDimensions2D` there, `FfxResource` /
`FfxDimensions2D` here) **except one** — both trees define a struct named
`FfxFrameGenerationConfig` (2.3.0's `ffx_framegeneration.h`, 3.0.4's `ffx_interface.h`) — and the
one macro both define, `FFX_RESOURCE_NAME_SIZE`, is `64` in each, a legal identical redefinition.
So the consumers include this tree **inside a namespace** (`namespace fsr3host { #include
<FidelityFX/host/ffx_fsr3.h> }`): the headers stay verbatim, the entry points keep their C
linkage (a C-linkage function declared in two namespace scopes is one function), and every field
the Overlay reads is still the vendor's own declaration, spelled `fsr3host::…`.
## Unmodified, and checked rather than claimed
`git hash-object` on each vendored file equals the blob sha the GitHub tree API reports for the
same path at the tag. Upstream ships **LF**; `.gitattributes` (`* text=auto eol=crlf`) stores LF
in the index and materialises CRLF in the working tree, so `git ls-files -s` agrees with the table
below and a checked-out file differs from upstream in line endings only — the same shape as the
`../fidelityfx/` tree:
| File | Blob sha |
|---|---|
| `LICENSE.txt` | `3c5c80518fc83a2532f8445f925d46677eca7782` |
| `sdk/include/FidelityFX/host/ffx_fsr3.h` | `62bf127fcbf0625d057b2f6ff0d72cdee9716f74` |
| `sdk/include/FidelityFX/host/ffx_interface.h` | `3a7277afae65bd651d1ae8ea4a356bc122df052c` |
| `sdk/include/FidelityFX/host/ffx_fsr3upscaler.h` | `83bee5d9cdf84ed32dd974cc447599d30d62be82` |
| `sdk/include/FidelityFX/host/ffx_frameinterpolation.h` | `4a98ad05eee506fed7ed17e79dfece37a6aeca77` |
| `sdk/include/FidelityFX/host/ffx_opticalflow.h` | `f18a6ddabb9c89cb8eede03c00d92869ca1a3764` |
| `sdk/include/FidelityFX/host/ffx_assert.h` | `11718eca730e0eae6a7b9f6db5070a649bab31ef` |
| `sdk/include/FidelityFX/host/ffx_types.h` | `64494df9eff3f14d29f97e9add9d85e83e8a4c07` |
| `sdk/include/FidelityFX/host/ffx_error.h` | `d1d466fec4ba3964ce9121850a51cdc42d0aa685` |
| `sdk/include/FidelityFX/host/ffx_util.h` | `123cd1969f6307601be8d94e902fe6e5a2b0d77c` |
| `sdk/include/FidelityFX/gpu/fsr3upscaler/ffx_fsr3upscaler_resources.h` | `d98cfcc0602c7dd59ece0960fd02dbdaef0bb897` |
## What is here, and what is not
Kept in upstream's `sdk/include/FidelityFX/…` layout because the headers include each other by
`<FidelityFX/host/…>` path; the CMake target `fl_fsr3_host_headers` adds `sdk/include` as a
`SYSTEM` include directory and links nothing.
| | |
|---|---|
| **Here** | the ten-file closure of `ffx_fsr3.h` above, and `LICENSE.txt` |
| **Not here** | everything else under `sdk/` — the backends (`ffx_dx12.h`, `ffx_vk.h`), every `.cpp`, every shader, every other effect's host header, the samples and `Kits/`. Nothing is vendored ahead of a consumer (`docs/18_GPU_VENDOR_APIS.md`) |
## How it is consumed
**Types and `decltype` only, never linked.** The Overlay reads exactly one field of the argument
the title passes to one export — `FfxFsr3DispatchUpscaleDescription::renderSize` on
`ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale` — for the upscaler's identity (`FL_UPSCALER_FSR3`)
and render extent. Never the context, never a resource, never the command list (CLAUDE.md
rule 4). `ffxFsr3DispatchFrameGeneration` and `ffxFsr3SkipPresent` are probe-only names
(`SpeaksFsr3Host` in `fl_hook_inventory.h`): checked for existence, never resolved, never called.
@@ -0,0 +1,104 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef FFX_FSR3UPSCALER_RESOURCES_H
#define FFX_FSR3UPSCALER_RESOURCES_H
#if defined(FFX_CPU) || defined(FFX_GPU)
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_NULL 0
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INPUT_OPAQUE_ONLY 1
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INPUT_COLOR 2
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INPUT_MOTION_VECTORS 3
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INPUT_DEPTH 4
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INPUT_EXPOSURE 5
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INPUT_REACTIVE_MASK 6
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INPUT_TRANSPARENCY_AND_COMPOSITION_MASK 7
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_RECONSTRUCTED_PREVIOUS_NEAREST_DEPTH 8
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_DILATED_MOTION_VECTORS 9
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_DILATED_DEPTH 10
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INTERNAL_UPSCALED_COLOR 11
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_LOCK_STATUS 12
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_NEW_LOCKS 13
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_PREPARED_INPUT_COLOR 14
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_LUMA_HISTORY 15
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_DEBUG_OUTPUT 16
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_LANCZOS_LUT 17
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SPD_ATOMIC_COUNT 18
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_UPSCALED_OUTPUT 19
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_RCAS_INPUT 20
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_LOCK_STATUS_1 21
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_LOCK_STATUS_2 22
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INTERNAL_UPSCALED_COLOR_1 23
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INTERNAL_UPSCALED_COLOR_2 24
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INTERNAL_DEFAULT_REACTIVITY 25
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INTERNAL_DEFAULT_TRANSPARENCY_AND_COMPOSITION 26
#define FFX_FSR3UPSCALER_RESOURCE_IDENTITIER_UPSAMPLE_MAXIMUM_BIAS_LUT 27
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_DILATED_REACTIVE_MASKS 28
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE 29 // same as FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_0
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_0 29
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_1 30
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_2 31
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_3 32
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_4 33
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_5 34
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_6 35
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_7 36
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_8 37
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_9 38
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_10 39
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_11 40
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_12 41
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_INTERNAL_DEFAULT_EXPOSURE 42
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_AUTO_EXPOSURE 43
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_AUTOREACTIVE 44
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_AUTOCOMPOSITION_DEPRECATED 45
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_PREV_PRE_ALPHA_COLOR 46
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_PREV_POST_ALPHA_COLOR 47
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_PREV_PRE_ALPHA_COLOR_1 48
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_PREV_POST_ALPHA_COLOR_1 49
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_PREV_PRE_ALPHA_COLOR_2 50
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_PREV_POST_ALPHA_COLOR_2 51
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_PREVIOUS_DILATED_MOTION_VECTORS 52
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_LUMA_HISTORY_1 53
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_LUMA_HISTORY_2 54
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_LOCK_INPUT_LUMA 55
// Shading change detection mip level setting, value must be in the range [FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_0, FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_12]
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_SHADING_CHANGE FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_4
#define FFX_FSR3UPSCALER_SHADING_CHANGE_MIP_LEVEL (FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE_MIPMAP_SHADING_CHANGE - FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_SCENE_LUMINANCE)
#define FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_COUNT 56
#define FFX_FSR3UPSCALER_CONSTANTBUFFER_IDENTIFIER_FSR3UPSCALER 0
#define FFX_FSR3UPSCALER_CONSTANTBUFFER_IDENTIFIER_SPD 1
#define FFX_FSR3UPSCALER_CONSTANTBUFFER_IDENTIFIER_RCAS 2
#define FFX_FSR3UPSCALER_CONSTANTBUFFER_IDENTIFIER_GENREACTIVE 3
#define FFX_FSR3UPSCALER_AUTOREACTIVEFLAGS_APPLY_TONEMAP 1
#define FFX_FSR3UPSCALER_AUTOREACTIVEFLAGS_APPLY_INVERSETONEMAP 2
#define FFX_FSR3UPSCALER_AUTOREACTIVEFLAGS_APPLY_THRESHOLD 4
#define FFX_FSR3UPSCALER_AUTOREACTIVEFLAGS_USE_COMPONENTS_MAX 8
#endif // #if defined(FFX_CPU) || defined(FFX_GPU)
#endif //!defined( FFX_FSR3UPSCALER_RESOURCES_H )
@@ -0,0 +1,151 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <FidelityFX/host/ffx_types.h>
#include <FidelityFX/host/ffx_util.h>
#ifdef __cplusplus
extern "C" {
#endif // #ifdef __cplusplus
/// @defgroup Asserts Asserts
/// Asserts used by FidelityFX SDK functions
///
/// @ingroup ffxHost
#ifdef _DEBUG
#ifdef _WIN32
#ifdef DISABLE_FFX_DEBUG_BREAK
#define FFX_DEBUG_BREAK \
{ \
}
#else
/// Macro to force the debugger to break at this point in the code.
///
/// @ingroup Asserts
#define FFX_DEBUG_BREAK __debugbreak();
#endif
#else
#define FFX_DEBUG_BREAK \
{ \
}
#endif
#else
// don't allow debug break in release builds.
#define FFX_DEBUG_BREAK
#endif
/// A typedef for the callback function for assert printing.
///
/// This can be used to re-route printing of assert messages from the FFX backend
/// to another destination. For example instead of the default behaviour of printing
/// the assert messages to the debugger's TTY the message can be re-routed to a
/// MessageBox in a GUI application.
///
/// @param [in] message The message generated by the assert.
///
/// @ingroup Asserts
typedef void (*FfxAssertCallback)(const char* message);
/// Function to report an assert.
///
/// @param [in] file The name of the file as a string.
/// @param [in] line The index of the line in the file.
/// @param [in] condition The boolean condition that was tested.
/// @param [in] msg The optional message to print.
///
/// @returns
/// Always returns true.
///
/// @ingroup Asserts
FFX_API bool ffxAssertReport(const char* file, int32_t line, const char* condition, const char* msg);
/// Provides the ability to set a callback for assert messages.
///
/// @param [in] callback The callback function that will receive assert messages.
///
/// @ingroup Asserts
FFX_API void ffxAssertSetPrintingCallback(FfxAssertCallback callback);
#ifdef _DEBUG
/// Standard assert macro.
///
/// @ingroup Asserts
#define FFX_ASSERT(condition) \
do \
{ \
if (!(condition) && ffxAssertReport(__FILE__, __LINE__, #condition, NULL)) \
FFX_DEBUG_BREAK \
} while (0)
/// Assert macro with message.
///
/// @ingroup Asserts
#define FFX_ASSERT_MESSAGE(condition, msg) \
do \
{ \
if (!(condition) && ffxAssertReport(__FILE__, __LINE__, #condition, msg)) \
FFX_DEBUG_BREAK \
} while (0)
/// Assert macro that always fails.
///
/// @ingroup Asserts
#define FFX_ASSERT_FAIL(message) \
do \
{ \
ffxAssertReport(__FILE__, __LINE__, NULL, message); \
FFX_DEBUG_BREAK \
} while (0)
#else
// asserts disabled
#define FFX_ASSERT(condition) \
do \
{ \
FFX_UNUSED(condition); \
} while (0)
#define FFX_ASSERT_MESSAGE(condition, message) \
do \
{ \
FFX_UNUSED(condition); \
FFX_UNUSED(message); \
} while (0)
#define FFX_ASSERT_FAIL(message) \
do \
{ \
FFX_UNUSED(message); \
} while (0)
#endif // #if _DEBUG
/// Simple static assert.
///
/// @ingroup Asserts
#define FFX_STATIC_ASSERT(condition) static_assert(condition, #condition)
#ifdef __cplusplus
}
#endif // #ifdef __cplusplus
@@ -0,0 +1,77 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <FidelityFX/host/ffx_types.h>
/// @defgroup Errors Error Codes
/// Error codes returned from FidelityFX SDK functions
///
/// @ingroup ffxHost
/// Typedef for error codes returned from functions in the FidelityFX SDK.
///
/// @ingroup Errors
typedef int32_t FfxErrorCode;
/// Error codes and their meaning
///
/// @ingroup Errors
typedef enum FfxErrorCodes {
FFX_OK = 0, ///< The operation completed successfully.
FFX_ERROR_INVALID_POINTER = 0x80000000, ///< The operation failed due to an invalid pointer.
FFX_ERROR_INVALID_ALIGNMENT = 0x80000001, ///< The operation failed due to an invalid alignment.
FFX_ERROR_INVALID_SIZE = 0x80000002, ///< The operation failed due to an invalid size.
FFX_EOF = 0x80000003, ///< The end of the file was encountered.
FFX_ERROR_INVALID_PATH = 0x80000004, ///< The operation failed because the specified path was invalid.
FFX_ERROR_EOF = 0x80000005, ///< The operation failed because end of file was reached.
FFX_ERROR_MALFORMED_DATA = 0x80000006, ///< The operation failed because of some malformed data.
FFX_ERROR_OUT_OF_MEMORY = 0x80000007, ///< The operation failed because it ran out memory.
FFX_ERROR_INCOMPLETE_INTERFACE = 0x80000008, ///< The operation failed because the interface was not fully configured.
FFX_ERROR_INVALID_ENUM = 0x80000009, ///< The operation failed because of an invalid enumeration value.
FFX_ERROR_INVALID_ARGUMENT = 0x8000000a, ///< The operation failed because an argument was invalid.
FFX_ERROR_OUT_OF_RANGE = 0x8000000b, ///< The operation failed because a value was out of range.
FFX_ERROR_NULL_DEVICE = 0x8000000c, ///< The operation failed because a device was null.
FFX_ERROR_BACKEND_API_ERROR = 0x8000000d, ///< The operation failed because the backend API returned an error code.
FFX_ERROR_INSUFFICIENT_MEMORY = 0x8000000e, ///< The operation failed because there was not enough memory.
}FfxErrorCodes;
/// Helper macro to return error code y from a function when a specific condition, x, is not met.
///
/// @ingroup Errors
#define FFX_RETURN_ON_ERROR(x, y) \
if (!(x)) \
{ \
return (y); \
}
/// Helper macro to return error code x from a function when it is not FFX_OK.
///
/// @ingroup Errors
#define FFX_VALIDATE(x) \
{ \
FfxErrorCode ret = x; \
FFX_RETURN_ON_ERROR(ret == FFX_OK, ret); \
}
@@ -0,0 +1,242 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// @defgroup FRAMEINTERPOLATION
#pragma once
// Include the interface for the backend of the Frameinterpolation API.
#include <FidelityFX/host/ffx_interface.h>
/// FidelityFX Frameinterpolation major version.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
#define FFX_FRAMEINTERPOLATION_VERSION_MAJOR (1)
/// FidelityFX Frameinterpolation minor version.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
#define FFX_FRAMEINTERPOLATION_VERSION_MINOR (0)
/// FidelityFX Frameinterpolation patch version.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
#define FFX_FRAMEINTERPOLATION_VERSION_PATCH (1)
/// FidelityFX Frame Interpolation context count
///
/// Defines the number of internal effect contexts required by Frame Interpolation
///
/// @ingroup ffxFrameInterpolation
#define FFX_FRAMEINTERPOLATION_CONTEXT_COUNT (1)
/// The size of the context specified in 32bit values.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
#define FFX_FRAMEINTERPOLATION_CONTEXT_SIZE (FFX_SDK_DEFAULT_CONTEXT_SIZE)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of all the passes which constitute the FSR3 algorithm.
///
/// FSR3 is implemented as a composite of several compute passes each
/// computing a key part of the final result. Each call to the
/// <c><i>FfxFsr3ScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single pass included in <c><i>FfxFsr3Pass</i></c>. For a
/// more comprehensive description of each pass, please refer to the FSR3
/// reference documentation.
///
/// Please note in some cases e.g.: <c><i>FFX_FSR3_PASS_ACCUMULATE</i></c>
/// and <c><i>FFX_FSR3_PASS_ACCUMULATE_SHARPEN</i></c> either one pass or the
/// other will be used (they are mutually exclusive). The choice of which will
/// depend on the way the <c><i>FfxFsr3Context</i></c> is created and the
/// precise contents of <c><i>FfxFsr3DispatchParamters</i></c> each time a call
/// is made to <c><i>ffxFsr3ContextDispatch</i></c>.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
typedef enum FfxFrameInterpolationPass
{
FFX_FRAMEINTERPOLATION_PASS_SETUP,
FFX_FRAMEINTERPOLATION_PASS_RECONSTRUCT_PREV_DEPTH,
FFX_FRAMEINTERPOLATION_PASS_GAME_MOTION_VECTOR_FIELD,
FFX_FRAMEINTERPOLATION_PASS_OPTICAL_FLOW_VECTOR_FIELD,
FFX_FRAMEINTERPOLATION_PASS_DISOCCLUSION_MASK,
FFX_FRAMEINTERPOLATION_PASS_INTERPOLATION,
FFX_FRAMEINTERPOLATION_PASS_INPAINTING_PYRAMID,
FFX_FRAMEINTERPOLATION_PASS_INPAINTING,
FFX_FRAMEINTERPOLATION_PASS_GAME_VECTOR_FIELD_INPAINTING_PYRAMID,
FFX_FRAMEINTERPOLATION_PASS_DEBUG_VIEW,
FFX_FRAMEINTERPOLATION_PASS_COUNT ///< The number of passes performed by FrameInterpolation.
} FfxFrameInterpolationPass;
// forward declarations
struct FfxFrameInterpolationContext;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxFrameInterpolationContext</i></c>. See <c><i>FfxFrameInterpolationContextDescription</i></c>.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
typedef enum FfxFrameInterpolationInitializationFlagBits {
FFX_FRAMEINTERPOLATION_ENABLE_DEPTH_INVERTED = (1<<0), ///< A bit indicating that the input depth buffer data provided is inverted [1..0].
FFX_FRAMEINTERPOLATION_ENABLE_DEPTH_INFINITE = (1<<1), ///< A bit indicating that the input depth buffer data provided is using an infinite far plane.
FFX_FRAMEINTERPOLATION_ENABLE_TEXTURE1D_USAGE = (1<<2), ///< A bit indicating that the backend should use 1D textures.
FFX_FRAMEINTERPOLATION_ENABLE_HDR_COLOR_INPUT = (1<<3) ///< A bit indicating that HDR values are present in the imaging pipeline.
} FfxFrameInterpolationInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize
/// FidelityFX Frameinterpolation upscaling.
///
/// @ingroup FRAMEINTERPOLATION
typedef struct FfxFrameInterpolationContextDescription {
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX SDK
uint32_t flags; ///< A collection of <c><i>FfxFrameInterpolationInitializationFlagBits</i></c>.
FfxDimensions2D maxRenderSize; ///< The maximum size that rendering will be performed at.
FfxDimensions2D displaySize; ///< The size of the presentation resolution
FfxSurfaceFormat backBufferFormat;
} FfxFrameInterpolationContextDescription;
/// A structure encapsulating the FidelityFX Super Resolution 2 context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by FSR3.
///
/// The <c><i>FfxFsr3Context</i></c> object should have a lifetime matching
/// your use of FSR3. Before destroying the FSR3 context care should be taken
/// to ensure the GPU is not accessing the resources created or used by FSR3.
/// It is therefore recommended that the GPU is idle before destroying the
/// FSR3 context.
///
/// @ingroup FRAMEINTERPOLATION
typedef struct FfxFrameInterpolationContext
{
uint32_t data[FFX_FRAMEINTERPOLATION_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxFrameInterpolationContext;
/// Create a FidelityFX Super Resolution 2 context from the parameters
/// programmed to the <c><i>FfxFsr3CreateParams</i></c> structure.
///
/// The context structure is the main object used to interact with the FSR3
/// API, and is responsible for the management of the internal resources used
/// by the FSR3 algorithm. When this API is called, multiple calls will be
/// made via the pointers contained in the <c><i>callbacks</i></c> structure.
/// These callbacks will attempt to retreive the device capabilities, and
/// create the internal resources, and pipelines required by FSR3's
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxFsr3Context</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The flags included in the <c><i>flags</i></c> field of
/// <c><i>FfxFsr3Context</i></c> how match the configuration of your
/// application as well as the intended use of FSR3. It is important that these
/// flags are set correctly (as well as a correct programmed
/// <c><i>FfxFsr3DispatchDescription</i></c>) to ensure correct operation. It is
/// recommended to consult the overview documentation for further details on
/// how FSR3 should be integerated into an application.
///
/// When the <c><i>FfxFsr3Context</i></c> is created, you should use the
/// <c><i>ffxFsr3ContextDispatch</i></c> function each frame where FSR3
/// upscaling should be applied. See the documentation of
/// <c><i>ffxFsr3ContextDispatch</i></c> for more details.
///
/// The <c><i>FfxFsr3Context</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or FSR3 upscaling is
/// disabled by a user. To destroy the FSR3 context you should call
/// <c><i>ffxFsr3ContextDestroy</i></c>.
///
/// @param [out] context A pointer to a <c><i>FfxFsr3Context</i></c> structure to populate.
/// @param [in] contextDescription A pointer to a <c><i>FfxFsr3ContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxFsr3ContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FRAMEINTERPOLATION
FFX_API FfxErrorCode ffxFrameInterpolationContextCreate(FfxFrameInterpolationContext* context, FfxFrameInterpolationContextDescription* contextDescription);
typedef enum FfxFrameInterpolationDispatchFlags
{
FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_TEAR_LINES = (1 << 0), ///< A bit indicating that the debug tear lines will be drawn to the interpolated output.
FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_VIEW = (1 << 1), ///< A bit indicating that the interpolated output resource will contain debug views with relevant information.
} FfxFrameInterpolationDispatchFlags;
typedef struct FfxFrameInterpolationDispatchDescription {
uint32_t flags; ///< combination of FfxFrameInterpolationDispatchFlags
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record frame interpolation commands into.
FfxDimensions2D displaySize; ///< The destination output dimensions
FfxDimensions2D renderSize; ///< The dimensions used to render game content, dilatedDepth, dilatedMotionVectors are expected to be of ths size.
FfxResource currentBackBuffer; ///< The current presentation color, if currentBackBuffer_HUDLess is not used, this will be used as interpolation source data.
FfxResource currentBackBuffer_HUDLess; ///< The current presentation color without HUD content, when use it will be used as interpolation source data.
FfxResource output; ///< The output resource where to store the interpolated result.
FfxResource dilatedDepth; ///< The dilated depth buffer data (see example computation in the FfxFsr3Upscaler effect)
FfxResource dilatedMotionVectors; ///< The dilated motion vector data (see example computation in the FfxFsr3Upscaler effect)
FfxResource reconstructPrevNearDepth; ///< The estimated previous frame depth buffer (see example computation in the FfxFsr3Upscaler effect)
FfxRect2D interpolationRect; ///< The area of the backbuffer that should be used for interpolation in case only a part of the screen is used e.g. due to movie bars
FfxResource opticalFlowVector; ///< The optical flow motion vectors (see example computation in the FfxOpticalFlow effect)
FfxResource opticalFlowSceneChangeDetection; ///< The optical flow scene change detection data
FfxDimensions2D opticalFlowBufferSize; ///< The optical flow motion vector resource dimensions
FfxFloatCoords2D opticalFlowScale; ///< The optical flow motion vector scale factor, used to scale resoure values into [0.0,1.0] range.
int opticalFlowBlockSize; ///< The optical flow block dimension size
float cameraNear; ///< The distance to the near plane of the camera.
float cameraFar; ///< The distance to the far plane of the camera. This is used only used in case of non infinite depth.
float cameraFovAngleVertical; ///< The camera angle field of view in the vertical direction (expressed in radians).
float viewSpaceToMetersFactor; ///< The unit to scale view space coordinates to meters.
float frameTimeDelta; ///< The time elapsed since the last frame (expressed in milliseconds).
bool reset; ///< A boolean value which when set to true, indicates the camera has moved discontinuously.
FfxBackbufferTransferFunction backBufferTransferFunction; ///< The transfer function use to convert interpolation source color data to linear RGB.
float minMaxLuminance[2]; ///< Min and max luminance values, used when converting HDR colors to linear RGB
} FfxFrameInterpolationDispatchDescription;
FFX_API FfxErrorCode ffxFrameInterpolationDispatch(FfxFrameInterpolationContext* context, const FfxFrameInterpolationDispatchDescription* params);
/// Destroy the FidelityFX Super Resolution context.
///
/// @param [out] context A pointer to a <c><i>FfxFsr3Context</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FRAMEINTERPOLATION
FFX_API FfxErrorCode ffxFrameInterpolationContextDestroy(FfxFrameInterpolationContext* context);
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,503 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// @defgroup FSR3
#pragma once
// Include the interface for the backend of the FSR3 API.
#include <FidelityFX/host/ffx_interface.h>
#include <FidelityFX/host/ffx_fsr3upscaler.h>
#include <FidelityFX/host/ffx_frameinterpolation.h>
#include <FidelityFX/host/ffx_opticalflow.h>
/// FidelityFX Super Resolution 3 major version.
///
/// @ingroup FSR3
#define FFX_FSR3_VERSION_MAJOR (3)
/// FidelityFX Super Resolution 0 minor version.
///
/// @ingroup FSR3
#define FFX_FSR3_VERSION_MINOR (0)
/// FidelityFX Super Resolution 0 patch version.
///
/// @ingroup FSR3
#define FFX_FSR3_VERSION_PATCH (4)
/// FidelityFX Super Resolution 3 context count
///
/// Defines the number of internal effect contexts required by FSR3 (+1 for proxy swapchain)
///
/// @ingroup ffxFsr3
#define FFX_FSR3_CONTEXT_COUNT (FFX_FSR3UPSCALER_CONTEXT_COUNT + FFX_OPTICALFLOW_CONTEXT_COUNT + FFX_FRAMEINTERPOLATION_CONTEXT_COUNT + 1)
/// The size of the context specified in 32bit values.
///
/// @ingroup FSR3
#define FFX_FSR3_CONTEXT_SIZE (16536)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
///// An enumeration of all the passes which constitute the FSR3 algorithm.
/////
///// FSR3 is implemented as a composite of several compute passes each
///// computing a key part of the final result. Each call to the
///// <c><i>FfxFsr3ScheduleGpuJobFunc</i></c> callback function will
///// correspond to a single pass included in <c><i>FfxFsr3Pass</i></c>. For a
///// more comprehensive description of each pass, please refer to the FSR3
///// reference documentation.
/////
///// Please note in some cases e.g.: <c><i>FFX_FSR3_PASS_ACCUMULATE</i></c>
///// and <c><i>FFX_FSR3_PASS_ACCUMULATE_SHARPEN</i></c> either one pass or the
///// other will be used (they are mutually exclusive). The choice of which will
///// depend on the way the <c><i>FfxFsr3Context</i></c> is created and the
///// precise contents of <c><i>FfxFsr3DispatchParamters</i></c> each time a call
///// is made to <c><i>ffxFsr3ContextDispatch</i></c>.
/////
///// @ingroup FSR3
//typedef enum FfxFsr3Pass
//{
// // no special FSR3 pipelines
//
// FFX_FSR3_PASS_COUNT ///< The number of passes performed by FSR3.
//} FfxFsr3Pass;
/// An enumeration of all the quality modes supported by FidelityFX Super
/// Resolution 2 upscaling.
///
/// In order to provide a consistent user experience across multiple
/// applications which implement FSR3. It is strongly recommended that the
/// following preset scaling factors are made available through your
/// application's user interface.
///
/// If your application does not expose the notion of preset scaling factors
/// for upscaling algorithms (perhaps instead implementing a fixed ratio which
/// is immutable) or implementing a more dynamic scaling scheme (such as
/// dynamic resolution scaling), then there is no need to use these presets.
///
/// Please note that <c><i>FFX_FSR3_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> is
/// an optional mode which may introduce significant quality degradation in the
/// final image. As such it is recommended that you evaluate the final results
/// of using this scaling mode before deciding if you should include it in your
/// application.
///
/// @ingroup FSR3
typedef enum FfxFsr3QualityMode {
FFX_FSR3_QUALITY_MODE_QUALITY = 1, ///< Perform upscaling with a per-dimension upscaling ratio of 1.5x.
FFX_FSR3_QUALITY_MODE_BALANCED = 2, ///< Perform upscaling with a per-dimension upscaling ratio of 1.7x.
FFX_FSR3_QUALITY_MODE_PERFORMANCE = 3, ///< Perform upscaling with a per-dimension upscaling ratio of 2.0x.
FFX_FSR3_QUALITY_MODE_ULTRA_PERFORMANCE = 4 ///< Perform upscaling with a per-dimension upscaling ratio of 3.0x.
} FfxFsr3QualityMode;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxFsr3Context</i></c>. See <c><i>FfxFsr3ContextDescription</i></c>.
///
/// @ingroup FSR3
typedef enum FfxFsr3InitializationFlagBits {
FFX_FSR3_ENABLE_HIGH_DYNAMIC_RANGE = (1<<0), ///< A bit indicating if the input color data provided to all inputs is using a high-dynamic range.
FFX_FSR3_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS = (1<<1), ///< A bit indicating if the motion vectors are rendered at display resolution.
FFX_FSR3_ENABLE_MOTION_VECTORS_JITTER_CANCELLATION = (1<<2), ///< A bit indicating that the motion vectors have the jittering pattern applied to them.
FFX_FSR3_ENABLE_DEPTH_INVERTED = (1<<3), ///< A bit indicating that the input depth buffer data provided is inverted [1..0].
FFX_FSR3_ENABLE_DEPTH_INFINITE = (1<<4), ///< A bit indicating that the input depth buffer data provided is using an infinite far plane.
FFX_FSR3_ENABLE_AUTO_EXPOSURE = (1<<5), ///< A bit indicating if automatic exposure should be applied to input color data.
FFX_FSR3_ENABLE_DYNAMIC_RESOLUTION = (1<<6), ///< A bit indicating that the application uses dynamic resolution scaling.
FFX_FSR3_ENABLE_TEXTURE1D_USAGE = (1<<7), ///< A bit indicating that the backend should use 1D textures.
FFX_FSR3_ENABLE_DEBUG_CHECKING = (1<<8), ///< A bit indicating that the runtime should check some API values and report issues.
FFX_FSR3_ENABLE_UPSCALING_ONLY = (1<<9), ///, A bit indicating that the context will only be used for upscaling
FFX_FSR3_ENABLE_HDR_UPSCALE_SDR_FINALOUTPUT = (1<<10), ///, A bit indicating if the input color data provided to UPSCALE is using a high-dynamic range, final output SDR.
FFX_FSR3_ENABLE_SDR_UPSCALE_HDR_FINALOUTPUT = (1<<11), ///, A bit indicating if the input color data provided to UPSCALE is using SDR, final output is high-dynamic range.
FFX_FSR3_ENABLE_ASYNC_WORKLOAD_SUPPORT = (1<<12),
} FfxFsr3InitializationFlagBits;
typedef enum FfxFsr3FrameGenerationFlags
{
FFX_FSR3_FRAME_GENERATION_FLAG_DRAW_DEBUG_TEAR_LINES = FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_TEAR_LINES, ///< A bit indicating that the debug tear lines will be drawn to the interpolated output.
FFX_FSR3_FRAME_GENERATION_FLAG_DRAW_DEBUG_VIEW = FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_VIEW, ///< A bit indicating that the interpolated output resource will contain debug views with relevant information.
} FfxFsr3FrameGenerationFlags;
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Super Resolution 3 upscaling.
///
/// @ingroup FSR3
typedef struct FfxFsr3ContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxFsr3InitializationFlagBits</i></c>.
FfxDimensions2D maxRenderSize; ///< The maximum size that rendering will be performed at.
FfxDimensions2D upscaleOutputSize; ///< The size of the presentation resolution targeted by the upscaling process.
FfxDimensions2D displaySize; ///< The size of the presentation resolution targeted by the frame interpolation process.
FfxInterface backendInterfaceSharedResources; ///< A set of pointers to the backend implementation for FidelityFX SDK
FfxInterface backendInterfaceUpscaling; ///< A set of pointers to the backend implementation for FidelityFX SDK
FfxInterface backendInterfaceFrameInterpolation; ///< A set of pointers to the backend implementation for FidelityFX SDK
FfxFsr3UpscalerMessage fpMessage; ///< A pointer to a function that can recieve messages from the runtime.
FfxSurfaceFormat backBufferFormat; ///< The format of the swapchain surface
} FfxFsr3ContextDescription;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX Super Resolution 3.
///
/// @ingroup FSR3
typedef struct FfxFsr3DispatchUpscaleDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR2 rendering commands into.
FfxResource color; ///< A <c><i>FfxResource</i></c> containing the color buffer for the current frame (at render resolution).
FfxResource depth; ///< A <c><i>FfxResource</i></c> containing 32bit depth values for the current frame (at render resolution).
FfxResource motionVectors; ///< A <c><i>FfxResource</i></c> containing 2-dimensional motion vectors (at render resolution if <c><i>FFX_FSR2_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS</i></c> is not set).
FfxResource exposure; ///< A optional <c><i>FfxResource</i></c> containing a 1x1 exposure value.
FfxResource reactive; ///< A optional <c><i>FfxResource</i></c> containing alpha value of reactive objects in the scene.
FfxResource transparencyAndComposition; ///< A optional <c><i>FfxResource</i></c> containing alpha value of special objects in the scene.
FfxResource upscaleOutput; ///< A <c><i>FfxResource</i></c> containing the output color buffer for the current frame (at presentation resolution).
FfxFloatCoords2D jitterOffset; ///< The subpixel jitter offset applied to the camera.
FfxFloatCoords2D motionVectorScale; ///< The scale factor to apply to motion vectors.
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
bool enableSharpening; ///< Enable an additional sharpening pass.
float sharpness; ///< The sharpness value between 0 and 1, where 0 is no additional sharpness and 1 is maximum additional sharpness.
float frameTimeDelta; ///< The time elapsed since the last frame (expressed in milliseconds).
float preExposure; ///< The pre exposure value (must be > 0.0f)
bool reset; ///< A boolean value which when set to true, indicates the camera has moved discontinuously.
float cameraNear; ///< The distance to the near plane of the camera.
float cameraFar; ///< The distance to the far plane of the camera. This is used only used in case of non infinite depth.
float cameraFovAngleVertical; ///< The camera angle field of view in the vertical direction (expressed in radians).
float viewSpaceToMetersFactor; ///< The scale factor to convert view space units to meters
} FfxFsr3DispatchUpscaleDescription;
FFX_API FfxErrorCode ffxFsr3DispatchFrameGeneration(const FfxFrameGenerationDispatchDescription* desc);
/// A structure encapsulating the parameters for automatic generation of a reactive mask
///
/// @ingroup FSR3
typedef struct FfxFsr3GenerateReactiveDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR3 rendering commands into.
FfxResource colorOpaqueOnly; ///< A <c><i>FfxResource</i></c> containing the opaque only color buffer for the current frame (at render resolution).
FfxResource colorPreUpscale; ///< A <c><i>FfxResource</i></c> containing the opaque+translucent color buffer for the current frame (at render resolution).
FfxResource outReactive; ///< A <c><i>FfxResource</i></c> containing the surface to generate the reactive mask into.
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
float scale; ///< A value to scale the output
float cutoffThreshold; ///< A threshold value to generate a binary reactive mask
float binaryValue;
uint32_t flags; ///< Flags to determine how to generate the reactive mask
} FfxFsr3GenerateReactiveDescription;
/// A structure encapsulating the FidelityFX Super Resolution 3 context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by FSR3.
///
/// The <c><i>FfxFsr3Context</i></c> object should have a lifetime matching
/// your use of FSR3. Before destroying the FSR3 context care should be taken
/// to ensure the GPU is not accessing the resources created or used by FSR3.
/// It is therefore recommended that the GPU is idle before destroying the
/// FSR3 context.
///
/// @ingroup FSR3
typedef struct FfxFsr3Context
{
uint32_t data[ FFX_FSR3UPSCALER_CONTEXT_SIZE
+ FFX_OPTICALFLOW_CONTEXT_SIZE
+ FFX_FRAMEINTERPOLATION_CONTEXT_SIZE
+ (16536)]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxFsr3Context;
/// Create a FidelityFX Super Resolution 3 context from the parameters
/// programmed to the <c><i>FfxFsr3CreateParams</i></c> structure.
///
/// The context structure is the main object used to interact with the FSR3
/// API, and is responsible for the management of the internal resources used
/// by the FSR3 algorithm. When this API is called, multiple calls will be
/// made via the pointers contained in the <c><i>callbacks</i></c> structure.
/// These callbacks will attempt to retreive the device capabilities, and
/// create the internal resources, and pipelines required by FSR3's
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxFsr3Context</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The flags included in the <c><i>flags</i></c> field of
/// <c><i>FfxFsr3Context</i></c> how match the configuration of your
/// application as well as the intended use of FSR3. It is important that these
/// flags are set correctly (as well as a correct programmed
/// <c><i>FfxFsr3DispatchDescription</i></c>) to ensure correct operation. It is
/// recommended to consult the overview documentation for further details on
/// how FSR3 should be integerated into an application.
///
/// When the <c><i>FfxFsr3Context</i></c> is created, you should use the
/// <c><i>ffxFsr3ContextDispatch</i></c> function each frame where FSR3
/// upscaling should be applied. See the documentation of
/// <c><i>ffxFsr3ContextDispatch</i></c> for more details.
///
/// The <c><i>FfxFsr3Context</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or FSR3 upscaling is
/// disabled by a user. To destroy the FSR3 context you should call
/// <c><i>ffxFsr3ContextDestroy</i></c>.
///
/// @param [out] context A pointer to a <c><i>FfxFsr3Context</i></c> structure to populate.
/// @param [in] contextDescription A pointer to a <c><i>FfxFsr3ContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxFsr3ContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3ContextCreate(FfxFsr3Context* context, FfxFsr3ContextDescription* contextDescription);
/// Dispatch the various passes that constitute FidelityFX Super Resolution 3 Upscaling.
///
/// FSR3 is a composite effect, meaning that it is compromised of multiple
/// constituent passes (implemented as one or more clears, copies and compute
/// dispatches). The <c><i>ffxFsr3ContextDispatchUpscale</i></c> function is the
/// function which (via the use of the functions contained in the
/// <c><i>callbacks</i></c> field of the <c><i>FfxFsr3Context</i></c>
/// structure) utlimately generates the sequence of graphics API calls required
/// each frame.
///
/// As with the creation of the <c><i>FfxFsr3Context</i></c> correctly
/// programming the <c><i>dispatchParams</i></c> is key to ensuring
/// the correct operation of FSR3. It is particularly important to ensure that
/// camera jitter is correctly applied to your application's projection matrix
/// (or camera origin for raytraced applications). FSR3 provides the
/// <c><i>ffxFsr3GetJitterPhaseCount</i></c> and
/// <c><i>ffxFsr3GetJitterOffset</i></c> entry points to help applications
/// correctly compute the camera jitter. Whatever jitter pattern is used by the
/// application it should be correctly programmed to the
/// <c><i>jitterOffset</i></c> field of the <c><i>dispatchParams</i></c>
/// structure. For more guidance on camera jitter please consult the
/// documentation for <c><i>ffxFsr3GetJitterOffset</i></c> as well as the
/// accompanying overview documentation for FSR3.
///
/// @param [in] context A pointer to a <c><i>FfxFsr3Context</i></c> structure.
/// @param [in] dispatchParams A pointer to a <c><i>FfxFsr3DispatchUpscaleDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchParams</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_OUT_OF_RANGE The operation failed because <c><i>dispatchParams.renderSize</i></c> was larger than the maximum render resolution.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the device inside the context was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3ContextDispatchUpscale(FfxFsr3Context* context, const FfxFsr3DispatchUpscaleDescription* dispatchParams);
FFX_API FfxErrorCode ffxFsr3SkipPresent(FfxFsr3Context* context);
/// A helper function generate a Reactive mask from an opaque only texure and one containing translucent objects.
///
/// @param [in] context A pointer to a <c><i>FfxFsr3Context</i></c> structure.
/// @param [in] params A pointer to a <c><i>FfxFsr3GenerateReactiveDescription</i></c> structure
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3ContextGenerateReactiveMask(FfxFsr3Context* context, const FfxFsr3GenerateReactiveDescription* params);
FFX_API FfxErrorCode ffxFsr3ConfigureFrameGeneration(FfxFsr3Context* context, const FfxFrameGenerationConfig* config);
/// Destroy the FidelityFX Super Resolution context.
///
/// @param [out] context A pointer to a <c><i>FfxFsr3Context</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3ContextDestroy(FfxFsr3Context* context);
/// Get the upscale ratio from the quality mode.
///
/// The following table enumerates the mapping of the quality modes to
/// per-dimension scaling ratios.
///
/// Quality preset | Scale factor
/// ----------------------------------------------------- | -------------
/// <c><i>FFX_FSR3_QUALITY_MODE_NATIVEAA</i></c> | 1.0x
/// <c><i>FFX_FSR3_QUALITY_MODE_QUALITY</i></c> | 1.5x
/// <c><i>FFX_FSR3_QUALITY_MODE_BALANCED</i></c> | 1.7x
/// <c><i>FFX_FSR3_QUALITY_MODE_PERFORMANCE</i></c> | 2.0x
/// <c><i>FFX_FSR3_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> | 3.0x
///
/// Passing an invalid <c><i>qualityMode</i></c> will return 0.0f.
///
/// @param [in] qualityMode The quality mode preset.
///
/// @returns
/// The upscaling the per-dimension upscaling ratio for
/// <c><i>qualityMode</i></c> according to the table above.
///
/// @ingroup FSR3
FFX_API float ffxFsr3GetUpscaleRatioFromQualityMode(FfxFsr3QualityMode qualityMode);
/// A helper function to calculate the rendering resolution from a target
/// resolution and desired quality level.
///
/// This function applies the scaling factor returned by
/// <c><i>ffxFsr3GetUpscaleRatioFromQualityMode</i></c> to each dimension.
///
/// @param [out] renderWidth A pointer to a <c>uint32_t</c> which will hold the calculated render resolution width.
/// @param [out] renderHeight A pointer to a <c>uint32_t</c> which will hold the calculated render resolution height.
/// @param [in] displayWidth The target display resolution width.
/// @param [in] displayHeight The target display resolution height.
/// @param [in] qualityMode The desired quality mode for FSR 2 upscaling.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>renderWidth</i></c> or <c><i>renderHeight</i></c> was <c>NULL</c>.
/// @retval
/// FFX_ERROR_INVALID_ENUM An invalid quality mode was specified.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3GetRenderResolutionFromQualityMode(
uint32_t* renderWidth,
uint32_t* renderHeight,
uint32_t displayWidth,
uint32_t displayHeight,
FfxFsr3QualityMode qualityMode);
/// A helper function to calculate the jitter phase count from display
/// resolution.
///
/// For more detailed information about the application of camera jitter to
/// your application's rendering please refer to the
/// <c><i>ffxFsr3GetJitterOffset</i></c> function.
///
/// The table below shows the jitter phase count which this function
/// would return for each of the quality presets.
///
/// Quality preset | Scale factor | Phase count
/// ----------------------------------------------------- | ------------- | ---------------
/// <c><i>FFX_FSR3_QUALITY_MODE_QUALITY</i></c> | 1.5x | 18
/// <c><i>FFX_FSR3_QUALITY_MODE_BALANCED</i></c> | 1.7x | 23
/// <c><i>FFX_FSR3_QUALITY_MODE_PERFORMANCE</i></c> | 2.0x | 32
/// <c><i>FFX_FSR3_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> | 3.0x | 72
/// Custom | [1..n]x | ceil(8*n^2)
///
/// @param [in] renderWidth The render resolution width.
/// @param [in] displayWidth The display resolution width.
///
/// @returns
/// The jitter phase count for the scaling factor between <c><i>renderWidth</i></c> and <c><i>displayWidth</i></c>.
///
/// @ingroup FSR3
FFX_API int32_t ffxFsr3GetJitterPhaseCount(int32_t renderWidth, int32_t displayWidth);
/// A helper function to calculate the subpixel jitter offset.
///
/// FSR3 relies on the application to apply sub-pixel jittering while rendering.
/// This is typically included in the projection matrix of the camera. To make
/// the application of camera jitter simple, the FSR3 API provides a small set
/// of utility function which computes the sub-pixel jitter offset for a
/// particular frame within a sequence of separate jitter offsets. To begin, the
/// index within the jitter phase must be computed. To calculate the
/// sequence's length, you can call the <c><i>ffxFsr3GetJitterPhaseCount</i></c>
/// function. The index should be a value which is incremented each frame modulo
/// the length of the sequence computed by <c><i>ffxFsr3GetJitterPhaseCount</i></c>.
/// The index within the jitter phase is passed to
/// <c><i>ffxFsr3GetJitterOffset</i></c> via the <c><i>index</i></c> parameter.
///
/// This function uses a Halton(2,3) sequence to compute the jitter offset.
/// The ultimate index used for the sequence is <c><i>index</i></c> %
/// <c><i>phaseCount</i></c>.
///
/// It is important to understand that the values returned from the
/// <c><i>ffxFsr3GetJitterOffset</i></c> function are in unit pixel space, and
/// in order to composite this correctly into a projection matrix we must
/// convert them into projection offsets. This is done as per the pseudo code
/// listing which is shown below.
///
/// const int32_t jitterPhaseCount = ffxFsr3GetJitterPhaseCount(renderWidth, displayWidth);
///
/// float jitterX = 0;
/// float jitterY = 0;
/// ffxFsr3GetJitterOffset(&jitterX, &jitterY, index, jitterPhaseCount);
///
/// const float jitterX = 2.0f * jitterX / (float)renderWidth;
/// const float jitterY = -2.0f * jitterY / (float)renderHeight;
/// const Matrix4 jitterTranslationMatrix = translateMatrix(Matrix3::identity, Vector3(jitterX, jitterY, 0));
/// const Matrix4 jitteredProjectionMatrix = jitterTranslationMatrix * projectionMatrix;
///
/// Jitter should be applied to all rendering. This includes opaque, alpha
/// transparent, and raytraced objects. For rasterized objects, the sub-pixel
/// jittering values calculated by the <c><i>iffxFsr3GetJitterOffset</i></c>
/// function can be applied to the camera projection matrix which is ultimately
/// used to perform transformations during vertex shading. For raytraced
/// rendering, the sub-pixel jitter should be applied to the ray's origin,
/// often the camera's position.
///
/// Whether you elect to use the <c><i>ffxFsr3GetJitterOffset</i></c> function
/// or your own sequence generator, you must program the
/// <c><i>jitterOffset</i></c> field of the
/// <c><i>FfxFsr3DispatchParameters</i></c> structure in order to inform FSR3
/// of the jitter offset that has been applied in order to render each frame.
///
/// If not using the recommended <c><i>ffxFsr3GetJitterOffset</i></c> function,
/// care should be taken that your jitter sequence never generates a null vector;
/// that is value of 0 in both the X and Y dimensions.
///
/// @param [out] outX A pointer to a <c>float</c> which will contain the subpixel jitter offset for the x dimension.
/// @param [out] outY A pointer to a <c>float</c> which will contain the subpixel jitter offset for the y dimension.
/// @param [in] index The index within the jitter sequence.
/// @param [in] phaseCount The length of jitter phase. See <c><i>ffxFsr3GetJitterPhaseCount</i></c>.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>outX</i></c> or <c><i>outY</i></c> was <c>NULL</c>.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT Argument <c><i>phaseCount</i></c> must be greater than 0.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3GetJitterOffset(float* outX, float* outY, int32_t index, int32_t phaseCount);
/// A helper function to check if a resource is
/// <c><i>FFX_FSR3_RESOURCE_IDENTIFIER_NULL</i></c>.
///
/// @param [in] resource A <c><i>FfxResource</i></c>.
///
/// @returns
/// true The <c><i>resource</i></c> was not <c><i>FFX_FSR3_RESOURCE_IDENTIFIER_NULL</i></c>.
/// @returns
/// false The <c><i>resource</i></c> was <c><i>FFX_FSR3_RESOURCE_IDENTIFIER_NULL</i></c>.
///
/// @ingroup FSR3
FFX_API bool ffxFsr3ResourceIsNull(FfxResource resource);
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,527 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
// Include the interface for the backend of the FSR3 API.
#include <FidelityFX/host/ffx_interface.h>
#include <FidelityFX/gpu/fsr3upscaler/ffx_fsr3upscaler_resources.h>
/// @defgroup ffxFsr3Upscaler FidelityFX FSR3
/// FidelityFX Super Resolution 3 runtime library
///
/// @ingroup SDKComponents
/// FidelityFX Super Resolution 3 major version.
///
/// @ingroup ffxFsr3Upscaler
#define FFX_FSR3UPSCALER_VERSION_MAJOR (3)
/// FidelityFX Super Resolution 3 minor version.
///
/// @ingroup ffxFsr3Upscaler
#define FFX_FSR3UPSCALER_VERSION_MINOR (0)
/// FidelityFX Super Resolution 3 patch version.
///
/// @ingroup ffxFsr3Upscaler
#define FFX_FSR3UPSCALER_VERSION_PATCH (3)
/// FidelityFX Super Resolution 3 context count
///
/// Defines the number of internal effect contexts required by FSR3
///
/// @ingroup ffxFsr3Upscaler
#define FFX_FSR3UPSCALER_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup ffxFsr3Upscaler
#define FFX_FSR3UPSCALER_CONTEXT_SIZE (FFX_SDK_DEFAULT_CONTEXT_SIZE)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of all the passes which constitute the FSR3 algorithm.
///
/// FSR3 is implemented as a composite of several compute passes each
/// computing a key part of the final result. Each call to the
/// <c><i>FfxFsr3UpscalerScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single pass included in <c><i>FfxFsr3UpscalerPass</i></c>. For a
/// more comprehensive description of each pass, please refer to the FSR3
/// reference documentation.
///
/// Please note in some cases e.g.: <c><i>FFX_FSR3UPSCALER_PASS_ACCUMULATE</i></c>
/// and <c><i>FFX_FSR3UPSCALER_PASS_ACCUMULATE_SHARPEN</i></c> either one pass or the
/// other will be used (they are mutually exclusive). The choice of which will
/// depend on the way the <c><i>FfxFsr3UpscalerContext</i></c> is created and the
/// precise contents of <c><i>FfxFsr3UpscalerDispatchParamters</i></c> each time a call
/// is made to <c><i>ffxFsr3UpscalerContextDispatch</i></c>.
///
/// @ingroup ffxFsr3Upscaler
typedef enum FfxFsr3UpscalerPass
{
FFX_FSR3UPSCALER_PASS_DEPTH_CLIP, ///< A pass which performs depth clipping.
FFX_FSR3UPSCALER_PASS_RECONSTRUCT_PREVIOUS_DEPTH, ///< A pass which performs reconstruction of previous frame's depth.
FFX_FSR3UPSCALER_PASS_LOCK, ///< A pass which calculates pixel locks.
FFX_FSR3UPSCALER_PASS_ACCUMULATE, ///< A pass which performs upscaling.
FFX_FSR3UPSCALER_PASS_ACCUMULATE_SHARPEN, ///< A pass which performs upscaling when sharpening is used.
FFX_FSR3UPSCALER_PASS_RCAS, ///< A pass which performs sharpening.
FFX_FSR3UPSCALER_PASS_COMPUTE_LUMINANCE_PYRAMID, ///< A pass which generates the luminance mipmap chain for the current frame.
FFX_FSR3UPSCALER_PASS_GENERATE_REACTIVE, ///< An optional pass to generate a reactive mask.
FFX_FSR3UPSCALER_PASS_TCR_AUTOGENERATE, ///< DEPRECATED - NO LONGER SUPPORTED
FFX_FSR3UPSCALER_PASS_COUNT ///< The number of passes performed by FSR3.
} FfxFsr3UpscalerPass;
/// An enumeration of all the quality modes supported by FidelityFX Super
/// Resolution 3 upscaling.
///
/// In order to provide a consistent user experience across multiple
/// applications which implement FSR3. It is strongly recommended that the
/// following preset scaling factors are made available through your
/// application's user interface.
///
/// If your application does not expose the notion of preset scaling factors
/// for upscaling algorithms (perhaps instead implementing a fixed ratio which
/// is immutable) or implementing a more dynamic scaling scheme (such as
/// dynamic resolution scaling), then there is no need to use these presets.
///
/// Please note that <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> is
/// an optional mode which may introduce significant quality degradation in the
/// final image. As such it is recommended that you evaluate the final results
/// of using this scaling mode before deciding if you should include it in your
/// application.
///
/// @ingroup ffxFsr3Upscaler
typedef enum FfxFsr3UpscalerQualityMode {
FFX_FSR3UPSCALER_QUALITY_MODE_NATIVEAA = 0, ///< Perform upscaling with a per-dimension upscaling ratio of 1.0x.
FFX_FSR3UPSCALER_QUALITY_MODE_QUALITY = 1, ///< Perform upscaling with a per-dimension upscaling ratio of 1.5x.
FFX_FSR3UPSCALER_QUALITY_MODE_BALANCED = 2, ///< Perform upscaling with a per-dimension upscaling ratio of 1.7x.
FFX_FSR3UPSCALER_QUALITY_MODE_PERFORMANCE = 3, ///< Perform upscaling with a per-dimension upscaling ratio of 2.0x.
FFX_FSR3UPSCALER_QUALITY_MODE_ULTRA_PERFORMANCE = 4 ///< Perform upscaling with a per-dimension upscaling ratio of 3.0x.
} FfxFsr3UpscalerQualityMode;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxFsr3UpscalerContext</i></c>. See <c><i>FfxFsr3UpscalerContextDescription</i></c>.
///
/// @ingroup ffxFsr3Upscaler
typedef enum FfxFsr3UpscalerInitializationFlagBits {
FFX_FSR3UPSCALER_ENABLE_HIGH_DYNAMIC_RANGE = (1<<0), ///< A bit indicating if the input color data provided is using a high-dynamic range.
FFX_FSR3UPSCALER_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS = (1<<1), ///< A bit indicating if the motion vectors are rendered at display resolution.
FFX_FSR3UPSCALER_ENABLE_MOTION_VECTORS_JITTER_CANCELLATION = (1<<2), ///< A bit indicating that the motion vectors have the jittering pattern applied to them.
FFX_FSR3UPSCALER_ENABLE_DEPTH_INVERTED = (1<<3), ///< A bit indicating that the input depth buffer data provided is inverted [1..0].
FFX_FSR3UPSCALER_ENABLE_DEPTH_INFINITE = (1<<4), ///< A bit indicating that the input depth buffer data provided is using an infinite far plane.
FFX_FSR3UPSCALER_ENABLE_AUTO_EXPOSURE = (1<<5), ///< A bit indicating if automatic exposure should be applied to input color data.
FFX_FSR3UPSCALER_ENABLE_DYNAMIC_RESOLUTION = (1<<6), ///< A bit indicating that the application uses dynamic resolution scaling.
FFX_FSR3UPSCALER_ENABLE_TEXTURE1D_USAGE = (1<<7), ///< A bit indicating that the backend should use 1D textures.
FFX_FSR3UPSCALER_ENABLE_DEBUG_CHECKING = (1<<8), ///< A bit indicating that the runtime should check some API values and report issues.
} FfxFsr3UpscalerInitializationFlagBits;
/// Pass a string message
///
/// Used for debug messages.
///
/// @param [in] type The type of message.
/// @param [in] message A string message to pass.
///
///
/// @ingroup ffxFsr3Upscaler
typedef void(*FfxFsr3UpscalerMessage)(
FfxMsgType type,
const wchar_t* message);
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Super Resolution 3 upscaling.
///
/// @ingroup ffxFsr3Upscaler
typedef struct FfxFsr3UpscalerContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxFsr3UpscalerInitializationFlagBits</i></c>.
FfxDimensions2D maxRenderSize; ///< The maximum size that rendering will be performed at.
FfxDimensions2D displaySize; ///< The size of the presentation resolution targeted by the upscaling process.
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX SDK
FfxFsr3UpscalerMessage fpMessage; ///< A pointer to a function that can receive messages from the runtime.
} FfxFsr3UpscalerContextDescription;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX Super Resolution 3.
///
/// @ingroup ffxFsr3Upscaler
typedef struct FfxFsr3UpscalerDispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR3 rendering commands into.
FfxResource color; ///< A <c><i>FfxResource</i></c> containing the color buffer for the current frame (at render resolution).
FfxResource depth; ///< A <c><i>FfxResource</i></c> containing 32bit depth values for the current frame (at render resolution).
FfxResource motionVectors; ///< A <c><i>FfxResource</i></c> containing 2-dimensional motion vectors (at render resolution if <c><i>FFX_FSR3UPSCALER_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS</i></c> is not set).
FfxResource exposure; ///< A optional <c><i>FfxResource</i></c> containing a 1x1 exposure value.
FfxResource reactive; ///< A optional <c><i>FfxResource</i></c> containing alpha value of reactive objects in the scene.
FfxResource transparencyAndComposition; ///< A optional <c><i>FfxResource</i></c> containing alpha value of special objects in the scene.
FfxResource dilatedDepth; ///< A <c><i>FfxResource</i></c> allocated as described in <c><i>FfxFsr3UpscalerSharedResourceDescriptions</i></c> that is used to emit dilated depth and share with following effects.
FfxResource dilatedMotionVectors; ///< A <c><i>FfxResource</i></c> allocated as described in <c><i>FfxFsr3UpscalerSharedResourceDescriptions</i></c> that is used to emit dilated motion vectors and share with following effects.
FfxResource reconstructedPrevNearestDepth; ///< A <c><i>FfxResource</i></c> allocated as described in <c><i>FfxFsr3UpscalerSharedResourceDescriptions</i></c> that is used to emit reconstructed previous nearest depth and share with following effects.
FfxResource output; ///< A <c><i>FfxResource</i></c> containing the output color buffer for the current frame (at presentation resolution).
FfxFloatCoords2D jitterOffset; ///< The subpixel jitter offset applied to the camera.
FfxFloatCoords2D motionVectorScale; ///< The scale factor to apply to motion vectors.
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
bool enableSharpening; ///< Enable an additional sharpening pass.
float sharpness; ///< The sharpness value between 0 and 1, where 0 is no additional sharpness and 1 is maximum additional sharpness.
float frameTimeDelta; ///< The time elapsed since the last frame (expressed in milliseconds).
float preExposure; ///< The pre exposure value (must be > 0.0f)
bool reset; ///< A boolean value which when set to true, indicates the camera has moved discontinuously.
float cameraNear; ///< The distance to the near plane of the camera.
float cameraFar; ///< The distance to the far plane of the camera.
float cameraFovAngleVertical; ///< The camera angle field of view in the vertical direction (expressed in radians).
float viewSpaceToMetersFactor; ///< The scale factor to convert view space units to meters
} FfxFsr3UpscalerDispatchDescription;
/// A structure encapsulating the parameters for automatic generation of a reactive mask
///
/// @ingroup ffxFsr3Upscaler
typedef struct FfxFsr3UpscalerGenerateReactiveDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR3 rendering commands into.
FfxResource colorOpaqueOnly; ///< A <c><i>FfxResource</i></c> containing the opaque only color buffer for the current frame (at render resolution).
FfxResource colorPreUpscale; ///< A <c><i>FfxResource</i></c> containing the opaque+translucent color buffer for the current frame (at render resolution).
FfxResource outReactive; ///< A <c><i>FfxResource</i></c> containing the surface to generate the reactive mask into.
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
float scale; ///< A value to scale the output
float cutoffThreshold; ///< A threshold value to generate a binary reactive mask
float binaryValue; ///< A value to set for the binary reactive mask
uint32_t flags; ///< Flags to determine how to generate the reactive mask
} FfxFsr3UpscalerGenerateReactiveDescription;
/// A structure encapsulating the resource descriptions for shared resources for this effect.
///
/// @ingroup ffxFsr3Upscaler
typedef struct FfxFsr3UpscalerSharedResourceDescriptions {
FfxCreateResourceDescription reconstructedPrevNearestDepth; ///< The <c><i>FfxCreateResourceDescription</i></c> for allocating the <c><i>reconstructedPrevNearestDepth</i></c> shared resource.
FfxCreateResourceDescription dilatedDepth; ///< The <c><i>FfxCreateResourceDescription</i></c> for allocating the <c><i>dilatedDepth</i></c> shared resource.
FfxCreateResourceDescription dilatedMotionVectors; ///< The <c><i>FfxCreateResourceDescription</i></c> for allocating the <c><i>dilatedMotionVectors</i></c> shared resource.
} FfxFsr3UpscalerSharedResourceDescriptions;
/// A structure encapsulating the FidelityFX Super Resolution 3 context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by FSR3.
///
/// The <c><i>FfxFsr3UpscalerContext</i></c> object should have a lifetime matching
/// your use of FSR3. Before destroying the FSR3 context care should be taken
/// to ensure the GPU is not accessing the resources created or used by FSR3.
/// It is therefore recommended that the GPU is idle before destroying the
/// FSR3 context.
///
/// @ingroup ffxFsr3Upscaler
typedef struct FfxFsr3UpscalerContext
{
uint32_t data[FFX_FSR3UPSCALER_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxFsr3UpscalerContext;
/// Create a FidelityFX Super Resolution 3 context from the parameters
/// programmed to the <c><i>FfxFsr3UpscalerCreateParams</i></c> structure.
///
/// The context structure is the main object used to interact with the FSR3
/// API, and is responsible for the management of the internal resources used
/// by the FSR3 algorithm. When this API is called, multiple calls will be
/// made via the pointers contained in the <c><i>callbacks</i></c> structure.
/// These callbacks will attempt to retreive the device capabilities, and
/// create the internal resources, and pipelines required by FSR3's
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxFsr3UpscalerContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The flags included in the <c><i>flags</i></c> field of
/// <c><i>FfxFsr3UpscalerContext</i></c> how match the configuration of your
/// application as well as the intended use of FSR3. It is important that these
/// flags are set correctly (as well as a correct programmed
/// <c><i>FfxFsr3UpscalerDispatchDescription</i></c>) to ensure correct operation. It is
/// recommended to consult the overview documentation for further details on
/// how FSR3 should be integerated into an application.
///
/// When the <c><i>FfxFsr3UpscalerContext</i></c> is created, you should use the
/// <c><i>ffxFsr3UpscalerContextDispatch</i></c> function each frame where FSR3
/// upscaling should be applied. See the documentation of
/// <c><i>ffxFsr3UpscalerContextDispatch</i></c> for more details.
///
/// The <c><i>FfxFsr3UpscalerContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or FSR3 upscaling is
/// disabled by a user. To destroy the FSR3 context you should call
/// <c><i>ffxFsr3UpscalerContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxFsr3UpscalerContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxFsr3UpscalerContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerContextCreate(FfxFsr3UpscalerContext* pContext, const FfxFsr3UpscalerContextDescription* pContextDescription);
/// Provides the descriptions for shared resources that must be allocated for this effect.
///
/// @param [in] context A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure.
/// @param [out] SharedResources A pointer to a <c><i>FfxFsr3UpscalerSharedResourceDescriptions</i></c> to populate.
///
/// @returns
/// FFX_OK The operation completed successfully.
/// @returns
/// Anything else The operation failed.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerGetSharedResourceDescriptions(FfxFsr3UpscalerContext* context, FfxFsr3UpscalerSharedResourceDescriptions* SharedResources);
/// Dispatch the various passes that constitute FidelityFX Super Resolution 3.
///
/// FSR3 is a composite effect, meaning that it is compromised of multiple
/// constituent passes (implemented as one or more clears, copies and compute
/// dispatches). The <c><i>ffxFsr3UpscalerContextDispatch</i></c> function is the
/// function which (via the use of the functions contained in the
/// <c><i>callbacks</i></c> field of the <c><i>FfxFsr3UpscalerContext</i></c>
/// structure) utlimately generates the sequence of graphics API calls required
/// each frame.
///
/// As with the creation of the <c><i>FfxFsr3UpscalerContext</i></c> correctly
/// programming the <c><i>FfxFsr3UpscalerDispatchDescription</i></c> is key to ensuring
/// the correct operation of FSR3. It is particularly important to ensure that
/// camera jitter is correctly applied to your application's projection matrix
/// (or camera origin for raytraced applications). FSR3 provides the
/// <c><i>ffxFsr3UpscalerGetJitterPhaseCount</i></c> and
/// <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> entry points to help applications
/// correctly compute the camera jitter. Whatever jitter pattern is used by the
/// application it should be correctly programmed to the
/// <c><i>jitterOffset</i></c> field of the <c><i>dispatchDescription</i></c>
/// structure. For more guidance on camera jitter please consult the
/// documentation for <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> as well as the
/// accompanying overview documentation for FSR3.
///
/// @param [in] pContext A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxFsr3UpscalerDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_OUT_OF_RANGE The operation failed because <c><i>dispatchDescription.renderSize</i></c> was larger than the maximum render resolution.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the device inside the context was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerContextDispatch(FfxFsr3UpscalerContext* pContext, const FfxFsr3UpscalerDispatchDescription* pDispatchDescription);
/// A helper function generate a Reactive mask from an opaque only texure and one containing translucent objects.
///
/// @param [in] pContext A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure.
/// @param [in] pParams A pointer to a <c><i>FfxFsr3UpscalerGenerateReactiveDescription</i></c> structure
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerContextGenerateReactiveMask(FfxFsr3UpscalerContext* pContext, const FfxFsr3UpscalerGenerateReactiveDescription* pParams);
/// Destroy the FidelityFX Super Resolution context.
///
/// @param [out] pContext A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerContextDestroy(FfxFsr3UpscalerContext* pContext);
/// Get the upscale ratio from the quality mode.
///
/// The following table enumerates the mapping of the quality modes to
/// per-dimension scaling ratios.
///
/// Quality preset | Scale factor
/// ----------------------------------------------------- | -------------
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_QUALITY</i></c> | 1.5x
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_BALANCED</i></c> | 1.7x
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_PERFORMANCE</i></c> | 2.0x
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> | 3.0x
///
/// Passing an invalid <c><i>qualityMode</i></c> will return 0.0f.
///
/// @param [in] qualityMode The quality mode preset.
///
/// @returns
/// The upscaling the per-dimension upscaling ratio for
/// <c><i>qualityMode</i></c> according to the table above.
///
/// @ingroup ffxFsr3Upscaler
FFX_API float ffxFsr3UpscalerGetUpscaleRatioFromQualityMode(FfxFsr3UpscalerQualityMode qualityMode);
/// A helper function to calculate the rendering resolution from a target
/// resolution and desired quality level.
///
/// This function applies the scaling factor returned by
/// <c><i>ffxFsr3UpscalerGetUpscaleRatioFromQualityMode</i></c> to each dimension.
///
/// @param [out] pRenderWidth A pointer to a <c>uint32_t</c> which will hold the calculated render resolution width.
/// @param [out] pRenderHeight A pointer to a <c>uint32_t</c> which will hold the calculated render resolution height.
/// @param [in] displayWidth The target display resolution width.
/// @param [in] displayHeight The target display resolution height.
/// @param [in] qualityMode The desired quality mode for FSR 2 upscaling.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>renderWidth</i></c> or <c><i>renderHeight</i></c> was <c>NULL</c>.
/// @retval
/// FFX_ERROR_INVALID_ENUM An invalid quality mode was specified.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerGetRenderResolutionFromQualityMode(
uint32_t* pRenderWidth,
uint32_t* pRenderHeight,
uint32_t displayWidth,
uint32_t displayHeight,
FfxFsr3UpscalerQualityMode qualityMode);
/// A helper function to calculate the jitter phase count from display
/// resolution.
///
/// For more detailed information about the application of camera jitter to
/// your application's rendering please refer to the
/// <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> function.
///
/// The table below shows the jitter phase count which this function
/// would return for each of the quality presets.
///
/// Quality preset | Scale factor | Phase count
/// ----------------------------------------------------- | ------------- | ---------------
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_QUALITY</i></c> | 1.5x | 18
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_BALANCED</i></c> | 1.7x | 23
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_PERFORMANCE</i></c> | 2.0x | 32
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> | 3.0x | 72
/// Custom | [1..n]x | ceil(8*n^2)
///
/// @param [in] renderWidth The render resolution width.
/// @param [in] displayWidth The display resolution width.
///
/// @returns
/// The jitter phase count for the scaling factor between <c><i>renderWidth</i></c> and <c><i>displayWidth</i></c>.
///
/// @ingroup ffxFsr3Upscaler
FFX_API int32_t ffxFsr3UpscalerGetJitterPhaseCount(int32_t renderWidth, int32_t displayWidth);
/// A helper function to calculate the subpixel jitter offset.
///
/// FSR3 relies on the application to apply sub-pixel jittering while rendering.
/// This is typically included in the projection matrix of the camera. To make
/// the application of camera jitter simple, the FSR3 API provides a small set
/// of utility function which computes the sub-pixel jitter offset for a
/// particular frame within a sequence of separate jitter offsets. To begin, the
/// index within the jitter phase must be computed. To calculate the
/// sequence's length, you can call the <c><i>ffxFsr3UpscalerGetJitterPhaseCount</i></c>
/// function. The index should be a value which is incremented each frame modulo
/// the length of the sequence computed by <c><i>ffxFsr3UpscalerGetJitterPhaseCount</i></c>.
/// The index within the jitter phase is passed to
/// <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> via the <c><i>index</i></c> parameter.
///
/// This function uses a Halton(2,3) sequence to compute the jitter offset.
/// The ultimate index used for the sequence is <c><i>index</i></c> %
/// <c><i>phaseCount</i></c>.
///
/// It is important to understand that the values returned from the
/// <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> function are in unit pixel space, and
/// in order to composite this correctly into a projection matrix we must
/// convert them into projection offsets. This is done as per the pseudo code
/// listing which is shown below.
///
/// const int32_t jitterPhaseCount = ffxFsr3UpscalerGetJitterPhaseCount(renderWidth, displayWidth);
///
/// float jitterX = 0;
/// float jitterY = 0;
/// ffxFsr3UpscalerGetJitterOffset(&jitterX, &jitterY, index, jitterPhaseCount);
///
/// const float jitterX = 2.0f * jitterX / (float)renderWidth;
/// const float jitterY = -2.0f * jitterY / (float)renderHeight;
/// const Matrix4 jitterTranslationMatrix = translateMatrix(Matrix3::identity, Vector3(jitterX, jitterY, 0));
/// const Matrix4 jitteredProjectionMatrix = jitterTranslationMatrix * projectionMatrix;
///
/// Jitter should be applied to all rendering. This includes opaque, alpha
/// transparent, and raytraced objects. For rasterized objects, the sub-pixel
/// jittering values calculated by the <c><i>iffxFsr3UpscalerGetJitterOffset</i></c>
/// function can be applied to the camera projection matrix which is ultimately
/// used to perform transformations during vertex shading. For raytraced
/// rendering, the sub-pixel jitter should be applied to the ray's origin,
/// often the camera's position.
///
/// Whether you elect to use the <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> function
/// or your own sequence generator, you must program the
/// <c><i>jitterOffset</i></c> field of the
/// <c><i>FfxFsr3UpscalerDispatchParameters</i></c> structure in order to inform FSR3
/// of the jitter offset that has been applied in order to render each frame.
///
/// If not using the recommended <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> function,
/// care should be taken that your jitter sequence never generates a null vector;
/// that is value of 0 in both the X and Y dimensions.
///
/// @param [out] pOutX A pointer to a <c>float</c> which will contain the subpixel jitter offset for the x dimension.
/// @param [out] pOutY A pointer to a <c>float</c> which will contain the subpixel jitter offset for the y dimension.
/// @param [in] index The index within the jitter sequence.
/// @param [in] phaseCount The length of jitter phase. See <c><i>ffxFsr3UpscalerGetJitterPhaseCount</i></c>.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>outX</i></c> or <c><i>outY</i></c> was <c>NULL</c>.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT Argument <c><i>phaseCount</i></c> must be greater than 0.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerGetJitterOffset(float* pOutX, float* pOutY, int32_t index, int32_t phaseCount);
/// A helper function to check if a resource is
/// <c><i>FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_NULL</i></c>.
///
/// @param [in] resource A <c><i>FfxResource</i></c>.
///
/// @returns
/// true The <c><i>resource</i></c> was not <c><i>FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_NULL</i></c>.
/// @returns
/// false The <c><i>resource</i></c> was <c><i>FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_NULL</i></c>.
///
/// @ingroup ffxFsr3Upscaler
FFX_API bool ffxFsr3UpscalerResourceIsNull(FfxResource resource);
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,465 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <FidelityFX/host/ffx_assert.h>
#include <FidelityFX/host/ffx_types.h>
#include <FidelityFX/host/ffx_error.h>
#if defined(__cplusplus)
#define FFX_CPU
extern "C" {
#endif // #if defined(__cplusplus)
/// @defgroup Backends Backends
/// Core interface declarations and natively supported backends
///
/// @ingroup ffxSDK
/// @defgroup FfxInterface FfxInterface
/// FidelityFX SDK function signatures and core defines requiring
/// overrides for backend implementation.
///
/// @ingroup Backends
FFX_FORWARD_DECLARE(FfxInterface);
/// FidelityFX SDK major version.
///
/// @ingroup FfxInterface
#define FFX_SDK_VERSION_MAJOR (1)
/// FidelityFX SDK minor version.
///
/// @ingroup FfxInterface
#define FFX_SDK_VERSION_MINOR (0)
/// FidelityFX SDK patch version.
///
/// @ingroup FfxInterface
#define FFX_SDK_VERSION_PATCH (1)
/// Macro to pack a FidelityFX SDK version id together.
///
/// @ingroup FfxInterface
#define FFX_SDK_MAKE_VERSION( major, minor, patch ) ( ( major << 22 ) | ( minor << 12 ) | patch )
/// Stand in type for FfxPass
///
/// These will be defined for each effect individually (i.e. FfxFsr2Pass).
/// They are used to fetch the proper blob index to build effect shaders
///
/// @ingroup FfxInterface
typedef uint32_t FfxPass;
/// Get the SDK version of the backend context.
///
/// Newer effects may require support that legacy versions of the SDK will not be
/// able to provide. A version query is thus required to ensure an effect component
/// will always be paired with a backend which will support all needed functionality.
///
/// @param [in] backendInterface A pointer to the backend interface.
///
/// @returns
/// The SDK version a backend was built with.
///
/// @ingroup FfxInterface
typedef FfxUInt32(*FfxGetSDKVersionFunc)(
FfxInterface* backendInterface);
/// Create and initialize the backend context.
///
/// The callback function sets up the backend context for rendering.
/// It will create or reference the device and create required internal data structures.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [out] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxCreateBackendContextFunc)(
FfxInterface* backendInterface,
FfxUInt32* effectContextId);
/// Get a list of capabilities of the device.
///
/// When creating an <c><i>FfxEffectContext</i></c> it is desirable for the FFX
/// core implementation to be aware of certain characteristics of the platform
/// that is being targetted. This is because some optimizations which FFX SDK
/// attempts to perform are more effective on certain classes of hardware than
/// others, or are not supported by older hardware. In order to avoid cases
/// where optimizations actually have the effect of decreasing performance, or
/// reduce the breadth of support provided by FFX SDK, the FFX interface queries the
/// capabilities of the device to make such decisions.
///
/// For target platforms with fixed hardware support you need not implement
/// this callback function by querying the device, but instead may hardcore
/// what features are available on the platform.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [out] outDeviceCapabilities The device capabilities structure to fill out.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode(*FfxGetDeviceCapabilitiesFunc)(
FfxInterface* backendInterface,
FfxDeviceCapabilities* outDeviceCapabilities);
/// Destroy the backend context and dereference the device.
///
/// This function is called when the <c><i>FfxEffectContext</i></c> is destroyed.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode(*FfxDestroyBackendContextFunc)(
FfxInterface* backendInterface,
FfxUInt32 effectContextId);
/// Create a resource.
///
/// This callback is intended for the backend to create internal resources.
///
/// Please note: It is also possible that the creation of resources might
/// itself cause additional resources to be created by simply calling the
/// <c><i>FfxCreateResourceFunc</i></c> function pointer again. This is
/// useful when handling the initial creation of resources which must be
/// initialized. The flow in such a case would be an initial call to create the
/// CPU-side resource, another to create the GPU-side resource, and then a call
/// to schedule a copy render job to move the data between the two. Typically
/// this type of function call flow is only seen during the creation of an
/// <c><i>FfxEffectContext</i></c>.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] createResourceDescription A pointer to a <c><i>FfxCreateResourceDescription</i></c>.
/// @param [in] effectContextId The context space to be used for the effect in question.
/// @param [out] outResource A pointer to a <c><i>FfxResource</i></c> object.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxCreateResourceFunc)(
FfxInterface* backendInterface,
const FfxCreateResourceDescription* createResourceDescription,
FfxUInt32 effectContextId,
FfxResourceInternal* outResource);
/// Register a resource in the backend for the current frame.
///
/// Since the FfxInterface and the backends are not aware how many different
/// resources will get passed in over time, it's not safe
/// to register all resources simultaneously in the backend.
/// Also passed resources may not be valid after the dispatch call.
/// As a result it's safest to register them as FfxResourceInternal
/// and clear them at the end of the dispatch call.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] inResource A pointer to a <c><i>FfxResource</i></c>.
/// @param [in] effectContextId The context space to be used for the effect in question.
/// @param [out] outResource A pointer to a <c><i>FfxResourceInternal</i></c> object.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode(*FfxRegisterResourceFunc)(
FfxInterface* backendInterface,
const FfxResource* inResource,
FfxUInt32 effectContextId,
FfxResourceInternal* outResource);
/// Get an FfxResource from an FfxResourceInternal resource.
///
/// At times it is necessary to create an FfxResource representation
/// of an internally created resource in order to register it with a
/// child effect context. This function sets up the FfxResource needed
/// to register.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] resource The <c><i>FfxResourceInternal</i></c> for which to setup an FfxResource.
///
/// @returns
/// An FfxResource built from the internal resource
///
/// @ingroup FfxInterface
typedef FfxResource(*FfxGetResourceFunc)(
FfxInterface* backendInterface,
FfxResourceInternal resource);
/// Unregister all temporary FfxResourceInternal from the backend.
///
/// Unregister FfxResourceInternal referencing resources passed to
/// a function as a parameter.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] commandList A pointer to a <c><i>FfxCommandList</i></c> structure.
/// @param [in] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode(*FfxUnregisterResourcesFunc)(
FfxInterface* backendInterface,
FfxCommandList commandList,
FfxUInt32 effectContextId);
/// Retrieve a <c><i>FfxResourceDescription</i></c> matching a
/// <c><i>FfxResource</i></c> structure.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] resource A pointer to a <c><i>FfxResource</i></c> object.
///
/// @returns
/// A description of the resource.
///
/// @ingroup FfxInterface
typedef FfxResourceDescription (*FfxGetResourceDescriptionFunc)(
FfxInterface* backendInterface,
FfxResourceInternal resource);
/// Destroy a resource
///
/// This callback is intended for the backend to release an internal resource.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] resource A pointer to a <c><i>FfxResource</i></c> object.
/// @param [in] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxDestroyResourceFunc)(
FfxInterface* backendInterface,
FfxResourceInternal resource,
FfxUInt32 effectContextId);
/// Create a render pipeline.
///
/// A rendering pipeline contains the shader as well as resource bindpoints
/// and samplers.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] pass The identifier for the pass.
/// @param [in] pipelineDescription A pointer to a <c><i>FfxPipelineDescription</i></c> describing the pipeline to be created.
/// @param [in] effectContextId The context space to be used for the effect in question.
/// @param [out] outPipeline A pointer to a <c><i>FfxPipelineState</i></c> structure which should be populated.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxCreatePipelineFunc)(
FfxInterface* backendInterface,
FfxEffect effect,
FfxPass pass,
uint32_t permutationOptions,
const FfxPipelineDescription* pipelineDescription,
FfxUInt32 effectContextId,
FfxPipelineState* outPipeline);
typedef FfxErrorCode(*FfxGetPermutationBlobByIndexFunc)(FfxEffect effectId,
FfxPass passId,
FfxBindStage bindStage,
uint32_t permutationOptions,
FfxShaderBlob* outBlob);
/// Destroy a render pipeline.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] effectContextId The context space to be used for the effect in question.
/// @param [out] pipeline A pointer to a <c><i>FfxPipelineState</i></c> structure which should be released.
/// @param [in] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxDestroyPipelineFunc)(
FfxInterface* backendInterface,
FfxPipelineState* pipeline,
FfxUInt32 effectContextId);
/// Schedule a render job to be executed on the next call of
/// <c><i>FfxExecuteGpuJobsFunc</i></c>.
///
/// Render jobs can perform one of three different tasks: clear, copy or
/// compute dispatches.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] job A pointer to a <c><i>FfxGpuJobDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxScheduleGpuJobFunc)(
FfxInterface* backendInterface,
const FfxGpuJobDescription* job);
/// Execute scheduled render jobs on the <c><i>comandList</i></c> provided.
///
/// The recording of the graphics API commands should take place in this
/// callback function, the render jobs which were previously enqueued (via
/// callbacks made to <c><i>FfxScheduleGpuJobFunc</i></c>) should be
/// processed in the order they were received. Advanced users might choose to
/// reorder the rendering jobs, but should do so with care to respect the
/// resource dependencies.
///
/// Depending on the precise contents of <c><i>FfxDispatchDescription</i></c> a
/// different number of render jobs might have previously been enqueued (for
/// example if sharpening is toggled on and off).
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] commandList A pointer to a <c><i>FfxCommandList</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxExecuteGpuJobsFunc)(
FfxInterface* backendInterface,
FfxCommandList commandList);
typedef FfxErrorCode(*FfxPresentCallbackFunc)(const FfxPresentCallbackDescription* params);
typedef FfxErrorCode(*FfxFrameGenerationDispatchFunc)(const FfxFrameGenerationDispatchDescription* params);
typedef struct FfxFrameGenerationConfig
{
FfxSwapchain swapChain;
FfxPresentCallbackFunc presentCallback;
FfxFrameGenerationDispatchFunc frameGenerationCallback;
bool frameGenerationEnabled;
bool allowAsyncWorkloads;
FfxResource HUDLessColor;
FfxUInt32 flags;
bool onlyPresentInterpolated;
} FfxFrameGenerationConfig;
typedef FfxErrorCode (*ffxSwapChainConfigureFrameGenerationFunc)(FfxFrameGenerationConfig const* config);
/// A structure encapsulating the interface between the core implementation of
/// the FfxInterface and any graphics API that it should ultimately call.
///
/// This set of functions serves as an abstraction layer between FfxInterfae and the
/// API used to implement it. While the FidelityFX SDK ships with backends for DirectX12 and
/// Vulkan, it is possible to implement your own backend for other platforms
/// which sit on top of your engine's own abstraction layer. For details on the
/// expectations of what each function should do you should refer the
/// description of the following function pointer types:
///
/// <c><i>FfxCreateDeviceFunc</i></c>
/// <c><i>FfxGetDeviceCapabilitiesFunc</i></c>
/// <c><i>FfxDestroyDeviceFunc</i></c>
/// <c><i>FfxCreateResourceFunc</i></c>
/// <c><i>FfxRegisterResourceFunc</i></c>
/// <c><i>FfxGetResourceFunc</i></c>
/// <c><i>FfxUnregisterResourcesFunc</i></c>
/// <c><i>FfxGetResourceDescriptionFunc</i></c>
/// <c><i>FfxDestroyResourceFunc</i></c>
/// <c><i>FfxCreatePipelineFunc</i></c>
/// <c><i>FfxDestroyPipelineFunc</i></c>
/// <c><i>FfxScheduleGpuJobFunc</i></c>
/// <c><i>FfxExecuteGpuJobsFunc</i></c>
///
/// Depending on the graphics API that is abstracted by the backend, it may be
/// required that the backend is to some extent stateful. To ensure that
/// applications retain full control to manage the memory used by the FidelityFX SDK, the
/// <c><i>scratchBuffer</i></c> and <c><i>scratchBufferSize</i></c> fields are
/// provided. A backend should provide a means of specifying how much scratch
/// memory is required for its internal implementation (e.g: via a function
/// or constant value). The application is then responsible for allocating that
/// memory and providing it when setting up the SDK backend. Backends provided
/// with the FidelityFX SDK do not perform dynamic memory allocations, and instead
/// sub-allocate all memory from the scratch buffers provided.
///
/// The <c><i>scratchBuffer</i></c> and <c><i>scratchBufferSize</i></c> fields
/// should be populated according to the requirements of each backend. For
/// example, if using the DirectX 12 backend you should call the
/// <c><i>ffxGetScratchMemorySizeDX12</i></c> function. It is not required
/// that custom backend implementations use a scratch buffer.
///
/// Any functional addition to this interface mandates a version
/// bump to ensure full functionality across effects and backends.
///
/// @ingroup FfxInterface
typedef struct FfxInterface {
FfxGetSDKVersionFunc fpGetSDKVersion; ///< A callback function to query the SDK version.
FfxCreateBackendContextFunc fpCreateBackendContext; ///< A callback function to create and initialize the backend context.
FfxGetDeviceCapabilitiesFunc fpGetDeviceCapabilities; ///< A callback function to query device capabilities.
FfxDestroyBackendContextFunc fpDestroyBackendContext; ///< A callback function to destroy the backend context. This also dereferences the device.
FfxCreateResourceFunc fpCreateResource; ///< A callback function to create a resource.
FfxRegisterResourceFunc fpRegisterResource; ///< A callback function to register an external resource.
FfxGetResourceFunc fpGetResource; ///< A callback function to convert an internal resource to external resource type
FfxUnregisterResourcesFunc fpUnregisterResources; ///< A callback function to unregister external resource.
FfxGetResourceDescriptionFunc fpGetResourceDescription; ///< A callback function to retrieve a resource description.
FfxDestroyResourceFunc fpDestroyResource; ///< A callback function to destroy a resource.
FfxCreatePipelineFunc fpCreatePipeline; ///< A callback function to create a render or compute pipeline.
FfxGetPermutationBlobByIndexFunc fpGetPermutationBlobByIndex;
FfxDestroyPipelineFunc fpDestroyPipeline; ///< A callback function to destroy a render or compute pipeline.
FfxScheduleGpuJobFunc fpScheduleGpuJob; ///< A callback function to schedule a render job.
FfxExecuteGpuJobsFunc fpExecuteGpuJobs; ///< A callback function to execute all queued render jobs.
ffxSwapChainConfigureFrameGenerationFunc fpSwapChainConfigureFrameGeneration; ///< A callback function to configure swap chain present callback.
void* scratchBuffer; ///< A preallocated buffer for memory utilized internally by the backend.
size_t scratchBufferSize; ///< Size of the buffer pointed to by <c><i>scratchBuffer</i></c>.
FfxDevice device; ///< A backend specific device
} FfxInterface;
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,202 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// @defgroup OpticalFlow
#pragma once
// Include the interface for the backend of the OpticalFlow API.
#include <FidelityFX/host/ffx_interface.h>
/// FidelityFX OpticalFlow major version.
///
/// @ingroup ffxOpticalflow
#define FFX_OPTICALFLOW_VERSION_MAJOR (1)
/// FidelityFX OpticalFlow minor version.
///
/// @ingroup ffxOpticalflow
#define FFX_OPTICALFLOW_VERSION_MINOR (0)
/// FidelityFX OpticalFlow patch version.
///
/// @ingroup ffxOpticalflow
#define FFX_OPTICALFLOW_VERSION_PATCH (0)
/// FidelityFX Optical Flow context count
///
/// Defines the number of internal effect contexts required by Optical Flow
///
/// @ingroup ffxOpticalFlow
#define FFX_OPTICALFLOW_CONTEXT_COUNT (1)
/// The size of the context specified in 32bit size units.
///
/// @ingroup ffxOpticalflow
#define FFX_OPTICALFLOW_CONTEXT_SIZE (FFX_SDK_DEFAULT_CONTEXT_SIZE)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of all the passes which constitute the OpticalFlow algorithm.
///
/// @ingroup ffxOpticalflow
typedef enum FfxOpticalflowPass
{
FFX_OPTICALFLOW_PASS_PREPARE_LUMA = 0,
FFX_OPTICALFLOW_PASS_GENERATE_OPTICAL_FLOW_INPUT_PYRAMID,
FFX_OPTICALFLOW_PASS_GENERATE_SCD_HISTOGRAM,
FFX_OPTICALFLOW_PASS_COMPUTE_SCD_DIVERGENCE,
FFX_OPTICALFLOW_PASS_COMPUTE_OPTICAL_FLOW_ADVANCED_V5,
FFX_OPTICALFLOW_PASS_FILTER_OPTICAL_FLOW_V5,
FFX_OPTICALFLOW_PASS_SCALE_OPTICAL_FLOW_ADVANCED_V5,
FFX_OPTICALFLOW_PASS_COUNT
} FfxOpticalflowPass;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxOpticalflowContext</i></c>. See <c><i>FfxOpticalflowDispatchDescription</i></c>.
///
/// @ingroup ffxOpticalflow
typedef enum FfxOpticalflowInitializationFlagBits
{
FFX_OPTICALFLOW_ENABLE_TEXTURE1D_USAGE = (1 << 0),
} FfxOpticalflowInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize
/// FidelityFX OpticalFlow.
///
/// @ingroup ffxOpticalflow
typedef struct FfxOpticalflowContextDescription {
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX SDK
uint32_t flags; ///< A collection of <c><i>FfxOpticalflowInitializationFlagBits</i></c>.
FfxDimensions2D resolution;
} FfxOpticalflowContextDescription;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX Opticalflow.
///
/// @ingroup ffxOpticalflow
typedef struct FfxOpticalflowDispatchDescription
{
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record rendering commands into.
FfxResource color; ///< A <c><i>FfxResource</i></c> containing the input color buffer
FfxResource opticalFlowVector; ///< A <c><i>FfxResource</i></c> containing the output motion buffer
FfxResource opticalFlowSCD; ///< A <c><i>FfxResource</i></c> containing the output scene change detection buffer
bool reset; ///< A boolean value which when set to true, indicates the camera has moved discontinuously.
int backbufferTransferFunction;
FfxFloatCoords2D minMaxLuminance;
} FfxOpticalflowDispatchDescription;
typedef struct FfxOpticalflowSharedResourceDescriptions {
FfxCreateResourceDescription opticalFlowVector;
FfxCreateResourceDescription opticalFlowSCD;
} FfxOpticalflowSharedResourceDescriptions;
/// A structure encapsulating the FidelityFX OpticalFlow context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by OpticalFlow.
///
/// The <c><i>FfxOpticalflowContext</i></c> object should have a lifetime matching
/// your use of OpticalFlow. Before destroying the OpticalFlow context care should be taken
/// to ensure the GPU is not accessing the resources created or used by OpticalFlow.
/// It is therefore recommended that the GPU is idle before destroying OpticalFlow
/// OpticalFlow context.
///
/// @ingroup ffxOpticalflow
typedef struct FfxOpticalflowContext
{
uint32_t data[FFX_OPTICALFLOW_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxOpticalflowContext;
/// Create a FidelityFX OpticalFlow context from the parameters
/// programmed to the <c><i>FfxOpticalflowContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the OpticalFlow
/// API, and is responsible for the management of the internal resources used
/// by the OpticalFlow algorithm. When this API is called, multiple calls will be
/// made via the pointers contained in the <c><i>callbacks</i></c> structure.
/// These callbacks will attempt to retreive the device capabilities, and
/// create the internal resources, and pipelines required by OpticalFlow's
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxOpticalflowContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The flags included in the <c><i>flags</i></c> field of
/// <c><i>FfxOpticalflowContext</i></c> how match the configuration of your
/// application as well as the intended use of OpticalFlow. It is important that these
/// flags are set correctly (as well as a correct programmed
/// <c><i>FfxOpticalflowContextDescription</i></c>) to ensure correct operation. It is
/// recommended to consult the overview documentation for further details on
/// how OpticalFlow should be integerated into an application.
///
/// When the <c><i>FfxOpticalflowContext</i></c> is created, you should use the
/// <c><i>ffxOpticalflowContextDispatch</i></c> function each frame where FSR3
/// upscaling should be applied. See the documentation of
/// <c><i>ffxOpticalflowContextDispatch</i></c> for more details.
///
/// The <c><i>FfxOpticalflowContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or OpticalFlow is
/// disabled by a user. To destroy the OpticalFlow context you should call
/// <c><i>ffxOpticalflowContextDestroy</i></c>.
///
/// @param [out] context A pointer to a <c><i>FfxOpticalflowContext</i></c> structure to populate.
/// @param [in] contextDescription A pointer to a <c><i>FfxOpticalflowContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxOpticalflowContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxOpticalflow
FFX_API FfxErrorCode ffxOpticalflowContextCreate(FfxOpticalflowContext* context, FfxOpticalflowContextDescription* contextDescription);
FFX_API FfxErrorCode ffxOpticalflowGetSharedResourceDescriptions(FfxOpticalflowContext* context, FfxOpticalflowSharedResourceDescriptions* SharedResources);
FFX_API FfxErrorCode ffxOpticalflowContextDispatch(FfxOpticalflowContext* context, const FfxOpticalflowDispatchDescription* dispatchDescription);
/// Destroy the FidelityFX OpticalFlow context.
///
/// @param [out] context A pointer to a <c><i>FfxOpticalflowContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxOpticalflow
FFX_API FfxErrorCode ffxOpticalflowContextDestroy(FfxOpticalflowContext* context);
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,937 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <stdint.h>
///
/// @defgroup ffxSDK SDK
/// The FidelityFX SDK
///
/// @defgroup ffxHost Host
/// The FidelityFX SDK host (CPU-side) References
///
/// @ingroup ffxSDK
/// @defgroup Defines Defines
/// Top level defines used by the FidelityFX SDK
///
/// @ingroup ffxHost
#if defined (FFX_GCC)
/// FidelityFX exported functions
///
/// @ingroup Defines
#define FFX_API
#else
/// FidelityFX exported functions
///
/// @ingroup Defines
#define FFX_API __declspec(dllexport)
#endif // #if defined (FFX_GCC)
#define FFX_SDK_DEFAULT_CONTEXT_SIZE (1024 * 128)
/// Maximum supported number of simultaneously bound SRVs.
///
/// @ingroup Defines
#define FFX_MAX_NUM_SRVS 16
/// Maximum supported number of simultaneously bound UAVs.
///
/// @ingroup Defines
#define FFX_MAX_NUM_UAVS 16
/// Maximum number of constant buffers bound.
///
/// @ingroup Defines
#define FFX_MAX_NUM_CONST_BUFFERS 3
/// Maximum size of bound constant buffers.
#define FFX_MAX_CONST_SIZE 256
/// Maximum number of characters in a resource name
///
/// @ingroup Defines
#define FFX_RESOURCE_NAME_SIZE 64
/// Maximum number of queued frames in the backend
///
/// @ingroup Defines
#define FFX_MAX_QUEUED_FRAMES (4)
/// Maximum number of resources per effect context
///
/// @ingroup Defines
#define FFX_MAX_RESOURCE_COUNT (128)
/// Maximum number of passes per effect component
///
/// @ingroup Defines
#define FFX_MAX_PASS_COUNT (50)
/// Total ring buffer size needed for a single effect context
///
/// @ingroup Defines
#define FFX_RING_BUFFER_SIZE (FFX_MAX_QUEUED_FRAMES * FFX_MAX_PASS_COUNT * FFX_MAX_RESOURCE_COUNT)
/// Size of constant buffer entry in the ring buffer table
///
/// @ingroup Defines
#define FFX_BUFFER_SIZE (768)
/// Total ring buffer memory size for a single effect context
///
/// @ingroup Defines
#define FFX_RING_BUFFER_MEM_BLOCK_SIZE (FFX_RING_BUFFER_SIZE * FFX_BUFFER_SIZE)
/// Maximum number of barriers per flush
///
/// @ingroup Defines
#define FFX_MAX_BARRIERS (16)
/// Maximum number of GPU jobs per submission
///
/// @ingroup Defines
#define FFX_MAX_GPU_JOBS (64)
/// Maximum number of samplers supported
///
/// @ingroup Defines
#define FFX_MAX_SAMPLERS (16)
/// Maximum number of simultaneous upload jobs
///
/// @ingroup Defines
#define UPLOAD_JOB_COUNT (16)
// Off by default warnings
#pragma warning(disable : 4365 4710 4820 5039)
#ifdef __cplusplus
extern "C" {
#endif // #ifdef __cplusplus
/// @defgroup CPUTypes CPU Types
/// CPU side type defines for all commonly used variables
///
/// @ingroup ffxHost
/// A typedef for a boolean value.
///
/// @ingroup CPUTypes
typedef bool FfxBoolean;
/// A typedef for a unsigned 8bit integer.
///
/// @ingroup CPUTypes
typedef uint8_t FfxUInt8;
/// A typedef for a unsigned 16bit integer.
///
/// @ingroup CPUTypes
typedef uint16_t FfxUInt16;
/// A typedef for a unsigned 32bit integer.
///
/// @ingroup CPUTypes
typedef uint32_t FfxUInt32;
/// A typedef for a unsigned 64bit integer.
///
/// @ingroup CPUTypes
typedef uint64_t FfxUInt64;
/// A typedef for a signed 8bit integer.
///
/// @ingroup CPUTypes
typedef int8_t FfxInt8;
/// A typedef for a signed 16bit integer.
///
/// @ingroup CPUTypes
typedef int16_t FfxInt16;
/// A typedef for a signed 32bit integer.
///
/// @ingroup CPUTypes
typedef int32_t FfxInt32;
/// A typedef for a signed 64bit integer.
///
/// @ingroup CPUTypes
typedef int64_t FfxInt64;
/// A typedef for a floating point value.
///
/// @ingroup CPUTypes
typedef float FfxFloat32;
/// A typedef for a 2-dimensional floating point value.
///
/// @ingroup CPUTypes
typedef float FfxFloat32x2[2];
/// A typedef for a 3-dimensional floating point value.
///
/// @ingroup CPUTypes
typedef float FfxFloat32x3[3];
/// A typedef for a 4-dimensional floating point value.
///
/// @ingroup CPUTypes
typedef float FfxFloat32x4[4];
/// A typedef for a 2-dimensional 32bit unsigned integer.
///
/// @ingroup CPUTypes
typedef uint32_t FfxUInt32x2[2];
/// A typedef for a 3-dimensional 32bit unsigned integer.
///
/// @ingroup CPUTypes
typedef uint32_t FfxUInt32x3[3];
/// A typedef for a 4-dimensional 32bit unsigned integer.
///
/// @ingroup CPUTypes
typedef uint32_t FfxUInt32x4[4];
/// @defgroup SDKTypes SDK Types
/// Structure and Enumeration definitions used by the FidelityFX SDK
///
/// @ingroup ffxHost
/// An enumeration of surface formats.
///
/// @ingroup SDKTypes
typedef enum FfxSurfaceFormat {
FFX_SURFACE_FORMAT_UNKNOWN, ///< Unknown format
FFX_SURFACE_FORMAT_R32G32B32A32_TYPELESS, ///< 32 bit per channel, 4 channel typeless format
FFX_SURFACE_FORMAT_R32G32B32A32_UINT, ///< 32 bit per channel, 4 channel uint format
FFX_SURFACE_FORMAT_R32G32B32A32_FLOAT, ///< 32 bit per channel, 4 channel float format
FFX_SURFACE_FORMAT_R16G16B16A16_FLOAT, ///< 16 bit per channel, 4 channel float format
FFX_SURFACE_FORMAT_R32G32_FLOAT, ///< 32 bit per channel, 2 channel float format
FFX_SURFACE_FORMAT_R8_UINT, ///< 8 bit per channel, 1 channel float format
FFX_SURFACE_FORMAT_R32_UINT, ///< 32 bit per channel, 1 channel float format
FFX_SURFACE_FORMAT_R10G10B10A2_UNORM, ///< 10 bit per RGB channel with 2 bit alpha, 4 channel unsigned normalized format
FFX_SURFACE_FORMAT_R8G8B8A8_TYPELESS, ///< 8 bit per channel, 4 channel float format
FFX_SURFACE_FORMAT_R8G8B8A8_UNORM, ///< 8 bit per channel, 4 channel unsigned normalized format
FFX_SURFACE_FORMAT_R8G8B8A8_SNORM, ///< 8 bit per channel, 4 channel signed normalized format
FFX_SURFACE_FORMAT_R8G8B8A8_SRGB, ///< 8 bit per channel, 4 channel srgb normalized
FFX_SURFACE_FORMAT_R11G11B10_FLOAT, ///< 32 bit 3 channel float format
FFX_SURFACE_FORMAT_R16G16_FLOAT, ///< 16 bit per channel, 2 channel float format
FFX_SURFACE_FORMAT_R16G16_UINT, ///< 16 bit per channel, 2 channel unsigned int format
FFX_SURFACE_FORMAT_R16G16_SINT, ///< 16 bit per channel, 2 channel signed int format
FFX_SURFACE_FORMAT_R16_FLOAT, ///< 16 bit per channel, 1 channel float format
FFX_SURFACE_FORMAT_R16_UINT, ///< 16 bit per channel, 1 channel unsigned int format
FFX_SURFACE_FORMAT_R16_UNORM, ///< 16 bit per channel, 1 channel unsigned normalized format
FFX_SURFACE_FORMAT_R16_SNORM, ///< 16 bit per channel, 1 channel signed normalized format
FFX_SURFACE_FORMAT_R8_UNORM, ///< 8 bit per channel, 1 channel unsigned normalized format
FFX_SURFACE_FORMAT_R8G8_UNORM, ///< 8 bit per channel, 2 channel unsigned normalized format
FFX_SURFACE_FORMAT_R8G8_UINT, ///< 8 bit per channel, 2 channel unsigned integer format
FFX_SURFACE_FORMAT_R32_FLOAT ///< 32 bit per channel, 1 channel float format
} FfxSurfaceFormat;
/// An enumeration of resource usage.
///
/// @ingroup SDKTypes
typedef enum FfxResourceUsage {
FFX_RESOURCE_USAGE_READ_ONLY = 0, ///< No usage flags indicate a resource is read only.
FFX_RESOURCE_USAGE_RENDERTARGET = (1<<0), ///< Indicates a resource will be used as render target.
FFX_RESOURCE_USAGE_UAV = (1<<1), ///< Indicates a resource will be used as UAV.
FFX_RESOURCE_USAGE_DEPTHTARGET = (1<<2), ///< Indicates a resource will be used as depth target.
FFX_RESOURCE_USAGE_INDIRECT = (1<<3), ///< Indicates a resource will be used as indirect argument buffer
FFX_RESOURCE_USAGE_ARRAYVIEW = (1<<4), ///< Indicates a resource that will generate array views. Works on 2D and cubemap textures
} FfxResourceUsage;
/// An enumeration of resource states.
///
/// @ingroup SDKTypes
typedef enum FfxResourceStates {
FFX_RESOURCE_STATE_COMMON = (1 << 0),
FFX_RESOURCE_STATE_UNORDERED_ACCESS = (1 << 1), ///< Indicates a resource is in the state to be used as UAV.
FFX_RESOURCE_STATE_COMPUTE_READ = (1 << 2), ///< Indicates a resource is in the state to be read by compute shaders.
FFX_RESOURCE_STATE_PIXEL_READ = (1 << 3), ///< Indicates a resource is in the state to be read by pixel shaders.
FFX_RESOURCE_STATE_PIXEL_COMPUTE_READ = (FFX_RESOURCE_STATE_PIXEL_READ | FFX_RESOURCE_STATE_COMPUTE_READ), ///< Indicates a resource is in the state to be read by pixel or compute shaders.
FFX_RESOURCE_STATE_COPY_SRC = (1 << 4), ///< Indicates a resource is in the state to be used as source in a copy command.
FFX_RESOURCE_STATE_COPY_DEST = (1 << 5), ///< Indicates a resource is in the state to be used as destination in a copy command.
FFX_RESOURCE_STATE_GENERIC_READ = (FFX_RESOURCE_STATE_COPY_SRC | FFX_RESOURCE_STATE_COMPUTE_READ), ///< Indicates a resource is in generic (slow) read state.
FFX_RESOURCE_STATE_INDIRECT_ARGUMENT = (1 << 6), ///< Indicates a resource is in the state to be used as an indirect command argument
FFX_RESOURCE_STATE_PRESENT = (1 << 7), ///< Indicates a resource is in the state to be used to present to the swap chain
FFX_RESOURCE_STATE_RENDER_TARGET = (1 << 8), ///< Indicates a resource is in the state to be used as render target
} FfxResourceStates;
/// An enumeration of surface dimensions.
///
/// @ingroup SDKTypes
typedef enum FfxResourceDimension {
FFX_RESOURCE_DIMENSION_TEXTURE_1D, ///< A resource with a single dimension.
FFX_RESOURCE_DIMENSION_TEXTURE_2D, ///< A resource with two dimensions.
} FfxResourceDimension;
/// An enumeration of resource view dimensions.
///
/// @ingroup SDKTypes
typedef enum FfxResourceViewDimension
{
FFX_RESOURCE_VIEW_DIMENSION_BUFFER, ///< A resource view on a buffer.
FFX_RESOURCE_VIEW_DIMENSION_TEXTURE_1D, ///< A resource view on a single dimension.
FFX_RESOURCE_VIEW_DIMENSION_TEXTURE_1D_ARRAY, ///< A resource view on a single dimensional array.
FFX_RESOURCE_VIEW_DIMENSION_TEXTURE_2D, ///< A resource view on two dimensions.
FFX_RESOURCE_VIEW_DIMENSION_TEXTURE_2D_ARRAY, ///< A resource view on two dimensional array.
FFX_RESOURCE_VIEW_DIMENSION_TEXTURE_3D, ///< A resource view on three dimensions.
} FfxResourceViewDimension;
/// An enumeration of surface dimensions.
///
/// @ingroup SDKTypes
typedef enum FfxResourceFlags {
FFX_RESOURCE_FLAGS_NONE = 0, ///< No flags.
FFX_RESOURCE_FLAGS_ALIASABLE = (1 << 0), ///< A bit indicating a resource does not need to persist across frames.
FFX_RESOURCE_FLAGS_UNDEFINED = (1 << 1), ///< Special case flag used internally when importing resources that require additional setup
} FfxResourceFlags;
/// An enumeration of all resource view types.
///
/// @ingroup SDKTypes
typedef enum FfxResourceViewType {
FFX_RESOURCE_VIEW_UNORDERED_ACCESS, ///< The resource view is an unordered access view (UAV).
FFX_RESOURCE_VIEW_SHADER_READ, ///< The resource view is a shader resource view (SRV).
} FfxResourceViewType;
/// The type of filtering to perform when reading a texture.
///
/// @ingroup SDKTypes
typedef enum FfxFilterType {
FFX_FILTER_TYPE_MINMAGMIP_POINT, ///< Point sampling.
FFX_FILTER_TYPE_MINMAGMIP_LINEAR, ///< Sampling with interpolation.
FFX_FILTER_TYPE_MINMAGLINEARMIP_POINT, ///< Use linear interpolation for minification and magnification; use point sampling for mip-level sampling.
} FfxFilterType;
/// The address mode used when reading a texture.
///
/// @ingroup SDKTypes
typedef enum FfxAddressMode {
FFX_ADDRESS_MODE_WRAP, ///< Wrap when reading texture.
FFX_ADDRESS_MODE_MIRROR, ///< Mirror when reading texture.
FFX_ADDRESS_MODE_CLAMP, ///< Clamp when reading texture.
FFX_ADDRESS_MODE_BORDER, ///< Border color when reading texture.
FFX_ADDRESS_MODE_MIRROR_ONCE, ///< Mirror once when reading texture.
} FfxAddressMode;
/// An enumeration of all supported shader models.
///
/// @ingroup SDKTypes
typedef enum FfxShaderModel {
FFX_SHADER_MODEL_5_1, ///< Shader model 5.1.
FFX_SHADER_MODEL_6_0, ///< Shader model 6.0.
FFX_SHADER_MODEL_6_1, ///< Shader model 6.1.
FFX_SHADER_MODEL_6_2, ///< Shader model 6.2.
FFX_SHADER_MODEL_6_3, ///< Shader model 6.3.
FFX_SHADER_MODEL_6_4, ///< Shader model 6.4.
FFX_SHADER_MODEL_6_5, ///< Shader model 6.5.
FFX_SHADER_MODEL_6_6, ///< Shader model 6.6.
FFX_SHADER_MODEL_6_7, ///< Shader model 6.7.
} FfxShaderModel;
// An enumeration for different resource types
///
/// @ingroup SDKTypes
typedef enum FfxResourceType {
FFX_RESOURCE_TYPE_BUFFER, ///< The resource is a buffer.
FFX_RESOURCE_TYPE_TEXTURE1D, ///< The resource is a 1-dimensional texture.
FFX_RESOURCE_TYPE_TEXTURE2D, ///< The resource is a 2-dimensional texture.
FFX_RESOURCE_TYPE_TEXTURE_CUBE, ///< The resource is a cube map.
FFX_RESOURCE_TYPE_TEXTURE3D, ///< The resource is a 3-dimensional texture.
} FfxResourceType;
/// An enumeration for different heap types
///
/// @ingroup SDKTypes
typedef enum FfxHeapType {
FFX_HEAP_TYPE_DEFAULT = 0, ///< Local memory.
FFX_HEAP_TYPE_UPLOAD ///< Heap used for uploading resources.
} FfxHeapType;
/// An enumeration for different render job types
///
/// @ingroup SDKTypes
typedef enum FfxGpuJobType {
FFX_GPU_JOB_CLEAR_FLOAT = 0, ///< The GPU job is performing a floating-point clear.
FFX_GPU_JOB_COPY = 1, ///< The GPU job is performing a copy.
FFX_GPU_JOB_COMPUTE = 2, ///< The GPU job is performing a compute dispatch.
FFX_GPU_JOB_BARRIER = 3, ///< The GPU job is performing a barrier.
} FfxGpuJobType;
/// An enumeration for various descriptor types
///
/// @ingroup SDKTypes
typedef enum FfxDescriptorType {
//FFX_DESCRIPTOR_CBV = 0, // All CBVs currently mapped to root signature
//FFX_DESCRIPTOR_SAMPLER, // All samplers currently static
FFX_DESCRIPTOR_TEXTURE_SRV = 0,
FFX_DESCRIPTOR_BUFFER_SRV,
FFX_DESCRIPTOR_TEXTURE_UAV,
FFX_DESCRIPTOR_BUFFER_UAV,
} FfxDescriptiorType;
/// An enumeration for view binding stages
///
/// @ingroup SDKTypes
typedef enum FfxBindStage {
FFX_BIND_PIXEL_SHADER_STAGE = 1 << 0,
FFX_BIND_VERTEX_SHADER_STAGE = 1 << 1,
FFX_BIND_COMPUTE_SHADER_STAGE = 1 << 2,
} FfxBindStage;
/// An enumeration for barrier types
///
/// @ingroup SDKTypes
typedef enum FfxBarrierType
{
FFX_BARRIER_TYPE_TRANSITION = 0,
FFX_BARRIER_TYPE_UAV,
} FfxBarrierType;
/// An enumeration for message types that can be passed
///
/// @ingroup SDKTypes
typedef enum FfxMsgType {
FFX_MESSAGE_TYPE_ERROR = 0,
FFX_MESSAGE_TYPE_WARNING = 1,
FFX_MESSAGE_TYPE_COUNT
} FfxMsgType;
/// An enumeration of all the effects which constitute the FidelityFX SDK.
///
/// Dictates what effect shader blobs to fetch for pipeline creation
///
/// @ingroup FfxInterface
typedef enum FfxEffect
{
FFX_EFFECT_FSR2 = 0, ///< FidelityFX Super Resolution v2
FFX_EFFECT_FSR1, ///< FidelityFX Super Resolution
FFX_EFFECT_SPD, ///< FidelityFX Single Pass Downsampler
FFX_EFFECT_BLUR, ///< FidelityFX Blur
FFX_EFFECT_CACAO, ///< FidelityFX Combined Adaptive Compute Ambient Occlusion
FFX_EFFECT_CAS, ///< FidelityFX Contrast Adaptive Sharpening
FFX_EFFECT_DENOISER, ///< FidelityFX Denoiser
FFX_EFFECT_LENS, ///< FidelityFX Lens
FFX_EFFECT_PARALLEL_SORT, ///< FidelityFX Parallel Sort
FFX_EFFECT_SSSR, ///< FidelityFX Stochastic Screen Space Reflections
FFX_EFFECT_VARIABLE_SHADING, ///< FidelityFX Variable Shading
FFX_EFFECT_LPM, ///< FidelityFX Luma Preserving Mapper
FFX_EFFECT_DOF, ///< FidelityFX Depth of Field
FFX_EFFECT_CLASSIFIER, ///< FidelityFX Classifier
FFX_EFFECT_FSR3UPSCALER, ///< FidelityFX Super Resolution v3
FFX_EFFECT_FRAMEINTERPOLATION, ///< FidelityFX Frame Interpolation, part of FidelityFX Super Resolution v3
FFX_EFFECT_OPTICALFLOW, ///< FidelityFX Optical Flow, part of FidelityFX Super Resolution v3
} FfxEffect;
typedef enum FfxBackbufferTransferFunction {
FFX_BACKBUFFER_TRANSFER_FUNCTION_SRGB,
FFX_BACKBUFFER_TRANSFER_FUNCTION_PQ,
FFX_BACKBUFFER_TRANSFER_FUNCTION_SCRGB
} FfxBackbufferTransferFunction;
/// A typedef representing the graphics device.
///
/// @ingroup SDKTypes
typedef void* FfxDevice;
typedef void* FfxCommandQueue;
typedef void* FfxSwapchain;
/// A typedef representing a command list or command buffer.
///
/// @ingroup SDKTypes
typedef void* FfxCommandList;
/// A typedef for a root signature.
///
/// @ingroup SDKTypes
typedef void* FfxRootSignature;
/// A typedef for a command signature, used for indirect workloads
///
/// @ingroup SDKTypes
typedef void* FfxCommandSignature;
/// A typedef for a pipeline state object.
///
/// @ingroup SDKTypes
typedef void* FfxPipeline;
/// A structure encapsulating a collection of device capabilities.
///
/// @ingroup SDKTypes
typedef struct FfxDeviceCapabilities {
FfxShaderModel minimumSupportedShaderModel; ///< The minimum shader model supported by the device.
uint32_t waveLaneCountMin; ///< The minimum supported wavefront width.
uint32_t waveLaneCountMax; ///< The maximum supported wavefront width.
bool fp16Supported; ///< The device supports FP16 in hardware.
bool raytracingSupported; ///< The device supports ray tracing.
} FfxDeviceCapabilities;
/// A structure encapsulating a 2-dimensional point, using 32bit unsigned integers.
///
/// @ingroup SDKTypes
typedef struct FfxDimensions2D {
uint32_t width; ///< The width of a 2-dimensional range.
uint32_t height; ///< The height of a 2-dimensional range.
} FfxDimensions2D;
/// A structure encapsulating a 2-dimensional point.
///
/// @ingroup SDKTypes
typedef struct FfxIntCoords2D {
int32_t x; ///< The x coordinate of a 2-dimensional point.
int32_t y; ///< The y coordinate of a 2-dimensional point.
} FfxIntCoords2D;
/// A structure encapsulating a 2-dimensional rect.
///
/// @ingroup SDKTypes
typedef struct FfxRect2D
{
int32_t left;
int32_t top;
int32_t width;
int32_t height;
} FfxRect2D;
/// A structure encapsulating a 2-dimensional set of floating point coordinates.
///
/// @ingroup SDKTypes
typedef struct FfxFloatCoords2D {
float x; ///< The x coordinate of a 2-dimensional point.
float y; ///< The y coordinate of a 2-dimensional point.
} FfxFloatCoords2D;
/// A structure describing a resource.
///
/// @ingroup SDKTypes
typedef struct FfxResourceDescription {
FfxResourceType type; ///< The type of the resource.
FfxSurfaceFormat format; ///< The surface format.
union {
uint32_t width; ///< The width of the texture resource.
uint32_t size; ///< The size of the buffer resource.
};
union {
uint32_t height; ///< The height of the texture resource.
uint32_t stride; ///< The stride of the buffer resource.
};
union {
uint32_t depth; ///< The depth of the texture resource.
uint32_t alignment; ///< The alignment of the buffer resource.
};
uint32_t mipCount; ///< Number of mips (or 0 for full mipchain).
FfxResourceFlags flags; ///< A set of <c><i>FfxResourceFlags</i></c> flags.
FfxResourceUsage usage; ///< Resource usage flags.
} FfxResourceDescription;
/// An outward facing structure containing a resource
///
/// @ingroup SDKTypes
typedef struct FfxResource {
void* resource; ///< pointer to the resource.
FfxResourceDescription description;
FfxResourceStates state;
wchar_t name[FFX_RESOURCE_NAME_SIZE]; ///< (optional) Resource name.
} FfxResource;
/// An internal structure containing a handle to a resource and resource views
///
/// @ingroup SDKTypes
typedef struct FfxResourceInternal {
int32_t internalIndex; ///< The index of the resource.
} FfxResourceInternal;
/// An internal structure housing all that is needed for backend resource descriptions
///
/// @ingroup SDKTypes
typedef struct FfxInternalResourceDescription {
uint32_t id;
const wchar_t* name;
FfxResourceType type;
FfxResourceUsage usage;
FfxSurfaceFormat format;
uint32_t width;
uint32_t height;
uint32_t mipCount;
FfxResourceFlags flags;
uint32_t initDataSize;
void* initData;
} FfxInternalResourceDescription;
/// A structure defining the view to create
///
/// @ingroup SDKTypes
typedef struct FfxViewDescription
{
bool uavView; ///< Indicates that the view is a UAV.
FfxResourceViewDimension viewDimension; ///< The view dimension to map
union {
int32_t mipLevel; ///< The mip level of the view, (-1) for default
int32_t firstElement; ///< The first element of a buffer view, (-1) for default
};
union {
int32_t arraySize; ///< The array size of the view, (-1) for full depth/array size
int32_t elementCount; ///< The number of elements in a buffer view, (-1) for full depth/array size
};
int32_t firstSlice; ///< The first slice to map to, (-1) for default first slice
wchar_t name[64];
} FfxViewDescription;
static FfxViewDescription s_FfxViewDescInit = { false, FFX_RESOURCE_VIEW_DIMENSION_TEXTURE_2D, -1, -1, -1, L"" };
/// A structure defining a resource bind point
///
/// @ingroup SDKTypes
typedef struct FfxResourceBinding
{
uint32_t slotIndex;
uint32_t resourceIdentifier;
uint32_t bindCount;
wchar_t name[64];
}FfxResourceBinding;
/// A structure encapsulating a single pass of an algorithm.
///
/// @ingroup SDKTypes
typedef struct FfxPipelineState {
FfxRootSignature rootSignature; ///< The pipelines rootSignature
FfxCommandSignature cmdSignature; ///< The command signature used for indirect workloads
FfxPipeline pipeline; ///< The pipeline object
uint32_t uavTextureCount; ///< Count of Texture UAVs used in this pipeline
uint32_t srvTextureCount; ///< Count of Texture SRVs used in this pipeline
uint32_t srvBufferCount; ///< Count of Buffer SRV used in this pipeline
uint32_t uavBufferCount; ///< Count of Buffer UAVs used in this pipeline
uint32_t constCount; ///< Count of constant buffers used in this pipeline
FfxResourceBinding uavTextureBindings[FFX_MAX_NUM_UAVS]; ///< Array of ResourceIdentifiers bound as texture UAVs
FfxResourceBinding srvTextureBindings[FFX_MAX_NUM_SRVS]; ///< Array of ResourceIdentifiers bound as texture SRVs
FfxResourceBinding srvBufferBindings[FFX_MAX_NUM_SRVS]; ///< Array of ResourceIdentifiers bound as buffer SRVs
FfxResourceBinding uavBufferBindings[FFX_MAX_NUM_UAVS]; ///< Array of ResourceIdentifiers bound as buffer UAVs
FfxResourceBinding constantBufferBindings[FFX_MAX_NUM_CONST_BUFFERS]; ///< Array of ResourceIdentifiers bound as CBs
} FfxPipelineState;
/// A structure containing the data required to create a resource.
///
/// @ingroup SDKTypes
typedef struct FfxCreateResourceDescription {
FfxHeapType heapType; ///< The heap type to hold the resource, typically <c><i>FFX_HEAP_TYPE_DEFAULT</i></c>.
FfxResourceDescription resourceDescription; ///< A resource description.
FfxResourceStates initalState; ///< The initial resource state.
uint32_t initDataSize; ///< Size of initial data buffer.
void* initData; ///< Buffer containing data to fill the resource.
const wchar_t* name; ///< Name of the resource.
uint32_t id; ///< Internal resource ID.
} FfxCreateResourceDescription;
/// A structure containing the data required to create sampler mappings
///
/// @ingroup SDKTypes
typedef struct FfxSamplerDescription {
FfxFilterType filter;
FfxAddressMode addressModeU;
FfxAddressMode addressModeV;
FfxAddressMode addressModeW;
FfxBindStage stage;
} FfxSamplerDescription;
/// A structure containing the data required to create root constant buffer mappings
///
/// @ingroup SDKTypes
typedef struct FfxRootConstantDescription
{
uint32_t size;
FfxBindStage stage;
} FfxRootConstantDescription;
/// A structure containing the description used to create a
/// <c><i>FfxPipeline</i></c> structure.
///
/// A pipeline is the name given to a shader and the collection of state that
/// is required to dispatch it. In the context of the FidelityFX SDK and its architecture
/// this means that a <c><i>FfxPipelineDescription</i></c> will map to either a
/// monolithic object in an explicit API (such as a
/// <c><i>PipelineStateObject</i></c> in DirectX 12). Or a shader and some
/// ancillary API objects (in something like DirectX 11).
///
/// The <c><i>contextFlags</i></c> field contains a copy of the flags passed
/// to <c><i>ffxContextCreate</i></c> via the <c><i>flags</i></c> field of
/// the <c><i>Ffx<Effect>InitializationParams</i></c> structure. These flags are
/// used to determine which permutation of a pipeline for a specific
/// <c><i>Ffx<Effect>Pass</i></c> should be used to implement the features required
/// by each application, as well as to achieve the best performance on specific
/// target hardware configurations.
///
/// When using one of the provided backends for FidelityFX SDK (such as DirectX 12 or
/// Vulkan) the data required to create a pipeline is compiled off line and
/// included into the backend library that you are using. For cases where the
/// backend interface is overridden by providing custom callback function
/// implementations care should be taken to respect the contents of the
/// <c><i>contextFlags</i></c> field in order to correctly support the options
/// provided by the FidelityFX SDK, and achieve best performance.
/// ///
/// @ingroup SDKTypes
typedef struct FfxPipelineDescription {
uint32_t contextFlags; ///< A collection of <c><i>FfxInitializationFlagBits</i></c> which were passed to the context.
const FfxSamplerDescription* samplers; ///< A collection of samplers to use when building the root signature for the pipeline
size_t samplerCount; ///< Number of samplers to create for the pipeline
const FfxRootConstantDescription* rootConstants; ///< A collection of root constant descriptions to use when building the root signature for the pipeline
uint32_t rootConstantBufferCount; ///< Number of root constant buffers to create for the pipeline
wchar_t name[64]; ///< Pipeline name with which to name the pipeline object
FfxBindStage stage; ///< The stage(s) for which this pipeline is being built
uint32_t indirectWorkload; ///< Whether this pipeline has an indirect workload
FfxSurfaceFormat backbufferFormat; ///< For raster pipelines this contains the backbuffer format
} FfxPipelineDescription;
/// A structure containing the data required to create a barrier
///
/// @ingroup SDKTypes
typedef struct FfxBarrierDescription
{
FfxResourceInternal resource;
FfxBarrierType barrierType;
FfxResourceStates currentState;
FfxResourceStates newState;
uint32_t subResourceID;
} FfxBarrierDescription;
/// A structure containing a constant buffer.
///
/// @ingroup SDKTypes
typedef struct FfxConstantBuffer {
uint32_t num32BitEntries; ///< The size (expressed in 32-bit chunks) stored in data.
uint32_t data[FFX_MAX_CONST_SIZE]; ///< Constant buffer data
}FfxConstantBuffer;
/// A structure describing a clear render job.
///
/// @ingroup SDKTypes
typedef struct FfxClearFloatJobDescription {
float color[4]; ///< The clear color of the resource.
FfxResourceInternal target; ///< The resource to be cleared.
} FfxClearFloatJobDescription;
/// A structure describing a compute render job.
///
/// @ingroup SDKTypes
typedef struct FfxComputeJobDescription {
FfxPipelineState pipeline; ///< Compute pipeline for the render job.
uint32_t dimensions[3]; ///< Dispatch dimensions.
FfxResourceInternal cmdArgument; ///< Dispatch indirect cmd argument buffer
uint32_t cmdArgumentOffset; ///< Dispatch indirect offset within the cmd argument buffer
FfxResourceInternal srvTextures[FFX_MAX_NUM_SRVS]; ///< SRV texture resources to be bound in the compute job.
wchar_t srvTextureNames[FFX_MAX_NUM_SRVS][64];
FfxResourceInternal uavTextures[FFX_MAX_NUM_UAVS]; ///< UAV texture resources to be bound in the compute job.
uint32_t uavTextureMips[FFX_MAX_NUM_UAVS]; ///< Mip level of UAV texture resources to be bound in the compute job.
wchar_t uavTextureNames[FFX_MAX_NUM_UAVS][64];
FfxResourceInternal srvBuffers[FFX_MAX_NUM_SRVS]; ///< SRV buffer resources to be bound in the compute job.
wchar_t srvBufferNames[FFX_MAX_NUM_SRVS][64];
FfxResourceInternal uavBuffers[FFX_MAX_NUM_UAVS]; ///< UAV buffer resources to be bound in the compute job.
wchar_t uavBufferNames[FFX_MAX_NUM_UAVS][64];
FfxConstantBuffer cbs[FFX_MAX_NUM_CONST_BUFFERS]; ///< Constant buffers to be bound in the compute job.
wchar_t cbNames[FFX_MAX_NUM_CONST_BUFFERS][64];
} FfxComputeJobDescription;
typedef struct FfxRasterJobDescription
{
FfxPipelineState pipeline; ///< Raster pipeline for the render job.
uint32_t numVertices;
FfxResourceInternal renderTarget;
FfxResourceInternal srvTextures[FFX_MAX_NUM_SRVS]; ///< SRV resources to be bound in the compute job.
wchar_t srvTextureNames[FFX_MAX_NUM_SRVS][64];
FfxResourceInternal uavTextures[FFX_MAX_NUM_UAVS]; ///< UAV resources to be bound in the compute job.
uint32_t uavTextureMips[FFX_MAX_NUM_UAVS]; ///< Mip level of UAV resources to be bound in the compute job.
wchar_t uavTextureNames[FFX_MAX_NUM_UAVS][64];
FfxConstantBuffer cbs[FFX_MAX_NUM_CONST_BUFFERS]; ///< Constant buffers to be bound in the compute job.
wchar_t cbNames[FFX_MAX_NUM_CONST_BUFFERS][64];
} FfxRasterJobDescription;
/// A structure describing a copy render job.
///
/// @ingroup SDKTypes
typedef struct FfxCopyJobDescription
{
FfxResourceInternal src; ///< Source resource for the copy.
FfxResourceInternal dst; ///< Destination resource for the copy.
} FfxCopyJobDescription;
/// A structure describing a single render job.
///
/// @ingroup SDKTypes
typedef struct FfxGpuJobDescription{
FfxGpuJobType jobType; ///< Type of the job.
union {
FfxClearFloatJobDescription clearJobDescriptor; ///< Clear job descriptor. Valid when <c><i>jobType</i></c> is <c><i>FFX_RENDER_JOB_CLEAR_FLOAT</i></c>.
FfxCopyJobDescription copyJobDescriptor; ///< Copy job descriptor. Valid when <c><i>jobType</i></c> is <c><i>FFX_RENDER_JOB_COPY</i></c>.
FfxComputeJobDescription computeJobDescriptor; ///< Compute job descriptor. Valid when <c><i>jobType</i></c> is <c><i>FFX_RENDER_JOB_COMPUTE</i></c>.
FfxRasterJobDescription rasterJobDescriptor;
FfxBarrierDescription barrierDescriptor;
};
} FfxGpuJobDescription;
#if defined(POPULATE_SHADER_BLOB_FFX)
#undef POPULATE_SHADER_BLOB_FFX
#endif // #if defined(POPULATE_SHADER_BLOB_FFX)
/// Macro definition to copy header shader blob information into its SDK structural representation
///
/// @ingroup SDKTypes
#define POPULATE_SHADER_BLOB_FFX(info, index) \
{ \
info[index].blobData, info[index].blobSize, info[index].numConstantBuffers, info[index].numSRVTextures, info[index].numUAVTextures, \
info[index].numSRVBuffers, info[index].numUAVBuffers, info[index].numSamplers, info[index].numRTAccelerationStructures, \
info[index].constantBufferNames, \
info[index].constantBufferBindings, info[index].constantBufferCounts, info[index].srvTextureNames, info[index].srvTextureBindings, \
info[index].srvTextureCounts, info[index].uavTextureNames, info[index].uavTextureBindings, info[index].uavTextureCounts, \
info[index].srvBufferNames, info[index].srvBufferBindings, info[index].srvBufferCounts, \
info[index].uavBufferNames, info[index].uavBufferBindings, info[index].uavBufferCounts, info[index].samplerNames, \
info[index].samplerBindings, info[index].samplerCounts, info[index].rtAccelerationStructureNames, info[index].rtAccelerationStructureBindings, \
info[index].rtAccelerationStructureCounts \
}
// A single shader blob and a description of its resources.
///
/// @ingroup SDKTypes
typedef struct FfxShaderBlob {
const uint8_t* data; // A pointer to the blob
const uint32_t size; // Size in bytes.
const uint32_t cbvCount; // Number of CBs.
const uint32_t srvTextureCount; // Number of SRV Textures.
const uint32_t uavTextureCount; // Number of UAV Textures.
const uint32_t srvBufferCount; // Number of SRV Buffers.
const uint32_t uavBufferCount; // Number of UAV Buffers.
const uint32_t samplerCount; // Number of Samplers.
const uint32_t rtAccelStructCount; // Number of RT Acceleration structures.
// constant buffers
const char** boundConstantBufferNames;
const uint32_t* boundConstantBuffers; // Pointer to an array of bound ConstantBuffers.
const uint32_t* boundConstantBufferCounts; // Pointer to an array of bound ConstantBuffer resource counts
// srv textures
const char** boundSRVTextureNames;
const uint32_t* boundSRVTextures; // Pointer to an array of bound SRV resources.
const uint32_t* boundSRVTextureCounts; // Pointer to an array of bound SRV resource counts
// uav textures
const char** boundUAVTextureNames;
const uint32_t* boundUAVTextures; // Pointer to an array of bound UAV texture resources.
const uint32_t* boundUAVTextureCounts; // Pointer to an array of bound UAV texture resource counts
// srv buffers
const char** boundSRVBufferNames;
const uint32_t* boundSRVBuffers; // Pointer to an array of bound SRV buffer resources.
const uint32_t* boundSRVBufferCounts; // Pointer to an array of bound SRV buffer resource counts
// uav buffers
const char** boundUAVBufferNames;
const uint32_t* boundUAVBuffers; // Pointer to an array of bound UAV buffer resources.
const uint32_t* boundUAVBufferCounts; // Pointer to an array of bound UAV buffer resource counts
// samplers
const char** boundSamplerNames;
const uint32_t* boundSamplers; // Pointer to an array of bound sampler resources.
const uint32_t* boundSamplerCounts; // Pointer to an array of bound sampler resource counts
// rt acceleration structures
const char** boundRTAccelerationStructureNames;
const uint32_t* boundRTAccelerationStructures; // Pointer to an array of bound UAV buffer resources.
const uint32_t* boundRTAccelerationStructureCounts; // Pointer to an array of bound UAV buffer resource counts
} FfxShaderBlob;
typedef struct FfxPresentCallbackDescription
{
FfxDevice device;
FfxCommandList commandList;
FfxResource currentBackBuffer;
FfxResource currentUI;
FfxResource outputSwapChainBuffer;
bool isInterpolatedFrame;
} FfxPresentCallbackDescription;
typedef struct FfxFrameGenerationDispatchDescription {
FfxCommandList commandList;
FfxResource presentColor;
FfxResource outputs[4];
uint32_t numInterpolatedFrames;
bool reset;
FfxBackbufferTransferFunction backBufferTransferFunction;
float minMaxLuminance[2];
} FfxFrameGenerationDispatchDescription;
#ifdef __cplusplus
}
#endif // #ifdef __cplusplus
@@ -0,0 +1,123 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <FidelityFX/host/ffx_types.h>
/// @defgroup Utils Utilities
/// Utility Macros used by the FidelityFX SDK
///
/// @ingroup ffxHost
/// The value of Pi.
///
/// @ingroup Utils
const float FFX_PI = 3.141592653589793f;
/// An epsilon value for floating point numbers.
///
/// @ingroup Utils
const float FFX_EPSILON = 1e-06f;
/// Helper macro to create the version number.
///
/// @ingroup Utils
#define FFX_MAKE_VERSION(major, minor, patch) ((major << 22) | (minor << 12) | patch)
///< Use this to specify no version.
///
/// @ingroup Utils
#define FFX_UNSPECIFIED_VERSION 0xFFFFAD00
/// Helper macro to avoid warnings about unused variables.
///
/// @ingroup Utils
#define FFX_UNUSED(x) ((void)(x))
/// Helper macro to align an integer to the specified power of 2 boundary
///
/// @ingroup Utils
#define FFX_ALIGN_UP(x, y) (((x) + ((y)-1)) & ~((y)-1))
/// Helper macro to check if a value is aligned.
///
/// @ingroup Utils
#define FFX_IS_ALIGNED(x) (((x) != 0) && ((x) & ((x)-1)))
/// Helper macro to compute the rounded-up integer division of two unsigned integers
///
/// @ingroup Utils
#define FFX_DIVIDE_ROUNDING_UP(x, y) ((x + y - 1) / y)
/// Helper macro to stringify a value.
///
/// @ingroup Utils
#define FFX_STR(s) FFX_XSTR(s)
#define FFX_XSTR(s) #s
/// Helper macro to forward declare a structure.
///
/// @ingroup Utils
#define FFX_FORWARD_DECLARE(x) typedef struct x x
/// Helper macro to return the maximum of two values.
///
/// @ingroup Utils
#define FFX_MAXIMUM(x, y) (((x) > (y)) ? (x) : (y))
/// Helper macro to return the minimum of two values.
///
/// @ingroup Utils
#define FFX_MINIMUM(x, y) (((x) < (y)) ? (x) : (y))
/// Helper macro to do safe free on a pointer.
///
/// @ingroup Utils
#define FFX_SAFE_FREE(x) \
if (x) \
free(x)
/// Helper macro to return the abs of an integer value.
///
/// @ingroup Utils
#define FFX_ABSOLUTE(x) (((x) < 0) ? (-(x)) : (x))
/// Helper macro to return sign of a value.
///
/// @ingroup Utils
#define FFX_SIGN(x) (((x) < 0) ? -1 : 1)
/// Helper macro to work out the number of elements in an array.
///
/// @ingroup Utils
#define FFX_ARRAY_ELEMENTS(x) (int32_t)((sizeof(x) / sizeof(0 [x])) / ((size_t)(!(sizeof(x) % sizeof(0 [x])))))
/// The maximum length of a path that can be specified to the FidelityFX API.
///
/// @ingroup Utils
#define FFX_MAXIMUM_PATH (260)
/// Helper macro to check if the specified key is set in a bitfield.
///
/// @ingroup Utils
#define FFX_CONTAINS_FLAG(options, key) ((options & key) == key)
+8 -2
View File
@@ -63,7 +63,12 @@ int main() {
Field("rtStateObjectsCreated", offsetof(FlWriterState, rtStateObjectsCreated), sizeof(uint32_t));
Field("rasterPsoCreated", offsetof(FlWriterState, rasterPsoCreated), sizeof(uint32_t));
Field("runtimeCensus", offsetof(FlWriterState, runtimeCensus), sizeof(uint32_t));
Field("reserved", offsetof(FlWriterState, reserved), sizeof(uint32_t) * 5, true);
Field("slTagCensus", offsetof(FlWriterState, slTagCensus), sizeof(uint32_t));
Field("dxgiPresentsUnseen", offsetof(FlWriterState, dxgiPresentsUnseen), sizeof(uint32_t));
Field("dxgiPresentSamples", offsetof(FlWriterState, dxgiPresentSamples), sizeof(uint32_t));
Field("loaderSignals", offsetof(FlWriterState, loaderSignals), sizeof(uint16_t));
Field("earlyStopFamily", offsetof(FlWriterState, earlyStopFamily), sizeof(uint16_t));
Field("dxgiPresentsBeforeHook", offsetof(FlWriterState, dxgiPresentsBeforeHook), sizeof(uint32_t), true);
std::printf(" ] },\n");
std::printf(" \"FlControlBlock\": { \"size\": %zu, \"fields\": [\n", sizeof(FlControlBlock));
@@ -98,7 +103,8 @@ int main() {
Field("fgEvaluations", offsetof(FlFrameRecord, fgEvaluations), sizeof(uint8_t));
Field("vramUsedMb", offsetof(FlFrameRecord, vramUsedMb), sizeof(uint32_t));
Field("reflexLatencyUs", offsetof(FlFrameRecord, reflexLatencyUs), sizeof(uint32_t));
Field("reserved", offsetof(FlFrameRecord, reserved), sizeof(uint32_t));
Field("dxgiUnseen", offsetof(FlFrameRecord, dxgiUnseen), sizeof(uint8_t));
Field("reserved", offsetof(FlFrameRecord, reserved), sizeof(uint8_t) * 3);
Field("seq", offsetof(FlFrameRecord, seq), sizeof(uint32_t));
Field("swapchainId", offsetof(FlFrameRecord, swapchainId), sizeof(uint32_t), true);
std::printf(" ] }\n");
+135 -1
View File
@@ -32,6 +32,8 @@
#include <windows.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "nvapi.h"
@@ -46,9 +48,141 @@ void Check(bool condition, const char* what) {
}
}
// --- --ngx-state <pid>: what the DRIVER says about a process's DLSS features -------
//
// WHY THIS MODE EXISTS (2026-09-05, 20_OPEN_QUESTIONS §H5 / §H11). Four real titles
// run DLSS through NGX directly and drive DLSS Frame Generation on a path the
// Streamline hooks never see (Lies of P, Hell Is Us, Expedition 33, Black Myth:
// Wukong), and a fifth (Dying Light: The Beast, Streamline 2.8) presents its
// generated frames where the present hook cannot count them. The NGX SDK is
// licence-blocked, so nothing in the Overlay may hook nvngx_*.dll. NVAPI is MIT and
// vendored, and NvAPI_NGX_GetNGXOverrideState (R570+) is documented as returning,
// FOR A GIVEN PROCESS ID, the driver's own feedback bits for Super Resolution, Ray
// Reconstruction and Frame Generation -- DLL loaded, feature created, evaluated, FG
// mode, multi-frame -- plus the scaling ratio, the performance (quality) mode and the
// frame-generation count. Out of process, by PID, from the driver's bookkeeping:
// no game memory, no hook, no vendor binary patched.
//
// WHAT IS NOT KNOWN, and why this is a probe rather than a producer: the API's name
// says "override", and whether its feedback bits are populated for a process with
// no NVIDIA-app override configured is unmeasured. Whether "frameGenerationCount" is
// the title's multiplier or only an override target is unmeasured. This mode prints
// the raw words and every decoded bit so the owner's run against a running title
// answers both, before any report line is built on it.
struct FlagName {
NvU64 bit;
const char* name;
};
constexpr FlagName kFlags[] = {
{NV_NGX_DLSS_OVERRIDE_FLAG_INITIALIZED, "INITIALIZED"},
{NV_NGX_DLSS_OVERRIDE_FLAG_ENABLED, "ENABLED"},
{NV_NGX_DLSS_OVERRIDE_FLAG_DLL_EXISTS, "DLL_EXISTS"},
{NV_NGX_DLSS_OVERRIDE_FLAG_DLL_LOADED, "DLL_LOADED"},
{NV_NGX_DLSS_OVERRIDE_FLAG_DLL_SELECTED, "DLL_SELECTED"},
{NV_NGX_DLSS_OVERRIDE_FLAG_PRESET, "PRESET"},
{NV_NGX_DLSS_OVERRIDE_FLAG_PERF_MODE, "PERF_MODE"},
{NV_NGX_DLSS_OVERRIDE_FLAG_SCALING_RATIO, "SCALING_RATIO"},
{NV_NGX_DLSS_OVERRIDE_FLAG_OPTIMAL_SETTINGS, "OPTIMAL_SETTINGS"},
{NV_NGX_DLSS_OVERRIDE_FLAG_CREATED, "CREATED"},
{NV_NGX_DLSS_OVERRIDE_FLAG_EVALUATE, "EVALUATE"},
{NV_NGX_DLSS_OVERRIDE_FLAG_FG_MODE, "FG_MODE"},
{NV_NGX_DLSS_OVERRIDE_FLAG_SR_DLAA_MODE, "SR_DLAA_MODE"},
{NV_NGX_DLSS_OVERRIDE_FLAG_FG_MULTI_FRAME, "FG_MULTI_FRAME"},
{NV_NGX_DLSS_OVERRIDE_FLAG_ERR_FAILED, "ERR_FAILED"},
{NV_NGX_DLSS_OVERRIDE_FLAG_ERR_DENIED, "ERR_DENIED"},
{NV_NGX_DLSS_OVERRIDE_FLAG_ERR_DRS, "ERR_DRS"},
{NV_NGX_DLSS_OVERRIDE_FLAG_ERR_NOT_FOUND, "ERR_NOT_FOUND"},
{NV_NGX_DLSS_OVERRIDE_FLAG_ERR_DLL_LOAD, "ERR_DLL_LOAD"},
};
void PrintMask(const char* feature, NvU64 mask) {
std::printf(" %-4s feedback 0x%016llX :", feature, static_cast<unsigned long long>(mask));
bool any = false;
for (const FlagName& f : kFlags) {
if ((mask & f.bit) != 0u) {
std::printf(" %s", f.name);
any = true;
}
}
NvU64 known = 0;
for (const FlagName& f : kFlags) {
known |= f.bit;
}
if ((mask & ~known) != 0u) {
std::printf(" +unknown(0x%llX)", static_cast<unsigned long long>(mask & ~known));
any = true;
}
std::printf("%s\n", any ? "" : " (none)");
}
int NgxState(unsigned long pid) {
std::printf("fl-probe-nvapi --ngx-state %lu — the driver's NGX feedback for one process\n\n", pid);
const NvAPI_Status init = NvAPI_Initialize();
if (init != NVAPI_OK) {
NvAPI_ShortString desc = {};
NvAPI_GetErrorMessage(init, desc);
std::printf(" NvAPI_Initialize -> %d (%s)\n BRANCH: DEGRADED — no usable NVIDIA driver on this machine.\n",
static_cast<int>(init), desc);
std::printf("NGXSTATE status=DEGRADED nvapi=%d\n", static_cast<int>(init));
return 2;
}
NvU32 driverVersion = 0;
NvAPI_ShortString branch = {};
if (NvAPI_SYS_GetDriverAndBranchVersion(&driverVersion, branch) == NVAPI_OK) {
std::printf(" driver %u.%02u (%s)\n", driverVersion / 100, driverVersion % 100, branch);
}
NV_NGX_DLSS_OVERRIDE_GET_STATE_PARAMS params = {};
params.version = NV_NGX_DLSS_OVERRIDE_GET_STATE_PARAMS_VER;
params.processIdentifier = static_cast<NvU32>(pid);
const NvAPI_Status status = NvAPI_NGX_GetNGXOverrideState(&params);
if (status != NVAPI_OK) {
NvAPI_ShortString desc = {};
NvAPI_GetErrorMessage(status, desc);
std::printf(" NvAPI_NGX_GetNGXOverrideState -> %d (%s)\n", static_cast<int>(status), desc);
std::printf(" BRANCH: UNANSWERED — the driver did not answer for pid %lu (not an NVIDIA-rendered process, a "
"driver older than R570, or the API refusing this caller).\n",
pid);
std::printf("NGXSTATE status=UNANSWERED nvapi=%d\n", static_cast<int>(status));
NvAPI_Unload();
return 3;
}
std::printf(" NvAPI_NGX_GetNGXOverrideState -> NVAPI_OK\n BRANCH: ANSWERED\n\n");
PrintMask("SR", params.feedbackMaskSR);
PrintMask("RR", params.feedbackMaskRR);
PrintMask("FG", params.feedbackMaskFG);
std::printf(" scalingRatio %.4f\n", static_cast<double>(params.scalingRatio));
std::printf(" performanceMode %u\n", params.performanceMode);
std::printf(" renderPreset %u\n", params.renderPreset);
std::printf(" frameGenerationCount %u (\"FG Override Frame Count Target\" per nvapi.h -- whether this is the "
"title's multiplier is what this run measures)\n",
params.frameGenerationCount);
std::printf(" frameGenerationPreset %u\n", params.frameGenerationPreset);
std::printf(" frameGenerationMode %u\n", params.frameGenerationMode);
std::printf(" reserved %u %u\n", params.reserved[0], params.reserved[1]);
// THE MACHINE LINE. FrameLedger.CaptureHost spawns this probe beside each module snapshot
// (NgxDriverProbe) and reads exactly this line; everything above is for a human. One line,
// key=value, hex masks, so a parser cannot mistake a decoded name for a field.
std::printf(
"NGXSTATE status=ANSWERED sr=0x%016llX rr=0x%016llX fg=0x%016llX ratio=%.4f mode=%u preset=%u fgcount=%u "
"fgpreset=%u fgmode=%u driver=%u\n",
static_cast<unsigned long long>(params.feedbackMaskSR), static_cast<unsigned long long>(params.feedbackMaskRR),
static_cast<unsigned long long>(params.feedbackMaskFG), static_cast<double>(params.scalingRatio),
params.performanceMode, params.renderPreset, params.frameGenerationCount, params.frameGenerationPreset,
params.frameGenerationMode, driverVersion);
NvAPI_Unload();
return 0;
}
} // namespace
int main() {
int main(int argc, char** argv) {
if (argc >= 3 && std::strcmp(argv[1], "--ngx-state") == 0) {
return NgxState(std::strtoul(argv[2], nullptr, 10));
}
std::printf("fl-probe-nvapi — the vendored NVAPI material, exercised\n\n");
// 1 + 2 are proven by this translation unit existing: it includes nvapi.h
+8 -3
View File
@@ -4,14 +4,17 @@
# Deliberately NOT built with fl_hostile_env_flags. This is our own process, not
# an injected DLL: it has no reason to give up exceptions, and the COM proxy in
# proxy_swapchain.h is ordinary C++ that benefits from them.
add_executable(hook-harness main.cpp proxy_swapchain.h)
# vk_hold.cpp is the Vulkan mode (P1 item 3): the loader is reached through
# LoadLibraryW at run time, so only the vendored Khronos HEADERS are needed and
# the harness still builds and runs on a machine with no Vulkan at all.
add_executable(hook-harness main.cpp vk_hold.cpp proxy_swapchain.h)
# fl_dxgi_vtable, not a local copy of the slot numbers: this harness proves the
# indices by behaviour, and it must prove the SHIPPED ones (§S29(b)). The same
# reasoning brings in fl_hook_inventory.h from the Overlay's include directory:
# --probe-upscaler-resolve calls the OVERLAY'S resolver, not a copy of it, or it
# would prove a fact about GetProcAddress.
target_link_libraries(hook-harness PRIVATE FrameLedger.Shm fl_dxgi_vtable fl_native_flags fl_streamline_headers
fl_fidelityfx_headers)
fl_fidelityfx_headers fl_fsr3_host_headers fl_vulkan_headers)
target_include_directories(hook-harness PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Overlay/include")
target_compile_definitions(hook-harness PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
@@ -30,6 +33,8 @@ target_compile_definitions(hook-harness PRIVATE
FL_STUB_FFX_UPSCALER=L"$<TARGET_FILE:fl_stub_ffx_upscaler>"
FL_STUB_FFX_FG=L"$<TARGET_FILE:fl_stub_ffx_fg>"
FL_STUB_FFX_LOADER=L"$<TARGET_FILE:fl_stub_ffx_loader>"
# The FSR 3.0 host stand-in (ffx_fsr3_x64.dll), same rule.
FL_STUB_FFX_FSR3_HOST=L"$<TARGET_FILE:fl_stub_ffx_fsr3_host>"
# Shared with fl_guard_test from src/native/CMakeLists.txt, so the fixture and
# the assertion cannot hold different numbers.
FL_TAGGED_RENDER_W=${FL_TAGGED_RENDER_W}
@@ -39,7 +44,7 @@ target_compile_definitions(hook-harness PRIVATE
FL_DXR_DISPATCH_D=${FL_DXR_DISPATCH_D}
)
add_dependencies(hook-harness fl_stub_sl_interposer fl_stub_sl_common fl_stub_sl_interposer_v1
fl_stub_ffx_dx12 fl_stub_ffx_upscaler fl_stub_ffx_fg fl_stub_ffx_loader)
fl_stub_ffx_dx12 fl_stub_ffx_upscaler fl_stub_ffx_fg fl_stub_ffx_loader fl_stub_ffx_fsr3_host)
# WARP + CreateSwapChainForComposition means no GPU and no HWND are needed, so
# these run on a hosted CI runner — which is what 20_OPEN_QUESTIONS §H4 said
+380 -33
View File
@@ -35,6 +35,22 @@
// issue DXGI_PRESENT_TEST, which submits nothing
// --plus-ui K also present K frames on a SECOND swapchain in the same
// process (fixture for stream separation)
// --load PATH LoadLibrary PATH before anything else. Fixture for the
// guard's signer half (§S19(b)): a fragment-matching
// module in the TARGET, signed or not, is what the guard
// must judge
// --load-after-ms N PATH
// LoadLibrary PATH from a worker thread N ms after startup,
// while the hold mode presents. Fixture for the Overlay's
// LoadLibrary detour (17_HOOK_ENGINE §DLL entry, §S6): a
// vendor module that appears LATE, or an anti-cheat-named
// one, is what the detour must react to. Up to 4
// --vulkan with --hold-presenting N: a REAL Vulkan swapchain on a hidden
// window instead of the D3D11 one, presented every few ms, so
// the implicit layer's vkQueuePresentKHR is exercised under the
// real loader (P1 item 3). Exit 77 = this machine cannot run it
// (no loader / no presentable device), which the test that
// spawns it reads as SKIP, never as failure. vk_hold.cpp.
// --hold-presenting-overflow N
// fill the Overlay's fixed 16-slot swapchain table, then
// present for N seconds on one that cannot get a slot. The
@@ -52,6 +68,16 @@
// production call site at all
// --presents-per-eval K
// the FG factor --hold-presenting-fg emits. 1 is the control
// --sl-tag-for-frame
// make --hold-presenting-upscaled tag through slSetTagForFrame
// (Streamline 2.8's frame-based API) instead of slSetTag
// --sl-tag-whole-resource
// make --hold-presenting-upscaled tag with a ZERO extent and the
// size on the Resource instead (the whole-resource shape)
// --sl-tag-dlssg-inputs
// make --hold-presenting-upscaled tag depth, motion vectors, HUD-less
// and UI beside the scaling input -- the list a DLSS-G title sends
// every frame -- with NO kFeatureDLSS_G evaluation
// --probe-ffx-resolve
// AMD ffx-api: the Overlay's resolver picks each LEAF's own
// ffxDispatch with the loader decoy present, and a dispatch
@@ -61,13 +87,16 @@
// an FSR title does: one UPSCALE and one PREPARE (issued twice,
// same frameID) per application frame, one FRAMEGENERATION per
// frame at K > 1, then K presents (--presents-per-eval K)
// --ffx-topology 1x|2x|ue
// --ffx-topology 1x|2x|ue|fsr3host|fsr3host+mono
// which vendor shape --hold-presenting-ffx stands in: 2x (default)
// is the SDK 2.x pair of effect DLLs behind the LOADER (the game
// calls the loader; the loader forwards NOT through the leaves'
// exports -- measured), 1x the SDK 1.1.x monolith sending the
// pre-V2 PREPARE, ue the UE5 shape: the two effect DLLs called
// directly, no loader
// directly, no loader; fsr3host the FSR 3.0 HOST DLL alone
// (ffx_fsr3_x64.dll!ffxFsr3ContextDispatchUpscale, no PREPARE,
// no frame generation), fsr3host+mono Cyberpunk's shape: the host
// upscales while the 1.1.x monolith prepares and generates
// --ffx-no-prepare drop the PREPARE dispatch: the frame-generation-OFF shape, where
// the Overlay must count UPSCALE dispatches instead
//
@@ -106,6 +135,12 @@
#include <ffx_api.h>
#include <ffx_framegeneration.h>
#include <ffx_upscale.h>
// And the FSR 3.0 HOST API (tag fsr3-v3.0.4), for the descriptor the fsr3host
// topologies build and the type of the export they call on the host stub. Inside a
// namespace, as the Overlay includes it: both trees define FfxFrameGenerationConfig.
namespace fsr3host {
#include <FidelityFX/host/ffx_fsr3.h>
} // namespace fsr3host
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3d12.lib")
@@ -567,6 +602,27 @@ bool ProbeCost_PerPresent(Gfx& g) {
// a tight Present(0, DXGI_PRESENT_TEST) loop, which is what an alt-tabbed game
// runs, and the Overlay has to be measured against it deliberately rather than
// by accident.
// --load-after-ms: a module that appears while the harness presents. The worker
// sleeps, loads by absolute path, and prints; the process keeps the module for
// its life so the Overlay's scan and the guard's both see it.
struct LateLoad {
DWORD delayMs = 0;
wchar_t path[MAX_PATH * 2]{};
};
constexpr int kMaxLateLoads = 4;
LateLoad g_lateLoads[kMaxLateLoads];
int g_lateLoadCount = 0;
DWORD WINAPI LateLoadThread(LPVOID arg) {
auto* l = static_cast<LateLoad*>(arg);
Sleep(l->delayMs);
const HMODULE h = LoadLibraryW(l->path);
std::printf(" --load-after-ms %lu %ls -> %s\n", static_cast<unsigned long>(l->delayMs), l->path,
h != nullptr ? "loaded" : "FAILED");
std::fflush(stdout);
return h != nullptr ? 0u : 1u;
}
int PresentLoop(Gfx& g, int frames, bool real) {
const UINT flags = real ? 0u : DXGI_PRESENT_TEST;
for (int i = 0; i < frames; ++i) {
@@ -1725,7 +1781,55 @@ bool ProbeSlInputs() {
const sl::BaseStructure* one[] = {&tagWholeResource};
const auto r = fl::slinputs::FindScalingInputExtent(one, 1);
Check(!r.found && r.renderW == 0 && r.renderH == 0,
"a whole-resource tag yields the honest unknown, not a 0x0 resolution");
"a whole-resource tag with NO size on the Resource yields the honest unknown, not a 0x0 resolution");
}
{
// THE WHOLE-RESOURCE SHAPE WITH THE SIZE ON THE RESOURCE: extent zero, and
// the Resource the tag points at declares width/height. That is the title's
// statement of the input buffer's size, read from the argument it passed.
sl::Resource sized(sl::ResourceType::eTex2d, nullptr);
sized.width = kTaggedRenderW;
sized.height = kTaggedRenderH;
sl::ResourceTag whole(&sized, sl::kBufferTypeScalingInputColor, sl::ResourceLifecycle::eValidUntilPresent,
&zero);
const sl::BaseStructure* one[] = {&whole};
const auto r = fl::slinputs::FindScalingInputExtent(one, 1);
Check(r.found && r.renderW == kTaggedRenderW && r.renderH == kTaggedRenderH,
"a whole-resource tag takes the exact size the Resource declares");
}
{
// A non-zero extent WINS over the Resource's size: the extent is the area in
// use, the Resource may be the larger dynamic-resolution target.
sl::Resource bigger(sl::ResourceType::eTex2d, nullptr);
bigger.width = kTaggedRenderW * 2u;
bigger.height = kTaggedRenderH * 2u;
sl::ResourceTag sub(&bigger, sl::kBufferTypeScalingInputColor, sl::ResourceLifecycle::eValidUntilPresent,
&real);
const sl::BaseStructure* one[] = {&sub};
const auto r = fl::slinputs::FindScalingInputExtent(one, 1);
Check(r.found && r.renderW == kTaggedRenderW && r.renderH == kTaggedRenderH,
"an extent takes precedence over the Resource's own size");
}
{
// The Resource pointer names something that is NOT a Resource: GUID-checked
// and skipped, never read as one.
sl::ViewportHandle notAResource{9u};
sl::ResourceTag bad(reinterpret_cast<sl::Resource*>(&notAResource), sl::kBufferTypeScalingInputColor,
sl::ResourceLifecycle::eValidUntilPresent, &zero);
const sl::BaseStructure* one[] = {&bad};
Check(!fl::slinputs::FindScalingInputExtent(one, 1).found,
"a whole-resource tag whose Resource fails the GUID check yields nothing");
}
{
// TagSize is the SAME reading the global-tag detours use, so the direct
// call is asserted too: a Resource with one zero dimension is not a size.
sl::Resource half(sl::ResourceType::eTex2d, nullptr);
half.width = kTaggedRenderW;
sl::ResourceTag whole(&half, sl::kBufferTypeScalingInputColor, sl::ResourceLifecycle::eValidUntilPresent,
&zero);
uint32_t w = 0;
uint32_t h = 0;
Check(!fl::slinputs::TagSize(whole, w, h), "a Resource declaring only a width is not a size");
}
{
const sl::BaseStructure* one[] = {&tagOtherBuffer};
@@ -2156,6 +2260,51 @@ bool ProbeFfxResolve() {
Check(exportsUp() == 0u && exportsFg() == 0u,
"neither leaf's EXPORT was entered by the forward - the loader reached the direct entry, as the real "
"one was measured to bypass the leaf exports");
// THE FSR 3.0 HOST, the fifth module: its own export, resolved by ITS name through
// the host ABI arm, and the negatives that keep it from being mistaken for a leaf.
std::printf("\n[ffx] the FSR 3.0 host facade: resolved by name through its own ABI arm, and not a leaf\n");
const HMODULE host = LoadStubExactly(FL_STUB_FFX_FSR3_HOST);
Check(host != nullptr, "the ffx_fsr3_x64.dll host stub loaded from its absolute path");
if (host == nullptr) {
return false;
}
Check(fl::inventory::SpeaksFsr3Host(host), "the host stub speaks the four FSR 3.0 host names");
Check(!fl::inventory::SpeaksFsr3Host(decoy), "the sl.common.dll decoy does not");
Check(!fl::inventory::SpeaksFsr3Host(monolith),
"and neither does the 1.1.x monolith - the host's names are its own, so a monolith of the wrong NAME cannot "
"pass the host arm");
Check(!fl::inventory::SpeaksFfxApi(host), "the host does not speak ffx-api: it exports no ffxDispatch");
Check(fl::inventory::SpeaksExpectedAbi(fl::inventory::kModuleFfxFsr3Host, host),
"the ABI arm approves the host by its own name");
Check(!fl::inventory::SpeaksExpectedAbi(fl::inventory::kModuleFfxFsr3Host, monolith),
"and refuses a module of the host's name that does not speak the host ABI");
Check(fl::inventory::FfxLeafOf(fl::inventory::kModuleFfxFsr3Host) < 0,
"the host is NOT a leaf slot - the installer keys it by module name");
void* fromHost =
fl::inventory::ResolveScoped(fl::inventory::kModuleFfxFsr3Host, fl::inventory::kSymbolFfxFsr3DispatchUpscale);
Check(fromHost != nullptr &&
fromHost == reinterpret_cast<void*>(GetProcAddress(host, fl::inventory::kSymbolFfxFsr3DispatchUpscale)),
"ResolveScoped returned the host's own ffxFsr3ContextDispatchUpscale");
Check(fl::inventory::ResolveScoped(fl::inventory::kModuleFfxFsr3Host, "ffxDispatch") == nullptr,
"and the host has no ffxDispatch to resolve");
// The non-row, stated at runtime as well as at compile time: the export EXISTS on the
// module and no inventory row names it (20_OPEN_QUESTIONS §H11's reversal condition).
Check(GetProcAddress(host, "ffxFsr3DispatchFrameGeneration") != nullptr,
"the host exports ffxFsr3DispatchFrameGeneration");
bool fgIsARow = false;
bool hostIsARow = false;
#define FL_PROBE_HOST_ROW(mod, sym, family) \
if (std::strcmp(sym, "ffxFsr3DispatchFrameGeneration") == 0) { \
fgIsARow = true; \
} \
if (_wcsicmp(mod, fl::inventory::kModuleFfxFsr3Host) == 0) { \
hostIsARow = true; \
}
FL_HOOK_INVENTORY(FL_PROBE_HOST_ROW)
#undef FL_PROBE_HOST_ROW
Check(hostIsARow, "an FL_HOOK_INVENTORY row names ffx_fsr3_x64.dll");
Check(!fgIsARow, "and no row names ffxFsr3DispatchFrameGeneration - deliberately (dllmain.cpp)");
return g_failures == 0;
}
@@ -2178,13 +2327,19 @@ bool ProbeFfxResolve() {
// ---------------------------------------------------------------------------
using StubSetTagFn = sl::Result(STDMETHODCALLTYPE*)(const sl::ViewportHandle&, const sl::ResourceTag*, uint32_t,
sl::CommandBuffer*);
// The token slot is integer-class (a reference is a pointer) and nothing on either
// side dereferences it, so the dummy buffer stands in exactly as it does for
// slEvaluateFeature's token below.
using StubSetTagForFrameFn = sl::Result(STDMETHODCALLTYPE*)(const void*, const sl::ViewportHandle&,
const sl::ResourceTag*, uint32_t, sl::CommandBuffer*);
using StubEvaluateFn = sl::Result(STDMETHODCALLTYPE*)(sl::Feature, const void*, const void*, uint32_t, void*);
using StubTokenFn = sl::Result(STDMETHODCALLTYPE*)(sl::FrameToken*&, const uint32_t*);
alignas(16) unsigned char g_dummyFrameToken[64]{};
int HoldPresentingUpscaled(Gfx& g, int seconds, bool real, sl::Feature feature) {
int HoldPresentingUpscaled(Gfx& g, int seconds, bool real, sl::Feature feature, bool tagForFrame, bool wholeResource,
bool dlssgInputs) {
const HMODULE stub = LoadStubExactly(FL_STUB_SL_INTERPOSER);
if (stub == nullptr) {
Check(false, "the sl.interposer.dll stub loaded for the upscaled hold");
@@ -2214,16 +2369,50 @@ int HoldPresentingUpscaled(Gfx& g, int seconds, bool real, sl::Feature feature)
Check(false, "the stub exports slSetTag");
return 1;
}
// THE 2.8 ROUTE: the same tag list through slSetTagForFrame, and NEVER through
// slSetTag in that mode -- so an extent in the record can only have come from the
// frame-based row, which is what the injected case for it asserts.
auto setTagForFrame =
reinterpret_cast<StubSetTagForFrameFn>(reinterpret_cast<void*>(GetProcAddress(stub, "slSetTagForFrame")));
if (setTagForFrame == nullptr) {
Check(false, "the stub exports slSetTagForFrame");
return 1;
}
// Two shapes of the same statement. The extent shape is Cyberpunk's; the
// whole-resource shape (zero extent, size on the Resource) is the one a title
// that tags entire buffers produces, and under it an extent in the record can
// only have come from the Resource's declared size.
sl::Extent extent{};
sl::Extent zero{};
extent.width = kTaggedRenderW;
extent.height = kTaggedRenderH;
sl::ResourceTag tag(nullptr, sl::kBufferTypeScalingInputColor, sl::ResourceLifecycle::eValidUntilPresent, &extent);
sl::Resource sized(sl::ResourceType::eTex2d, nullptr);
sized.width = kTaggedRenderW;
sized.height = kTaggedRenderH;
sl::ResourceTag tag(wholeResource ? &sized : nullptr, sl::kBufferTypeScalingInputColor,
sl::ResourceLifecycle::eValidUntilPresent, wholeResource ? &zero : &extent);
sl::ViewportHandle viewport{0u};
// THE DLSS-G SHAPE: the same list a title running DLSS Frame Generation sends every
// frame (DLSS-G programming guide §5.0) -- depth, motion vectors, HUD-less colour and
// UI colour+alpha beside the scaling input. No kFeatureDLSS_G is evaluated here, so a
// record naming DLSS_G can only have come from the tags' TYPES.
sl::ResourceTag depthTag(nullptr, sl::kBufferTypeDepth, sl::ResourceLifecycle::eValidUntilPresent, &extent);
sl::ResourceTag mvecTag(nullptr, sl::kBufferTypeMotionVectors, sl::ResourceLifecycle::eValidUntilPresent, &extent);
sl::ResourceTag hudlessTag(nullptr, sl::kBufferTypeHUDLessColor, sl::ResourceLifecycle::eValidUntilPresent,
&extent);
sl::ResourceTag uiTag(nullptr, sl::kBufferTypeUIColorAndAlpha, sl::ResourceLifecycle::eValidUntilPresent, &extent);
sl::ResourceTag list[5] = {depthTag, mvecTag, tag, hudlessTag, uiTag};
const sl::ResourceTag* tags = dlssgInputs ? list : &tag;
const uint32_t numTags = dlssgInputs ? 5u : 1u;
const UINT flags = real ? 0u : DXGI_PRESENT_TEST;
std::printf(" presenting for %d second(s) [%s], evaluating feature %u before each present\n", seconds,
real ? "REAL" : "DXGI_PRESENT_TEST", static_cast<unsigned>(feature));
std::printf(" tagged kBufferTypeScalingInputColor extent %ux%u\n", kTaggedRenderW, kTaggedRenderH);
std::printf(" tagged kBufferTypeScalingInputColor %s %ux%u through %s%s\n",
wholeResource ? "whole resource, Resource size" : "extent", kTaggedRenderW, kTaggedRenderH,
tagForFrame ? "slSetTagForFrame (Streamline 2.8, frame-based)" : "slSetTag",
dlssgInputs ? ", beside depth, motion vectors, HUD-less and UI (the DLSS-G inputs)" : "");
std::fflush(stdout);
const ULONGLONG until = GetTickCount64() + static_cast<ULONGLONG>(seconds) * 1000ULL;
@@ -2233,7 +2422,11 @@ int HoldPresentingUpscaled(Gfx& g, int seconds, bool real, sl::Feature feature)
// Tag, then evaluate, then present -- the order a Streamline title uses,
// and the order that matters: the extent must be in place before the
// evaluation the Overlay attributes it to.
setTag(viewport, &tag, 1, nullptr);
if (tagForFrame) {
setTagForFrame(g_dummyFrameToken, viewport, tags, numTags, nullptr);
} else {
setTag(viewport, tags, numTags, nullptr);
}
// ONE EVALUATION PER PRESENT, which is what a real upscaled title does
// and what makes the drained record's identity checkable frame by frame.
eval(feature, g_dummyFrameToken, nullptr, 0, nullptr);
@@ -2368,13 +2561,37 @@ int HoldPresentingFg(Gfx& g, int seconds, bool real, int presentsPerEval) {
// ---------------------------------------------------------------------------
// Which module the fixture calls: 1x = the monolith, 2x = the loader (which forwards to
// the two leaves through their DIRECT entry, as measured), ue = the two leaves called
// directly with no loader in the process, the UE5 shape.
enum class FfxTopology { Monolith, Loader, Ue };
// directly with no loader in the process, the UE5 shape, fsr3host = the FSR 3.0 HOST
// DLL alone (its named UPSCALE export, no PREPARE, no frame generation -- the K = 1
// double-count control for that row), fsr3host+mono = Cyberpunk 2077's measured shape:
// the host upscales while the 1.1.x monolith prepares and generates.
enum class FfxTopology { Monolith, Loader, Ue, Fsr3Host, Fsr3HostMonolith };
using PfnFsr3DispatchUpscale = decltype(&fsr3host::ffxFsr3ContextDispatchUpscale);
int HoldPresentingFfx(Gfx& g, int seconds, bool real, int presentsPerEval, FfxTopology topology, bool prepare) {
HMODULE upEntry = nullptr; // where UPSCALE goes
HMODULE fgEntry = nullptr; // where PREPARE and FRAMEGENERATION go
if (topology == FfxTopology::Monolith) {
HMODULE upEntry = nullptr; // where UPSCALE goes (an ffx-api module)
HMODULE fgEntry = nullptr; // where PREPARE and FRAMEGENERATION go
HMODULE hostEntry = nullptr; // where UPSCALE goes on the FSR 3.0 host topologies
if (topology == FfxTopology::Fsr3Host || topology == FfxTopology::Fsr3HostMonolith) {
hostEntry = LoadStubExactly(FL_STUB_FFX_FSR3_HOST);
if (hostEntry == nullptr) {
Check(false, "the ffx_fsr3_x64.dll host stub loaded for the ffx hold");
return 1;
}
if (topology == FfxTopology::Fsr3HostMonolith) {
fgEntry = LoadStubExactly(FL_STUB_FFX_DX12);
if (fgEntry == nullptr) {
Check(false, "the SDK 1.1.x monolith stub loaded beside the host for the ffx hold");
return 1;
}
} else {
// The host alone prepares nothing and generates nothing: FSR 3.0's frame
// generation lives in ffx_frameinterpolation_x64.dll, which no row hooks. The
// count must come from the host's UPSCALE, so PREPARE is off whatever was asked.
prepare = false;
}
} else if (topology == FfxTopology::Monolith) {
upEntry = fgEntry = LoadStubExactly(FL_STUB_FFX_DX12);
if (upEntry == nullptr) {
Check(false, "the SDK 1.1.x monolith stub loaded for the ffx hold");
@@ -2406,16 +2623,30 @@ int HoldPresentingFfx(Gfx& g, int seconds, bool real, int presentsPerEval, FfxTo
fgEntry = fg;
}
}
auto dispatchUp = reinterpret_cast<PfnFfxDispatch>(reinterpret_cast<void*>(GetProcAddress(upEntry, "ffxDispatch")));
auto dispatchFg = reinterpret_cast<PfnFfxDispatch>(reinterpret_cast<void*>(GetProcAddress(fgEntry, "ffxDispatch")));
if (dispatchUp == nullptr || dispatchFg == nullptr) {
Check(false, "the entry module(s) export ffxDispatch");
auto dispatchUp =
upEntry != nullptr
? reinterpret_cast<PfnFfxDispatch>(reinterpret_cast<void*>(GetProcAddress(upEntry, "ffxDispatch")))
: nullptr;
auto dispatchFg =
fgEntry != nullptr
? reinterpret_cast<PfnFfxDispatch>(reinterpret_cast<void*>(GetProcAddress(fgEntry, "ffxDispatch")))
: nullptr;
auto dispatchHost = hostEntry != nullptr
? reinterpret_cast<PfnFsr3DispatchUpscale>(reinterpret_cast<void*>(
GetProcAddress(hostEntry, fl::inventory::kSymbolFfxFsr3DispatchUpscale)))
: nullptr;
if ((upEntry != nullptr && dispatchUp == nullptr) || (fgEntry != nullptr && dispatchFg == nullptr) ||
(hostEntry != nullptr && dispatchHost == nullptr)) {
Check(false, "the entry module(s) export their dispatch entry point");
return 1;
}
const bool topology2x = topology != FfxTopology::Monolith;
const char* topologyName = topology == FfxTopology::Monolith ? "SDK 1.1.x (monolith)"
: topology == FfxTopology::Loader ? "SDK 2.x (two leaves behind the loader)"
: "UE5 (two leaves, no loader)";
// The pre-V2 PREPARE is the 1.1.x monolith's, on both topologies that use it.
const bool topology2x = topology == FfxTopology::Loader || topology == FfxTopology::Ue;
const char* topologyName = topology == FfxTopology::Monolith ? "SDK 1.1.x (monolith)"
: topology == FfxTopology::Loader ? "SDK 2.x (two leaves behind the loader)"
: topology == FfxTopology::Ue ? "UE5 (two leaves, no loader)"
: topology == FfxTopology::Fsr3Host ? "FSR 3.0 host DLL alone"
: "FSR 3.0 host DLL + SDK 1.1.x monolith";
const int k = presentsPerEval < 1 ? 1 : presentsPerEval;
const UINT flags = real ? 0u : DXGI_PRESENT_TEST;
@@ -2447,14 +2678,26 @@ int HoldPresentingFfx(Gfx& g, int seconds, bool real, int presentsPerEval, FfxTo
gen.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATION;
gen.numGeneratedFrames = static_cast<uint32_t>(k - 1);
// The FSR 3.0 HOST descriptor, from the vendored fsr3-v3.0.4 struct: the same tagged
// extent, in the field the Overlay pins at offset 1256. Nothing else is set, and the
// stub reads nothing at all, so a record carrying this size proves the Overlay read it
// off the argument.
fsr3host::FfxFsr3DispatchUpscaleDescription hostUp{};
hostUp.renderSize.width = kTaggedRenderW;
hostUp.renderSize.height = kTaggedRenderH;
const ULONGLONG until = GetTickCount64() + static_cast<ULONGLONG>(seconds) * 1000ULL;
long long presented = 0;
long long frames = 0;
uint64_t frameId = 0;
while (GetTickCount64() < until) {
++frameId;
dispatchUp(nullptr, &up.header);
if (prepare) {
if (dispatchHost != nullptr) {
dispatchHost(nullptr, &hostUp);
} else {
dispatchUp(nullptr, &up.header);
}
if (prepare && dispatchFg != nullptr) {
// TWICE, SAME frameID: the SDK's own sample re-issues the prepare when its
// configuration changes, and the vendor's contract is about the INDEX. A
// writer that counted calls reads 2.0 at K = 1 here.
@@ -2462,7 +2705,7 @@ int HoldPresentingFfx(Gfx& g, int seconds, bool real, int presentsPerEval, FfxTo
dispatchFg(nullptr, &prep.header);
dispatchFg(nullptr, &prep.header);
}
if (k > 1) {
if (k > 1 && dispatchFg != nullptr) {
gen.frameID = frameId;
dispatchFg(nullptr, &gen.header);
}
@@ -2509,6 +2752,30 @@ bool ProbeFrameIdentity(Gfx& g) {
Check(realIsAFrame, "a real present submits exactly one frame");
std::printf(" %d real present(s) moved the counter by %u\n", kReal, afterReal - afterTest);
// The cost of asking. The Overlay reads this counter on every hooked present
// (dllmain RecordPresent, the DXGI-counted diagnostic 20_OPEN_QUESTIONS §H5
// A1.7), so the price of one call is part of the present hook's overhead
// statement. A measurement, not a check: a threshold here fails on a shared
// runner for reasons unrelated to the code (see --probe-cost).
{
constexpr int kCalls = 20000;
LARGE_INTEGER f{};
LARGE_INTEGER t0{};
LARGE_INTEGER t1{};
QueryPerformanceFrequency(&f);
UINT sink = 0;
QueryPerformanceCounter(&t0);
for (int i = 0; i < kCalls; ++i) {
g.swapChain1->GetLastPresentCount(&sink);
}
QueryPerformanceCounter(&t1);
const double ns =
static_cast<double>(t1.QuadPart - t0.QuadPart) * 1e9 / static_cast<double>(f.QuadPart) / kCalls;
std::printf(" GetLastPresentCount costs %.1f ns/call (%d calls, WARP; the Overlay pays this once per hooked "
"present)\n",
ns, kCalls);
}
// The two together are the contract. Separately, each passes against a
// wrong writer: a writer that ignores everything satisfies the first, and
// one that counts everything satisfies the second.
@@ -2517,11 +2784,31 @@ bool ProbeFrameIdentity(Gfx& g) {
} // namespace
// vk_hold.cpp -- the Vulkan mode (P1 item 3).
int HoldPresentingVulkan(int seconds, int presentIntervalMs);
int main(int argc, char** argv) {
std::printf("FrameLedger hook-harness (WARP, headless — no GPU or window required)\n");
// --vulkan skips the D3D11 device entirely: a Vulkan fixture that also mapped
// dxgi + d3d11 would be classified as a D3D target by the launch-mode guard
// (fl_guard.cpp FindPresentationRuntime) and get the Overlay instead of the
// layer -- the Overlay owning the ring and the layer observing nothing.
bool vulkanMode = false;
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--vulkan") == 0) {
vulkanMode = true;
}
}
if (vulkanMode) {
// A real Vulkan title imports vulkan-1.dll, so it is mapped before its
// first instruction; this fixture imports d3d11/dxgi instead. Map the
// loader NOW so the launch-mode guard's first poll sees what it would see
// on a real title, rather than a D3D process that turns Vulkan later.
LoadLibraryW(L"vulkan-1.dll");
}
Gfx g;
if (!CreateGfx(g)) {
if (!vulkanMode && !CreateGfx(g)) {
std::printf("FAILED: could not create the graphics objects\n");
return 2;
}
@@ -2535,6 +2822,7 @@ int main(int argc, char** argv) {
bool ranSomething = false;
// --real applies to --present and --hold, wherever it appears on the line.
bool real = false;
bool vulkan = false;
int plusUi = 0;
// MILLISECONDS BETWEEN PRESENTS in the --hold-presenting modes. 8 is ~120/s and is the default for
@@ -2562,10 +2850,15 @@ int main(int argc, char** argv) {
// hold mode drives every combination and the tests assert one expression.
FfxTopology ffxTopology = FfxTopology::Loader;
bool ffxPrepare = true;
bool slTagForFrame = false;
bool slTagWholeResource = false;
bool slTagDlssgInputs = false;
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--real") == 0) {
real = true;
} else if (std::strcmp(argv[i], "--vulkan") == 0) {
vulkan = true;
} else if (std::strcmp(argv[i], "--plus-ui") == 0 && i + 1 < argc) {
plusUi = std::atoi(argv[++i]);
} else if (std::strcmp(argv[i], "--present-interval-ms") == 0 && i + 1 < argc) {
@@ -2584,22 +2877,65 @@ int main(int argc, char** argv) {
}
} else if (std::strcmp(argv[i], "--ffx-topology") == 0 && i + 1 < argc) {
const char* t = argv[++i];
ffxTopology = std::strcmp(t, "1x") == 0 ? FfxTopology::Monolith
: std::strcmp(t, "ue") == 0 ? FfxTopology::Ue
: FfxTopology::Loader;
ffxTopology = std::strcmp(t, "1x") == 0 ? FfxTopology::Monolith
: std::strcmp(t, "ue") == 0 ? FfxTopology::Ue
: std::strcmp(t, "fsr3host") == 0 ? FfxTopology::Fsr3Host
: std::strcmp(t, "fsr3host+mono") == 0 ? FfxTopology::Fsr3HostMonolith
: FfxTopology::Loader;
} else if (std::strcmp(argv[i], "--ffx-no-prepare") == 0) {
ffxPrepare = false;
} else if (std::strcmp(argv[i], "--sl-tag-for-frame") == 0) {
slTagForFrame = true;
} else if (std::strcmp(argv[i], "--sl-tag-whole-resource") == 0) {
slTagWholeResource = true;
} else if (std::strcmp(argv[i], "--sl-tag-dlssg-inputs") == 0) {
slTagDlssgInputs = true;
} else if (std::strcmp(argv[i], "--load-after-ms") == 0 && i + 2 < argc) {
if (g_lateLoadCount < kMaxLateLoads) {
LateLoad& l = g_lateLoads[g_lateLoadCount];
l.delayMs = static_cast<DWORD>(std::atoi(argv[++i]));
const char* path = argv[++i];
MultiByteToWideChar(CP_ACP, 0, path, -1, l.path, static_cast<int>(sizeof(l.path) / sizeof(l.path[0])));
HANDLE t = CreateThread(nullptr, 0, &LateLoadThread, &l, 0, nullptr);
if (t != nullptr) {
CloseHandle(t);
}
++g_lateLoadCount;
} else {
i += 2;
}
} else if (std::strcmp(argv[i], "--load") == 0 && i + 1 < argc) {
// The fixture for the guard's signer half: put a named module into
// THIS process before the guard looks. Loaded, not injected, and it
// stays loaded for the life of the process so the scan sees it.
const char* path = argv[++i];
wchar_t wide[MAX_PATH * 2]{};
const int n =
MultiByteToWideChar(CP_ACP, 0, path, -1, wide, static_cast<int>(sizeof(wide) / sizeof(wide[0])));
HMODULE h = n > 0 ? LoadLibraryW(wide) : nullptr;
std::printf(" --load %s -> %s\n", path, h != nullptr ? "loaded" : "FAILED");
if (h == nullptr) {
return 3;
}
}
}
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--real") == 0 || std::strcmp(argv[i], "--plus-ui") == 0 ||
std::strcmp(argv[i], "--present-interval-ms") == 0 || std::strcmp(argv[i], "--presents-per-eval") == 0 ||
std::strcmp(argv[i], "--ffx-topology") == 0 || std::strcmp(argv[i], "--ffx-no-prepare") == 0) {
if (std::strcmp(argv[i], "--real") == 0 || std::strcmp(argv[i], "--vulkan") == 0 ||
std::strcmp(argv[i], "--plus-ui") == 0 || std::strcmp(argv[i], "--present-interval-ms") == 0 ||
std::strcmp(argv[i], "--presents-per-eval") == 0 || std::strcmp(argv[i], "--ffx-topology") == 0 ||
std::strcmp(argv[i], "--ffx-no-prepare") == 0 || std::strcmp(argv[i], "--sl-tag-for-frame") == 0 ||
std::strcmp(argv[i], "--sl-tag-whole-resource") == 0 ||
std::strcmp(argv[i], "--sl-tag-dlssg-inputs") == 0 || std::strcmp(argv[i], "--load") == 0 ||
std::strcmp(argv[i], "--load-after-ms") == 0) {
if (std::strcmp(argv[i], "--plus-ui") == 0 || std::strcmp(argv[i], "--present-interval-ms") == 0 ||
std::strcmp(argv[i], "--presents-per-eval") == 0 || std::strcmp(argv[i], "--ffx-topology") == 0) {
std::strcmp(argv[i], "--presents-per-eval") == 0 || std::strcmp(argv[i], "--ffx-topology") == 0 ||
std::strcmp(argv[i], "--load") == 0) {
++i;
}
if (std::strcmp(argv[i], "--load-after-ms") == 0) {
i += 2;
}
continue; // consumed above
} else if (std::strcmp(argv[i], "--probe-frames") == 0) {
ok = ProbeFrameIdentity(g) && ok;
@@ -2611,7 +2947,9 @@ int main(int argc, char** argv) {
ok = HoldPresentingFfx(g, std::atoi(argv[++i]), real, presentsPerEval, ffxTopology, ffxPrepare) == 0 && ok;
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting-upscaled") == 0 && i + 1 < argc) {
ok = HoldPresentingUpscaled(g, std::atoi(argv[++i]), real, sl::kFeatureDLSS) == 0 && ok;
ok = HoldPresentingUpscaled(g, std::atoi(argv[++i]), real, sl::kFeatureDLSS, slTagForFrame,
slTagWholeResource, slTagDlssgInputs) == 0 &&
ok;
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting-upscaled-unknown") == 0 && i + 1 < argc) {
// The SAME target, evaluating a feature id the Overlay does not
@@ -2619,7 +2957,9 @@ int main(int argc, char** argv) {
// SET -- "a hook ran and could not identify what it saw" -- and must
// never report FL_UPSCALER_NONE, which is the only state that may be
// aggregated as a negative. 0xF00D is not a Streamline feature.
ok = HoldPresentingUpscaled(g, std::atoi(argv[++i]), real, static_cast<sl::Feature>(0xF00Du)) == 0 && ok;
ok = HoldPresentingUpscaled(g, std::atoi(argv[++i]), real, static_cast<sl::Feature>(0xF00Du), slTagForFrame,
slTagWholeResource, slTagDlssgInputs) == 0 &&
ok;
ranSomething = true;
} else if (std::strcmp(argv[i], "--probe-upscaler-resolve") == 0) {
ok = ProbeUpscalerResolve() && ok;
@@ -2748,6 +3088,13 @@ int main(int argc, char** argv) {
f->Release();
}
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting") == 0 && i + 1 < argc && vulkan) {
// The Vulkan mode: its own file, its own exit codes (77 = cannot run here).
const int code = HoldPresentingVulkan(std::atoi(argv[++i]), presentIntervalMs);
if (code != 0) {
return code;
}
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting") == 0 && i + 1 < argc) {
// WHAT --hold CANNOT DO, and why the injection tests needed this.
//
+328
View File
@@ -0,0 +1,328 @@
// hook-harness --vulkan --hold-presenting N: a REAL Vulkan swapchain on a hidden
// window, presented every few milliseconds for N seconds, so the layer's
// vkQueuePresentKHR can be exercised under the real loader (12_BUILD §Targets:
// "Vulkan and OpenGL modes to follow as those hooks land" -- this is the Vulkan
// one, P1 item 3).
//
// The loader is reached through LoadLibraryW("vulkan-1.dll") and
// vkGetInstanceProcAddr, never a link-time import: the repository vendors the
// Khronos HEADERS only, and CI has no loader at all. Exit codes:
// 0 presented for the whole hold
// 77 this machine cannot run the fixture (no loader, no device, no surface
// support) -- a SKIP for the test that spawns it, never a failure
// 2 the fixture is broken (an API that should have worked did not)
#define VK_USE_PLATFORM_WIN32_KHR
#include <windows.h>
#include <vulkan/vulkan.h>
#include <cstdio>
#include <cstdlib>
#include <vector>
namespace {
PFN_vkGetInstanceProcAddr g_gipa = nullptr;
template <typename T>
T Instance(VkInstance instance, const char* name) {
return reinterpret_cast<T>(g_gipa(instance, name));
}
LRESULT CALLBACK HiddenWndProc(HWND h, UINT m, WPARAM w, LPARAM l) {
return DefWindowProcW(h, m, w, l);
}
HWND CreateHiddenWindow() {
WNDCLASSW wc{};
wc.lpfnWndProc = &HiddenWndProc;
wc.hInstance = GetModuleHandleW(nullptr);
wc.lpszClassName = L"FrameLedgerHookHarnessVulkan";
RegisterClassW(&wc);
// Never shown: a surface needs an HWND, not a visible one.
return CreateWindowExW(0, wc.lpszClassName, L"FrameLedger hook-harness (Vulkan)", WS_OVERLAPPEDWINDOW, 0, 0, 256,
256, nullptr, nullptr, wc.hInstance, nullptr);
}
int Skip(const char* why) {
std::printf(" [SKIP] %s\n", why);
std::fflush(stdout);
return 77;
}
int Broken(const char* what, VkResult r) {
std::printf(" [FAIL] %s (VkResult %d)\n", what, static_cast<int>(r));
std::fflush(stdout);
return 2;
}
} // namespace
int HoldPresentingVulkan(int seconds, int presentIntervalMs) {
std::printf("\n[vulkan-hold] a real swapchain on a hidden window, presenting for %d second(s) every %d ms\n",
seconds, presentIntervalMs);
std::fflush(stdout);
const HMODULE loader = LoadLibraryW(L"vulkan-1.dll");
if (loader == nullptr) {
return Skip("no vulkan-1.dll on this machine");
}
g_gipa = reinterpret_cast<PFN_vkGetInstanceProcAddr>(GetProcAddress(loader, "vkGetInstanceProcAddr"));
if (g_gipa == nullptr) {
return Skip("vulkan-1.dll exports no vkGetInstanceProcAddr");
}
// --- instance ---------------------------------------------------------
auto createInstance = Instance<PFN_vkCreateInstance>(nullptr, "vkCreateInstance");
VkApplicationInfo app{};
app.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app.pApplicationName = "FrameLedger hook-harness";
app.apiVersion = VK_API_VERSION_1_1;
const char* instanceExts[] = {"VK_KHR_surface", "VK_KHR_win32_surface"};
VkInstanceCreateInfo ici{};
ici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
ici.pApplicationInfo = &app;
ici.enabledExtensionCount = 2;
ici.ppEnabledExtensionNames = instanceExts;
VkInstance instance = nullptr;
if (createInstance == nullptr || createInstance(&ici, nullptr, &instance) != VK_SUCCESS) {
return Skip("vkCreateInstance failed (no ICD, or no surface extensions)");
}
auto enumPhys = Instance<PFN_vkEnumeratePhysicalDevices>(instance, "vkEnumeratePhysicalDevices");
auto queueProps =
Instance<PFN_vkGetPhysicalDeviceQueueFamilyProperties>(instance, "vkGetPhysicalDeviceQueueFamilyProperties");
auto surfaceSupport =
Instance<PFN_vkGetPhysicalDeviceSurfaceSupportKHR>(instance, "vkGetPhysicalDeviceSurfaceSupportKHR");
auto createSurface = Instance<PFN_vkCreateWin32SurfaceKHR>(instance, "vkCreateWin32SurfaceKHR");
auto surfaceCaps =
Instance<PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR>(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
auto surfaceFormats =
Instance<PFN_vkGetPhysicalDeviceSurfaceFormatsKHR>(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR");
auto createDevice = Instance<PFN_vkCreateDevice>(instance, "vkCreateDevice");
auto gdpa = Instance<PFN_vkGetDeviceProcAddr>(instance, "vkGetDeviceProcAddr");
if (enumPhys == nullptr || queueProps == nullptr || surfaceSupport == nullptr || createSurface == nullptr ||
surfaceCaps == nullptr || surfaceFormats == nullptr || createDevice == nullptr || gdpa == nullptr) {
return Skip("the instance lacks the surface / device entry points this fixture needs");
}
// --- surface ----------------------------------------------------------
const HWND hwnd = CreateHiddenWindow();
if (hwnd == nullptr) {
return Skip("no window could be created (no interactive window station?)");
}
VkWin32SurfaceCreateInfoKHR sci{};
sci.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
sci.hinstance = GetModuleHandleW(nullptr);
sci.hwnd = hwnd;
VkSurfaceKHR surface = VK_NULL_HANDLE;
if (createSurface(instance, &sci, nullptr, &surface) != VK_SUCCESS) {
return Skip("vkCreateWin32SurfaceKHR failed");
}
// --- a physical device with a queue that can draw AND present ---------
uint32_t physCount = 0;
enumPhys(instance, &physCount, nullptr);
std::vector<VkPhysicalDevice> phys(physCount);
enumPhys(instance, &physCount, phys.data());
VkPhysicalDevice chosen = nullptr;
uint32_t family = 0;
for (VkPhysicalDevice p : phys) {
uint32_t n = 0;
queueProps(p, &n, nullptr);
std::vector<VkQueueFamilyProperties> props(n);
queueProps(p, &n, props.data());
for (uint32_t i = 0; i < n && chosen == nullptr; ++i) {
VkBool32 present = VK_FALSE;
if ((props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0u &&
surfaceSupport(p, i, surface, &present) == VK_SUCCESS && present == VK_TRUE) {
chosen = p;
family = i;
}
}
if (chosen != nullptr) {
break;
}
}
if (chosen == nullptr) {
return Skip("no physical device with a graphics queue that can present to a Win32 surface");
}
// --- device -----------------------------------------------------------
const float priority = 1.0f;
VkDeviceQueueCreateInfo qci{};
qci.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
qci.queueFamilyIndex = family;
qci.queueCount = 1;
qci.pQueuePriorities = &priority;
const char* deviceExts[] = {"VK_KHR_swapchain"};
VkDeviceCreateInfo dci{};
dci.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
dci.queueCreateInfoCount = 1;
dci.pQueueCreateInfos = &qci;
dci.enabledExtensionCount = 1;
dci.ppEnabledExtensionNames = deviceExts;
VkDevice device = nullptr;
if (VkResult r = createDevice(chosen, &dci, nullptr, &device); r != VK_SUCCESS) {
return Broken("vkCreateDevice", r);
}
#define FL_DEV(name) auto name = reinterpret_cast<PFN_##name>(gdpa(device, #name))
FL_DEV(vkGetDeviceQueue);
FL_DEV(vkCreateSwapchainKHR);
FL_DEV(vkGetSwapchainImagesKHR);
FL_DEV(vkAcquireNextImageKHR);
FL_DEV(vkQueuePresentKHR);
FL_DEV(vkQueueSubmit);
FL_DEV(vkQueueWaitIdle);
FL_DEV(vkCreateSemaphore);
FL_DEV(vkCreateCommandPool);
FL_DEV(vkAllocateCommandBuffers);
FL_DEV(vkBeginCommandBuffer);
FL_DEV(vkEndCommandBuffer);
FL_DEV(vkCmdPipelineBarrier);
FL_DEV(vkDeviceWaitIdle);
#undef FL_DEV
if (vkGetDeviceQueue == nullptr || vkCreateSwapchainKHR == nullptr || vkGetSwapchainImagesKHR == nullptr ||
vkAcquireNextImageKHR == nullptr || vkQueuePresentKHR == nullptr || vkQueueSubmit == nullptr ||
vkQueueWaitIdle == nullptr || vkCreateSemaphore == nullptr || vkCreateCommandPool == nullptr ||
vkAllocateCommandBuffers == nullptr || vkBeginCommandBuffer == nullptr || vkEndCommandBuffer == nullptr ||
vkCmdPipelineBarrier == nullptr || vkDeviceWaitIdle == nullptr) {
return Broken("a device entry point was missing", VK_ERROR_INITIALIZATION_FAILED);
}
VkQueue queue = nullptr;
vkGetDeviceQueue(device, family, 0, &queue);
// --- swapchain --------------------------------------------------------
VkSurfaceCapabilitiesKHR caps{};
surfaceCaps(chosen, surface, &caps);
uint32_t formatCount = 0;
surfaceFormats(chosen, surface, &formatCount, nullptr);
std::vector<VkSurfaceFormatKHR> formats(formatCount);
surfaceFormats(chosen, surface, &formatCount, formats.data());
if (formats.empty()) {
return Skip("the surface reports no formats");
}
VkExtent2D extent = caps.currentExtent;
if (extent.width == 0xFFFFFFFFu || extent.width == 0u || extent.height == 0u) {
extent = VkExtent2D{256u, 256u};
}
VkSwapchainCreateInfoKHR sc{};
sc.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
sc.surface = surface;
sc.minImageCount = caps.minImageCount < 2u ? 2u : caps.minImageCount;
if (caps.maxImageCount != 0u && sc.minImageCount > caps.maxImageCount) {
sc.minImageCount = caps.maxImageCount;
}
sc.imageFormat = formats[0].format;
sc.imageColorSpace = formats[0].colorSpace;
sc.imageExtent = extent;
sc.imageArrayLayers = 1;
sc.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
sc.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
sc.preTransform = caps.currentTransform;
sc.compositeAlpha = (caps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) != 0u
? VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR
: VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
sc.presentMode = VK_PRESENT_MODE_FIFO_KHR;
sc.clipped = VK_TRUE;
VkSwapchainKHR swapchain = VK_NULL_HANDLE;
if (VkResult r = vkCreateSwapchainKHR(device, &sc, nullptr, &swapchain); r != VK_SUCCESS) {
return Broken("vkCreateSwapchainKHR", r);
}
uint32_t imageCount = 0;
vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr);
std::vector<VkImage> images(imageCount);
vkGetSwapchainImagesKHR(device, swapchain, &imageCount, images.data());
// --- one command buffer per image: UNDEFINED -> PRESENT_SRC, nothing drawn -
VkCommandPoolCreateInfo pci{};
pci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pci.queueFamilyIndex = family;
VkCommandPool pool = VK_NULL_HANDLE;
if (VkResult r = vkCreateCommandPool(device, &pci, nullptr, &pool); r != VK_SUCCESS) {
return Broken("vkCreateCommandPool", r);
}
VkCommandBufferAllocateInfo cai{};
cai.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cai.commandPool = pool;
cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cai.commandBufferCount = imageCount;
std::vector<VkCommandBuffer> cmds(imageCount);
if (VkResult r = vkAllocateCommandBuffers(device, &cai, cmds.data()); r != VK_SUCCESS) {
return Broken("vkAllocateCommandBuffers", r);
}
for (uint32_t i = 0; i < imageCount; ++i) {
VkCommandBufferBeginInfo bi{};
bi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
vkBeginCommandBuffer(cmds[i], &bi);
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = images[i];
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.layerCount = 1;
barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
vkCmdPipelineBarrier(cmds[i], VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0,
nullptr, 0, nullptr, 1, &barrier);
vkEndCommandBuffer(cmds[i]);
}
VkSemaphoreCreateInfo semi{};
semi.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkSemaphore acquired = VK_NULL_HANDLE;
VkSemaphore ready = VK_NULL_HANDLE;
vkCreateSemaphore(device, &semi, nullptr, &acquired);
vkCreateSemaphore(device, &semi, nullptr, &ready);
// --- the hold ---------------------------------------------------------
const ULONGLONG until = GetTickCount64() + static_cast<ULONGLONG>(seconds) * 1000ULL;
long long presented = 0;
while (GetTickCount64() < until) {
uint32_t index = 0;
VkResult r = vkAcquireNextImageKHR(device, swapchain, 1000000000ull, acquired, VK_NULL_HANDLE, &index);
if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) {
return Broken("vkAcquireNextImageKHR", r);
}
const VkPipelineStageFlags wait = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
VkSubmitInfo si{};
si.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
si.waitSemaphoreCount = 1;
si.pWaitSemaphores = &acquired;
si.pWaitDstStageMask = &wait;
si.commandBufferCount = 1;
si.pCommandBuffers = &cmds[index];
si.signalSemaphoreCount = 1;
si.pSignalSemaphores = &ready;
if (r = vkQueueSubmit(queue, 1, &si, VK_NULL_HANDLE); r != VK_SUCCESS) {
return Broken("vkQueueSubmit", r);
}
VkPresentInfoKHR pi{};
pi.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
pi.waitSemaphoreCount = 1;
pi.pWaitSemaphores = &ready;
pi.swapchainCount = 1;
pi.pSwapchains = &swapchain;
pi.pImageIndices = &index;
r = vkQueuePresentKHR(queue, &pi);
if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) {
return Broken("vkQueuePresentKHR", r);
}
++presented;
vkQueueWaitIdle(queue); // simplest correct pacing: no fences to juggle in a fixture
if (presentIntervalMs > 0) {
Sleep(static_cast<DWORD>(presentIntervalMs));
}
}
vkDeviceWaitIdle(device);
// The count goes to stdout so a test can compare it against records drained
// from the ring rather than asserting "more than zero".
std::printf(" presented=%lld\n", presented);
std::fflush(stdout);
// Objects are left for process exit: this is a fixture that ends here, and a
// teardown that itself could fail would only add exit codes to a test.
return 0;
}
+10 -1
View File
@@ -23,7 +23,7 @@ function(fl_add_vendor_stub target output source)
# supply the vendor signatures so the stub and the detour cannot disagree about
# the ABI. Both are INTERFACE include targets and link nothing.
target_link_libraries(${target} PRIVATE FrameLedger.Shm fl_native_flags fl_streamline_headers
fl_fidelityfx_headers)
fl_fidelityfx_headers fl_fsr3_host_headers)
target_include_directories(${target} PRIVATE
"${CMAKE_SOURCE_DIR}/FrameLedger.Overlay/include"
"${CMAKE_CURRENT_SOURCE_DIR}")
@@ -75,3 +75,12 @@ fl_add_vendor_stub(fl_stub_ffx_dx12 "amd_fidelityfx_dx12" stub_amd_fidelityfx_dx
fl_add_vendor_stub(fl_stub_ffx_upscaler "amd_fidelityfx_upscaler_dx12" stub_amd_fidelityfx_upscaler_dx12.cpp)
fl_add_vendor_stub(fl_stub_ffx_fg "amd_fidelityfx_framegeneration_dx12" stub_amd_fidelityfx_framegeneration_dx12.cpp)
fl_add_vendor_stub(fl_stub_ffx_loader "amd_fidelityfx_loader_dx12" stub_amd_fidelityfx_loader_dx12.cpp)
# --- AMD FidelityFX, the FSR 3.0 HOST API (Cyberpunk 2077's ffx_fsr3_x64.dll) ---
#
# NOT A LEAF: named exports, the 3.0 host's own descriptor, one row
# (ffxFsr3ContextDispatchUpscale). Exports exactly the four names SpeaksFsr3Host
# probes for, through the vendored header's own FFX_API (dllexport, no switch) -- and
# is therefore hookinventory-check Pass C's SECOND positive control for the export
# parser, beside the ffx-api leaf.
fl_add_vendor_stub(fl_stub_ffx_fsr3_host "ffx_fsr3_x64" stub_ffx_fsr3_x64.cpp)
@@ -0,0 +1,81 @@
// A stub that answers to the name `ffx_fsr3_x64.dll` -- the FSR 3.0 HOST DLL Cyberpunk
// 2077 ships beside its 1.1.x monolith -- and exports the four names
// fl::inventory::SpeaksFsr3Host probes for, one of which is the row the Overlay hooks.
//
// NOT A LEAF: it exports no ffxDispatch and shares nothing with stub_ffx_leaf.inl. The
// one export the Overlay detours takes the host API's own descriptor, whose renderSize
// sits 1256 bytes in; the stub reads none of it, so renderW/H in a record can only have
// come from the Overlay reading the argument.
//
// THE SIGNATURES AND THE EXPORT LINKAGE COME FROM THE VENDORED MIT HEADER (tag
// fsr3-v3.0.4). FFX_API there is __declspec(dllexport) with no switch, so defining
// the function here exports it under exactly the declaration the Overlay's detour is
// typed by -- and the same header, included by FrameLedger.Overlay for types only,
// exports nothing there because nothing there defines these names. This DLL is Pass C's
// second positive control: its export table MUST show ffxFsr3ContextDispatchUpscale.
#include <FidelityFX/host/ffx_fsr3.h>
#include "stub_common.h"
static_assert(
fl::stub::InventoryHasRow(fl::inventory::kModuleFfxFsr3Host, fl::inventory::kSymbolFfxFsr3DispatchUpscale),
"fl_hook_inventory.h has no ffxFsr3ContextDispatchUpscale row for ffx_fsr3_x64.dll, so this fixture would "
"exercise a name the Overlay does not install");
static_assert(
!fl::stub::InventoryHas("ffxFsr3DispatchFrameGeneration"),
"ffxFsr3DispatchFrameGeneration is deliberately NOT a row (dllmain.cpp, fl_hook_inventory.h): on the one "
"title that ships the host DLL frame generation goes through the monolith, and the pre-committed reversal "
"condition in 20_OPEN_QUESTIONS §H11 has not fired");
static_assert(!fl::stub::InventoryHas("ffxFsr3SkipPresent"), "probe-only, never a row");
namespace {
volatile LONG g_upscales = 0;
volatile LONG g_contexts = 0;
} // namespace
extern "C" {
FFX_API FfxErrorCode ffxFsr3ContextCreate(FfxFsr3Context* context, FfxFsr3ContextDescription* contextDescription) {
if (context == nullptr || contextDescription == nullptr) {
return FFX_ERROR_INVALID_POINTER;
}
InterlockedIncrement(&g_contexts);
return FFX_OK;
}
// THE ROW'S TARGET. Counts the call and reads nothing of the descriptor.
FFX_API FfxErrorCode ffxFsr3ContextDispatchUpscale(FfxFsr3Context* context,
const FfxFsr3DispatchUpscaleDescription* dispatchParams) {
(void)context;
if (dispatchParams == nullptr) {
return FFX_ERROR_INVALID_POINTER;
}
InterlockedIncrement(&g_upscales);
return FFX_OK;
}
FFX_API FfxErrorCode ffxFsr3DispatchFrameGeneration(const FfxFrameGenerationDispatchDescription* desc) {
return desc != nullptr ? FFX_OK : FFX_ERROR_INVALID_POINTER;
}
FFX_API FfxErrorCode ffxFsr3SkipPresent(FfxFsr3Context* context) {
(void)context;
return FFX_OK;
}
// FrameLedger-named observer, so nothing here pretends to be part of a vendor API.
__declspec(dllexport) unsigned int FlStubFsr3UpscaleCalls() {
return static_cast<unsigned int>(InterlockedCompareExchange(&g_upscales, 0, 0));
}
} // extern "C"
BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID) {
if (reason == DLL_PROCESS_ATTACH) {
DisableThreadLibraryCalls(module);
}
return TRUE;
}
@@ -59,6 +59,9 @@ StubFrameToken g_tokenPool[8];
static_assert(fl::stub::InventoryHas("slGetNewFrameToken"),
"fl_hook_inventory.h no longer contains \"slGetNewFrameToken\", so the frame-token fixture would "
"exercise a row the Overlay does not install.");
static_assert(fl::stub::InventoryHas("slSetTagForFrame"),
"fl_hook_inventory.h no longer contains \"slSetTagForFrame\", so the frame-based tag fixture would "
"exercise a row the Overlay does not install.");
static_assert(fl::stub::InventoryHas("slEvaluateFeature"),
"fl_hook_inventory.h no longer contains \"slEvaluateFeature\", so this stub would export a name "
"the Overlay does not look for -- the fixture would pass while proving nothing "
@@ -99,6 +102,22 @@ SL_API sl::Result slSetTag(const sl::ViewportHandle& viewport, const sl::Resourc
return sl::Result::eOk;
}
// THE FRAME-BASED TAG ENTRY POINT (Streamline 2.8: Dying Light: The Beast ships
// 2.8.0, which exports this beside the deprecated slSetTag). Signature from the
// vendored header, as above. The stub records nothing here either; the harness
// drives it with a known extent so the injected case can assert the Overlay read
// renderW/H off THIS route rather than off slSetTag.
SL_API sl::Result slSetTagForFrame(const sl::FrameToken& frame, const sl::ViewportHandle& viewport,
const sl::ResourceTag* resources, uint32_t numResources,
sl::CommandBuffer* cmdBuffer) {
(void)frame;
(void)viewport;
(void)resources;
(void)numResources;
(void)cmdBuffer;
return sl::Result::eOk;
}
// THE ABI MARKERS. Three SL2-only entry points, exported so this stub actually
// looks like the generation it stands in for.
//
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more