app: cherry-pick rune's pause and sound fixes onto the checkout
Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch ported, carrying the four commits of upstream issues 1320 (a pause while a clip is layered holds the layer's picture and time) and 1325 (a video's sound is read ahead of the clock and leads it). Both were written against eb9f1104 and ported across the refactors since. The faults are the first two and the third in docs/rune-upstream.md; the app's workarounds in review.rs stay until the fixes arrive upstream.
This commit is contained in:
1 parent
80fef698ce
commit
5bf262b82b
3795 files changed
+663463
-28
No files matched your search
@@ -0,0 +1,155 @@
|
||||
// A minimal hand-written Metal HUD for comparing per-frame CPU with Rune's overlay
|
||||
// (crates/rune/examples/overlay_hud_cost.rs): a 360x80 borderless panel at the bottom of the
|
||||
// screen whose CAMetalLayer is cleared to an animating colour from a CVDisplayLink callback,
|
||||
// one command buffer per frame with the drawable presented on it.
|
||||
//
|
||||
// swiftc -O metal_hud.swift -o metal_hud && ./metal_hud
|
||||
//
|
||||
// Env: HUD_SECONDS (default 12); HUD_EXTRA_CBS=n commits n empty command buffers a frame;
|
||||
// HUD_SPLIT_PRESENT=1 presents from a command buffer of its own; HUD_DIRECT_PRESENT=1 commits,
|
||||
// waits until the command buffer is scheduled and presents the drawable with no command buffer;
|
||||
// HUD_HANDLERS=n adds a completion handler to n command buffers a frame (extras first);
|
||||
// HUD_LABELS=1 labels each one; HUD_MAIN=1 draws on the main thread (the display link only
|
||||
// wakes it). These mimic what wgpu does per frame (research/30-overlay-gpu-cost.md).
|
||||
// Prints frames, fps and CPU ms per second for the main thread, the drawing thread and the rest.
|
||||
|
||||
import AppKit
|
||||
import CoreVideo
|
||||
import Metal
|
||||
import QuartzCore
|
||||
|
||||
func env(_ name: String, _ fallback: Int) -> Int { Int(ProcessInfo.processInfo.environment[name] ?? "") ?? fallback }
|
||||
let seconds = Double(env("HUD_SECONDS", 12))
|
||||
let extraCBs = env("HUD_EXTRA_CBS", 0)
|
||||
let splitPresent = env("HUD_SPLIT_PRESENT", 0) != 0
|
||||
let directPresent = env("HUD_DIRECT_PRESENT", 0) != 0
|
||||
let handlers = env("HUD_HANDLERS", 0)
|
||||
let labels = env("HUD_LABELS", 0) != 0
|
||||
let onMain = env("HUD_MAIN", 0) != 0
|
||||
|
||||
func threadCPU() -> Double {
|
||||
var t = timespec()
|
||||
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t)
|
||||
return Double(t.tv_sec) * 1e3 + Double(t.tv_nsec) / 1e6
|
||||
}
|
||||
func processCPU() -> Double {
|
||||
var u = rusage()
|
||||
getrusage(RUSAGE_SELF, &u)
|
||||
func ms(_ t: timeval) -> Double { Double(t.tv_sec) * 1e3 + Double(t.tv_usec) / 1e3 }
|
||||
return ms(u.ru_utime) + ms(u.ru_stime)
|
||||
}
|
||||
|
||||
func processCounts() -> [UInt64] {
|
||||
var info = rusage_info_v4()
|
||||
let ok = withUnsafeMutablePointer(to: &info) { p in
|
||||
p.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { proc_pid_rusage(getpid(), RUSAGE_INFO_V4, $0) }
|
||||
}
|
||||
return ok == 0 ? [info.ri_instructions, info.ri_cycles, info.ri_interrupt_wkups] : [0, 0, 0]
|
||||
}
|
||||
|
||||
final class Hud {
|
||||
let device = MTLCreateSystemDefaultDevice()!
|
||||
lazy var queue = device.makeCommandQueue()!
|
||||
let layer = CAMetalLayer()
|
||||
let start = Date()
|
||||
var frames = 0
|
||||
var drawCPU = 0.0
|
||||
var mainCPU0 = 0.0, process0 = 0.0, draw0 = 0.0, frames0 = 0, wall0 = Date()
|
||||
var warm = false
|
||||
var counts0: [UInt64] = [0, 0, 0]
|
||||
|
||||
var handled = 0
|
||||
|
||||
func frame() {
|
||||
handled = 0
|
||||
let entered = threadCPU()
|
||||
frames += 1
|
||||
let elapsed = Date().timeIntervalSince(start)
|
||||
if !warm && elapsed >= 2 {
|
||||
warm = true
|
||||
process0 = processCPU(); counts0 = processCounts(); draw0 = drawCPU; frames0 = frames; wall0 = Date()
|
||||
DispatchQueue.main.async { self.mainCPU0 = threadCPU() }
|
||||
}
|
||||
if warm && elapsed >= seconds {
|
||||
let wall = Date().timeIntervalSince(wall0)
|
||||
let n = Double(frames - frames0)
|
||||
let draw = drawCPU - draw0
|
||||
let process = processCPU() - process0
|
||||
let counts = processCounts()
|
||||
let per = { (i: Int) in Double(counts[i] - self.counts0[i]) / n }
|
||||
DispatchQueue.main.async {
|
||||
let main = threadCPU() - self.mainCPU0
|
||||
let drawing = onMain ? 0 : draw
|
||||
print(String(format: "frames=%.0f fps=%.1f main_ms_per_s=%.1f draw_thread_ms_per_s=%.1f other_ms_per_s=%.1f process_cpu_pct=%.1f draw_us_per_frame=%.1f",
|
||||
n, n / wall, main / wall, drawing / wall, (process - main - drawing) / wall, process / wall / 10, draw * 1e3 / n))
|
||||
print(String(format: "process_per_frame: kinstructions=%.1f kcycles=%.1f wakeups=%.2f", per(0) / 1e3, per(1) / 1e3, per(2)))
|
||||
exit(0)
|
||||
}
|
||||
}
|
||||
autoreleasepool {
|
||||
guard let drawable = layer.nextDrawable() else { return }
|
||||
let phase = sin(elapsed * 2) * 0.5 + 0.5
|
||||
for _ in 0..<extraCBs { commit(queue.makeCommandBufferWithUnretainedReferences()!, "extra") }
|
||||
let cb = queue.makeCommandBufferWithUnretainedReferences()!
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = drawable.texture
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: phase * 0.4, alpha: 0.4)
|
||||
cb.makeRenderCommandEncoder(descriptor: pass)!.endEncoding()
|
||||
if directPresent {
|
||||
commit(cb, "frame")
|
||||
cb.waitUntilScheduled()
|
||||
drawable.present()
|
||||
} else if splitPresent {
|
||||
commit(cb, "frame")
|
||||
let present = queue.makeCommandBuffer()!
|
||||
present.present(drawable)
|
||||
commit(present, "present")
|
||||
} else {
|
||||
cb.present(drawable)
|
||||
commit(cb, "frame")
|
||||
}
|
||||
}
|
||||
drawCPU += threadCPU() - entered
|
||||
}
|
||||
|
||||
func commit(_ cb: MTLCommandBuffer, _ label: String) {
|
||||
if labels { cb.label = label }
|
||||
if handled < handlers { handled += 1; cb.addCompletedHandler { _ in } }
|
||||
cb.commit()
|
||||
}
|
||||
}
|
||||
|
||||
let app = NSApplication.shared
|
||||
app.setActivationPolicy(.accessory)
|
||||
let hud = Hud()
|
||||
let screen = NSScreen.main!.frame
|
||||
let size = NSSize(width: 360, height: 80)
|
||||
let panel = NSPanel(contentRect: NSRect(x: screen.midX - size.width / 2, y: screen.minY + 60, width: size.width, height: size.height),
|
||||
styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
|
||||
panel.isOpaque = false
|
||||
panel.backgroundColor = .clear
|
||||
panel.level = .statusBar
|
||||
panel.ignoresMouseEvents = true
|
||||
let view = NSView(frame: NSRect(origin: .zero, size: size))
|
||||
view.wantsLayer = true
|
||||
hud.layer.device = hud.device
|
||||
hud.layer.pixelFormat = .bgra8Unorm
|
||||
hud.layer.isOpaque = false
|
||||
hud.layer.framebufferOnly = true
|
||||
hud.layer.contentsScale = panel.backingScaleFactor
|
||||
hud.layer.drawableSize = CGSize(width: size.width * panel.backingScaleFactor, height: size.height * panel.backingScaleFactor)
|
||||
view.layer = hud.layer
|
||||
panel.contentView = view
|
||||
panel.orderFrontRegardless()
|
||||
|
||||
var link: CVDisplayLink?
|
||||
CVDisplayLinkCreateWithActiveCGDisplays(&link)
|
||||
CVDisplayLinkSetOutputHandler(link!) { _, _, _, _, _ in
|
||||
if onMain { DispatchQueue.main.async { hud.frame() } } else { hud.frame() }
|
||||
return kCVReturnSuccess
|
||||
}
|
||||
CVDisplayLinkStart(link!)
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + seconds + 20) { print("metal_hud: no frames"); exit(1) }
|
||||
app.run()
|
||||
@@ -0,0 +1,16 @@
|
||||
diff --git a/src/device/queue.rs b/src/device/queue.rs
|
||||
index 1c0ac26..7c9c458 100644
|
||||
--- a/src/device/queue.rs
|
||||
+++ b/src/device/queue.rs
|
||||
@@ -186,7 +186,10 @@ impl Queue {
|
||||
pending
|
||||
};
|
||||
|
||||
- if pending.is_empty() {
|
||||
+ if pending.is_empty()
|
||||
+ || (!needs_clear
|
||||
+ && pending.iter().all(|p| p.usage.from == wgt::TextureUses::PRESENT))
|
||||
+ {
|
||||
// This assert checks that we don't return here if we encoded a
|
||||
// clear operation for the texture, which would be a problem since
|
||||
// we haven't done anything yet to ensure it stays alive. If we
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
diff --git a/src/metal/command.rs b/src/metal/command.rs
|
||||
index ba41a63..5993441 100644
|
||||
--- a/src/metal/command.rs
|
||||
+++ b/src/metal/command.rs
|
||||
@@ -153,6 +153,35 @@ impl Encoder<'_> {
|
||||
}
|
||||
|
||||
impl super::CommandEncoder {
|
||||
+ /// The Metal command buffer, made now if this encoding hasn't needed one yet.
|
||||
+ fn cmd_buf(&mut self) -> Retained<ProtocolObject<dyn MTLCommandBuffer>> {
|
||||
+ if self.raw_cmd_buf.is_none() {
|
||||
+ assert!(self.begun);
|
||||
+ let queue = &self.queue_shared.raw;
|
||||
+ let retain_references = self.shared.settings.retain_command_buffer_references;
|
||||
+ let relay = self.queue_shared.relay.get();
|
||||
+ let label = self.label.as_deref();
|
||||
+ let raw = autoreleasepool(move |_| {
|
||||
+ let cmd_buf_ref = if retain_references {
|
||||
+ queue.commandBuffer()
|
||||
+ } else {
|
||||
+ queue.commandBufferWithUnretainedReferences()
|
||||
+ }
|
||||
+ .unwrap();
|
||||
+ if let Some(label) = label {
|
||||
+ cmd_buf_ref.setLabel(Some(&NSString::from_str(label)));
|
||||
+ }
|
||||
+ if let Some(relay) = relay {
|
||||
+ let expected = relay.next_release_value.load(atomic::Ordering::Acquire);
|
||||
+ cmd_buf_ref.encodeWaitForEvent_value(relay.event.as_ref(), expected);
|
||||
+ }
|
||||
+ cmd_buf_ref.to_owned()
|
||||
+ });
|
||||
+ self.raw_cmd_buf = Some(raw);
|
||||
+ }
|
||||
+ self.raw_cmd_buf.clone().unwrap()
|
||||
+ }
|
||||
+
|
||||
pub fn raw_command_buffer(&self) -> Option<&ProtocolObject<dyn MTLCommandBuffer>> {
|
||||
self.raw_cmd_buf.as_deref()
|
||||
}
|
||||
@@ -161,7 +190,7 @@ impl super::CommandEncoder {
|
||||
if self.state.blit.is_none() {
|
||||
self.leave_acceleration_structure_builder();
|
||||
debug_assert!(self.state.render.is_none() && self.state.compute.is_none());
|
||||
- let cmd_buf = self.raw_cmd_buf.as_ref().unwrap();
|
||||
+ let cmd_buf = &self.cmd_buf();
|
||||
|
||||
// This code path is currently unused since the written timestamp is always 0.
|
||||
// We should see if we can get it working again, if not remove the code.
|
||||
@@ -271,7 +300,7 @@ impl super::CommandEncoder {
|
||||
&& self.state.compute.is_none()
|
||||
&& self.state.blit.is_none()
|
||||
);
|
||||
- let cmd_buf = self.raw_cmd_buf.as_ref().unwrap();
|
||||
+ let cmd_buf = &self.cmd_buf();
|
||||
autoreleasepool(|_| {
|
||||
self.state.acceleration_structure_builder =
|
||||
cmd_buf.accelerationStructureCommandEncoder().to_owned();
|
||||
@@ -500,32 +529,9 @@ impl crate::CommandEncoder for super::CommandEncoder {
|
||||
return Err(crate::DeviceError::Lost);
|
||||
}
|
||||
|
||||
- let raw = autoreleasepool(move |_| {
|
||||
- let cmd_buf_ref = if retain_references {
|
||||
- queue.commandBuffer()
|
||||
- } else {
|
||||
- queue.commandBufferWithUnretainedReferences()
|
||||
- }
|
||||
- .unwrap();
|
||||
- if let Some(label) = label {
|
||||
- cmd_buf_ref.setLabel(Some(&NSString::from_str(label)));
|
||||
- }
|
||||
- // If strict event sync is enabled on this queue, gate the
|
||||
- // CB on the relay event at the value the next submit will
|
||||
- // signal. The CB pauses at the start until the relay fires.
|
||||
- if let Some(relay) = relay {
|
||||
- let expected = relay.next_release_value.load(atomic::Ordering::Acquire);
|
||||
- cmd_buf_ref.encodeWaitForEvent_value(relay.event.as_ref(), expected);
|
||||
- }
|
||||
- cmd_buf_ref.to_owned()
|
||||
- });
|
||||
-
|
||||
- // Queries should either be closed out, or cleared in `discard_encoding`.
|
||||
- // This assertion is here mainly to facilitate comparison with the other
|
||||
- // backends, which clear in `begin_encoding` rather than `discard_encoding`.
|
||||
- debug_assert!(self.state.pending_timer_queries.is_empty());
|
||||
-
|
||||
- self.raw_cmd_buf = Some(raw);
|
||||
+ let _ = (queue, retain_references, relay);
|
||||
+ self.label = label.map(str::to_owned);
|
||||
+ self.begun = true;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -542,7 +548,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
|
||||
encoder.endEncoding();
|
||||
}
|
||||
self.state.pending_timer_queries.clear();
|
||||
- let had_command_buffer = self.raw_cmd_buf.is_some();
|
||||
+ let had_command_buffer = std::mem::take(&mut self.begun);
|
||||
// Clear the Option first so the underlying `metal::CommandBuffer` is
|
||||
// dropped before we update the counter.
|
||||
self.raw_cmd_buf = None;
|
||||
@@ -566,8 +572,9 @@ impl crate::CommandEncoder for super::CommandEncoder {
|
||||
debug_assert!(self.state.compute.is_none());
|
||||
debug_assert!(self.state.pending_timer_queries.is_empty());
|
||||
|
||||
+ self.begun = false;
|
||||
Ok(super::CommandBuffer {
|
||||
- raw: self.raw_cmd_buf.take().unwrap(),
|
||||
+ raw: self.raw_cmd_buf.take(),
|
||||
queue_shared: Arc::clone(&self.queue_shared),
|
||||
})
|
||||
}
|
||||
@@ -1049,7 +1056,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
|
||||
if let Some(mv) = desc.multiview_mask {
|
||||
descriptor.setRenderTargetArrayLength(32 - mv.leading_zeros() as usize);
|
||||
}
|
||||
- let raw = self.raw_cmd_buf.as_ref().unwrap();
|
||||
+ let raw = &self.cmd_buf();
|
||||
let encoder = raw.renderCommandEncoderWithDescriptor(&descriptor).unwrap();
|
||||
if let Some(mv) = desc.multiview_mask {
|
||||
// Most likely the API just wasn't thought about enough. It's not like they ever allow you
|
||||
@@ -1260,14 +1267,16 @@ impl crate::CommandEncoder for super::CommandEncoder {
|
||||
unsafe fn begin_debug_marker(&mut self, group_label: &str) {
|
||||
if let Some(encoder) = self.active_encoder() {
|
||||
encoder.pushDebugGroup(&NSString::from_str(group_label));
|
||||
- } else if let Some(ref buf) = self.raw_cmd_buf {
|
||||
+ } else if self.begun {
|
||||
+ let buf = self.cmd_buf();
|
||||
buf.pushDebugGroup(&NSString::from_str(group_label));
|
||||
}
|
||||
}
|
||||
unsafe fn end_debug_marker(&mut self) {
|
||||
if let Some(encoder) = self.active_encoder() {
|
||||
encoder.popDebugGroup();
|
||||
- } else if let Some(ref buf) = self.raw_cmd_buf {
|
||||
+ } else if self.begun {
|
||||
+ let buf = self.cmd_buf();
|
||||
buf.popDebugGroup();
|
||||
}
|
||||
}
|
||||
@@ -1689,7 +1698,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
|
||||
debug_assert!(self.state.compute.is_none());
|
||||
debug_assert!(self.state.render.is_none());
|
||||
|
||||
- let raw = self.raw_cmd_buf.as_ref().unwrap();
|
||||
+ let raw = &self.cmd_buf();
|
||||
|
||||
autoreleasepool(|_| {
|
||||
// TimeStamp Queries and ComputePassDescriptor were both introduced in Metal 2.3 (macOS 11, iOS 14)
|
||||
@@ -1897,18 +1906,19 @@ impl crate::CommandEncoder for super::CommandEncoder {
|
||||
command_buffers: &[&super::CommandBuffer],
|
||||
dependencies: &[&super::AccelerationStructure],
|
||||
) {
|
||||
- let Some(first_command_buffer) = command_buffers.first() else {
|
||||
+ let Some(first_raw) = command_buffers.iter().find_map(|b| b.raw.as_ref()) else {
|
||||
return;
|
||||
};
|
||||
let desc = MTLResidencySetDescriptor::new();
|
||||
- desc.setLabel(first_command_buffer.raw.label().as_deref());
|
||||
- let residency_set = first_command_buffer
|
||||
- .raw
|
||||
+ desc.setLabel(first_raw.label().as_deref());
|
||||
+ let residency_set = first_raw
|
||||
.device()
|
||||
.newResidencySetWithDescriptor_error(&desc)
|
||||
.unwrap();
|
||||
for command_buffer in command_buffers {
|
||||
- command_buffer.raw.useResidencySet(&residency_set);
|
||||
+ if let Some(raw) = &command_buffer.raw {
|
||||
+ raw.useResidencySet(&residency_set);
|
||||
+ }
|
||||
}
|
||||
for dependency in dependencies {
|
||||
residency_set.addAllocation(ProtocolObject::from_ref(&*dependency.raw));
|
||||
@@ -1965,7 +1975,8 @@ impl Drop for super::CommandBuffer {
|
||||
// `command_buffer_created_not_submitted` is usually decremented when the command
|
||||
// buffer is submitted. But if we're dropping a command buffer that was never
|
||||
// submitted, we need to decrement the count here.
|
||||
- let status = self.raw.status();
|
||||
+ let Some(raw) = &self.raw else { return };
|
||||
+ let status = raw.status();
|
||||
if status == MTLCommandBufferStatus::NotEnqueued
|
||||
|| status == MTLCommandBufferStatus::Enqueued
|
||||
{
|
||||
diff --git a/src/metal/device.rs b/src/metal/device.rs
|
||||
index d7287b9..9ba3335 100644
|
||||
--- a/src/metal/device.rs
|
||||
+++ b/src/metal/device.rs
|
||||
@@ -773,6 +773,8 @@ impl crate::Device for super::Device {
|
||||
shared: Arc::clone(&self.shared),
|
||||
queue_shared: Arc::clone(&desc.queue.shared),
|
||||
raw_cmd_buf: None,
|
||||
+ begun: false,
|
||||
+ label: None,
|
||||
state: super::CommandState::default(),
|
||||
temp: super::Temp::default(),
|
||||
counters: Arc::clone(&self.counters),
|
||||
diff --git a/src/metal/mod.rs b/src/metal/mod.rs
|
||||
index e227590..831e0f0 100644
|
||||
--- a/src/metal/mod.rs
|
||||
+++ b/src/metal/mod.rs
|
||||
@@ -741,8 +741,9 @@ impl crate::Queue for Queue {
|
||||
fence_sync.1.notify_all();
|
||||
});
|
||||
|
||||
- let raw = match command_buffers.last() {
|
||||
- Some(&cmd_buf) => cmd_buf.raw.clone(),
|
||||
+ let last = command_buffers.iter().rev().find_map(|b| b.raw.clone());
|
||||
+ let raw = match last.clone() {
|
||||
+ Some(raw) => raw,
|
||||
None => {
|
||||
// We do not bother adjusting `command_buffer_created_not_submitted`
|
||||
// because we immediately commit this buffer.
|
||||
@@ -775,14 +776,16 @@ impl crate::Queue for Queue {
|
||||
}
|
||||
|
||||
// only return an extra one if it's extra
|
||||
- match command_buffers.last() {
|
||||
+ match last {
|
||||
Some(_) => None,
|
||||
None => Some(raw),
|
||||
}
|
||||
};
|
||||
|
||||
for cmd_buffer in command_buffers {
|
||||
- cmd_buffer.raw.commit();
|
||||
+ if let Some(raw) = &cmd_buffer.raw {
|
||||
+ raw.commit();
|
||||
+ }
|
||||
// One command buffer per `end_encoding` call moves from the
|
||||
// "created but not yet submitted" bucket into the submitted
|
||||
// set, so update the counter.
|
||||
@@ -1354,6 +1357,10 @@ pub struct CommandEncoder {
|
||||
shared: Arc<AdapterShared>,
|
||||
queue_shared: Arc<QueueShared>,
|
||||
raw_cmd_buf: Option<Retained<ProtocolObject<dyn MTLCommandBuffer>>>,
|
||||
+ /// Between `begin_encoding` and `end_encoding`/`discard_encoding`; the Metal command
|
||||
+ /// buffer is made on first use, so an encoding that records nothing commits nothing.
|
||||
+ begun: bool,
|
||||
+ label: Option<String>,
|
||||
state: CommandState,
|
||||
temp: Temp,
|
||||
counters: Arc<wgt::HalCounters>,
|
||||
@@ -1372,7 +1379,7 @@ unsafe impl Sync for CommandEncoder {}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CommandBuffer {
|
||||
- raw: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
|
||||
+ raw: Option<Retained<ProtocolObject<dyn MTLCommandBuffer>>>,
|
||||
queue_shared: Arc<QueueShared>,
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user