Skip to content
Closed
59 changes: 56 additions & 3 deletions crates/pf-nx-app/src/core/settings.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand All @@ -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;
Expand All @@ -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)
}
Expand Down Expand Up @@ -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();
Expand Down
9 changes: 7 additions & 2 deletions crates/pf-nx-app/src/platform/fake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -240,6 +240,7 @@ impl Storage for FakeStorage {
pub struct FakeLifecycle {
pub events: Arc<Mutex<VecDeque<SystemEvent>>>,
pub splash_hidden: Arc<Mutex<bool>>,
pub clock_stages: Arc<Mutex<Vec<ClockStage>>>,
}

impl Lifecycle for FakeLifecycle {
Expand All @@ -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");
}
Expand Down
141 changes: 141 additions & 0 deletions crates/pf-nx-app/src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<fn()> {
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<String> {
Expand Down Expand Up @@ -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<u32>,
pub gpu_hz: Option<u32>,
pub emc_hz: Option<u32>,
}

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<u32>, 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<String>| 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 {
Expand All @@ -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));
}
}
}
2 changes: 1 addition & 1 deletion crates/pf-nx-app/src/runtime/connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
},
Expand Down
3 changes: 3 additions & 0 deletions crates/pf-nx-app/src/runtime/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,9 @@ pub(super) fn run(app: &mut App, notice: Option<String>) -> Result<UiOutcome> {
}

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 {
Expand Down
Loading