Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions crates/pf-nx-app/src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,13 +329,76 @@ pub trait Lifecycle {
None
}

/// The socket calls made since the title started, for the logs. `None` where nothing counts
/// them: a dev box.
fn socket_calls(&self) -> Option<SocketCalls> {
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> {
None
}
}

/// The console's socket calls since the title started, and the two A/B switches they ran under.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SocketCalls {
pub polls: u64,
pub batch_reads: u64,
pub batch_datagrams: u64,
pub batch_read_ns: u64,
pub recvs: u64,
pub recv_froms: u64,
pub sends: u64,
pub send_tos: u64,
pub lean_waker: bool,
pub read_wait_us: u32,
}

impl SocketCalls {
/// One summary of the calls since `before`, `secs` ago, as rates a second.
pub fn window(&self, before: &Self, secs: f64) -> String {
let reads = self.batch_reads - before.batch_reads;
let datagrams = self.batch_datagrams - before.batch_datagrams;
let read_ns = self.batch_read_ns - before.batch_read_ns;
let polls = self.polls - before.polls;
let recvs = self.recvs - before.recvs;
let recv_froms = self.recv_froms - before.recv_froms;
let sends = self.sends - before.sends;
let send_tos = self.send_tos - before.send_tos;
let total = polls + reads + recvs + recv_froms + sends + send_tos;
let rate = |n: u64| n as f64 / secs.max(0.001);
let each = |n: u64| n as f64 / reads.max(1) as f64;
format!(
"socket calls {secs:.1}s: {:.0}/s | poll {:.0}, recvmmsg {:.0} ({:.1} datagrams, {:.0} us each), recv {:.0}, \
recvfrom {:.0}, send {:.0}, sendto {:.0} a second | lean waker {}, read wait {} us",
rate(total),
rate(polls),
rate(reads),
each(datagrams),
each(read_ns) / 1e3,
rate(recvs),
rate(recv_froms),
rate(sends),
rate(send_tos),
if self.lean_waker { "on" } else { "off" },
self.read_wait_us,
)
}
}

/// The read wait a marker file asks for, in microseconds: its text is milliseconds, capped at
/// 5 ms. Anything else is no wait.
pub fn read_wait_us(text: &str) -> u32 {
let text = text.trim_start_matches('\u{feff}').trim().replace(',', ".");
text.parse::<f64>()
.ok()
.filter(|ms| ms.is_finite() && *ms > 0.0)
.map_or(0, |ms| (ms.min(5.0) * 1000.0) as u32)
}

/// The CPU, GPU and memory clocks, in Hz.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Clocks {
Expand Down
14 changes: 13 additions & 1 deletion crates/pf-nx-app/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ pub mod testrun;
mod touch;

use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;

use crate::core::model::bitrate_max_kbps;
use crate::platform::{Display, Lifecycle, Pads, Platform, SystemEvent};
use crate::platform::{Display, Lifecycle, Pads, Platform, SocketCalls, SystemEvent};
use crate::services::power::ExitPlan;
use crate::services::store;
use crate::session::{self, Media};
Expand Down Expand Up @@ -55,6 +56,17 @@ impl App {
.clocks()
.map_or_else(String::new, |c| format!(" | clocks {c}"))
}

/// The socket calls since the last call, one summary; the first call only starts the count.
fn socket_window(&self, last: &mut Option<(SocketCalls, Instant)>) -> Option<String> {
let now = self.lifecycle.socket_calls()?;
let at = Instant::now();
let window = last
.as_ref()
.map(|(before, then)| now.window(before, at.duration_since(*then).as_secs_f64()));
*last = Some((now, at));
window
}
}

