Streamline: NVIDIA Reflex low latency without frame generation (VICTORY_REFLEX=on|boost) #3072

Open
Adriwin06 wants to merge 3 commits from upstream-pr/3072 into main
Adriwin06 commented 2026-11-29 19:52:57 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Adriwin06 on 2026-11-29T19:52:57Z.


What it changes

Reflex low latency was set only while frame generation is on (#250).
VICTORY_REFLEX=on (or boost, low latency with boost) turns it on with
or without frame generation and paces the title's frames with Reflex's
markers:

  • streamline/reflex.rs: the per-frame state (frame tokens matched
    across the input reading, the origin wait, the submissions and the
    present), Reflex's sleep with a watchdog, and 10 s telemetry lines;
    streamline/abi.rs: the Streamline 2.14 ReflexReport, ReflexReport2
    and ReflexState layouts.
  • frame.rs, queue.rs and GameInput: frame_begins, title_submits (the
    first direct-queue submission of a frame, tagged by ExecuteCommandListsX's
    token), title_presents, and input_sampling (GetCurrentReading), where
    the sleep and SimulationStart happen when the title reads input
    every frame.
  • F1: NVIDIA REFLEX (LOW LATENCY): OFF / ON / ON + BOOST.

Unset, nothing changes: no marker is sent and frame generation sets
Reflex as before.

Ported from Kemerd/VIctory-NVIDIA-RT@6463141 and
Kemerd/VIctory-NVIDIA-RT@14f973b (Kemerd),
GPL-3.0-or-later. Upstream asked for Reflex as a pull request of its
own in #18.

How it was tested

  • GPU and profile: RTX 4070 SUPER, Ryzen 7 5800X. Not measured in the title on these commits by themselves: they come from a fork of mine that carries them with the rest of this set, and the title ran there. What is below is the unit tests on this branch.
  • Before: n/a (no in-title measurement on this branch)
  • After: n/a
  • cargo test passed for the crates it touches:
    • this change: no: 112 passed, 1 failed: host::menu::tests::a_change_is_saved_at_once_however_the_game_was_started (cargo test -p victory-gpu --lib -- streamline:: queue:: frame:: host::menu::); the one failure is the menu tests' race on VICTORY_MENU_FILE, which fails on main too (fixed in #3061)
  • cargo clippy --workspace --all-targets --locked: no finding that main does not already have (main has 34 of its own, which is why the Clippy step of CI is red on main itself).
  • cargo xtask policy: no new finding (main fails it on crates/victory-loader/src/heap_sites/frame_users.rs).
  • With all eleven of my pull requests merged together: cargo clippy also with --all-features adds no finding, and cargo test --workspace --locked fails only tests main also fails on this machine: the five shader tests that fail on main here too (WARP's SM 6.2 and the validator) (barycentric_tests::first_half_values_render_on_hardware_and_warp, hw_tests::split_lds_wave32_read_after_read_barrier_coalescing_and_parity, intersect_tests::flat_global_stores_and_atomics_fence_uavs_at_group_barriers_across_waves, rect::tests::rectangles_are_drawn_whole, rect::tests::the_rectangle_stage_is_a_geometry_shader) and xtask's repository_passes_policy (frame_users.rs). 2208 passed, including five that fail on main (three BCPack oracle tests, the menu save race, the shader key test).

Checked for overlap

  • I searched the open pull requests for the same issue and for the files this touches. Related:
    #250 (merged) turns Reflex on only with frame generation; #1938 (open) keeps the card awake less while Reflex paces. Neither adds Reflex without frame generation. #18 (closed) asked for Reflex as a pull request of its own.

🤖 Generated with Claude Code

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:issue:5554486088 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072). Originally posted by [Adriwin06](https://github.com/Adriwin06) on 2026-11-29T19:52:57Z. --- ## What it changes Reflex low latency was set only while frame generation is on (#250). VICTORY_REFLEX=on (or boost, low latency with boost) turns it on with or without frame generation and paces the title's frames with Reflex's markers: - streamline/reflex.rs: the per-frame state (frame tokens matched across the input reading, the origin wait, the submissions and the present), Reflex's sleep with a watchdog, and 10 s telemetry lines; streamline/abi.rs: the Streamline 2.14 ReflexReport, ReflexReport2 and ReflexState layouts. - frame.rs, queue.rs and GameInput: frame_begins, title_submits (the first direct-queue submission of a frame, tagged by ExecuteCommandListsX's token), title_presents, and input_sampling (GetCurrentReading), where the sleep and SimulationStart happen when the title reads input every frame. - F1: NVIDIA REFLEX (LOW LATENCY): OFF / ON / ON + BOOST. Unset, nothing changes: no marker is sent and frame generation sets Reflex as before. Ported from Kemerd/VIctory-NVIDIA-RT@6463141 and Kemerd/VIctory-NVIDIA-RT@14f973b (Kemerd), GPL-3.0-or-later. Upstream asked for Reflex as a pull request of its own in #18. ## How it was tested - GPU and profile: RTX 4070 SUPER, Ryzen 7 5800X. Not measured in the title on these commits by themselves: they come from a fork of mine that carries them with the rest of this set, and the title ran there. What is below is the unit tests on this branch. - Before: n/a (no in-title measurement on this branch) - After: n/a - `cargo test` passed for the crates it touches: - this change: no: 112 passed, 1 failed: host::menu::tests::a_change_is_saved_at_once_however_the_game_was_started (`cargo test -p victory-gpu --lib -- streamline:: queue:: frame:: host::menu::`); the one failure is the menu tests' race on VICTORY_MENU_FILE, which fails on main too (fixed in #3061) - `cargo clippy --workspace --all-targets --locked`: no finding that main does not already have (main has 34 of its own, which is why the Clippy step of CI is red on main itself). - `cargo xtask policy`: no new finding (main fails it on crates/victory-loader/src/heap_sites/frame_users.rs). - With all eleven of my pull requests merged together: `cargo clippy` also with `--all-features` adds no finding, and `cargo test --workspace --locked` fails only tests main also fails on this machine: the five shader tests that fail on main here too (WARP's SM 6.2 and the validator) (barycentric_tests::first_half_values_render_on_hardware_and_warp, hw_tests::split_lds_wave32_read_after_read_barrier_coalescing_and_parity, intersect_tests::flat_global_stores_and_atomics_fence_uavs_at_group_barriers_across_waves, rect::tests::rectangles_are_drawn_whole, rect::tests::the_rectangle_stage_is_a_geometry_shader) and xtask's repository_passes_policy (frame_users.rs). 2208 passed, including five that fail on main (three BCPack oracle tests, the menu save race, the shader key test). ## Checked for overlap - [x] I searched the open pull requests for the same issue and for the files this touches. Related: #250 (merged) turns Reflex on only with frame generation; #1938 (open) keeps the card awake less while Reflex paces. Neither adds Reflex without frame generation. #18 (closed) asked for Reflex as a pull request of its own. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Copilot commented 2026-11-29 19:58:53 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Copilot on 2026-11-29T19:58:53Z.

Code review location: crates/victory-gpu/src/streamline/reflex.rs; line 629

@@ -0,0 +1,1386 @@
+//! Reflex by itself (`VICTORY_REFLEX`), the part that needs no library: the
+//! switch, which latency markers a frame has sent and which it owes at each
+//! point of its life, where the Reflex sleep goes, and what the reports of a
+//! Reflex state average to.
+//!
+//! A Reflex frame is one index, and the Reflex sleep and every marker of it
+//! are given a frame token made from that index, on whichever thread they
+//! happen. [`Frames`] is what the threads share: who holds it decides, so a
+//! frame's markers leave in order and once each.
+//!
+//! Where a frame's index comes from. The title begins its frames with a wait
+//! for the frame origin (`crate::frame`), whose token it hands to the
+//! frame's submissions and its present. The runs with the first version of
+//! this (the sleep and the simulation start at that wait) showed the title
+//! reading its pad once a frame and after the frame's first submission (in
+//! the world 101 of 108 frames, and none before it): what a
+//! frame submits right after its origin wait is a simulation made before
+//! it, and the reading that follows is the input of a later frame's
+//! simulation. Which thread reads, the one that waits for the origin or
+//! another, the runs did not show; the ten-second line counts it. Either
+//! way the sleep and the simulation start belong at that reading, and the
+//! reading opens the simulation ([`Frames::sample`]): it gets a new index,
+//! the sleep is made there, and the next origin wait takes the simulation
+//! for its frame ([`Frames::begin`]), so that its token's submission ends
+//! that simulation and its present shows it. This assumes
+//! the title is one frame deep (the simulation read after frame N's first
+//! submission is the one frame N + 1 submits); nothing seen from outside
+//! the title can tell one frame deep from two. A title frame with no
+//! simulation to take gets an index of its own: with no sleep while most of
+//! the last [`HOLD`] frames took one (the title reads input nearly every
+//! frame, and this frame's reading was missed), else with the sleep at the
+//! origin wait, as before (loads, cutscenes, menus that read now and then or
+//! never).
+
+use super::abi;
+
+/// `VICTORY_REFLEX`: Reflex by itself, with or without frame generation.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Reflex {
+    /// `on` or `1`: low latency.
+    On,
+    /// `boost`: low latency with boost.
+    Boost,
+}
+
+impl Reflex {
+    /// The switch's value: unset, empty, `0` and `off` are no Reflex by
+    /// itself (everything as without the switch); any other word is an
+    /// error, as an unknown DLSS mode is.
+    pub fn from_switch(value: Option<&str>) -> Result<Option<Self>, String> {
+        let Some(value) = value else { return Ok(None) };
+        Ok(match value.trim().to_ascii_lowercase().as_str() {
+            "" | "0" | "off" => None,
+            "1" | "on" => Some(Reflex::On),
+            "boost" => Some(Reflex::Boost),
+            _ => return Err(format!("VICTORY_REFLEX={value}: not one of on, 1, boost, off, 0")),
+        })
+    }
+
+    pub fn name(self) -> &'static str {
+        match self {
+            Reflex::On => "on",
+            Reflex::Boost => "boost",
+        }
+    }
+
+    /// The `sl::ReflexMode` of the switch.
+    pub fn sl_mode(self) -> u32 {
+        match self {
+            Reflex::On => abi::REFLEX_LOW_LATENCY,
+            Reflex::Boost => abi::REFLEX_LOW_LATENCY_WITH_BOOST,
+        }
+    }
+}
+
+/// The points of a frame's life that have a marker, in the order a frame
+/// passes them.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Stage {
+    /// The Reflex sleep before the frame's simulation returned (at the
+    /// reading that opened it, or at the origin wait), or the frame began
+    /// with no sleep.
+    SimulationStart = 0,
+    /// The title asked for the pad or keyboard reading that opened the
+    /// frame's simulation.
+    InputSample = 1,
+    /// The title's first submission of command lists: its simulation is over
+    /// and its submissions begin.
+    SimulationEnd = 2,
+    SubmitStart = 3,
+    /// The present begins on the host.
+    SubmitEnd = 4,
+    PresentStart = 5,
+    PresentEnd = 6,
+}
+
+/// The `sl::PCLMarker` of each stage.
+const ORDER: [u32; 7] = [
+    abi::SIMULATION_START,
+    abi::CONTROLLER_INPUT_SAMPLE,
+    abi::SIMULATION_END,
+    abi::RENDER_SUBMIT_START,
+    abi::RENDER_SUBMIT_END,
+    abi::PRESENT_START,
+    abi::PRESENT_END,
+];
+
+const fn bit(stage: Stage) -> u8 {
+    1 << stage as u8
+}
+
+/// Markers to send now, as bits by stage.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Markers(u8);
+
+impl Markers {
+    pub fn is_empty(self) -> bool {
+        self.0 == 0
+    }
+
+    /// Their `sl::PCLMarker` values, in the order they are to be sent.
+    pub fn iter(self) -> impl Iterator<Item = u32> {
+        ORDER.iter().enumerate().filter(move |(stage, _)| self.0 & (1 << stage) != 0).map(|(_, &marker)| marker)
+    }
+}
+
+/// One frame that is not over yet.
+struct Frame {
+    /// The index its frame tokens are made from.
+    index: u32,
+    /// The token the title's origin wait gave it (0: no origin wait has it
+    /// yet, or the frame was made at a present the title began none for).
+    origin: u64,
+    /// The number of the title's present that shows it (0: none yet).
+    present: u64,
+    /// The stages whose markers were sent.
+    sent: u8,
+    /// A title's origin wait has it: it began the frame, or took the
+    /// simulation a reading opened. False for a simulation not taken yet
+    /// and for a frame made at a present.
+    begun: bool,
+    /// The thread of that origin wait, or of the reading that opened the
+    /// frame while none has it (0: none).
+    thread: u32,
+    /// When (microseconds, the caller's clock) the origin wait had it, or
+    /// the reading opened it while none has it.
+    at: u64,
+    /// The title submitted to a queue that draws for it, and when.
+    submitted: bool,
+    submitted_at: u64,
+}
+
+impl Frame {
+    fn has(&self, stage: Stage) -> bool {
+        self.sent & bit(stage) != 0
+    }
+
+    /// The frame's simulation began (its sleep is over): from here on the
+    /// title's submissions and presents may end it.
+    fn started(&self) -> bool {
+        self.has(Stage::SimulationStart)
+    }
+
+    /// The markers of every stage up to `stage` that were not sent, now
+    /// counted as sent. The input sample is never owed: it is sent with the
+    /// simulation's start at the reading that opened the frame, or not at
+    /// all. What was sent is always a run from the first stage on, so
+    /// nothing ever leaves out of order.
+    fn reach(&mut self, stage: Stage) -> Markers {
+        let up_to = (bit(stage) << 1).wrapping_sub(1);
+        let owed = up_to & !bit(Stage::InputSample) & !self.sent;
+        self.sent |= owed;
+        Markers(owed)
+    }
+}
+
+/// Microseconds between two events of a frame, over the frames that had
+/// both since the counts were last taken.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Gap {
+    pub count: u32,
+    pub sum_us: u64,
+    pub longest_us: u64,
+}
+
+impl Gap {
+    const ZERO: Gap = Gap { count: 0, sum_us: 0, longest_us: 0 };
+
+    fn add(&mut self, us: u64) {
+        self.count = self.count.saturating_add(1);
+        self.sum_us = self.sum_us.saturating_add(us);
+        self.longest_us = self.longest_us.max(us);
+    }
+
+    pub fn average_us(&self) -> u64 {
+        self.sum_us / u64::from(self.count.max(1))
+    }
+}
+
+/// What happened since the counts were last taken (the ten-second line).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Counts {
+    /// Frames the title began (origin waits that made a token).
+    pub begun: u32,
+    /// Of them: frames that took the simulation a reading opened, frames
+    /// with no simulation to take and no sleep (most of the last [`HOLD`]
+    /// frames took one), and frames with no simulation to take that slept
+    /// at the origin wait (fewer did).
+    pub adopted: u32,
+    pub unpaced: u32,
+    pub origin_sleeps: u32,
+    /// Frames whose simulation start and input sample were sent where the
+    /// reading's sleep returned.
+    pub sampled: u32,
+    /// Readings that opened a simulation (with its sleep), that belonged to
+    /// the one open, that came before the newest begun frame's simulation
+    /// ended at a submission (the frame still simulates, or is in its sleep
+    /// at the origin wait), and that came on another thread than the one
+    /// that opens simulations.
+    pub opened: u32,
+    pub belongs: u32,
+    pub held_back: u32,
+    pub other_thread: u32,
+    /// Simulations let go because a reading came while one was open and
+    /// no origin wait had taken it for [`Frames::stale_after_us`] (a load).
+    pub stale: u32,
+    /// Simulations whose frame was over or past its simulation's end when
+    /// the reading's sleep returned: no input sample was sent for them.
+    pub lost: u32,
+    /// Frames whose first submission came before their simulation started
+    /// (the opening reading was still in its sleep): that submission was of
+    /// a simulation before, so the title is deeper than one frame there.
+    pub submitted_before_start: u32,
+    /// Where things happened, by thread: \[0\] on the thread of the origin
+    /// wait of the frame concerned, \[1\] on another. For an opening
+    /// reading the frame is the newest begun one; for the first submission
+    /// and the title's present, the frame they are of.
+    pub openings_by_thread: [u32; 2],
+    pub first_submits_by_thread: [u32; 2],
+    pub presents_by_thread: [u32; 2],
+    /// From a frame's origin wait to its first submission; from the newest
+    /// begun frame's first submission to the reading that opens the next
+    /// simulation; from the opening (after its sleep) to the origin wait
+    /// that takes it.
+    pub origin_to_submit: Gap,
+    pub submit_to_open: Gap,
+    pub open_to_adopt: Gap,
+    /// Frames presented without a submission of the title's before.
+    pub unsubmitted: u32,
+    /// Presents the title began no frame for (a second present of one
+    /// frame's token among them).
+    pub unbegun: u32,
+    /// Presents that found their frame by the title's token, and by order.
+    pub by_token: u32,
+    pub by_order: u32,
+    /// Frames whose simulation was ended by a submission that named them
+    /// with the title's token, and by one that did not (no token, or one no
+    /// frame here has): the newest running frame was taken then, which is
+    /// the wrong one if the title still submits a frame after it began the
+    /// next.
+    pub submitted_by_token: u32,
+    pub submitted_by_order: u32,
+    /// Frames begun and never presented.
+    pub never_presented: u32,
+}
+
+impl Counts {
+    const ZERO: Counts = Counts {
+        begun: 0,
+        adopted: 0,
+        unpaced: 0,
+        origin_sleeps: 0,
+        sampled: 0,
+        opened: 0,
+        belongs: 0,
+        held_back: 0,
+        other_thread: 0,
+        stale: 0,
+        lost: 0,
+        submitted_before_start: 0,
+        openings_by_thread: [0; 2],
+        first_submits_by_thread: [0; 2],
+        presents_by_thread: [0; 2],
+        origin_to_submit: Gap::ZERO,
+        submit_to_open: Gap::ZERO,
+        open_to_adopt: Gap::ZERO,
+        unsubmitted: 0,
+        unbegun: 0,
+        by_token: 0,
+        by_order: 0,
+        submitted_by_token: 0,
+        submitted_by_order: 0,
+        never_presented: 0,
+    };
+}
+
+/// Where a title frame's simulation starts ([`Frames::begin`]).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Begin {
+    /// The frame took the simulation a reading opened, with this index: its
+    /// sleep and its start were the reading's, nothing is sent here.
+    Adopted(u32),
+    /// A frame of its own with no sleep (most of the last [`HOLD`] frames
+    /// took a simulation, just not this one): its start now.
+    Unpaced(u32),
+    /// A frame of its own that sleeps here first (the title reads input on
+    /// fewer frames than that, or none): its start where the sleep returns.
+    Paced(u32),
+}
+
+/// What the title asking for a reading is ([`Frames::sample`]).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Sample {
+    /// It opens a simulation with this index: the sleep is made now, on the
+    /// reading's thread, and then [`Frames::sampled`] says its markers.
+    Open(u32),
+    /// A simulation is open and this reading is part of it.
+    Belongs,
+    /// The newest begun frame's simulation has not ended at a submission
+    /// yet: the reading is of that simulation, or the frame is in its sleep
+    /// at the origin wait.
+    HeldBack,
+    /// Another thread opens simulations.
+    OtherThread,
+}
+
+/// The frames that are not over, oldest first, the last index given, and
+/// the simulation a reading opened that no origin wait has taken yet.
+pub(crate) struct Frames {
+    last: u32,
+    live: Vec<Frame>,
+    /// The index of the open simulation: always newer than every frame an
+    /// origin wait has (the next origin wait takes it instead of making a
+    /// frame of its own), so indexes stay in the order the title presents
+    /// its frames.
+    open: Option<u32>,
+    /// The thread that opened the last simulation (0: none yet).
+    sampler: u32,
+    /// Origin waits since the last simulation was opened (saturating; it
+    /// starts above [`HOLD`], so any thread may open the first one).
+    since_opened: u32,
+    /// Which of the last [`HOLD`] title frames took a simulation a reading
+    /// opened, one bit each, the newest lowest (none at first, so the first
+    /// frames sleep at the origin wait).
+    adopted_recently: u32,
+    /// When the last origin wait came, and how long before it the one
+    /// before came (microseconds, the caller's clock; 0 until two came).
+    begun_at: Option<u64>,
+    interval_us: u64,
+    /// The title's present that was a second present of one frame's token,
+    /// and that frame's index: the host's present of it shows that frame
+    /// again ([`Frames::presenting`]).
+    repeat: Option<(u64, u32)>,
+    counts: Counts,
+}
+
+/// Frames kept at most (Streamline expects no more than three in flight; the
+/// rest is room for frames the title begins and never presents).
+const KEPT: usize = 8;
+
+/// The title frames looked back on. A frame with no simulation to take goes
+/// without a sleep only when more than half of the last `HOLD` frames took
+/// one: the title reads input nearly every frame and missed this one (in
+/// the world about one frame in fifteen had no reading counted), and a
+/// sleep at the origin wait would hold back a finished frame again. Where
+/// the title reads input on fewer frames (a menu that reads every tenth),
+/// its other frames sleep at the origin wait as they did before readings
+/// were looked at: Reflex's guide has `slReflexSleep` called always, and
+/// whether its pacing or frame generation's bears frames with no sleep the
+/// guides on disk do not say. Also the frames after which another thread
+/// may open simulations. Eight frames is a third of a second to two seconds
+/// in the world (4 to 28 frames a second there) and a few milliseconds in
+/// the menus.
+pub(crate) const HOLD: u32 = 8;
+const _: () = assert!(HOLD > 0 && HOLD <= u32::BITS);
+
+/// An open simulation is let go when a reading comes and no origin wait has
+/// taken it for this many microseconds or for [`STALE_FRAMES`] times the
+/// last interval between origin waits, whichever is longer: the title read
+/// input and began no frame (a load), and the reading opens a new one. A
+/// fixed bound alone let every simulation go in the world's slow stretches,
+/// where the origin wait that takes a simulation comes 80 to 370 ms after
+/// the reading that opened it.
+pub(crate) const STALE_US: u64 = 250_000;
+pub(crate) const STALE_FRAMES: u64 = 4;
+
+impl Frames {
+    pub const fn new() -> Self {
+        Frames {
+            last: 0,
+            live: Vec::new(),
+            open: None,
+            sampler: 0,
+            since_opened: u32::MAX,
+            adopted_recently: 0,
+            begun_at: None,
+            interval_us: 0,
+            repeat: None,
+            counts: Counts::ZERO,
+        }
+    }
+
+    /// How long an open simulation may wait for its origin wait while
+    /// readings come, in microseconds ([`STALE_US`]).
+    pub fn stale_after_us(&self) -> u64 {
+        STALE_US.max(self.interval_us.saturating_mul(STALE_FRAMES))
+    }
+
+    /// A new frame with the next index (indexes count from 1 and wrap).
+    fn push(&mut self, origin: u64, present: u64, begun: bool, thread: u32, at: u64) -> u32 {
+        // The oldest goes if the title begins frames it never presents.
+        // (Never the open simulation: it is the newest, and KEPT is above 1.)
+        if self.live.len() >= KEPT {
+            self.live.remove(0);
+            self.counts.never_presented += 1;
+        }
+        self.last = self.last.wrapping_add(1);
+        self.live.push(Frame {
+            index: self.last,
+            origin,
+            present,
+            sent: 0,
+            begun,
+            thread,
+            at,
+            submitted: false,
+            submitted_at: 0,
+        });
+        self.last
+    }
+
+    /// The open simulation is let go if no origin wait took it within
+    /// [`Frames::stale_after_us`] (`now` is the caller's clock, as at the
+    /// opening). Only a reading asks this: the origin wait that comes always
+    /// takes the open simulation, however long after, since that is the
+    /// frame that submits it.
+    fn let_go_stale(&mut self, now: u64) {
+        let Some(index) = self.open else { return };
+        let Some(at) = self.live.iter().position(|f| f.index == index) else {
+            self.open = None;
+            return;
+        };
+        if now.saturating_sub(self.live[at].at) > self.stale_after_us() {
+            self.live.remove(at);
+            self.open = None;
+            self.counts.stale += 1;
+        }
+    }
+
+    /// The title begins a frame on `thread` at `now`: its origin wait made
+    /// token `origin`. The frame takes the open simulation if there is one,
+    /// else it gets an index of its own, with or without a sleep here.
+    pub fn begin(&mut self, origin: u64, thread: u32, now: u64) -> Begin {
+        self.counts.begun += 1;
+        // The interval between origin waits, for how long an open
+        // simulation may wait for one while readings come.
+        if let Some(before) = self.begun_at {
+            self.interval_us = now.saturating_sub(before);
+        }
+        self.begun_at = Some(now);
+        self.since_opened = self.since_opened.saturating_add(1);
+        // The frames before this one that took a simulation; this one's bit
+        // is set below if it takes one.
+        let window = u32::MAX >> (u32::BITS - HOLD);
+        let took_before = (self.adopted_recently & window).count_ones();
+        self.adopted_recently = (self.adopted_recently << 1) & window;
+        // No time bound here: the simulation open now is the one this frame
+        // submits, whether the frame came 3 ms or 370 ms after its reading.
+        if let Some(index) = self.open.take()
+            && let Some(frame) = self.live.iter_mut().find(|f| f.index == index)
+        {
+            self.counts.open_to_adopt.add(now.saturating_sub(frame.at));
+            frame.origin = origin;
+            frame.begun = true;
+            frame.thread = thread;
+            frame.at = now;
+            self.counts.adopted += 1;
+            self.adopted_recently |= 1;
+            return Begin::Adopted(index);
+        }
+        let index = self.push(origin, 0, true, thread, now);
+        if took_before > HOLD / 2 {
+            self.counts.unpaced += 1;
+            Begin::Unpaced(index)
+        } else {
+            self.counts.origin_sleeps += 1;
+            Begin::Paced(index)
+        }
+    }
+
+    /// The markers frame `index` owes up to `stage`, now sent; none if the
+    /// frame is over.
+    pub fn reach(&mut self, index: u32, stage: Stage) -> Markers {
+        self.live.iter_mut().find(|f| f.index == index).map_or(Markers(0), |f| f.reach(stage))
+    }
+
+    /// The title asks for a pad or keyboard reading on `thread` at `now`,
+    /// before the reading is picked. It opens a simulation only when none
+    /// is open, the newest begun frame's simulation has ended at its
+    /// submission (or it has its present, or there is no begun frame), and
+    /// the thread is the one that opens them (or
+    /// that one has not for more than [`HOLD`] frames). So at most one
+    /// simulation opens between two origin waits, one sleep is made for
+    /// it, and it never runs while a sleep at the origin wait does (that
+    /// frame has not submitted yet). A simulation that waited too long for
+    /// its origin wait ([`Frames::stale_after_us`]) is let go first, and the
+    /// reading opens another.
+    pub fn sample(&mut self, thread: u32, now: u64) -> Sample {
+        self.let_go_stale(now);
+        if self.sampler != 0 && self.sampler != thread && self.since_opened <= HOLD {
+            self.counts.other_thread += 1;
+            return Sample::OtherThread;
+        }
+        if self.open.is_some() {
+            self.counts.belongs += 1;
+            return Sample::Belongs;
+        }
+        let newest = self.live.iter().rev().find(|f| f.begun);
+        if let Some(frame) = newest {
+            // (Its simulation's end, not its first submission: a submission
+            // that came while the opening reading still slept ended nothing,
+            // and the readings of that simulation must not open another.)
+            if !frame.has(Stage::SimulationEnd) && frame.present == 0 {
+                self.counts.held_back += 1;
+                return Sample::HeldBack;
+            }
+            // Which thread reads, against the one that begins frames; and
+            // how long after that frame's first submission.
+            self.counts.openings_by_thread[usize::from(frame.thread != thread)] += 1;
+            if frame.submitted {
+                self.counts.submit_to_open.add(now.saturating_sub(frame.submitted_at));
+            }
+        }
+        let index = self.push(0, 0, false, thread, now);
+        self.open = Some(index);
+        self.sampler = thread;
+        self.since_opened = 0;
+        self.counts.opened += 1;
+        Sample::Open(index)
+    }
+
+    /// The sleep of the simulation `index` opened returned at `now`: its
+    /// simulation start and its input sample, now sent; none if the frame
+    /// is over or its present already sent its simulation's markers (the
+    /// sample is lost then, and counted).
+    pub fn sampled(&mut self, index: u32, now: u64) -> Markers {
+        let Some(frame) = self.live.iter_mut().find(|f| f.index == index) else {
+            self.counts.lost += 1;
+            return Markers(0);
+        };
+        if frame.started() {
+            self.counts.lost += 1;
+            return Markers(0);
+        }
+        // While no origin wait has it, the opening counts from here (the
+        // gap to the adoption is measured after the sleep).
+        if !frame.begun {
+            frame.at = frame.at.max(now);
+        }
+        let owed = bit(Stage::SimulationStart) | bit(Stage::InputSample);
+        frame.sent |= owed;
+        self.counts.sampled += 1;
+        Markers(owed)
+    }
+
+    /// The title submits command lists to a queue that draws, on `thread`
+    /// at `now`, tagged with frame token `origin` (0: not tagged): at the
+    /// frame's first submission its simulation ends and its submissions
+    /// begin. The frame is the one of that token, else the newest begun
+    /// frame whose simulation runs and whose present the title has not
+    /// called (never a simulation no origin wait has taken). Which of the
+    /// two ended a frame's simulation is counted, for the line.
+    pub fn submit(&mut self, origin: u64, thread: u32, now: u64) -> Option<(u32, Markers)> {
+        let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten();
+        let at = match tagged {
+            Some(at) => at,
+            None => self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0)?,
+        };
+        let frame = &mut self.live[at];
+        let first = !frame.submitted;
+        if first {
+            frame.submitted = true;
+            frame.submitted_at = now;
+            self.counts.first_submits_by_thread[usize::from(frame.thread != thread)] += 1;
+            self.counts.origin_to_submit.add(now.saturating_sub(frame.at));
+        }
+        // A frame still in its sleep has no simulation to end. (At the
+        // origin wait that cannot be: the title has not got the token yet.
+        // At a reading it means this submission is of a simulation before.)
+        if !frame.started() {
+            if first {
+                self.counts.submitted_before_start += 1;
+            }
+            return None;
+        }
+        let owed = frame.reach(Stage::SubmitStart);
+        // Later submissions of the frame owe nothing and count nothing.
+        if owed.is_empty() {
+            return None;
+        }
+        // Counted where it has an effect: this submission is the one that
+        // ends the frame's simulation.
+        match tagged {
+            Some(_) => self.counts.submitted_by_token += 1,
+            None => self.counts.submitted_by_order += 1,
+        }
+        Some((frame.index, owed))
+    }
+
+    /// The title calls its present number `present` (counted from 1) on
+    /// `thread` with frame token `origin` in its first plane (0: none): the
+    /// present is that frame's, else the newest begun frame's whose
+    /// simulation runs and that has no present yet. Frames begun before it
+    /// that have none are over: the title never presented them. (By the
+    /// token the frame need not have started: a simulation whose reading is
+    /// still in its sleep may be presented, and then sends what it owes at
+    /// the present.)
+    pub fn title_presents(&mut self, present: u64, origin: u64, thread: u32) {
+        let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten();
+        let at = match tagged {
+            Some(at) if self.live[at].present == 0 => {
+                self.counts.by_token += 1;
+                at
+            }
+            // The token's frame has its present: this one shows that frame
+            // again, and the host's present of it names that frame's index
+            // ([`Frames::presenting`]).
+            Some(at) => {
+                self.repeat = Some((present, self.live[at].index));

This single slot overwrites an unconsumed repeat: with simulation 2 open, three queued presents of the same origin produce host indexes [1, 2, 1] instead of [1, 1, 1]. The middle present consumes the next simulation, and the last moves frame-generation constants and markers backwards. Keep a pending present-to-index mapping for every repeat, consume only the matching entry in presenting, and test multiple queued repeats.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:review-comment:4732931845 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072#discussion_r4732931845). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-29T19:58:53Z. **Code review location:** `crates/victory-gpu/src/streamline/reflex.rs`; line 629 ~~~~diff @@ -0,0 +1,1386 @@ +//! Reflex by itself (`VICTORY_REFLEX`), the part that needs no library: the +//! switch, which latency markers a frame has sent and which it owes at each +//! point of its life, where the Reflex sleep goes, and what the reports of a +//! Reflex state average to. +//! +//! A Reflex frame is one index, and the Reflex sleep and every marker of it +//! are given a frame token made from that index, on whichever thread they +//! happen. [`Frames`] is what the threads share: who holds it decides, so a +//! frame's markers leave in order and once each. +//! +//! Where a frame's index comes from. The title begins its frames with a wait +//! for the frame origin (`crate::frame`), whose token it hands to the +//! frame's submissions and its present. The runs with the first version of +//! this (the sleep and the simulation start at that wait) showed the title +//! reading its pad once a frame and after the frame's first submission (in +//! the world 101 of 108 frames, and none before it): what a +//! frame submits right after its origin wait is a simulation made before +//! it, and the reading that follows is the input of a later frame's +//! simulation. Which thread reads, the one that waits for the origin or +//! another, the runs did not show; the ten-second line counts it. Either +//! way the sleep and the simulation start belong at that reading, and the +//! reading opens the simulation ([`Frames::sample`]): it gets a new index, +//! the sleep is made there, and the next origin wait takes the simulation +//! for its frame ([`Frames::begin`]), so that its token's submission ends +//! that simulation and its present shows it. This assumes +//! the title is one frame deep (the simulation read after frame N's first +//! submission is the one frame N + 1 submits); nothing seen from outside +//! the title can tell one frame deep from two. A title frame with no +//! simulation to take gets an index of its own: with no sleep while most of +//! the last [`HOLD`] frames took one (the title reads input nearly every +//! frame, and this frame's reading was missed), else with the sleep at the +//! origin wait, as before (loads, cutscenes, menus that read now and then or +//! never). + +use super::abi; + +/// `VICTORY_REFLEX`: Reflex by itself, with or without frame generation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reflex { + /// `on` or `1`: low latency. + On, + /// `boost`: low latency with boost. + Boost, +} + +impl Reflex { + /// The switch's value: unset, empty, `0` and `off` are no Reflex by + /// itself (everything as without the switch); any other word is an + /// error, as an unknown DLSS mode is. + pub fn from_switch(value: Option<&str>) -> Result<Option<Self>, String> { + let Some(value) = value else { return Ok(None) }; + Ok(match value.trim().to_ascii_lowercase().as_str() { + "" | "0" | "off" => None, + "1" | "on" => Some(Reflex::On), + "boost" => Some(Reflex::Boost), + _ => return Err(format!("VICTORY_REFLEX={value}: not one of on, 1, boost, off, 0")), + }) + } + + pub fn name(self) -> &'static str { + match self { + Reflex::On => "on", + Reflex::Boost => "boost", + } + } + + /// The `sl::ReflexMode` of the switch. + pub fn sl_mode(self) -> u32 { + match self { + Reflex::On => abi::REFLEX_LOW_LATENCY, + Reflex::Boost => abi::REFLEX_LOW_LATENCY_WITH_BOOST, + } + } +} + +/// The points of a frame's life that have a marker, in the order a frame +/// passes them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Stage { + /// The Reflex sleep before the frame's simulation returned (at the + /// reading that opened it, or at the origin wait), or the frame began + /// with no sleep. + SimulationStart = 0, + /// The title asked for the pad or keyboard reading that opened the + /// frame's simulation. + InputSample = 1, + /// The title's first submission of command lists: its simulation is over + /// and its submissions begin. + SimulationEnd = 2, + SubmitStart = 3, + /// The present begins on the host. + SubmitEnd = 4, + PresentStart = 5, + PresentEnd = 6, +} + +/// The `sl::PCLMarker` of each stage. +const ORDER: [u32; 7] = [ + abi::SIMULATION_START, + abi::CONTROLLER_INPUT_SAMPLE, + abi::SIMULATION_END, + abi::RENDER_SUBMIT_START, + abi::RENDER_SUBMIT_END, + abi::PRESENT_START, + abi::PRESENT_END, +]; + +const fn bit(stage: Stage) -> u8 { + 1 << stage as u8 +} + +/// Markers to send now, as bits by stage. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Markers(u8); + +impl Markers { + pub fn is_empty(self) -> bool { + self.0 == 0 + } + + /// Their `sl::PCLMarker` values, in the order they are to be sent. + pub fn iter(self) -> impl Iterator<Item = u32> { + ORDER.iter().enumerate().filter(move |(stage, _)| self.0 & (1 << stage) != 0).map(|(_, &marker)| marker) + } +} + +/// One frame that is not over yet. +struct Frame { + /// The index its frame tokens are made from. + index: u32, + /// The token the title's origin wait gave it (0: no origin wait has it + /// yet, or the frame was made at a present the title began none for). + origin: u64, + /// The number of the title's present that shows it (0: none yet). + present: u64, + /// The stages whose markers were sent. + sent: u8, + /// A title's origin wait has it: it began the frame, or took the + /// simulation a reading opened. False for a simulation not taken yet + /// and for a frame made at a present. + begun: bool, + /// The thread of that origin wait, or of the reading that opened the + /// frame while none has it (0: none). + thread: u32, + /// When (microseconds, the caller's clock) the origin wait had it, or + /// the reading opened it while none has it. + at: u64, + /// The title submitted to a queue that draws for it, and when. + submitted: bool, + submitted_at: u64, +} + +impl Frame { + fn has(&self, stage: Stage) -> bool { + self.sent & bit(stage) != 0 + } + + /// The frame's simulation began (its sleep is over): from here on the + /// title's submissions and presents may end it. + fn started(&self) -> bool { + self.has(Stage::SimulationStart) + } + + /// The markers of every stage up to `stage` that were not sent, now + /// counted as sent. The input sample is never owed: it is sent with the + /// simulation's start at the reading that opened the frame, or not at + /// all. What was sent is always a run from the first stage on, so + /// nothing ever leaves out of order. + fn reach(&mut self, stage: Stage) -> Markers { + let up_to = (bit(stage) << 1).wrapping_sub(1); + let owed = up_to & !bit(Stage::InputSample) & !self.sent; + self.sent |= owed; + Markers(owed) + } +} + +/// Microseconds between two events of a frame, over the frames that had +/// both since the counts were last taken. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Gap { + pub count: u32, + pub sum_us: u64, + pub longest_us: u64, +} + +impl Gap { + const ZERO: Gap = Gap { count: 0, sum_us: 0, longest_us: 0 }; + + fn add(&mut self, us: u64) { + self.count = self.count.saturating_add(1); + self.sum_us = self.sum_us.saturating_add(us); + self.longest_us = self.longest_us.max(us); + } + + pub fn average_us(&self) -> u64 { + self.sum_us / u64::from(self.count.max(1)) + } +} + +/// What happened since the counts were last taken (the ten-second line). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Counts { + /// Frames the title began (origin waits that made a token). + pub begun: u32, + /// Of them: frames that took the simulation a reading opened, frames + /// with no simulation to take and no sleep (most of the last [`HOLD`] + /// frames took one), and frames with no simulation to take that slept + /// at the origin wait (fewer did). + pub adopted: u32, + pub unpaced: u32, + pub origin_sleeps: u32, + /// Frames whose simulation start and input sample were sent where the + /// reading's sleep returned. + pub sampled: u32, + /// Readings that opened a simulation (with its sleep), that belonged to + /// the one open, that came before the newest begun frame's simulation + /// ended at a submission (the frame still simulates, or is in its sleep + /// at the origin wait), and that came on another thread than the one + /// that opens simulations. + pub opened: u32, + pub belongs: u32, + pub held_back: u32, + pub other_thread: u32, + /// Simulations let go because a reading came while one was open and + /// no origin wait had taken it for [`Frames::stale_after_us`] (a load). + pub stale: u32, + /// Simulations whose frame was over or past its simulation's end when + /// the reading's sleep returned: no input sample was sent for them. + pub lost: u32, + /// Frames whose first submission came before their simulation started + /// (the opening reading was still in its sleep): that submission was of + /// a simulation before, so the title is deeper than one frame there. + pub submitted_before_start: u32, + /// Where things happened, by thread: \[0\] on the thread of the origin + /// wait of the frame concerned, \[1\] on another. For an opening + /// reading the frame is the newest begun one; for the first submission + /// and the title's present, the frame they are of. + pub openings_by_thread: [u32; 2], + pub first_submits_by_thread: [u32; 2], + pub presents_by_thread: [u32; 2], + /// From a frame's origin wait to its first submission; from the newest + /// begun frame's first submission to the reading that opens the next + /// simulation; from the opening (after its sleep) to the origin wait + /// that takes it. + pub origin_to_submit: Gap, + pub submit_to_open: Gap, + pub open_to_adopt: Gap, + /// Frames presented without a submission of the title's before. + pub unsubmitted: u32, + /// Presents the title began no frame for (a second present of one + /// frame's token among them). + pub unbegun: u32, + /// Presents that found their frame by the title's token, and by order. + pub by_token: u32, + pub by_order: u32, + /// Frames whose simulation was ended by a submission that named them + /// with the title's token, and by one that did not (no token, or one no + /// frame here has): the newest running frame was taken then, which is + /// the wrong one if the title still submits a frame after it began the + /// next. + pub submitted_by_token: u32, + pub submitted_by_order: u32, + /// Frames begun and never presented. + pub never_presented: u32, +} + +impl Counts { + const ZERO: Counts = Counts { + begun: 0, + adopted: 0, + unpaced: 0, + origin_sleeps: 0, + sampled: 0, + opened: 0, + belongs: 0, + held_back: 0, + other_thread: 0, + stale: 0, + lost: 0, + submitted_before_start: 0, + openings_by_thread: [0; 2], + first_submits_by_thread: [0; 2], + presents_by_thread: [0; 2], + origin_to_submit: Gap::ZERO, + submit_to_open: Gap::ZERO, + open_to_adopt: Gap::ZERO, + unsubmitted: 0, + unbegun: 0, + by_token: 0, + by_order: 0, + submitted_by_token: 0, + submitted_by_order: 0, + never_presented: 0, + }; +} + +/// Where a title frame's simulation starts ([`Frames::begin`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Begin { + /// The frame took the simulation a reading opened, with this index: its + /// sleep and its start were the reading's, nothing is sent here. + Adopted(u32), + /// A frame of its own with no sleep (most of the last [`HOLD`] frames + /// took a simulation, just not this one): its start now. + Unpaced(u32), + /// A frame of its own that sleeps here first (the title reads input on + /// fewer frames than that, or none): its start where the sleep returns. + Paced(u32), +} + +/// What the title asking for a reading is ([`Frames::sample`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Sample { + /// It opens a simulation with this index: the sleep is made now, on the + /// reading's thread, and then [`Frames::sampled`] says its markers. + Open(u32), + /// A simulation is open and this reading is part of it. + Belongs, + /// The newest begun frame's simulation has not ended at a submission + /// yet: the reading is of that simulation, or the frame is in its sleep + /// at the origin wait. + HeldBack, + /// Another thread opens simulations. + OtherThread, +} + +/// The frames that are not over, oldest first, the last index given, and +/// the simulation a reading opened that no origin wait has taken yet. +pub(crate) struct Frames { + last: u32, + live: Vec<Frame>, + /// The index of the open simulation: always newer than every frame an + /// origin wait has (the next origin wait takes it instead of making a + /// frame of its own), so indexes stay in the order the title presents + /// its frames. + open: Option<u32>, + /// The thread that opened the last simulation (0: none yet). + sampler: u32, + /// Origin waits since the last simulation was opened (saturating; it + /// starts above [`HOLD`], so any thread may open the first one). + since_opened: u32, + /// Which of the last [`HOLD`] title frames took a simulation a reading + /// opened, one bit each, the newest lowest (none at first, so the first + /// frames sleep at the origin wait). + adopted_recently: u32, + /// When the last origin wait came, and how long before it the one + /// before came (microseconds, the caller's clock; 0 until two came). + begun_at: Option<u64>, + interval_us: u64, + /// The title's present that was a second present of one frame's token, + /// and that frame's index: the host's present of it shows that frame + /// again ([`Frames::presenting`]). + repeat: Option<(u64, u32)>, + counts: Counts, +} + +/// Frames kept at most (Streamline expects no more than three in flight; the +/// rest is room for frames the title begins and never presents). +const KEPT: usize = 8; + +/// The title frames looked back on. A frame with no simulation to take goes +/// without a sleep only when more than half of the last `HOLD` frames took +/// one: the title reads input nearly every frame and missed this one (in +/// the world about one frame in fifteen had no reading counted), and a +/// sleep at the origin wait would hold back a finished frame again. Where +/// the title reads input on fewer frames (a menu that reads every tenth), +/// its other frames sleep at the origin wait as they did before readings +/// were looked at: Reflex's guide has `slReflexSleep` called always, and +/// whether its pacing or frame generation's bears frames with no sleep the +/// guides on disk do not say. Also the frames after which another thread +/// may open simulations. Eight frames is a third of a second to two seconds +/// in the world (4 to 28 frames a second there) and a few milliseconds in +/// the menus. +pub(crate) const HOLD: u32 = 8; +const _: () = assert!(HOLD > 0 && HOLD <= u32::BITS); + +/// An open simulation is let go when a reading comes and no origin wait has +/// taken it for this many microseconds or for [`STALE_FRAMES`] times the +/// last interval between origin waits, whichever is longer: the title read +/// input and began no frame (a load), and the reading opens a new one. A +/// fixed bound alone let every simulation go in the world's slow stretches, +/// where the origin wait that takes a simulation comes 80 to 370 ms after +/// the reading that opened it. +pub(crate) const STALE_US: u64 = 250_000; +pub(crate) const STALE_FRAMES: u64 = 4; + +impl Frames { + pub const fn new() -> Self { + Frames { + last: 0, + live: Vec::new(), + open: None, + sampler: 0, + since_opened: u32::MAX, + adopted_recently: 0, + begun_at: None, + interval_us: 0, + repeat: None, + counts: Counts::ZERO, + } + } + + /// How long an open simulation may wait for its origin wait while + /// readings come, in microseconds ([`STALE_US`]). + pub fn stale_after_us(&self) -> u64 { + STALE_US.max(self.interval_us.saturating_mul(STALE_FRAMES)) + } + + /// A new frame with the next index (indexes count from 1 and wrap). + fn push(&mut self, origin: u64, present: u64, begun: bool, thread: u32, at: u64) -> u32 { + // The oldest goes if the title begins frames it never presents. + // (Never the open simulation: it is the newest, and KEPT is above 1.) + if self.live.len() >= KEPT { + self.live.remove(0); + self.counts.never_presented += 1; + } + self.last = self.last.wrapping_add(1); + self.live.push(Frame { + index: self.last, + origin, + present, + sent: 0, + begun, + thread, + at, + submitted: false, + submitted_at: 0, + }); + self.last + } + + /// The open simulation is let go if no origin wait took it within + /// [`Frames::stale_after_us`] (`now` is the caller's clock, as at the + /// opening). Only a reading asks this: the origin wait that comes always + /// takes the open simulation, however long after, since that is the + /// frame that submits it. + fn let_go_stale(&mut self, now: u64) { + let Some(index) = self.open else { return }; + let Some(at) = self.live.iter().position(|f| f.index == index) else { + self.open = None; + return; + }; + if now.saturating_sub(self.live[at].at) > self.stale_after_us() { + self.live.remove(at); + self.open = None; + self.counts.stale += 1; + } + } + + /// The title begins a frame on `thread` at `now`: its origin wait made + /// token `origin`. The frame takes the open simulation if there is one, + /// else it gets an index of its own, with or without a sleep here. + pub fn begin(&mut self, origin: u64, thread: u32, now: u64) -> Begin { + self.counts.begun += 1; + // The interval between origin waits, for how long an open + // simulation may wait for one while readings come. + if let Some(before) = self.begun_at { + self.interval_us = now.saturating_sub(before); + } + self.begun_at = Some(now); + self.since_opened = self.since_opened.saturating_add(1); + // The frames before this one that took a simulation; this one's bit + // is set below if it takes one. + let window = u32::MAX >> (u32::BITS - HOLD); + let took_before = (self.adopted_recently & window).count_ones(); + self.adopted_recently = (self.adopted_recently << 1) & window; + // No time bound here: the simulation open now is the one this frame + // submits, whether the frame came 3 ms or 370 ms after its reading. + if let Some(index) = self.open.take() + && let Some(frame) = self.live.iter_mut().find(|f| f.index == index) + { + self.counts.open_to_adopt.add(now.saturating_sub(frame.at)); + frame.origin = origin; + frame.begun = true; + frame.thread = thread; + frame.at = now; + self.counts.adopted += 1; + self.adopted_recently |= 1; + return Begin::Adopted(index); + } + let index = self.push(origin, 0, true, thread, now); + if took_before > HOLD / 2 { + self.counts.unpaced += 1; + Begin::Unpaced(index) + } else { + self.counts.origin_sleeps += 1; + Begin::Paced(index) + } + } + + /// The markers frame `index` owes up to `stage`, now sent; none if the + /// frame is over. + pub fn reach(&mut self, index: u32, stage: Stage) -> Markers { + self.live.iter_mut().find(|f| f.index == index).map_or(Markers(0), |f| f.reach(stage)) + } + + /// The title asks for a pad or keyboard reading on `thread` at `now`, + /// before the reading is picked. It opens a simulation only when none + /// is open, the newest begun frame's simulation has ended at its + /// submission (or it has its present, or there is no begun frame), and + /// the thread is the one that opens them (or + /// that one has not for more than [`HOLD`] frames). So at most one + /// simulation opens between two origin waits, one sleep is made for + /// it, and it never runs while a sleep at the origin wait does (that + /// frame has not submitted yet). A simulation that waited too long for + /// its origin wait ([`Frames::stale_after_us`]) is let go first, and the + /// reading opens another. + pub fn sample(&mut self, thread: u32, now: u64) -> Sample { + self.let_go_stale(now); + if self.sampler != 0 && self.sampler != thread && self.since_opened <= HOLD { + self.counts.other_thread += 1; + return Sample::OtherThread; + } + if self.open.is_some() { + self.counts.belongs += 1; + return Sample::Belongs; + } + let newest = self.live.iter().rev().find(|f| f.begun); + if let Some(frame) = newest { + // (Its simulation's end, not its first submission: a submission + // that came while the opening reading still slept ended nothing, + // and the readings of that simulation must not open another.) + if !frame.has(Stage::SimulationEnd) && frame.present == 0 { + self.counts.held_back += 1; + return Sample::HeldBack; + } + // Which thread reads, against the one that begins frames; and + // how long after that frame's first submission. + self.counts.openings_by_thread[usize::from(frame.thread != thread)] += 1; + if frame.submitted { + self.counts.submit_to_open.add(now.saturating_sub(frame.submitted_at)); + } + } + let index = self.push(0, 0, false, thread, now); + self.open = Some(index); + self.sampler = thread; + self.since_opened = 0; + self.counts.opened += 1; + Sample::Open(index) + } + + /// The sleep of the simulation `index` opened returned at `now`: its + /// simulation start and its input sample, now sent; none if the frame + /// is over or its present already sent its simulation's markers (the + /// sample is lost then, and counted). + pub fn sampled(&mut self, index: u32, now: u64) -> Markers { + let Some(frame) = self.live.iter_mut().find(|f| f.index == index) else { + self.counts.lost += 1; + return Markers(0); + }; + if frame.started() { + self.counts.lost += 1; + return Markers(0); + } + // While no origin wait has it, the opening counts from here (the + // gap to the adoption is measured after the sleep). + if !frame.begun { + frame.at = frame.at.max(now); + } + let owed = bit(Stage::SimulationStart) | bit(Stage::InputSample); + frame.sent |= owed; + self.counts.sampled += 1; + Markers(owed) + } + + /// The title submits command lists to a queue that draws, on `thread` + /// at `now`, tagged with frame token `origin` (0: not tagged): at the + /// frame's first submission its simulation ends and its submissions + /// begin. The frame is the one of that token, else the newest begun + /// frame whose simulation runs and whose present the title has not + /// called (never a simulation no origin wait has taken). Which of the + /// two ended a frame's simulation is counted, for the line. + pub fn submit(&mut self, origin: u64, thread: u32, now: u64) -> Option<(u32, Markers)> { + let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten(); + let at = match tagged { + Some(at) => at, + None => self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0)?, + }; + let frame = &mut self.live[at]; + let first = !frame.submitted; + if first { + frame.submitted = true; + frame.submitted_at = now; + self.counts.first_submits_by_thread[usize::from(frame.thread != thread)] += 1; + self.counts.origin_to_submit.add(now.saturating_sub(frame.at)); + } + // A frame still in its sleep has no simulation to end. (At the + // origin wait that cannot be: the title has not got the token yet. + // At a reading it means this submission is of a simulation before.) + if !frame.started() { + if first { + self.counts.submitted_before_start += 1; + } + return None; + } + let owed = frame.reach(Stage::SubmitStart); + // Later submissions of the frame owe nothing and count nothing. + if owed.is_empty() { + return None; + } + // Counted where it has an effect: this submission is the one that + // ends the frame's simulation. + match tagged { + Some(_) => self.counts.submitted_by_token += 1, + None => self.counts.submitted_by_order += 1, + } + Some((frame.index, owed)) + } + + /// The title calls its present number `present` (counted from 1) on + /// `thread` with frame token `origin` in its first plane (0: none): the + /// present is that frame's, else the newest begun frame's whose + /// simulation runs and that has no present yet. Frames begun before it + /// that have none are over: the title never presented them. (By the + /// token the frame need not have started: a simulation whose reading is + /// still in its sleep may be presented, and then sends what it owes at + /// the present.) + pub fn title_presents(&mut self, present: u64, origin: u64, thread: u32) { + let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten(); + let at = match tagged { + Some(at) if self.live[at].present == 0 => { + self.counts.by_token += 1; + at + } + // The token's frame has its present: this one shows that frame + // again, and the host's present of it names that frame's index + // ([`Frames::presenting`]). + Some(at) => { + self.repeat = Some((present, self.live[at].index)); ~~~~ --- This single slot overwrites an unconsumed repeat: with simulation 2 open, three queued presents of the same origin produce host indexes [1, 2, 1] instead of [1, 1, 1]. The middle present consumes the next simulation, and the last moves frame-generation constants and markers backwards. Keep a pending present-to-index mapping for every repeat, consume only the matching entry in `presenting`, and test multiple queued repeats.
Copilot commented 2026-11-29 19:58:54 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Copilot on 2026-11-29T19:58:54Z.

Code review location: crates/victory-gpu/src/streamline/reflex.rs; line 698

@@ -0,0 +1,1386 @@
+//! Reflex by itself (`VICTORY_REFLEX`), the part that needs no library: the
+//! switch, which latency markers a frame has sent and which it owes at each
+//! point of its life, where the Reflex sleep goes, and what the reports of a
+//! Reflex state average to.
+//!
+//! A Reflex frame is one index, and the Reflex sleep and every marker of it
+//! are given a frame token made from that index, on whichever thread they
+//! happen. [`Frames`] is what the threads share: who holds it decides, so a
+//! frame's markers leave in order and once each.
+//!
+//! Where a frame's index comes from. The title begins its frames with a wait
+//! for the frame origin (`crate::frame`), whose token it hands to the
+//! frame's submissions and its present. The runs with the first version of
+//! this (the sleep and the simulation start at that wait) showed the title
+//! reading its pad once a frame and after the frame's first submission (in
+//! the world 101 of 108 frames, and none before it): what a
+//! frame submits right after its origin wait is a simulation made before
+//! it, and the reading that follows is the input of a later frame's
+//! simulation. Which thread reads, the one that waits for the origin or
+//! another, the runs did not show; the ten-second line counts it. Either
+//! way the sleep and the simulation start belong at that reading, and the
+//! reading opens the simulation ([`Frames::sample`]): it gets a new index,
+//! the sleep is made there, and the next origin wait takes the simulation
+//! for its frame ([`Frames::begin`]), so that its token's submission ends
+//! that simulation and its present shows it. This assumes
+//! the title is one frame deep (the simulation read after frame N's first
+//! submission is the one frame N + 1 submits); nothing seen from outside
+//! the title can tell one frame deep from two. A title frame with no
+//! simulation to take gets an index of its own: with no sleep while most of
+//! the last [`HOLD`] frames took one (the title reads input nearly every
+//! frame, and this frame's reading was missed), else with the sleep at the
+//! origin wait, as before (loads, cutscenes, menus that read now and then or
+//! never).
+
+use super::abi;
+
+/// `VICTORY_REFLEX`: Reflex by itself, with or without frame generation.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Reflex {
+    /// `on` or `1`: low latency.
+    On,
+    /// `boost`: low latency with boost.
+    Boost,
+}
+
+impl Reflex {
+    /// The switch's value: unset, empty, `0` and `off` are no Reflex by
+    /// itself (everything as without the switch); any other word is an
+    /// error, as an unknown DLSS mode is.
+    pub fn from_switch(value: Option<&str>) -> Result<Option<Self>, String> {
+        let Some(value) = value else { return Ok(None) };
+        Ok(match value.trim().to_ascii_lowercase().as_str() {
+            "" | "0" | "off" => None,
+            "1" | "on" => Some(Reflex::On),
+            "boost" => Some(Reflex::Boost),
+            _ => return Err(format!("VICTORY_REFLEX={value}: not one of on, 1, boost, off, 0")),
+        })
+    }
+
+    pub fn name(self) -> &'static str {
+        match self {
+            Reflex::On => "on",
+            Reflex::Boost => "boost",
+        }
+    }
+
+    /// The `sl::ReflexMode` of the switch.
+    pub fn sl_mode(self) -> u32 {
+        match self {
+            Reflex::On => abi::REFLEX_LOW_LATENCY,
+            Reflex::Boost => abi::REFLEX_LOW_LATENCY_WITH_BOOST,
+        }
+    }
+}
+
+/// The points of a frame's life that have a marker, in the order a frame
+/// passes them.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Stage {
+    /// The Reflex sleep before the frame's simulation returned (at the
+    /// reading that opened it, or at the origin wait), or the frame began
+    /// with no sleep.
+    SimulationStart = 0,
+    /// The title asked for the pad or keyboard reading that opened the
+    /// frame's simulation.
+    InputSample = 1,
+    /// The title's first submission of command lists: its simulation is over
+    /// and its submissions begin.
+    SimulationEnd = 2,
+    SubmitStart = 3,
+    /// The present begins on the host.
+    SubmitEnd = 4,
+    PresentStart = 5,
+    PresentEnd = 6,
+}
+
+/// The `sl::PCLMarker` of each stage.
+const ORDER: [u32; 7] = [
+    abi::SIMULATION_START,
+    abi::CONTROLLER_INPUT_SAMPLE,
+    abi::SIMULATION_END,
+    abi::RENDER_SUBMIT_START,
+    abi::RENDER_SUBMIT_END,
+    abi::PRESENT_START,
+    abi::PRESENT_END,
+];
+
+const fn bit(stage: Stage) -> u8 {
+    1 << stage as u8
+}
+
+/// Markers to send now, as bits by stage.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Markers(u8);
+
+impl Markers {
+    pub fn is_empty(self) -> bool {
+        self.0 == 0
+    }
+
+    /// Their `sl::PCLMarker` values, in the order they are to be sent.
+    pub fn iter(self) -> impl Iterator<Item = u32> {
+        ORDER.iter().enumerate().filter(move |(stage, _)| self.0 & (1 << stage) != 0).map(|(_, &marker)| marker)
+    }
+}
+
+/// One frame that is not over yet.
+struct Frame {
+    /// The index its frame tokens are made from.
+    index: u32,
+    /// The token the title's origin wait gave it (0: no origin wait has it
+    /// yet, or the frame was made at a present the title began none for).
+    origin: u64,
+    /// The number of the title's present that shows it (0: none yet).
+    present: u64,
+    /// The stages whose markers were sent.
+    sent: u8,
+    /// A title's origin wait has it: it began the frame, or took the
+    /// simulation a reading opened. False for a simulation not taken yet
+    /// and for a frame made at a present.
+    begun: bool,
+    /// The thread of that origin wait, or of the reading that opened the
+    /// frame while none has it (0: none).
+    thread: u32,
+    /// When (microseconds, the caller's clock) the origin wait had it, or
+    /// the reading opened it while none has it.
+    at: u64,
+    /// The title submitted to a queue that draws for it, and when.
+    submitted: bool,
+    submitted_at: u64,
+}
+
+impl Frame {
+    fn has(&self, stage: Stage) -> bool {
+        self.sent & bit(stage) != 0
+    }
+
+    /// The frame's simulation began (its sleep is over): from here on the
+    /// title's submissions and presents may end it.
+    fn started(&self) -> bool {
+        self.has(Stage::SimulationStart)
+    }
+
+    /// The markers of every stage up to `stage` that were not sent, now
+    /// counted as sent. The input sample is never owed: it is sent with the
+    /// simulation's start at the reading that opened the frame, or not at
+    /// all. What was sent is always a run from the first stage on, so
+    /// nothing ever leaves out of order.
+    fn reach(&mut self, stage: Stage) -> Markers {
+        let up_to = (bit(stage) << 1).wrapping_sub(1);
+        let owed = up_to & !bit(Stage::InputSample) & !self.sent;
+        self.sent |= owed;
+        Markers(owed)
+    }
+}
+
+/// Microseconds between two events of a frame, over the frames that had
+/// both since the counts were last taken.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Gap {
+    pub count: u32,
+    pub sum_us: u64,
+    pub longest_us: u64,
+}
+
+impl Gap {
+    const ZERO: Gap = Gap { count: 0, sum_us: 0, longest_us: 0 };
+
+    fn add(&mut self, us: u64) {
+        self.count = self.count.saturating_add(1);
+        self.sum_us = self.sum_us.saturating_add(us);
+        self.longest_us = self.longest_us.max(us);
+    }
+
+    pub fn average_us(&self) -> u64 {
+        self.sum_us / u64::from(self.count.max(1))
+    }
+}
+
+/// What happened since the counts were last taken (the ten-second line).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Counts {
+    /// Frames the title began (origin waits that made a token).
+    pub begun: u32,
+    /// Of them: frames that took the simulation a reading opened, frames
+    /// with no simulation to take and no sleep (most of the last [`HOLD`]
+    /// frames took one), and frames with no simulation to take that slept
+    /// at the origin wait (fewer did).
+    pub adopted: u32,
+    pub unpaced: u32,
+    pub origin_sleeps: u32,
+    /// Frames whose simulation start and input sample were sent where the
+    /// reading's sleep returned.
+    pub sampled: u32,
+    /// Readings that opened a simulation (with its sleep), that belonged to
+    /// the one open, that came before the newest begun frame's simulation
+    /// ended at a submission (the frame still simulates, or is in its sleep
+    /// at the origin wait), and that came on another thread than the one
+    /// that opens simulations.
+    pub opened: u32,
+    pub belongs: u32,
+    pub held_back: u32,
+    pub other_thread: u32,
+    /// Simulations let go because a reading came while one was open and
+    /// no origin wait had taken it for [`Frames::stale_after_us`] (a load).
+    pub stale: u32,
+    /// Simulations whose frame was over or past its simulation's end when
+    /// the reading's sleep returned: no input sample was sent for them.
+    pub lost: u32,
+    /// Frames whose first submission came before their simulation started
+    /// (the opening reading was still in its sleep): that submission was of
+    /// a simulation before, so the title is deeper than one frame there.
+    pub submitted_before_start: u32,
+    /// Where things happened, by thread: \[0\] on the thread of the origin
+    /// wait of the frame concerned, \[1\] on another. For an opening
+    /// reading the frame is the newest begun one; for the first submission
+    /// and the title's present, the frame they are of.
+    pub openings_by_thread: [u32; 2],
+    pub first_submits_by_thread: [u32; 2],
+    pub presents_by_thread: [u32; 2],
+    /// From a frame's origin wait to its first submission; from the newest
+    /// begun frame's first submission to the reading that opens the next
+    /// simulation; from the opening (after its sleep) to the origin wait
+    /// that takes it.
+    pub origin_to_submit: Gap,
+    pub submit_to_open: Gap,
+    pub open_to_adopt: Gap,
+    /// Frames presented without a submission of the title's before.
+    pub unsubmitted: u32,
+    /// Presents the title began no frame for (a second present of one
+    /// frame's token among them).
+    pub unbegun: u32,
+    /// Presents that found their frame by the title's token, and by order.
+    pub by_token: u32,
+    pub by_order: u32,
+    /// Frames whose simulation was ended by a submission that named them
+    /// with the title's token, and by one that did not (no token, or one no
+    /// frame here has): the newest running frame was taken then, which is
+    /// the wrong one if the title still submits a frame after it began the
+    /// next.
+    pub submitted_by_token: u32,
+    pub submitted_by_order: u32,
+    /// Frames begun and never presented.
+    pub never_presented: u32,
+}
+
+impl Counts {
+    const ZERO: Counts = Counts {
+        begun: 0,
+        adopted: 0,
+        unpaced: 0,
+        origin_sleeps: 0,
+        sampled: 0,
+        opened: 0,
+        belongs: 0,
+        held_back: 0,
+        other_thread: 0,
+        stale: 0,
+        lost: 0,
+        submitted_before_start: 0,
+        openings_by_thread: [0; 2],
+        first_submits_by_thread: [0; 2],
+        presents_by_thread: [0; 2],
+        origin_to_submit: Gap::ZERO,
+        submit_to_open: Gap::ZERO,
+        open_to_adopt: Gap::ZERO,
+        unsubmitted: 0,
+        unbegun: 0,
+        by_token: 0,
+        by_order: 0,
+        submitted_by_token: 0,
+        submitted_by_order: 0,
+        never_presented: 0,
+    };
+}
+
+/// Where a title frame's simulation starts ([`Frames::begin`]).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Begin {
+    /// The frame took the simulation a reading opened, with this index: its
+    /// sleep and its start were the reading's, nothing is sent here.
+    Adopted(u32),
+    /// A frame of its own with no sleep (most of the last [`HOLD`] frames
+    /// took a simulation, just not this one): its start now.
+    Unpaced(u32),
+    /// A frame of its own that sleeps here first (the title reads input on
+    /// fewer frames than that, or none): its start where the sleep returns.
+    Paced(u32),
+}
+
+/// What the title asking for a reading is ([`Frames::sample`]).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Sample {
+    /// It opens a simulation with this index: the sleep is made now, on the
+    /// reading's thread, and then [`Frames::sampled`] says its markers.
+    Open(u32),
+    /// A simulation is open and this reading is part of it.
+    Belongs,
+    /// The newest begun frame's simulation has not ended at a submission
+    /// yet: the reading is of that simulation, or the frame is in its sleep
+    /// at the origin wait.
+    HeldBack,
+    /// Another thread opens simulations.
+    OtherThread,
+}
+
+/// The frames that are not over, oldest first, the last index given, and
+/// the simulation a reading opened that no origin wait has taken yet.
+pub(crate) struct Frames {
+    last: u32,
+    live: Vec<Frame>,
+    /// The index of the open simulation: always newer than every frame an
+    /// origin wait has (the next origin wait takes it instead of making a
+    /// frame of its own), so indexes stay in the order the title presents
+    /// its frames.
+    open: Option<u32>,
+    /// The thread that opened the last simulation (0: none yet).
+    sampler: u32,
+    /// Origin waits since the last simulation was opened (saturating; it
+    /// starts above [`HOLD`], so any thread may open the first one).
+    since_opened: u32,
+    /// Which of the last [`HOLD`] title frames took a simulation a reading
+    /// opened, one bit each, the newest lowest (none at first, so the first
+    /// frames sleep at the origin wait).
+    adopted_recently: u32,
+    /// When the last origin wait came, and how long before it the one
+    /// before came (microseconds, the caller's clock; 0 until two came).
+    begun_at: Option<u64>,
+    interval_us: u64,
+    /// The title's present that was a second present of one frame's token,
+    /// and that frame's index: the host's present of it shows that frame
+    /// again ([`Frames::presenting`]).
+    repeat: Option<(u64, u32)>,
+    counts: Counts,
+}
+
+/// Frames kept at most (Streamline expects no more than three in flight; the
+/// rest is room for frames the title begins and never presents).
+const KEPT: usize = 8;
+
+/// The title frames looked back on. A frame with no simulation to take goes
+/// without a sleep only when more than half of the last `HOLD` frames took
+/// one: the title reads input nearly every frame and missed this one (in
+/// the world about one frame in fifteen had no reading counted), and a
+/// sleep at the origin wait would hold back a finished frame again. Where
+/// the title reads input on fewer frames (a menu that reads every tenth),
+/// its other frames sleep at the origin wait as they did before readings
+/// were looked at: Reflex's guide has `slReflexSleep` called always, and
+/// whether its pacing or frame generation's bears frames with no sleep the
+/// guides on disk do not say. Also the frames after which another thread
+/// may open simulations. Eight frames is a third of a second to two seconds
+/// in the world (4 to 28 frames a second there) and a few milliseconds in
+/// the menus.
+pub(crate) const HOLD: u32 = 8;
+const _: () = assert!(HOLD > 0 && HOLD <= u32::BITS);
+
+/// An open simulation is let go when a reading comes and no origin wait has
+/// taken it for this many microseconds or for [`STALE_FRAMES`] times the
+/// last interval between origin waits, whichever is longer: the title read
+/// input and began no frame (a load), and the reading opens a new one. A
+/// fixed bound alone let every simulation go in the world's slow stretches,
+/// where the origin wait that takes a simulation comes 80 to 370 ms after
+/// the reading that opened it.
+pub(crate) const STALE_US: u64 = 250_000;
+pub(crate) const STALE_FRAMES: u64 = 4;
+
+impl Frames {
+    pub const fn new() -> Self {
+        Frames {
+            last: 0,
+            live: Vec::new(),
+            open: None,
+            sampler: 0,
+            since_opened: u32::MAX,
+            adopted_recently: 0,
+            begun_at: None,
+            interval_us: 0,
+            repeat: None,
+            counts: Counts::ZERO,
+        }
+    }
+
+    /// How long an open simulation may wait for its origin wait while
+    /// readings come, in microseconds ([`STALE_US`]).
+    pub fn stale_after_us(&self) -> u64 {
+        STALE_US.max(self.interval_us.saturating_mul(STALE_FRAMES))
+    }
+
+    /// A new frame with the next index (indexes count from 1 and wrap).
+    fn push(&mut self, origin: u64, present: u64, begun: bool, thread: u32, at: u64) -> u32 {
+        // The oldest goes if the title begins frames it never presents.
+        // (Never the open simulation: it is the newest, and KEPT is above 1.)
+        if self.live.len() >= KEPT {
+            self.live.remove(0);
+            self.counts.never_presented += 1;
+        }
+        self.last = self.last.wrapping_add(1);
+        self.live.push(Frame {
+            index: self.last,
+            origin,
+            present,
+            sent: 0,
+            begun,
+            thread,
+            at,
+            submitted: false,
+            submitted_at: 0,
+        });
+        self.last
+    }
+
+    /// The open simulation is let go if no origin wait took it within
+    /// [`Frames::stale_after_us`] (`now` is the caller's clock, as at the
+    /// opening). Only a reading asks this: the origin wait that comes always
+    /// takes the open simulation, however long after, since that is the
+    /// frame that submits it.
+    fn let_go_stale(&mut self, now: u64) {
+        let Some(index) = self.open else { return };
+        let Some(at) = self.live.iter().position(|f| f.index == index) else {
+            self.open = None;
+            return;
+        };
+        if now.saturating_sub(self.live[at].at) > self.stale_after_us() {
+            self.live.remove(at);
+            self.open = None;
+            self.counts.stale += 1;
+        }
+    }
+
+    /// The title begins a frame on `thread` at `now`: its origin wait made
+    /// token `origin`. The frame takes the open simulation if there is one,
+    /// else it gets an index of its own, with or without a sleep here.
+    pub fn begin(&mut self, origin: u64, thread: u32, now: u64) -> Begin {
+        self.counts.begun += 1;
+        // The interval between origin waits, for how long an open
+        // simulation may wait for one while readings come.
+        if let Some(before) = self.begun_at {
+            self.interval_us = now.saturating_sub(before);
+        }
+        self.begun_at = Some(now);
+        self.since_opened = self.since_opened.saturating_add(1);
+        // The frames before this one that took a simulation; this one's bit
+        // is set below if it takes one.
+        let window = u32::MAX >> (u32::BITS - HOLD);
+        let took_before = (self.adopted_recently & window).count_ones();
+        self.adopted_recently = (self.adopted_recently << 1) & window;
+        // No time bound here: the simulation open now is the one this frame
+        // submits, whether the frame came 3 ms or 370 ms after its reading.
+        if let Some(index) = self.open.take()
+            && let Some(frame) = self.live.iter_mut().find(|f| f.index == index)
+        {
+            self.counts.open_to_adopt.add(now.saturating_sub(frame.at));
+            frame.origin = origin;
+            frame.begun = true;
+            frame.thread = thread;
+            frame.at = now;
+            self.counts.adopted += 1;
+            self.adopted_recently |= 1;
+            return Begin::Adopted(index);
+        }
+        let index = self.push(origin, 0, true, thread, now);
+        if took_before > HOLD / 2 {
+            self.counts.unpaced += 1;
+            Begin::Unpaced(index)
+        } else {
+            self.counts.origin_sleeps += 1;
+            Begin::Paced(index)
+        }
+    }
+
+    /// The markers frame `index` owes up to `stage`, now sent; none if the
+    /// frame is over.
+    pub fn reach(&mut self, index: u32, stage: Stage) -> Markers {
+        self.live.iter_mut().find(|f| f.index == index).map_or(Markers(0), |f| f.reach(stage))
+    }
+
+    /// The title asks for a pad or keyboard reading on `thread` at `now`,
+    /// before the reading is picked. It opens a simulation only when none
+    /// is open, the newest begun frame's simulation has ended at its
+    /// submission (or it has its present, or there is no begun frame), and
+    /// the thread is the one that opens them (or
+    /// that one has not for more than [`HOLD`] frames). So at most one
+    /// simulation opens between two origin waits, one sleep is made for
+    /// it, and it never runs while a sleep at the origin wait does (that
+    /// frame has not submitted yet). A simulation that waited too long for
+    /// its origin wait ([`Frames::stale_after_us`]) is let go first, and the
+    /// reading opens another.
+    pub fn sample(&mut self, thread: u32, now: u64) -> Sample {
+        self.let_go_stale(now);
+        if self.sampler != 0 && self.sampler != thread && self.since_opened <= HOLD {
+            self.counts.other_thread += 1;
+            return Sample::OtherThread;
+        }
+        if self.open.is_some() {
+            self.counts.belongs += 1;
+            return Sample::Belongs;
+        }
+        let newest = self.live.iter().rev().find(|f| f.begun);
+        if let Some(frame) = newest {
+            // (Its simulation's end, not its first submission: a submission
+            // that came while the opening reading still slept ended nothing,
+            // and the readings of that simulation must not open another.)
+            if !frame.has(Stage::SimulationEnd) && frame.present == 0 {
+                self.counts.held_back += 1;
+                return Sample::HeldBack;
+            }
+            // Which thread reads, against the one that begins frames; and
+            // how long after that frame's first submission.
+            self.counts.openings_by_thread[usize::from(frame.thread != thread)] += 1;
+            if frame.submitted {
+                self.counts.submit_to_open.add(now.saturating_sub(frame.submitted_at));
+            }
+        }
+        let index = self.push(0, 0, false, thread, now);
+        self.open = Some(index);
+        self.sampler = thread;
+        self.since_opened = 0;
+        self.counts.opened += 1;
+        Sample::Open(index)
+    }
+
+    /// The sleep of the simulation `index` opened returned at `now`: its
+    /// simulation start and its input sample, now sent; none if the frame
+    /// is over or its present already sent its simulation's markers (the
+    /// sample is lost then, and counted).
+    pub fn sampled(&mut self, index: u32, now: u64) -> Markers {
+        let Some(frame) = self.live.iter_mut().find(|f| f.index == index) else {
+            self.counts.lost += 1;
+            return Markers(0);
+        };
+        if frame.started() {
+            self.counts.lost += 1;
+            return Markers(0);
+        }
+        // While no origin wait has it, the opening counts from here (the
+        // gap to the adoption is measured after the sleep).
+        if !frame.begun {
+            frame.at = frame.at.max(now);
+        }
+        let owed = bit(Stage::SimulationStart) | bit(Stage::InputSample);
+        frame.sent |= owed;
+        self.counts.sampled += 1;
+        Markers(owed)
+    }
+
+    /// The title submits command lists to a queue that draws, on `thread`
+    /// at `now`, tagged with frame token `origin` (0: not tagged): at the
+    /// frame's first submission its simulation ends and its submissions
+    /// begin. The frame is the one of that token, else the newest begun
+    /// frame whose simulation runs and whose present the title has not
+    /// called (never a simulation no origin wait has taken). Which of the
+    /// two ended a frame's simulation is counted, for the line.
+    pub fn submit(&mut self, origin: u64, thread: u32, now: u64) -> Option<(u32, Markers)> {
+        let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten();
+        let at = match tagged {
+            Some(at) => at,
+            None => self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0)?,
+        };
+        let frame = &mut self.live[at];
+        let first = !frame.submitted;
+        if first {
+            frame.submitted = true;
+            frame.submitted_at = now;
+            self.counts.first_submits_by_thread[usize::from(frame.thread != thread)] += 1;
+            self.counts.origin_to_submit.add(now.saturating_sub(frame.at));
+        }
+        // A frame still in its sleep has no simulation to end. (At the
+        // origin wait that cannot be: the title has not got the token yet.
+        // At a reading it means this submission is of a simulation before.)
+        if !frame.started() {
+            if first {
+                self.counts.submitted_before_start += 1;
+            }
+            return None;
+        }
+        let owed = frame.reach(Stage::SubmitStart);
+        // Later submissions of the frame owe nothing and count nothing.
+        if owed.is_empty() {
+            return None;
+        }
+        // Counted where it has an effect: this submission is the one that
+        // ends the frame's simulation.
+        match tagged {
+            Some(_) => self.counts.submitted_by_token += 1,
+            None => self.counts.submitted_by_order += 1,
+        }
+        Some((frame.index, owed))
+    }
+
+    /// The title calls its present number `present` (counted from 1) on
+    /// `thread` with frame token `origin` in its first plane (0: none): the
+    /// present is that frame's, else the newest begun frame's whose
+    /// simulation runs and that has no present yet. Frames begun before it
+    /// that have none are over: the title never presented them. (By the
+    /// token the frame need not have started: a simulation whose reading is
+    /// still in its sleep may be presented, and then sends what it owes at
+    /// the present.)
+    pub fn title_presents(&mut self, present: u64, origin: u64, thread: u32) {
+        let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten();
+        let at = match tagged {
+            Some(at) if self.live[at].present == 0 => {
+                self.counts.by_token += 1;
+                at
+            }
+            // The token's frame has its present: this one shows that frame
+            // again, and the host's present of it names that frame's index
+            // ([`Frames::presenting`]).
+            Some(at) => {
+                self.repeat = Some((present, self.live[at].index));
+                return;
+            }
+            None => {
+                let Some(at) = self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0) else { return };
+                self.counts.by_order += 1;
+                at
+            }
+        };
+        self.counts.presents_by_thread[usize::from(self.live[at].thread != thread)] += 1;
+        self.live[at].present = present;
+        let before = self.live.len();
+        let mut place = 0;
+        // (An open simulation is the newest, after `at`: it stays.)
+        self.live.retain(|f| {
+            let keep = place >= at || f.present != 0;
+            place += 1;
+            keep
+        });
+        self.counts.never_presented += (before - self.live.len()) as u32;
+    }
+
+    /// Present number `present` begins on the host: its frame's index. The
+    /// indexes the host presents must keep rising: frame generation's
+    /// constants, tags and present markers use them, and its guide ties
+    /// present markers out of step with the frame shown to constants it
+    /// cannot find. So a present the title began no frame for does not get
+    /// an index newer than a simulation still to be presented:
+    /// - a second present of one frame's token shows that frame again and
+    ///   gets its index (its markers were sent once, nothing more is);
+    /// - another, while a simulation a reading opened is open, takes that
+    ///   simulation (the next index in order): its markers are completed
+    ///   here, and the next origin wait has none to take;
+    /// - else it gets a frame made here, which owes every marker (the
+    ///   check's presents, a present before the title's first frame).
+    ///
+    /// The line counts all three as presents with no frame begun; in the
+    /// runs there were none in the title.
+    pub fn presenting(&mut self, present: u64) -> u32 {
+        if present != 0
+            && let Some(frame) = self.live.iter().find(|f| f.present == present)
+        {
+            if !frame.has(Stage::SubmitStart) {
+                self.counts.unsubmitted += 1;
+            }
+            return frame.index;
+        }
+        self.counts.unbegun += 1;
+        if present != 0
+            && let Some((repeated, index)) = self.repeat
+            && repeated == present
+        {
+            self.repeat = None;
+            return index;
+        }
+        if let Some(index) = self.open.take()
+            && let Some(frame) = self.live.iter_mut().find(|f| f.index == index)
+        {
+            frame.present = present;
+            return index;
+        }
+        self.push(0, present, false, 0, 0)
+    }
+
+    /// The present of frame `index` returned: its last marker, and the frame
+    /// is over.
+    pub fn presented(&mut self, index: u32) -> Markers {
+        let Some(at) = self.live.iter().position(|f| f.index == index) else { return Markers(0) };
+        let owed = self.live[at].reach(Stage::PresentEnd);
+        self.live.remove(at);

Removing the frame also loses its origin-token-to-index mapping, so a repeated title present after the first host present completes is no longer recognised. It then consumes the next open simulation or creates a new frame instead of reusing the completed frame's index without markers. Retain bounded completed-token history separately from live marker state, and test a repeat arriving after host completion.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:review-comment:4732931855 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072#discussion_r4732931855). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-29T19:58:54Z. **Code review location:** `crates/victory-gpu/src/streamline/reflex.rs`; line 698 ~~~~diff @@ -0,0 +1,1386 @@ +//! Reflex by itself (`VICTORY_REFLEX`), the part that needs no library: the +//! switch, which latency markers a frame has sent and which it owes at each +//! point of its life, where the Reflex sleep goes, and what the reports of a +//! Reflex state average to. +//! +//! A Reflex frame is one index, and the Reflex sleep and every marker of it +//! are given a frame token made from that index, on whichever thread they +//! happen. [`Frames`] is what the threads share: who holds it decides, so a +//! frame's markers leave in order and once each. +//! +//! Where a frame's index comes from. The title begins its frames with a wait +//! for the frame origin (`crate::frame`), whose token it hands to the +//! frame's submissions and its present. The runs with the first version of +//! this (the sleep and the simulation start at that wait) showed the title +//! reading its pad once a frame and after the frame's first submission (in +//! the world 101 of 108 frames, and none before it): what a +//! frame submits right after its origin wait is a simulation made before +//! it, and the reading that follows is the input of a later frame's +//! simulation. Which thread reads, the one that waits for the origin or +//! another, the runs did not show; the ten-second line counts it. Either +//! way the sleep and the simulation start belong at that reading, and the +//! reading opens the simulation ([`Frames::sample`]): it gets a new index, +//! the sleep is made there, and the next origin wait takes the simulation +//! for its frame ([`Frames::begin`]), so that its token's submission ends +//! that simulation and its present shows it. This assumes +//! the title is one frame deep (the simulation read after frame N's first +//! submission is the one frame N + 1 submits); nothing seen from outside +//! the title can tell one frame deep from two. A title frame with no +//! simulation to take gets an index of its own: with no sleep while most of +//! the last [`HOLD`] frames took one (the title reads input nearly every +//! frame, and this frame's reading was missed), else with the sleep at the +//! origin wait, as before (loads, cutscenes, menus that read now and then or +//! never). + +use super::abi; + +/// `VICTORY_REFLEX`: Reflex by itself, with or without frame generation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reflex { + /// `on` or `1`: low latency. + On, + /// `boost`: low latency with boost. + Boost, +} + +impl Reflex { + /// The switch's value: unset, empty, `0` and `off` are no Reflex by + /// itself (everything as without the switch); any other word is an + /// error, as an unknown DLSS mode is. + pub fn from_switch(value: Option<&str>) -> Result<Option<Self>, String> { + let Some(value) = value else { return Ok(None) }; + Ok(match value.trim().to_ascii_lowercase().as_str() { + "" | "0" | "off" => None, + "1" | "on" => Some(Reflex::On), + "boost" => Some(Reflex::Boost), + _ => return Err(format!("VICTORY_REFLEX={value}: not one of on, 1, boost, off, 0")), + }) + } + + pub fn name(self) -> &'static str { + match self { + Reflex::On => "on", + Reflex::Boost => "boost", + } + } + + /// The `sl::ReflexMode` of the switch. + pub fn sl_mode(self) -> u32 { + match self { + Reflex::On => abi::REFLEX_LOW_LATENCY, + Reflex::Boost => abi::REFLEX_LOW_LATENCY_WITH_BOOST, + } + } +} + +/// The points of a frame's life that have a marker, in the order a frame +/// passes them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Stage { + /// The Reflex sleep before the frame's simulation returned (at the + /// reading that opened it, or at the origin wait), or the frame began + /// with no sleep. + SimulationStart = 0, + /// The title asked for the pad or keyboard reading that opened the + /// frame's simulation. + InputSample = 1, + /// The title's first submission of command lists: its simulation is over + /// and its submissions begin. + SimulationEnd = 2, + SubmitStart = 3, + /// The present begins on the host. + SubmitEnd = 4, + PresentStart = 5, + PresentEnd = 6, +} + +/// The `sl::PCLMarker` of each stage. +const ORDER: [u32; 7] = [ + abi::SIMULATION_START, + abi::CONTROLLER_INPUT_SAMPLE, + abi::SIMULATION_END, + abi::RENDER_SUBMIT_START, + abi::RENDER_SUBMIT_END, + abi::PRESENT_START, + abi::PRESENT_END, +]; + +const fn bit(stage: Stage) -> u8 { + 1 << stage as u8 +} + +/// Markers to send now, as bits by stage. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Markers(u8); + +impl Markers { + pub fn is_empty(self) -> bool { + self.0 == 0 + } + + /// Their `sl::PCLMarker` values, in the order they are to be sent. + pub fn iter(self) -> impl Iterator<Item = u32> { + ORDER.iter().enumerate().filter(move |(stage, _)| self.0 & (1 << stage) != 0).map(|(_, &marker)| marker) + } +} + +/// One frame that is not over yet. +struct Frame { + /// The index its frame tokens are made from. + index: u32, + /// The token the title's origin wait gave it (0: no origin wait has it + /// yet, or the frame was made at a present the title began none for). + origin: u64, + /// The number of the title's present that shows it (0: none yet). + present: u64, + /// The stages whose markers were sent. + sent: u8, + /// A title's origin wait has it: it began the frame, or took the + /// simulation a reading opened. False for a simulation not taken yet + /// and for a frame made at a present. + begun: bool, + /// The thread of that origin wait, or of the reading that opened the + /// frame while none has it (0: none). + thread: u32, + /// When (microseconds, the caller's clock) the origin wait had it, or + /// the reading opened it while none has it. + at: u64, + /// The title submitted to a queue that draws for it, and when. + submitted: bool, + submitted_at: u64, +} + +impl Frame { + fn has(&self, stage: Stage) -> bool { + self.sent & bit(stage) != 0 + } + + /// The frame's simulation began (its sleep is over): from here on the + /// title's submissions and presents may end it. + fn started(&self) -> bool { + self.has(Stage::SimulationStart) + } + + /// The markers of every stage up to `stage` that were not sent, now + /// counted as sent. The input sample is never owed: it is sent with the + /// simulation's start at the reading that opened the frame, or not at + /// all. What was sent is always a run from the first stage on, so + /// nothing ever leaves out of order. + fn reach(&mut self, stage: Stage) -> Markers { + let up_to = (bit(stage) << 1).wrapping_sub(1); + let owed = up_to & !bit(Stage::InputSample) & !self.sent; + self.sent |= owed; + Markers(owed) + } +} + +/// Microseconds between two events of a frame, over the frames that had +/// both since the counts were last taken. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Gap { + pub count: u32, + pub sum_us: u64, + pub longest_us: u64, +} + +impl Gap { + const ZERO: Gap = Gap { count: 0, sum_us: 0, longest_us: 0 }; + + fn add(&mut self, us: u64) { + self.count = self.count.saturating_add(1); + self.sum_us = self.sum_us.saturating_add(us); + self.longest_us = self.longest_us.max(us); + } + + pub fn average_us(&self) -> u64 { + self.sum_us / u64::from(self.count.max(1)) + } +} + +/// What happened since the counts were last taken (the ten-second line). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Counts { + /// Frames the title began (origin waits that made a token). + pub begun: u32, + /// Of them: frames that took the simulation a reading opened, frames + /// with no simulation to take and no sleep (most of the last [`HOLD`] + /// frames took one), and frames with no simulation to take that slept + /// at the origin wait (fewer did). + pub adopted: u32, + pub unpaced: u32, + pub origin_sleeps: u32, + /// Frames whose simulation start and input sample were sent where the + /// reading's sleep returned. + pub sampled: u32, + /// Readings that opened a simulation (with its sleep), that belonged to + /// the one open, that came before the newest begun frame's simulation + /// ended at a submission (the frame still simulates, or is in its sleep + /// at the origin wait), and that came on another thread than the one + /// that opens simulations. + pub opened: u32, + pub belongs: u32, + pub held_back: u32, + pub other_thread: u32, + /// Simulations let go because a reading came while one was open and + /// no origin wait had taken it for [`Frames::stale_after_us`] (a load). + pub stale: u32, + /// Simulations whose frame was over or past its simulation's end when + /// the reading's sleep returned: no input sample was sent for them. + pub lost: u32, + /// Frames whose first submission came before their simulation started + /// (the opening reading was still in its sleep): that submission was of + /// a simulation before, so the title is deeper than one frame there. + pub submitted_before_start: u32, + /// Where things happened, by thread: \[0\] on the thread of the origin + /// wait of the frame concerned, \[1\] on another. For an opening + /// reading the frame is the newest begun one; for the first submission + /// and the title's present, the frame they are of. + pub openings_by_thread: [u32; 2], + pub first_submits_by_thread: [u32; 2], + pub presents_by_thread: [u32; 2], + /// From a frame's origin wait to its first submission; from the newest + /// begun frame's first submission to the reading that opens the next + /// simulation; from the opening (after its sleep) to the origin wait + /// that takes it. + pub origin_to_submit: Gap, + pub submit_to_open: Gap, + pub open_to_adopt: Gap, + /// Frames presented without a submission of the title's before. + pub unsubmitted: u32, + /// Presents the title began no frame for (a second present of one + /// frame's token among them). + pub unbegun: u32, + /// Presents that found their frame by the title's token, and by order. + pub by_token: u32, + pub by_order: u32, + /// Frames whose simulation was ended by a submission that named them + /// with the title's token, and by one that did not (no token, or one no + /// frame here has): the newest running frame was taken then, which is + /// the wrong one if the title still submits a frame after it began the + /// next. + pub submitted_by_token: u32, + pub submitted_by_order: u32, + /// Frames begun and never presented. + pub never_presented: u32, +} + +impl Counts { + const ZERO: Counts = Counts { + begun: 0, + adopted: 0, + unpaced: 0, + origin_sleeps: 0, + sampled: 0, + opened: 0, + belongs: 0, + held_back: 0, + other_thread: 0, + stale: 0, + lost: 0, + submitted_before_start: 0, + openings_by_thread: [0; 2], + first_submits_by_thread: [0; 2], + presents_by_thread: [0; 2], + origin_to_submit: Gap::ZERO, + submit_to_open: Gap::ZERO, + open_to_adopt: Gap::ZERO, + unsubmitted: 0, + unbegun: 0, + by_token: 0, + by_order: 0, + submitted_by_token: 0, + submitted_by_order: 0, + never_presented: 0, + }; +} + +/// Where a title frame's simulation starts ([`Frames::begin`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Begin { + /// The frame took the simulation a reading opened, with this index: its + /// sleep and its start were the reading's, nothing is sent here. + Adopted(u32), + /// A frame of its own with no sleep (most of the last [`HOLD`] frames + /// took a simulation, just not this one): its start now. + Unpaced(u32), + /// A frame of its own that sleeps here first (the title reads input on + /// fewer frames than that, or none): its start where the sleep returns. + Paced(u32), +} + +/// What the title asking for a reading is ([`Frames::sample`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Sample { + /// It opens a simulation with this index: the sleep is made now, on the + /// reading's thread, and then [`Frames::sampled`] says its markers. + Open(u32), + /// A simulation is open and this reading is part of it. + Belongs, + /// The newest begun frame's simulation has not ended at a submission + /// yet: the reading is of that simulation, or the frame is in its sleep + /// at the origin wait. + HeldBack, + /// Another thread opens simulations. + OtherThread, +} + +/// The frames that are not over, oldest first, the last index given, and +/// the simulation a reading opened that no origin wait has taken yet. +pub(crate) struct Frames { + last: u32, + live: Vec<Frame>, + /// The index of the open simulation: always newer than every frame an + /// origin wait has (the next origin wait takes it instead of making a + /// frame of its own), so indexes stay in the order the title presents + /// its frames. + open: Option<u32>, + /// The thread that opened the last simulation (0: none yet). + sampler: u32, + /// Origin waits since the last simulation was opened (saturating; it + /// starts above [`HOLD`], so any thread may open the first one). + since_opened: u32, + /// Which of the last [`HOLD`] title frames took a simulation a reading + /// opened, one bit each, the newest lowest (none at first, so the first + /// frames sleep at the origin wait). + adopted_recently: u32, + /// When the last origin wait came, and how long before it the one + /// before came (microseconds, the caller's clock; 0 until two came). + begun_at: Option<u64>, + interval_us: u64, + /// The title's present that was a second present of one frame's token, + /// and that frame's index: the host's present of it shows that frame + /// again ([`Frames::presenting`]). + repeat: Option<(u64, u32)>, + counts: Counts, +} + +/// Frames kept at most (Streamline expects no more than three in flight; the +/// rest is room for frames the title begins and never presents). +const KEPT: usize = 8; + +/// The title frames looked back on. A frame with no simulation to take goes +/// without a sleep only when more than half of the last `HOLD` frames took +/// one: the title reads input nearly every frame and missed this one (in +/// the world about one frame in fifteen had no reading counted), and a +/// sleep at the origin wait would hold back a finished frame again. Where +/// the title reads input on fewer frames (a menu that reads every tenth), +/// its other frames sleep at the origin wait as they did before readings +/// were looked at: Reflex's guide has `slReflexSleep` called always, and +/// whether its pacing or frame generation's bears frames with no sleep the +/// guides on disk do not say. Also the frames after which another thread +/// may open simulations. Eight frames is a third of a second to two seconds +/// in the world (4 to 28 frames a second there) and a few milliseconds in +/// the menus. +pub(crate) const HOLD: u32 = 8; +const _: () = assert!(HOLD > 0 && HOLD <= u32::BITS); + +/// An open simulation is let go when a reading comes and no origin wait has +/// taken it for this many microseconds or for [`STALE_FRAMES`] times the +/// last interval between origin waits, whichever is longer: the title read +/// input and began no frame (a load), and the reading opens a new one. A +/// fixed bound alone let every simulation go in the world's slow stretches, +/// where the origin wait that takes a simulation comes 80 to 370 ms after +/// the reading that opened it. +pub(crate) const STALE_US: u64 = 250_000; +pub(crate) const STALE_FRAMES: u64 = 4; + +impl Frames { + pub const fn new() -> Self { + Frames { + last: 0, + live: Vec::new(), + open: None, + sampler: 0, + since_opened: u32::MAX, + adopted_recently: 0, + begun_at: None, + interval_us: 0, + repeat: None, + counts: Counts::ZERO, + } + } + + /// How long an open simulation may wait for its origin wait while + /// readings come, in microseconds ([`STALE_US`]). + pub fn stale_after_us(&self) -> u64 { + STALE_US.max(self.interval_us.saturating_mul(STALE_FRAMES)) + } + + /// A new frame with the next index (indexes count from 1 and wrap). + fn push(&mut self, origin: u64, present: u64, begun: bool, thread: u32, at: u64) -> u32 { + // The oldest goes if the title begins frames it never presents. + // (Never the open simulation: it is the newest, and KEPT is above 1.) + if self.live.len() >= KEPT { + self.live.remove(0); + self.counts.never_presented += 1; + } + self.last = self.last.wrapping_add(1); + self.live.push(Frame { + index: self.last, + origin, + present, + sent: 0, + begun, + thread, + at, + submitted: false, + submitted_at: 0, + }); + self.last + } + + /// The open simulation is let go if no origin wait took it within + /// [`Frames::stale_after_us`] (`now` is the caller's clock, as at the + /// opening). Only a reading asks this: the origin wait that comes always + /// takes the open simulation, however long after, since that is the + /// frame that submits it. + fn let_go_stale(&mut self, now: u64) { + let Some(index) = self.open else { return }; + let Some(at) = self.live.iter().position(|f| f.index == index) else { + self.open = None; + return; + }; + if now.saturating_sub(self.live[at].at) > self.stale_after_us() { + self.live.remove(at); + self.open = None; + self.counts.stale += 1; + } + } + + /// The title begins a frame on `thread` at `now`: its origin wait made + /// token `origin`. The frame takes the open simulation if there is one, + /// else it gets an index of its own, with or without a sleep here. + pub fn begin(&mut self, origin: u64, thread: u32, now: u64) -> Begin { + self.counts.begun += 1; + // The interval between origin waits, for how long an open + // simulation may wait for one while readings come. + if let Some(before) = self.begun_at { + self.interval_us = now.saturating_sub(before); + } + self.begun_at = Some(now); + self.since_opened = self.since_opened.saturating_add(1); + // The frames before this one that took a simulation; this one's bit + // is set below if it takes one. + let window = u32::MAX >> (u32::BITS - HOLD); + let took_before = (self.adopted_recently & window).count_ones(); + self.adopted_recently = (self.adopted_recently << 1) & window; + // No time bound here: the simulation open now is the one this frame + // submits, whether the frame came 3 ms or 370 ms after its reading. + if let Some(index) = self.open.take() + && let Some(frame) = self.live.iter_mut().find(|f| f.index == index) + { + self.counts.open_to_adopt.add(now.saturating_sub(frame.at)); + frame.origin = origin; + frame.begun = true; + frame.thread = thread; + frame.at = now; + self.counts.adopted += 1; + self.adopted_recently |= 1; + return Begin::Adopted(index); + } + let index = self.push(origin, 0, true, thread, now); + if took_before > HOLD / 2 { + self.counts.unpaced += 1; + Begin::Unpaced(index) + } else { + self.counts.origin_sleeps += 1; + Begin::Paced(index) + } + } + + /// The markers frame `index` owes up to `stage`, now sent; none if the + /// frame is over. + pub fn reach(&mut self, index: u32, stage: Stage) -> Markers { + self.live.iter_mut().find(|f| f.index == index).map_or(Markers(0), |f| f.reach(stage)) + } + + /// The title asks for a pad or keyboard reading on `thread` at `now`, + /// before the reading is picked. It opens a simulation only when none + /// is open, the newest begun frame's simulation has ended at its + /// submission (or it has its present, or there is no begun frame), and + /// the thread is the one that opens them (or + /// that one has not for more than [`HOLD`] frames). So at most one + /// simulation opens between two origin waits, one sleep is made for + /// it, and it never runs while a sleep at the origin wait does (that + /// frame has not submitted yet). A simulation that waited too long for + /// its origin wait ([`Frames::stale_after_us`]) is let go first, and the + /// reading opens another. + pub fn sample(&mut self, thread: u32, now: u64) -> Sample { + self.let_go_stale(now); + if self.sampler != 0 && self.sampler != thread && self.since_opened <= HOLD { + self.counts.other_thread += 1; + return Sample::OtherThread; + } + if self.open.is_some() { + self.counts.belongs += 1; + return Sample::Belongs; + } + let newest = self.live.iter().rev().find(|f| f.begun); + if let Some(frame) = newest { + // (Its simulation's end, not its first submission: a submission + // that came while the opening reading still slept ended nothing, + // and the readings of that simulation must not open another.) + if !frame.has(Stage::SimulationEnd) && frame.present == 0 { + self.counts.held_back += 1; + return Sample::HeldBack; + } + // Which thread reads, against the one that begins frames; and + // how long after that frame's first submission. + self.counts.openings_by_thread[usize::from(frame.thread != thread)] += 1; + if frame.submitted { + self.counts.submit_to_open.add(now.saturating_sub(frame.submitted_at)); + } + } + let index = self.push(0, 0, false, thread, now); + self.open = Some(index); + self.sampler = thread; + self.since_opened = 0; + self.counts.opened += 1; + Sample::Open(index) + } + + /// The sleep of the simulation `index` opened returned at `now`: its + /// simulation start and its input sample, now sent; none if the frame + /// is over or its present already sent its simulation's markers (the + /// sample is lost then, and counted). + pub fn sampled(&mut self, index: u32, now: u64) -> Markers { + let Some(frame) = self.live.iter_mut().find(|f| f.index == index) else { + self.counts.lost += 1; + return Markers(0); + }; + if frame.started() { + self.counts.lost += 1; + return Markers(0); + } + // While no origin wait has it, the opening counts from here (the + // gap to the adoption is measured after the sleep). + if !frame.begun { + frame.at = frame.at.max(now); + } + let owed = bit(Stage::SimulationStart) | bit(Stage::InputSample); + frame.sent |= owed; + self.counts.sampled += 1; + Markers(owed) + } + + /// The title submits command lists to a queue that draws, on `thread` + /// at `now`, tagged with frame token `origin` (0: not tagged): at the + /// frame's first submission its simulation ends and its submissions + /// begin. The frame is the one of that token, else the newest begun + /// frame whose simulation runs and whose present the title has not + /// called (never a simulation no origin wait has taken). Which of the + /// two ended a frame's simulation is counted, for the line. + pub fn submit(&mut self, origin: u64, thread: u32, now: u64) -> Option<(u32, Markers)> { + let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten(); + let at = match tagged { + Some(at) => at, + None => self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0)?, + }; + let frame = &mut self.live[at]; + let first = !frame.submitted; + if first { + frame.submitted = true; + frame.submitted_at = now; + self.counts.first_submits_by_thread[usize::from(frame.thread != thread)] += 1; + self.counts.origin_to_submit.add(now.saturating_sub(frame.at)); + } + // A frame still in its sleep has no simulation to end. (At the + // origin wait that cannot be: the title has not got the token yet. + // At a reading it means this submission is of a simulation before.) + if !frame.started() { + if first { + self.counts.submitted_before_start += 1; + } + return None; + } + let owed = frame.reach(Stage::SubmitStart); + // Later submissions of the frame owe nothing and count nothing. + if owed.is_empty() { + return None; + } + // Counted where it has an effect: this submission is the one that + // ends the frame's simulation. + match tagged { + Some(_) => self.counts.submitted_by_token += 1, + None => self.counts.submitted_by_order += 1, + } + Some((frame.index, owed)) + } + + /// The title calls its present number `present` (counted from 1) on + /// `thread` with frame token `origin` in its first plane (0: none): the + /// present is that frame's, else the newest begun frame's whose + /// simulation runs and that has no present yet. Frames begun before it + /// that have none are over: the title never presented them. (By the + /// token the frame need not have started: a simulation whose reading is + /// still in its sleep may be presented, and then sends what it owes at + /// the present.) + pub fn title_presents(&mut self, present: u64, origin: u64, thread: u32) { + let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten(); + let at = match tagged { + Some(at) if self.live[at].present == 0 => { + self.counts.by_token += 1; + at + } + // The token's frame has its present: this one shows that frame + // again, and the host's present of it names that frame's index + // ([`Frames::presenting`]). + Some(at) => { + self.repeat = Some((present, self.live[at].index)); + return; + } + None => { + let Some(at) = self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0) else { return }; + self.counts.by_order += 1; + at + } + }; + self.counts.presents_by_thread[usize::from(self.live[at].thread != thread)] += 1; + self.live[at].present = present; + let before = self.live.len(); + let mut place = 0; + // (An open simulation is the newest, after `at`: it stays.) + self.live.retain(|f| { + let keep = place >= at || f.present != 0; + place += 1; + keep + }); + self.counts.never_presented += (before - self.live.len()) as u32; + } + + /// Present number `present` begins on the host: its frame's index. The + /// indexes the host presents must keep rising: frame generation's + /// constants, tags and present markers use them, and its guide ties + /// present markers out of step with the frame shown to constants it + /// cannot find. So a present the title began no frame for does not get + /// an index newer than a simulation still to be presented: + /// - a second present of one frame's token shows that frame again and + /// gets its index (its markers were sent once, nothing more is); + /// - another, while a simulation a reading opened is open, takes that + /// simulation (the next index in order): its markers are completed + /// here, and the next origin wait has none to take; + /// - else it gets a frame made here, which owes every marker (the + /// check's presents, a present before the title's first frame). + /// + /// The line counts all three as presents with no frame begun; in the + /// runs there were none in the title. + pub fn presenting(&mut self, present: u64) -> u32 { + if present != 0 + && let Some(frame) = self.live.iter().find(|f| f.present == present) + { + if !frame.has(Stage::SubmitStart) { + self.counts.unsubmitted += 1; + } + return frame.index; + } + self.counts.unbegun += 1; + if present != 0 + && let Some((repeated, index)) = self.repeat + && repeated == present + { + self.repeat = None; + return index; + } + if let Some(index) = self.open.take() + && let Some(frame) = self.live.iter_mut().find(|f| f.index == index) + { + frame.present = present; + return index; + } + self.push(0, present, false, 0, 0) + } + + /// The present of frame `index` returned: its last marker, and the frame + /// is over. + pub fn presented(&mut self, index: u32) -> Markers { + let Some(at) = self.live.iter().position(|f| f.index == index) else { return Markers(0) }; + let owed = self.live[at].reach(Stage::PresentEnd); + self.live.remove(at); ~~~~ --- Removing the frame also loses its origin-token-to-index mapping, so a repeated title present after the first host present completes is no longer recognised. It then consumes the next open simulation or creates a new frame instead of reusing the completed frame's index without markers. Retain bounded completed-token history separately from live marker state, and test a repeat arriving after host completion.
Copilot commented 2026-11-29 19:58:54 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Copilot on 2026-11-29T19:58:54Z.

Code review location: crates/victory-gpu/src/streamline.rs; line 1388

@@ -1280,21 +1365,70 @@ pub(crate) fn device_made(device: &ID3D12Device) -> Option<ID3D12CommandQueue> {
             tracing::warn!("DLSS Frame Generation stays off: the device hand-over to Streamline did not complete");
         }
     }
