Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use vendored performance API to handle timing on WASM #3318

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
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
5 changes: 3 additions & 2 deletions embassy-time/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ target = "x86_64-unknown-linux-gnu"
features = ["defmt", "std"]

[features]
default = ["panic_on_webworker"]
std = ["tick-hz-1_000_000", "critical-section/std"]
wasm = ["dep:wasm-bindgen", "dep:js-sys", "dep:wasm-timer", "tick-hz-1_000_000"]
wasm = ["dep:wasm-bindgen", "dep:js-sys", "tick-hz-1_000_000"]
panic_on_webworker = []

## Display the time since startup next to defmt log messages.
## At most 1 `defmt-timestamp-uptime-*` feature can be used.
Expand Down Expand Up @@ -426,7 +428,6 @@ document-features = "0.2.7"
# WASM dependencies
wasm-bindgen = { version = "0.2.81", optional = true }
js-sys = { version = "0.3", optional = true }
wasm-timer = { version = "0.2.5", optional = true }

[dev-dependencies]
serial_test = "0.9"
Expand Down
112 changes: 97 additions & 15 deletions embassy-time/src/driver_wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use std::sync::{Mutex, Once};

use embassy_time_driver::{AlarmHandle, Driver};
use wasm_bindgen::prelude::*;
use wasm_timer::Instant as StdInstant;

const ALARM_COUNT: usize = 4;

Expand Down Expand Up @@ -37,32 +36,42 @@ struct TimeDriver {

once: Once,
alarms: UninitCell<Mutex<[AlarmState; ALARM_COUNT]>>,
zero_instant: UninitCell<StdInstant>,
}

const ALARM_NEW: AlarmState = AlarmState::new();
embassy_time_driver::time_driver_impl!(static DRIVER: TimeDriver = TimeDriver {
alarm_count: AtomicU8::new(0),
once: Once::new(),
alarms: UninitCell::uninit(),
zero_instant: UninitCell::uninit(),
});

#[cfg(feature = "panic_on_webworker")]
thread_local! {
static CHECK_THREAD: Once = Once::new();
}

impl TimeDriver {
fn init(&self) {
fn ensure_init(&self) {
self.once.call_once(|| unsafe {
self.alarms.write(Mutex::new([ALARM_NEW; ALARM_COUNT]));
self.zero_instant.write(StdInstant::now());
});
#[cfg(feature = "panic_on_webworker")]
CHECK_THREAD.with(|val| {
val.call_once(|| {
assert!(
!is_web_worker_thread(),
"Timer currently has issues on Web Workers: https://github.com/embassy-rs/embassy/issues/3313"
);
})
});
}
}

impl Driver for TimeDriver {
fn now(&self) -> u64 {
self.init();

let zero = unsafe { self.zero_instant.read() };
StdInstant::now().duration_since(zero).as_micros() as u64
self.ensure_init();
// this is calibrated with timeOrigin.
now_as_calibrated_timestamp().as_micros() as u64
}

unsafe fn allocate_alarm(&self) -> Option<AlarmHandle> {
Expand All @@ -81,7 +90,7 @@ impl Driver for TimeDriver {
}

fn set_alarm_callback(&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) {
self.init();
self.ensure_init();
let mut alarms = unsafe { self.alarms.as_ref() }.lock().unwrap();
let alarm = &mut alarms[alarm.id() as usize];
alarm.closure.replace(Closure::new(move || {
Expand All @@ -90,7 +99,7 @@ impl Driver for TimeDriver {
}

fn set_alarm(&self, alarm: AlarmHandle, timestamp: u64) -> bool {
self.init();
self.ensure_init();
let mut alarms = unsafe { self.alarms.as_ref() }.lock().unwrap();
let alarm = &mut alarms[alarm.id() as usize];
if let Some(token) = alarm.token {
Expand Down Expand Up @@ -134,8 +143,81 @@ impl<T> UninitCell<T> {
}
}

impl<T: Copy> UninitCell<T> {
pub unsafe fn read(&self) -> T {
ptr::read(self.as_mut_ptr())
}
fn is_web_worker_thread() -> bool {
js_sys::eval("typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope")
.unwrap()
.is_truthy()
}

// ---------------- taken from web-time/js.rs
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::{JsCast, JsValue};

#[wasm_bindgen]
extern "C" {
/// Type for the [global object](https://developer.mozilla.org/en-US/docs/Glossary/Global_object).
type Global;

/// Returns the [`Performance`](https://developer.mozilla.org/en-US/docs/Web/API/Performance) object.
#[wasm_bindgen(method, getter)]
fn performance(this: &Global) -> JsValue;

/// Type for the [`Performance` object](https://developer.mozilla.org/en-US/docs/Web/API/Performance).
pub(super) type Performance;

/// Binding to [`Performance.now()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now).
#[wasm_bindgen(method)]
pub(super) fn now(this: &Performance) -> f64;

/// Binding to [`Performance.timeOrigin`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/timeOrigin).
#[wasm_bindgen(method, getter, js_name = timeOrigin)]
pub(super) fn time_origin(this: &Performance) -> f64;
}

thread_local! {
pub(super) static PERFORMANCE: Performance = {
let global: Global = js_sys::global().unchecked_into();
let performance = global.performance();

if performance.is_undefined() {
panic!("`Performance` object not found")
} else {
performance.unchecked_into()
}
};
}

// ---------------- taken from web-time/instant.rs

thread_local! {
static ORIGIN: f64 = PERFORMANCE.with(Performance::time_origin);
}

/// This will get a Duration from a synchronized start point, whether in webworkers or the main browser thread.
///
/// # Panics
///
/// This call will panic if the [`Performance` object] was not found, e.g.
/// calling from a [worklet].
///
/// [`Performance` object]: https://developer.mozilla.org/en-US/docs/Web/API/performance_property
/// [worklet]: https://developer.mozilla.org/en-US/docs/Web/API/Worklet
#[must_use]
pub fn now_as_calibrated_timestamp() -> core::time::Duration {
let now = PERFORMANCE.with(|performance| {
return ORIGIN.with(|origin| performance.now() + origin);
});
time_stamp_to_duration(now)
}

/// Converts a `DOMHighResTimeStamp` to a [`Duration`].
///
/// # Note
///
/// Keep in mind that like [`Duration::from_secs_f64()`] this doesn't do perfect
/// rounding.
#[allow(clippy::as_conversions, clippy::cast_possible_truncation, clippy::cast_sign_loss)]
fn time_stamp_to_duration(time_stamp: f64) -> core::time::Duration {
core::time::Duration::from_millis(time_stamp.trunc() as u64)
+ core::time::Duration::from_nanos((time_stamp.fract() * 1.0e6).round() as u64)
}