gallery/vendor/i-slint-backend-android-activity-1.18.1/vsync.rs
Greg Pomerantz b97b6515d5 120Hz: Choreographer chain self-sustains on (animating||dirty); EW gates the wake; MISS v2 forensics; ctxsw discriminator + present CPU split
vsync.rs:
- set_state(animating, dirty) replaces set_animating. The Choreographer
  callback chain re-posts while animating||dirty: gating on animating
  alone let the chain die during flings (pointer inactivity >200ms) —
  with EW disabled the loop then froze (measured: 30 frames in 4s,
  then silence). The dirty mirror is pushed every main-loop iteration
  (<=8ms stale); the 6ms poll backstop bounds chain-break damage.
- EW_ON now gates the WAKE itself: the early waker raced the
  Choreographer (fires at edge+0.52ms measured) and its independent
  phase caused the -4..+4ms render-phase wander. Choreographer is the
  single wake source.
- MISS lines carry forensics: sw/sn (wake slot vs last rendered slot),
  eage (ms since last observed vsync edge), lastage (ms since last
  render) — distinguishes chain-stall / loop-stuck / guard-reject /
  no-wake-iteration without a second run.
stg.rs:
- ctxsw_sample() reads /proc/self/task/<pid>/stat for voluntary/involuntary
  context switches, CONDITIONAL on iteration >5ms (per-iteration procfs
  reads were a measured confounder: 20-50us each, pushed phase across
  the slot boundary, 10x worse drops). vsw/nvol on the IT line.
- precpu: CPU time inside Queue::present on the PRES line (pre_us >>
  precpu = blocked on binder/fence/SF; pre_us ~= precpu = CPU-bound).
wgpu_30_surface.rs: EW_ON moved here (vkprobe) so vsync.rs can gate the
wake without a new crate dependency.
lib.rs: poll backstop uses the dirty state; 6ms cap during active phases.
2026-10-30 14:51:06 -04:00

346 lines
13 KiB
Rust

// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
//! Drives animation frames from the display's vsync using the Android Choreographer.
//! Optimized for ultra-low latency: self-re-entrant Choreographer callbacks wake
//! the main loop directly on vsync without thread round-trip serialization delay.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;
use crate::android_activity::AndroidAppWaker;
use crate::ndk::looper::{ForeignLooper, ThreadLooper};
mod ffi {
use core::ffi::{c_long, c_void};
#[repr(C)]
pub struct AChoreographer {
_unused: [u8; 0],
}
pub type FrameCallback = unsafe extern "C" fn(frame_time_nanos: c_long, data: *mut c_void);
#[link(name = "android")]
unsafe extern "C" {
pub fn AChoreographer_getInstance() -> *mut AChoreographer;
pub fn AChoreographer_postFrameCallback(
choreographer: *mut AChoreographer,
callback: FrameCallback,
data: *mut c_void,
);
}
}
struct Shared {
state: Mutex<State>,
cond: Condvar,
driving: AtomicBool,
looper: Mutex<Option<ForeignLooper>>,
main_waker: AndroidAppWaker,
choreographer: *mut ffi::AChoreographer,
}
unsafe impl Send for Shared {}
unsafe impl Sync for Shared {}
#[derive(Default)]
struct State {
animating: bool,
/// Window is dirty (pending_redraw). The Choreographer callback chain
/// re-posts while `animating || dirty` (2026-07-09): gating on
/// `animating` alone let the chain die during flings (pointer
/// inactivity >200 ms) and on any `has_active_animations` flicker —
/// with the early waker disabled the loop then froze until the next
/// input event (measured: 30 frames in 4 s of drag, then silence).
/// `set_state` is called by the main loop on EVERY iteration, so the
/// dirty mirror can be at most one iteration (≈8 ms) stale — the 6 ms
/// poll backstop for dirty windows bounds the damage of a chain break.
dirty: bool,
quit: bool,
callback_posted: bool,
}
pub struct VsyncDriver {
shared: Arc<Shared>,
handle: Option<JoinHandle<()>>,
waker_handle: Option<JoinHandle<()>>,
}
impl VsyncDriver {
pub fn new(main_waker: AndroidAppWaker) -> Self {
let shared = Arc::new(Shared {
state: Mutex::new(State::default()),
cond: Condvar::new(),
driving: AtomicBool::new(false),
looper: Mutex::new(None),
main_waker: main_waker.clone(),
choreographer: std::ptr::null_mut(),
});
let handle = std::thread::Builder::new()
.name("slint vsync".into())
.spawn({
let shared = shared.clone();
move || vsync_thread(shared)
})
.ok();
// EARLY WAKER (the real 120Hz fix, part 2): the Choreographer
// callback only reaches the UI thread ~2.5-6 ms AFTER the vsync
// edge — with a 2.5-5 ms Skia render plus present, that leaves
// no phase margin inside the 8.3 ms slot (measured: 51% of frames
// landed one slot late). This thread learns the vsync grid from
// the callback's `frame_time_nanos` (vkprobe::note_vsync_edge) and
// wakes the main loop slightly BEFORE each edge, so render start ≈
// the edge and present lands at a constant ~edge+3 ms phase.
// The Choreographer's late wake remains as fallback (the render
// freshness guard in the event loop prevents double renders).
let waker_handle = std::thread::Builder::new()
.name("slint early-waker".into())
.spawn({
let shared = shared.clone();
move || early_waker_thread(shared)
})
.ok();
Self {
shared,
handle,
waker_handle,
}
}
pub fn is_driving(&self) -> bool {
self.shared.driving.load(Ordering::Acquire)
}
/// Push (animating, dirty) into the driver every main-loop iteration.
/// The vsync thread re-posts the first Choreographer callback, and
/// `frame_callback` re-posts the chain, while `animating || dirty`.
pub fn set_state(&self, animating: bool, dirty: bool) {
let mut state = self.shared.state.lock().unwrap();
let was_active = state.animating || state.dirty;
let now_active = animating || dirty;
state.animating = animating;
state.dirty = dirty;
if !was_active && now_active {
drop(state);
// Wake the vsync thread: it may be parked in `poll_once` (the
// Choreographer queue drained once the previous active phase's
// self-sustaining callback chain ended). Waking the looper is
// what makes it re-check the state and post the first frame
// callback for this new phase.
if let Some(looper) = self.shared.looper.lock().unwrap().as_ref() {
looper.wake();
}
self.shared.cond.notify_one();
}
}
}
impl Drop for VsyncDriver {
fn drop(&mut self) {
let mut state = self.shared.state.lock().unwrap();
state.quit = true;
drop(state);
self.shared.cond.notify_one();
if let Some(looper) = self.shared.looper.lock().unwrap().as_ref() {
looper.wake();
}
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
if let Some(handle) = self.waker_handle.take() {
let _ = handle.join();
}
}
}
/// Wakes the main loop a few hundred microseconds before each vsync edge
/// (see the `early_waker_handle` docs in `VsyncDriver::new`). Runs at 120 Hz
/// only while animating; otherwise parks in short sleeps.
fn early_waker_thread(shared: Arc<Shared>) {
let waker = shared.main_waker.clone();
// Wake slightly BEFORE the edge so poll-returns + render-start lands on
// the edge; with a 2.5-5 ms Skia render the present then sits at a
// constant ~edge+3 ms (middle of the slot, ~2.5 ms of deadline margin
// both ways).
const LEAD_NS: u64 = 800_000;
loop {
{
let state = shared.state.lock().unwrap();
if state.quit {
return;
}
if !state.animating {
drop(state);
std::thread::sleep(std::time::Duration::from_millis(5));
continue;
}
}
let edge = i_slint_renderer_skia::wgpu_30_surface::vkprobe::VSYNC_EDGE_NS
.load(Ordering::Relaxed);
let period = i_slint_renderer_skia::wgpu_30_surface::vkprobe::VSYNC_PERIOD_NS
.load(Ordering::Relaxed);
let now = i_slint_renderer_skia::wgpu_30_surface::vkprobe::monotonic_ns();
// Grid unknown or stale (no callbacks for ~100 ms, e.g. the app
// went to the background): park briefly and re-check.
if edge == 0 || period == 0 || now == 0 || now > edge + 100_000_000 {
std::thread::sleep(std::time::Duration::from_millis(10));
continue;
}
// Next edge at/after (now + LEAD).
let mut target = edge + period;
while target < now.saturating_add(LEAD_NS) {
target += period;
}
let delay = target.saturating_sub(now + LEAD_NS);
if delay > 0 {
std::thread::sleep(std::time::Duration::from_nanos(delay));
}
let landed = i_slint_renderer_skia::wgpu_30_surface::vkprobe::monotonic_ns()
.saturating_sub(target);
// WAKE PROBE: log every attempt (120/s, non-blocking logger) so we
// can see the nanosleep landing distribution: `land` is ns relative
// to the edge target (negative = early). H1 (hypotheses-120hz.md):
// if land is systematically > +1 ms the waker skips every wake and
// the late Choreographer wake (~edge+5) wins every slot.
if i_slint_renderer_skia::wgpu_30_surface::vkprobe::EW_ON
.load(Ordering::Relaxed)
{
log::info!("EW land={}ms", (landed as i64 - 800_000) / 1000);
}
// Wake only if we landed within ~1 ms of the edge. If we overshot
// (CPU starvation), the Choreographer's late wake (~5 ms after the
// edge) covers the frame instead.
//
// EW_ON (2026-07-09) now gates the WAKE itself, not just the EW log.
// The waker was built on the refuted "callback 3-6 ms late" model;
// the Choreographer fires at edge+0.52 ms (measured) and is the
// single correct wake source. Two wake sources race the slot guard
// and each renders at its own phase — the measured render-phase
// wander (-4..+4 ms) that turned a 120 Hz stream into 12-17 ms
// gaps (drops) and 4-6 ms gaps (doubles). With the Choreographer
// alone, the render phase is pinned to edge+~0.5-1.0 ms.
if landed <= 1_000_000
&& i_slint_renderer_skia::wgpu_30_surface::vkprobe::EW_ON
.load(Ordering::Relaxed)
{
waker.wake();
}
}
}
// Jank-hunt: frame-alignment probes. `frame_time_nanos` is the Choreographer
// vsync timestamp (System.nanoTime epoch = CLOCK_MONOTONIC on Android); we
// ALSO stamp CLOCK_MONOTONIC here so VSYNC and PRES lines share one clock and
// we can measure, per presented frame, how far past the vsync edge it landed
// (phase). If presents systematically land in the back half of the 8.3 ms
// window the compositor shows them one vsync late → effective 60 Hz + judder
// even though our frame-to-frame cadence looks like 120 Hz.
unsafe fn mon_ns() -> u64 {
#[repr(C)]
struct Ts {
tv_sec: i64,
tv_nsec: i64,
}
unsafe extern "C" {
fn clock_gettime(clkid: i32, tp: *mut Ts) -> i32;
}
const CLOCK_MONOTONIC: i32 = 1;
let mut ts = Ts { tv_sec: 0, tv_nsec: 0 };
if unsafe { clock_gettime(CLOCK_MONOTONIC, &mut ts) } == 0 {
ts.tv_sec as u64 * 1_000_000_000 + ts.tv_nsec as u64
} else {
0
}
}
unsafe extern "C" fn frame_callback(
frame_time_nanos: core::ffi::c_long,
data: *mut core::ffi::c_void,
) {
let shared = &*(data as *const Shared);
// CRITICAL PATH: wake the main loop FIRST. The VSYNC log line below is
// a file write (50-200us typical, worse under I/O pressure) — doing it
// before the wake would push the main loop's render start (and thus the
// present phase) later in the slot.
shared.main_waker.wake();
// PRESENT GATE: publish the exact vsync edge (CLOCK_MONOTONIC ns — the
// same epoch as `mon_ns()` above) so the renderer can quantize its
// `Queue::present` to the vsync grid (wgpu_30_surface::vkprobe).
i_slint_renderer_skia::wgpu_30_surface::vkprobe::note_vsync_edge(
frame_time_nanos as u64,
);
let mon = unsafe { mon_ns() };
if mon > 0 {
log::info!("VSYNC ftn={} mon={}", frame_time_nanos, mon);
}
let mut state = shared.state.lock().unwrap();
if (state.animating || state.dirty) && !state.quit {
unsafe {
ffi::AChoreographer_postFrameCallback(
shared.choreographer,
frame_callback,
data,
);
}
} else {
state.callback_posted = false;
}
}
fn vsync_thread(shared: Arc<Shared>) {
let looper = ThreadLooper::prepare();
*shared.looper.lock().unwrap() = Some(looper.as_foreign().clone());
let choreographer = unsafe { ffi::AChoreographer_getInstance() };
if choreographer.is_null() {
return;
}
let ptr = Arc::as_ptr(&shared) as *mut Shared;
unsafe {
(*ptr).choreographer = choreographer;
}
shared.driving.store(true, Ordering::Release);
let raw_shared = Arc::into_raw(shared);
loop {
{
let mut state = unsafe { &(*raw_shared).state }.lock().unwrap();
if state.quit {
break;
}
// Post the FIRST frame callback ONLY when we're animating AND no
// callback is already pending. While animating, `frame_callback`
// re-posts itself on every vsync (self-sustaining chain), so a
// callback is always pending — we must NOT post another here, or
// the pending-callback count grows by one every vsync (1, 2, 3,
// 4…) and each vsync fires N callbacks → N main-loop wakes with N
// unbounded. That was the ~1600 iters/s busy-spin. See
// docs/BUGS/scroll-jank-120hz.md.
if (state.animating || state.dirty) && !state.callback_posted {
state.callback_posted = true;
unsafe {
ffi::AChoreographer_postFrameCallback(
choreographer,
frame_callback,
raw_shared as *mut core::ffi::c_void,
);
}
}
}
// Block until the next Choreographer message (a vsync fires the frame
// callback) or a wake (set_animating/quit). While animating the
// self-sustaining chain keeps delivering one message per vsync; when
// the animation stops the chain ends and this blocks until the next
// animation's set_animating(true) wakes the looper.
let _ = looper.poll_once();
}
let _ = unsafe { Arc::from_raw(raw_shared) };
}