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:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
[package]
name = "video-tiles"
version = "0.0.1"
edition.workspace = true
license.workspace = true
[dependencies]
rune = { workspace = true, default-features = true, features = ["keys-overlay"] }
wgpu = { workspace = true, features = ["std", "wgsl"] }
serde_json = { workspace = true }
[lints]
workspace = true
+121
View File
@@ -0,0 +1,121 @@
# Video tiles
Four Rune nodes fed by a background producer. macOS creates synthetic NV12 IOSurfaces;
other platforms use the same shader with uploaded byte planes. `--snap` freezes frame 0.
```sh
cargo build --release -p video-tiles
target/release/video-tiles --snap tiles.png --scale 2
cargo build --profile perf -p video-tiles
target/perf/video-tiles --bench-native
```
`--bench-native` is headless: 1/4/9 independent 1080p tiles, then one 4K and one 5K
surface, all at 1:1 device-pixel scale. It uses three prefilled IOSurfaces per tile,
pushes fresh frame IDs at 60 Hz, excludes generation/readback from timing, and emits
seven measured runs after one warmup. CPU includes push/import/encode/submit; GPU is
GPU render-pass timestamp duration. A 16-byte timing readback follows each pass; no pixel
readback is timed. No window, physical display, decoder, or network is measured.
## App integration
```rust,ignore
let surface = rune::NativeSurface::new(); // keep in app state; clones share a bounded slot
surface.set_waker(waker); // from AppSpec::setup
surface.set_observer(Arc::new(|timing| {
// First notification: frame_id + submitted_at (std::time::Instant).
// Second: completed_at plus optional GPU render-pass timestamp seconds.
// Callbacks can arrive on Rune's completion worker. Keep them short.
}));
// VideoToolbox callback, after decoding has completed:
let pixel_buffer = unsafe {
rune::native_surface::macos::PixelBuffer::from_raw(cv_pixel_buffer.cast())?
}; // retains the borrowed CVPixelBufferRef
surface.push(pixel_buffer, frame_id)?;
// In the ordinary Rune view; dimensions are points (960x540 at 2x is 1920x1080):
el().w(960.0).h(540.0).radius(12.0)
.native_surface(&surface, rune::SurfaceFit::Fit)
```
The buffer's pixels and attachments must remain immutable until all Rune/GPU ownership
ends. Request IOSurface-backed, Metal-compatible output from VideoToolbox. There is no
CPU pixel lock, copy, or upload in the import path. `push` is thread-safe and replaces
the pending frame; only the newest is imported at render preparation. Repeated rendering
of the same source is cached. `clear()` removes the frame and wakes the app.
Import failures (e.g. a non-IOSurface pixel buffer) appear in `surface.last_error()`;
unsupported formats/colour metadata are rejected by `push`. On non-macOS, `push_bytes`
accepts packed BGRA or two packed NV12 planes. The native `PixelBuffer` API is macOS-only.
## Camera preview
Ask `AVCaptureVideoDataOutput` for IOSurface-backed, Metal-compatible BGRA or `420v`
buffers (`kCVPixelBufferMetalCompatibilityKey`), and `push` each one from its sample-buffer
delegate. Then:
```rust,ignore
surface.set_mirrored(front_camera); // draw-time flip; captured stills stay unmirrored
el().w(480.0).h(480.0).radius(24.0)
.native_surface(&surface, rune::SurfaceFit::Fill) // aspect-fill, centred crop
```
Mirroring flips about the image centre, so a Fill crop stays centred, and 1:1 pixels stay
exact. Changing it wakes the app and redraws the current frame. When the preview window
hides, stop the capture session and call `clear()`: a hidden window draws nothing, but
each `push` still wakes the app.
## Colour, sampling, ownership and timing
- BGRA, NV12 `420v` (16..235 luma / 16..240 chroma) and `420f` (full range).
- YCbCr BT.601/BT.709 matrix and sRGB/BT.709 transfer come from CoreVideo attachments.
Missing matrix defaults to BT.601 for <=576-line sources, BT.709 otherwise; missing
transfer defaults to BT.709 for NV12, sRGB for BGRA. Output is linear RGB into Rune's
sRGB target. Unsupported matrix/transfer metadata is an error. SDR only; wide-gamut
primary conversion, HDR, interlacing, clean-aperture cropping, rotation and explicit
chroma-siting metadata are not implemented. BGRA alpha is treated as straight alpha.
- Fit letterboxes; Fill crops. Matching pixel size snaps the image origin to device
pixels and uses `textureLoad`: no luma/BGRA interpolation at 1:1, including Retina.
NV12's native 2x2 chroma samples are preserved at 1:1. Other scales use bilinear
sampling with an area grid up to 8x8 taps for shrinking. Beyond 8x shrink this is
an approximation, not a full-resolution area integral. Rounded corners, inherited
rectangular soft clips, node opacity and painter order apply to the video.
- Each imported plane owns its `CVMetalTexture` **and** pixel buffer through a wgpu-hal
drop callback. wgpu retains these resources through in-flight submissions, even if
a new frame arrives, the node disappears, or an encoder is abandoned. Decoder pool
buffers cannot be recycled merely because the pending slot changed.
- `counts()` returns draw submissions/completions, not unique decoded frames; dropped
pending frames generate no submit notification. A source frame can be submitted more
than once. `timing()` holds the newest submission only; the observer receives both
events for every draw. `submitted_at` is sampled immediately before submit setup;
`completed_at` is when completion was observed, while `gpu_start_seconds/gpu_end_seconds`
come from hardware render-pass queries (the containing UI pass, when embedded in Rune).
Their difference is GPU duration; the GPU epoch is backend-specific. Do not subtract
them from `Instant`. Backends without timestamp queries still report completion.
An explicit query set passed to `Renderer::draw_timed` takes precedence; that draw's
NativeSurface notifications carry CPU submit/completion times only.
`Frame::draw_ui`, `Renderer::draw`, and `draw_range` interleave prepared video at its
`before_instance` position, including inside isolated groups. A custom compositor must
preserve those absolute insertion indices when concatenating or rearranging lists and
call `encode_layers` before opening its render pass. Prepared but undrawn video generates
no submission notification.
A coalesced completion worker uses nonblocking polls, sleeping between them, including
for the final frame at idle. It never holds wgpu's device lock while waiting on a GPU
fence. Counter resolution runs in a separate submission after render completion to
avoid stale Metal counter samples; the second notification follows its 16-byte readback.
Completion time is captured before that readback, but includes callback latency; it is not an exact Metal
command-buffer completion timestamp. wgpu 30 rejects `as_hal_mut` after normal render
encoding, so its raw completed-handler hook cannot be used here. A tested prototype
hit that validation error and was removed. No backend fork or untracked raw submission.
- True **presented-frame** timestamps require Rune's own Mac shell owning CAMetalLayer /
CAMetalDisplayLink (planned, not built). wgpu-hal 30 exposes the render layer and raw
command buffer but keeps the acquired drawable private. There is no cheap, supported
presented-handler hook to prototype without owning that shell. GPU-done is not present.
Verification: `cargo test -p rune-media native_surface -- --test-threads=1` (and `cargo test -p rune --lib -- native_surface:: --test-threads=1` for renderer interleaving).
The GPU test compares native IOSurface and byte-upload results with a scalar colour oracle,
checks exact one-pixel patterns, fitting/clipping, notifications, and released backing ownership.
The overlap test acquires the same exclusive device lock as presentation while GPU work
is still in flight, without creating a window.
+134
View File
@@ -0,0 +1,134 @@
//! No window/pixel readback. Import/encode/submit CPU and GPU render-pass timestamp duration.
use rune::native_surface::{NativeSurface, SurfaceDraw, SurfaceFit, SurfaceRenderer, synthetic};
use rune::render::{Gpu, OFFSCREEN_FORMAT};
use std::sync::{Arc, Mutex};
use std::time::Duration;
pub fn run() {
let gpu = Gpu::new(Gpu::instance(), None);
eprintln!("adapter={:?}", gpu.adapter.get_info());
for (tiles, w, h) in [(1, 1920, 1080), (4, 1920, 1080), (9, 1920, 1080), (1, 3840, 2160), (1, 5120, 2880)] {
let columns = (tiles as f32).sqrt() as u32;
let size = (w * columns, h * columns);
let target = gpu.device.create_texture(&wgpu::TextureDescriptor {
label: Some("video benchmark"),
size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: OFFSCREEN_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let view = target.create_view(&Default::default());
let mut renderer = SurfaceRenderer::new(&gpu.device, OFFSCREEN_FORMAT);
let timings = Arc::new(Mutex::new(Vec::new()));
let (completed, completion) = std::sync::mpsc::channel();
let surfaces: Vec<_> = (0..tiles).map(|_| NativeSurface::new()).collect();
let times = timings.clone();
surfaces[0].set_observer(Arc::new(move |t| {
if let (Some(a), Some(b)) = (t.gpu_start_seconds, t.gpu_end_seconds) {
times.lock().unwrap().push((b - a) * 1000.0);
}
if t.completed_at.is_some() {
completed.send(()).ok();
}
}));
let draws: Vec<_> = surfaces
.iter()
.enumerate()
.map(|(i, s)| SurfaceDraw {
surface: s.clone(),
fit: SurfaceFit::Fit,
before_instance: 0,
rect: [(i as u32 % columns * w) as f32, (i as u32 / columns * h) as f32, w as f32, h as f32],
radii: [0.0; 4],
clip: rune::render::NO_CLIP,
fade: [0; 4],
opacity: 1.0,
})
.collect();
// Three independent IOSurface buffers per tile model a decoder's recyclable output pool.
// Fill only before timing: production import never accesses pixels on CPU.
#[cfg(target_os = "macos")]
let buffers: Vec<Vec<_>> = (0..tiles)
.map(|_| {
(0..3)
.map(|i| rune::native_surface::macos::PixelBuffer::from_bytes(&synthetic(w, h, i)).unwrap())
.collect()
})
.collect();
let mut runs = Vec::new();
for run in 0..8 {
timings.lock().unwrap().clear();
let mut cpu = Vec::new();
for frame in 0..30 {
let begin = rune::time::now();
for (i, s) in surfaces.iter().enumerate() {
#[cfg(target_os = "macos")]
s.push(buffers[i][frame % 3].clone(), (run * 30 + frame) as u64).unwrap();
#[cfg(not(target_os = "macos"))]
{
let _ = i;
s.push_bytes(synthetic(w, h, frame as u64), (run * 30 + frame) as u64).unwrap();
}
}
renderer.prepare(&gpu.device, &gpu.queue, &draws, size);
let mut encoder = gpu.device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("video benchmark"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: renderer.timestamp_writes(),
occlusion_query_set: None,
multiview_mask: None,
});
for i in 0..renderer.len() {
renderer.draw(&mut pass, i);
}
}
renderer.submit(&gpu.queue, encoder);
cpu.push(begin.elapsed().as_secs_f64() * 1000.0);
completion.recv_timeout(Duration::from_secs(10)).expect("final frame completion without another draw");
// Pace actual submissions at 60 Hz; waiting is excluded from CPU cost.
if let Some(wait) = Duration::from_secs_f64(1.0 / 60.0).checked_sub(begin.elapsed()) {
std::thread::sleep(wait);
}
}
let gpu_ms = timings.lock().unwrap().clone();
if gpu.device.features().contains(wgpu::Features::TIMESTAMP_QUERY) {
assert_eq!(gpu_ms.len(), 30, "every submitted frame must have a valid GPU timestamp pair");
}
for s in &surfaces {
assert_eq!(s.last_error(), None);
}
if run > 0 {
runs.push(serde_json::json!({"cpu_p50_ms":median(&cpu),"cpu_p95_ms":percentile(&cpu,0.95),"gpu_samples":gpu_ms.len(),"gpu_p50_ms":median(&gpu_ms),"gpu_p95_ms":percentile(&gpu_ms,0.95)}));
}
}
let cpu: Vec<_> = runs.iter().map(|r| r["cpu_p50_ms"].as_f64().unwrap()).collect();
let gpu_ms: Vec<_> = runs.iter().filter_map(|r| r["gpu_p50_ms"].as_f64()).collect();
println!(
"{}",
serde_json::json!({"tiles":tiles,"source":[w,h],"target":[size.0,size.1],"hz":60,"warmup_runs":1,"runs":runs,
"cpu_median_ms":median(&cpu),"gpu_median_ms":median(&gpu_ms),"cpu_per_tile_ms":median(&cpu).map(|v|v/tiles as f64),"gpu_per_tile_ms":median(&gpu_ms).map(|v|v/tiles as f64)})
);
}
}
fn median(xs: &[f64]) -> Option<f64> {
percentile(xs, 0.5)
}
fn percentile(xs: &[f64], p: f64) -> Option<f64> {
let mut xs = xs.to_vec();
xs.sort_by(f64::total_cmp);
xs.get((xs.len() as f64 * p) as usize).copied()
}
+76
View File
@@ -0,0 +1,76 @@
//! Copy this producer/view boundary into a VideoToolbox application.
#![forbid(unsafe_code)]
use rune::native_surface::{ByteFrame, synthetic};
use rune::{AppSpec, Cx, El, NativeSurface, SurfaceFit, Waker, col, el, row};
use std::time::Duration;
mod bench;
fn push(surface: &NativeSurface, bytes: &ByteFrame, id: u64) {
#[cfg(target_os = "macos")]
surface.push(rune::native_surface::macos::PixelBuffer::from_bytes(bytes).unwrap(), id).unwrap();
#[cfg(not(target_os = "macos"))]
surface
.push_bytes(
ByteFrame {
width: bytes.width,
height: bytes.height,
format: bytes.format,
color: bytes.color,
planes: bytes.planes.clone(),
},
id,
)
.unwrap();
}
struct Tiles {
surfaces: Vec<NativeSurface>,
}
fn state() -> Tiles {
let surfaces: Vec<_> = (0..4).map(|_| NativeSurface::new()).collect();
let bytes = synthetic(640, 360, 0);
for s in &surfaces {
push(s, &bytes, 0);
}
Tiles { surfaces }
}
fn setup(s: &mut Tiles, wake: Waker) {
for surface in &s.surfaces {
surface.set_waker(wake.clone());
}
// Headless scenes use the deterministic initial frame, not a wall-clock producer.
if std::env::args()
.any(|v| matches!(v.as_str(), "--snap" | "--frames" | "--first-pixels" | "--tree" | "--trace" | "--strip"))
{
return;
}
let surfaces = s.surfaces.clone();
std::thread::spawn(move || {
for id in 1..=u64::MAX {
let bytes = synthetic(640, 360, id);
for s in &surfaces {
push(s, &bytes, id);
}
std::thread::sleep(Duration::from_millis(16));
}
});
}
fn view(s: &Tiles, _: &mut Cx<Tiles>) -> El {
col().key("tiles").gap(8.0).padding(8.0).children((0..2).map(|y| {
row().gap(8.0).children((0..2).map(|x| {
el().key(format!("tile-{x}-{y}"))
.w(320.0)
.h(180.0)
.radius(8.0)
.native_surface(&s.surfaces[y * 2 + x], SurfaceFit::Fit)
}))
}))
}
fn main() {
if std::env::args().any(|a| a == "--bench-native") {
bench::run();
return;
}
rune::run(AppSpec { setup: Some(setup), ..AppSpec::new("Video tiles", (664.0, 384.0), state, view) });
}