+    // Reflex by itself (`VICTORY_REFLEX`): its functions whenever Streamline
+    // is loaded, with or without frame generation.
+    let mut reflex_ready = false;
+    if let Some(mode) = plan.reflex {
+        functions.reflex_set_options =
+            functions.reflex_set_options.or_else(|| f!(abi::FEATURE_REFLEX, c"slReflexSetOptions", abi::SlReflexSetOptions));
+        functions.pcl_set_marker = functions.pcl_set_marker.or_else(|| f!(abi::FEATURE_PCL, c"slPCLSetMarker", abi::SlPclSetMarker));
+        functions.reflex_sleep = f!(abi::FEATURE_REFLEX, c"slReflexSleep", abi::SlReflexSleep);
+        functions.reflex_get_state = f!(abi::FEATURE_REFLEX, c"slReflexGetState", abi::SlReflexGetState);
+        if !plan.framegen {
+            log_version(sl, abi::FEATURE_REFLEX, "Reflex");
+        }
+        match (functions.reflex_set_options, functions.reflex_sleep, functions.pcl_set_marker) {
+            (Some(set_options), Some(_), Some(_)) => {
+                if !reflex_set {
+                    let options = reflex_options(mode.sl_mode());
+                    // SAFETY: filled options; nothing else calls the library yet.
+                    let code = unsafe { set_options(&options) };
+                    tracing::info!(code, result = abi::result_name(code), mode = mode.name(), "Streamline: Reflex options set (VICTORY_REFLEX)");
+                }
+                reflex_ready = true;

reflex_ready becomes true even when slReflexSetOptions fails, enabling title-thread sleeps and markers and logging Reflex as on despite the rejected mode. The earlier frame-generation setup also sets reflex_set after a failed call, causing this path to skip configuration. Carry the options call's success through both initialization paths and publish readiness only after success; otherwise warn and leave standalone Reflex disabled.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:review-comment:4732931869 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072#discussion_r4732931869). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-29T19:58:54Z. **Code review location:** `crates/victory-gpu/src/streamline.rs`; line 1388 ~~~~diff @@ -1280,21 +1365,70 @@ pub(crate) fn device_made(device: &ID3D12Device) -> Option<ID3D12CommandQueue> { tracing::warn!("DLSS Frame Generation stays off: the device hand-over to Streamline did not complete"); } } + // Reflex by itself (`VICTORY_REFLEX`): its functions whenever Streamline + // is loaded, with or without frame generation. + let mut reflex_ready = false; + if let Some(mode) = plan.reflex { + functions.reflex_set_options = + functions.reflex_set_options.or_else(|| f!(abi::FEATURE_REFLEX, c"slReflexSetOptions", abi::SlReflexSetOptions)); + functions.pcl_set_marker = functions.pcl_set_marker.or_else(|| f!(abi::FEATURE_PCL, c"slPCLSetMarker", abi::SlPclSetMarker)); + functions.reflex_sleep = f!(abi::FEATURE_REFLEX, c"slReflexSleep", abi::SlReflexSleep); + functions.reflex_get_state = f!(abi::FEATURE_REFLEX, c"slReflexGetState", abi::SlReflexGetState); + if !plan.framegen { + log_version(sl, abi::FEATURE_REFLEX, "Reflex"); + } + match (functions.reflex_set_options, functions.reflex_sleep, functions.pcl_set_marker) { + (Some(set_options), Some(_), Some(_)) => { + if !reflex_set { + let options = reflex_options(mode.sl_mode()); + // SAFETY: filled options; nothing else calls the library yet. + let code = unsafe { set_options(&options) }; + tracing::info!(code, result = abi::result_name(code), mode = mode.name(), "Streamline: Reflex options set (VICTORY_REFLEX)"); + } + reflex_ready = true; ~~~~ --- `reflex_ready` becomes true even when `slReflexSetOptions` fails, enabling title-thread sleeps and markers and logging Reflex as on despite the rejected mode. The earlier frame-generation setup also sets `reflex_set` after a failed call, causing this path to skip configuration. Carry the options call's success through both initialization paths and publish readiness only after success; otherwise warn and leave standalone Reflex disabled.
copilot-pull-request-reviewer[bot] commented 2026-11-29 19:58:54 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-29T19:58:54Z.

Review: COMMENTED


Repeated presents can consume the wrong simulation and move frame indexes backwards because pending and completed token mappings are lost, while failed Reflex configuration can still enable sleeps and markers.

3 open issues
What changed in this PR

Adds opt-in NVIDIA Reflex low latency with or without frame generation, extending the existing Streamline integration while preserving unset behavior.

Changes:

  • Adds VICTORY_REFLEX=on|boost and an F1 menu setting.
  • Connects input sampling, frame starts, submissions and presents through shared Reflex frame tracking.
  • Adds latency-report layouts, telemetry, sleep-duration safeguards and unit tests.
File Description
crates/​victory-hle/​src/​modules/​gameinput.rs Hooks input reads into Reflex pacing and markers.
crates/​victory-gpu/​src/​streamline/​reflex.rs Adds frame tracking, marker sequencing, latency calculations and tests.
crates/​victory-gpu/​src/​streamline/​abi.rs Defines Reflex report layouts and function signatures.
crates/​victory-gpu/​src/​streamline.rs Integrates Reflex initialization, tokens, sleeps, markers and telemetry.
crates/​victory-gpu/​src/​queue.rs Associates submissions and presents with title frame tokens.
crates/​victory-gpu/​src/​host/​menu.rs Adds Reflex OFF, ON and ON + BOOST settings.
crates/​victory-gpu/​src/​frame.rs Connects frame-origin waits to Reflex tracking and pacing.

Review effort: Balanced

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:review:6104542247 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072#pullrequestreview-6104542247). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-29T19:58:54Z. **Review:** COMMENTED --- <!-- ccr-overview-v2 --> ### 🟡 Changes recommended Repeated presents can consume the wrong simulation and move frame indexes backwards because pending and completed token mappings are lost, while failed Reflex configuration can still enable sleeps and markers. <details open> <summary><strong>3 open issues</strong></summary> - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Track every queued repeat present-to-index mapping](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072#discussion_r4732931845) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Retain completed origin-token mappings for repeats](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072#discussion_r4732931855) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Enable Reflex only after options are accepted](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072#discussion_r4732931869) · New </details> <details> <summary><strong>What changed in this PR</strong></summary> Adds opt-in NVIDIA Reflex low latency with or without frame generation, extending the existing Streamline integration while preserving unset behavior. **Changes:** - Adds `VICTORY_REFLEX=on|boost` and an F1 menu setting. - Connects input sampling, frame starts, submissions and presents through shared Reflex frame tracking. - Adds latency-report layouts, telemetry, sleep-duration safeguards and unit tests. | File | Description | | ---- | ----------- | | `crates/​victory-hle/​src/​modules/​gameinput.rs` | Hooks input reads into Reflex pacing and markers. | | `crates/​victory-gpu/​src/​streamline/​reflex.rs` | Adds frame tracking, marker sequencing, latency calculations and tests. | | `crates/​victory-gpu/​src/​streamline/​abi.rs` | Defines Reflex report layouts and function signatures. | | `crates/​victory-gpu/​src/​streamline.rs` | Integrates Reflex initialization, tokens, sleeps, markers and telemetry. | | `crates/​victory-gpu/​src/​queue.rs` | Associates submissions and presents with title frame tokens. | | `crates/​victory-gpu/​src/​host/​menu.rs` | Adds Reflex OFF, ON and ON + BOOST settings. | | `crates/​victory-gpu/​src/​frame.rs` | Connects frame-origin waits to Reflex tracking and pacing. | </details> <sub>Review effort: Balanced</sub>
Aniseto commented 2026-11-29 20:23:49 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Aniseto on 2026-11-29T20:23:49Z.


Ran the Reflex and related groups at 3e5f6c72 on an NVIDIA Blackwell desktop part.

System

  • GPU: NVIDIA GeForce RTX 5070 Ti (Blackwell, 32-lane waves only, mesh shaders), driver 32.0.16.2140 (621.40)
  • CPU: Intel Core i5-12400F, 64 GB RAM
  • OS: Windows 11 Pro build 26200 x64
  • Toolchain: Rust 1.98.1 (48a229cea 2026-09-01, pinned by rust-toolchain.toml), MSVC 14.44.35207, DXC 1.9.2609.5
  • Build: debug

Results

  • VICTORY_D3D12_ADAPTER=NVIDIA cargo test -p victory-gpu --lib --locked streamline:: -- --test-threads=1: 73 passed, 0 failed, 0 ignored.
  • ... queue::: 24 passed, 0 failed, 0 ignored.
  • ... frame::: 2 passed, 0 failed, 0 ignored.
  • ... host::menu::: 14 passed, 0 failed, 0 ignored. The menu save race the author reports on an RTX 4070 SUPER did not reproduce here.

What this adds
All four groups pass on an RTX 5070 Ti. This is the first datapoint from this card in the thread and adds driver 32.0.16.2140. These are CPU-side tests; no title latency was measured with VICTORY_REFLEX=on|boost, so no latency claim is made.

Not tested
A retail title, input-to-photon latency, a paired smoke run, the full workspace suite, AMD and Intel GPUs, native wave64 hosts, Wine, release profile, game data.

AI-assisted (OpenCode), model: DeepSeek V4.1 Flash Free - ran the commands above on this machine and wrote this report; no game data was used.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7262046222 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072#issuecomment-7262046222). Originally posted by [Aniseto](https://github.com/Aniseto) on 2026-11-29T20:23:49Z. --- Ran the Reflex and related groups at `3e5f6c72` on an NVIDIA Blackwell desktop part. **System** - GPU: NVIDIA GeForce RTX 5070 Ti (Blackwell, 32-lane waves only, mesh shaders), driver 32.0.16.2140 (621.40) - CPU: Intel Core i5-12400F, 64 GB RAM - OS: Windows 11 Pro build 26200 x64 - Toolchain: Rust 1.98.1 (48a229cea 2026-09-01, pinned by `rust-toolchain.toml`), MSVC 14.44.35207, DXC 1.9.2609.5 - Build: debug **Results** - `VICTORY_D3D12_ADAPTER=NVIDIA cargo test -p victory-gpu --lib --locked streamline:: -- --test-threads=1`: 73 passed, 0 failed, 0 ignored. - `... queue::`: 24 passed, 0 failed, 0 ignored. - `... frame::`: 2 passed, 0 failed, 0 ignored. - `... host::menu::`: 14 passed, 0 failed, 0 ignored. The menu save race the author reports on an RTX 4070 SUPER did not reproduce here. **What this adds** All four groups pass on an RTX 5070 Ti. This is the first datapoint from this card in the thread and adds driver 32.0.16.2140. These are CPU-side tests; no title latency was measured with `VICTORY_REFLEX=on|boost`, so no latency claim is made. **Not tested** A retail title, input-to-photon latency, a paired smoke run, the full workspace suite, AMD and Intel GPUs, native wave64 hosts, Wine, release profile, game data. AI-assisted (OpenCode), model: **DeepSeek V4.1 Flash Free** - ran the commands above on this machine and wrote this report; no game data was used.
Adriwin06 commented 2026-11-30 00:54:51 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Adriwin06 on 2026-11-30T00:54:51Z.

Code review location: crates/victory-gpu/src/streamline/reflex.rs; line 629

@@ -0,0 +1,1386 @@
+//! Reflex by itself (`VICTORY_REFLEX`), the part that needs no library: the
+//! switch, which latency markers a frame has sent and which it owes at each
+//! point of its life, where the Reflex sleep goes, and what the reports of a
+//! Reflex state average to.
+//!
+//! A Reflex frame is one index, and the Reflex sleep and every marker of it
+//! are given a frame token made from that index, on whichever thread they
+//! happen. [`Frames`] is what the threads share: who holds it decides, so a
+//! frame's markers leave in order and once each.
+//!
+//! Where a frame's index comes from. The title begins its frames with a wait
+//! for the frame origin (`crate::frame`), whose token it hands to the
+//! frame's submissions and its present. The runs with the first version of
+//! this (the sleep and the simulation start at that wait) showed the title
+//! reading its pad once a frame and after the frame's first submission (in
+//! the world 101 of 108 frames, and none before it): what a
+//! frame submits right after its origin wait is a simulation made before
+//! it, and the reading that follows is the input of a later frame's
+//! simulation. Which thread reads, the one that waits for the origin or
+//! another, the runs did not show; the ten-second line counts it. Either
+//! way the sleep and the simulation start belong at that reading, and the
+//! reading opens the simulation ([`Frames::sample`]): it gets a new index,
+//! the sleep is made there, and the next origin wait takes the simulation
+//! for its frame ([`Frames::begin`]), so that its token's submission ends
+//! that simulation and its present shows it. This assumes
+//! the title is one frame deep (the simulation read after frame N's first
+//! submission is the one frame N + 1 submits); nothing seen from outside
+//! the title can tell one frame deep from two. A title frame with no
+//! simulation to take gets an index of its own: with no sleep while most of
+//! the last [`HOLD`] frames took one (the title reads input nearly every
+//! frame, and this frame's reading was missed), else with the sleep at the
+//! origin wait, as before (loads, cutscenes, menus that read now and then or
+//! never).
+
+use super::abi;
+
+/// `VICTORY_REFLEX`: Reflex by itself, with or without frame generation.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Reflex {
+    /// `on` or `1`: low latency.
+    On,
+    /// `boost`: low latency with boost.
+    Boost,
+}
+
+impl Reflex {
+    /// The switch's value: unset, empty, `0` and `off` are no Reflex by
+    /// itself (everything as without the switch); any other word is an
+    /// error, as an unknown DLSS mode is.
+    pub fn from_switch(value: Option<&str>) -> Result<Option<Self>, String> {
+        let Some(value) = value else { return Ok(None) };
+        Ok(match value.trim().to_ascii_lowercase().as_str() {
+            "" | "0" | "off" => None,
+            "1" | "on" => Some(Reflex::On),
+            "boost" => Some(Reflex::Boost),
+            _ => return Err(format!("VICTORY_REFLEX={value}: not one of on, 1, boost, off, 0")),
+        })
+    }
+
+    pub fn name(self) -> &'static str {
+        match self {
+            Reflex::On => "on",
+            Reflex::Boost => "boost",
+        }
+    }
+
+    /// The `sl::ReflexMode` of the switch.
+    pub fn sl_mode(self) -> u32 {
+        match self {
+            Reflex::On => abi::REFLEX_LOW_LATENCY,
+            Reflex::Boost => abi::REFLEX_LOW_LATENCY_WITH_BOOST,
+        }
+    }
+}
+
+/// The points of a frame's life that have a marker, in the order a frame
+/// passes them.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Stage {
+    /// The Reflex sleep before the frame's simulation returned (at the
+    /// reading that opened it, or at the origin wait), or the frame began
+    /// with no sleep.
+    SimulationStart = 0,
+    /// The title asked for the pad or keyboard reading that opened the
+    /// frame's simulation.
+    InputSample = 1,
+    /// The title's first submission of command lists: its simulation is over
+    /// and its submissions begin.
+    SimulationEnd = 2,
+    SubmitStart = 3,
+    /// The present begins on the host.
+    SubmitEnd = 4,
+    PresentStart = 5,
+    PresentEnd = 6,
+}
+
+/// The `sl::PCLMarker` of each stage.
+const ORDER: [u32; 7] = [
+    abi::SIMULATION_START,
+    abi::CONTROLLER_INPUT_SAMPLE,
+    abi::SIMULATION_END,
+    abi::RENDER_SUBMIT_START,
+    abi::RENDER_SUBMIT_END,
+    abi::PRESENT_START,
+    abi::PRESENT_END,
+];
+
+const fn bit(stage: Stage) -> u8 {
+    1 << stage as u8
+}
+
+/// Markers to send now, as bits by stage.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Markers(u8);
+
+impl Markers {
+    pub fn is_empty(self) -> bool {
+        self.0 == 0
+    }
+
+    /// Their `sl::PCLMarker` values, in the order they are to be sent.
+    pub fn iter(self) -> impl Iterator<Item = u32> {
+        ORDER.iter().enumerate().filter(move |(stage, _)| self.0 & (1 << stage) != 0).map(|(_, &marker)| marker)
+    }
+}
+
+/// One frame that is not over yet.
+struct Frame {
+    /// The index its frame tokens are made from.
+    index: u32,
+    /// The token the title's origin wait gave it (0: no origin wait has it
+    /// yet, or the frame was made at a present the title began none for).
+    origin: u64,
+    /// The number of the title's present that shows it (0: none yet).
+    present: u64,
+    /// The stages whose markers were sent.
+    sent: u8,
+    /// A title's origin wait has it: it began the frame, or took the
+    /// simulation a reading opened. False for a simulation not taken yet
+    /// and for a frame made at a present.
+    begun: bool,
+    /// The thread of that origin wait, or of the reading that opened the
+    /// frame while none has it (0: none).
+    thread: u32,
+    /// When (microseconds, the caller's clock) the origin wait had it, or
+    /// the reading opened it while none has it.
+    at: u64,
+    /// The title submitted to a queue that draws for it, and when.
+    submitted: bool,
+    submitted_at: u64,
+}
+
+impl Frame {
+    fn has(&self, stage: Stage) -> bool {
+        self.sent & bit(stage) != 0
+    }
+
+    /// The frame's simulation began (its sleep is over): from here on the
+    /// title's submissions and presents may end it.
+    fn started(&self) -> bool {
+        self.has(Stage::SimulationStart)
+    }
+
+    /// The markers of every stage up to `stage` that were not sent, now
+    /// counted as sent. The input sample is never owed: it is sent with the
+    /// simulation's start at the reading that opened the frame, or not at
+    /// all. What was sent is always a run from the first stage on, so
+    /// nothing ever leaves out of order.
+    fn reach(&mut self, stage: Stage) -> Markers {
+        let up_to = (bit(stage) << 1).wrapping_sub(1);
+        let owed = up_to & !bit(Stage::InputSample) & !self.sent;
+        self.sent |= owed;
+        Markers(owed)
+    }
+}
+
+/// Microseconds between two events of a frame, over the frames that had
+/// both since the counts were last taken.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Gap {
+    pub count: u32,
+    pub sum_us: u64,
+    pub longest_us: u64,
+}
+
+impl Gap {
+    const ZERO: Gap = Gap { count: 0, sum_us: 0, longest_us: 0 };
+
+    fn add(&mut self, us: u64) {
+        self.count = self.count.saturating_add(1);
+        self.sum_us = self.sum_us.saturating_add(us);
+        self.longest_us = self.longest_us.max(us);
+    }
+
+    pub fn average_us(&self) -> u64 {
+        self.sum_us / u64::from(self.count.max(1))
+    }
+}
+
+/// What happened since the counts were last taken (the ten-second line).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Counts {
+    /// Frames the title began (origin waits that made a token).
+    pub begun: u32,
+    /// Of them: frames that took the simulation a reading opened, frames
+    /// with no simulation to take and no sleep (most of the last [`HOLD`]
+    /// frames took one), and frames with no simulation to take that slept
+    /// at the origin wait (fewer did).
+    pub adopted: u32,
+    pub unpaced: u32,
+    pub origin_sleeps: u32,
+    /// Frames whose simulation start and input sample were sent where the
+    /// reading's sleep returned.
+    pub sampled: u32,
+    /// Readings that opened a simulation (with its sleep), that belonged to
+    /// the one open, that came before the newest begun frame's simulation
+    /// ended at a submission (the frame still simulates, or is in its sleep
+    /// at the origin wait), and that came on another thread than the one
+    /// that opens simulations.
+    pub opened: u32,
+    pub belongs: u32,
+    pub held_back: u32,
+    pub other_thread: u32,
+    /// Simulations let go because a reading came while one was open and
+    /// no origin wait had taken it for [`Frames::stale_after_us`] (a load).
+    pub stale: u32,
+    /// Simulations whose frame was over or past its simulation's end when
+    /// the reading's sleep returned: no input sample was sent for them.
+    pub lost: u32,
+    /// Frames whose first submission came before their simulation started
+    /// (the opening reading was still in its sleep): that submission was of
+    /// a simulation before, so the title is deeper than one frame there.
+    pub submitted_before_start: u32,
+    /// Where things happened, by thread: \[0\] on the thread of the origin
+    /// wait of the frame concerned, \[1\] on another. For an opening
+    /// reading the frame is the newest begun one; for the first submission
+    /// and the title's present, the frame they are of.
+    pub openings_by_thread: [u32; 2],
+    pub first_submits_by_thread: [u32; 2],
+    pub presents_by_thread: [u32; 2],
+    /// From a frame's origin wait to its first submission; from the newest
+    /// begun frame's first submission to the reading that opens the next
+    /// simulation; from the opening (after its sleep) to the origin wait
+    /// that takes it.
+    pub origin_to_submit: Gap,
+    pub submit_to_open: Gap,
+    pub open_to_adopt: Gap,
+    /// Frames presented without a submission of the title's before.
+    pub unsubmitted: u32,
+    /// Presents the title began no frame for (a second present of one
+    /// frame's token among them).
+    pub unbegun: u32,
+    /// Presents that found their frame by the title's token, and by order.
+    pub by_token: u32,
+    pub by_order: u32,
+    /// Frames whose simulation was ended by a submission that named them
+    /// with the title's token, and by one that did not (no token, or one no
+    /// frame here has): the newest running frame was taken then, which is
+    /// the wrong one if the title still submits a frame after it began the
+    /// next.
+    pub submitted_by_token: u32,
+    pub submitted_by_order: u32,
+    /// Frames begun and never presented.
+    pub never_presented: u32,
+}
+
+impl Counts {
+    const ZERO: Counts = Counts {
+        begun: 0,
+        adopted: 0,
+        unpaced: 0,
+        origin_sleeps: 0,
+        sampled: 0,
+        opened: 0,
+        belongs: 0,
+        held_back: 0,
+        other_thread: 0,
+        stale: 0,
+        lost: 0,
+        submitted_before_start: 0,
+        openings_by_thread: [0; 2],
+        first_submits_by_thread: [0; 2],
+        presents_by_thread: [0; 2],
+        origin_to_submit: Gap::ZERO,
+        submit_to_open: Gap::ZERO,
+        open_to_adopt: Gap::ZERO,
+        unsubmitted: 0,
+        unbegun: 0,
+        by_token: 0,
+        by_order: 0,
+        submitted_by_token: 0,
+        submitted_by_order: 0,
+        never_presented: 0,
+    };
+}
+
+/// Where a title frame's simulation starts ([`Frames::begin`]).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Begin {
+    /// The frame took the simulation a reading opened, with this index: its
+    /// sleep and its start were the reading's, nothing is sent here.
+    Adopted(u32),
+    /// A frame of its own with no sleep (most of the last [`HOLD`] frames
+    /// took a simulation, just not this one): its start now.
+    Unpaced(u32),
+    /// A frame of its own that sleeps here first (the title reads input on
+    /// fewer frames than that, or none): its start where the sleep returns.
+    Paced(u32),
+}
+
+/// What the title asking for a reading is ([`Frames::sample`]).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Sample {
+    /// It opens a simulation with this index: the sleep is made now, on the
+    /// reading's thread, and then [`Frames::sampled`] says its markers.
+    Open(u32),
+    /// A simulation is open and this reading is part of it.
+    Belongs,
+    /// The newest begun frame's simulation has not ended at a submission
+    /// yet: the reading is of that simulation, or the frame is in its sleep
+    /// at the origin wait.
+    HeldBack,
+    /// Another thread opens simulations.
+    OtherThread,
+}
+
+/// The frames that are not over, oldest first, the last index given, and
+/// the simulation a reading opened that no origin wait has taken yet.
+pub(crate) struct Frames {
+    last: u32,
+    live: Vec<Frame>,
+    /// The index of the open simulation: always newer than every frame an
+    /// origin wait has (the next origin wait takes it instead of making a
+    /// frame of its own), so indexes stay in the order the title presents
+    /// its frames.
+    open: Option<u32>,
+    /// The thread that opened the last simulation (0: none yet).
+    sampler: u32,
+    /// Origin waits since the last simulation was opened (saturating; it
+    /// starts above [`HOLD`], so any thread may open the first one).
+    since_opened: u32,
+    /// Which of the last [`HOLD`] title frames took a simulation a reading
+    /// opened, one bit each, the newest lowest (none at first, so the first
+    /// frames sleep at the origin wait).
+    adopted_recently: u32,
+    /// When the last origin wait came, and how long before it the one
+    /// before came (microseconds, the caller's clock; 0 until two came).
+    begun_at: Option<u64>,
+    interval_us: u64,
+    /// The title's present that was a second present of one frame's token,
+    /// and that frame's index: the host's present of it shows that frame
+    /// again ([`Frames::presenting`]).
+    repeat: Option<(u64, u32)>,
+    counts: Counts,
+}
+
+/// Frames kept at most (Streamline expects no more than three in flight; the
+/// rest is room for frames the title begins and never presents).
+const KEPT: usize = 8;
+
+/// The title frames looked back on. A frame with no simulation to take goes
+/// without a sleep only when more than half of the last `HOLD` frames took
+/// one: the title reads input nearly every frame and missed this one (in
+/// the world about one frame in fifteen had no reading counted), and a
+/// sleep at the origin wait would hold back a finished frame again. Where
+/// the title reads input on fewer frames (a menu that reads every tenth),
+/// its other frames sleep at the origin wait as they did before readings
+/// were looked at: Reflex's guide has `slReflexSleep` called always, and
+/// whether its pacing or frame generation's bears frames with no sleep the
+/// guides on disk do not say. Also the frames after which another thread
+/// may open simulations. Eight frames is a third of a second to two seconds
+/// in the world (4 to 28 frames a second there) and a few milliseconds in
+/// the menus.
+pub(crate) const HOLD: u32 = 8;
+const _: () = assert!(HOLD > 0 && HOLD <= u32::BITS);
+
+/// An open simulation is let go when a reading comes and no origin wait has
+/// taken it for this many microseconds or for [`STALE_FRAMES`] times the
+/// last interval between origin waits, whichever is longer: the title read
+/// input and began no frame (a load), and the reading opens a new one. A
+/// fixed bound alone let every simulation go in the world's slow stretches,
+/// where the origin wait that takes a simulation comes 80 to 370 ms after
+/// the reading that opened it.
+pub(crate) const STALE_US: u64 = 250_000;
+pub(crate) const STALE_FRAMES: u64 = 4;
+
+impl Frames {
+    pub const fn new() -> Self {
+        Frames {
+            last: 0,
+            live: Vec::new(),
+            open: None,
+            sampler: 0,
+            since_opened: u32::MAX,
+            adopted_recently: 0,
+            begun_at: None,
+            interval_us: 0,
+            repeat: None,
+            counts: Counts::ZERO,
+        }
+    }
+
+    /// How long an open simulation may wait for its origin wait while
+    /// readings come, in microseconds ([`STALE_US`]).
+    pub fn stale_after_us(&self) -> u64 {
+        STALE_US.max(self.interval_us.saturating_mul(STALE_FRAMES))
+    }
+
+    /// A new frame with the next index (indexes count from 1 and wrap).
+    fn push(&mut self, origin: u64, present: u64, begun: bool, thread: u32, at: u64) -> u32 {
+        // The oldest goes if the title begins frames it never presents.
+        // (Never the open simulation: it is the newest, and KEPT is above 1.)
+        if self.live.len() >= KEPT {
+            self.live.remove(0);
+            self.counts.never_presented += 1;
+        }
+        self.last = self.last.wrapping_add(1);
+        self.live.push(Frame {
+            index: self.last,
+            origin,
+            present,
+            sent: 0,
+            begun,
+            thread,
+            at,
+            submitted: false,
+            submitted_at: 0,
+        });
+        self.last
+    }
+
+    /// The open simulation is let go if no origin wait took it within
+    /// [`Frames::stale_after_us`] (`now` is the caller's clock, as at the
+    /// opening). Only a reading asks this: the origin wait that comes always
+    /// takes the open simulation, however long after, since that is the
+    /// frame that submits it.
+    fn let_go_stale(&mut self, now: u64) {
+        let Some(index) = self.open else { return };
+        let Some(at) = self.live.iter().position(|f| f.index == index) else {
+            self.open = None;
+            return;
+        };
+        if now.saturating_sub(self.live[at].at) > self.stale_after_us() {
+            self.live.remove(at);
+            self.open = None;
+            self.counts.stale += 1;
+        }
+    }
+
+    /// The title begins a frame on `thread` at `now`: its origin wait made
+    /// token `origin`. The frame takes the open simulation if there is one,
+    /// else it gets an index of its own, with or without a sleep here.
+    pub fn begin(&mut self, origin: u64, thread: u32, now: u64) -> Begin {
+        self.counts.begun += 1;
+        // The interval between origin waits, for how long an open
+        // simulation may wait for one while readings come.
+        if let Some(before) = self.begun_at {
+            self.interval_us = now.saturating_sub(before);
+        }
+        self.begun_at = Some(now);
+        self.since_opened = self.since_opened.saturating_add(1);
+        // The frames before this one that took a simulation; this one's bit
+        // is set below if it takes one.
+        let window = u32::MAX >> (u32::BITS - HOLD);
+        let took_before = (self.adopted_recently & window).count_ones();
+        self.adopted_recently = (self.adopted_recently << 1) & window;
+        // No time bound here: the simulation open now is the one this frame
+        // submits, whether the frame came 3 ms or 370 ms after its reading.
+        if let Some(index) = self.open.take()
+            && let Some(frame) = self.live.iter_mut().find(|f| f.index == index)
+        {
+            self.counts.open_to_adopt.add(now.saturating_sub(frame.at));
+            frame.origin = origin;
+            frame.begun = true;
+            frame.thread = thread;
+            frame.at = now;
+            self.counts.adopted += 1;
+            self.adopted_recently |= 1;
+            return Begin::Adopted(index);
+        }
+        let index = self.push(origin, 0, true, thread, now);
+        if took_before > HOLD / 2 {
+            self.counts.unpaced += 1;
+            Begin::Unpaced(index)
+        } else {
+            self.counts.origin_sleeps += 1;
+            Begin::Paced(index)
+        }
+    }
+
+    /// The markers frame `index` owes up to `stage`, now sent; none if the
+    /// frame is over.
+    pub fn reach(&mut self, index: u32, stage: Stage) -> Markers {
+        self.live.iter_mut().find(|f| f.index == index).map_or(Markers(0), |f| f.reach(stage))
+    }
+
+    /// The title asks for a pad or keyboard reading on `thread` at `now`,
+    /// before the reading is picked. It opens a simulation only when none
+    /// is open, the newest begun frame's simulation has ended at its
+    /// submission (or it has its present, or there is no begun frame), and
+    /// the thread is the one that opens them (or
+    /// that one has not for more than [`HOLD`] frames). So at most one
+    /// simulation opens between two origin waits, one sleep is made for
+    /// it, and it never runs while a sleep at the origin wait does (that
+    /// frame has not submitted yet). A simulation that waited too long for
+    /// its origin wait ([`Frames::stale_after_us`]) is let go first, and the
+    /// reading opens another.
+    pub fn sample(&mut self, thread: u32, now: u64) -> Sample {
+        self.let_go_stale(now);
+        if self.sampler != 0 && self.sampler != thread && self.since_opened <= HOLD {
+            self.counts.other_thread += 1;
+            return Sample::OtherThread;
+        }
+        if self.open.is_some() {
+            self.counts.belongs += 1;
+            return Sample::Belongs;
+        }
+        let newest = self.live.iter().rev().find(|f| f.begun);
+        if let Some(frame) = newest {
+            // (Its simulation's end, not its first submission: a submission
+            // that came while the opening reading still slept ended nothing,
+            // and the readings of that simulation must not open another.)
+            if !frame.has(Stage::SimulationEnd) && frame.present == 0 {
+                self.counts.held_back += 1;
+                return Sample::HeldBack;
+            }
+            // Which thread reads, against the one that begins frames; and
+            // how long after that frame's first submission.
+            self.counts.openings_by_thread[usize::from(frame.thread != thread)] += 1;
+            if frame.submitted {
+                self.counts.submit_to_open.add(now.saturating_sub(frame.submitted_at));
+            }
+        }
+        let index = self.push(0, 0, false, thread, now);
+        self.open = Some(index);
+        self.sampler = thread;
+        self.since_opened = 0;
+        self.counts.opened += 1;
+        Sample::Open(index)
+    }
+
+    /// The sleep of the simulation `index` opened returned at `now`: its
+    /// simulation start and its input sample, now sent; none if the frame
+    /// is over or its present already sent its simulation's markers (the
+    /// sample is lost then, and counted).
+    pub fn sampled(&mut self, index: u32, now: u64) -> Markers {
+        let Some(frame) = self.live.iter_mut().find(|f| f.index == index) else {
+            self.counts.lost += 1;
+            return Markers(0);
+        };
+        if frame.started() {
+            self.counts.lost += 1;
+            return Markers(0);
+        }
+        // While no origin wait has it, the opening counts from here (the
+        // gap to the adoption is measured after the sleep).
+        if !frame.begun {
+            frame.at = frame.at.max(now);
+        }
+        let owed = bit(Stage::SimulationStart) | bit(Stage::InputSample);
+        frame.sent |= owed;
+        self.counts.sampled += 1;
+        Markers(owed)
+    }
+
+    /// The title submits command lists to a queue that draws, on `thread`
+    /// at `now`, tagged with frame token `origin` (0: not tagged): at the
+    /// frame's first submission its simulation ends and its submissions
+    /// begin. The frame is the one of that token, else the newest begun
+    /// frame whose simulation runs and whose present the title has not
+    /// called (never a simulation no origin wait has taken). Which of the
+    /// two ended a frame's simulation is counted, for the line.
+    pub fn submit(&mut self, origin: u64, thread: u32, now: u64) -> Option<(u32, Markers)> {
+        let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten();
+        let at = match tagged {
+            Some(at) => at,
+            None => self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0)?,
+        };
+        let frame = &mut self.live[at];
+        let first = !frame.submitted;
+        if first {
+            frame.submitted = true;
+            frame.submitted_at = now;
+            self.counts.first_submits_by_thread[usize::from(frame.thread != thread)] += 1;
+            self.counts.origin_to_submit.add(now.saturating_sub(frame.at));
+        }
+        // A frame still in its sleep has no simulation to end. (At the
+        // origin wait that cannot be: the title has not got the token yet.
+        // At a reading it means this submission is of a simulation before.)
+        if !frame.started() {
+            if first {
+                self.counts.submitted_before_start += 1;
+            }
+            return None;
+        }
+        let owed = frame.reach(Stage::SubmitStart);
+        // Later submissions of the frame owe nothing and count nothing.
+        if owed.is_empty() {
+            return None;
+        }
+        // Counted where it has an effect: this submission is the one that
+        // ends the frame's simulation.
+        match tagged {
+            Some(_) => self.counts.submitted_by_token += 1,
+            None => self.counts.submitted_by_order += 1,
+        }
+        Some((frame.index, owed))
+    }
+
+    /// The title calls its present number `present` (counted from 1) on
+    /// `thread` with frame token `origin` in its first plane (0: none): the
+    /// present is that frame's, else the newest begun frame's whose
+    /// simulation runs and that has no present yet. Frames begun before it
+    /// that have none are over: the title never presented them. (By the
+    /// token the frame need not have started: a simulation whose reading is
+    /// still in its sleep may be presented, and then sends what it owes at
+    /// the present.)
+    pub fn title_presents(&mut self, present: u64, origin: u64, thread: u32) {
+        let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten();
+        let at = match tagged {
+            Some(at) if self.live[at].present == 0 => {
+                self.counts.by_token += 1;
+                at
+            }
+            // The token's frame has its present: this one shows that frame
+            // again, and the host's present of it names that frame's index
+            // ([`Frames::presenting`]).
+            Some(at) => {
+                self.repeat = Some((present, self.live[at].index));

Fixed in c5cd5410: further presents now wait in KEPT places (one per repeat), each consumed only by its own host present. Regression test: queued_further_presents_of_one_frame_each_show_that_frame (three queued repeats with simulation 2 open give [1, 1, 1] and leave simulation 2 for the next frame).

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:review-comment:4734026858 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072#discussion_r4734026858). Originally posted by [Adriwin06](https://github.com/Adriwin06) on 2026-11-30T00:54:51Z. **Code review location:** `crates/victory-gpu/src/streamline/reflex.rs`; line 629 ~~~~diff @@ -0,0 +1,1386 @@ +//! Reflex by itself (`VICTORY_REFLEX`), the part that needs no library: the +//! switch, which latency markers a frame has sent and which it owes at each +//! point of its life, where the Reflex sleep goes, and what the reports of a +//! Reflex state average to. +//! +//! A Reflex frame is one index, and the Reflex sleep and every marker of it +//! are given a frame token made from that index, on whichever thread they +//! happen. [`Frames`] is what the threads share: who holds it decides, so a +//! frame's markers leave in order and once each. +//! +//! Where a frame's index comes from. The title begins its frames with a wait +//! for the frame origin (`crate::frame`), whose token it hands to the +//! frame's submissions and its present. The runs with the first version of +//! this (the sleep and the simulation start at that wait) showed the title +//! reading its pad once a frame and after the frame's first submission (in +//! the world 101 of 108 frames, and none before it): what a +//! frame submits right after its origin wait is a simulation made before +//! it, and the reading that follows is the input of a later frame's +//! simulation. Which thread reads, the one that waits for the origin or +//! another, the runs did not show; the ten-second line counts it. Either +//! way the sleep and the simulation start belong at that reading, and the +//! reading opens the simulation ([`Frames::sample`]): it gets a new index, +//! the sleep is made there, and the next origin wait takes the simulation +//! for its frame ([`Frames::begin`]), so that its token's submission ends +//! that simulation and its present shows it. This assumes +//! the title is one frame deep (the simulation read after frame N's first +//! submission is the one frame N + 1 submits); nothing seen from outside +//! the title can tell one frame deep from two. A title frame with no +//! simulation to take gets an index of its own: with no sleep while most of +//! the last [`HOLD`] frames took one (the title reads input nearly every +//! frame, and this frame's reading was missed), else with the sleep at the +//! origin wait, as before (loads, cutscenes, menus that read now and then or +//! never). + +use super::abi; + +/// `VICTORY_REFLEX`: Reflex by itself, with or without frame generation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reflex { + /// `on` or `1`: low latency. + On, + /// `boost`: low latency with boost. + Boost, +} + +impl Reflex { + /// The switch's value: unset, empty, `0` and `off` are no Reflex by + /// itself (everything as without the switch); any other word is an + /// error, as an unknown DLSS mode is. + pub fn from_switch(value: Option<&str>) -> Result<Option<Self>, String> { + let Some(value) = value else { return Ok(None) }; + Ok(match value.trim().to_ascii_lowercase().as_str() { + "" | "0" | "off" => None, + "1" | "on" => Some(Reflex::On), + "boost" => Some(Reflex::Boost), + _ => return Err(format!("VICTORY_REFLEX={value}: not one of on, 1, boost, off, 0")), + }) + } + + pub fn name(self) -> &'static str { + match self { + Reflex::On => "on", + Reflex::Boost => "boost", + } + } + + /// The `sl::ReflexMode` of the switch. + pub fn sl_mode(self) -> u32 { + match self { + Reflex::On => abi::REFLEX_LOW_LATENCY, + Reflex::Boost => abi::REFLEX_LOW_LATENCY_WITH_BOOST, + } + } +} + +/// The points of a frame's life that have a marker, in the order a frame +/// passes them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Stage { + /// The Reflex sleep before the frame's simulation returned (at the + /// reading that opened it, or at the origin wait), or the frame began + /// with no sleep. + SimulationStart = 0, + /// The title asked for the pad or keyboard reading that opened the + /// frame's simulation. + InputSample = 1, + /// The title's first submission of command lists: its simulation is over + /// and its submissions begin. + SimulationEnd = 2, + SubmitStart = 3, + /// The present begins on the host. + SubmitEnd = 4, + PresentStart = 5, + PresentEnd = 6, +} + +/// The `sl::PCLMarker` of each stage. +const ORDER: [u32; 7] = [ + abi::SIMULATION_START, + abi::CONTROLLER_INPUT_SAMPLE, + abi::SIMULATION_END, + abi::RENDER_SUBMIT_START, + abi::RENDER_SUBMIT_END, + abi::PRESENT_START, + abi::PRESENT_END, +]; + +const fn bit(stage: Stage) -> u8 { + 1 << stage as u8 +} + +/// Markers to send now, as bits by stage. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Markers(u8); + +impl Markers { + pub fn is_empty(self) -> bool { + self.0 == 0 + } + + /// Their `sl::PCLMarker` values, in the order they are to be sent. + pub fn iter(self) -> impl Iterator<Item = u32> { + ORDER.iter().enumerate().filter(move |(stage, _)| self.0 & (1 << stage) != 0).map(|(_, &marker)| marker) + } +} + +/// One frame that is not over yet. +struct Frame { + /// The index its frame tokens are made from. + index: u32, + /// The token the title's origin wait gave it (0: no origin wait has it + /// yet, or the frame was made at a present the title began none for). + origin: u64, + /// The number of the title's present that shows it (0: none yet). + present: u64, + /// The stages whose markers were sent. + sent: u8, + /// A title's origin wait has it: it began the frame, or took the + /// simulation a reading opened. False for a simulation not taken yet + /// and for a frame made at a present. + begun: bool, + /// The thread of that origin wait, or of the reading that opened the + /// frame while none has it (0: none). + thread: u32, + /// When (microseconds, the caller's clock) the origin wait had it, or + /// the reading opened it while none has it. + at: u64, + /// The title submitted to a queue that draws for it, and when. + submitted: bool, + submitted_at: u64, +} + +impl Frame { + fn has(&self, stage: Stage) -> bool { + self.sent & bit(stage) != 0 + } + + /// The frame's simulation began (its sleep is over): from here on the + /// title's submissions and presents may end it. + fn started(&self) -> bool { + self.has(Stage::SimulationStart) + } + + /// The markers of every stage up to `stage` that were not sent, now + /// counted as sent. The input sample is never owed: it is sent with the + /// simulation's start at the reading that opened the frame, or not at + /// all. What was sent is always a run from the first stage on, so + /// nothing ever leaves out of order. + fn reach(&mut self, stage: Stage) -> Markers { + let up_to = (bit(stage) << 1).wrapping_sub(1); + let owed = up_to & !bit(Stage::InputSample) & !self.sent; + self.sent |= owed; + Markers(owed) + } +} + +/// Microseconds between two events of a frame, over the frames that had +/// both since the counts were last taken. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Gap { + pub count: u32, + pub sum_us: u64, + pub longest_us: u64, +} + +impl Gap { + const ZERO: Gap = Gap { count: 0, sum_us: 0, longest_us: 0 }; + + fn add(&mut self, us: u64) { + self.count = self.count.saturating_add(1); + self.sum_us = self.sum_us.saturating_add(us); + self.longest_us = self.longest_us.max(us); + } + + pub fn average_us(&self) -> u64 { + self.sum_us / u64::from(self.count.max(1)) + } +} + +/// What happened since the counts were last taken (the ten-second line). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Counts { + /// Frames the title began (origin waits that made a token). + pub begun: u32, + /// Of them: frames that took the simulation a reading opened, frames + /// with no simulation to take and no sleep (most of the last [`HOLD`] + /// frames took one), and frames with no simulation to take that slept + /// at the origin wait (fewer did). + pub adopted: u32, + pub unpaced: u32, + pub origin_sleeps: u32, + /// Frames whose simulation start and input sample were sent where the + /// reading's sleep returned. + pub sampled: u32, + /// Readings that opened a simulation (with its sleep), that belonged to + /// the one open, that came before the newest begun frame's simulation + /// ended at a submission (the frame still simulates, or is in its sleep + /// at the origin wait), and that came on another thread than the one + /// that opens simulations. + pub opened: u32, + pub belongs: u32, + pub held_back: u32, + pub other_thread: u32, + /// Simulations let go because a reading came while one was open and + /// no origin wait had taken it for [`Frames::stale_after_us`] (a load). + pub stale: u32, + /// Simulations whose frame was over or past its simulation's end when + /// the reading's sleep returned: no input sample was sent for them. + pub lost: u32, + /// Frames whose first submission came before their simulation started + /// (the opening reading was still in its sleep): that submission was of + /// a simulation before, so the title is deeper than one frame there. + pub submitted_before_start: u32, + /// Where things happened, by thread: \[0\] on the thread of the origin + /// wait of the frame concerned, \[1\] on another. For an opening + /// reading the frame is the newest begun one; for the first submission + /// and the title's present, the frame they are of. + pub openings_by_thread: [u32; 2], + pub first_submits_by_thread: [u32; 2], + pub presents_by_thread: [u32; 2], + /// From a frame's origin wait to its first submission; from the newest + /// begun frame's first submission to the reading that opens the next + /// simulation; from the opening (after its sleep) to the origin wait + /// that takes it. + pub origin_to_submit: Gap, + pub submit_to_open: Gap, + pub open_to_adopt: Gap, + /// Frames presented without a submission of the title's before. + pub unsubmitted: u32, + /// Presents the title began no frame for (a second present of one + /// frame's token among them). + pub unbegun: u32, + /// Presents that found their frame by the title's token, and by order. + pub by_token: u32, + pub by_order: u32, + /// Frames whose simulation was ended by a submission that named them + /// with the title's token, and by one that did not (no token, or one no + /// frame here has): the newest running frame was taken then, which is + /// the wrong one if the title still submits a frame after it began the + /// next. + pub submitted_by_token: u32, + pub submitted_by_order: u32, + /// Frames begun and never presented. + pub never_presented: u32, +} + +impl Counts { + const ZERO: Counts = Counts { + begun: 0, + adopted: 0, + unpaced: 0, + origin_sleeps: 0, + sampled: 0, + opened: 0, + belongs: 0, + held_back: 0, + other_thread: 0, + stale: 0, + lost: 0, + submitted_before_start: 0, + openings_by_thread: [0; 2], + first_submits_by_thread: [0; 2], + presents_by_thread: [0; 2], + origin_to_submit: Gap::ZERO, + submit_to_open: Gap::ZERO, + open_to_adopt: Gap::ZERO, + unsubmitted: 0, + unbegun: 0, + by_token: 0, + by_order: 0, + submitted_by_token: 0, + submitted_by_order: 0, + never_presented: 0, + }; +} + +/// Where a title frame's simulation starts ([`Frames::begin`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Begin { + /// The frame took the simulation a reading opened, with this index: its + /// sleep and its start were the reading's, nothing is sent here. + Adopted(u32), + /// A frame of its own with no sleep (most of the last [`HOLD`] frames + /// took a simulation, just not this one): its start now. + Unpaced(u32), + /// A frame of its own that sleeps here first (the title reads input on + /// fewer frames than that, or none): its start where the sleep returns. + Paced(u32), +} + +/// What the title asking for a reading is ([`Frames::sample`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Sample { + /// It opens a simulation with this index: the sleep is made now, on the + /// reading's thread, and then [`Frames::sampled`] says its markers. + Open(u32), + /// A simulation is open and this reading is part of it. + Belongs, + /// The newest begun frame's simulation has not ended at a submission + /// yet: the reading is of that simulation, or the frame is in its sleep + /// at the origin wait. + HeldBack, + /// Another thread opens simulations. + OtherThread, +} + +/// The frames that are not over, oldest first, the last index given, and +/// the simulation a reading opened that no origin wait has taken yet. +pub(crate) struct Frames { + last: u32, + live: Vec<Frame>, + /// The index of the open simulation: always newer than every frame an + /// origin wait has (the next origin wait takes it instead of making a + /// frame of its own), so indexes stay in the order the title presents + /// its frames. + open: Option<u32>, + /// The thread that opened the last simulation (0: none yet). + sampler: u32, + /// Origin waits since the last simulation was opened (saturating; it + /// starts above [`HOLD`], so any thread may open the first one). + since_opened: u32, + /// Which of the last [`HOLD`] title frames took a simulation a reading + /// opened, one bit each, the newest lowest (none at first, so the first + /// frames sleep at the origin wait). + adopted_recently: u32, + /// When the last origin wait came, and how long before it the one + /// before came (microseconds, the caller's clock; 0 until two came). + begun_at: Option<u64>, + interval_us: u64, + /// The title's present that was a second present of one frame's token, + /// and that frame's index: the host's present of it shows that frame + /// again ([`Frames::presenting`]). + repeat: Option<(u64, u32)>, + counts: Counts, +} + +/// Frames kept at most (Streamline expects no more than three in flight; the +/// rest is room for frames the title begins and never presents). +const KEPT: usize = 8; + +/// The title frames looked back on. A frame with no simulation to take goes +/// without a sleep only when more than half of the last `HOLD` frames took +/// one: the title reads input nearly every frame and missed this one (in +/// the world about one frame in fifteen had no reading counted), and a +/// sleep at the origin wait would hold back a finished frame again. Where +/// the title reads input on fewer frames (a menu that reads every tenth), +/// its other frames sleep at the origin wait as they did before readings +/// were looked at: Reflex's guide has `slReflexSleep` called always, and +/// whether its pacing or frame generation's bears frames with no sleep the +/// guides on disk do not say. Also the frames after which another thread +/// may open simulations. Eight frames is a third of a second to two seconds +/// in the world (4 to 28 frames a second there) and a few milliseconds in +/// the menus. +pub(crate) const HOLD: u32 = 8; +const _: () = assert!(HOLD > 0 && HOLD <= u32::BITS); + +/// An open simulation is let go when a reading comes and no origin wait has +/// taken it for this many microseconds or for [`STALE_FRAMES`] times the +/// last interval between origin waits, whichever is longer: the title read +/// input and began no frame (a load), and the reading opens a new one. A +/// fixed bound alone let every simulation go in the world's slow stretches, +/// where the origin wait that takes a simulation comes 80 to 370 ms after +/// the reading that opened it. +pub(crate) const STALE_US: u64 = 250_000; +pub(crate) const STALE_FRAMES: u64 = 4; + +impl Frames { + pub const fn new() -> Self { + Frames { + last: 0, + live: Vec::new(), + open: None, + sampler: 0, + since_opened: u32::MAX, + adopted_recently: 0, + begun_at: None, + interval_us: 0, + repeat: None, + counts: Counts::ZERO, + } + } + + /// How long an open simulation may wait for its origin wait while + /// readings come, in microseconds ([`STALE_US`]). + pub fn stale_after_us(&self) -> u64 { + STALE_US.max(self.interval_us.saturating_mul(STALE_FRAMES)) + } + + /// A new frame with the next index (indexes count from 1 and wrap). + fn push(&mut self, origin: u64, present: u64, begun: bool, thread: u32, at: u64) -> u32 { + // The oldest goes if the title begins frames it never presents. + // (Never the open simulation: it is the newest, and KEPT is above 1.) + if self.live.len() >= KEPT { + self.live.remove(0); + self.counts.never_presented += 1; + } + self.last = self.last.wrapping_add(1); + self.live.push(Frame { + index: self.last, + origin, + present, + sent: 0, + begun, + thread, + at, + submitted: false, + submitted_at: 0, + }); + self.last + } + + /// The open simulation is let go if no origin wait took it within + /// [`Frames::stale_after_us`] (`now` is the caller's clock, as at the + /// opening). Only a reading asks this: the origin wait that comes always + /// takes the open simulation, however long after, since that is the + /// frame that submits it. + fn let_go_stale(&mut self, now: u64) { + let Some(index) = self.open else { return }; + let Some(at) = self.live.iter().position(|f| f.index == index) else { + self.open = None; + return; + }; + if now.saturating_sub(self.live[at].at) > self.stale_after_us() { + self.live.remove(at); + self.open = None; + self.counts.stale += 1; + } + } + + /// The title begins a frame on `thread` at `now`: its origin wait made + /// token `origin`. The frame takes the open simulation if there is one, + /// else it gets an index of its own, with or without a sleep here. + pub fn begin(&mut self, origin: u64, thread: u32, now: u64) -> Begin { + self.counts.begun += 1; + // The interval between origin waits, for how long an open + // simulation may wait for one while readings come. + if let Some(before) = self.begun_at { + self.interval_us = now.saturating_sub(before); + } + self.begun_at = Some(now); + self.since_opened = self.since_opened.saturating_add(1); + // The frames before this one that took a simulation; this one's bit + // is set below if it takes one. + let window = u32::MAX >> (u32::BITS - HOLD); + let took_before = (self.adopted_recently & window).count_ones(); + self.adopted_recently = (self.adopted_recently << 1) & window; + // No time bound here: the simulation open now is the one this frame + // submits, whether the frame came 3 ms or 370 ms after its reading. + if let Some(index) = self.open.take() + && let Some(frame) = self.live.iter_mut().find(|f| f.index == index) + { + self.counts.open_to_adopt.add(now.saturating_sub(frame.at)); + frame.origin = origin; + frame.begun = true; + frame.thread = thread; + frame.at = now; + self.counts.adopted += 1; + self.adopted_recently |= 1; + return Begin::Adopted(index); + } + let index = self.push(origin, 0, true, thread, now); + if took_before > HOLD / 2 { + self.counts.unpaced += 1; + Begin::Unpaced(index) + } else { + self.counts.origin_sleeps += 1; + Begin::Paced(index) + } + } + + /// The markers frame `index` owes up to `stage`, now sent; none if the + /// frame is over. + pub fn reach(&mut self, index: u32, stage: Stage) -> Markers { + self.live.iter_mut().find(|f| f.index == index).map_or(Markers(0), |f| f.reach(stage)) + } + + /// The title asks for a pad or keyboard reading on `thread` at `now`, + /// before the reading is picked. It opens a simulation only when none + /// is open, the newest begun frame's simulation has ended at its + /// submission (or it has its present, or there is no begun frame), and + /// the thread is the one that opens them (or + /// that one has not for more than [`HOLD`] frames). So at most one + /// simulation opens between two origin waits, one sleep is made for + /// it, and it never runs while a sleep at the origin wait does (that + /// frame has not submitted yet). A simulation that waited too long for + /// its origin wait ([`Frames::stale_after_us`]) is let go first, and the + /// reading opens another. + pub fn sample(&mut self, thread: u32, now: u64) -> Sample { + self.let_go_stale(now); + if self.sampler != 0 && self.sampler != thread && self.since_opened <= HOLD { + self.counts.other_thread += 1; + return Sample::OtherThread; + } + if self.open.is_some() { + self.counts.belongs += 1; + return Sample::Belongs; + } + let newest = self.live.iter().rev().find(|f| f.begun); + if let Some(frame) = newest { + // (Its simulation's end, not its first submission: a submission + // that came while the opening reading still slept ended nothing, + // and the readings of that simulation must not open another.) + if !frame.has(Stage::SimulationEnd) && frame.present == 0 { + self.counts.held_back += 1; + return Sample::HeldBack; + } + // Which thread reads, against the one that begins frames; and + // how long after that frame's first submission. + self.counts.openings_by_thread[usize::from(frame.thread != thread)] += 1; + if frame.submitted { + self.counts.submit_to_open.add(now.saturating_sub(frame.submitted_at)); + } + } + let index = self.push(0, 0, false, thread, now); + self.open = Some(index); + self.sampler = thread; + self.since_opened = 0; + self.counts.opened += 1; + Sample::Open(index) + } + + /// The sleep of the simulation `index` opened returned at `now`: its + /// simulation start and its input sample, now sent; none if the frame + /// is over or its present already sent its simulation's markers (the + /// sample is lost then, and counted). + pub fn sampled(&mut self, index: u32, now: u64) -> Markers { + let Some(frame) = self.live.iter_mut().find(|f| f.index == index) else { + self.counts.lost += 1; + return Markers(0); + }; + if frame.started() { + self.counts.lost += 1; + return Markers(0); + } + // While no origin wait has it, the opening counts from here (the + // gap to the adoption is measured after the sleep). + if !frame.begun { + frame.at = frame.at.max(now); + } + let owed = bit(Stage::SimulationStart) | bit(Stage::InputSample); + frame.sent |= owed; + self.counts.sampled += 1; + Markers(owed) + } + + /// The title submits command lists to a queue that draws, on `thread` + /// at `now`, tagged with frame token `origin` (0: not tagged): at the + /// frame's first submission its simulation ends and its submissions + /// begin. The frame is the one of that token, else the newest begun + /// frame whose simulation runs and whose present the title has not + /// called (never a simulation no origin wait has taken). Which of the + /// two ended a frame's simulation is counted, for the line. + pub fn submit(&mut self, origin: u64, thread: u32, now: u64) -> Option<(u32, Markers)> { + let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten(); + let at = match tagged { + Some(at) => at, + None => self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0)?, + }; + let frame = &mut self.live[at]; + let first = !frame.submitted; + if first { + frame.submitted = true; + frame.submitted_at = now; + self.counts.first_submits_by_thread[usize::from(frame.thread != thread)] += 1; + self.counts.origin_to_submit.add(now.saturating_sub(frame.at)); + } + // A frame still in its sleep has no simulation to end. (At the + // origin wait that cannot be: the title has not got the token yet. + // At a reading it means this submission is of a simulation before.) + if !frame.started() { + if first { + self.counts.submitted_before_start += 1; + } + return None; + } + let owed = frame.reach(Stage::SubmitStart); + // Later submissions of the frame owe nothing and count nothing. + if owed.is_empty() { + return None; + } + // Counted where it has an effect: this submission is the one that + // ends the frame's simulation. + match tagged { + Some(_) => self.counts.submitted_by_token += 1, + None => self.counts.submitted_by_order += 1, + } + Some((frame.index, owed)) + } + + /// The title calls its present number `present` (counted from 1) on + /// `thread` with frame token `origin` in its first plane (0: none): the + /// present is that frame's, else the newest begun frame's whose + /// simulation runs and that has no present yet. Frames begun before it + /// that have none are over: the title never presented them. (By the + /// token the frame need not have started: a simulation whose reading is + /// still in its sleep may be presented, and then sends what it owes at + /// the present.) + pub fn title_presents(&mut self, present: u64, origin: u64, thread: u32) { + let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten(); + let at = match tagged { + Some(at) if self.live[at].present == 0 => { + self.counts.by_token += 1; + at + } + // The token's frame has its present: this one shows that frame + // again, and the host's present of it names that frame's index + // ([`Frames::presenting`]). + Some(at) => { + self.repeat = Some((present, self.live[at].index)); ~~~~ --- Fixed in c5cd5410: further presents now wait in `KEPT` places (one per repeat), each consumed only by its own host present. Regression test: `queued_further_presents_of_one_frame_each_show_that_frame` (three queued repeats with simulation 2 open give [1, 1, 1] and leave simulation 2 for the next frame).
Adriwin06 commented 2026-11-30 00:54:53 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Adriwin06 on 2026-11-30T00:54:53Z.

Code review location: crates/victory-gpu/src/streamline/reflex.rs; line 698

@@ -0,0 +1,1386 @@
+//! Reflex by itself (`VICTORY_REFLEX`), the part that needs no library: the
+//! switch, which latency markers a frame has sent and which it owes at each
+//! point of its life, where the Reflex sleep goes, and what the reports of a
+//! Reflex state average to.
+//!
+//! A Reflex frame is one index, and the Reflex sleep and every marker of it
+//! are given a frame token made from that index, on whichever thread they
+//! happen. [`Frames`] is what the threads share: who holds it decides, so a
+//! frame's markers leave in order and once each.
+//!
+//! Where a frame's index comes from. The title begins its frames with a wait
+//! for the frame origin (`crate::frame`), whose token it hands to the
+//! frame's submissions and its present. The runs with the first version of
+//! this (the sleep and the simulation start at that wait) showed the title
+//! reading its pad once a frame and after the frame's first submission (in
+//! the world 101 of 108 frames, and none before it): what a
+//! frame submits right after its origin wait is a simulation made before
+//! it, and the reading that follows is the input of a later frame's
+//! simulation. Which thread reads, the one that waits for the origin or
+//! another, the runs did not show; the ten-second line counts it. Either
+//! way the sleep and the simulation start belong at that reading, and the
+//! reading opens the simulation ([`Frames::sample`]): it gets a new index,
+//! the sleep is made there, and the next origin wait takes the simulation
+//! for its frame ([`Frames::begin`]), so that its token's submission ends
+//! that simulation and its present shows it. This assumes
+//! the title is one frame deep (the simulation read after frame N's first
+//! submission is the one frame N + 1 submits); nothing seen from outside
+//! the title can tell one frame deep from two. A title frame with no
+//! simulation to take gets an index of its own: with no sleep while most of
+//! the last [`HOLD`] frames took one (the title reads input nearly every
+//! frame, and this frame's reading was missed), else with the sleep at the
+//! origin wait, as before (loads, cutscenes, menus that read now and then or
+//! never).
+
+use super::abi;
+
+/// `VICTORY_REFLEX`: Reflex by itself, with or without frame generation.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Reflex {
+    /// `on` or `1`: low latency.
+    On,
+    /// `boost`: low latency with boost.
+    Boost,
+}
+
+impl Reflex {
+    /// The switch's value: unset, empty, `0` and `off` are no Reflex by
+    /// itself (everything as without the switch); any other word is an
+    /// error, as an unknown DLSS mode is.
+    pub fn from_switch(value: Option<&str>) -> Result<Option<Self>, String> {
+        let Some(value) = value else { return Ok(None) };
+        Ok(match value.trim().to_ascii_lowercase().as_str() {
+            "" | "0" | "off" => None,
+            "1" | "on" => Some(Reflex::On),
+            "boost" => Some(Reflex::Boost),
+            _ => return Err(format!("VICTORY_REFLEX={value}: not one of on, 1, boost, off, 0")),
+        })
+    }
+
+    pub fn name(self) -> &'static str {
+        match self {
+            Reflex::On => "on",
+            Reflex::Boost => "boost",
+        }
+    }
+
+    /// The `sl::ReflexMode` of the switch.
+    pub fn sl_mode(self) -> u32 {
+        match self {
+            Reflex::On => abi::REFLEX_LOW_LATENCY,
+            Reflex::Boost => abi::REFLEX_LOW_LATENCY_WITH_BOOST,
+        }
+    }
+}
+
+/// The points of a frame's life that have a marker, in the order a frame
+/// passes them.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Stage {
+    /// The Reflex sleep before the frame's simulation returned (at the
+    /// reading that opened it, or at the origin wait), or the frame began
+    /// with no sleep.
+    SimulationStart = 0,
+    /// The title asked for the pad or keyboard reading that opened the
+    /// frame's simulation.
+    InputSample = 1,
+    /// The title's first submission of command lists: its simulation is over
+    /// and its submissions begin.
+    SimulationEnd = 2,
+    SubmitStart = 3,
+    /// The present begins on the host.
+    SubmitEnd = 4,
+    PresentStart = 5,
+    PresentEnd = 6,
+}
+
+/// The `sl::PCLMarker` of each stage.
+const ORDER: [u32; 7] = [
+    abi::SIMULATION_START,
+    abi::CONTROLLER_INPUT_SAMPLE,
+    abi::SIMULATION_END,
+    abi::RENDER_SUBMIT_START,
+    abi::RENDER_SUBMIT_END,
+    abi::PRESENT_START,
+    abi::PRESENT_END,
+];
+
+const fn bit(stage: Stage) -> u8 {
+    1 << stage as u8
+}
+
+/// Markers to send now, as bits by stage.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Markers(u8);
+
+impl Markers {
+    pub fn is_empty(self) -> bool {
+        self.0 == 0
+    }
+
+    /// Their `sl::PCLMarker` values, in the order they are to be sent.
+    pub fn iter(self) -> impl Iterator<Item = u32> {
+        ORDER.iter().enumerate().filter(move |(stage, _)| self.0 & (1 << stage) != 0).map(|(_, &marker)| marker)
+    }
+}
+
+/// One frame that is not over yet.
+struct Frame {
+    /// The index its frame tokens are made from.
+    index: u32,
+    /// The token the title's origin wait gave it (0: no origin wait has it
+    /// yet, or the frame was made at a present the title began none for).
+    origin: u64,
+    /// The number of the title's present that shows it (0: none yet).
+    present: u64,
+    /// The stages whose markers were sent.
+    sent: u8,
+    /// A title's origin wait has it: it began the frame, or took the
+    /// simulation a reading opened. False for a simulation not taken yet
+    /// and for a frame made at a present.
+    begun: bool,
+    /// The thread of that origin wait, or of the reading that opened the
+    /// frame while none has it (0: none).
+    thread: u32,
+    /// When (microseconds, the caller's clock) the origin wait had it, or
+    /// the reading opened it while none has it.
+    at: u64,
+    /// The title submitted to a queue that draws for it, and when.
+    submitted: bool,
+    submitted_at: u64,
+}
+
+impl Frame {
+    fn has(&self, stage: Stage) -> bool {
+        self.sent & bit(stage) != 0
+    }
+
+    /// The frame's simulation began (its sleep is over): from here on the
+    /// title's submissions and presents may end it.
+    fn started(&self) -> bool {
+        self.has(Stage::SimulationStart)
+    }
+
+    /// The markers of every stage up to `stage` that were not sent, now
+    /// counted as sent. The input sample is never owed: it is sent with the
+    /// simulation's start at the reading that opened the frame, or not at
+    /// all. What was sent is always a run from the first stage on, so
+    /// nothing ever leaves out of order.
+    fn reach(&mut self, stage: Stage) -> Markers {
+        let up_to = (bit(stage) << 1).wrapping_sub(1);
+        let owed = up_to & !bit(Stage::InputSample) & !self.sent;
+        self.sent |= owed;
+        Markers(owed)
+    }
+}
+
+/// Microseconds between two events of a frame, over the frames that had
+/// both since the counts were last taken.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Gap {
+    pub count: u32,
+    pub sum_us: u64,
+    pub longest_us: u64,
+}
+
+impl Gap {
+    const ZERO: Gap = Gap { count: 0, sum_us: 0, longest_us: 0 };
+
+    fn add(&mut self, us: u64) {
+        self.count = self.count.saturating_add(1);
+        self.sum_us = self.sum_us.saturating_add(us);
+        self.longest_us = self.longest_us.max(us);
+    }
+
+    pub fn average_us(&self) -> u64 {
+        self.sum_us / u64::from(self.count.max(1))
+    }
+}
+
+/// What happened since the counts were last taken (the ten-second line).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Counts {
+    /// Frames the title began (origin waits that made a token).
+    pub begun: u32,
+    /// Of them: frames that took the simulation a reading opened, frames
+    /// with no simulation to take and no sleep (most of the last [`HOLD`]
+    /// frames took one), and frames with no simulation to take that slept
+    /// at the origin wait (fewer did).
+    pub adopted: u32,
+    pub unpaced: u32,
+    pub origin_sleeps: u32,
+    /// Frames whose simulation start and input sample were sent where the
+    /// reading's sleep returned.
+    pub sampled: u32,
+    /// Readings that opened a simulation (with its sleep), that belonged to
+    /// the one open, that came before the newest begun frame's simulation
+    /// ended at a submission (the frame still simulates, or is in its sleep
+    /// at the origin wait), and that came on another thread than the one
+    /// that opens simulations.
+    pub opened: u32,
+    pub belongs: u32,
+    pub held_back: u32,
+    pub other_thread: u32,
+    /// Simulations let go because a reading came while one was open and
+    /// no origin wait had taken it for [`Frames::stale_after_us`] (a load).
+    pub stale: u32,
+    /// Simulations whose frame was over or past its simulation's end when
+    /// the reading's sleep returned: no input sample was sent for them.
+    pub lost: u32,
+    /// Frames whose first submission came before their simulation started
+    /// (the opening reading was still in its sleep): that submission was of
+    /// a simulation before, so the title is deeper than one frame there.
+    pub submitted_before_start: u32,
+    /// Where things happened, by thread: \[0\] on the thread of the origin
+    /// wait of the frame concerned, \[1\] on another. For an opening
+    /// reading the frame is the newest begun one; for the first submission
+    /// and the title's present, the frame they are of.
+    pub openings_by_thread: [u32; 2],
+    pub first_submits_by_thread: [u32; 2],
+    pub presents_by_thread: [u32; 2],
+    /// From a frame's origin wait to its first submission; from the newest
+    /// begun frame's first submission to the reading that opens the next
+    /// simulation; from the opening (after its sleep) to the origin wait
+    /// that takes it.
+    pub origin_to_submit: Gap,
+    pub submit_to_open: Gap,
+    pub open_to_adopt: Gap,
+    /// Frames presented without a submission of the title's before.
+    pub unsubmitted: u32,
+    /// Presents the title began no frame for (a second present of one
+    /// frame's token among them).
+    pub unbegun: u32,
+    /// Presents that found their frame by the title's token, and by order.
+    pub by_token: u32,
+    pub by_order: u32,
+    /// Frames whose simulation was ended by a submission that named them
+    /// with the title's token, and by one that did not (no token, or one no
+    /// frame here has): the newest running frame was taken then, which is
+    /// the wrong one if the title still submits a frame after it began the
+    /// next.
+    pub submitted_by_token: u32,
+    pub submitted_by_order: u32,
+    /// Frames begun and never presented.
+    pub never_presented: u32,
+}
+
+impl Counts {
+    const ZERO: Counts = Counts {
+        begun: 0,
+        adopted: 0,
+        unpaced: 0,
+        origin_sleeps: 0,
+        sampled: 0,
+        opened: 0,
+        belongs: 0,
+        held_back: 0,
+        other_thread: 0,
+        stale: 0,
+        lost: 0,
+        submitted_before_start: 0,
+        openings_by_thread: [0; 2],
+        first_submits_by_thread: [0; 2],
+        presents_by_thread: [0; 2],
+        origin_to_submit: Gap::ZERO,
+        submit_to_open: Gap::ZERO,
+        open_to_adopt: Gap::ZERO,
+        unsubmitted: 0,
+        unbegun: 0,
+        by_token: 0,
+        by_order: 0,
+        submitted_by_token: 0,
+        submitted_by_order: 0,
+        never_presented: 0,
+    };
+}
+
+/// Where a title frame's simulation starts ([`Frames::begin`]).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Begin {
+    /// The frame took the simulation a reading opened, with this index: its
+    /// sleep and its start were the reading's, nothing is sent here.
+    Adopted(u32),
+    /// A frame of its own with no sleep (most of the last [`HOLD`] frames
+    /// took a simulation, just not this one): its start now.
+    Unpaced(u32),
+    /// A frame of its own that sleeps here first (the title reads input on
+    /// fewer frames than that, or none): its start where the sleep returns.
+    Paced(u32),
+}
+
+/// What the title asking for a reading is ([`Frames::sample`]).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Sample {
+    /// It opens a simulation with this index: the sleep is made now, on the
+    /// reading's thread, and then [`Frames::sampled`] says its markers.
+    Open(u32),
+    /// A simulation is open and this reading is part of it.
+    Belongs,
+    /// The newest begun frame's simulation has not ended at a submission
+    /// yet: the reading is of that simulation, or the frame is in its sleep
+    /// at the origin wait.
+    HeldBack,
+    /// Another thread opens simulations.
+    OtherThread,
+}
+
+/// The frames that are not over, oldest first, the last index given, and
+/// the simulation a reading opened that no origin wait has taken yet.
+pub(crate) struct Frames {
+    last: u32,
+    live: Vec<Frame>,
+    /// The index of the open simulation: always newer than every frame an
+    /// origin wait has (the next origin wait takes it instead of making a
+    /// frame of its own), so indexes stay in the order the title presents
+    /// its frames.
+    open: Option<u32>,
+    /// The thread that opened the last simulation (0: none yet).
+    sampler: u32,
+    /// Origin waits since the last simulation was opened (saturating; it
+    /// starts above [`HOLD`], so any thread may open the first one).
+    since_opened: u32,
+    /// Which of the last [`HOLD`] title frames took a simulation a reading
+    /// opened, one bit each, the newest lowest (none at first, so the first
+    /// frames sleep at the origin wait).
+    adopted_recently: u32,
+    /// When the last origin wait came, and how long before it the one
+    /// before came (microseconds, the caller's clock; 0 until two came).
+    begun_at: Option<u64>,
+    interval_us: u64,
+    /// The title's present that was a second present of one frame's token,
+    /// and that frame's index: the host's present of it shows that frame
+    /// again ([`Frames::presenting`]).
+    repeat: Option<(u64, u32)>,
+    counts: Counts,
+}
+
+/// Frames kept at most (Streamline expects no more than three in flight; the
+/// rest is room for frames the title begins and never presents).
+const KEPT: usize = 8;
+
+/// The title frames looked back on. A frame with no simulation to take goes
+/// without a sleep only when more than half of the last `HOLD` frames took
+/// one: the title reads input nearly every frame and missed this one (in
+/// the world about one frame in fifteen had no reading counted), and a
+/// sleep at the origin wait would hold back a finished frame again. Where
+/// the title reads input on fewer frames (a menu that reads every tenth),
+/// its other frames sleep at the origin wait as they did before readings
+/// were looked at: Reflex's guide has `slReflexSleep` called always, and
+/// whether its pacing or frame generation's bears frames with no sleep the
+/// guides on disk do not say. Also the frames after which another thread
+/// may open simulations. Eight frames is a third of a second to two seconds
+/// in the world (4 to 28 frames a second there) and a few milliseconds in
+/// the menus.
+pub(crate) const HOLD: u32 = 8;
+const _: () = assert!(HOLD > 0 && HOLD <= u32::BITS);
+
+/// An open simulation is let go when a reading comes and no origin wait has
+/// taken it for this many microseconds or for [`STALE_FRAMES`] times the
+/// last interval between origin waits, whichever is longer: the title read
+/// input and began no frame (a load), and the reading opens a new one. A
+/// fixed bound alone let every simulation go in the world's slow stretches,
+/// where the origin wait that takes a simulation comes 80 to 370 ms after
+/// the reading that opened it.
+pub(crate) const STALE_US: u64 = 250_000;
+pub(crate) const STALE_FRAMES: u64 = 4;
+
+impl Frames {
+    pub const fn new() -> Self {
+        Frames {
+            last: 0,
+            live: Vec::new(),
+            open: None,
+            sampler: 0,
+            since_opened: u32::MAX,
+            adopted_recently: 0,
+            begun_at: None,
+            interval_us: 0,
+            repeat: None,
+            counts: Counts::ZERO,
+        }
+    }
+
+    /// How long an open simulation may wait for its origin wait while
+    /// readings come, in microseconds ([`STALE_US`]).
+    pub fn stale_after_us(&self) -> u64 {
+        STALE_US.max(self.interval_us.saturating_mul(STALE_FRAMES))
+    }
+
+    /// A new frame with the next index (indexes count from 1 and wrap).
+    fn push(&mut self, origin: u64, present: u64, begun: bool, thread: u32, at: u64) -> u32 {
+        // The oldest goes if the title begins frames it never presents.
+        // (Never the open simulation: it is the newest, and KEPT is above 1.)
+        if self.live.len() >= KEPT {
+            self.live.remove(0);
+            self.counts.never_presented += 1;
+        }
+        self.last = self.last.wrapping_add(1);
+        self.live.push(Frame {
+            index: self.last,
+            origin,
+            present,
+            sent: 0,
+            begun,
+            thread,
+            at,
+            submitted: false,
+            submitted_at: 0,
+        });
+        self.last
+    }
+
+    /// The open simulation is let go if no origin wait took it within
+    /// [`Frames::stale_after_us`] (`now` is the caller's clock, as at the
+    /// opening). Only a reading asks this: the origin wait that comes always
+    /// takes the open simulation, however long after, since that is the
+    /// frame that submits it.
+    fn let_go_stale(&mut self, now: u64) {
+        let Some(index) = self.open else { return };
+        let Some(at) = self.live.iter().position(|f| f.index == index) else {
+            self.open = None;
+            return;
+        };
+        if now.saturating_sub(self.live[at].at) > self.stale_after_us() {
+            self.live.remove(at);
+            self.open = None;
+            self.counts.stale += 1;
+        }
+    }
+
+    /// The title begins a frame on `thread` at `now`: its origin wait made
+    /// token `origin`. The frame takes the open simulation if there is one,
+    /// else it gets an index of its own, with or without a sleep here.
+    pub fn begin(&mut self, origin: u64, thread: u32, now: u64) -> Begin {
+        self.counts.begun += 1;
+        // The interval between origin waits, for how long an open
+        // simulation may wait for one while readings come.
+        if let Some(before) = self.begun_at {
+            self.interval_us = now.saturating_sub(before);
+        }
+        self.begun_at = Some(now);
+        self.since_opened = self.since_opened.saturating_add(1);
+        // The frames before this one that took a simulation; this one's bit
+        // is set below if it takes one.
+        let window = u32::MAX >> (u32::BITS - HOLD);
+        let took_before = (self.adopted_recently & window).count_ones();
+        self.adopted_recently = (self.adopted_recently << 1) & window;
+        // No time bound here: the simulation open now is the one this frame
+        // submits, whether the frame came 3 ms or 370 ms after its reading.
+        if let Some(index) = self.open.take()
+            && let Some(frame) = self.live.iter_mut().find(|f| f.index == index)
+        {
+            self.counts.open_to_adopt.add(now.saturating_sub(frame.at));
+            frame.origin = origin;
+            frame.begun = true;
+            frame.thread = thread;
+            frame.at = now;
+            self.counts.adopted += 1;
+            self.adopted_recently |= 1;
+            return Begin::Adopted(index);
+        }
+        let index = self.push(origin, 0, true, thread, now);
+        if took_before > HOLD / 2 {
+            self.counts.unpaced += 1;
+            Begin::Unpaced(index)
+        } else {
+            self.counts.origin_sleeps += 1;
+            Begin::Paced(index)
+        }
+    }
+
+    /// The markers frame `index` owes up to `stage`, now sent; none if the
+    /// frame is over.
+    pub fn reach(&mut self, index: u32, stage: Stage) -> Markers {
+        self.live.iter_mut().find(|f| f.index == index).map_or(Markers(0), |f| f.reach(stage))
+    }
+
+    /// The title asks for a pad or keyboard reading on `thread` at `now`,
+    /// before the reading is picked. It opens a simulation only when none
+    /// is open, the newest begun frame's simulation has ended at its
+    /// submission (or it has its present, or there is no begun frame), and
+    /// the thread is the one that opens them (or
+    /// that one has not for more than [`HOLD`] frames). So at most one
+    /// simulation opens between two origin waits, one sleep is made for
+    /// it, and it never runs while a sleep at the origin wait does (that
+    /// frame has not submitted yet). A simulation that waited too long for
+    /// its origin wait ([`Frames::stale_after_us`]) is let go first, and the
+    /// reading opens another.
+    pub fn sample(&mut self, thread: u32, now: u64) -> Sample {
+        self.let_go_stale(now);
+        if self.sampler != 0 && self.sampler != thread && self.since_opened <= HOLD {
+            self.counts.other_thread += 1;
+            return Sample::OtherThread;
+        }
+        if self.open.is_some() {
+            self.counts.belongs += 1;
+            return Sample::Belongs;
+        }
+        let newest = self.live.iter().rev().find(|f| f.begun);
+        if let Some(frame) = newest {
+            // (Its simulation's end, not its first submission: a submission
+            // that came while the opening reading still slept ended nothing,
+            // and the readings of that simulation must not open another.)
+            if !frame.has(Stage::SimulationEnd) && frame.present == 0 {
+                self.counts.held_back += 1;
+                return Sample::HeldBack;
+            }
+            // Which thread reads, against the one that begins frames; and
+            // how long after that frame's first submission.
+            self.counts.openings_by_thread[usize::from(frame.thread != thread)] += 1;
+            if frame.submitted {
+                self.counts.submit_to_open.add(now.saturating_sub(frame.submitted_at));
+            }
+        }
+        let index = self.push(0, 0, false, thread, now);
+        self.open = Some(index);
+        self.sampler = thread;
+        self.since_opened = 0;
+        self.counts.opened += 1;
+        Sample::Open(index)
+    }
+
+    /// The sleep of the simulation `index` opened returned at `now`: its
+    /// simulation start and its input sample, now sent; none if the frame
+    /// is over or its present already sent its simulation's markers (the
+    /// sample is lost then, and counted).
+    pub fn sampled(&mut self, index: u32, now: u64) -> Markers {
+        let Some(frame) = self.live.iter_mut().find(|f| f.index == index) else {
+            self.counts.lost += 1;
+            return Markers(0);
+        };
+        if frame.started() {
+            self.counts.lost += 1;
+            return Markers(0);
+        }
+        // While no origin wait has it, the opening counts from here (the
+        // gap to the adoption is measured after the sleep).
+        if !frame.begun {
+            frame.at = frame.at.max(now);
+        }
+        let owed = bit(Stage::SimulationStart) | bit(Stage::InputSample);
+        frame.sent |= owed;
+        self.counts.sampled += 1;
+        Markers(owed)
+    }
+
+    /// The title submits command lists to a queue that draws, on `thread`
+    /// at `now`, tagged with frame token `origin` (0: not tagged): at the
+    /// frame's first submission its simulation ends and its submissions
+    /// begin. The frame is the one of that token, else the newest begun
+    /// frame whose simulation runs and whose present the title has not
+    /// called (never a simulation no origin wait has taken). Which of the
+    /// two ended a frame's simulation is counted, for the line.
+    pub fn submit(&mut self, origin: u64, thread: u32, now: u64) -> Option<(u32, Markers)> {
+        let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten();
+        let at = match tagged {
+            Some(at) => at,
+            None => self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0)?,
+        };
+        let frame = &mut self.live[at];
+        let first = !frame.submitted;
+        if first {
+            frame.submitted = true;
+            frame.submitted_at = now;
+            self.counts.first_submits_by_thread[usize::from(frame.thread != thread)] += 1;
+            self.counts.origin_to_submit.add(now.saturating_sub(frame.at));
+        }
+        // A frame still in its sleep has no simulation to end. (At the
+        // origin wait that cannot be: the title has not got the token yet.
+        // At a reading it means this submission is of a simulation before.)
+        if !frame.started() {
+            if first {
+                self.counts.submitted_before_start += 1;
+            }
+            return None;
+        }
+        let owed = frame.reach(Stage::SubmitStart);
+        // Later submissions of the frame owe nothing and count nothing.
+        if owed.is_empty() {
+            return None;
+        }
+        // Counted where it has an effect: this submission is the one that
+        // ends the frame's simulation.
+        match tagged {
+            Some(_) => self.counts.submitted_by_token += 1,
+            None => self.counts.submitted_by_order += 1,
+        }
+        Some((frame.index, owed))
+    }
+
+    /// The title calls its present number `present` (counted from 1) on
+    /// `thread` with frame token `origin` in its first plane (0: none): the
+    /// present is that frame's, else the newest begun frame's whose
+    /// simulation runs and that has no present yet. Frames begun before it
+    /// that have none are over: the title never presented them. (By the
+    /// token the frame need not have started: a simulation whose reading is
+    /// still in its sleep may be presented, and then sends what it owes at
+    /// the present.)
+    pub fn title_presents(&mut self, present: u64, origin: u64, thread: u32) {
+        let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten();
+        let at = match tagged {
+            Some(at) if self.live[at].present == 0 => {
+                self.counts.by_token += 1;
+                at
+            }
+            // The token's frame has its present: this one shows that frame
+            // again, and the host's present of it names that frame's index
+            // ([`Frames::presenting`]).
+            Some(at) => {
+                self.repeat = Some((present, self.live[at].index));
+                return;
+            }
+            None => {
+                let Some(at) = self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0) else { return };
+                self.counts.by_order += 1;
+                at
+            }
+        };
+        self.counts.presents_by_thread[usize::from(self.live[at].thread != thread)] += 1;
+        self.live[at].present = present;
+        let before = self.live.len();
+        let mut place = 0;
+        // (An open simulation is the newest, after `at`: it stays.)
+        self.live.retain(|f| {
+            let keep = place >= at || f.present != 0;
+            place += 1;
+            keep
+        });
+        self.counts.never_presented += (before - self.live.len()) as u32;
+    }
+
+    /// Present number `present` begins on the host: its frame's index. The
+    /// indexes the host presents must keep rising: frame generation's
+    /// constants, tags and present markers use them, and its guide ties
+    /// present markers out of step with the frame shown to constants it
+    /// cannot find. So a present the title began no frame for does not get
+    /// an index newer than a simulation still to be presented:
+    /// - a second present of one frame's token shows that frame again and
+    ///   gets its index (its markers were sent once, nothing more is);
+    /// - another, while a simulation a reading opened is open, takes that
+    ///   simulation (the next index in order): its markers are completed
+    ///   here, and the next origin wait has none to take;
+    /// - else it gets a frame made here, which owes every marker (the
+    ///   check's presents, a present before the title's first frame).
+    ///
+    /// The line counts all three as presents with no frame begun; in the
+    /// runs there were none in the title.
+    pub fn presenting(&mut self, present: u64) -> u32 {
+        if present != 0
+            && let Some(frame) = self.live.iter().find(|f| f.present == present)
+        {
+            if !frame.has(Stage::SubmitStart) {
+                self.counts.unsubmitted += 1;
+            }
+            return frame.index;
+        }
+        self.counts.unbegun += 1;
+        if present != 0
+            && let Some((repeated, index)) = self.repeat
+            && repeated == present
+        {
+            self.repeat = None;
+            return index;
+        }
+        if let Some(index) = self.open.take()
+            && let Some(frame) = self.live.iter_mut().find(|f| f.index == index)
+        {
+            frame.present = present;
+            return index;
+        }
+        self.push(0, present, false, 0, 0)
+    }
+
+    /// The present of frame `index` returned: its last marker, and the frame
+    /// is over.
+    pub fn presented(&mut self, index: u32) -> Markers {
+        let Some(at) = self.live.iter().position(|f| f.index == index) else { return Markers(0) };
+        let owed = self.live[at].reach(Stage::PresentEnd);
+        self.live.remove(at);

Fixed in c5cd5410 as well: the last KEPT presented frames' origin tokens and indexes are kept apart from the live marker state, so a repeat arriving after the host present still reuses that index with no markers. Regression test: a_further_present_after_the_hosts_present_shows_that_frame_again (it also checks the history is bounded).

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:review-comment:4734027006 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072#discussion_r4734027006). Originally posted by [Adriwin06](https://github.com/Adriwin06) on 2026-11-30T00:54:53Z. **Code review location:** `crates/victory-gpu/src/streamline/reflex.rs`; line 698 ~~~~diff @@ -0,0 +1,1386 @@ +//! Reflex by itself (`VICTORY_REFLEX`), the part that needs no library: the +//! switch, which latency markers a frame has sent and which it owes at each +//! point of its life, where the Reflex sleep goes, and what the reports of a +//! Reflex state average to. +//! +//! A Reflex frame is one index, and the Reflex sleep and every marker of it +//! are given a frame token made from that index, on whichever thread they +//! happen. [`Frames`] is what the threads share: who holds it decides, so a +//! frame's markers leave in order and once each. +//! +//! Where a frame's index comes from. The title begins its frames with a wait +//! for the frame origin (`crate::frame`), whose token it hands to the +//! frame's submissions and its present. The runs with the first version of +//! this (the sleep and the simulation start at that wait) showed the title +//! reading its pad once a frame and after the frame's first submission (in +//! the world 101 of 108 frames, and none before it): what a +//! frame submits right after its origin wait is a simulation made before +//! it, and the reading that follows is the input of a later frame's +//! simulation. Which thread reads, the one that waits for the origin or +//! another, the runs did not show; the ten-second line counts it. Either +//! way the sleep and the simulation start belong at that reading, and the +//! reading opens the simulation ([`Frames::sample`]): it gets a new index, +//! the sleep is made there, and the next origin wait takes the simulation +//! for its frame ([`Frames::begin`]), so that its token's submission ends +//! that simulation and its present shows it. This assumes +//! the title is one frame deep (the simulation read after frame N's first +//! submission is the one frame N + 1 submits); nothing seen from outside +//! the title can tell one frame deep from two. A title frame with no +//! simulation to take gets an index of its own: with no sleep while most of +//! the last [`HOLD`] frames took one (the title reads input nearly every +//! frame, and this frame's reading was missed), else with the sleep at the +//! origin wait, as before (loads, cutscenes, menus that read now and then or +//! never). + +use super::abi; + +/// `VICTORY_REFLEX`: Reflex by itself, with or without frame generation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reflex { + /// `on` or `1`: low latency. + On, + /// `boost`: low latency with boost. + Boost, +} + +impl Reflex { + /// The switch's value: unset, empty, `0` and `off` are no Reflex by + /// itself (everything as without the switch); any other word is an + /// error, as an unknown DLSS mode is. + pub fn from_switch(value: Option<&str>) -> Result<Option<Self>, String> { + let Some(value) = value else { return Ok(None) }; + Ok(match value.trim().to_ascii_lowercase().as_str() { + "" | "0" | "off" => None, + "1" | "on" => Some(Reflex::On), + "boost" => Some(Reflex::Boost), + _ => return Err(format!("VICTORY_REFLEX={value}: not one of on, 1, boost, off, 0")), + }) + } + + pub fn name(self) -> &'static str { + match self { + Reflex::On => "on", + Reflex::Boost => "boost", + } + } + + /// The `sl::ReflexMode` of the switch. + pub fn sl_mode(self) -> u32 { + match self { + Reflex::On => abi::REFLEX_LOW_LATENCY, + Reflex::Boost => abi::REFLEX_LOW_LATENCY_WITH_BOOST, + } + } +} + +/// The points of a frame's life that have a marker, in the order a frame +/// passes them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Stage { + /// The Reflex sleep before the frame's simulation returned (at the + /// reading that opened it, or at the origin wait), or the frame began + /// with no sleep. + SimulationStart = 0, + /// The title asked for the pad or keyboard reading that opened the + /// frame's simulation. + InputSample = 1, + /// The title's first submission of command lists: its simulation is over + /// and its submissions begin. + SimulationEnd = 2, + SubmitStart = 3, + /// The present begins on the host. + SubmitEnd = 4, + PresentStart = 5, + PresentEnd = 6, +} + +/// The `sl::PCLMarker` of each stage. +const ORDER: [u32; 7] = [ + abi::SIMULATION_START, + abi::CONTROLLER_INPUT_SAMPLE, + abi::SIMULATION_END, + abi::RENDER_SUBMIT_START, + abi::RENDER_SUBMIT_END, + abi::PRESENT_START, + abi::PRESENT_END, +]; + +const fn bit(stage: Stage) -> u8 { + 1 << stage as u8 +} + +/// Markers to send now, as bits by stage. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Markers(u8); + +impl Markers { + pub fn is_empty(self) -> bool { + self.0 == 0 + } + + /// Their `sl::PCLMarker` values, in the order they are to be sent. + pub fn iter(self) -> impl Iterator<Item = u32> { + ORDER.iter().enumerate().filter(move |(stage, _)| self.0 & (1 << stage) != 0).map(|(_, &marker)| marker) + } +} + +/// One frame that is not over yet. +struct Frame { + /// The index its frame tokens are made from. + index: u32, + /// The token the title's origin wait gave it (0: no origin wait has it + /// yet, or the frame was made at a present the title began none for). + origin: u64, + /// The number of the title's present that shows it (0: none yet). + present: u64, + /// The stages whose markers were sent. + sent: u8, + /// A title's origin wait has it: it began the frame, or took the + /// simulation a reading opened. False for a simulation not taken yet + /// and for a frame made at a present. + begun: bool, + /// The thread of that origin wait, or of the reading that opened the + /// frame while none has it (0: none). + thread: u32, + /// When (microseconds, the caller's clock) the origin wait had it, or + /// the reading opened it while none has it. + at: u64, + /// The title submitted to a queue that draws for it, and when. + submitted: bool, + submitted_at: u64, +} + +impl Frame { + fn has(&self, stage: Stage) -> bool { + self.sent & bit(stage) != 0 + } + + /// The frame's simulation began (its sleep is over): from here on the + /// title's submissions and presents may end it. + fn started(&self) -> bool { + self.has(Stage::SimulationStart) + } + + /// The markers of every stage up to `stage` that were not sent, now + /// counted as sent. The input sample is never owed: it is sent with the + /// simulation's start at the reading that opened the frame, or not at + /// all. What was sent is always a run from the first stage on, so + /// nothing ever leaves out of order. + fn reach(&mut self, stage: Stage) -> Markers { + let up_to = (bit(stage) << 1).wrapping_sub(1); + let owed = up_to & !bit(Stage::InputSample) & !self.sent; + self.sent |= owed; + Markers(owed) + } +} + +/// Microseconds between two events of a frame, over the frames that had +/// both since the counts were last taken. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Gap { + pub count: u32, + pub sum_us: u64, + pub longest_us: u64, +} + +impl Gap { + const ZERO: Gap = Gap { count: 0, sum_us: 0, longest_us: 0 }; + + fn add(&mut self, us: u64) { + self.count = self.count.saturating_add(1); + self.sum_us = self.sum_us.saturating_add(us); + self.longest_us = self.longest_us.max(us); + } + + pub fn average_us(&self) -> u64 { + self.sum_us / u64::from(self.count.max(1)) + } +} + +/// What happened since the counts were last taken (the ten-second line). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Counts { + /// Frames the title began (origin waits that made a token). + pub begun: u32, + /// Of them: frames that took the simulation a reading opened, frames + /// with no simulation to take and no sleep (most of the last [`HOLD`] + /// frames took one), and frames with no simulation to take that slept + /// at the origin wait (fewer did). + pub adopted: u32, + pub unpaced: u32, + pub origin_sleeps: u32, + /// Frames whose simulation start and input sample were sent where the + /// reading's sleep returned. + pub sampled: u32, + /// Readings that opened a simulation (with its sleep), that belonged to + /// the one open, that came before the newest begun frame's simulation + /// ended at a submission (the frame still simulates, or is in its sleep + /// at the origin wait), and that came on another thread than the one + /// that opens simulations. + pub opened: u32, + pub belongs: u32, + pub held_back: u32, + pub other_thread: u32, + /// Simulations let go because a reading came while one was open and + /// no origin wait had taken it for [`Frames::stale_after_us`] (a load). + pub stale: u32, + /// Simulations whose frame was over or past its simulation's end when + /// the reading's sleep returned: no input sample was sent for them. + pub lost: u32, + /// Frames whose first submission came before their simulation started + /// (the opening reading was still in its sleep): that submission was of + /// a simulation before, so the title is deeper than one frame there. + pub submitted_before_start: u32, + /// Where things happened, by thread: \[0\] on the thread of the origin + /// wait of the frame concerned, \[1\] on another. For an opening + /// reading the frame is the newest begun one; for the first submission + /// and the title's present, the frame they are of. + pub openings_by_thread: [u32; 2], + pub first_submits_by_thread: [u32; 2], + pub presents_by_thread: [u32; 2], + /// From a frame's origin wait to its first submission; from the newest + /// begun frame's first submission to the reading that opens the next + /// simulation; from the opening (after its sleep) to the origin wait + /// that takes it. + pub origin_to_submit: Gap, + pub submit_to_open: Gap, + pub open_to_adopt: Gap, + /// Frames presented without a submission of the title's before. + pub unsubmitted: u32, + /// Presents the title began no frame for (a second present of one + /// frame's token among them). + pub unbegun: u32, + /// Presents that found their frame by the title's token, and by order. + pub by_token: u32, + pub by_order: u32, + /// Frames whose simulation was ended by a submission that named them + /// with the title's token, and by one that did not (no token, or one no + /// frame here has): the newest running frame was taken then, which is + /// the wrong one if the title still submits a frame after it began the + /// next. + pub submitted_by_token: u32, + pub submitted_by_order: u32, + /// Frames begun and never presented. + pub never_presented: u32, +} + +impl Counts { + const ZERO: Counts = Counts { + begun: 0, + adopted: 0, + unpaced: 0, + origin_sleeps: 0, + sampled: 0, + opened: 0, + belongs: 0, + held_back: 0, + other_thread: 0, + stale: 0, + lost: 0, + submitted_before_start: 0, + openings_by_thread: [0; 2], + first_submits_by_thread: [0; 2], + presents_by_thread: [0; 2], + origin_to_submit: Gap::ZERO, + submit_to_open: Gap::ZERO, + open_to_adopt: Gap::ZERO, + unsubmitted: 0, + unbegun: 0, + by_token: 0, + by_order: 0, + submitted_by_token: 0, + submitted_by_order: 0, + never_presented: 0, + }; +} + +/// Where a title frame's simulation starts ([`Frames::begin`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Begin { + /// The frame took the simulation a reading opened, with this index: its + /// sleep and its start were the reading's, nothing is sent here. + Adopted(u32), + /// A frame of its own with no sleep (most of the last [`HOLD`] frames + /// took a simulation, just not this one): its start now. + Unpaced(u32), + /// A frame of its own that sleeps here first (the title reads input on + /// fewer frames than that, or none): its start where the sleep returns. + Paced(u32), +} + +/// What the title asking for a reading is ([`Frames::sample`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Sample { + /// It opens a simulation with this index: the sleep is made now, on the + /// reading's thread, and then [`Frames::sampled`] says its markers. + Open(u32), + /// A simulation is open and this reading is part of it. + Belongs, + /// The newest begun frame's simulation has not ended at a submission + /// yet: the reading is of that simulation, or the frame is in its sleep + /// at the origin wait. + HeldBack, + /// Another thread opens simulations. + OtherThread, +} + +/// The frames that are not over, oldest first, the last index given, and +/// the simulation a reading opened that no origin wait has taken yet. +pub(crate) struct Frames { + last: u32, + live: Vec<Frame>, + /// The index of the open simulation: always newer than every frame an + /// origin wait has (the next origin wait takes it instead of making a + /// frame of its own), so indexes stay in the order the title presents + /// its frames. + open: Option<u32>, + /// The thread that opened the last simulation (0: none yet). + sampler: u32, + /// Origin waits since the last simulation was opened (saturating; it + /// starts above [`HOLD`], so any thread may open the first one). + since_opened: u32, + /// Which of the last [`HOLD`] title frames took a simulation a reading + /// opened, one bit each, the newest lowest (none at first, so the first + /// frames sleep at the origin wait). + adopted_recently: u32, + /// When the last origin wait came, and how long before it the one + /// before came (microseconds, the caller's clock; 0 until two came). + begun_at: Option<u64>, + interval_us: u64, + /// The title's present that was a second present of one frame's token, + /// and that frame's index: the host's present of it shows that frame + /// again ([`Frames::presenting`]). + repeat: Option<(u64, u32)>, + counts: Counts, +} + +/// Frames kept at most (Streamline expects no more than three in flight; the +/// rest is room for frames the title begins and never presents). +const KEPT: usize = 8; + +/// The title frames looked back on. A frame with no simulation to take goes +/// without a sleep only when more than half of the last `HOLD` frames took +/// one: the title reads input nearly every frame and missed this one (in +/// the world about one frame in fifteen had no reading counted), and a +/// sleep at the origin wait would hold back a finished frame again. Where +/// the title reads input on fewer frames (a menu that reads every tenth), +/// its other frames sleep at the origin wait as they did before readings +/// were looked at: Reflex's guide has `slReflexSleep` called always, and +/// whether its pacing or frame generation's bears frames with no sleep the +/// guides on disk do not say. Also the frames after which another thread +/// may open simulations. Eight frames is a third of a second to two seconds +/// in the world (4 to 28 frames a second there) and a few milliseconds in +/// the menus. +pub(crate) const HOLD: u32 = 8; +const _: () = assert!(HOLD > 0 && HOLD <= u32::BITS); + +/// An open simulation is let go when a reading comes and no origin wait has +/// taken it for this many microseconds or for [`STALE_FRAMES`] times the +/// last interval between origin waits, whichever is longer: the title read +/// input and began no frame (a load), and the reading opens a new one. A +/// fixed bound alone let every simulation go in the world's slow stretches, +/// where the origin wait that takes a simulation comes 80 to 370 ms after +/// the reading that opened it. +pub(crate) const STALE_US: u64 = 250_000; +pub(crate) const STALE_FRAMES: u64 = 4; + +impl Frames { + pub const fn new() -> Self { + Frames { + last: 0, + live: Vec::new(), + open: None, + sampler: 0, + since_opened: u32::MAX, + adopted_recently: 0, + begun_at: None, + interval_us: 0, + repeat: None, + counts: Counts::ZERO, + } + } + + /// How long an open simulation may wait for its origin wait while + /// readings come, in microseconds ([`STALE_US`]). + pub fn stale_after_us(&self) -> u64 { + STALE_US.max(self.interval_us.saturating_mul(STALE_FRAMES)) + } + + /// A new frame with the next index (indexes count from 1 and wrap). + fn push(&mut self, origin: u64, present: u64, begun: bool, thread: u32, at: u64) -> u32 { + // The oldest goes if the title begins frames it never presents. + // (Never the open simulation: it is the newest, and KEPT is above 1.) + if self.live.len() >= KEPT { + self.live.remove(0); + self.counts.never_presented += 1; + } + self.last = self.last.wrapping_add(1); + self.live.push(Frame { + index: self.last, + origin, + present, + sent: 0, + begun, + thread, + at, + submitted: false, + submitted_at: 0, + }); + self.last + } + + /// The open simulation is let go if no origin wait took it within + /// [`Frames::stale_after_us`] (`now` is the caller's clock, as at the + /// opening). Only a reading asks this: the origin wait that comes always + /// takes the open simulation, however long after, since that is the + /// frame that submits it. + fn let_go_stale(&mut self, now: u64) { + let Some(index) = self.open else { return }; + let Some(at) = self.live.iter().position(|f| f.index == index) else { + self.open = None; + return; + }; + if now.saturating_sub(self.live[at].at) > self.stale_after_us() { + self.live.remove(at); + self.open = None; + self.counts.stale += 1; + } + } + + /// The title begins a frame on `thread` at `now`: its origin wait made + /// token `origin`. The frame takes the open simulation if there is one, + /// else it gets an index of its own, with or without a sleep here. + pub fn begin(&mut self, origin: u64, thread: u32, now: u64) -> Begin { + self.counts.begun += 1; + // The interval between origin waits, for how long an open + // simulation may wait for one while readings come. + if let Some(before) = self.begun_at { + self.interval_us = now.saturating_sub(before); + } + self.begun_at = Some(now); + self.since_opened = self.since_opened.saturating_add(1); + // The frames before this one that took a simulation; this one's bit + // is set below if it takes one. + let window = u32::MAX >> (u32::BITS - HOLD); + let took_before = (self.adopted_recently & window).count_ones(); + self.adopted_recently = (self.adopted_recently << 1) & window; + // No time bound here: the simulation open now is the one this frame + // submits, whether the frame came 3 ms or 370 ms after its reading. + if let Some(index) = self.open.take() + && let Some(frame) = self.live.iter_mut().find(|f| f.index == index) + { + self.counts.open_to_adopt.add(now.saturating_sub(frame.at)); + frame.origin = origin; + frame.begun = true; + frame.thread = thread; + frame.at = now; + self.counts.adopted += 1; + self.adopted_recently |= 1; + return Begin::Adopted(index); + } + let index = self.push(origin, 0, true, thread, now); + if took_before > HOLD / 2 { + self.counts.unpaced += 1; + Begin::Unpaced(index) + } else { + self.counts.origin_sleeps += 1; + Begin::Paced(index) + } + } + + /// The markers frame `index` owes up to `stage`, now sent; none if the + /// frame is over. + pub fn reach(&mut self, index: u32, stage: Stage) -> Markers { + self.live.iter_mut().find(|f| f.index == index).map_or(Markers(0), |f| f.reach(stage)) + } + + /// The title asks for a pad or keyboard reading on `thread` at `now`, + /// before the reading is picked. It opens a simulation only when none + /// is open, the newest begun frame's simulation has ended at its + /// submission (or it has its present, or there is no begun frame), and + /// the thread is the one that opens them (or + /// that one has not for more than [`HOLD`] frames). So at most one + /// simulation opens between two origin waits, one sleep is made for + /// it, and it never runs while a sleep at the origin wait does (that + /// frame has not submitted yet). A simulation that waited too long for + /// its origin wait ([`Frames::stale_after_us`]) is let go first, and the + /// reading opens another. + pub fn sample(&mut self, thread: u32, now: u64) -> Sample { + self.let_go_stale(now); + if self.sampler != 0 && self.sampler != thread && self.since_opened <= HOLD { + self.counts.other_thread += 1; + return Sample::OtherThread; + } + if self.open.is_some() { + self.counts.belongs += 1; + return Sample::Belongs; + } + let newest = self.live.iter().rev().find(|f| f.begun); + if let Some(frame) = newest { + // (Its simulation's end, not its first submission: a submission + // that came while the opening reading still slept ended nothing, + // and the readings of that simulation must not open another.) + if !frame.has(Stage::SimulationEnd) && frame.present == 0 { + self.counts.held_back += 1; + return Sample::HeldBack; + } + // Which thread reads, against the one that begins frames; and + // how long after that frame's first submission. + self.counts.openings_by_thread[usize::from(frame.thread != thread)] += 1; + if frame.submitted { + self.counts.submit_to_open.add(now.saturating_sub(frame.submitted_at)); + } + } + let index = self.push(0, 0, false, thread, now); + self.open = Some(index); + self.sampler = thread; + self.since_opened = 0; + self.counts.opened += 1; + Sample::Open(index) + } + + /// The sleep of the simulation `index` opened returned at `now`: its + /// simulation start and its input sample, now sent; none if the frame + /// is over or its present already sent its simulation's markers (the + /// sample is lost then, and counted). + pub fn sampled(&mut self, index: u32, now: u64) -> Markers { + let Some(frame) = self.live.iter_mut().find(|f| f.index == index) else { + self.counts.lost += 1; + return Markers(0); + }; + if frame.started() { + self.counts.lost += 1; + return Markers(0); + } + // While no origin wait has it, the opening counts from here (the + // gap to the adoption is measured after the sleep). + if !frame.begun { + frame.at = frame.at.max(now); + } + let owed = bit(Stage::SimulationStart) | bit(Stage::InputSample); + frame.sent |= owed; + self.counts.sampled += 1; + Markers(owed) + } + + /// The title submits command lists to a queue that draws, on `thread` + /// at `now`, tagged with frame token `origin` (0: not tagged): at the + /// frame's first submission its simulation ends and its submissions + /// begin. The frame is the one of that token, else the newest begun + /// frame whose simulation runs and whose present the title has not + /// called (never a simulation no origin wait has taken). Which of the + /// two ended a frame's simulation is counted, for the line. + pub fn submit(&mut self, origin: u64, thread: u32, now: u64) -> Option<(u32, Markers)> { + let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten(); + let at = match tagged { + Some(at) => at, + None => self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0)?, + }; + let frame = &mut self.live[at]; + let first = !frame.submitted; + if first { + frame.submitted = true; + frame.submitted_at = now; + self.counts.first_submits_by_thread[usize::from(frame.thread != thread)] += 1; + self.counts.origin_to_submit.add(now.saturating_sub(frame.at)); + } + // A frame still in its sleep has no simulation to end. (At the + // origin wait that cannot be: the title has not got the token yet. + // At a reading it means this submission is of a simulation before.) + if !frame.started() { + if first { + self.counts.submitted_before_start += 1; + } + return None; + } + let owed = frame.reach(Stage::SubmitStart); + // Later submissions of the frame owe nothing and count nothing. + if owed.is_empty() { + return None; + } + // Counted where it has an effect: this submission is the one that + // ends the frame's simulation. + match tagged { + Some(_) => self.counts.submitted_by_token += 1, + None => self.counts.submitted_by_order += 1, + } + Some((frame.index, owed)) + } + + /// The title calls its present number `present` (counted from 1) on + /// `thread` with frame token `origin` in its first plane (0: none): the + /// present is that frame's, else the newest begun frame's whose + /// simulation runs and that has no present yet. Frames begun before it + /// that have none are over: the title never presented them. (By the + /// token the frame need not have started: a simulation whose reading is + /// still in its sleep may be presented, and then sends what it owes at + /// the present.) + pub fn title_presents(&mut self, present: u64, origin: u64, thread: u32) { + let tagged = (origin != 0).then(|| self.live.iter().position(|f| f.origin == origin)).flatten(); + let at = match tagged { + Some(at) if self.live[at].present == 0 => { + self.counts.by_token += 1; + at + } + // The token's frame has its present: this one shows that frame + // again, and the host's present of it names that frame's index + // ([`Frames::presenting`]). + Some(at) => { + self.repeat = Some((present, self.live[at].index)); + return; + } + None => { + let Some(at) = self.live.iter().rposition(|f| f.begun && f.started() && f.present == 0) else { return }; + self.counts.by_order += 1; + at + } + }; + self.counts.presents_by_thread[usize::from(self.live[at].thread != thread)] += 1; + self.live[at].present = present; + let before = self.live.len(); + let mut place = 0; + // (An open simulation is the newest, after `at`: it stays.) + self.live.retain(|f| { + let keep = place >= at || f.present != 0; + place += 1; + keep + }); + self.counts.never_presented += (before - self.live.len()) as u32; + } + + /// Present number `present` begins on the host: its frame's index. The + /// indexes the host presents must keep rising: frame generation's + /// constants, tags and present markers use them, and its guide ties + /// present markers out of step with the frame shown to constants it + /// cannot find. So a present the title began no frame for does not get + /// an index newer than a simulation still to be presented: + /// - a second present of one frame's token shows that frame again and + /// gets its index (its markers were sent once, nothing more is); + /// - another, while a simulation a reading opened is open, takes that + /// simulation (the next index in order): its markers are completed + /// here, and the next origin wait has none to take; + /// - else it gets a frame made here, which owes every marker (the + /// check's presents, a present before the title's first frame). + /// + /// The line counts all three as presents with no frame begun; in the + /// runs there were none in the title. + pub fn presenting(&mut self, present: u64) -> u32 { + if present != 0 + && let Some(frame) = self.live.iter().find(|f| f.present == present) + { + if !frame.has(Stage::SubmitStart) { + self.counts.unsubmitted += 1; + } + return frame.index; + } + self.counts.unbegun += 1; + if present != 0 + && let Some((repeated, index)) = self.repeat + && repeated == present + { + self.repeat = None; + return index; + } + if let Some(index) = self.open.take() + && let Some(frame) = self.live.iter_mut().find(|f| f.index == index) + { + frame.present = present; + return index; + } + self.push(0, present, false, 0, 0) + } + + /// The present of frame `index` returned: its last marker, and the frame + /// is over. + pub fn presented(&mut self, index: u32) -> Markers { + let Some(at) = self.live.iter().position(|f| f.index == index) else { return Markers(0) }; + let owed = self.live[at].reach(Stage::PresentEnd); + self.live.remove(at); ~~~~ --- Fixed in c5cd5410 as well: the last `KEPT` presented frames' origin tokens and indexes are kept apart from the live marker state, so a repeat arriving after the host present still reuses that index with no markers. Regression test: `a_further_present_after_the_hosts_present_shows_that_frame_again` (it also checks the history is bounded).
Adriwin06 commented 2026-11-30 00:54:56 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Adriwin06 on 2026-11-30T00:54:56Z.

Code review location: crates/victory-gpu/src/streamline.rs; line 1388

@@ -1280,21 +1365,70 @@ pub(crate) fn device_made(device: &ID3D12Device) -> Option<ID3D12CommandQueue> {
             tracing::warn!("DLSS Frame Generation stays off: the device hand-over to Streamline did not complete");
         }
     }
