diff --git a/crates/pf-nx-app/src/core/settings.rs b/crates/pf-nx-app/src/core/settings.rs index 2947042..7b4e6e9 100644 --- a/crates/pf-nx-app/src/core/settings.rs +++ b/crates/pf-nx-app/src/core/settings.rs @@ -1,8 +1,8 @@ //! This client's typed view of the shared settings document (`pf_client_core::trust::Settings`), -//! the one settings type it stores and edits. Every row here is a shared field; a row only the -//! console has would live in `extra` under an `nx.` prefix, and none exists. +//! the one settings type it stores and edits. Every row here is a shared field but Save Battery, +//! which only the console has and which lives in `extra` under an `nx.` prefix. -use pf_client_core::trust::Settings; +use pf_client_core::trust::{PresentPriority, Settings}; use punktfunk_core::config::GamepadPref; use crate::core::model::{CodecPref, GamepadType}; @@ -27,8 +27,18 @@ fn local_codec(name: &str) -> CodecPref { } } +/// Save Battery's key in `extra`: on, the title leaves the clocks to the system. +pub const SAVE_BATTERY_KEY: &str = "nx.save_battery"; + /// The typed reads and writes this client makes on the shared document. pub trait NxSettings { + /// Whether the title leaves the clocks to the system instead of holding its own. Off until + /// the player turns it on. + fn save_battery(&self) -> bool; + fn set_save_battery(&mut self, on: bool); + /// The shared rule but for Automatic smoothness, which takes one frame here, not two: on the + /// console one frame presents as many pictures as two, a refresh sooner. + fn nx_present_priority(&self) -> PresentPriority; fn codec_pref(&self) -> CodecPref; fn set_codec_pref(&mut self, codec: CodecPref); fn gamepad_type(&self) -> GamepadType; @@ -41,6 +51,24 @@ pub trait NxSettings { } impl NxSettings for Settings { + fn save_battery(&self) -> bool { + self.extra + .get(SAVE_BATTERY_KEY) + .and_then(serde_json::Value::as_bool) + .unwrap_or(false) + } + + fn set_save_battery(&mut self, on: bool) { + self.extra.insert(SAVE_BATTERY_KEY.into(), serde_json::Value::Bool(on)); + } + + fn nx_present_priority(&self) -> PresentPriority { + match self.present_priority() { + PresentPriority::Smooth { .. } if self.smooth_buffer == 0 => PresentPriority::Smooth { buffer: 1 }, + shared => shared, + } + } + fn codec_pref(&self) -> CodecPref { local_codec(&self.codec) } @@ -100,6 +128,31 @@ mod tests { assert_eq!(back.gamepad_type(), GamepadType::JoyConPair); } + #[test] + fn save_battery_starts_off_and_round_trips() { + let mut s = default_document(); + assert!(!s.save_battery()); + s.set_save_battery(true); + let back: Settings = serde_json::from_value(serde_json::to_value(&s).unwrap()).unwrap(); + assert!(back.save_battery()); + assert_eq!(back.extra[SAVE_BATTERY_KEY], serde_json::Value::Bool(true)); + } + + #[test] + fn automatic_smoothness_takes_one_frame() { + let mut s = default_document(); + s.present_priority = "smooth".into(); + s.smooth_buffer = 0; + assert_eq!(s.nx_present_priority(), PresentPriority::Smooth { buffer: 1 }); + for buffer in 1..=3 { + s.smooth_buffer = buffer; + assert_eq!(s.nx_present_priority(), PresentPriority::Smooth { buffer }); + } + s.present_priority = "latency".into(); + s.smooth_buffer = 0; + assert_eq!(s.nx_present_priority(), PresentPriority::Latency); + } + #[test] fn clamp_keeps_hdr_and_narrows_channels() { let mut s = default_document(); diff --git a/crates/pf-nx-app/src/platform/fake.rs b/crates/pf-nx-app/src/platform/fake.rs index 3b8b333..b466e7c 100644 --- a/crates/pf-nx-app/src/platform/fake.rs +++ b/crates/pf-nx-app/src/platform/fake.rs @@ -8,8 +8,8 @@ use std::sync::{Arc, Mutex}; use anyhow::Result; use super::{ - AudioOut, AudioPort, Display, Fit, FrameReport, Lifecycle, Motion, PadFeedback, PadSample, Pads, Refresh, Rgba, - Storage, StreamSpec, SystemEvent, TouchPoint, VideoDecoders, + AudioOut, AudioPort, ClockStage, Display, Fit, FrameReport, Lifecycle, Motion, PadFeedback, PadSample, Pads, + Refresh, Rgba, Storage, StreamSpec, SystemEvent, TouchPoint, VideoDecoders, }; use crate::core::caps::VideoCaps; use crate::core::media::{VideoSink, VideoSinkCaps}; @@ -240,6 +240,7 @@ impl Storage for FakeStorage { pub struct FakeLifecycle { pub events: Arc>>, pub splash_hidden: Arc>, + pub clock_stages: Arc>>, } impl Lifecycle for FakeLifecycle { @@ -251,6 +252,10 @@ impl Lifecycle for FakeLifecycle { out.extend(self.events.lock().expect("fake lifecycle poisoned").drain(..)); } + fn set_clock_stage(&mut self, stage: ClockStage) { + self.clock_stages.lock().expect("fake lifecycle poisoned").push(stage); + } + fn exit(&self) -> ! { panic!("title exited"); } diff --git a/crates/pf-nx-app/src/platform/mod.rs b/crates/pf-nx-app/src/platform/mod.rs index 129938c..a373069 100644 --- a/crates/pf-nx-app/src/platform/mod.rs +++ b/crates/pf-nx-app/src/platform/mod.rs @@ -342,6 +342,14 @@ pub trait Lifecycle { None } + /// Holds the clocks for `stage`. [`Self::exit`] hands them back. + fn set_clock_stage(&mut self, _stage: ClockStage) {} + + /// Hands the clocks back from any thread, for a panic, which never reaches [`Self::exit`]. + fn clock_release(&self) -> Option { + None + } + /// Shows the system's keyboard over the title and blocks until the player closes it: the /// text they confirmed, or `None` when they cancelled or there is no such keyboard. fn keyboard(&mut self) -> Option { @@ -401,6 +409,82 @@ impl SocketCalls { } } +/// What the title is doing, for the clocks it holds. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ClockStage { + Menu, + Stream, + /// Save Battery: the system's own clocks, the title holds none. + System, +} + +/// The rates a stage holds, in Hz. `None` leaves that clock to the system. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ClockTargets { + pub cpu_hz: Option, + pub gpu_hz: Option, + pub emc_hz: Option, +} + +impl ClockStage { + /// The menu's rates keep it near 60 fps for under a watt. The stream needs the CPU: it cuts + /// the receive path and the VIC transfer, and the GPU adds little there. Docked, the system's + /// GPU rate is already above the menu's, so the GPU stays the system's. + pub fn targets(self, mode: OperationMode) -> ClockTargets { + match self { + Self::Menu => ClockTargets { + cpu_hz: Some(1_428_000_000), + gpu_hz: (mode == OperationMode::Handheld).then_some(422_400_000), + emc_hz: Some(1_600_000_000), + }, + Self::Stream => ClockTargets { + cpu_hz: Some(1_785_000_000), + gpu_hz: None, + emc_hz: Some(1_600_000_000), + }, + Self::System => ClockTargets { + cpu_hz: None, + gpu_hz: None, + emc_hz: None, + }, + } + } +} + +impl ClockTargets { + /// Only the rates above what the system or the player's profile runs: the title raises a + /// clock and never lowers one. An unknown rate (0) is held. + pub fn above(self, running: Clocks) -> Self { + let raise = |want: Option, run: u32| want.filter(|&hz| run == 0 || run < hz); + Self { + cpu_hz: raise(self.cpu_hz, running.cpu_hz), + gpu_hz: raise(self.gpu_hz, running.gpu_hz), + emc_hz: raise(self.emc_hz, running.emc_hz), + } + } + + /// `holds cpu 1785.0; leaves gpu at 384.0, emc at 2400.0 MHz`, for the log. + pub fn describe(self, running: Clocks) -> String { + let mhz = |hz: u32| f64::from(hz) / 1e6; + let rows = [ + ("cpu", self.cpu_hz, running.cpu_hz), + ("gpu", self.gpu_hz, running.gpu_hz), + ("emc", self.emc_hz, running.emc_hz), + ]; + let join = |v: Vec| if v.is_empty() { "none".to_string() } else { v.join(", ") }; + let holds = rows + .iter() + .filter_map(|(n, hz, _)| hz.map(|hz| format!("{n} {:.1}", mhz(hz)))) + .collect(); + let leaves = rows + .iter() + .filter(|(_, hz, _)| hz.is_none()) + .map(|(n, _, run)| format!("{n} at {:.1}", mhz(*run))) + .collect(); + format!("holds {}; leaves {} MHz", join(holds), join(leaves)) + } +} + /// The CPU, GPU and memory clocks, in Hz. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Clocks { @@ -421,3 +505,60 @@ impl std::fmt::Display for Clocks { ) } } + +#[cfg(test)] +mod clock_tests { + use super::{ClockStage, Clocks, OperationMode}; + + #[test] + fn the_menu_raises_the_gpu_only_in_handheld() { + assert_eq!( + ClockStage::Menu.targets(OperationMode::Handheld).gpu_hz, + Some(422_400_000) + ); + assert_eq!(ClockStage::Menu.targets(OperationMode::Docked).gpu_hz, None); + } + + #[test] + fn the_stream_leaves_the_gpu_and_stays_in_the_official_limits() { + for mode in [OperationMode::Handheld, OperationMode::Docked] { + let stream = ClockStage::Stream.targets(mode); + assert_eq!(stream.cpu_hz, Some(1_785_000_000)); + assert_eq!(stream.gpu_hz, None); + assert_eq!(stream.emc_hz, Some(1_600_000_000)); + } + } + + /// A rate the profile already runs at or above the stage's is left; a lower one is raised. + #[test] + fn the_title_only_raises_a_clock() { + let mhz = |m: u32| m * 1_000_000; + let run = |cpu, gpu, emc| Clocks { + cpu_hz: mhz(cpu), + gpu_hz: mhz(gpu), + emc_hz: mhz(emc), + }; + let stream = ClockStage::Stream.targets(OperationMode::Handheld); + let governed = stream.above(run(612, 384, 2400)); + assert_eq!( + (governed.cpu_hz, governed.gpu_hz, governed.emc_hz), + (Some(mhz(1785)), None, None), + "the governor's 612 is raised, a 2400 memory clock left" + ); + let profile = stream.above(run(2397, 768, 1600)); + assert_eq!((profile.cpu_hz, profile.gpu_hz, profile.emc_hz), (None, None, None)); + assert_eq!(stream.above(Clocks::default()), stream, "an unknown rate is held"); + assert_eq!( + governed.describe(run(612, 384, 2400)), + "holds cpu 1785.0; leaves gpu at 384.0, emc at 2400.0 MHz" + ); + } + + #[test] + fn save_battery_holds_nothing() { + for mode in [OperationMode::Handheld, OperationMode::Docked] { + let system = ClockStage::System.targets(mode); + assert_eq!((system.cpu_hz, system.gpu_hz, system.emc_hz), (None, None, None)); + } + } +} diff --git a/crates/pf-nx-app/src/runtime/connect.rs b/crates/pf-nx-app/src/runtime/connect.rs index f2c324c..0c683e9 100644 --- a/crates/pf-nx-app/src/runtime/connect.rs +++ b/crates/pf-nx-app/src/runtime/connect.rs @@ -125,7 +125,7 @@ pub(super) fn spawn( // Pad-only: the host draws the cursor. cursor_capture: true, pad_audio_caps: 0, - present_priority: settings.present_priority(), + present_priority: settings.nx_present_priority(), // A spelling the wire can't carry is no wish. screen_wish: ScreenWish::parse(&settings.host_screen), }, diff --git a/crates/pf-nx-app/src/runtime/menu.rs b/crates/pf-nx-app/src/runtime/menu.rs index 5e4c38c..7c32339 100644 --- a/crates/pf-nx-app/src/runtime/menu.rs +++ b/crates/pf-nx-app/src/runtime/menu.rs @@ -149,6 +149,9 @@ pub(super) fn run(app: &mut App, notice: Option) -> Result { } service.tick(); + // Save Battery takes effect as the player flips it. + app.save_battery = store.with(|s| s.settings.save_battery()); + app.hold_clocks(crate::platform::ClockStage::Menu); while let Some(action) = console.take_action() { match action { diff --git a/crates/pf-nx-app/src/runtime/mod.rs b/crates/pf-nx-app/src/runtime/mod.rs index df91fd2..1ebce62 100644 --- a/crates/pf-nx-app/src/runtime/mod.rs +++ b/crates/pf-nx-app/src/runtime/mod.rs @@ -13,10 +13,11 @@ pub mod testrun; mod touch; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::OnceLock; use std::time::Instant; use crate::core::model::bitrate_max_kbps; -use crate::platform::{Display, Lifecycle, Pads, Platform, SocketCalls, SystemEvent}; +use crate::platform::{ClockStage, Display, Lifecycle, Pads, Platform, SocketCalls, SystemEvent}; use crate::services::power::ExitPlan; use crate::services::store; use crate::session::{self, Media}; @@ -32,9 +33,23 @@ pub(crate) struct App { /// A scripted run from `test-run.json`, taken at start-up. pub test_run: Option, pub device: crate::platform::DeviceInfo, + /// The player's Save Battery, as the menu last read it. + pub save_battery: bool, + /// The stage last handed to the lifecycle. + pub clock_stage: ClockStage, } impl App { + /// Holds the clocks for `stage`, or leaves them to the system while Save Battery is on. + /// Asks the lifecycle only on a change. + fn hold_clocks(&mut self, stage: ClockStage) { + let stage = if self.save_battery { ClockStage::System } else { stage }; + if stage != self.clock_stage { + self.clock_stage = stage; + self.lifecycle.set_clock_stage(stage); + } + } + /// System events since the last call. `Suspend` also sets [`SUSPENDED`]. fn system_events(&mut self) -> Vec { let mut events = Vec::new(); @@ -107,13 +122,16 @@ pub fn run(platform: Platform) -> ! { audio, pads, storage, - lifecycle, + mut lifecycle, log, device, } = platform; crate::services::paths::install(storage.data_dir()); // Without a log there is nothing to diagnose a failure from; the title still runs. let flush = crate::logger::init_subscriber(&crate::services::paths::logs_dir(), log).ok(); + if let Some(release) = lifecycle.clock_release() { + let _ = CLOCK_RELEASE.set(release); + } install_panic_hook(); let language = pf_l10n::set_languages(&device.languages); tracing::info!( @@ -128,6 +146,16 @@ pub fn run(platform: Platform) -> ! { ); tracing::info!("language {language} for the system's {:?}", device.languages); punktfunk_core::client::set_client_label(&client_label(&device)); + let save_battery = { + use crate::core::settings::NxSettings; + store::load().settings.save_battery() + }; + let clock_stage = if save_battery { + ClockStage::System + } else { + ClockStage::Menu + }; + lifecycle.set_clock_stage(clock_stage); crate::core::caps::install(video.caps()); // ureq's agents resolve their provider from the process default and panic without one. punktfunk_core::tls::install_default_provider(); @@ -139,6 +167,8 @@ pub fn run(platform: Platform) -> ! { identity: (String::new(), String::new()), test_run: testrun::take(), device, + save_battery, + clock_stage, }; let plan = match store::load_or_create_identity() { Ok(identity) => { @@ -190,10 +220,16 @@ fn alternate(app: &mut App) -> Option { }; match outcome { UiOutcome::Quit(plan) => return plan, - UiOutcome::Launch(launch) => match stream::run(app, *launch) { - StreamOutcome::ReturnToMenu(why) => notice = why, - StreamOutcome::Quit(plan) => return plan, - }, + UiOutcome::Launch(launch) => { + app.hold_clocks(ClockStage::Stream); + match stream::run(app, *launch) { + StreamOutcome::ReturnToMenu(why) => { + app.hold_clocks(ClockStage::Menu); + notice = why; + } + StreamOutcome::Quit(plan) => return plan, + } + } } } } @@ -203,15 +239,21 @@ fn client_label(device: &crate::platform::DeviceInfo) -> String { format!("Switch {}", device.firmware).trim_end().to_string() } +/// The platform's way to hand the clocks back, for the panic hook. +static CLOCK_RELEASE: OnceLock = OnceLock::new(); + /// A panic on any thread goes to the log, then its frames where the target can walk them, then -/// the process aborts. The message is flushed before the walk: on the console, which builds -/// without unwind tables, the walk itself aborts. +/// the process aborts. The message is flushed and the clocks go back before the walk: on the +/// console, which builds without unwind tables, the walk itself aborts. fn install_panic_hook() { std::panic::set_hook(Box::new(|info| { let thread = std::thread::current(); let name = thread.name().unwrap_or("unnamed"); tracing::error!("PANIC on thread {name:?}: {info}"); crate::logger::flush(); + if let Some(release) = CLOCK_RELEASE.get() { + release(); + } let backtrace = std::backtrace::Backtrace::force_capture(); tracing::error!("PANIC on thread {name:?}, frames:\n{backtrace}"); crate::logger::flush(); diff --git a/crates/pf-nx-app/tests/seams.rs b/crates/pf-nx-app/tests/seams.rs index 06d43b1..457285a 100644 --- a/crates/pf-nx-app/tests/seams.rs +++ b/crates/pf-nx-app/tests/seams.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use pf_nx_app::platform::fake::{FakeAudio, FakeDisplay, FakeLifecycle, FakePads, FakeStorage, FakeVideo}; +use pf_nx_app::platform::ClockStage; use pf_nx_app::platform::{AudioOut, Display, Pads, Platform, Refresh, SocketCalls, Storage}; /// A display presents what the UI drew and reads it back at its own size. @@ -59,6 +60,8 @@ fn a_menu_test_run_leaves_a_bundle_and_exits() { let storage = FakeStorage::temp("menu-run"); std::fs::write(storage.data_dir().join("test-run.json"), r#"{"scenario":"menu"}"#).unwrap(); let dir = storage.data_dir().to_path_buf(); + let lifecycle = FakeLifecycle::default(); + let clock_stages = lifecycle.clock_stages.clone(); let title = std::thread::spawn(move || { pf_nx_app::run(Platform { display: Box::new(FakeDisplay::new(640, 360)), @@ -66,7 +69,7 @@ fn a_menu_test_run_leaves_a_bundle_and_exits() { audio: Arc::new(FakeAudio::default()), pads: Box::new(FakePads::default()), storage: Arc::new(storage), - lifecycle: Box::new(FakeLifecycle::default()), + lifecycle: Box::new(lifecycle), log: None, device: pf_nx_app::platform::DeviceInfo { platform: "fake", @@ -77,6 +80,11 @@ fn a_menu_test_run_leaves_a_bundle_and_exits() { let exit = title.join().expect_err("the title only leaves through Lifecycle::exit"); assert_eq!(exit.downcast_ref::<&str>(), Some(&"title exited")); assert!(!dir.join("test-run.json").exists(), "the scenario is consumed"); + assert_eq!( + *clock_stages.lock().unwrap(), + [ClockStage::Menu], + "the menu holds its clocks from the start" + ); let verdict_root = dir.join("verdict"); let bundle = std::fs::read_dir(&verdict_root) .unwrap() diff --git a/crates/pf-nx-platform/src/console/clocks.rs b/crates/pf-nx-platform/src/console/clocks.rs new file mode 100644 index 0000000..2afc8f6 --- /dev/null +++ b/crates/pf-nx-platform/src/console/clocks.rs @@ -0,0 +1,216 @@ +//! The clocks the title holds for each [`ClockStage`], and the way back to the system's own. +//! +//! The title only raises a clock. Each one runs at the rate the system or the player's overclock +//! profile set, read before the title asks for anything; a stage holds a clock only where that +//! rate is below the stage's. A memory clock a player runs at 2400 stays there (issue 30's +//! console froze on a runtime memory change). +//! +//! A running overclock module takes the ask: it keeps the rates through sleep on its own, and +//! puts back whatever clkrst sets (with no profile, Horizon OC resets the clock in 100-300 ms). +//! Without one the title sets clkrst itself. The system puts its own rates back on a wake, on a +//! return from HOME and on a dock change (NOTES, 2026-11-07), so the title asks again at those +//! events, with a module too, and once more [`AGAIN_AFTER`] later in case the system moved them +//! after the event. Between events it reads nothing. +//! +//! A module's hold outlives the title, so the first stage lets go of whatever a crash left and +//! reads the rates once the module has put its own back. [`release`] runs on every way out. + +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +use pf_nx_app::platform::{ClockStage, Clocks, OperationMode}; +use pf_nx_sys::ocmod::{self, OcModule}; +use pf_nx_sys::{clk, result_code}; + +/// After an event that moves the clocks, how long until the title asks once more. Also how long +/// a module takes to put its own rates back once a hold is let go (about 0.3 s, NOTES). +const AGAIN_AFTER: Duration = Duration::from_millis(500); +/// Log lines for clocks asked again, so a console that wakes all day cannot fill the log. +const KEEP_LINES: u32 = 20; + +/// CPU, GPU and memory: the module's id, then clkrst's. +const CLOCKS: [(u32, u32); 3] = [ + (ocmod::MODULE_CPU, clk::MODULE_CPU), + (ocmod::MODULE_GPU, clk::MODULE_GPU), + (ocmod::MODULE_MEM, clk::MODULE_EMC), +]; + +/// The module found at the first stage. Statics, so a panic on any thread can reach them. +static MODULE: OnceLock> = OnceLock::new(); +/// The rates the system or the player's profile runs, in [`CLOCKS`]' order; 0 is unknown. +static STOCK: [AtomicU32; 3] = [AtomicU32::new(0), AtomicU32::new(0), AtomicU32::new(0)]; + +fn module() -> Option { + *MODULE.get_or_init(|| { + // The first read comes before any ask, so it is what the system chose. Under a module it + // may be a crash's hold, so the first stage reads again once that is let go. + read_stock(); + match OcModule::find() { + Ok(Some(module)) => { + tracing::info!("clocks: asking {}", module.service()); + Some(module) + } + Ok(None) => { + tracing::info!("clocks: no overclock module, setting them directly"); + None + } + Err(rc) => { + tracing::warn!("clocks: sm could not say ({}), setting them directly", result_code(rc)); + None + } + } + }) +} + +fn read_stock() { + if let Some(c) = clk::clocks() { + store_stock(&[c.cpu_hz, c.gpu_hz, c.emc_hz]); + } +} + +fn store_stock(rates: &[u32; 3]) { + for (slot, hz) in STOCK.iter().zip(rates) { + slot.store(*hz, Ordering::Relaxed); + } +} + +/// Hands the clocks back. Safe on any thread and more than once; a title that never asked +/// touches nothing. +pub fn release() { + match MODULE.get() { + Some(Some(module)) => { + for (id, _) in CLOCKS { + let _ = module.hold(id, 0); + } + } + Some(None) => { + for ((_, id), stock) in CLOCKS.into_iter().zip(&STOCK) { + let hz = stock.load(Ordering::Relaxed); + if hz != 0 { + let _ = clk::set_rate(id, hz); + } + } + } + None => {} + } +} + +/// The stage in force, kept up on the main thread. +pub struct ClockHold { + stage: Option, + mode: OperationMode, + /// The first stage has run: a crash's hold is let go and the rates are being read. + started: bool, + /// When to ask once more after an event that moves the clocks. + again: Option, + /// The rates the system or the profile runs changed (a dock change, the first stage under a + /// module), so the next ask reads them first and nothing is asked before it. + restock: bool, + keep_lines: u32, +} + +impl ClockHold { + pub fn new(mode: OperationMode) -> Self { + Self { + stage: None, + mode, + started: false, + again: None, + restock: false, + keep_lines: 0, + } + } + + pub fn set_stage(&mut self, stage: ClockStage) { + tracing::info!("clocks: {stage:?}"); + if !std::mem::replace(&mut self.started, true) && module().is_some() { + // A hold a crash left would read as the profile's rate: let go of it, then read. + release(); + self.restock = true; + self.again = Some(Instant::now() + AGAIN_AFTER); + } + if stage == ClockStage::System { + // With no stage the title stops asking again. + release(); + self.stage = None; + return; + } + self.stage = Some(stage); + if !self.restock { + self.apply(); + } + } + + /// A dock change: the rates the system or the profile runs change with it. A module's holds + /// are let go so it can put the new ones back, and they are read [`AGAIN_AFTER`] from here. + pub fn mode_changed(&mut self, mode: OperationMode) { + self.mode = mode; + if self.stage.is_none() { + return; + } + if module().is_some() { + release(); + } + self.restock = true; + self.again = Some(Instant::now() + AGAIN_AFTER); + } + + /// The system may have put its own clocks back: a wake, a return to focus, a new performance + /// mode. The title asks again now and once more [`AGAIN_AFTER`] later. + pub fn system_moved(&mut self, why: &str) { + if self.stage.is_none() || self.restock { + return; + } + if self.keep_lines < KEEP_LINES { + self.keep_lines += 1; + tracing::info!("clocks: {why}, asking again"); + } + self.apply(); + self.again = Some(Instant::now() + AGAIN_AFTER); + } + + /// Once a frame: the second ask after an event, when it is due. Reads no clock otherwise. + pub fn tick(&mut self) { + if self.again.is_some_and(|at| Instant::now() >= at) { + self.again = None; + if std::mem::take(&mut self.restock) { + read_stock(); + } + self.apply(); + } + } + + fn apply(&mut self) { + let Some(stage) = self.stage else { return }; + let targets = stage.targets(self.mode); + let stock = STOCK.each_ref().map(|s| s.load(Ordering::Relaxed)); + let running = Clocks { + cpu_hz: stock[0], + gpu_hz: stock[1], + emc_hz: stock[2], + }; + let held = targets.above(running); + if self.keep_lines < KEEP_LINES { + tracing::info!("clocks: {stage:?} {}", held.describe(running)); + } + let wanted = [held.cpu_hz, held.gpu_hz, held.emc_hz]; + if let Some(module) = module() { + for ((id, _), hz) in CLOCKS.into_iter().zip(wanted) { + if let Err(rc) = module.hold(id, hz.unwrap_or(0)) { + tracing::warn!("clocks: {} refused module {id}: {}", module.service(), result_code(rc)); + } + } + return; + } + for (((_, id), hz), stock) in CLOCKS.into_iter().zip(wanted).zip(stock) { + let hz = hz.unwrap_or(stock); + if hz == 0 { + continue; + } + if let Err(rc) = clk::set_rate(id, hz) { + tracing::warn!("clocks: clkrst refused {id:#x}: {}", result_code(rc)); + } + } + } +} diff --git a/crates/pf-nx-platform/src/console/lifecycle.rs b/crates/pf-nx-platform/src/console/lifecycle.rs index 6fad193..3a634ea 100644 --- a/crates/pf-nx-platform/src/console/lifecycle.rs +++ b/crates/pf-nx-platform/src/console/lifecycle.rs @@ -8,13 +8,16 @@ use std::cell::OnceCell; use std::sync::mpsc; use std::time::{Duration, Instant}; -use pf_nx_app::platform::{Clocks, Lifecycle, SocketCalls, SystemEvent}; +use pf_nx_app::platform::{ClockStage, Clocks, Lifecycle, SocketCalls, SystemEvent}; use pf_nx_sys::applet::{self, FocusState, HookEvent}; use pf_nx_sys::{clk, mem, pl, rt, set, socket, swkbd}; +use super::clocks::{self, ClockHold}; + pub struct NxLifecycle { events: mpsc::Receiver, _hook: applet::Hook, + hold: ClockHold, /// The system asked the title to close; the next poll leaves. closing: bool, /// The first poll logs the applet type and mode: the logger starts after `new`. @@ -34,6 +37,7 @@ impl NxLifecycle { Self { events, _hook: hook, + hold: ClockHold::new(super::operation_mode()), closing: false, reported: false, fonts: OnceCell::new(), @@ -58,6 +62,7 @@ impl Lifecycle for NxLifecycle { .map_or_else(|| "unreadable".to_string(), |c| c.to_string()) ); } + self.hold.tick(); // `appletMainLoop` in its halves, so every message is logged: no hook event and no // operation-mode change has reached a log yet, the dock change included. if let Some(msg) = applet::take_message() { @@ -72,18 +77,31 @@ impl Lifecycle for NxLifecycle { for event in self.events.try_iter() { match event { HookEvent::FocusState => out.push(match applet::focus_state() { - FocusState::InFocus => SystemEvent::FocusGained, + FocusState::InFocus => { + self.hold.system_moved("back in focus"); + SystemEvent::FocusGained + } FocusState::OutOfFocus => SystemEvent::FocusLost, FocusState::Background => SystemEvent::Suspend, }), - HookEvent::Resume => out.push(SystemEvent::Resume), - HookEvent::OperationMode => out.push(SystemEvent::OperationMode(super::operation_mode())), + HookEvent::Resume => { + self.hold.system_moved("awake"); + out.push(SystemEvent::Resume); + } + HookEvent::OperationMode => { + let mode = super::operation_mode(); + self.hold.mode_changed(mode); + out.push(SystemEvent::OperationMode(mode)); + } // The system moved the title to another clock configuration (WP5's question). - HookEvent::PerformanceMode => tracing::info!( - "lifecycle: performance mode changed, clocks {}", - self.clocks() - .map_or_else(|| "unreadable".to_string(), |c| c.to_string()) - ), + HookEvent::PerformanceMode => { + tracing::info!( + "lifecycle: performance mode changed, clocks {}", + self.clocks() + .map_or_else(|| "unreadable".to_string(), |c| c.to_string()) + ); + self.hold.system_moved("new performance mode"); + } HookEvent::Exit => {} } } @@ -111,6 +129,14 @@ impl Lifecycle for NxLifecycle { }) } + fn set_clock_stage(&mut self, stage: ClockStage) { + self.hold.set_stage(stage); + } + + fn clock_release(&self) -> Option { + Some(clocks::release) + } + fn keyboard(&mut self) -> Option { match swkbd::ask("Text to type on the PC", "Send") { Ok(text) => Some(text), @@ -138,7 +164,9 @@ impl Lifecycle for NxLifecycle { /// Returns the socket driver's lent heap, closes the detached threads' stacks, and leaves /// through libnx's `__appExit`: back to hbl when the heap is clean, else through AM to HOME. + /// HOME's close comes straight here from [`Lifecycle::poll_events`], so the clocks go back here. fn exit(&self) -> ! { + clocks::release(); applet::unlock_exit(); socket::exit(); release_heap(); diff --git a/crates/pf-nx-platform/src/console/mod.rs b/crates/pf-nx-platform/src/console/mod.rs index afe6835..d37f600 100644 --- a/crates/pf-nx-platform/src/console/mod.rs +++ b/crates/pf-nx-platform/src/console/mod.rs @@ -1,6 +1,7 @@ //! The console's implementations, assembled into one [`Platform`]. mod audio; +mod clocks; mod display_fb; mod display_nvk; mod lifecycle; diff --git a/crates/pf-nx-probe/src/clock.rs b/crates/pf-nx-probe/src/clock.rs new file mode 100644 index 0000000..93c4a72 --- /dev/null +++ b/crates/pf-nx-probe/src/clock.rs @@ -0,0 +1,218 @@ +//! Check 7: whether the title can set the CPU clock, and what the system does to it after. +//! +//! Y in the first seconds of a run starts it in place of the other checks. The tester asks for a +//! rate with a button, then sleeps, docks or leaves; every change of the clocks, focus or mode +//! becomes a line. The rate is never put back on the way out: the next run's first line shows +//! what the system left. Runs add to `probe-clock.log`, so one file holds a whole session. +//! +//! X, Y and B set clkrst directly. A and R go through the overclock module, when one runs. + +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::path::Path; +use std::sync::mpsc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use pf_nx_sys::clk::{self, Clocks}; +use pf_nx_sys::ocmod::{OcModule, MODULE_CPU}; +use pf_nx_sys::{applet, hid, result_code}; + +use crate::{nx, Out}; + +/// `HidNpadButton`'s bits. +const BUTTON_A: u64 = 1 << 0; +const BUTTON_B: u64 = 1 << 1; +const BUTTON_X: u64 = 1 << 2; +const BUTTON_Y: u64 = 1 << 3; +const BUTTON_R: u64 = 1 << 7; +const BUTTON_PLUS: u64 = 1 << 10; + +/// The official top rate, a middle one for the menu, and the rate games run at. +const CPU_TOP_HZ: u32 = 1_785_000_000; +const CPU_MIDDLE_HZ: u32 = 1_224_000_000; +const CPU_STOCK_HZ: u32 = 1_020_000_000; + +const ASK_WINDOW: Duration = Duration::from_secs(5); +const FRAME: Duration = Duration::from_micros(16_667); +/// Between reads of the clocks: under the rate a sysmodule could rewrite them at, so a rewrite +/// shows as its own line. +const SAMPLE: Duration = Duration::from_millis(100); +/// A line with nothing new, so a quiet stretch reads as held and not as a stopped probe. +const BEAT: Duration = Duration::from_secs(10); + +/// Runs the check if Y comes within [`ASK_WINDOW`]; `true` once it ran. +pub fn run_if_asked(dir: &Path, out: &mut Out) -> bool { + let mut pads = match hid::Pads::init(1) { + Ok(pads) => pads, + Err(e) => { + out.line(&format!("probe 7 clock fail pads={e:#}")); + return false; + } + }; + out.line("Y now: clock test. Wait 5 s: all the other checks."); + let start = Instant::now(); + while start.elapsed() < ASK_WINDOW && applet::main_loop() { + if buttons(&mut pads) & BUTTON_Y != 0 { + run(dir, out, &mut pads); + return true; + } + nx::screen_flush(); + std::thread::sleep(FRAME); + } + false +} + +/// A line on the screen, in `probe.log` and in `probe-clock.log`. +struct Lines<'a> { + out: &'a mut Out, + file: Option, +} + +impl Lines<'_> { + fn say(&mut self, text: &str) { + let line = format!("probe 7 clock {} {text}", stamp()); + self.out.line(&line); + if let Some(file) = self.file.as_mut() { + let _ = writeln!(file, "{line}").and_then(|()| file.sync_data()); + } + } +} + +fn run(dir: &Path, out: &mut Out, pads: &mut hid::Pads) { + let file = OpenOptions::new() + .create(true) + .append(true) + .open(dir.join("probe-clock.log")) + .ok(); + let mut lines = Lines { out, file }; + let mut seen = clk::clocks(); + lines.say(&format!( + "start {:?} {:?} {:?} {}", + applet::applet_type(), + applet::operation_mode(), + applet::focus_state(), + show(seen) + )); + lines.say("X: CPU 1785. Y: CPU 1224. B: CPU 1020. Plus: leave without restoring."); + let module = find_module(&mut lines); + + let (tx, events) = mpsc::channel(); + let _hook = applet::hook(move |e| { + let _ = tx.send(e); + }); + let mut held = buttons(pads); + let mut sampled = Instant::now(); + let mut beat = Instant::now(); + while applet::main_loop() { + for event in events.try_iter() { + lines.say(&format!( + "event {event:?} {:?} {:?} {}", + applet::operation_mode(), + applet::focus_state(), + show(clk::clocks()) + )); + } + + let now = buttons(pads); + let pressed = now & !held; + held = now; + if pressed & BUTTON_PLUS != 0 { + lines.say(&format!("leave {}", show(clk::clocks()))); + return; + } + for (button, hz) in [(BUTTON_A, CPU_TOP_HZ), (BUTTON_R, 0)] { + if pressed & button != 0 { + let answer = match module.as_ref().map(|m| m.hold(MODULE_CPU, hz)) { + Some(Ok(())) => "ok".to_owned(), + Some(Err(rc)) => format!("FAIL({})", result_code(rc)), + None => "no-module".to_owned(), + }; + lines.say(&format!("hold cpu={} {answer} {}", hz / 1_000_000, show(clk::clocks()))); + } + } + for (button, hz) in [ + (BUTTON_X, CPU_TOP_HZ), + (BUTTON_Y, CPU_MIDDLE_HZ), + (BUTTON_B, CPU_STOCK_HZ), + ] { + if pressed & button != 0 { + let answer = match clk::set_rate(clk::MODULE_CPU, hz) { + Ok(()) => "ok".to_owned(), + Err(rc) => format!("FAIL({})", result_code(rc)), + }; + lines.say(&format!("ask cpu={} {answer} {}", hz / 1_000_000, show(clk::clocks()))); + } + } + + if sampled.elapsed() >= SAMPLE { + sampled = Instant::now(); + let clocks = clk::clocks(); + if clocks != seen { + lines.say(&format!("change {} -> {}", show(seen), show(clocks))); + seen = clocks; + beat = Instant::now(); + } + } + if beat.elapsed() >= BEAT { + beat = Instant::now(); + lines.say(&format!("held {}", show(seen))); + } + nx::screen_flush(); + std::thread::sleep(FRAME); + } + lines.say("closed by the system"); +} + +/// The overclock module that runs, named in a line with its versions. +fn find_module(lines: &mut Lines) -> Option { + let module = match OcModule::find() { + Ok(module) => module, + Err(rc) => { + lines.say(&format!("module FAIL({})", result_code(rc))); + return None; + } + }; + let Some(found) = module else { + lines.say("module none"); + return None; + }; + match found.info() { + Ok((api, version)) => lines.say(&format!("module {} api={api} version={version}", found.service())), + Err(rc) => lines.say(&format!("module {} info=FAIL({})", found.service(), result_code(rc))), + } + lines.say("A: module holds CPU 1785. R: module lets go."); + module +} + +/// The buttons down on player 1 or the handheld. +fn buttons(pads: &mut hid::Pads) -> u64 { + pads.update(); + pads.sample(0).map_or(0, |pad| pad.buttons) +} + +fn show(clocks: Option) -> String { + clocks.map_or_else( + || "clocks=unreadable".to_owned(), + |c| { + format!( + "cpu={} gpu={} emc={}", + c.cpu_hz / 1_000_000, + c.gpu_hz / 1_000_000, + c.emc_hz / 1_000_000 + ) + }, + ) +} + +/// The wall clock, UTC: unlike a monotonic count, it still runs through sleep. +fn stamp() -> String { + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default(); + let secs = now.as_secs() % 86_400; + format!( + "{:02}:{:02}:{:02}.{:03}Z", + secs / 3600, + secs / 60 % 60, + secs % 60, + now.subsec_millis() + ) +} diff --git a/crates/pf-nx-probe/src/main.rs b/crates/pf-nx-probe/src/main.rs index 2b222a1..055ad5c 100644 --- a/crates/pf-nx-probe/src/main.rs +++ b/crates/pf-nx-probe/src/main.rs @@ -4,7 +4,10 @@ //! A check runs all its steps and lists each as `step=value` or `step=FAIL(why)`, so one run on //! the console names every failure. `--panic` ends the run with a panic: the hook writes //! `panic.txt`, and the next run prints it as `probe 1 panic-log`. Runs the same on a dev box. +//! On the console, Y in the first seconds runs check 7 alone (`clock`). +#[cfg(target_os = "horizon")] +mod clock; #[cfg(all(target_os = "horizon", feature = "nvdec"))] mod nvdec; #[cfg(target_os = "horizon")] @@ -55,6 +58,12 @@ fn main() { println!("probe 1 panic {} {text}", if wrote { "ok" } else { "fail" }); })); + #[cfg(target_os = "horizon")] + if clock::run_if_asked(&dir, &mut out) { + nx::leave(); + return; + } + out.check(1, "std", std_steps(&dir)); out.check(2, "sockets", socket_steps()); #[cfg(feature = "quic")] diff --git a/crates/pf-nx-probe/src/nx.rs b/crates/pf-nx-probe/src/nx.rs index be4180a..10612a0 100644 --- a/crates/pf-nx-probe/src/nx.rs +++ b/crates/pf-nx-probe/src/nx.rs @@ -73,3 +73,11 @@ pub fn finish() { } socket::exit(); } + +/// Tears down at once, for check 7: its last lines were read while it ran. +pub fn leave() { + if SCREEN.load(Ordering::Relaxed) { + console::exit(); + } + socket::exit(); +} diff --git a/crates/pf-nx-sys/build.rs b/crates/pf-nx-sys/build.rs index 0dced81..9500438 100644 --- a/crates/pf-nx-sys/build.rs +++ b/crates/pf-nx-sys/build.rs @@ -1,4 +1,4 @@ -//! On the console target: builds `csrc/pf_swkbd.c`, and `csrc/pf_av.c` with `av`, and links libnx, newlib, the pinned libavcodec and +//! On the console target: builds `csrc/pf_swkbd.c` and `csrc/pf_ocmod.c`, and `csrc/pf_av.c` with `av`, and links libnx, newlib, the pinned libavcodec and //! NVK. On Linux with `av`: the same shim against the system's libavcodec, which decodes in //! software for the dev box. Elsewhere: nothing. `cfg(pf_av)` says the shim is linked. @@ -28,6 +28,7 @@ fn main() { println!("cargo:rustc-cfg=pf_av"); } build_shim(&dkp, &portlibs, "pf_swkbd"); + build_shim(&dkp, &portlibs, "pf_ocmod"); let nvk = PathBuf::from(env::var_os("PF_NX_NVK_LIB").unwrap_or_else(|| "/opt/pf-nx/nvk/lib".into())); if nvk_on && !nvk.join("libvulkan_bh.a").is_file() { diff --git a/crates/pf-nx-sys/csrc/pf_ocmod.c b/crates/pf-nx-sys/csrc/pf_ocmod.c new file mode 100644 index 0000000..8740f49 --- /dev/null +++ b/crates/pf-nx-sys/csrc/pf_ocmod.c @@ -0,0 +1,70 @@ +// The overclock module's IPC, for src/ocmod.rs. libnx's dispatch calls are inline, so they stay on +// this side. sys-clk and Horizon OC share commands 0, 1 and 8 under different service names. +#include + +#define CMD_API_VERSION 0 +#define CMD_VERSION_STRING 1 +#define CMD_SET_OVERRIDE 8 +// Atmosphère's sm extension. +#define SM_HAS_SERVICE 65100 + +// Whether `name` is registered, in `out`. smGetService on a missing name waits for it for good, +// so this comes first. +uint32_t pf_ocmod_has(const char *name, uint8_t *out) { + Result rc = smInitialize(); + if (R_FAILED(rc)) { + return rc; + } + SmServiceName encoded = smEncodeName(name); + if (hosversionAtLeast(12, 0, 0)) { + rc = tipcDispatchInOut(smGetServiceSessionTipc(), SM_HAS_SERVICE, encoded, *out); + } else { + rc = serviceDispatchInOut(smGetServiceSession(), SM_HAS_SERVICE, encoded, *out); + } + smExit(); + return rc; +} + +static Result open_module(const char *name, Service *srv) { + Result rc = smInitialize(); + if (R_FAILED(rc)) { + return rc; + } + rc = smGetService(srv, name); + smExit(); + return rc; +} + +// The module's API version and its version string, NUL-terminated in `version`. +uint32_t pf_ocmod_info(const char *name, uint32_t *api, char *version, size_t version_len) { + Service srv; + Result rc = open_module(name, &srv); + if (R_FAILED(rc)) { + return rc; + } + rc = serviceDispatchOut(&srv, CMD_API_VERSION, *api); + if (R_SUCCEEDED(rc)) { + rc = serviceDispatch(&srv, CMD_VERSION_STRING, + .buffer_attrs = { SfBufferAttr_HipcAutoSelect | SfBufferAttr_Out }, + .buffers = { { version, version_len } }, + ); + } + serviceClose(&srv); + return rc; +} + +// Asks the module to hold `module` at `hz`; 0 hands the clock back. +uint32_t pf_ocmod_override(const char *name, uint32_t module, uint32_t hz) { + Service srv; + Result rc = open_module(name, &srv); + if (R_FAILED(rc)) { + return rc; + } + const struct { + uint32_t module; + uint32_t hz; + } args = { module, hz }; + rc = serviceDispatchIn(&srv, CMD_SET_OVERRIDE, args); + serviceClose(&srv); + return rc; +} diff --git a/crates/pf-nx-sys/src/clk.rs b/crates/pf-nx-sys/src/clk.rs index 707157b..e613cde 100644 --- a/crates/pf-nx-sys/src/clk.rs +++ b/crates/pf-nx-sys/src/clk.rs @@ -29,6 +29,7 @@ mod ffi { pub fn clkrstOpenSession(session_out: *mut ClkrstSession, module_id: u32, unk: u32) -> u32; pub fn clkrstCloseSession(session: *mut ClkrstSession); pub fn clkrstGetClockRate(session: *mut ClkrstSession, out_hz: *mut u32) -> u32; + pub fn clkrstSetClockRate(session: *mut ClkrstSession, hz: u32) -> u32; } } @@ -65,3 +66,29 @@ pub fn clocks() -> Option { unsafe { ffi::clkrstExit() }; c } + +/// Asks for `hz` on `module`, a `MODULE_*`. `Err` is the libnx result of the step that failed. +#[cfg(target_os = "horizon")] +pub fn set_rate(module: u32, hz: u32) -> Result<(), u32> { + // SAFETY: no arguments; balanced by clkrstExit. + let rc = unsafe { ffi::clkrstInitialize() }; + if rc != 0 { + return Err(rc); + } + let mut s = ClkrstSession::default(); + // SAFETY: clkrst is open; `s` receives the session. + let mut rc = unsafe { ffi::clkrstOpenSession(&mut s, module, 3) }; + if rc == 0 { + // SAFETY: `s` is the session just opened; closed right after. + rc = unsafe { ffi::clkrstSetClockRate(&mut s, hz) }; + // SAFETY: closes the session opened above. + unsafe { ffi::clkrstCloseSession(&mut s) }; + } + // SAFETY: balances the clkrstInitialize above. + unsafe { ffi::clkrstExit() }; + if rc == 0 { + Ok(()) + } else { + Err(rc) + } +} diff --git a/crates/pf-nx-sys/src/lib.rs b/crates/pf-nx-sys/src/lib.rs index 344aa28..bd1c3fb 100644 --- a/crates/pf-nx-sys/src/lib.rs +++ b/crates/pf-nx-sys/src/lib.rs @@ -24,6 +24,7 @@ pub mod hid; pub mod mem; #[cfg(all(target_os = "horizon", feature = "nvk"))] pub mod nvk; +pub mod ocmod; pub mod pl; pub mod random; #[cfg(target_os = "horizon")] diff --git a/crates/pf-nx-sys/src/ocmod.rs b/crates/pf-nx-sys/src/ocmod.rs new file mode 100644 index 0000000..3065b2f --- /dev/null +++ b/crates/pf-nx-sys/src/ocmod.rs @@ -0,0 +1,82 @@ +//! The overclock module a player may run, through `csrc/pf_ocmod.c`. A module that sees the clock +//! change under it can put it back (Horizon OC does, with no profile set), so while one runs the +//! title asks it for the rate instead of setting clkrst itself. + +#[cfg(target_os = "horizon")] +use core::ffi::{c_char, CStr}; + +/// `HocClkModule_*`, `SysClkModule_*`: the same numbers in both. +pub const MODULE_CPU: u32 = 0; +pub const MODULE_GPU: u32 = 1; +pub const MODULE_MEM: u32 = 2; + +/// Horizon OC's service, then sys-clk's and its forks'. +#[cfg(target_os = "horizon")] +const SERVICES: [&CStr; 2] = [c"hoc:clk", c"sys:clk"]; + +#[cfg(target_os = "horizon")] +mod ffi { + use core::ffi::c_char; + + extern "C" { + pub fn pf_ocmod_has(name: *const c_char, out: *mut u8) -> u32; + pub fn pf_ocmod_info(name: *const c_char, api: *mut u32, version: *mut c_char, version_len: usize) -> u32; + pub fn pf_ocmod_override(name: *const c_char, module: u32, hz: u32) -> u32; + } +} + +/// A running overclock module. +#[cfg(target_os = "horizon")] +#[derive(Clone, Copy, Debug)] +pub struct OcModule { + service: &'static CStr, +} + +#[cfg(target_os = "horizon")] +impl OcModule { + /// The module that is running, if one is. `Err` is the libnx result when sm could not say. + pub fn find() -> Result, u32> { + for service in SERVICES { + let mut has = 0u8; + // SAFETY: `service` is NUL-terminated and `has` is a writable byte. + let rc = unsafe { ffi::pf_ocmod_has(service.as_ptr(), &mut has) }; + if rc != 0 { + return Err(rc); + } + if has != 0 { + return Ok(Some(Self { service })); + } + } + Ok(None) + } + + pub fn service(&self) -> &'static str { + self.service.to_str().unwrap_or("?") + } + + /// Its API version and version string. + pub fn info(&self) -> Result<(u32, String), u32> { + let mut api = 0u32; + let mut version = [0 as c_char; 64]; + // SAFETY: `service` is NUL-terminated; `api` and `version` are writable for their sizes. + let rc = unsafe { ffi::pf_ocmod_info(self.service.as_ptr(), &mut api, version.as_mut_ptr(), version.len()) }; + if rc != 0 { + return Err(rc); + } + // The module may fill the buffer without a NUL. + version[version.len() - 1] = 0; + // SAFETY: NUL-terminated by the line above; `version` outlives the borrow. + let text = unsafe { CStr::from_ptr(version.as_ptr()) }; + Ok((api, text.to_string_lossy().into_owned())) + } + + /// Asks it to hold `module`, a `MODULE_*`, at `hz`; 0 hands the clock back. It lives in the + /// module's memory until then, past the title's exit. + pub fn hold(&self, module: u32, hz: u32) -> Result<(), u32> { + // SAFETY: `service` is NUL-terminated; the rest are plain values. + match unsafe { ffi::pf_ocmod_override(self.service.as_ptr(), module, hz) } { + 0 => Ok(()), + rc => Err(rc), + } + } +} diff --git a/crates/pf-nx-vk/src/lib.rs b/crates/pf-nx-vk/src/lib.rs index ac66978..7ce2ada 100644 --- a/crates/pf-nx-vk/src/lib.rs +++ b/crates/pf-nx-vk/src/lib.rs @@ -15,6 +15,7 @@ pub mod pipelines; pub mod presenter; #[cfg(feature = "pyrowave")] pub mod pyro; +mod steer; mod timer; pub mod ui; pub mod util; diff --git a/crates/pf-nx-vk/src/pacing.rs b/crates/pf-nx-vk/src/pacing.rs index 64dbb1d..99b837f 100644 --- a/crates/pf-nx-vk/src/pacing.rs +++ b/crates/pf-nx-vk/src/pacing.rs @@ -9,7 +9,9 @@ //! of them, every frame after. //! //! [`Pacing::Late`] also sleeps into the refresh before the picture is taken, leaving the GPU's -//! slowest recent frame plus `MARGIN` before the vblank. +//! slowest recent frame plus `MARGIN` before the vblank. Under the latency intent the take +//! follows the pictures' arrivals within that budget (`steer`), so the band of arrivals never +//! straddles it. //! //! Only a stream paces on the vblank. The menu paces on the acquire: its frames carry no picture //! whose lateness counts, and the two frames queued hide the slow ones a tab change draws, which @@ -22,6 +24,7 @@ use std::time::{Duration, Instant}; use crate::device::Vsync; +use crate::steer::Steer; /// How the loop meets the vblank. Without a vsync event every mode paces on the acquire. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -75,6 +78,10 @@ pub(crate) struct Pace { quiet: u32, /// Quick acquires since a stall emptied the queue, while the run lasts. burst: Option, + /// Where the latency intent takes its picture. + steer: Steer, + /// The slot runs the latency intent: the take follows the arrivals. + steering: bool, window: Window, } @@ -113,6 +120,8 @@ impl Pace { drains: true, quiet: 0, burst: None, + steer: Steer::new(), + steering: false, window: Window { wait: samples(), acquire: samples(), @@ -134,6 +143,7 @@ impl Pace { self.drain = false; self.drained = false; self.burst = None; + self.steer.reset(); if let Some(v) = self.vsync.filter(|_| self.pacing != Pacing::Acquire) { (v.clear)(); } @@ -234,14 +244,28 @@ impl Pace { quick } - /// Late pacing: sleeps until the composition's budget before the vblank after `vblank`. Notes - /// where in the refresh the picture is taken either way. + /// The pictures that reached the slot since the last take, against the vblank at `vblank`. + /// `latency`: the slot runs newest wins, and the take follows them. + pub fn arrived(&mut self, vblank: Instant, period: Duration, arrivals: &[Instant], latency: bool) { + self.steering = latency; + if latency { + self.steer.note(vblank, period, arrivals); + } + } + + /// Late pacing: sleeps until the composition's budget before the vblank after `vblank`, or, + /// under the latency intent, to where the steer puts the take within it. Notes where in the + /// refresh the picture is taken either way. pub fn take(&mut self, vblank: Instant, period: Duration) { if self.pacing == Pacing::Late { - if let Some(rest) = self - .late_offset(period) - .and_then(|at| (vblank + at).checked_duration_since(Instant::now())) - { + let at = self.late_offset(period).map(|max| { + if self.steering { + self.steer.offset(max, period) + } else { + max + } + }); + if let Some(rest) = at.and_then(|at| (vblank + at).checked_duration_since(Instant::now())) { std::thread::sleep(rest); } } @@ -289,12 +313,17 @@ impl Pace { (Some(_), Pacing::Late) => "on the vblank, taken late", (Some(_), _) => "on the vblank", }; + let steered = self + .steering + .then(|| self.steer.summary()) + .flatten() + .map_or_else(String::new, |s| format!("; steered: {s}")); let w = &mut self.window; let b = w.bursts; let line = format!( "present[{}s]: {} frames {mode}; vblank wait {}, {} timed out; acquire {}, {} under 1 ms; present {}; \ {} found a frame queued, {} drained; picture taken {} after the vblank; quick acquires after a stall \ - 0:{} 1:{} 2:{} 3:{} {}+:{}", + 0:{} 1:{} 2:{} 3:{} {}+:{}{steered}", WINDOW.as_secs(), w.frames, spread(&mut w.wait), diff --git a/crates/pf-nx-vk/src/picture.rs b/crates/pf-nx-vk/src/picture.rs index 75c4208..cf465b3 100644 --- a/crates/pf-nx-vk/src/picture.rs +++ b/crates/pf-nx-vk/src/picture.rs @@ -75,7 +75,20 @@ impl VideoSlot { /// Queues `picture`; under the latency intent it replaces whatever was not taken yet. pub fn publish(&self, picture: Picture) { let due = picture.due; - self.lock().push(due, Arc::new(picture)); + let mut q = self.lock(); + if q.arrivals.len() < MAX_ARRIVALS { + q.arrivals.push(Instant::now()); + } + q.push(due, Arc::new(picture)); + } + + /// Moves into `out` when each picture since the last call reached the slot. `true` under the + /// latency intent. + pub fn drain_arrivals(&self, out: &mut Vec) -> bool { + out.clear(); + let mut q = self.lock(); + out.append(&mut q.arrivals); + q.smoothing == 0 } /// The picture for the vblank at `latch`, if a new one is due by then. @@ -117,6 +130,8 @@ const SMOOTHING_SLACK: usize = 2; const STANDING_TAKES: u32 = 30; /// The most pictures the slot ever holds. const MAX_QUEUED: usize = MAX_SMOOTHING + SMOOTHING_SLACK; +/// Arrival times the slot keeps between takes; a stall past this many keeps the first. +const MAX_ARRIVALS: usize = 64; /// Pictures the slot dropped without showing them, the figure the smoothness intent exists to /// keep at zero. @@ -213,11 +228,14 @@ struct Queue { standing: u32, /// Smoothing only: the takes since the last report. window: Window, + /// When each picture since the presenter last looked reached the slot. + arrivals: Vec, } impl Default for Queue { fn default() -> Self { Self { + arrivals: Vec::with_capacity(MAX_ARRIVALS), items: VecDeque::with_capacity(MAX_QUEUED + 1), smoothing: 0, drops: Drops::default(), @@ -281,6 +299,7 @@ impl Queue { fn clear(&mut self) { self.items.clear(); + self.arrivals.clear(); self.standing = 0; } diff --git a/crates/pf-nx-vk/src/presenter.rs b/crates/pf-nx-vk/src/presenter.rs index 141061c..1348ea7 100644 --- a/crates/pf-nx-vk/src/presenter.rs +++ b/crates/pf-nx-vk/src/presenter.rs @@ -64,6 +64,8 @@ pub struct Presenter { /// The UI layer is drawn and blended; a stream with an empty overlay turns it off. ui_on: bool, slot: Arc, + /// The slot's arrival times, drained at each take. + arrivals: Vec, current: Option>, stream: Option, last_present: Option, @@ -182,6 +184,7 @@ impl Presenter { ui, ui_on: true, slot, + arrivals: Vec::with_capacity(64), current: None, stream: None, last_present: None, @@ -582,6 +585,8 @@ impl Display for Presenter { // acquire that blocked, at the vblank a refresh from here. let latch = match vblank.filter(|_| quick) { Some(at) => { + let latency = self.slot.drain_arrivals(&mut self.arrivals); + self.pace.arrived(at, period, &self.arrivals, latency); self.pace.take(at, period); at + period } diff --git a/crates/pf-nx-vk/src/steer.rs b/crates/pf-nx-vk/src/steer.rs new file mode 100644 index 0000000..f996960 --- /dev/null +++ b/crates/pf-nx-vk/src/steer.rs @@ -0,0 +1,276 @@ +//! Where in the refresh the latency intent takes its picture. +//! +//! Newest wins: a picture that lands just after the take waits a whole refresh, and the one after +//! it lands before the next take and replaces it unseen. The host's frame clock and the panel's +//! drift apart, so the arrivals walk through the refresh, about 0.8 ms a minute in issue 30's run. +//! A take at a fixed point is crossed every twenty minutes or so, and while the band of arrivals +//! straddles it, up to a third of the pictures go unseen for minutes. +//! +//! The steer follows the arrivals instead. It places the take [`GUARD`] past the latest usual +//! arrival, within what the GPU budget allows. It moves at once when the arrivals come within +//! [`UNSAFE`] of the take, and moves earlier when that would cut the wait by more than [`SLACK`]. +//! A band that runs past the budget is taken at the start of the next refresh. + +use std::time::{Duration, Instant}; + +/// Arrivals the band is read over: about two seconds at 60 pictures a second. +const ARRIVALS: usize = 128; +/// Arrivals between looks at the take: about a second. +const EVERY: usize = 60; +/// Room the take leaves past the latest usual arrival. +const GUARD: Duration = Duration::from_millis(2); +/// A take this close to the latest usual arrival moves at once. +const UNSAFE: Duration = Duration::from_millis(1); +/// A take that could wait this much less moves earlier. +const SLACK: Duration = Duration::from_millis(3); +/// Arrivals the band holds, in percent of the window; the rest are a late burst it lets go. +const BAND_PCT: usize = 98; + +pub(crate) struct Steer { + /// Each arrival's place in the refresh, µs after the vblank, the last [`ARRIVALS`]. + phases: [u32; ARRIVALS], + n: usize, + /// Arrivals since the last look. + since: usize, + /// The take's place in the refresh; `None` until the first look, which starts from the budget. + at: Option, + /// The band at the last look: its centre and its width. + band: Option<(Duration, Duration)>, + /// Moves since the last report. + moves: u32, +} + +/// A band of arrivals, in µs: where its earliest usual arrival sits and how wide it runs. +struct Band { + earliest: u64, + width: u64, + centre: u64, +} + +impl Steer { + pub fn new() -> Self { + Self { + phases: [0; ARRIVALS], + n: 0, + since: 0, + at: None, + band: None, + moves: 0, + } + } + + /// Forgets the arrivals: a new stream, a new host clock. + pub fn reset(&mut self) { + *self = Self::new(); + } + + /// Notes `arrivals` against the vblank at `vblank`, `period` apart. + pub fn note(&mut self, vblank: Instant, period: Duration, arrivals: &[Instant]) { + let p = period.as_micros() as i64; + if p == 0 { + return; + } + for &a in arrivals { + let off = if a >= vblank { + (a - vblank).as_micros() as i64 + } else { + -((vblank - a).as_micros() as i64) + }; + self.phases[self.n % ARRIVALS] = off.rem_euclid(p) as u32; + self.n += 1; + self.since += 1; + } + } + + /// The take's place in the refresh, at most `max`, the GPU budget's latest. + pub fn offset(&mut self, max: Duration, period: Duration) -> Duration { + if self.n >= EVERY && self.since >= EVERY { + self.since = 0; + self.look(max, period); + } + self.at.unwrap_or(max).min(max) + } + + fn look(&mut self, max: Duration, period: Duration) { + let p = period.as_micros() as u64; + let held = self.n.min(ARRIVALS); + let Some(band) = band(&self.phases[..held], p) else { + return; + }; + self.band = Some((Duration::from_micros(band.centre), Duration::from_micros(band.width))); + let (guard, unsafe_, slack) = (us(GUARD), us(UNSAFE), us(SLACK)); + if band.width + 2 * guard >= p { + // No point in the refresh clears the band: leave the take where it is. + return; + } + let max = us(max).min(p - 1); + // How far past the band's latest usual arrival a take at `t` sits; 0 inside the band. + let margin = |t: u64| ((t + p - band.earliest) % p).saturating_sub(band.width); + let want = (band.earliest + band.width + guard) % p; + let target = if want <= max { want } else { 0 }; + let cur = self.at.map_or(max, |d| us(d).min(max)); + let cur_margin = margin(cur); + let move_now = cur_margin < unsafe_ || (self.at.is_none() && cur != target); + let saves = cur_margin.saturating_sub(margin(target)) > slack; + if (move_now || saves) && cur != target { + self.moves += u32::from(self.at.is_some()); + self.at = Some(Duration::from_micros(target)); + } else if self.at.is_none() { + self.at = Some(Duration::from_micros(cur)); + } + } + + /// `arrivals at … ms, band … ms, take … ms, … moves`, then a fresh count; `None` before the + /// first look. + pub fn summary(&mut self) -> Option { + let (centre, width) = self.band?; + let at = self.at?; + let ms = |d: Duration| d.as_secs_f64() * 1e3; + let line = format!( + "arrivals at {:.1} ms in a {:.1} ms band, take at {:.1} ms, {} moves", + ms(centre), + ms(width), + ms(at), + self.moves + ); + self.moves = 0; + Some(line) + } +} + +fn us(d: Duration) -> u64 { + d.as_micros() as u64 +} + +/// The band the arrivals' `phases` (µs into a `p` µs refresh) make: its centre by the circular +/// mean, then the spread around it that holds [`BAND_PCT`] of them. +fn band(phases: &[u32], p: u64) -> Option { + if phases.is_empty() || p == 0 { + return None; + } + let tau = std::f64::consts::TAU; + let (mut s, mut c) = (0.0, 0.0); + for &ph in phases { + let a = f64::from(ph) / p as f64 * tau; + s += a.sin(); + c += a.cos(); + } + let centre = (s.atan2(c).rem_euclid(tau) / tau * p as f64) as i64; + let half = (p / 2) as i64; + let mut devs: Vec = phases + .iter() + .map(|&ph| (i64::from(ph) - centre + half).rem_euclid(p as i64) - half) + .collect(); + devs.sort_unstable(); + let cut = |pct: usize| devs[((devs.len() - 1) * pct) / 100]; + let (lo, hi) = (cut(100 - BAND_PCT), cut(BAND_PCT)); + Some(Band { + earliest: (centre + lo).rem_euclid(p as i64) as u64, + width: (hi - lo) as u64, + centre: centre.rem_euclid(p as i64) as u64, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const PERIOD: Duration = Duration::from_nanos(16_666_667); + const MAX: Duration = Duration::from_millis(10); + + /// One second of arrivals around `centre_us` into the refresh, spread over ±`jitter_us`. + fn second(steer: &mut Steer, centre_us: u64, jitter_us: u64) { + let vblank = Instant::now() + Duration::from_secs(1); + let arrivals: Vec = (0..EVERY as u64) + .map(|i| { + let j = if jitter_us == 0 { + 0 + } else { + (i * 7919) % (2 * jitter_us + 1) + }; + vblank + Duration::from_micros(centre_us + j) - Duration::from_micros(jitter_us) + }) + .collect(); + steer.note(vblank, PERIOD, &arrivals); + } + + fn ms(steer: &mut Steer) -> f64 { + steer.offset(MAX, PERIOD).as_secs_f64() * 1e3 + } + + /// Until the first look the take is the budget's; then it sits the guard past the band. + #[test] + fn the_take_starts_at_the_budget_then_follows_the_band() { + let mut s = Steer::new(); + assert_eq!(s.offset(MAX, PERIOD), MAX); + second(&mut s, 3_000, 500); + let at = ms(&mut s); + assert!((5.3..=5.7).contains(&at), "{at}"); + } + + /// A band that walks through the refresh, earlier as in issue 30's run or later, never comes + /// within the unsafe distance of the take, and the take steps after it. + #[test] + fn a_drifting_band_never_reaches_the_take() { + for step in [-13, 13] { + drift(step); + } + } + + /// Twenty-five minutes of a band walking `step` µs a second, about a refresh and a half. + fn drift(step: i64) { + let mut s = Steer::new(); + let mut centre: i64 = 8_000; + let mut moves = 0; + for _ in 0..1_500 { + let c = centre.rem_euclid(16_667) as u64; + second(&mut s, c, 800); + let before = s.at; + let at = us(s.offset(MAX, PERIOD)) as i64; + moves += u32::from(before.is_some() && before != s.at); + // The latest arrival of all, against the take: the band's edge holds 98 of 100, so + // the take keeps at least half the unsafe distance from the very last. + let latest = (c as i64 + 800).rem_euclid(16_667); + let gap = (at - latest).rem_euclid(16_667); + assert!(gap >= us(UNSAFE) as i64 / 2, "take {at} µs, latest arrival {latest} µs"); + centre += step; // 0.78 ms a minute + } + assert!(moves > 0 && moves < 60, "{moves} moves at {step} µs a second"); + } + + /// A band past the budget's latest point is taken at the start of the next refresh. + #[test] + fn a_band_past_the_budget_is_taken_at_the_next_refresh() { + let mut s = Steer::new(); + second(&mut s, 12_000, 500); + assert_eq!(s.offset(MAX, PERIOD), Duration::ZERO); + } + + /// A band that comes up on the take moves it at once; a calm one leaves it. + #[test] + fn the_take_moves_only_when_unsafe_or_wasteful() { + let mut s = Steer::new(); + second(&mut s, 3_000, 300); + let first = s.offset(MAX, PERIOD); + second(&mut s, 3_500, 300); + assert_eq!(s.offset(MAX, PERIOD), first, "half a millisecond is not worth a move"); + second(&mut s, 5_000, 300); + assert!(s.offset(MAX, PERIOD) > first, "the band reached the take"); + } + + /// No point clears a band nearly a refresh wide: the take stays. + #[test] + fn a_band_too_wide_leaves_the_take() { + let mut s = Steer::new(); + second(&mut s, 8_000, 7_500); + assert_eq!(s.offset(MAX, PERIOD), MAX); + } + + /// A band across the vblank reads as one band, not two halves. + #[test] + fn a_band_across_the_vblank_is_one_band() { + let b = band(&[16_500, 16_600, 100, 200], 16_667).unwrap(); + assert!(b.width < 1_000, "{}", b.width); + assert!(b.earliest >= 16_400, "{}", b.earliest); + } +} diff --git a/docs/NOTES.md b/docs/NOTES.md index e895912..d77f2bd 100644 --- a/docs/NOTES.md +++ b/docs/NOTES.md @@ -208,3 +208,18 @@ record their clocks; the numbers below are under that profile unless an item say (title at `be98e16`, 2026-10-31). - With the accelerometer's sign flipped, a pad lying still reads [0, 1, 0] g on the wire, as SDL's frame has it (title at `8a18316`, 2026-10-31). +- With Horizon OC 2.5.1 on (`hoc:clk`, API 2) and no profile, clkrst alone falls back to 1020 in + 100-300 ms, and the module's override (command 8) holds 1785 with no help from the title. The + hold comes back on its own within 0.2 s of a wake, and a wake without one reads 1020. Clearing + it takes about 0.3 s, and clearing with nothing held answers ok. The hold outlives the title: + 1785 was still there on the next run, 12 s after leaving. With the module off, sm's HasService + answers without blocking and clkrst holds until sleep. Dock changes, plain sys-clk and GPU or + memory holds are not proven (probe at `c5b5088`, 2026-11-06). +- The title holds menu clocks of CPU 1428, GPU 422.4 handheld and memory 1600 MHz (422.4 is a + table rate, read back as asked), and CPU 1785 with memory 1600 through a stream. It does so + through `hoc:clk` with Horizon OC on and through clkrst with no module; without one, the system + moves the clocks on wake and on a return from HOME, and the title asks again within a second. + Docked, the menu leaves the GPU at the system's 768. Leaving through the menu or HOME's close + puts the stock clocks back, read on the overlay. The clocks read at a performance-mode message + are the system's stock ones before a hold returns, so the overlay, not that line, shows a dock + change. A dock change mid-stream is not in the logs (title at `cebd83b`, 2026-11-07). diff --git a/docs/improvements.md b/docs/improvements.md index 57c648a..18ab6a3 100644 --- a/docs/improvements.md +++ b/docs/improvements.md @@ -154,10 +154,23 @@ the first frame and adds a stream period for each further one (`session/timeline console, one frame presented 59 to 60 pictures a second at 15 to 23 ms decode to present; two frames presented the same at 31 to 40 ms (NOTES, 2026-10-31). -**The proposal.** Automatic picks one frame on the Switch, either through a per-platform default -in the shared crate (section 1 would carry it) or an override here. **Needs the maintainer's -yes**: it changes what a player sees by default. **Open:** one tester's Wi-Fi so far; a busier -network may want the second frame back. +**Done.** Automatic picks one frame on the Switch, through an override here +(`NxSettings::nx_present_priority`); the shared rule still gives two everywhere else. A second +network agrees: issue 30's tester saw Automatic swing between about 23 and 36 ms end to end where +one frame held 21 to 25 ms, with the same pictures presented. **Open:** a busier network may want +the second frame back, which the player can still pick. + +### Lowest latency: the take follows the arrivals + +Issue 30's logs (run2, 11:25 to 11:34) show the arrivals walking through the refresh at about +0.8 ms a minute, with a band of 1 to 2 ms. Once the band reached the fixed take at 10 ms after +the vblank, newest wins dropped up to 150 pictures a window. Under the latency intent the take +now sits 2 ms past the latest usual arrival (98 of 100 over the last two seconds), inside the GPU +budget. It moves at once when the band comes within 1 ms of it and moves earlier when that saves +over 3 ms; a band past the budget is taken at the start of the next refresh (`pf-nx-vk` +`steer.rs`). Smoothness keeps its fixed late take. **Test:** Lowest latency for ten minutes or +more, handheld. `present[10s]` adds `steered: arrivals at … ms in a … ms band, take at … ms, +… moves`; `unseen (replaced)` should stay near zero through the whole run. ### Other later work