Skip to content
Merged
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
105 changes: 102 additions & 3 deletions crates/pf-nx-app/src/core/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,47 @@ pub fn upsert_known_host(hosts: &mut Vec<KnownHost>, mut new: KnownHost) -> Opti
None
}

/// Follows a paired host to the address it now advertises from, matched by its pinned
/// fingerprint, so a DHCP move doesn't leave the record offline and a re-add doesn't save
/// it twice. `advertised` says whether some advert currently comes from an address: a record
/// whose own address still advertises is a second interface, not a move, and stays put.
///
/// The advert is unauthenticated, but the pin is what every connection checks, so a forged
/// one can only point the record at an address whose handshake then fails.
///
/// With no record at the advert's address, the record that pins `fp_hex` moves there. With
/// one there that pins the same certificate, the others pinning it are dropped as
/// duplicates. Returns whether anything changed.
pub fn follow_moved_host(
hosts: &mut Vec<KnownHost>,
fp_hex: &str,
addr: &str,
port: u16,
advertised: impl Fn(&str, u16) -> bool,
) -> bool {
if fp_hex.is_empty() {
return false;
}
let stale =
|h: &KnownHost| h.fp_hex == fp_hex && (h.addr.as_str(), h.port) != (addr, port) && !advertised(&h.addr, h.port);
match hosts.iter().find(|h| (h.addr.as_str(), h.port) == (addr, port)) {
Some(here) if here.fp_hex == fp_hex => {
let before = hosts.len();
hosts.retain(|h| !stale(h));
hosts.len() != before
}
Some(_) => false,
None => {
let Some(moved) = hosts.iter_mut().find(|h| stale(h)) else {
return false;
};
moved.addr = addr.to_string();
moved.port = port;
true
}
}
}