+    // Reflex by itself (`VICTORY_REFLEX`): its functions whenever Streamline
+    // is loaded, with or without frame generation.
+    let mut reflex_ready = false;
+    if let Some(mode) = plan.reflex {
+        functions.reflex_set_options =
+            functions.reflex_set_options.or_else(|| f!(abi::FEATURE_REFLEX, c"slReflexSetOptions", abi::SlReflexSetOptions));
+        functions.pcl_set_marker = functions.pcl_set_marker.or_else(|| f!(abi::FEATURE_PCL, c"slPCLSetMarker", abi::SlPclSetMarker));
+        functions.reflex_sleep = f!(abi::FEATURE_REFLEX, c"slReflexSleep", abi::SlReflexSleep);
+        functions.reflex_get_state = f!(abi::FEATURE_REFLEX, c"slReflexGetState", abi::SlReflexGetState);
+        if !plan.framegen {
+            log_version(sl, abi::FEATURE_REFLEX, "Reflex");
+        }
+        match (functions.reflex_set_options, functions.reflex_sleep, functions.pcl_set_marker) {
+            (Some(set_options), Some(_), Some(_)) => {
+                if !reflex_set {
+                    let options = reflex_options(mode.sl_mode());
+                    // SAFETY: filled options; nothing else calls the library yet.
+                    let code = unsafe { set_options(&options) };
+                    tracing::info!(code, result = abi::result_name(code), mode = mode.name(), "Streamline: Reflex options set (VICTORY_REFLEX)");
+                }
+                reflex_ready = true;

Fixed in e2561b1e: the frame-generation setup now carries the slReflexSetOptions result code, and the VICTORY_REFLEX path calls the function only if nothing was asked yet. It publishes REFLEX_READY only when the code is OK; otherwise it warns and standalone Reflex stays off.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:review-comment:4734027143 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/3072#discussion_r4734027143). Originally posted by [Adriwin06](https://github.com/Adriwin06) on 2026-11-30T00:54:56Z. **Code review location:** `crates/victory-gpu/src/streamline.rs`; line 1388 ~~~~diff @@ -1280,21 +1365,70 @@ pub(crate) fn device_made(device: &ID3D12Device) -> Option<ID3D12CommandQueue> { tracing::warn!("DLSS Frame Generation stays off: the device hand-over to Streamline did not complete"); } } + // Reflex by itself (`VICTORY_REFLEX`): its functions whenever Streamline + // is loaded, with or without frame generation. + let mut reflex_ready = false; + if let Some(mode) = plan.reflex { + functions.reflex_set_options = + functions.reflex_set_options.or_else(|| f!(abi::FEATURE_REFLEX, c"slReflexSetOptions", abi::SlReflexSetOptions)); + functions.pcl_set_marker = functions.pcl_set_marker.or_else(|| f!(abi::FEATURE_PCL, c"slPCLSetMarker", abi::SlPclSetMarker)); + functions.reflex_sleep = f!(abi::FEATURE_REFLEX, c"slReflexSleep", abi::SlReflexSleep); + functions.reflex_get_state = f!(abi::FEATURE_REFLEX, c"slReflexGetState", abi::SlReflexGetState); + if !plan.framegen { + log_version(sl, abi::FEATURE_REFLEX, "Reflex"); + } + match (functions.reflex_set_options, functions.reflex_sleep, functions.pcl_set_marker) { + (Some(set_options), Some(_), Some(_)) => { + if !reflex_set { + let options = reflex_options(mode.sl_mode()); + // SAFETY: filled options; nothing else calls the library yet. + let code = unsafe { set_options(&options) }; + tracing::info!(code, result = abi::result_name(code), mode = mode.name(), "Streamline: Reflex options set (VICTORY_REFLEX)"); + } + reflex_ready = true; ~~~~ --- Fixed in e2561b1e: the frame-generation setup now carries the `slReflexSetOptions` result code, and the `VICTORY_REFLEX` path calls the function only if nothing was asked yet. It publishes `REFLEX_READY` only when the code is OK; otherwise it warns and standalone Reflex stays off.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3072:upstream-pr/3072'
git switch 'upstream-pr/3072'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3072'
git switch 'upstream-pr/3072'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3072'
git switch 'upstream-pr/3072'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3072'
git switch 'main'
git merge --squash 'upstream-pr/3072'
git switch 'main'
git merge --ff-only 'upstream-pr/3072'
git switch 'main'
git merge 'upstream-pr/3072'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
trustno1-coder/VIctory-NVIDIA!3072
No description provided.