use std::sync::{Arc, OnceLock, Weak};
use std::time::Duration;
use mln_style::error::Error;
use parking_lot::Mutex;
#[cfg_attr(target_os = "android", expect(unsafe_code, reason = "the choreographer and its looper are the FFI here"))]
mod android;
#[cfg_attr(
any(target_os = "macos", target_os = "ios", target_os = "tvos"),
expect(unsafe_code, reason = "the display link through objc2 is the FFI here")
)]
mod apple;
#[cfg_attr(target_env = "ohos", expect(unsafe_code, reason = "the native VSync is the FFI here"))]
mod ohos;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limit {
frames_per_second: u32,
period: Duration,
}
impl Limit {
#[must_use]
pub fn new(frames_per_second: u32) -> Option<Self> {
let period = Duration::from_secs(1).checked_div(frames_per_second)?;
Some(Self { frames_per_second, period })
}
#[must_use]
pub fn frames_per_second(self) -> u32 {
self.frames_per_second
}
fn slack(self) -> Duration {
self.period / 10
}
}
#[derive(Debug, Default)]
struct Throttle {
limit: Option<Limit>,
next: Option<Duration>,
last: Option<Duration>,
}
impl Throttle {
fn new(limit: Option<Limit>) -> Self {
Self { limit, ..Self::default() }
}
fn admit(&mut self, time: Duration) -> bool {
let Some(limit) = self.limit else {
self.last = Some(time);
return true;
};
if self.last.is_some_and(|last| time < last) {
self.next = None;
}
if self.next.is_some_and(|next| time + limit.slack() < next) {
return false;
}
self.next = Some(match self.next {
Some(next) if time < next + limit.period => next + limit.period,
_ => time + limit.period,
});
self.last = Some(time);
true
}
fn set_limit(&mut self, limit: Option<Limit>) {
self.limit = limit;
self.next = limit.zip(self.last).map(|(limit, last)| last + limit.period);
}
}
pub trait VsyncSource: Send + Sync {
fn schedule(&self);
fn set_limit(&self, _limit: Option<Limit>) {}
}
#[derive(Clone, Default)]
pub struct Vsyncs(Arc<OnceLock<Weak<FramePacer>>>);
impl Vsyncs {
pub fn vsync(&self, time: Duration) {
if let Some(pacer) = self.0.get().and_then(Weak::upgrade) {
pacer.on_vsync(time);
}
}
}
pub trait RefreshWaiter: Send + Sync {
fn refresh(&self, time: Duration);
}
impl<F: Fn(Duration) + Send + Sync> RefreshWaiter for F {
fn refresh(&self, time: Duration) {
self(time);
}
}
pub struct FramePacer {
state: Mutex<PacerState>,
limit_lock: Mutex<()>,
source: Box<dyn VsyncSource>,
}
struct PacerState {
waiting: Vec<Arc<dyn RefreshWaiter>>,
scheduled: bool,
throttle: Throttle,
}
impl FramePacer {
pub fn new(limit: Option<Limit>) -> Result<Arc<Self>, Error> {
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos"))]
let source = |vsyncs, limit| apple::display_link::DisplayLinkSource::new(vsyncs, limit, None);
#[cfg(target_os = "android")]
let source = android::choreographer::ChoreographerSource::new;
#[cfg(target_env = "ohos")]
let source = ohos::native_vsync::NativeVsyncSource::new;
#[cfg(not(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "android",
target_env = "ohos"
)))]
let source = |_, _| Err::<Unsupported, _>(Error::unsupported("the platform's display has no frame pacer"));
Self::with_source(limit, source)
}
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos"))]
#[expect(unsafe_code, reason = "the view is a pointer to an Objective-C object")]
pub unsafe fn for_view(
view: core::ptr::NonNull<core::ffi::c_void>,
limit: Option<Limit>,
) -> Result<Arc<Self>, Error> {
let view = apple::display_link::View(view);
Self::with_source(limit, |vsyncs, limit| apple::display_link::DisplayLinkSource::new(vsyncs, limit, Some(view)))
}
pub fn with_source<S: VsyncSource + 'static, E>(
limit: Option<Limit>,
source: impl FnOnce(Vsyncs, Option<Limit>) -> Result<S, E>,
) -> Result<Arc<Self>, E> {
let vsyncs = Vsyncs::default();
let source = source(vsyncs.clone(), limit)?;
let pacer = Arc::new(Self {
state: Mutex::new(PacerState { waiting: Vec::new(), scheduled: false, throttle: Throttle::new(limit) }),
limit_lock: Mutex::new(()),
source: Box::new(source),
});
let _ = vsyncs.0.set(Arc::downgrade(&pacer));
Ok(pacer)
}
pub fn request(&self, waiter: &Arc<dyn RefreshWaiter>) {
{
let mut state = self.state.lock();
if !state.waiting.iter().any(|waiting| Arc::ptr_eq(waiting, waiter)) {
state.waiting.push(Arc::clone(waiter));
}
if std::mem::replace(&mut state.scheduled, true) {
return;
}
}
self.source.schedule();
}
#[must_use]
pub fn limit(&self) -> Option<Limit> {
self.state.lock().throttle.limit
}
pub fn set_limit(&self, limit: Option<Limit>) {
let _changing = self.limit_lock.lock();
self.state.lock().throttle.set_limit(limit);
self.source.set_limit(limit);
}
fn on_vsync(&self, time: Duration) {
let due = {
let mut state = self.state.lock();
if state.waiting.is_empty() {
state.scheduled = false;
return;
}
if state.throttle.admit(time) {
state.scheduled = false;
Some(std::mem::take(&mut state.waiting))
} else {
None
}
};
match due {
Some(waiters) => waiters.iter().for_each(|waiter| waiter.refresh(time)),
None => self.source.schedule(),
}
}
}
#[cfg(not(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "android",
target_env = "ohos"
)))]
enum Unsupported {}
#[cfg(not(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "android",
target_env = "ohos"
)))]
impl VsyncSource for Unsupported {
fn schedule(&self) {
match *self {}
}
}
#[cfg(test)]
mod tests;