Skip to main content

oa/runtime/
clock_calibration.rs

1//! Paired host/device clock sample and wrap-aware timestamp mapping.
2//!
3//! Donor: oacpp/source/cpp/include/oa/runtime/clockCalibration.h.
4//! Adaptation: Rust naming; device-side sampling lives in
5//! `runtime::device` behind `Runtime::calibrate_clock`.
6
7/// Host clock paired with the Vulkan device timestamp domain. Host timestamps
8/// are nanoseconds in the corresponding POSIX clock domain; device timestamps
9/// are ticks and must be scaled by `device_nanoseconds_per_tick`.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum HostClockDomain {
12	#[default]
13	Monotonic,
14	MonotonicRaw,
15}
16
17/// One quasi-simultaneous host/device clock sample.
18/// `maximum_deviation_nanoseconds` is the Vulkan implementation's uncertainty
19/// bound for the pair, not an OA estimate. Consumers should recalibrate
20/// long-running traces periodically.
21#[derive(Clone, Copy, Debug, Default)]
22pub struct ClockCalibration {
23	pub device_timestamp_ticks: u64,
24	pub host_timestamp_nanoseconds: u64,
25	pub maximum_deviation_nanoseconds: u64,
26	pub device_nanoseconds_per_tick: f64,
27	pub device_timestamp_valid_bits: u32,
28	pub host_clock_domain: HostClockDomain,
29}
30
31impl ClockCalibration {
32	/// Map a query-pool timestamp into the calibrated host clock.
33	///
34	/// The signed modular delta handles Vulkan timestamp wrap for queues
35	/// exposing fewer than 64 valid bits. Values farther than half a
36	/// device-clock period from this sample are inherently ambiguous and
37	/// require a newer calibration. Returns 0 when the sample fields cannot
38	/// describe a usable mapping.
39	pub fn host_nanoseconds_for_device_timestamp(&self, device_timestamp_ticks: u64) -> f64 {
40		if self.device_timestamp_valid_bits == 0
41			|| self.device_timestamp_valid_bits > 64
42			|| self.device_nanoseconds_per_tick <= 0.0
43		{
44			return 0.0;
45		}
46		let signed_delta = if self.device_timestamp_valid_bits == 64 {
47			device_timestamp_ticks.wrapping_sub(self.device_timestamp_ticks) as i64
48		} else {
49			let modulus = 1_u64 << self.device_timestamp_valid_bits;
50			let mask = modulus - 1;
51			let delta = device_timestamp_ticks.wrapping_sub(self.device_timestamp_ticks) & mask;
52			if delta >= (modulus >> 1) {
53				-((modulus - delta) as i64)
54			} else {
55				delta as i64
56			}
57		};
58		self.host_timestamp_nanoseconds as f64 + signed_delta as f64 * self.device_nanoseconds_per_tick
59	}
60}
61
62#[cfg(test)]
63#[path = "../../../../test/rs/runtime/clock_calibration_unit.rs"]
64mod tests;