/// Sleep is on its way: no new session may start.
Expand Down
4 changes: 4 additions & 0 deletions crates/pf-nx-app/src/runtime/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ fn stream(
let mut last_elapsed = Duration::ZERO;
let mut dial_was_open = false;
let mut perf = StreamPerf::default();
let mut sockets = None;
let mut last_frame = Instant::now();

let next = loop {
Expand Down Expand Up @@ -426,6 +427,9 @@ fn stream(

if let Some(core) = hud.refresh(connected, decoder) {
tracing::info!("stats: {} | {core}{}", perf.take_window(), app.clocks_suffix());
if let Some(line) = app.socket_window(&mut sockets) {
tracing::info!("{line}");
}
}
hud.local = vec![format!(
"present: {} frames, {} missed{}",
Expand Down
37 changes: 36 additions & 1 deletion crates/pf-nx-app/tests/seams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::sync::Arc;

use pf_nx_app::platform::fake::{FakeAudio, FakeDisplay, FakeLifecycle, FakePads, FakeStorage, FakeVideo};
use pf_nx_app::platform::{AudioOut, Display, Pads, Platform, Refresh, Storage};
use pf_nx_app::platform::{read_wait_us, AudioOut, Display, Pads, Platform, Refresh, SocketCalls, Storage};

/// A display presents what the UI drew and reads it back at its own size.
#[test]
Expand Down Expand Up @@ -90,3 +90,38 @@ fn a_menu_test_run_leaves_a_bundle_and_exits() {
assert!(bundle.join("frame-menu.png").exists());
assert!(bundle.join("environment.json").exists());
}

/// A window's rates come from what changed since the last one, and it names both switches.
#[test]
fn a_socket_window_reads_as_rates() {
let before = SocketCalls {
polls: 100,
batch_reads: 50,
batch_datagrams: 200,
..SocketCalls::default()
};
let now = SocketCalls {
polls: 300,
batch_reads: 150,
batch_datagrams: 600,
batch_read_ns: 20_000_000,
sends: 40,
lean_waker: true,
read_wait_us: 1000,
..before
};
let line = now.window(&before, 10.0);
assert!(line.starts_with("socket calls 10.0s: 34/s"), "{line}");
assert!(line.contains("recvmmsg 10 (4.0 datagrams, 200 us each)"), "{line}");
assert!(line.ends_with("lean waker on, read wait 1000 us"), "{line}");
}

/// A marker holds milliseconds as any text editor writes them.
#[test]
fn a_read_wait_marker_is_milliseconds() {
assert_eq!(read_wait_us("1"), 1000);
assert_eq!(read_wait_us("\u{feff}0,5\r\n"), 500);
assert_eq!(read_wait_us("60"), 5000);
assert_eq!(read_wait_us(""), 0);
assert_eq!(read_wait_us("-1"), 0);
}
19 changes: 18 additions & 1 deletion crates/pf-nx-platform/src/console/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use std::sync::mpsc;
use std::time::{Duration, Instant};

use pf_nx_app::platform::{Clocks, Lifecycle, SystemEvent};
use pf_nx_app::platform::{Clocks, Lifecycle, SocketCalls, SystemEvent};
use pf_nx_sys::applet::{self, FocusState, HookEvent};
use pf_nx_sys::{clk, mem, rt, socket, swkbd};

Expand Down Expand Up @@ -93,6 +93,23 @@ impl Lifecycle for NxLifecycle {
})
}

fn socket_calls(&self) -> Option<SocketCalls> {
let c = rt::socket_calls();
let (lean_waker, read_wait_us) = super::socket_switches();
Some(SocketCalls {
polls: c.polls,
batch_reads: c.batch_reads,
batch_datagrams: c.batch_datagrams,
batch_read_ns: c.batch_read_ns,
recvs: c.recvs,
recv_froms: c.recv_froms,
sends: c.sends,
send_tos: c.send_tos,
lean_waker,
read_wait_us,
})
}

fn keyboard(&mut self) -> Option<String> {
match swkbd::ask("Text to type on the PC", "Send") {
Ok(text) => Some(text),
Expand Down
32 changes: 30 additions & 2 deletions crates/pf-nx-platform/src/console/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ mod pads;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
use std::time::Duration;

use anyhow::{Context, Result};
use pf_nx_app::platform::{DeviceInfo, Display, OperationMode, Platform, Storage, VideoDecoders};
use pf_nx_sys::{applet, nvk, setsys, socket, vi};
use pf_nx_app::platform::{read_wait_us, DeviceInfo, Display, OperationMode, Platform, Storage, VideoDecoders};
use pf_nx_sys::{applet, nvk, rt, setsys, socket, vi};
use pf_nx_vk::{GpuDevice, Presenter, Target, VideoSlot};

/// Identity, settings, logs and bundles; the NRO itself lives here too (plan D18).
Expand All @@ -22,6 +23,13 @@ const DATA_DIR: &str = "sdmc:/switch/punktfunk";
/// build A/Bs both routes.
const STRAIGHT_MARKER: &str = "vic-direto";

/// A file of this name in [`DATA_DIR`], read at start, turns the mio leg's lean waker on.
const LEAN_WAKER_MARKER: &str = "despertador-leve";

/// A file of this name in [`DATA_DIR`], read at start, makes every batch read wait the
/// milliseconds it holds, so one build A/Bs several waits.
const READ_WAIT_MARKER: &str = "espera-leitura";

/// The Mesa pin NVK was built from, for the log and the About screen.
const MESA_PIN: &str = match option_env!("PF_MESA_PIN") {
Some(p) => p,
Expand Down Expand Up @@ -75,11 +83,31 @@ fn nxlink() -> Option<Box<dyn Write + Send>> {
up.then(|| Box::new(std::io::stdout()) as Box<dyn Write + Send>)
}

/// The markers' switches, read once: whether the waker is lean, and the read wait in microseconds.
fn socket_switches() -> (bool, u32) {
static SWITCHES: OnceLock<(bool, u32)> = OnceLock::new();
*SWITCHES.get_or_init(|| {
let dir = Path::new(DATA_DIR);
let wait = std::fs::read_to_string(dir.join(READ_WAIT_MARKER)).map_or(0, |text| read_wait_us(&text));
(dir.join(LEAN_WAKER_MARKER).exists(), wait)
})
}

/// Applies the markers. Before any thread exists: `set_var` is not thread-safe.
fn apply_socket_switches() {
let (lean_waker, wait_us) = socket_switches();
if lean_waker {
std::env::set_var("PF_NX_LEAN_WAKER", "1");
}
rt::set_read_wait(Duration::from_micros(u64::from(wait_us)));
}

/// Builds the console platform. Sockets and nxlink come first, so a display that fails to come
/// up is reported; the display comes next, as the step most likely to fail.
pub fn platform(kind: DisplayKind) -> Result<Platform> {
let log = nxlink();
std::fs::create_dir_all(DATA_DIR).with_context(|| format!("create {DATA_DIR}"))?;
apply_socket_switches();
let (display, video, gpu, ui): (Box<dyn Display>, Arc<dyn VideoDecoders>, String, String) = match kind {
DisplayKind::Nvk => {
let window = vi::default_window();
Expand Down
Loading
Loading