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
+84
@@ -0,0 +1,84 @@
|
||||
# Native presentation pacing
|
||||
|
||||
Timestamp-only probe on a GUI Mac. No screen capture. It measures `nextDrawable` entry to
|
||||
positive Metal `presentedTime`, using the overlay team's steady-state endpoint.
|
||||
Three batches per mode, two-second warmup, then three three-second intervals;
|
||||
the summary is the median of nine interval medians.
|
||||
|
||||
Build with `cargo build --profile perf -j 2 -p rune --example pacing_overlay --example pacing`
|
||||
on the Mac that runs the probe, and run jobs one at a time. Pass the
|
||||
`target/perf/examples/` executable path; the runners refuse binaries from any
|
||||
other profile.
|
||||
|
||||
```sh
|
||||
python3 scripts/native-pacing/run.py <out> <pacing_overlay> \
|
||||
--reference <path to a reference app executable>
|
||||
```
|
||||
|
||||
The runner checks it is on the expected GUI host, holds a GUI lock file, bounds
|
||||
app lifetimes, and removes its instrumentation dylib. `--modes native` selects only
|
||||
the continuous Rune workload; the default tests injected redraws and native
|
||||
animation. The reference app is optional and its order alternates between batches.
|
||||
|
||||
Rune uses a 680×160-point overlay. Native mode animates opacity continuously;
|
||||
injected mode uses a static view with an AppKit 60-Hz redraw timer. The reference
|
||||
app runs on a different-sized surface.
|
||||
Results include executable hashes, raw callback logs, drawable waits, interval
|
||||
medians, acquisition gaps, and counts of excluded zero presentation timestamps.
|
||||
These excluded callbacks are not a dropped-frame count. A timeout is a failed
|
||||
run and cannot serve as a complete performance baseline.
|
||||
|
||||
The `pacing` example separately exercises state commits, idle, hide/show and
|
||||
shutdown. Run it under the same GUI lock with `--native --trace <file>`, then
|
||||
check the file with `python3 scripts/check-native-pacing.py <file>`.
|
||||
|
||||
## Isolated refresh-rate experiments
|
||||
|
||||
Use a fresh output directory for each experiment:
|
||||
|
||||
```sh
|
||||
# Same production executable; one change at a time, in this order.
|
||||
python3 scripts/native-pacing/run.py <out-ca> <pacing_overlay> --modes native --display-link ca
|
||||
python3 scripts/native-pacing/run.py <out-two> <pacing_overlay> --modes native --drawables 2
|
||||
python3 scripts/native-pacing/run.py <out-unsynced> <pacing_overlay> --modes native --display-sync 0
|
||||
```
|
||||
|
||||
`clock-probe.m` interposes CV callback registration/start/stop. Its default mode
|
||||
counts real CV callbacks. CA mode supplies the same Rune callback from an NSView
|
||||
`CADisplayLink` with `CAFrameRateRangeMake(80, 120, 120)` on macOS 14+. This adapter
|
||||
selects the fixture's visible panel and supports this single-surface workload;
|
||||
it is not a general replacement for Rune's native display-link implementation.
|
||||
Layer overrides affect Rune only. An optional reference app keeps its settings.
|
||||
|
||||
For the admission-guard comparison, apply `admission-probe.patch` in a disposable
|
||||
checkout, generate a new source manifest, and rebuild the example. Run `--guard production` then `--guard no-half` on that same executable.
|
||||
The latter removes only elapsed-half-refresh admission, retaining stale-target
|
||||
and duplicate-target rejection. The runner requires matching diagnostic output.
|
||||
Counters are printed after stopping the link, not in the callback. Revert the
|
||||
patch and rebuild when finished. Never ship this patch; it exists to reproduce
|
||||
the experiment and intentionally leaves the original unit-test helper unused.
|
||||
|
||||
`acquisition_hz` uses `nextDrawable` entry times. `presentation_hz` uses distinct,
|
||||
positive `presentedTime` timestamps for frames acquired in the nine-second sample.
|
||||
Callback Hz and guard counts cover the full app run, including warmup. Guard
|
||||
reason counters can overlap; they are not an exhaustive partition of callbacks
|
||||
because pending callbacks coalesce. The summary includes the selected overrides
|
||||
and binary hash. Raw logs retain the actual layer settings.
|
||||
|
||||
With display sync disabled, positive presentation timestamps do not establish
|
||||
tear-free 120-Hz scanout. Apple's API explicitly allows tearing in this mode.
|
||||
|
||||
## Findings
|
||||
|
||||
With the default synced layer, the tested overlay presents at about 60 Hz on a
|
||||
120-Hz display, although CVDisplayLink and NSView CADisplayLink both deliver
|
||||
about 120 callbacks/s. Two drawables lower latency but keep 60-Hz presentation.
|
||||
Disabling display sync raises positive presentations above 100/s, which does not
|
||||
prove tear-free output. Removing the half-refresh admission guard moves waiting
|
||||
into `nextDrawable` without raising presentation frequency, and breaks the
|
||||
half-refresh bound: keep the guard. The evidence points to synced drawable
|
||||
backpressure, not callback rate.
|
||||
|
||||
`refresh-probe.m` then found the cause of the 60-Hz cap: Low Power Mode holds a
|
||||
ProMotion panel at 60 Hz while both display links and `NSScreen` still report
|
||||
120 Hz. `crates/rune/src/platform/display_link.rs` paces submissions at that cap.
|
||||
@@ -0,0 +1,59 @@
|
||||
diff --git a/crates/rune/src/display_link.rs b/crates/rune/src/display_link.rs
|
||||
index fc25f6e..25823f9 100644
|
||||
--- a/crates/rune/src/display_link.rs
|
||||
+++ b/crates/rune/src/display_link.rs
|
||||
@@ -25,6 +25,8 @@ pub(crate) struct DisplayLink {
|
||||
last_target: Option<Instant>,
|
||||
display: Option<u32>,
|
||||
running: bool,
|
||||
+ probe_no_half: bool,
|
||||
+ probe_counts: [u64; 5],
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn tick(
|
||||
@@ -70,7 +72,8 @@ impl DisplayLink {
|
||||
});
|
||||
let status = unsafe { link.set_output_callback(Some(tick), (&mut *callback as *mut Callback).cast()) };
|
||||
if status != 0 { eprintln!("display link callback failed: {status}"); return None; }
|
||||
- let mut pacing = Self { link, callback, last_present: None, last_target: None, display: None, running: false };
|
||||
+ let mut pacing = Self { link, callback, last_present: None, last_target: None, display: None, running: false,
|
||||
+ probe_no_half: std::env::var("STEADY_GUARD").as_deref() == Ok("no-half"), probe_counts: [0; 5] };
|
||||
pacing.update_display(window);
|
||||
Some(pacing)
|
||||
}
|
||||
@@ -93,13 +96,20 @@ impl DisplayLink {
|
||||
self.running = true;
|
||||
}
|
||||
let host_target = self.callback.target.swap(0, Ordering::Acquire);
|
||||
- if host_target == 0 { return None; }
|
||||
+ if host_target == 0 { self.probe_counts[0] += 1; return None; }
|
||||
let now = Instant::now();
|
||||
let target = target_time(now, CVGetCurrentHostTime(), host_target, self.callback.host_frequency);
|
||||
let period = Duration::from_nanos(self.callback.period_ns.load(Ordering::Relaxed));
|
||||
// A late render followed by an on-time tick must skip, not submit two frames
|
||||
// together. Also discard stale callbacks after main-thread stalls.
|
||||
- if !permits(self.last_present, self.last_target, target, now, period) { return None; }
|
||||
+ let stale = now >= target;
|
||||
+ let duplicate = self.last_target.is_some_and(|last| target <= last);
|
||||
+ let short = self.last_present.is_some_and(|last| now.saturating_duration_since(last) < period / 2);
|
||||
+ self.probe_counts[1] += u64::from(stale);
|
||||
+ self.probe_counts[2] += u64::from(duplicate);
|
||||
+ self.probe_counts[3] += u64::from(short);
|
||||
+ if stale || duplicate || (!self.probe_no_half && short) { return None; }
|
||||
+ self.probe_counts[4] += 1;
|
||||
self.last_target = Some(target);
|
||||
Some(target)
|
||||
}
|
||||
@@ -110,6 +120,12 @@ impl DisplayLink {
|
||||
|
||||
pub(crate) fn stop(&mut self) {
|
||||
if self.running { self.link.stop(); self.running = false; }
|
||||
+ if self.probe_counts[4] > 0 {
|
||||
+ eprintln!("steady guard mode={} empty={} stale={} duplicate={} short={} admitted={}",
|
||||
+ if self.probe_no_half { "no-half" } else { "production" }, self.probe_counts[0], self.probe_counts[1],
|
||||
+ self.probe_counts[2], self.probe_counts[3], self.probe_counts[4]);
|
||||
+ self.probe_counts = [0; 5];
|
||||
+ }
|
||||
self.callback.target.store(0, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// Diagnostic adapter only: keep Rune's admission/render path unchanged while swapping
|
||||
// its CV callback source for an NSView CADisplayLink. Not linked into shipping Rune.
|
||||
#import <AppKit/AppKit.h>
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
#import <CoreVideo/CoreVideo.h>
|
||||
|
||||
@interface RuneClockProbe : NSObject
|
||||
@property(nonatomic) CVDisplayLinkRef cv;
|
||||
@property(nonatomic) CVDisplayLinkOutputCallback callback;
|
||||
@property(nonatomic) void *context;
|
||||
@property(nonatomic, strong) CADisplayLink *ca;
|
||||
@property(nonatomic) unsigned count;
|
||||
@property(nonatomic) double first;
|
||||
@property(nonatomic) double last;
|
||||
@end
|
||||
@implementation RuneClockProbe
|
||||
- (void)tick:(CADisplayLink *)link {
|
||||
double now = CACurrentMediaTime();
|
||||
CVTimeStamp at = {0}, target = {0};
|
||||
at.hostTime = CVGetCurrentHostTime();
|
||||
target.hostTime = at.hostTime + (int64_t)((link.targetTimestamp - now) * CVGetHostClockFrequency());
|
||||
target.videoTimeScale = 1000000000;
|
||||
target.videoRefreshPeriod = (int64_t)((link.targetTimestamp - link.timestamp) * 1e9);
|
||||
target.flags = kCVTimeStampHostTimeValid | kCVTimeStampVideoRefreshPeriodValid;
|
||||
CVOptionFlags flags = 0;
|
||||
if (!self.count++) self.first = now;
|
||||
self.last = now;
|
||||
self.callback(self.cv, &at, &target, 0, &flags, self.context);
|
||||
}
|
||||
@end
|
||||
|
||||
static NSMutableDictionary<NSValue *, RuneClockProbe *> *clocks;
|
||||
static CVReturn counted(CVDisplayLinkRef link, const CVTimeStamp *now, const CVTimeStamp *target,
|
||||
CVOptionFlags in, CVOptionFlags *out, void *context) {
|
||||
RuneClockProbe *probe = (__bridge RuneClockProbe *)context;
|
||||
double at = CACurrentMediaTime();
|
||||
if (!probe.count++) probe.first = at;
|
||||
probe.last = at;
|
||||
return probe.callback(link, now, target, in, out, probe.context);
|
||||
}
|
||||
static CVReturn probeSet(CVDisplayLinkRef link, CVDisplayLinkOutputCallback callback, void *context) {
|
||||
if (!getenv("STEADY_CLOCK")) return CVDisplayLinkSetOutputCallback(link, callback, context);
|
||||
if (!clocks) clocks = [NSMutableDictionary new];
|
||||
RuneClockProbe *probe = [RuneClockProbe new];
|
||||
probe.cv = link; probe.callback = callback; probe.context = context;
|
||||
clocks[[NSValue valueWithPointer:link]] = probe;
|
||||
return CVDisplayLinkSetOutputCallback(link, counted, (__bridge void *)probe);
|
||||
}
|
||||
static CVReturn probeStart(CVDisplayLinkRef link) {
|
||||
RuneClockProbe *probe = clocks[[NSValue valueWithPointer:link]];
|
||||
if (!getenv("STEADY_CA") || !probe) return CVDisplayLinkStart(link);
|
||||
if (@available(macOS 14.0, *)) {
|
||||
NSView *view = nil;
|
||||
for (NSWindow *window in NSApp.windows)
|
||||
if ([window isKindOfClass:NSPanel.class] && window.visible) { view = window.contentView; break; }
|
||||
if (!view) return kCVReturnError;
|
||||
probe.ca = [view displayLinkWithTarget:probe selector:@selector(tick:)];
|
||||
probe.ca.preferredFrameRateRange = CAFrameRateRangeMake(80, 120, 120);
|
||||
[probe.ca addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];
|
||||
return kCVReturnSuccess;
|
||||
}
|
||||
return kCVReturnError;
|
||||
}
|
||||
static CVReturn probeStop(CVDisplayLinkRef link) {
|
||||
RuneClockProbe *probe = clocks[[NSValue valueWithPointer:link]];
|
||||
CVReturn status = kCVReturnSuccess;
|
||||
if (probe.ca) { [probe.ca invalidate]; probe.ca = nil; }
|
||||
else status = CVDisplayLinkStop(link);
|
||||
if (probe.count > 1) fprintf(stderr, "steady clock source=%s callbacks=%u hz=%.3f\n",
|
||||
getenv("STEADY_CA") ? "ca" : "cv", probe.count, (probe.count - 1) / (probe.last - probe.first));
|
||||
probe.count = 0;
|
||||
return status;
|
||||
}
|
||||
#define INTERPOSE(new, old) __attribute__((used)) static struct { const void *replacement; const void *original; } \
|
||||
interpose_##old __attribute__((section("__DATA,__interpose"))) = { (const void *)&new, (const void *)&old }
|
||||
INTERPOSE(probeSet, CVDisplayLinkSetOutputCallback);
|
||||
INTERPOSE(probeStart, CVDisplayLinkStart);
|
||||
INTERPOSE(probeStop, CVDisplayLinkStop);
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Pro-only, no capture. Post-commit cadence of the `pacing` example under /tmp/pro-gui.lock.
|
||||
|
||||
python3 scripts/native-pacing/commit-probe.py <out> <pacing executable> [runs]
|
||||
|
||||
Each burst starts after an idle gap. Prints the first acquisition (`nextDrawable` entry) and
|
||||
positive Metal presentedTime intervals of each burst, plus totals over all bursts.
|
||||
"""
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from perf_binary import perf_binary
|
||||
|
||||
assert socket.gethostname().startswith("Kits-Shiny-Computer"), "Pro only"
|
||||
out, pacing = Path(sys.argv[1]).resolve(), perf_binary(sys.argv[2])
|
||||
runs = int(sys.argv[3]) if len(sys.argv) > 3 else 3
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
library = out / "steady-probe.dylib"
|
||||
subprocess.run(["clang", "-dynamiclib", "-fobjc-arc", "-fblocks", "-O2", str(Path(__file__).with_name("steady-probe.m")),
|
||||
"-framework", "AppKit", "-framework", "QuartzCore", "-framework", "Metal", "-o", str(library)], check=True)
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("STEADY_")}
|
||||
env["DYLD_INSERT_LIBRARIES"] = str(library)
|
||||
|
||||
|
||||
def gaps(times):
|
||||
return [round((b - a) * 1000, 1) for a, b in zip(times, times[1:])]
|
||||
|
||||
|
||||
summary = []
|
||||
with open("/tmp/pro-gui.lock", "a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
try:
|
||||
for run in range(runs):
|
||||
log = out / f"{run}-pacing.log"
|
||||
trace = out / f"{run}-pacing.jsonl"
|
||||
with log.open("w") as output:
|
||||
subprocess.run([str(pacing), "--native", "--trace", str(trace)], env=env, stdout=output,
|
||||
stderr=subprocess.STDOUT, timeout=60, check=True)
|
||||
rows = [{k: float(v) for k, v in re.findall(r"(\w+)=([\d.]+)", line)}
|
||||
for line in log.read_text().splitlines() if line.startswith("steady frame ")]
|
||||
rows.sort(key=lambda r: r["entered"])
|
||||
bursts, current = [], []
|
||||
for row in rows:
|
||||
if current and row["entered"] - current[-1]["entered"] > 0.05:
|
||||
bursts.append(current)
|
||||
current = []
|
||||
current.append(row)
|
||||
bursts.append(current)
|
||||
for index, burst in enumerate(bursts[1:], 1):
|
||||
presented = sorted(r["presented"] for r in burst if r["presented"] > 0)
|
||||
result = dict(run=run, burst=index, frames=len(burst), zero=sum(r["presented"] == 0 for r in burst),
|
||||
acquisition_gaps_ms=gaps([r["entered"] for r in burst]),
|
||||
presentation_gaps_ms=gaps(presented),
|
||||
latency_ms=round(statistics.median((r["presented"] - r["entered"]) * 1000
|
||||
for r in burst if r["presented"] > 0), 1),
|
||||
wait_ms=round(statistics.median((r["acquired"] - r["entered"]) * 1000 for r in burst), 2))
|
||||
summary.append(result)
|
||||
print(json.dumps(result), flush=True)
|
||||
finally:
|
||||
library.unlink(missing_ok=True)
|
||||
acquisition = [g for r in summary for g in r["acquisition_gaps_ms"]]
|
||||
presentation = [g for r in summary for g in r["presentation_gaps_ms"]]
|
||||
first = [g for r in summary for g in r["acquisition_gaps_ms"][:4]]
|
||||
total = dict(bursts=len(summary), frames=sum(r["frames"] for r in summary),
|
||||
median_acquisition_ms=statistics.median(acquisition), median_presentation_ms=statistics.median(presentation),
|
||||
first_four_acquisition_gaps_under_12ms=sum(g < 12 for g in first), first_four_acquisition_gaps=len(first),
|
||||
presentation_gaps_under_12ms=sum(g < 12 for g in presentation),
|
||||
median_latency_ms=statistics.median(r["latency_ms"] for r in summary))
|
||||
(out / "summary.json").write_text(json.dumps(dict(total=total, bursts=summary), indent=2) + "\n")
|
||||
print(json.dumps(total), flush=True)
|
||||
@@ -0,0 +1,150 @@
|
||||
// Minimal native CAMetalLayer presenter, independent of Rune and wgpu. Prints the display's
|
||||
// power and refresh state, then measures positive presentedTime cadence and the screen's
|
||||
// framebuffer-update cadence for one presentation variant.
|
||||
// refresh-probe <present|transaction|minduration|unsynced> <sub|backing> <drawables> <seconds>
|
||||
#import <AppKit/AppKit.h>
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
#import <Metal/Metal.h>
|
||||
#import <CoreVideo/CoreVideo.h>
|
||||
|
||||
static NSString *mode, *host;
|
||||
static int drawables;
|
||||
static double seconds;
|
||||
static CAMetalLayer *layer;
|
||||
static id<MTLCommandQueue> queue;
|
||||
static NSMutableArray<NSNumber *> *presented, *updates, *callbacks;
|
||||
static double started;
|
||||
static NSScreen *screen;
|
||||
|
||||
static void summary(NSString *name, NSArray<NSNumber *> *times) {
|
||||
NSArray<NSNumber *> *sorted = [times sortedArrayUsingSelector:@selector(compare:)];
|
||||
NSMutableDictionary<NSNumber *, NSNumber *> *ticks = [NSMutableDictionary dictionary];
|
||||
double first = 0, last = 0;
|
||||
for (NSUInteger i = 1; i < sorted.count; i++) {
|
||||
double gap = (sorted[i].doubleValue - sorted[i - 1].doubleValue) * 1000;
|
||||
NSNumber *key = @(lround(gap / (1000.0 / 120)));
|
||||
ticks[key] = @(ticks[key].intValue + 1);
|
||||
}
|
||||
if (sorted.count > 1) { first = sorted.firstObject.doubleValue; last = sorted.lastObject.doubleValue; }
|
||||
NSMutableString *histogram = [NSMutableString string];
|
||||
for (NSNumber *key in [ticks.allKeys sortedArrayUsingSelector:@selector(compare:)])
|
||||
[histogram appendFormat:@" %@t:%@", key, ticks[key]];
|
||||
printf("probe %s n=%lu hz=%.2f gaps_in_120hz_ticks=%s\n", name.UTF8String, (unsigned long)sorted.count,
|
||||
sorted.count > 1 ? (sorted.count - 1) / (last - first) : 0, histogram.UTF8String);
|
||||
}
|
||||
|
||||
@interface Target : NSObject
|
||||
@end
|
||||
@implementation Target
|
||||
- (void)tick:(CADisplayLink *)link {
|
||||
double now = CACurrentMediaTime();
|
||||
if (now - started > seconds) {
|
||||
[link invalidate];
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 2), dispatch_get_main_queue(), ^{
|
||||
printf("probe variant mode=%s host=%s drawables=%d presents_with_transaction=%d display_sync=%d opaque=%d format=%lu\n",
|
||||
mode.UTF8String, host.UTF8String, drawables, layer.presentsWithTransaction,
|
||||
layer.displaySyncEnabled, layer.opaque, (unsigned long)layer.pixelFormat);
|
||||
summary(@"callbacks", callbacks);
|
||||
summary(@"positive_presentations", presented);
|
||||
summary(@"screen_updates", updates);
|
||||
exit(0);
|
||||
});
|
||||
return;
|
||||
}
|
||||
[callbacks addObject:@(now)];
|
||||
if (@available(macOS 12.0, *)) {
|
||||
NSNumber *update = @(screen.lastDisplayUpdateTimestamp);
|
||||
if (update.doubleValue > 0 && ![updates.lastObject isEqual:update]) [updates addObject:update];
|
||||
}
|
||||
id<CAMetalDrawable> drawable = [layer nextDrawable];
|
||||
if (!drawable) return;
|
||||
BOOL measured = now - started > 1;
|
||||
[drawable addPresentedHandler:^(id<MTLDrawable> d) {
|
||||
if (measured && d.presentedTime > 0) dispatch_async(dispatch_get_main_queue(), ^{ [presented addObject:@(d.presentedTime)]; });
|
||||
}];
|
||||
MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor];
|
||||
pass.colorAttachments[0].texture = drawable.texture;
|
||||
pass.colorAttachments[0].loadAction = MTLLoadActionClear;
|
||||
pass.colorAttachments[0].storeAction = MTLStoreActionStore;
|
||||
double phase = fmod(now, 1.0);
|
||||
pass.colorAttachments[0].clearColor = MTLClearColorMake(0.1 * phase, 0.3 * phase, 0.6 * phase, 0.6 + 0.3 * phase);
|
||||
id<MTLCommandBuffer> buffer = [queue commandBuffer];
|
||||
[[buffer renderCommandEncoderWithDescriptor:pass] endEncoding];
|
||||
if ([mode isEqual:@"transaction"]) {
|
||||
[buffer commit];
|
||||
[buffer waitUntilScheduled];
|
||||
[drawable present];
|
||||
} else {
|
||||
if ([mode isEqual:@"minduration"]) [buffer presentDrawable:drawable afterMinimumDuration:1.0 / 120];
|
||||
else [buffer presentDrawable:drawable];
|
||||
[buffer commit];
|
||||
}
|
||||
}
|
||||
@end
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
@autoreleasepool {
|
||||
mode = argc > 1 ? @(argv[1]) : @"present";
|
||||
host = argc > 2 ? @(argv[2]) : @"sub";
|
||||
drawables = argc > 3 ? atoi(argv[3]) : 3;
|
||||
seconds = argc > 4 ? atof(argv[4]) : 5;
|
||||
[NSApplication sharedApplication];
|
||||
NSApp.activationPolicy = NSApplicationActivationPolicyAccessory;
|
||||
screen = NSScreen.mainScreen;
|
||||
CGDirectDisplayID display = [screen.deviceDescription[@"NSScreenNumber"] unsignedIntValue];
|
||||
CGDisplayModeRef displayMode = CGDisplayCopyDisplayMode(display);
|
||||
CVDisplayLinkRef cv;
|
||||
CVDisplayLinkCreateWithCGDisplay(display, &cv);
|
||||
CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(cv);
|
||||
printf("probe system low_power=%d thermal=%ld max_fps=%ld min_interval_ms=%.3f max_interval_ms=%.3f granularity_ms=%.3f mode_hz=%.2f cv_nominal_ms=%.3f builtin=%d asleep=%d\n",
|
||||
NSProcessInfo.processInfo.isLowPowerModeEnabled, (long)NSProcessInfo.processInfo.thermalState,
|
||||
(long)screen.maximumFramesPerSecond, screen.minimumRefreshInterval * 1000, screen.maximumRefreshInterval * 1000,
|
||||
screen.displayUpdateGranularity * 1000, CGDisplayModeGetRefreshRate(displayMode),
|
||||
nominal.timeScale ? 1000.0 * nominal.timeValue / nominal.timeScale : 0, CGDisplayIsBuiltin(display),
|
||||
CGDisplayIsAsleep(display));
|
||||
CGDisplayModeRelease(displayMode);
|
||||
CVDisplayLinkRelease(cv);
|
||||
|
||||
NSRect frame = NSMakeRect(NSMidX(screen.frame) - 340, NSMaxY(screen.visibleFrame) - 200, 680, 160);
|
||||
NSPanel *panel = [[NSPanel alloc] initWithContentRect:frame
|
||||
styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel backing:NSBackingStoreBuffered defer:NO];
|
||||
panel.opaque = NO;
|
||||
panel.backgroundColor = NSColor.clearColor;
|
||||
panel.level = NSStatusWindowLevel;
|
||||
panel.hasShadow = NO;
|
||||
panel.ignoresMouseEvents = YES;
|
||||
NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 680, 160)];
|
||||
layer = [CAMetalLayer layer];
|
||||
layer.device = MTLCreateSystemDefaultDevice();
|
||||
layer.pixelFormat = MTLPixelFormatBGRA8Unorm_sRGB;
|
||||
layer.opaque = NO;
|
||||
layer.maximumDrawableCount = drawables;
|
||||
layer.displaySyncEnabled = ![mode isEqual:@"unsynced"];
|
||||
layer.presentsWithTransaction = [mode isEqual:@"transaction"];
|
||||
layer.contentsScale = screen.backingScaleFactor;
|
||||
layer.drawableSize = CGSizeMake(680 * screen.backingScaleFactor, 160 * screen.backingScaleFactor);
|
||||
if ([host isEqual:@"backing"]) {
|
||||
view.layer = layer;
|
||||
view.wantsLayer = YES;
|
||||
} else {
|
||||
view.wantsLayer = YES;
|
||||
layer.frame = view.layer.bounds;
|
||||
[view.layer addSublayer:layer];
|
||||
}
|
||||
panel.contentView = view;
|
||||
[panel orderFrontRegardless];
|
||||
queue = [layer.device newCommandQueue];
|
||||
presented = [NSMutableArray array];
|
||||
updates = [NSMutableArray array];
|
||||
callbacks = [NSMutableArray array];
|
||||
started = CACurrentMediaTime();
|
||||
CADisplayLink *link = [view displayLinkWithTarget:[Target new] selector:@selector(tick:)];
|
||||
link.preferredFrameRateRange = CAFrameRateRangeMake(80, 120, 120);
|
||||
[link addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((seconds + 5) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
fprintf(stderr, "probe timeout\n");
|
||||
exit(2);
|
||||
});
|
||||
[NSApp run];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Pro-only, no capture. Runs refresh-probe.m variants under /tmp/pro-gui.lock.
|
||||
|
||||
python3 scripts/native-pacing/refresh-probe.py <out> [mode:host:drawables ...]
|
||||
"""
|
||||
import fcntl
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
assert socket.gethostname().startswith("Kits-Shiny-Computer"), "Pro only"
|
||||
out = Path(sys.argv[1]).resolve()
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
variants = sys.argv[2:] or ["present:sub:3", "transaction:backing:3", "minduration:sub:3", "present:sub:2", "unsynced:sub:3"]
|
||||
binary = out / "refresh-probe"
|
||||
subprocess.run(["clang", "-fobjc-arc", "-O2", str(Path(__file__).with_name("refresh-probe.m")),
|
||||
"-framework", "AppKit", "-framework", "QuartzCore", "-framework", "Metal",
|
||||
"-framework", "CoreVideo", "-Wno-deprecated-declarations", "-o", str(binary)], check=True)
|
||||
with open("/tmp/pro-gui.lock", "a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
for variant in variants:
|
||||
mode, host, drawables = variant.split(":")
|
||||
result = subprocess.run([str(binary), mode, host, drawables, "5"], capture_output=True, text=True, timeout=30)
|
||||
text = result.stdout + result.stderr
|
||||
(out / f"{mode}-{host}-{drawables}.log").write_text(text)
|
||||
print(text, flush=True)
|
||||
binary.unlink(missing_ok=True)
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
"""Pro-only, no capture. Same 3 batches x 3 intervals and endpoint as the overlay team's probe.
|
||||
|
||||
Run through hash-checked GUI admission on the build queue. A matched 1360x320 Rune surface is
|
||||
tested with both injected 60 Hz redraws and its real continuous animation scheduler.
|
||||
"""
|
||||
import argparse
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import socket
|
||||
import signal
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from perf_binary import perf_binary
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("out", type=Path)
|
||||
parser.add_argument("rune", type=Path)
|
||||
parser.add_argument("--reference", type=Path)
|
||||
parser.add_argument("--modes", default="injected,native")
|
||||
parser.add_argument("--display-link", choices=["cv", "ca"], default="cv")
|
||||
parser.add_argument("--drawables", choices=["2", "3"])
|
||||
parser.add_argument("--display-sync", choices=["0", "1"])
|
||||
parser.add_argument("--guard", choices=["production", "no-half"], help="requires the diagnostic admission patch")
|
||||
args = parser.parse_args()
|
||||
assert socket.gethostname().startswith("Kits-Shiny-Computer"), "Pro only"
|
||||
root, rune = args.out.resolve(), perf_binary(args.rune)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def stats(values):
|
||||
if not values:
|
||||
return None
|
||||
return dict(n=len(values), median=statistics.median(values),
|
||||
p95=sorted(values)[math.ceil(len(values) * .95) - 1], min=min(values), max=max(values))
|
||||
|
||||
|
||||
def parse(path, mode):
|
||||
rows, configs, clocks, guards = [], [], [], []
|
||||
for line in path.read_text().splitlines():
|
||||
if line.startswith("steady config "):
|
||||
configs.append(line)
|
||||
if line.startswith("steady clock "):
|
||||
clocks.append(line)
|
||||
if line.startswith("steady guard "):
|
||||
guards.append(line)
|
||||
if line.startswith("steady frame "):
|
||||
rows.append({k: float(v) for k, v in re.findall(r"(\w+)=([\d.]+)", line)})
|
||||
visible = [r for r in rows if r["visible"] and r["window"] > 0]
|
||||
assert visible, f"no visible frames: {path}"
|
||||
start = min(r["entered"] for r in visible) + 2
|
||||
selected = [r for r in visible if start <= r["entered"] < start + 9]
|
||||
valid = [r for r in selected if r["presented"] >= r["acquired"]]
|
||||
assert len(valid) >= 30, f"too few valid presentations: {path}"
|
||||
intervals = [stats([(r["presented"] - r["entered"]) * 1000 for r in valid
|
||||
if start + i * 3 <= r["entered"] < start + (i + 1) * 3]) for i in range(3)]
|
||||
requests = [r for r in valid if 0 < r["requested"] <= r["entered"]]
|
||||
entries = sorted(r["entered"] for r in selected)
|
||||
gaps = [(b - a) * 1000 for a, b in zip(entries, entries[1:])]
|
||||
presented = sorted(set(r["presented"] for r in valid))
|
||||
presentation_gaps = [(b - a) * 1000 for a, b in zip(presented, presented[1:])]
|
||||
if args.guard and mode != "reference":
|
||||
assert guards and all(f"mode={args.guard} " in line for line in guards), "wrong admission-probe binary"
|
||||
return dict(configs=configs, clocks=clocks, guards=guards, positive=len(valid), visible_callbacks=len(selected),
|
||||
acquisition_hz=(len(entries)-1)/(entries[-1]-entries[0]),
|
||||
presentation_hz=(len(presented)-1)/(presented[-1]-presented[0]),
|
||||
presentation_gaps_ms=stats(presentation_gaps),
|
||||
zero_callbacks=sum(r["presented"] == 0 for r in selected),
|
||||
acquire_to_present_ms=stats([(r["presented"] - r["entered"]) * 1000 for r in valid]),
|
||||
next_drawable_wait_ms=stats([(r["acquired"] - r["entered"]) * 1000 for r in valid]),
|
||||
request_to_present_ms=stats([(r["presented"] - r["requested"]) * 1000 for r in requests]),
|
||||
acquisition_gaps_ms=stats(gaps), sub_half_refresh_gaps=sum(g < 4.166666 - .01 for g in gaps),
|
||||
interval_medians=intervals)
|
||||
|
||||
|
||||
with open("/tmp/pro-gui.lock", "a") as lock:
|
||||
def lock_timeout(_signal, _frame):
|
||||
raise TimeoutError("Pro GUI lock remained busy for ten minutes")
|
||||
signal.signal(signal.SIGALRM, lock_timeout)
|
||||
signal.alarm(600)
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
signal.alarm(0)
|
||||
for pattern in ["[r]une-smoke/ci/Hex.app", "[s]crawl lab"]:
|
||||
assert subprocess.run(["pgrep", "-f", pattern], capture_output=True).returncode != 0, pattern
|
||||
for name in ["overlay-lab", "pacing_overlay"]:
|
||||
assert subprocess.run(["pgrep", "-x", name], capture_output=True).returncode != 0, name
|
||||
library = root / "steady-probe.dylib"
|
||||
subprocess.run(["clang", "-dynamiclib", "-fobjc-arc", "-fblocks", "-O2",
|
||||
str(Path(__file__).with_name("steady-probe.m")), str(Path(__file__).with_name("clock-probe.m")),
|
||||
"-Wno-deprecated-declarations", "-framework", "AppKit", "-framework", "CoreVideo",
|
||||
"-framework", "QuartzCore", "-framework", "Metal", "-o", str(library)], check=True)
|
||||
env = dict(os.environ, DYLD_INSERT_LIBRARIES=str(library))
|
||||
for key in ["OVERLAY_LAB_CONTROL", "OVERLAY_PROBE_REDRAW", "RUNE_OVERLAY_TRACE_INPUT",
|
||||
"STEADY_RUNE_REDRAW", "STEADY_MAX_DRAWABLES", "STEADY_TRANSACTION", "PACING_NATIVE",
|
||||
"STEADY_CA", "STEADY_CLOCK", "STEADY_DISPLAY_SYNC", "STEADY_GUARD"]:
|
||||
env.pop(key, None)
|
||||
modes = args.modes.split(",") + (["reference"] if args.reference else [])
|
||||
assert all(mode in ["injected", "native", "reference"] for mode in modes)
|
||||
results = []
|
||||
(root / "load-before.txt").write_bytes(subprocess.check_output(["top", "-l", "1", "-n", "0"]))
|
||||
try:
|
||||
for batch in range(3):
|
||||
for mode in (modes if batch % 2 == 0 else list(reversed(modes))):
|
||||
command = [str(rune)] if mode != "reference" else [str(args.reference.resolve()), "lab", "pill",
|
||||
"tap-then-screen", "--repeat", "0", "--time-scale", "1", "--no-backdrop"]
|
||||
runenv = dict(env)
|
||||
if mode != "reference":
|
||||
runenv["STEADY_CLOCK"] = "1"
|
||||
if args.display_link == "ca": runenv["STEADY_CA"] = "1"
|
||||
if args.drawables: runenv["STEADY_MAX_DRAWABLES"] = args.drawables
|
||||
if args.display_sync: runenv["STEADY_DISPLAY_SYNC"] = args.display_sync
|
||||
if args.guard: runenv["STEADY_GUARD"] = args.guard
|
||||
if mode == "injected":
|
||||
runenv["STEADY_RUNE_REDRAW"] = "1"
|
||||
elif mode == "native":
|
||||
runenv["PACING_NATIVE"] = "1"
|
||||
log = root / f"{batch}-{mode}.log"
|
||||
with log.open("w") as output:
|
||||
process = subprocess.Popen(command, env=runenv, stdout=output, stderr=subprocess.STDOUT)
|
||||
try:
|
||||
process.wait(timeout=14 if mode == "reference" else 22)
|
||||
assert mode != "reference" and process.returncode == 0, (mode, process.returncode)
|
||||
except subprocess.TimeoutExpired:
|
||||
if mode != "reference":
|
||||
subprocess.run(["sample", str(process.pid), "1", "-file", str(root / f"{batch}-{mode}-timeout.txt")], timeout=10)
|
||||
raise
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
result = dict(batch=batch, mode=mode, **parse(log, mode))
|
||||
results.append(result)
|
||||
print(json.dumps(result), flush=True)
|
||||
summary = dict(endpoint="nextDrawable entry to positive Metal presentedTime",
|
||||
rune_sha256=hashlib.sha256(rune.read_bytes()).hexdigest(), runs=results,
|
||||
experiment=dict(display_link=args.display_link, drawables=args.drawables,
|
||||
display_sync=args.display_sync, guard=args.guard))
|
||||
if args.reference:
|
||||
summary["reference_sha256"] = hashlib.sha256(args.reference.read_bytes()).hexdigest()
|
||||
for mode in modes:
|
||||
medians = [interval["median"] for r in results if r["mode"] == mode
|
||||
for interval in r["interval_medians"] if interval]
|
||||
assert len(medians) == 9, (mode, medians)
|
||||
summary[mode] = stats(medians)
|
||||
(root / "results.json").write_text(json.dumps(summary, indent=2) + "\n")
|
||||
print(json.dumps({k: v for k, v in summary.items() if k != "runs"}), flush=True)
|
||||
finally:
|
||||
library.unlink(missing_ok=True)
|
||||
(root / "load-after.txt").write_bytes(subprocess.check_output(["top", "-l", "1", "-n", "0"]))
|
||||
print("All disposable apps exited; GUI lock released.", flush=True)
|
||||
@@ -0,0 +1,64 @@
|
||||
// Same nextDrawable -> positive presentedTime endpoint as overlays/steady-state/steady-probe.m.
|
||||
#import <AppKit/AppKit.h>
|
||||
#import <QuartzCore/CAMetalLayer.h>
|
||||
#import <Metal/Metal.h>
|
||||
#import <objc/runtime.h>
|
||||
|
||||
static id<CAMetalDrawable> (*originalNext)(id, SEL);
|
||||
static char requestKey, configKey;
|
||||
static dispatch_source_t timer;
|
||||
|
||||
static NSWindow *ownerOf(CALayer *layer) {
|
||||
for (NSWindow *window in NSApp.windows) {
|
||||
CALayer *root = window.contentView.layer;
|
||||
for (CALayer *p = layer; p; p = p.superlayer)
|
||||
if (p == root) return window.contentView.window;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
static id<CAMetalDrawable> nextDrawable(CAMetalLayer *layer, SEL selector) {
|
||||
if (getenv("STEADY_MAX_DRAWABLES")) layer.maximumDrawableCount = atoi(getenv("STEADY_MAX_DRAWABLES"));
|
||||
if (getenv("STEADY_DISPLAY_SYNC")) layer.displaySyncEnabled = atoi(getenv("STEADY_DISPLAY_SYNC"));
|
||||
double entered = CACurrentMediaTime();
|
||||
id<CAMetalDrawable> drawable = originalNext(layer, selector);
|
||||
double acquired = CACurrentMediaTime();
|
||||
if (!drawable) return drawable;
|
||||
NSWindow *owner = ownerOf(layer);
|
||||
NSInteger windowID = owner.windowNumber;
|
||||
BOOL visible = owner.visible && owner.alphaValue > 0;
|
||||
NSNumber *request = objc_getAssociatedObject(owner, &requestKey);
|
||||
double requested = request.doubleValue;
|
||||
if (owner) objc_setAssociatedObject(owner, &requestKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
if (!objc_getAssociatedObject(layer, &configKey)) {
|
||||
objc_setAssociatedObject(layer, &configKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
fprintf(stderr, "steady config window=%ld max_drawables=%lu transaction=%d display_sync=%d width=%.0f height=%.0f screen_hz=%ld\n",
|
||||
(long)windowID, (unsigned long)layer.maximumDrawableCount, layer.presentsWithTransaction,
|
||||
layer.displaySyncEnabled, layer.drawableSize.width, layer.drawableSize.height,
|
||||
(long)owner.screen.maximumFramesPerSecond);
|
||||
}
|
||||
[drawable addPresentedHandler:^(id<MTLDrawable> d) {
|
||||
fprintf(stderr, "steady frame window=%ld visible=%d requested=%.9f entered=%.9f acquired=%.9f presented=%.9f callback=%.9f\n",
|
||||
(long)windowID, visible, requested, entered, acquired, d.presentedTime, CACurrentMediaTime());
|
||||
}];
|
||||
return drawable;
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void install(void) {
|
||||
Method method = class_getInstanceMethod(CAMetalLayer.class, @selector(nextDrawable));
|
||||
originalNext = (void *)method_setImplementation(method, (IMP)nextDrawable);
|
||||
if (!getenv("STEADY_RUNE_REDRAW")) return;
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
|
||||
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), NSEC_PER_SEC / 60, 0);
|
||||
dispatch_source_set_event_handler(timer, ^{
|
||||
for (NSWindow *window in NSApp.windows) {
|
||||
if (![window isKindOfClass:NSPanel.class] || !window.visible || window.alphaValue <= 0) continue;
|
||||
if (!objc_getAssociatedObject(window, &requestKey))
|
||||
objc_setAssociatedObject(window, &requestKey, @(CACurrentMediaTime()), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
window.contentView.needsDisplay = YES;
|
||||
}
|
||||
});
|
||||
dispatch_resume(timer);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user