fn unique_profile_name(catalog: &[StreamPreset], wanted: &str) -> String {
let taken = |name: &str| catalog.iter().any(|p| p.name == name);
if !taken(wanted) {
Expand Down Expand Up @@ -273,12 +314,26 @@ impl GamepadType {
}
}

/// Automatic bitrate's ceiling, handed to `punktfunk_core::abr` through `run`
/// (`PUNKTFUNK_ABR_MAX_MBPS`). It binds every codec, so it sits above Automatic `PyroWave`'s
/// Automatic bitrate's ceiling where `PyroWave` decodes, handed to `punktfunk_core::abr` through
/// `run` (`PUNKTFUNK_ABR_MAX_MBPS`). It binds every codec, so it sits above Automatic `PyroWave`'s
/// quality floor (0.5 bit/pixel), below which core clamps a `PyroWave` session to that floor.
/// HEVC and H.264 stop well below it, at the link's and the decoder's headroom.
pub const BITRATE_MAX_KBPS: u32 = 650_000;

/// Automatic bitrate's ceiling where only NVDEC decodes: the rate a pinned stream ran clean at,
/// handheld at stock clocks. Core finds the link's edge by crossing it, and its climbs to
/// 22-25 Mb/s preceded every 60-110 ms delay spike (2026-10-31). Under the ceiling it still cuts
/// for a dock or a weak Wi-Fi. A raised CPU clock is what would carry more.
pub const NVDEC_BITRATE_MAX_KBPS: u32 = 20_000;

/// Automatic bitrate's ceiling for a title whose video lane can or cannot decode `PyroWave`.
pub const fn bitrate_max_kbps(pyrowave: bool) -> u32 {
if pyrowave {
BITRATE_MAX_KBPS
} else {
NVDEC_BITRATE_MAX_KBPS
}
}

/// 70% of measured goodput (headroom for FEC, loss).
/// Integer arithmetic order matters (`/ 10 * 7`, not `* 0.7`) — all clients must agree exactly.
pub fn recommended_bitrate_kbps(throughput_kbps: u32) -> u32 {
Expand Down Expand Up @@ -430,4 +485,48 @@ mod tests {
assert_eq!(hosts[0].id, h.id);
assert_eq!(hosts[0].game_profile("doom"), Some("p1"));
}

fn paired_at(addr: &str, fp: u8) -> KnownHost {
let mut h = KnownHost {
shared: pf_client_core::trust::KnownHost {
name: "desk".into(),
addr: addr.into(),
port: 9777,
..Default::default()
},
..Default::default()
};
h.set_fingerprint([fp; 32]);
h
}

/// The 2026-11-02 settings: the router moved the host from .137 to .10, the record stayed
/// on .137 and showed offline, and re-adding it saved the same pin a second time.
#[test]
fn a_paired_host_follows_its_advert_to_a_new_address() {
let fp = "5a".repeat(32);
let quiet = |_: &str, _: u16| false;

let mut hosts = vec![paired_at("192.168.0.137", 0x5a)];
assert!(follow_moved_host(&mut hosts, &fp, "192.168.0.10", 9777, quiet));
assert_eq!(hosts[0].addr, "192.168.0.10");

let mut hosts = vec![paired_at("192.168.0.137", 0x5a), paired_at("192.168.0.10", 0x5a)];
assert!(follow_moved_host(&mut hosts, &fp, "192.168.0.10", 9777, quiet));
assert_eq!(hosts.len(), 1, "the stale duplicate is dropped");
assert_eq!(hosts[0].addr, "192.168.0.10");

// A second interface that still advertises is not a move.
let mut hosts = vec![paired_at("192.168.0.137", 0x5a)];
let both = |a: &str, _: u16| a == "192.168.0.137";
assert!(!follow_moved_host(&mut hosts, &fp, "192.168.0.10", 9777, both));
assert_eq!(hosts[0].addr, "192.168.0.137");

// Another certificate, or another host already at the address, moves nothing.
let mut hosts = vec![paired_at("192.168.0.137", 0x11)];
assert!(!follow_moved_host(&mut hosts, &fp, "192.168.0.10", 9777, quiet));
let mut hosts = vec![paired_at("192.168.0.137", 0x5a), paired_at("192.168.0.10", 0x11)];
assert!(!follow_moved_host(&mut hosts, &fp, "192.168.0.10", 9777, quiet));
assert_eq!(hosts.len(), 2);
}
}
78 changes: 78 additions & 0 deletions crates/pf-nx-app/src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod fake;

use std::io::Write;
use std::path::Path;
use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
use std::sync::Arc;

use anyhow::Result;
Expand Down Expand Up @@ -122,6 +123,9 @@ pub struct FrameReport {
pub replaced: u32,
/// Decoded pictures dropped unseen since the last frame, pushed out of a full smoothing queue.
pub overflow: u32,
/// How long an earlier frame's composition ran on the GPU (the one whose slot this frame
/// reused), where the GPU can time it.
pub gpu_us: Option<u32>,
}

/// A read-back frame.
Expand Down Expand Up @@ -159,6 +163,42 @@ pub struct StreamSpec {
pub smoothing: usize,
/// The session's overlay figures: lanes note decode, the presenter notes display.
pub hud: Arc<punktfunk_core::hud::Stats>,
/// Where the presenter leaves each picture's capture-to-glass time for the audio's A/V
/// sync measure.
pub video_e2e: VideoE2e,
}

/// The video's capture-to-glass time in core's cells: the presenter writes it, the audio route
/// compares its own against it. `0` until a picture reaches the glass.
#[derive(Clone, Debug, Default)]
pub struct VideoE2e {
e2e_ns: Arc<AtomicU64>,
/// Host clock minus this one, kept current by core.
clock_offset_ns: Arc<AtomicI64>,
}

/// A capture-to-glass time past this is a clock step, not a picture.
const E2E_SANE_NS: u64 = 10_000_000_000;

impl VideoE2e {
pub fn new(e2e_ns: Arc<AtomicU64>, clock_offset_ns: Arc<AtomicI64>) -> Self {
Self {
e2e_ns,
clock_offset_ns,
}
}

/// A picture captured at host time `pts_ns` reached the glass at `displayed_ns`, this
/// clock's realtime.
pub fn note(&self, pts_ns: u64, displayed_ns: u64) {
let offset = self.clock_offset_ns.load(Ordering::Relaxed);
let e2e = i128::from(displayed_ns) + i128::from(offset) - i128::from(pts_ns);
if let Ok(ns) = u64::try_from(e2e) {
if ns > 0 && ns < E2E_SANE_NS {
self.e2e_ns.store(ns, Ordering::Relaxed);
}
}
}
}

/// The console's audio output. Opening a port is cheap; a session holds one.
Expand All @@ -173,6 +213,11 @@ pub trait AudioPort: Send {

/// Plays exactly one grain, blocking until the device takes it.
fn write(&mut self, pcm: &[f32]) -> Result<()>;

/// Frames handed to the device and not yet played, which the next grain queues behind.
fn queued_frames(&self) -> usize {
0
}
}

/// One pad's state at one instant, already in punktfunk's wire vocabulary.
Expand Down Expand Up @@ -277,4 +322,37 @@ pub trait Lifecycle {
fn hide_splash(&self);
fn poll_events(&mut self, out: &mut Vec<SystemEvent>);
fn exit(&self) -> !;

/// The clocks the system runs the title at now, for the logs. `None` where they cannot be
/// read: a dev box, or a console before firmware 8.0.0.
fn clocks(&self) -> Option<Clocks> {
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 CPU, GPU and memory clocks, in Hz.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Clocks {
pub cpu_hz: u32,
pub gpu_hz: u32,
pub emc_hz: u32,
}

impl std::fmt::Display for Clocks {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mhz = |hz: u32| f64::from(hz) / 1e6;
write!(
f,
"gpu {:.1} cpu {:.1} emc {:.1} MHz",
mhz(self.gpu_hz),
mhz(self.cpu_hz),
mhz(self.emc_hz)
)
}
}
2 changes: 1 addition & 1 deletion crates/pf-nx-app/src/runtime/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ pub(super) fn run(app: &mut App, notice: Option<String>) -> Result<UiOutcome> {
})?;
frames += 1;
if let Some(report) = perf.frame(before_draw + drew, art_snapshot()) {
tracing::info!("{}", report.line());
tracing::info!("{}{}", report.line(), app.clocks_suffix());
}
if let Some(done) = testrun::menu_step(app, frames) {
break 'ui done;
Expand Down
18 changes: 14 additions & 4 deletions crates/pf-nx-app/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ mod touch;

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

use crate::core::model::BITRATE_MAX_KBPS;
use crate::core::model::bitrate_max_kbps;
use crate::platform::{Display, Lifecycle, Pads, Platform, SystemEvent};
use crate::services::power::ExitPlan;
use crate::services::store;
Expand Down Expand Up @@ -48,6 +48,13 @@ impl App {
}
events
}

/// `" | clocks gpu … MHz"` for a 10 s summary line, empty where the clocks cannot be read.
fn clocks_suffix(&self) -> String {
self.lifecycle
.clocks()
.map_or_else(String::new, |c| format!(" | clocks {c}"))
}
}

/// Sleep is on its way: no new session may start.
Expand All @@ -71,14 +78,17 @@ const ABR_PROBE_KBPS: u32 = 320_000;

/// The two automatic-bitrate knobs punktfunk-core reads from the environment. Set before any
/// thread exists: `set_var` is not thread-safe.
fn set_abr_env() {
fn set_abr_env(pyrowave: bool) {
std::env::set_var("PUNKTFUNK_ABR_PROBE_KBPS", ABR_PROBE_KBPS.to_string());
std::env::set_var("PUNKTFUNK_ABR_MAX_MBPS", (BITRATE_MAX_KBPS / 1_000).to_string());
std::env::set_var(
"PUNKTFUNK_ABR_MAX_MBPS",
(bitrate_max_kbps(pyrowave) / 1_000).to_string(),
);
}

/// Runs the title until the player leaves it. Never returns.
pub fn run(platform: Platform) -> ! {
set_abr_env();
set_abr_env(platform.video.caps().pyrowave);
let Platform {
display,
video,
Expand Down
Loading
Loading