use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{LazyLock, Mutex};
use metal::{CommandBuffer, CommandBufferRef, MTLCommandBufferStatus};
use objc::{msg_send, sel, sel_impl};
static ENABLED: AtomicBool = AtomicBool::new(false);
struct Pending {
command: CommandBuffer,
record: CommandTimeline,
}
unsafe impl Send for Pending {}
static PENDING: Mutex<Vec<Pending>> = Mutex::new(Vec::new());
static MARKS: Mutex<Vec<(&'static str, f64)>> = Mutex::new(Vec::new());
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CommandTimeline {
pub label: String,
pub encode_begin_s: f64,
pub commit_begin_s: f64,
pub commit_end_s: f64,
pub wait_begin_s: f64,
pub wait_end_s: f64,
pub kernel_start_s: f64,
pub kernel_end_s: f64,
pub gpu_start_s: f64,
pub gpu_end_s: f64,
pub dispatches_at_commit: u64,
pub barriers_at_commit: u64,
pub completed: bool,
pub waited_in_drain: bool,
}
pub fn set_enabled(enabled: bool) {
ENABLED.store(enabled, Ordering::Relaxed);
}
#[inline]
pub fn enabled() -> bool {
ENABLED.load(Ordering::Relaxed)
}
#[inline]
pub fn mark(name: &'static str) {
if enabled() {
record_mark(name);
}
}
#[cold]
fn record_mark(name: &'static str) {
mark_at(name, now_seconds());
}
pub(crate) fn mark_at(name: &'static str, seconds: f64) {
if let Ok(mut marks) = MARKS.lock() {
if marks.len() >= MAX_PENDING {
DROPPED_MARKS.fetch_add(marks.len() as u64, Ordering::Relaxed);
marks.clear();
}
marks.push((name, seconds));
}
}
pub fn drain_marks() -> Vec<(&'static str, f64)> {
MARKS
.lock()
.map(|mut marks| std::mem::take(&mut *marks))
.unwrap_or_default()
}
#[repr(C)]
struct MachTimebaseInfo {
numer: u32,
denom: u32,
}
extern "C" {
fn mach_absolute_time() -> u64;
fn mach_timebase_info(info: *mut MachTimebaseInfo) -> i32;
}
pub fn now_seconds() -> f64 {
static SECONDS_PER_TICK: LazyLock<f64> = LazyLock::new(|| {
let mut info = MachTimebaseInfo { numer: 0, denom: 0 };
let status = unsafe { mach_timebase_info(&mut info) };
if status != 0 || info.denom == 0 {
return 0.0;
}
f64::from(info.numer) / f64::from(info.denom) * 1e-9
});
unsafe { mach_absolute_time() as f64 * *SECONDS_PER_TICK }
}
const MAX_PENDING: usize = 4096;
static DROPPED: AtomicU64 = AtomicU64::new(0);
static DROPPED_MARKS: AtomicU64 = AtomicU64::new(0);
pub fn dropped() -> u64 {
DROPPED.load(Ordering::Relaxed)
}
pub fn dropped_marks() -> u64 {
DROPPED_MARKS.load(Ordering::Relaxed)
}
pub(crate) fn committed(
command: &CommandBufferRef,
label: &str,
encode_begin_s: f64,
commit_begin_s: f64,
commit_end_s: f64,
dispatches_at_commit: u64,
barriers_at_commit: u64,
) {
let pending = Pending {
command: command.to_owned(),
record: CommandTimeline {
label: label.to_owned(),
encode_begin_s,
commit_begin_s,
commit_end_s,
dispatches_at_commit,
barriers_at_commit,
..CommandTimeline::default()
},
};
if let Ok(mut list) = PENDING.lock() {
if list.len() >= MAX_PENDING {
DROPPED.fetch_add(list.len() as u64, Ordering::Relaxed);
objc::rc::autoreleasepool(|| list.clear());
}
list.push(pending);
}
}
pub(crate) fn waited(command: &CommandBufferRef, wait_begin_s: f64, wait_end_s: f64) {
let Ok(mut list) = PENDING.lock() else {
return;
};
let target = command as *const CommandBufferRef;
if let Some(pending) = list
.iter_mut()
.rev()
.find(|pending| std::ptr::eq(&*pending.command as *const CommandBufferRef, target))
{
if pending.record.wait_begin_s == 0.0 {
pending.record.wait_begin_s = wait_begin_s;
pending.record.wait_end_s = wait_end_s;
}
}
}
pub fn drain() -> Vec<CommandTimeline> {
let pending = match PENDING.lock() {
Ok(mut list) => std::mem::take(&mut *list),
Err(_) => return Vec::new(),
};
let mut records = Vec::with_capacity(pending.len());
objc::rc::autoreleasepool(|| {
for Pending {
command,
mut record,
} in pending
{
let mut status = command.status();
if !matches!(
status,
MTLCommandBufferStatus::Completed | MTLCommandBufferStatus::Error
) {
command.wait_until_completed();
record.waited_in_drain = true;
status = command.status();
}
if matches!(status, MTLCommandBufferStatus::Completed) {
record.completed = true;
unsafe {
let command: &CommandBufferRef = &command;
record.kernel_start_s = msg_send![command, kernelStartTime];
record.kernel_end_s = msg_send![command, kernelEndTime];
record.gpu_start_s = msg_send![command, GPUStartTime];
record.gpu_end_s = msg_send![command, GPUEndTime];
}
}
records.push(record);
}
});
records
}