FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M4.8: HEVC transform/SAO speed-up, catch-up decoding, perf.stats
Brandon Thomas1f6562c08a23
diff --git a/Cargo.lock b/Cargo.lockindex 946a9963a..1cd532309 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1772,6 +1772,7 @@ dependencies = ["log","symphonia","thiserror 2.0.21",+ "web-time",][[package]]diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.tomlindex aa2b951f2..1d704831f 100644--- a/crates/codecs/Cargo.toml+++ b/crates/codecs/Cargo.toml@@ -27,6 +27,8 @@ filmcraft-aac = { workspace = true }filmcraft-opus = { workspace = true }thiserror = { workspace = true }log = { workspace = true }+# Decode timing counters (`gop_stats`); std's Instant panics on wasm32.+web-time = "1"image = { version = "0.25", default-features = false, features = ["jpeg"] }# Bootstrap audio decoding (MPL-2.0, used unmodified); replaced by own decoders over time.symphonia = { version = "0.5.5", default-features = false, features = ["aac", "mp3", "flac", "alac", "pcm", "wav", "ogg", "vorbis", "isomp4"] }diff --git a/crates/codecs/src/gop.rs b/crates/codecs/src/gop.rsindex 5e0b038be..9acdbde3e 100644--- a/crates/codecs/src/gop.rs+++ b/crates/codecs/src/gop.rs@@ -27,6 +27,23 @@ pub struct GopStats {pub decoded: u64,/// Decoded frames evicted from the cache.pub evicted: u64,+ /// Wall time spent inside decoders (`decode` / `flush`), nanoseconds.+ pub decode_ns: u64,+ /// Non-reference samples left out while catching up (frames already late).+ pub skipped: u64,+}++impl GopStats {+ /// Share of requests answered from the decoded-frame cache (0 when there were none).+ pub fn hit_rate(&self) -> f64 {+ let n = self.hits + self.misses;+ if n == 0 { 0.0 } else { self.hits as f64 / n as f64 }+ }++ /// Mean decoder wall time per sample fed (ms).+ pub fn decode_ms_per_sample(&self) -> f64 {+ if self.decoded == 0 { 0.0 } else { self.decode_ns as f64 / 1e6 / self.decoded as f64 }+ }}static HITS: AtomicU64 = AtomicU64::new(0);@@ -34,6 +51,16 @@ static MISSES: AtomicU64 = AtomicU64::new(0);static SEEKS: AtomicU64 = AtomicU64::new(0);static DECODED: AtomicU64 = AtomicU64::new(0);static EVICTED: AtomicU64 = AtomicU64::new(0);+static DECODE_NS: AtomicU64 = AtomicU64::new(0);+static SKIPPED: AtomicU64 = AtomicU64::new(0);++/// Run a decoder call, adding its wall time to the process-wide counter.+fn timed<R>(f: impl FnOnce() -> R) -> R {+ let t0 = web_time::Instant::now();+ let r = f();+ DECODE_NS.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);+ r+}/// The counters so far (they only grow; subtract two snapshots to measure an interval).pub fn gop_stats() -> GopStats {@@ -43,6 +70,8 @@ pub fn gop_stats() -> GopStats {seeks: SEEKS.load(Ordering::Relaxed),decoded: DECODED.load(Ordering::Relaxed),evicted: EVICTED.load(Ordering::Relaxed),+ decode_ns: DECODE_NS.load(Ordering::Relaxed),+ skipped: SKIPPED.load(Ordering::Relaxed),}}@@ -55,6 +84,8 @@ impl std::ops::Sub for GopStats {seeks: self.seeks - o.seeks,decoded: self.decoded - o.decoded,evicted: self.evicted - o.evicted,+ decode_ns: self.decode_ns - o.decode_ns,+ skipped: self.skipped - o.skipped,}}}@@ -196,6 +227,14 @@ impl GopCache {/// cache's lock. Such a nested request must not lock again (deadlock): it decodes the frame/// with a private decoder instead ([`Self::private_frame`]).pub fn frame(&self, s: &dyn VideoSamples, target: i64) -> crate::Result<Arc<VideoFrame>> {+ self.frame_late(s, target, None)+ }++ /// [`Self::frame`] while catching up: frames shown before `late_before` (track units) are+ /// late. Non-reference samples of late frames are left out on the way to the wanted frame+ /// (no other picture depends on them, so the wanted frame decodes exactly as it would+ /// otherwise; a later request for a skipped frame re-seeks).+ pub fn frame_late(&self, s: &dyn VideoSamples, target: i64, late_before: Option<i64>) -> crate::Result<Arc<VideoFrame>> {let n = s.count();let i = s.sample_at(target.max(0)).or_else(|| (n > 0).then(|| n - 1)).ok_or_else(|| CodecError::Decode("empty track".into()))?;let want_pts = s.pts(i);@@ -253,6 +292,7 @@ impl GopCache {st.out_max = i64::MIN;}let limit = (i.max(st.next) + 64).min(n);+ let late = late_before.unwrap_or(i64::MIN).min(want_pts);while st.next < limit {if filmcraft_media::cancel::cancelled() {// The decoder state stays consistent (`next`, `out_max`): a later request continues.@@ -260,7 +300,12 @@ impl GopCache {}let k = st.next;let data = s.read(k)?;- let out = st.decoder.as_mut().expect("decoder").decode(&data, s.pts(k))?;+ if k != i && s.pts(k) < late && st.decoder.as_ref().expect("decoder").is_disposable(&data) {+ st.next += 1;+ SKIPPED.fetch_add(1, Ordering::Relaxed);+ continue;+ }+ let out = timed(|| st.decoder.as_mut().expect("decoder").decode(&data, s.pts(k)))?;st.next += 1;DECODED.fetch_add(1, Ordering::Relaxed);self.store_output(&mut st, out);@@ -269,7 +314,7 @@ impl GopCache {}}if !st.frames.contains_key(&want_pts) {- let out = st.decoder.as_mut().expect("decoder").flush();+ let out = timed(|| st.decoder.as_mut().expect("decoder").flush());self.store_output(&mut st, out);st.next = usize::MAX;}@@ -328,7 +373,7 @@ impl GopCache {while *next < limit {let k = *next;let data = s.read(k)?;- let pics = d.decode(&data, s.pts(k))?;+ let pics = timed(|| d.decode(&data, s.pts(k)))?;*next += 1;found |= pics.iter().any(|p| p.pts == want_pts);out.extend(pics);@@ -337,7 +382,7 @@ impl GopCache {}}if !found {- out.extend(d.flush());+ out.extend(timed(|| d.flush()));*next = usize::MAX;}Ok(out)@@ -355,7 +400,7 @@ impl GopCache {};let res = s.read(i).and_then(|data| {DECODED.fetch_add(1, Ordering::Relaxed);- dec.decode(&data, want_pts)+ timed(|| dec.decode(&data, want_pts))});let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());if st.spare.len() < 16 {@@ -426,6 +471,10 @@ mod tests {fn intra_only(&self) -> bool {self.intra}+ // odd samples are non-reference pictures+ fn is_disposable(&self, sample: &[u8]) -> bool {+ sample[0] % 2 == 1+ }}impl VideoSamples for Samples {@@ -510,6 +559,39 @@ mod tests {assert_eq!(s.resets.load(Ordering::Relaxed), 0);}+ #[test]+ fn catching_up_skips_late_non_reference_samples_only() {+ let s = samples(300, 250, 4, false);+ let c = GopCache::new(None);+ assert_eq!(index_of(&c.frame(&s, 2_000).expect("frame")), 2);+ let before = s.decodes.load(Ordering::Relaxed);+ // playback is behind: frame 41 is due, 7..=40 are late+ let f = c.frame_late(&s, 41_000, Some(41_000)).expect("frame");+ assert_eq!(index_of(&f), 41, "the wanted (odd, disposable) frame itself is decoded");+ let fed = s.decodes.load(Ordering::Relaxed) - before;+ // samples 7..41 minus the odd ones before 41, plus the decoder's output delay+ assert!(fed <= 18 + 4 + 1, "fed {fed}");+ // the decoder continues from there: the next frames are decoded, not skipped+ for i in 42..48usize {+ assert_eq!(index_of(&c.frame(&s, i as i64 * 1000).expect("frame")), i);+ }+ assert_eq!(s.resets.load(Ordering::Relaxed), 1);+ // without the hint nothing is skipped+ let s2 = samples(300, 250, 4, false);+ let c2 = GopCache::new(None);+ assert_eq!(index_of(&c2.frame(&s2, 41_000).expect("frame")), 41);+ assert!(s2.decodes.load(Ordering::Relaxed) >= 42);+ // a prefetch job for frame 41 while frame 30 is due: only frames before 30 are late+ let s3 = samples(300, 250, 0, false);+ let c3 = GopCache::new(None);+ assert_eq!(index_of(&c3.frame_late(&s3, 41_000, Some(30_000)).expect("frame")), 41);+ assert_eq!(s3.decodes.load(Ordering::Relaxed), 42 - 15, "odd samples 1..=29 skipped");+ for i in 30..41usize {+ assert_eq!(index_of(&c3.frame(&s3, i as i64 * 1000).expect("cached")), i);+ }+ assert_eq!(s3.resets.load(Ordering::Relaxed), 1);+ }+#[test]fn cancelled_request_stops_decoding_and_keeps_state() {let s = samples(300, 250, 0, false);diff --git a/crates/codecs/src/mkv.rs b/crates/codecs/src/mkv.rsindex 492047232..f839a6e13 100644--- a/crates/codecs/src/mkv.rs+++ b/crates/codecs/src/mkv.rs@@ -431,8 +431,10 @@ impl MediaSource for MkvSource {fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>, MediaError> {let ti = self.vtrack.ok_or(MediaError::NoStream("video"))?;- let target = from_tick(&self.file.tracks[ti], req.time.max(Tick::ZERO));- Ok(self.video.frame(&MkvVideo { src: self, track: ti }, target)?)+ let t = req.time.max(Tick::ZERO);+ let target = from_tick(&self.file.tracks[ti], t);+ let late = filmcraft_media::cancel::catch_up().map(|m| from_tick(&self.file.tracks[ti], t - m));+ Ok(self.video.frame_late(&MkvVideo { src: self, track: ti }, target, late)?)}fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer, MediaError> {diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rsindex f940c1e7e..2be505188 100644--- a/crates/codecs/src/mp4.rs+++ b/crates/codecs/src/mp4.rs@@ -235,7 +235,8 @@ impl Mp4Source {fn video_at(&self, t: Tick) -> crate::Result<Arc<VideoFrame>> {let ti = self.vtrack.ok_or_else(|| CodecError::Unsupported("no video".into()))?;let ts = self.file.tracks[ti].timescale as i64;- self.video.frame(&Mp4Video { src: self, track: ti }, t.to_rational_floor(1, ts))+ let late = filmcraft_media::cancel::catch_up().map(|m| (t - m).to_rational_floor(1, ts));+ self.video.frame_late(&Mp4Video { src: self, track: ti }, t.to_rational_floor(1, ts), late)}fn audio_packet(&self, st: &mut AudioState, i: usize) -> crate::Result<Arc<Vec<Vec<f32>>>> {diff --git a/crates/codecs/src/video.rs b/crates/codecs/src/video.rsindex c83de2c03..39b479783 100644--- a/crates/codecs/src/video.rs+++ b/crates/codecs/src/video.rs@@ -31,6 +31,78 @@ pub trait VideoDecoder: Send {fn is_random_access(&self, _sample: &[u8]) -> Option<bool> {None}+ /// Whether `sample` can be left out without changing any other picture: a non-reference+ /// picture. Decoding forward to a frame while catching up skips such samples when their+ /// frames are late ([`filmcraft_media::cancel::catch_up`]). False when unknown.+ fn is_disposable(&self, _sample: &[u8]) -> bool {+ false+ }+}++/// NAL unit headers of a length-prefixed (avcC / hvcC) sample: the first two bytes of each unit.+fn nal_headers(sample: &[u8], length_size: usize) -> impl Iterator<Item = (u8, u8)> + '_ {+ let mut pos = 0usize;+ std::iter::from_fn(move || {+ if length_size == 0 || length_size > 4 || pos + length_size > sample.len() {+ return None;+ }+ let len = sample[pos..pos + length_size].iter().fold(0usize, |a, &b| (a << 8) | b as usize);+ pos += length_size;+ if len == 0 || pos + len > sample.len() {+ return None;+ }+ let h = (sample[pos], if len > 1 { sample[pos + 1] } else { 0 });+ pos += len;+ Some(h)+ })+}++/// H.264 (7.4.1): every coded slice (NAL types 1-5) of the access unit has nal_ref_idc 0.+pub fn h264_disposable(sample: &[u8], length_size: usize) -> bool {+ let mut slices = 0;+ for (h, _) in nal_headers(sample, length_size) {+ if (1..=5).contains(&(h & 0x1f)) {+ if h & 0x60 != 0 {+ return false;+ }+ slices += 1;+ }+ }+ slices > 0+}++/// HEVC (7.4.2.2): every VCL NAL unit is a sub-layer non-reference picture (TRAIL_N, TSA_N,+/// STSA_N, RADL_N, RASL_N, RSV_VCL_N10/12/14) of the highest temporal sub-layer, so no picture+/// references it. `highest_tid` = numTemporalLayers - 1 from the hvcC (None: unknown).+pub fn hevc_disposable(sample: &[u8], length_size: usize, highest_tid: Option<u8>) -> bool {+ let Some(top) = highest_tid else { return false };+ let mut slices = 0;+ for (h0, h1) in nal_headers(sample, length_size) {+ let t = (h0 >> 1) & 0x3f;+ if t < 32 {+ let tid = (h1 & 7).saturating_sub(1);+ if t > 14 || t % 2 == 1 || tid != top {+ return false;+ }+ slices += 1;+ }+ }+ slices > 0+}++/// A plane as a tight `w`×`h` buffer. Decoders hand over owned planes that usually are tight+/// already: those are moved, not copied (a 2160p 4:2:0 picture is 12 MB per copy).+pub(crate) fn tight_plane<T: Copy>(src: Vec<T>, stride: usize, w: usize, h: usize) -> Vec<T> {+ if stride == w && src.len() >= w * h {+ let mut v = src;+ v.truncate(w * h);+ return v;+ }+ let mut out = Vec::with_capacity(w * h);+ for y in 0..h {+ out.extend_from_slice(&src[y * stride..y * stride + w]);+ }+ out}/// A factory returns `None` when it does not handle the entry.@@ -67,30 +139,22 @@ pub fn mjpeg_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {pub struct H264Decoder {avcc: Vec<u8>,dec: filmcraft_h264::Decoder,+ length_size: usize,}impl H264Decoder {pub fn new(avcc: Vec<u8>) -> Result<Self> {let dec = filmcraft_h264::Decoder::from_avcc(&avcc).map_err(|e| CodecError::Decode(e.to_string()))?;- Ok(Self { avcc, dec })+ let length_size = avcc.get(4).map_or(4, |b| (b & 3) as usize + 1);+ Ok(Self { avcc, dec, length_size })}fn convert(p: filmcraft_h264::Picture) -> DecodedFrame {use std::sync::Arc;let (w, h) = (p.width as usize, p.height as usize);let (cw, ch) = (p.chroma_width as usize, p.chroma_height as usize);- let tight = |src: &[u8], stride: usize, w: usize, h: usize| -> Vec<u8> {- if stride == w && src.len() >= w * h {- return src[..w * h].to_vec();- }- let mut out = Vec::with_capacity(w * h);- for y in 0..h {- out.extend_from_slice(&src[y * stride..y * stride + w]);- }- out- };- let y = tight(&p.y, p.y_stride, w, h);- let u = tight(&p.u, p.uv_stride, cw, ch);- let v = tight(&p.v, p.uv_stride, cw, ch);+ let y = tight_plane(p.y, p.y_stride, w, h);+ let u = tight_plane(p.u, p.uv_stride, cw, ch);+ let v = tight_plane(p.v, p.uv_stride, cw, ch);let mut color = filmcraft_color::ColorInfo { matrix: filmcraft_frame::default_matrix(p.width, p.height), ..filmcraft_color::ColorInfo::REC709 };if let Some(m) = filmcraft_color::Matrix::from_code(p.color.matrix) {color.matrix = m;@@ -130,6 +194,9 @@ impl VideoDecoder for H264Decoder {fn name(&self) -> &str {"FilmCraft H.264"}+ fn is_disposable(&self, sample: &[u8]) -> bool {+ h264_disposable(sample, self.length_size)+ }}pub fn h264_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {@@ -143,47 +210,42 @@ pub fn h264_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {pub struct HevcDecoder {hvcc: Vec<u8>,dec: filmcraft_hevc::Decoder,+ length_size: usize,+ highest_tid: Option<u8>,}impl HevcDecoder {pub fn new(hvcc: Vec<u8>) -> Result<Self> {let dec = filmcraft_hevc::Decoder::from_hvcc(&hvcc).map_err(|e| CodecError::Decode(e.to_string()))?;- Ok(Self { hvcc, dec })+ // hvcC byte 21: constantFrameRate(2) numTemporalLayers(3) temporalIdNested(1) lengthSizeMinusOne(2)+ let length_size = hvcc.get(21).map_or(4, |b| (b & 3) as usize + 1);+ let highest_tid = hvcc.get(21).map(|b| (b >> 3) & 7).filter(|&n| n > 0).map(|n| n - 1);+ Ok(Self { hvcc, dec, length_size, highest_tid })}fn convert(p: filmcraft_hevc::Picture) -> DecodedFrame {use filmcraft_hevc::Plane;use std::sync::Arc;- fn tight<T: Copy>(src: &[T], stride: usize, w: usize, h: usize) -> Vec<T> {- if stride == w && src.len() >= w * h {- return src[..w * h].to_vec();- }- let mut out = Vec::with_capacity(w * h);- for y in 0..h {- out.extend_from_slice(&src[y * stride..y * stride + w]);- }- out- }let (w, h) = (p.width as usize, p.height as usize);let (cw, ch) = (p.chroma_width as usize, p.chroma_height as usize);- let data = match (&p.y, &p.u, &p.v) {+ let (ys, uvs) = (p.y_stride, p.uv_stride);+ let wide = |pl: Plane| -> Vec<u16> {+ match pl {+ Plane::U16(v) => v,+ Plane::U8(v) => v.into_iter().map(u16::from).collect(),+ }+ };+ let data = match (p.y, p.u, p.v) {(Plane::U8(y), Plane::U8(u), Plane::U8(v)) => filmcraft_frame::PixelData::Yuv8 {- planes: [Arc::new(tight(y, p.y_stride, w, h)), Arc::new(tight(u, p.uv_stride, cw, ch)), Arc::new(tight(v, p.uv_stride, cw, ch))],+ planes: [Arc::new(tight_plane(y, ys, w, h)), Arc::new(tight_plane(u, uvs, cw, ch)), Arc::new(tight_plane(v, uvs, cw, ch))],chroma: filmcraft_frame::Chroma::C420,alpha: None,},- _ => {- let wide = |pl: &Plane| -> Vec<u16> { (0..pl.len()).map(|i| pl.get(i)).collect() };- filmcraft_frame::PixelData::Yuv16 {- planes: [- Arc::new(tight(&wide(&p.y), p.y_stride, w, h)),- Arc::new(tight(&wide(&p.u), p.uv_stride, cw, ch)),- Arc::new(tight(&wide(&p.v), p.uv_stride, cw, ch)),- ],- chroma: filmcraft_frame::Chroma::C420,- bits: p.bit_depth,- alpha: None,- }- }+ (y, u, v) => filmcraft_frame::PixelData::Yuv16 {+ planes: [Arc::new(tight_plane(wide(y), ys, w, h)), Arc::new(tight_plane(wide(u), uvs, cw, ch)), Arc::new(tight_plane(wide(v), uvs, cw, ch))],+ chroma: filmcraft_frame::Chroma::C420,+ bits: p.bit_depth,+ alpha: None,+ },};let mut color = filmcraft_color::ColorInfo { matrix: filmcraft_frame::default_matrix(p.width, p.height), ..filmcraft_color::ColorInfo::REC709 };if let Some(m) = filmcraft_color::Matrix::from_code(p.color.matrix) {@@ -217,6 +279,9 @@ impl VideoDecoder for HevcDecoder {fn name(&self) -> &str {"FilmCraft HEVC"}+ fn is_disposable(&self, sample: &[u8]) -> bool {+ hevc_disposable(sample, self.length_size, self.highest_tid)+ }}pub fn hevc_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {@@ -304,9 +369,10 @@ impl Vp9Decoder {(false, false) => (Chroma::C444, false),(false, true) => (Chroma::C444, true),};- fn expand<T: Copy>(v: &[T], cw: usize, ch: usize, h: usize, rows_440: bool) -> Vec<T> {+ // planes are moved (tight already), not copied+ fn expand<T: Copy>(v: Vec<T>, cw: usize, ch: usize, h: usize, rows_440: bool) -> Vec<T> {if !rows_440 {- return v[..cw * ch].to_vec();+ return tight_plane(v, cw, cw, ch);}let mut out = Vec::with_capacity(cw * h);for y in 0..h {@@ -314,14 +380,14 @@ impl Vp9Decoder {}out}- let data = match (&p.y, &p.u, &p.v) {+ let data = match (p.y, p.u, p.v) {(Plane::U8(y), Plane::U8(u), Plane::U8(v)) => PixelData::Yuv8 {- planes: [Arc::new(y[..w * h].to_vec()), Arc::new(expand(u, cw, ch, h, rows_440)), Arc::new(expand(v, cw, ch, h, rows_440))],+ planes: [Arc::new(tight_plane(y, w, w, h)), Arc::new(expand(u, cw, ch, h, rows_440)), Arc::new(expand(v, cw, ch, h, rows_440))],chroma,alpha: None,},(Plane::U16(y), Plane::U16(u), Plane::U16(v)) => PixelData::Yuv16 {- planes: [Arc::new(y[..w * h].to_vec()), Arc::new(expand(u, cw, ch, h, rows_440)), Arc::new(expand(v, cw, ch, h, rows_440))],+ planes: [Arc::new(tight_plane(y, w, w, h)), Arc::new(expand(u, cw, ch, h, rows_440)), Arc::new(expand(v, cw, ch, h, rows_440))],chroma,bits: p.bit_depth,alpha: None,@@ -586,3 +652,47 @@ impl VideoDecoder for DnxDecoder {pub fn dnx_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {matches!(e.codec, CodecConfig::Dnx { .. }).then(|| Ok(Box::new(DnxDecoder) as Box<dyn VideoDecoder>))}++#[cfg(test)]+mod disposable_tests {+ use super::{h264_disposable, hevc_disposable};++ /// A 4-byte length-prefixed sample of the given NAL units.+ fn sample(nals: &[&[u8]]) -> Vec<u8> {+ let mut v = Vec::new();+ for n in nals {+ v.extend_from_slice(&(n.len() as u32).to_be_bytes());+ v.extend_from_slice(n);+ }+ v+ }++ #[test]+ fn h264_non_reference_access_units() {+ // nal_ref_idc 0 slice (type 1), with an SEI (type 6) before it+ assert!(h264_disposable(&sample(&[&[0x06, 5, 1], &[0x01, 0x9a, 0]]), 4));+ // reference P slice (nal_ref_idc 2), IDR, mixed reference / non-reference slices+ assert!(!h264_disposable(&sample(&[&[0x41, 0x9a]]), 4));+ assert!(!h264_disposable(&sample(&[&[0x65, 0x88]]), 4));+ assert!(!h264_disposable(&sample(&[&[0x01, 0x9a], &[0x21, 0x9a]]), 4));+ // no slice at all, truncated data+ assert!(!h264_disposable(&sample(&[&[0x06, 5]]), 4));+ assert!(!h264_disposable(&[0, 0, 0, 9, 1], 4));+ }++ #[test]+ fn hevc_sub_layer_non_reference_pictures_of_the_top_layer() {+ let nal = |t: u8, tid1: u8| [t << 1, tid1, 0xaf];+ // TRAIL_N (0) at TemporalId 0 with one temporal layer+ assert!(hevc_disposable(&sample(&[&nal(39, 1), &nal(0, 1)]), 4, Some(0)));+ // TRAIL_R (1), CRA (21), IDR (19) are referenced+ for t in [1u8, 19, 21] {+ assert!(!hevc_disposable(&sample(&[&nal(t, 1)]), 4, Some(0)), "type {t}");+ }+ // RASL_N (8) at the top layer of two; at a lower layer it may be referenced+ assert!(hevc_disposable(&sample(&[&nal(8, 2)]), 4, Some(1)));+ assert!(!hevc_disposable(&sample(&[&nal(0, 1)]), 4, Some(1)));+ // unknown layering: never+ assert!(!hevc_disposable(&sample(&[&nal(0, 1)]), 4, None));+ }+}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 9db124484..8a0a81aca 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -758,6 +758,7 @@ fn build() -> Vec<CommandSpec> {|s, p| export_media(s, p)),query!("jobs.list", "List Jobs", "{}", |s, _| Ok(Value::Array(s.jobs.iter().map(crate::Job::to_json).collect()))),+ query!("perf.stats", "Performance Statistics", "{}", |s, _| Ok(crate::perf::stats(s))),cmd!("jobs.cancel", "Cancel Job", [], None, r#"{"job":id}"#, always, |s, p| {let id = u64_p(p, "job").ok_or_else(|| bad("jobs.cancel", "need `job`"))?;let j = s.jobs.iter().find(|j| j.id == id).ok_or_else(|| bad("jobs.cancel", "no such job"))?;diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex aa392e958..2146bbafd 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -21,6 +21,7 @@ pub mod masks;pub mod media_pool;pub mod mixer;pub mod multicam;+pub mod perf;pub mod presets;pub mod previews;pub mod project_manager;diff --git a/crates/engine/src/media_pool.rs b/crates/engine/src/media_pool.rsindex 118f51f98..5aa5338e1 100644--- a/crates/engine/src/media_pool.rs+++ b/crates/engine/src/media_pool.rs@@ -100,6 +100,11 @@ impl MediaPool {self.sources.read().unwrap_or_else(|e| e.into_inner()).get(&item).map(|(_, s)| s.clone())}+ /// Sources opened so far (originals and proxies; `perf.stats`).+ pub fn open_sources(&self) -> usize {+ self.sources.read().unwrap_or_else(|e| e.into_inner()).len() + self.proxies.read().unwrap_or_else(|e| e.into_inner()).len()+ }+pub fn use_proxies(&self) -> bool {self.use_proxies.load(Ordering::Relaxed)}diff --git a/crates/engine/src/perf.rs b/crates/engine/src/perf.rsnew file mode 100644index 000000000..de656bc3c--- /dev/null+++ b/crates/engine/src/perf.rs@@ -0,0 +1,56 @@+//! `perf.stats`: performance counters an agent can read (headless engine part). The desktop UI+//! extends the same query with playback, frame-worker and UI timings (`ui-egui` `perf.rs`).++use serde_json::{Value, json};++use crate::Session;++/// Decoder / GOP-cache counters since the process started (they only grow: diff two readings to+/// measure an interval).+pub fn decode_json() -> Value {+ let g = filmcraft_codecs::gop_stats();+ json!({+ "requests": g.hits + g.misses,+ "cacheHits": g.hits,+ "cacheMisses": g.misses,+ "cacheHitRate": g.hit_rate(),+ "seeks": g.seeks,+ "samplesDecoded": g.decoded,+ "samplesSkipped": g.skipped,+ "evicted": g.evicted,+ "decodeMs": g.decode_ns as f64 / 1e6,+ "decodeMsPerSample": g.decode_ms_per_sample(),+ })+}++/// The engine's `perf.stats`.+pub fn stats(s: &Session) -> Value {+ let running = s.jobs.iter().filter(|j| j.result.lock().map(|r| r.is_none()).unwrap_or(false)).count();+ json!({+ "decode": decode_json(),+ "media": {"openSources": s.media.open_sources()},+ "jobs": {"total": s.jobs.len(), "running": running},+ })+}++#[cfg(test)]+mod tests {+ use serde_json::json;++ use crate::Session;++ #[test]+ fn perf_stats_query_reports_decode_counters() {+ let mut s = Session::default();+ assert!(s.execute("perf.stats", json!({})).is_ok(), "available without a project");+ s.execute("file.openDemoProject", json!({})).unwrap();+ let undo = s.history.undo.len();+ let v = s.execute("perf.stats", json!({})).unwrap();+ for k in ["requests", "cacheHitRate", "seeks", "samplesDecoded", "samplesSkipped", "decodeMs", "decodeMsPerSample"] {+ assert!(v["decode"][k].is_number(), "decode.{k} in {v}");+ }+ assert!(v["media"]["openSources"].is_number());+ assert_eq!(v["jobs"]["running"], json!(0));+ assert_eq!(s.history.undo.len(), undo, "a query adds no undo step");+ }+}diff --git a/crates/hevc/README.md b/crates/hevc/README.mdindex 574b77910..37eba9e07 100644--- a/crates/hevc/README.md+++ b/crates/hevc/README.md@@ -135,7 +135,15 @@ average 50-100), so these are lower bounds:| 1080p Main, x265 medium CRF 24, 60 frames | ~75 fps | ~225 fps || 2160p Main 10, x265 fast CRF 26, 20 frames | ~20 fps | ~95 fps |-No SIMD-specific code yet; interpolation, transforms and loop filters are plain loops.+No SIMD-specific code yet; interpolation, transforms and loop filters are plain loops. M4.8+profiling (`cargo xtask bench`, macOS `sample`) found the inverse transform at over half of the+decoder's CPU time: it evaluated the full matrix product with strided table reads. It now sums+contiguous basis rows scaled by the non-zero coefficients only, with the block size a compile-time+constant so the loops vectorise (exact integer sums, so bit-exact; `transform::tests` checks it+against the direct product on random sparse and dense blocks). SAO edge offset has a check-free+loop for samples whose neighbours are inside the CTB. Together: ~60 % less CPU per frame+(1080p 78 → 33 ms, 2160p 320 → 129 ms of CPU per frame through the media stack, alternating A/B), see+[docs/performance.md](../../docs/performance.md).`cargo run --release -p filmcraft-hevc --example hevcdec -- in.hevc out.yuv` decodes a file.## Known gapsdiff --git a/crates/hevc/src/filter.rs b/crates/hevc/src/filter.rsindex 6cc55ed10..95c326c2d 100644--- a/crates/hevc/src/filter.rs+++ b/crates/hevc/src/filter.rs@@ -424,36 +424,59 @@ fn sao_ctb(true};let edge_map = [1usize, 2, 0, 3, 4];- for y in y0..y1 {- for x in x0..x1 {- if any_nofilter && nofilter(pic, x, y) {- continue;+ // Offset per (2 + sum of neighbour signs); edgeIdx 0 adds nothing.+ let by_sum = edge_map.map(|e| if e == 0 { 0 } else { offs[e - 1] });+ // Any sample: neighbours outside the picture or in a CTB that may not be used leave it as is.+ let general = |x: usize, y: usize| -> Option<u16> {+ if any_nofilter && nofilter(pic, x, y) {+ return None;+ }+ let mut sum = 0i32;+ let v = pic.planes[c][y * w + x] as i32;+ for k in 0..2 {+ let xn = x as i32 + hp[k];+ let yn = y as i32 + vp[k];+ if xn < 0 || yn < 0 || xn >= w as i32 || yn >= h as i32 {+ return None;}- let mut ok = true;- let mut sum = 0i32;- let v = pic.planes[c][y * w + x] as i32;- for k in 0..2 {- let xn = x as i32 + hp[k];- let yn = y as i32 + vp[k];- if xn < 0 || yn < 0 || xn >= w as i32 || yn >= h as i32 {- ok = false;- break;- }- let (xn, yn) = (xn as usize, yn as usize);- if (xn < x0 || xn >= x1 || yn < y0 || yn >= y1) && !cross_ok(pic, xn, yn) {- ok = false;- break;- }- sum += (v - pic.planes[c][yn * w + xn] as i32).signum();+ let (xn, yn) = (xn as usize, yn as usize);+ if (xn < x0 || xn >= x1 || yn < y0 || yn >= y1) && !cross_ok(pic, xn, yn) {+ return None;}- if !ok {- continue;+ sum += (v - pic.planes[c][yn * w + xn] as i32).signum();+ }+ Some((v + by_sum[(2 + sum) as usize]).clamp(0, max) as u16)+ };+ // Samples whose two neighbours lie inside this CTB need none of those checks: a tight loop+ // (same arithmetic) for them, the general path for the CTB border.+ let (mx, my) = ((hp[0] != 0) as usize, (vp[0] != 0) as usize);+ let plane = &pic.planes[c];+ for y in y0..y1 {+ let inner_row = !any_nofilter && y >= y0 + my && y + my < y1 && x1 - x0 > 2 * mx;+ if !inner_row {+ for x in x0..x1 {+ if let Some(v) = general(x, y) {+ dst[(y - y0) * w + x] = v;+ }}- let edge_idx = edge_map[(2 + sum) as usize];- if edge_idx == 0 {- continue;+ continue;+ }+ for x in (x0..x0 + mx).chain(x1 - mx..x1) {+ if let Some(v) = general(x, y) {+ dst[(y - y0) * w + x] = v;}- dst[(y - y0) * w + x] = (v + offs[edge_idx - 1]).clamp(0, max) as u16;+ }+ let (ya, yb) = ((y as i32 + vp[0]) as usize, (y as i32 + vp[1]) as usize);+ let (xa, xb) = (x0 as i32 + mx as i32 + hp[0], x0 as i32 + mx as i32 + hp[1]);+ let n = x1 - x0 - 2 * mx;+ let cur = &plane[y * w + x0 + mx..][..n];+ let na = &plane[ya * w + xa as usize..][..n];+ let nb = &plane[yb * w + xb as usize..][..n];+ let out = &mut dst[(y - y0) * w + x0 + mx..][..n];+ for i in 0..n {+ let v = cur[i] as i32;+ let sum = (v - na[i] as i32).signum() + (v - nb[i] as i32).signum();+ out[i] = (v + by_sum[(2 + sum) as usize]).clamp(0, max) as u16;}}}diff --git a/crates/hevc/src/transform.rs b/crates/hevc/src/transform.rsindex b22b4e535..5c0361f4a 100644--- a/crates/hevc/src/transform.rs+++ b/crates/hevc/src/transform.rs@@ -5,31 +5,56 @@ use crate::tables::{DST_MATRIX, TRANS_MATRIX};/// Inverse transform of an n x n block of scaled coefficients `c` (row-major, `c[y * n + x]`) in place,/// producing residuals after the final `bd_shift` rounding (8-299). `max_x` / `max_y` bound the/// non-zero coefficients (inclusive). `dst`: DST-VII (intra 4x4 luma).+///+/// Evaluated as sums of basis rows scaled by the non-zero coefficients (zero coefficients, which+/// are most of them, cost nothing), with the size a compile-time constant so the inner loops over+/// contiguous basis rows vectorise. Integer sums are exact (|sum| < 2^27), so the result equals the+/// direct matrix product of 8.6.4.2 in any summation order.pub fn inverse_transform(c: &mut [i32], n: usize, dst: bool, max_x: usize, max_y: usize, bd_shift: u32) {- let mut tmp = [0i32; 32 * 32];- let step = 32 / n;- // 1. columns: e[x][y] = sum_j M[j][y] * d[x][j]- for x in 0..=max_x {- for y in 0..n {- let mut s = 0i32;- for j in 0..=max_y {- let m = if dst { DST_MATRIX[j][y] as i32 } else { TRANS_MATRIX[j * step][y] as i32 };- s += m * c[j * n + x];+ match n {+ 4 => inverse::<4>(c, dst, max_x, max_y, bd_shift),+ 8 => inverse::<8>(c, false, max_x, max_y, bd_shift),+ 16 => inverse::<16>(c, false, max_x, max_y, bd_shift),+ _ => inverse::<32>(c, false, max_x, max_y, bd_shift),+ }+}++#[inline(always)]+fn inverse<const N: usize>(c: &mut [i32], dst: bool, max_x: usize, max_y: usize, bd_shift: u32) {+ let step = 32 / N;+ // basis function of coefficient index j (row j of the transform matrix, N samples)+ let basis = |j: usize| -> &[i8] { if dst { &DST_MATRIX[j][..N] } else { &TRANS_MATRIX[j * step][..N] } };+ // 1. columns (8-297 ... first stage): e[x][y] = sum_j M[j][y] * d[x][j], stored transposed+ // (col[x][y]) so each coefficient adds one contiguous basis row.+ let mut col = [[0i32; N]; N];+ for x in 0..=max_x.min(N - 1) {+ let acc = &mut col[x];+ for j in 0..=max_y.min(N - 1) {+ let d = c[j * N + x];+ if d != 0 {+ for (a, &m) in acc.iter_mut().zip(basis(j)) {+ *a += m as i32 * d;+ }}- tmp[y * n + x] = ((s + 64) >> 7).clamp(-32768, 32767);+ }+ for a in acc.iter_mut() {+ *a = ((*a + 64) >> 7).clamp(-32768, 32767);}}- // 2. rows: r[x][y] = sum_j M[j][x] * g[j][y]+ // 2. rows: r[x][y] = sum_j M[j][x] * g[j][y], g[j][y] = col[j][y]let round = 1 << (bd_shift - 1);- for y in 0..n {- let row = &tmp[y * n..y * n + n];- for x in 0..n {- let mut s = 0i32;- for j in 0..=max_x {- let m = if dst { DST_MATRIX[j][x] as i32 } else { TRANS_MATRIX[j * step][x] as i32 };- s += m * row[j];+ for y in 0..N {+ let mut out = [round; N];+ for (j, g) in col.iter().enumerate().take(max_x.min(N - 1) + 1) {+ let g = g[y];+ if g != 0 {+ for (o, &m) in out.iter_mut().zip(basis(j)) {+ *o += m as i32 * g;+ }}- c[y * n + x] = (s + round) >> bd_shift;+ }+ for (r, o) in c[y * N..y * N + N].iter_mut().zip(out) {+ *r = o >> bd_shift;}}}@@ -53,6 +78,69 @@ pub fn transform_skip(c: &mut [i32], n: usize, bd_shift: u32) {mod tests {use super::*;+ /// The direct matrix product of 8.6.4.2 (the original implementation), as the reference.+ fn reference(c: &mut [i32], n: usize, dst: bool, max_x: usize, max_y: usize, bd_shift: u32) {+ let mut tmp = [0i32; 32 * 32];+ let step = 32 / n;+ for x in 0..=max_x {+ for y in 0..n {+ let mut s = 0i32;+ for j in 0..=max_y {+ let m = if dst { DST_MATRIX[j][y] as i32 } else { TRANS_MATRIX[j * step][y] as i32 };+ s += m * c[j * n + x];+ }+ tmp[y * n + x] = ((s + 64) >> 7).clamp(-32768, 32767);+ }+ }+ let round = 1 << (bd_shift - 1);+ for y in 0..n {+ for x in 0..n {+ let mut s = 0i32;+ for j in 0..=max_x {+ let m = if dst { DST_MATRIX[j][x] as i32 } else { TRANS_MATRIX[j * step][x] as i32 };+ s += m * tmp[y * n + j];+ }+ c[y * n + x] = (s + round) >> bd_shift;+ }+ }+ }++ #[test]+ fn matches_the_direct_matrix_product() {+ // sparse and dense blocks, extreme coefficients, every size, DST, 8- and 10-bit shifts+ let mut rng = 0x2545_f491_4f6c_dd1du64;+ let mut next = move || {+ rng ^= rng << 13;+ rng ^= rng >> 7;+ rng ^= rng << 17;+ rng+ };+ for &(n, dst) in &[(4usize, true), (4, false), (8, false), (16, false), (32, false)] {+ for case in 0..400 {+ let (max_x, max_y) = ((next() as usize) % n, (next() as usize) % n);+ let density = [2u64, 8, 50, 100][case % 4];+ let mut c = vec![0i32; n * n];+ for y in 0..=max_y {+ for x in 0..=max_x {+ if next() % 100 < density {+ c[y * n + x] = match next() % 8 {+ 0 => 32767,+ 1 => -32768,+ _ => (next() % 2001) as i32 - 1000,+ };+ }+ }+ }+ for bd_shift in [12u32, 10] {+ let (mut a, mut b) = (c.clone(), c.clone());+ inverse_transform(&mut a, n, dst, max_x, max_y, bd_shift);+ reference(&mut b, n, dst, max_x, max_y, bd_shift);+ assert_eq!(a, b, "n {n} dst {dst} max ({max_x}, {max_y}) shift {bd_shift}");+ }+ }+ }+ }+#[test]fn dc_only_matches_full_transform() {for &n in &[4usize, 8, 16, 32] {diff --git a/crates/media/src/cancel.rs b/crates/media/src/cancel.rsindex de73242fd..b6622dadb 100644--- a/crates/media/src/cancel.rs+++ b/crates/media/src/cancel.rs@@ -5,13 +5,36 @@//! [`MediaError::Cancelled`](crate::MediaError::Cancelled) once the job is no longer wanted, e.g.//! playback has moved past its frame. The flag travels through a thread-local, so the//! [`MediaSource`](crate::MediaSource) API is unchanged.+//!+//! The same way, [`with_catch_up`] tells sources which frames before the requested one are late+//! (playback has passed them): a decoder that has to decode forward to the frame may skip+//! pictures that only produce late frames and that nothing else references.-use std::cell::RefCell;+use std::cell::{Cell, RefCell};use std::sync::Arc;use std::sync::atomic::{AtomicBool, Ordering};+use filmcraft_time::Tick;+thread_local! {static CURRENT: RefCell<Option<Arc<AtomicBool>>> = const { RefCell::new(None) };+ static CATCH_UP: Cell<Option<Tick>> = const { Cell::new(None) };+}++/// Run `f` with the catch-up hint `margin` (restoring the previous one after): frames shown more+/// than `margin` before the requested time are late (`Some(Tick::ZERO)`: everything before it).+/// The margin is measured in media time at normal speed; a wrong guess (a sped-up or reversed+/// clip) only costs a later re-seek, never a wrong frame.+pub fn with_catch_up<R>(margin: Option<Tick>, f: impl FnOnce() -> R) -> R {+ let prev = CATCH_UP.with(|c| c.replace(margin));+ let r = f();+ CATCH_UP.with(|c| c.set(prev));+ r+}++/// The catch-up margin of the work running on this thread (None: no frame is late).+pub fn catch_up() -> Option<Tick> {+ CATCH_UP.with(Cell::get)}/// Run `f` with `flag` as this thread's cancellation flag (restoring the previous one after).@@ -42,4 +65,15 @@ mod tests {});assert!(!cancelled());}++ #[test]+ fn catch_up_is_scoped_to_the_closure() {+ assert_eq!(catch_up(), None);+ with_catch_up(Some(Tick(5)), || {+ assert_eq!(catch_up(), Some(Tick(5)));+ with_catch_up(None, || assert_eq!(catch_up(), None));+ assert_eq!(catch_up(), Some(Tick(5)));+ });+ assert_eq!(catch_up(), None);+ }}diff --git a/crates/ui-egui/examples/bench/fixtures.rs b/crates/ui-egui/examples/bench/fixtures.rsindex 51b0a9868..eec64b6fc 100644--- a/crates/ui-egui/examples/bench/fixtures.rs+++ b/crates/ui-egui/examples/bench/fixtures.rs@@ -41,7 +41,8 @@ const SPECS: &[Spec] = &[Spec { name: "c1080.mp4", src: "smptehdbars=s=1920x1080:r=24000/1001:d=20,noise=alls=10:allf=t+u", secs: 20, audio: false, codec: X264 },Spec { name: "a2160.mp4", src: "testsrc2=s=3840x2160:r=24000/1001:d=10,noise=alls=6:allf=t", secs: 10, audio: false, codec: X264 },Spec { name: "hevc2160.mp4", src: "testsrc2=s=3840x2160:r=24000/1001:d=10,noise=alls=6:allf=t", secs: 10, audio: false, codec: X265 },- // Decode-speed matrix: 1080p (5 s) and 2160p (3 s) per codec, same picture content.+ // Decode-speed matrix: 1080p (5 s) and 2160p (3 s) per codec, same picture content (ProRes+ // 2 s / 1 s: intra-only, every frame costs the same, and the files are large).Spec { name: "dec_h264_1080.mp4", src: "testsrc2=s=1920x1080:r=24000/1001:d=5,noise=alls=6:allf=t", secs: 5, audio: false, codec: X264 },Spec { name: "dec_h264_2160.mp4", src: "testsrc2=s=3840x2160:r=24000/1001:d=3,noise=alls=6:allf=t", secs: 3, audio: false, codec: X264 },Spec { name: "dec_hevc_1080.mp4", src: "testsrc2=s=1920x1080:r=24000/1001:d=5,noise=alls=6:allf=t", secs: 5, audio: false, codec: X265 },@@ -50,8 +51,8 @@ const SPECS: &[Spec] = &[Spec { name: "dec_vp9_2160.webm", src: "testsrc2=s=3840x2160:r=24000/1001:d=3,noise=alls=6:allf=t", secs: 3, audio: false, codec: VP9 },Spec { name: "dec_av1_1080.mp4", src: "testsrc2=s=1920x1080:r=24000/1001:d=5,noise=alls=6:allf=t", secs: 5, audio: false, codec: AV1 },Spec { name: "dec_av1_2160.mp4", src: "testsrc2=s=3840x2160:r=24000/1001:d=3,noise=alls=6:allf=t", secs: 3, audio: false, codec: AV1 },- Spec { name: "dec_prores_1080.mov", src: "testsrc2=s=1920x1080:r=24000/1001:d=5,noise=alls=6:allf=t", secs: 5, audio: false, codec: PRORES },- Spec { name: "dec_prores_2160.mov", src: "testsrc2=s=3840x2160:r=24000/1001:d=3,noise=alls=6:allf=t", secs: 3, audio: false, codec: PRORES },+ Spec { name: "dec_prores_1080.mov", src: "testsrc2=s=1920x1080:r=24000/1001:d=2,noise=alls=6:allf=t", secs: 2, audio: false, codec: PRORES },+ Spec { name: "dec_prores_2160.mov", src: "testsrc2=s=3840x2160:r=24000/1001:d=1,noise=alls=6:allf=t", secs: 1, audio: false, codec: PRORES },// Small clip media for the 1000-clip timeline / project benchmarks (video + audio).Spec { name: "clip360.mp4", src: "testsrc2=s=640x360:r=24000/1001:d=20", secs: 20, audio: true, codec: X264 },];diff --git a/crates/ui-egui/examples/bench/main.rs b/crates/ui-egui/examples/bench/main.rsindex ea2af8e12..597472ea3 100644--- a/crates/ui-egui/examples/bench/main.rs+++ b/crates/ui-egui/examples/bench/main.rs@@ -24,7 +24,7 @@ use std::process::Command;use serde_json::{Value, json};-pub const SECTIONS: &[&str] = &["decode", "playback", "scrub", "timeline", "export", "project"];+pub const SECTIONS: &[&str] = &["decode", "seek", "playback", "scrub", "timeline", "export", "project"];#[derive(Clone)]pub struct Opts {@@ -77,6 +77,7 @@ fn run_section(name: &str, o: &Opts) -> Value {let load0 = playback::load_avg();let rows = match name {"decode" => sections::decode(o),+ "seek" => sections::seek(o),"playback" => sections::playback(o),"scrub" => sections::scrub(o),"timeline" => sections::timeline(o),@@ -155,7 +156,7 @@ fn time_wrapper() -> Command {/// The child's own output: everything before the `time` report (macOS `-l`: a "… real … user …"/// line; GNU `-v`: "Command being timed").fn child_lines(stderr: &str) -> Vec<&str> {- stderr.lines().take_while(|l| !(l.contains(" real ") && l.contains(" user ")) && !l.trim_start().starts_with("Command being timed")).collect()+ stderr.lines().take_while(|l| !(l.trim_start().starts_with("Command being timed") || (l.contains(" real ") && l.contains(" user ")))).collect()}/// Peak RSS in bytes from `/usr/bin/time -l` (macOS: bytes) or `-v` (GNU: kbytes).@@ -256,6 +257,21 @@ pub fn section_markdown(v: &Value) -> String {("decode_ms", "decode ms/job"),("ui_p95_ms", "UI p95 ms"),("seeks", "seeks"),+ ("skipped", "skipped"),+ ("load", "load"),+ ],+ 1,+ ),+ "seek" => (+ &[+ ("fixture", "fixture"),+ ("mode", "mode"),+ ("seeks", "seeks"),+ ("p50_ms", "p50 ms"),+ ("p95_ms", "p95 ms"),+ ("cpu_ms_mean", "CPU ms/seek"),+ ("decoded_per_seek", "decoded/seek"),+ ("skipped_per_seek", "skipped/seek"),("load", "load"),],1,diff --git a/crates/ui-egui/examples/bench/playback.rs b/crates/ui-egui/examples/bench/playback.rsindex 94e070df2..e412332a2 100644--- a/crates/ui-egui/examples/bench/playback.rs+++ b/crates/ui-egui/examples/bench/playback.rs@@ -569,7 +569,7 @@ pub fn to_json(r: &PlayReport, scenario: &str, res: &str, path: &str) -> Value {"present_ms": {"p50": pct(&r.present, 0.5), "p95": pct(&r.present, 0.95), "max": pct(&r.present, 1.0)},"ui_cpu_ms": r.ui_cpu, "process_cpu_ms": r.process_cpu, "cpu_ms_per_frame": r.process_cpu / frames,"jobs": r.jobs, "wasted_jobs": r.wasted_jobs, "cancelled_jobs": r.cancelled_jobs, "preview_jobs": r.preview_jobs, "uploaded_mb": r.uploaded_mb,- "gop": {"hits": r.gop.hits, "misses": r.gop.misses, "seeks": r.gop.seeks, "decoded": r.gop.decoded, "evicted": r.gop.evicted},+ "gop": {"hits": r.gop.hits, "misses": r.gop.misses, "seeks": r.gop.seeks, "decoded": r.gop.decoded, "evicted": r.gop.evicted, "skipped": r.gop.skipped, "decode_ms": r.gop.decode_ns as f64 / 1e6},"loadavg": r.load, "preroll_ms": r.preroll_ms,})}diff --git a/crates/ui-egui/examples/bench/sections.rs b/crates/ui-egui/examples/bench/sections.rsindex 841cf3480..d25c2057f 100644--- a/crates/ui-egui/examples/bench/sections.rs+++ b/crates/ui-egui/examples/bench/sections.rs@@ -94,6 +94,56 @@ pub fn decode(o: &Opts) -> Vec<Value> {rows}+// ------------------------------------------------------------------------------------ seek++/// Cold seeks through the media stack, the three catch-up modes interleaved per target so they+/// see the same machine load: `full` (decode every picture from the keyframe), `keep 2 s` (what a+/// scrub request does: skip non-reference pictures more than 2 s before the target) and `late`+/// (playback catching up: skip every non-reference picture before the target). A fresh source per+/// seek (cold GOP cache). CPU time and samples decoded do not depend on load; wall time does.+pub fn seek(o: &Opts) -> Vec<Value> {+ let seeks = if o.quick { 4 } else { 12 };+ let modes: [(&str, Option<Tick>); 3] = [("full", None), ("keep 2 s", Some(Tick::from_seconds_f64(2.0))), ("late", Some(Tick::ZERO))];+ let mut rows = Vec::new();+ for name in ["a1080.mp4", "a2160.mp4", "hevc2160.mp4"].into_iter().filter(|n| o.wants(n)) {+ let Some(path) = fixture(name) else {+ eprintln!("seek {name}: skipped (fixture unavailable)");+ continue;+ };+ let bytes: Arc<[u8]> = std::fs::read(&path).expect("read fixture").into();+ let mut rng = 0x2545_f491_4f6c_dd1du64;+ let (mut wall, mut cpu, mut dec, mut skip) = ([vec![], vec![], vec![]], [vec![], vec![], vec![]], [0u64; 3], [0u64; 3]);+ for _ in 0..seeks {+ rng ^= rng << 13;+ rng ^= rng >> 7;+ rng ^= rng << 17;+ for (m, (_, margin)) in modes.iter().enumerate() {+ let src = filmcraft_codecs::open_bytes(name, bytes.clone()).expect("open");+ let rate = src.info().frame_rate();+ let n = rate.frame_at(src.info().duration).max(1);+ let t = rate.tick_of((rng % n as u64) as i64);+ let (g0, t0, c0) = (filmcraft_codecs::gop_stats(), Instant::now(), cpu_now());+ filmcraft_media::cancel::with_catch_up(*margin, || src.video_frame(filmcraft_media::FrameRequest::full(t))).expect("frame");+ wall[m].push(ms(t0.elapsed()));+ cpu[m].push(ms(cpu_now() - c0));+ let g = filmcraft_codecs::gop_stats() - g0;+ dec[m] += g.decoded;+ skip[m] += g.skipped;+ }+ }+ for (m, (mode, _)) in modes.iter().enumerate() {+ let row = json!({+ "fixture": name, "mode": mode, "seeks": seeks,+ "p50_ms": pct(&wall[m], 0.5), "p95_ms": pct(&wall[m], 0.95), "cpu_ms_mean": cpu[m].iter().sum::<f64>() / seeks as f64,+ "decoded_per_seek": dec[m] as f64 / seeks as f64, "skipped_per_seek": skip[m] as f64 / seeks as f64, "load": load_avg(),+ });+ eprintln!("seek {name} {mode}: p50 {:.0} ms, CPU {:.0} ms", pct(&wall[m], 0.5), cpu[m].iter().sum::<f64>() / seeks as f64);+ rows.push(row);+ }+ }+ rows+}+// ------------------------------------------------------------------------------------ playbackfn new_bench(s: &Session, seconds: f64) -> Bench {@@ -133,6 +183,7 @@ pub fn playback(o: &Opts) -> Vec<Value> {v["decode_ms"] = json!(r.src_wall.iter().sum::<f64>() / r.jobs.max(1) as f64);v["ui_p95_ms"] = json!(pct(&r.present, 0.95));v["seeks"] = json!(r.gop.seeks);+ v["skipped"] = json!(r.gop.skipped);v["load"] = json!(r.load);v["cores_needed"] = json!(r.process_cpu / frames * fps / 1000.0);eprintln!("playback {scenario} {res}: {}/{} shown/dropped (load {})", r.shown, r.dropped, r.load);@@ -164,7 +215,7 @@ pub fn scrub(o: &Opts) -> Vec<Value> {"seek_p50_ms": pct(&r.seek_ms, 0.5), "seek_p95_ms": pct(&r.seek_ms, 0.95), "seek_max_ms": pct(&r.seek_ms, 1.0),"settle_p50_ms": pct(&r.settle_ms, 0.5), "settle_p95_ms": pct(&r.settle_ms, 0.95),"drag_shown_pct": 100.0 * r.drag_shown as f64 / r.drag_steps.max(1) as f64,- "timeouts": r.timeouts, "gop_seeks": r.gop.seeks, "decoded": r.gop.decoded,+ "timeouts": r.timeouts, "gop_seeks": r.gop.seeks, "decoded": r.gop.decoded, "skipped": r.gop.skipped,"decoded_per_seek": r.gop.decoded as f64 / positions, "process_cpu_ms": r.process_cpu_ms, "load": r.load,});eprintln!("scrub {scenario}: seek p50 {:.0} ms p95 {:.0} ms (load {})", pct(&r.seek_ms, 0.5), pct(&r.seek_ms, 0.95), r.load);@@ -358,7 +409,7 @@ pub fn export(o: &Opts) -> Vec<Value> {let dir = std::env::temp_dir().join(format!("filmcraft-bench-export-{}", std::process::id()));std::fs::create_dir_all(&dir).expect("tmp dir");let mut rows = Vec::new();- for (format, label, ext) in [("h264", "H.264 + AAC (MP4)", "mp4"), ("prores", "ProRes 422 (MOV)", "mov")] {+ for (format, label, ext) in [("h264", "H.264 + AAC (MP4)", "mp4"), ("prores", "ProRes 422 (MOV)", "mov")].into_iter().filter(|f| o.wants(f.0)) {let mut runs = Vec::new();let mut cpu = Vec::new();let mut bytes = 0u64;diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 9e39f018b..821770fab 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -99,6 +99,7 @@ pub fn handle(app: &mut FilmcraftApp, ctx: &egui::Context, req: &ControlRequest)},"ui.menu.list" => ok(serde_json::to_value(crate::menus::menu_items(app)).unwrap_or_default()),"ui.inspect" => ok(inspect(app, ctx)),+ "perf.stats" => ok(crate::perf::stats(app)),"ui.elements" => {let prefix = s("prefix").unwrap_or("");ok(serde_json::to_value(app.auto.query(prefix)).unwrap_or_default())diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rsindex 254709d0f..322cc4e83 100644--- a/crates/ui-egui/src/frames.rs+++ b/crates/ui-egui/src/frames.rs@@ -55,6 +55,10 @@ struct Job {cancel: Arc<std::sync::atomic::AtomicBool>,/// Queued by playback prefetch (dropped when playback stops).prefetch: bool,+ /// While playing: how far before this frame the frames are late (the playhead's distance;+ /// zero for the frame due now), so a decoder catching up may skip pictures only late frames+ /// need (`filmcraft_media::cancel::with_catch_up`).+ catch_up: Option<Tick>,time: Tick,/// Output scale relative to the target's frame size.scale: f32,@@ -77,6 +81,55 @@ struct Shared {/// started, and the workers can finish at most `workers / cost` of them per second.render_cost: Mutex<f64>,workers: usize,+ /// Always-on counters for `perf.stats`.+ stats: Mutex<FrameStats>,+}++/// Cumulative frame-job statistics (`perf.stats`): cheap enough to keep on all the time.+#[derive(Clone, Debug, Default)]+pub struct FrameStats {+ /// Jobs finished (including cancelled ones).+ pub jobs: u64,+ pub cancelled: u64,+ /// Jobs served from a render preview.+ pub preview: u64,+ /// Playback prefetch jobs.+ pub prefetch: u64,+ /// Requests answered by a cached frame or one already queued / running.+ pub request_hits: u64,+ /// Requests that queued a new job.+ pub request_misses: u64,+ /// Totals over all jobs (ms): getting source frames (decode), the rest (render), whole job.+ pub source_ms: f64,+ pub render_ms: f64,+ pub job_ms: f64,+ /// The most recent jobs: (source ms, render ms).+ pub recent: VecDeque<(f32, f32)>,+}++impl FrameStats {+ const RECENT: usize = 256;++ /// JSON for `perf.stats`.+ pub fn to_json(&self) -> serde_json::Value {+ let pct = |f: &dyn Fn(&(f32, f32)) -> f32, p: f64| -> f64 {+ let mut v: Vec<f32> = self.recent.iter().map(f).collect();+ if v.is_empty() {+ return 0.0;+ }+ v.sort_by(|a, b| a.total_cmp(b));+ v[((v.len() - 1) as f64 * p).round() as usize] as f64+ };+ let n = self.jobs.max(1) as f64;+ let req = self.request_hits + self.request_misses;+ serde_json::json!({+ "jobs": self.jobs, "cancelled": self.cancelled, "previewJobs": self.preview, "prefetchJobs": self.prefetch,+ "requestHitRate": if req == 0 { 0.0 } else { self.request_hits as f64 / req as f64 },+ "decodeMs": {"mean": self.source_ms / n, "p50": pct(&|r| r.0, 0.5), "p95": pct(&|r| r.0, 0.95)},+ "renderMs": {"mean": self.render_ms / n, "p50": pct(&|r| r.1, 0.5), "p95": pct(&|r| r.1, 0.95)},+ "jobMsMean": self.job_ms / n,+ })+ }}/// Timing of one finished frame job (collected while [`FrameServer::set_profiling`] is on).@@ -278,6 +331,10 @@ pub fn prefetch_depth(speed: f64) -> i64 {/// [`PREROLL_TIMEOUT_S`]: otherwise the first frames after Play are due before any decoder had a/// chance to produce them (a seek decodes from the previous keyframe).pub const PREROLL_FRAMES: i64 = 6;++/// Seconds before a scrubbed-to frame whose frames a seek still decodes in full (see+/// [`FrameServer::request`]); earlier non-reference pictures are skipped on the way.+pub const SCRUB_KEEP_S: f64 = 2.0;pub const PREROLL_TIMEOUT_S: f64 = 0.5;/// Which frames playback asks for, given the per-frame render cost (s), the displayed frame rate@@ -307,6 +364,7 @@ impl FrameServer {records: Mutex::new(Vec::new()),render_cost: Mutex::new(0.0),workers: workers.max(1),+ stats: Mutex::new(FrameStats::default()),});let repaint: Arc<Mutex<Option<Box<dyn Fn() + Send + Sync>>>> = Arc::new(Mutex::new(None));#[cfg(not(target_arch = "wasm32"))]@@ -345,6 +403,26 @@ impl FrameServer {std::mem::take(&mut *self.shared.records.lock().unwrap_or_else(|e| e.into_inner()))}+ /// Cumulative job statistics (`perf.stats`).+ pub fn stats(&self) -> FrameStats {+ self.shared.stats.lock().unwrap_or_else(|e| e.into_inner()).clone()+ }++ /// Worker threads.+ pub fn workers(&self) -> usize {+ self.shared.workers+ }++ /// (cached images, their bytes, cached GPU plans, their bytes).+ pub fn cache_usage(&self) -> (usize, usize, usize, usize) {+ let (n, b) = {+ let c = self.shared.done.lock().unwrap_or_else(|e| e.into_inner());+ (c.map.len(), c.bytes)+ };+ let p = self.shared.plans.lock().unwrap_or_else(|e| e.into_inner());+ (n, b, p.map.len(), p.bytes)+ }+pub fn get(&self, k: &FrameKey) -> Option<Arc<Rgba>> {let mut c = self.shared.done.lock().unwrap_or_else(|e| e.into_inner());c.clock += 1;@@ -377,25 +455,41 @@ impl FrameServer {}/// Queue a job unless it is cached, queued or in flight.+ ///+ /// The frame on screen (`prio` 0: scrubbing, a seek) treats frames more than+ /// [`SCRUB_KEEP_S`] before it as not wanted: a decoder seeking from a keyframe skips their+ /// non-reference pictures, while nearby frames stay decoded (and cached) for scrubbing back.pub fn request(&self, key: FrameKey, time: Tick, scale: f32, project: &Arc<Project>, prio: u32) {- self.request_job(key, time, scale, project, prio, false);+ let late = (prio == 0).then(|| Tick::from_seconds_f64(SCRUB_KEEP_S));+ self.request_job(key, time, scale, project, prio, false, late);}- fn request_job(&self, key: FrameKey, time: Tick, scale: f32, project: &Arc<Project>, prio: u32, prefetch: bool) {+ fn request_job(&self, key: FrameKey, time: Tick, scale: f32, project: &Arc<Project>, prio: u32, prefetch: bool, catch_up: Option<Tick>) {+ let hit = || self.shared.stats.lock().unwrap_or_else(|e| e.into_inner()).request_hits += 1;if self.shared.done.lock().unwrap_or_else(|e| e.into_inner()).map.contains_key(&key)|| self.shared.plans.lock().unwrap_or_else(|e| e.into_inner()).map.contains_key(&key){+ hit();return;}if self.shared.in_flight.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|(k, c, _)| *k == key && !c.load(Ordering::Relaxed)) {+ hit();return;}let mut q = self.shared.queue.lock().unwrap_or_else(|e| e.into_inner());if let Some(j) = q.iter_mut().find(|j| j.key == key) {j.prio = j.prio.min(prio);j.prefetch &= prefetch;+ // the playhead only moves on: the newest (smallest) margin+ j.catch_up = match (j.catch_up, catch_up) {+ (Some(a), Some(b)) => Some(a.min(b)),+ (a, b) => a.or(b),+ };+ drop(q);+ hit();return;}+ self.shared.stats.lock().unwrap_or_else(|e| e.into_inner()).request_misses += 1;if prio == 0 {// A new frame on screen for this view replaces the one asked for before: scrubbing// asks for one per refresh, and without this the oldest position would decode@@ -408,7 +502,7 @@ impl FrameServer {}}}- q.push_back(Job { key, queued: Instant::now(), cancel: Default::default(), prefetch, time, scale, project: project.clone(), prio });+ q.push_back(Job { key, queued: Instant::now(), cancel: Default::default(), prefetch, catch_up, time, scale, project: project.clone(), prio });drop(q);self.shared.cv.notify_one();}@@ -426,13 +520,16 @@ impl FrameServer {let fps = rate.as_f64() * speed.abs().max(1.0) / step as f64;let (lead, stride) = if preroll { (1, 1) } else { playback_plan(self.render_cost(), fps, self.shared.workers) };if lead <= 1 {- self.request(key, rate.tick_of(key.frame), scale, project, 0);+ // the frame due now; once the clock runs, the frames before it are late+ self.request_job(key, rate.tick_of(key.frame), scale, project, 0, false, (!preroll && dir > 0).then_some(Tick::ZERO));}let ahead = prefetch_depth(speed);for i in 0..ahead {let f = key.frame + (lead + i * stride) * dir * step;if f >= 0 {- self.request_job(FrameKey { frame: f, ..key }, rate.tick_of(f), scale, project, i as u32 + 1, true);+ // forward play: frames before the playhead are late (reverse play skips nothing)+ let late = (!preroll && dir > 0).then(|| rate.tick_of(f) - rate.tick_of(key.frame));+ self.request_job(FrameKey { frame: f, ..key }, rate.tick_of(f), scale, project, i as u32 + 1, true, late);}}let (target, rev, cur) = (key.target, key.revision, key.frame);@@ -640,23 +737,25 @@ fn run_job(sh: &Shared, job: &Job, pool: &Arc<MediaPool>, services: &Arc<dyn Serlet _ = filmcraft_media::pending::take();let mut loading = false;let preview = filmcraft_media::cancel::with_cancel(&job.cancel, || {- if let Target::SequencePlan(seq) = job.key.target {- let (plan, pv) = plan_job(job, seq, pool, services, previews);- loading = filmcraft_media::pending::take();- if !job.cancel.load(Ordering::Relaxed) && !loading {- // Convert texels for upload here, not on the UI thread when the frame is shown.- let prepared = filmcraft_gpu::prepare(&plan);- sh.plans.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, GpuPlan { plan, prepared });- }- pv- } else {- let (img, pv) = render_job(job, pool, services, previews);- loading = filmcraft_media::pending::take();- if !job.cancel.load(Ordering::Relaxed) && !loading {- sh.done.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, Arc::new(img));+ filmcraft_media::cancel::with_catch_up(job.catch_up, || {+ if let Target::SequencePlan(seq) = job.key.target {+ let (plan, pv) = plan_job(job, seq, pool, services, previews);+ loading = filmcraft_media::pending::take();+ if !job.cancel.load(Ordering::Relaxed) && !loading {+ // Convert texels for upload here, not on the UI thread when the frame is shown.+ let prepared = filmcraft_gpu::prepare(&plan);+ sh.plans.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, GpuPlan { plan, prepared });+ }+ pv+ } else {+ let (img, pv) = render_job(job, pool, services, previews);+ loading = filmcraft_media::pending::take();+ if !job.cancel.load(Ordering::Relaxed) && !loading {+ sh.done.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, Arc::new(img));+ }+ pv}- pv- }+ })});let cancelled = job.cancel.load(Ordering::Relaxed);sh.in_flight.lock().unwrap_or_else(|e| e.into_inner()).retain(|(k, c, _)| !(*k == job.key && Arc::ptr_eq(c, &job.cancel)));@@ -670,6 +769,23 @@ fn run_job(sh: &Shared, job: &Job, pool: &Arc<MediaPool>, services: &Arc<dyn Ser*c = if *c == 0.0 { cost } else { *c * 0.8 + cost * 0.2 };}}+ {+ let job_wall = started.elapsed();+ let source = SOURCE_TIME.with(|s| s.get()).0;+ let (src_ms, render_ms) = (source.as_secs_f64() * 1e3, job_wall.saturating_sub(source).as_secs_f64() * 1e3);+ let mut st = sh.stats.lock().unwrap_or_else(|e| e.into_inner());+ st.jobs += 1;+ st.cancelled += cancelled as u64;+ st.preview += preview as u64;+ st.prefetch += job.prefetch as u64;+ st.source_ms += src_ms;+ st.render_ms += render_ms;+ st.job_ms += job_wall.as_secs_f64() * 1e3;+ if st.recent.len() >= FrameStats::RECENT {+ st.recent.pop_front();+ }+ st.recent.push_back((src_ms as f32, render_ms as f32));+ }if profiling {let (source_wall, source_cpu) = SOURCE_TIME.with(|s| s.get());let rec = JobRecord {diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 44e8e435c..07c718105 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -14,6 +14,7 @@ pub mod icons;pub mod links;pub mod menus;pub mod panels;+pub mod perf;pub mod state;pub mod theme;pub mod widgets;diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex cb5096bd8..948782462 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -122,6 +122,10 @@ pub fn panel_command_id(p: PanelKind) -> String {/// Execute a UI or engine command by id.pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {+ if id == "perf.stats" {+ // the engine's counters plus playback, frame workers and UI timings+ return Ok(crate::perf::stats(app));+ }if let Some(rest) = id.strip_prefix("window.panel.") {let p = PanelKind::from_name(rest).ok_or_else(|| format!("unknown panel `{rest}`"))?;app.show_panel(p);diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rsindex 317c79c7b..a5fe9009a 100644--- a/crates/ui-egui/src/panels/timeline.rs+++ b/crates/ui-egui/src/panels/timeline.rs@@ -39,6 +39,9 @@ pub struct TlState {snap_x: Option<f32>,pub peaks: Arc<Mutex<HashMap<ItemId, Arc<Vec<(f32, f32)>>>>>,peaks_pending: Arc<Mutex<Vec<ItemId>>>,+ /// Source peak of each cached peak list (keyed by the list's address), for the waveform+ /// display gain: scanning the whole source per clip per frame cost more than drawing.+ peak_max: HashMap<ItemId, (usize, f32)>,zoom_anchor: Option<(f64, f32)>,}@@ -49,6 +52,7 @@ impl TlState {pub fn reset_media_caches(&mut self) {self.peaks = Default::default();self.peaks_pending = Default::default();+ self.peak_max.clear();}}@@ -551,7 +555,15 @@ fn draw_waveform(app: &mut FilmcraftApp, p: &egui::Painter, body: Rect, it: &Traif clip.width() <= 0.0 {return;}- let peak = peaks.iter().fold(0f32, |m, (a, b)| m.max(a.abs()).max(b.abs()));+ let key = Arc::as_ptr(&peaks) as usize;+ let peak = match app.tl.peak_max.get(&it.item) {+ Some(&(k, v)) if k == key => v,+ _ => {+ let v = peaks.iter().fold(0f32, |m, (a, b)| m.max(a.abs()).max(b.abs()));+ app.tl.peak_max.insert(it.item, (key, v));+ v+ }+ };let gain = waveform_display_gain(peak, it.gain_db);let mut mesh = egui::Mesh::default();let dur_px = body.width().max(1.0);diff --git a/crates/ui-egui/src/perf.rs b/crates/ui-egui/src/perf.rsnew file mode 100644index 000000000..f990eb394--- /dev/null+++ b/crates/ui-egui/src/perf.rs@@ -0,0 +1,31 @@+//! `perf.stats` in the app: the engine's counters (decoder / GOP cache, jobs) plus playback+//! (shown / dropped frames), the frame workers (decode and render ms per job, request hit rate,+//! cache use), UI frame rate and process CPU time. Readable over the control channel+//! (`perf.stats`, or `engine.execute {"command": "perf.stats"}`) and MCP `command_run`.++use serde_json::{Value, json};++use crate::FilmcraftApp;++pub fn stats(app: &FilmcraftApp) -> Value {+ let mut v = filmcraft_engine::perf::stats(&app.session);+ let (shown, dropped) = app.playback.meter.counts();+ let (images, image_bytes, plans, plan_bytes) = app.frames.cache_usage();+ v["playback"] = json!({+ "playing": app.playback.playing,+ "speed": app.playback.speed,+ "shown": shown,+ "dropped": dropped,+ "dropRate": if shown + dropped == 0 { 0.0 } else { dropped as f64 / (shown + dropped) as f64 },+ "resolution": app.ui.program.res.label(),+ });+ let mut frames = app.frames.stats().to_json();+ frames["workers"] = json!(app.frames.workers());+ frames["queued"] = json!(app.frames.queue_len());+ frames["renderCostMs"] = json!(app.frames.render_cost() * 1e3);+ frames["cache"] = json!({"images": images, "imageMB": image_bytes as f64 / 1e6, "plans": plans, "planMB": plan_bytes as f64 / 1e6});+ v["frames"] = frames;+ v["ui"] = json!({"fps": app.fps, "frameMs": if app.fps > 0.0 { 1000.0 / app.fps as f64 } else { 0.0 }});+ v["process"] = json!({"cpuS": crate::frames::process_cpu_time().map(|d| d.as_secs_f64())});+ v+}diff --git a/crates/ui-egui/tests/perf_ui.rs b/crates/ui-egui/tests/perf_ui.rsnew file mode 100644index 000000000..55b52874c--- /dev/null+++ b/crates/ui-egui/tests/perf_ui.rs@@ -0,0 +1,79 @@+//! `perf.stats` through the control channel (headless app under `egui_kittest`): the control+//! method and the command id (what MCP `command_run` sends) both return the engine's decode+//! counters plus playback, frame-worker and UI timings.++use std::sync::mpsc::{Sender, channel};++use egui_kittest::Harness;+use filmcraft_engine::Session;+use filmcraft_ui_egui::FilmcraftApp;+use filmcraft_ui_egui::control::ControlRequest;+use serde_json::{Value, json};++struct Driver {+ harness: Harness<'static, FilmcraftApp>,+ tx: Sender<ControlRequest>,+}++impl Driver {+ fn demo() -> Self {+ let mut session = Session::default();+ session.execute("file.openDemoProject", json!({})).expect("demo project");+ let (tx, rx) = channel();+ let app = FilmcraftApp::new(session).with_control(rx);+ let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |_cc| app);+ let mut d = Driver { harness, tx };+ d.frames(4);+ d+ }++ fn frames(&mut self, n: usize) {+ for _ in 0..n {+ let ctx = self.harness.ctx.clone();+ let mut raw = std::mem::take(self.harness.input_mut());+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);+ *self.harness.input_mut() = raw;+ self.harness.step();+ }+ }++ fn ok(&mut self, method: &str, params: Value) -> Value {+ let (req, reply) = ControlRequest::new(method, params.clone());+ self.tx.send(req).unwrap();+ for _ in 0..600 {+ self.frames(1);+ if let Ok(v) = reply.try_recv() {+ assert_eq!(v["ok"], json!(true), "{method} {params}: {v}");+ return v["result"].clone();+ }+ }+ panic!("no reply to {method}");+ }+}++#[test]+fn perf_stats_reports_playback_frames_and_decode() {+ let mut d = Driver::demo();+ // let the Program monitor render a few frames on the workers+ for _ in 0..50 {+ d.frames(1);+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ let v = d.ok("perf.stats", json!({}));+ for (section, keys) in [+ ("decode", &["cacheHitRate", "samplesDecoded", "decodeMs"][..]),+ ("playback", &["shown", "dropped", "dropRate"][..]),+ ("frames", &["jobs", "cancelled", "requestHitRate", "workers", "queued"][..]),+ ("ui", &["fps", "frameMs"][..]),+ ] {+ for k in keys {+ assert!(!v[section][k].is_null(), "{section}.{k} missing in {v}");+ }+ }+ assert!(v["frames"]["decodeMs"]["p95"].is_number() && v["frames"]["renderMs"]["mean"].is_number(), "{v}");+ assert!(v["frames"]["jobs"].as_u64().unwrap() > 0, "the monitor rendered frames: {v}");+ assert_eq!(v["playback"]["playing"], json!(false));+ // the same through the command id (what MCP `command_run` sends in bridge mode)+ let c = d.ok("engine.execute", json!({"command": "perf.stats"}));+ assert!(c["frames"]["workers"].as_u64().unwrap() >= 1 && c["decode"].is_object(), "{c}");+}diff --git a/docs/architecture.md b/docs/architecture.mdindex 3402c3455..60bcdf9a5 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -230,7 +230,12 @@ file ──► codecs (MP4/MOV, MKV, audio) demux + decode, GOP-aware see`filmcraft_media::cancel`) jobs for frames the playhead has passed; a new on-screen framereplaces the one asked for before (scrubbing); Stop cancels the prefetch. When frames cost morethan the workers can render in real time (CPU effects), it starts only frames that can still be- on time and spaces them evenly (`playback_plan`). GPU plans carry their texels already+ on time and spaces them evenly (`playback_plan`). When decoding is what falls behind, each job+ tells its sources which frames are already late (`filmcraft_media::cancel::with_catch_up`: the+ playhead's distance, two seconds for a scrubbed-to frame), and the GOP cache skips+ non-reference pictures of late frames on the way (`VideoDecoder::is_disposable`, H.264+ `nal_ref_idc` 0 and HEVC sub-layer non-reference pictures; the wanted frame decodes exactly as+ before). `perf.stats` reports the counters. GPU plans carry their texels alreadyconverted for upload (`filmcraft_gpu::prepare`), so the UI thread only copies them.- **Audio clock.** The desktop app passes a cpal output (`apps/filmcraft/src/audio.rs`) to the UI as`AudioOut`. While playing, the samples played by the sound card drive the playhead and video follows.diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex b4ad1381d..c7995c146 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -29,6 +29,7 @@ Methods (handlers in `crates/ui-egui/src/control.rs`):| `ui.playback` | `{action: play|stop|toggle, speed?}` | || `ui.screenshot` | `{path?, panel?}` | PNG of the window or one panel; fails after 10 s when no frame is presented (window hidden, display asleep) || `ui.resize`, `ui.focus`, `app.quit` | | `ui.focus` is the only request that activates the app and takes keyboard focus |+| `perf.stats` | – | performance counters (also the command `perf.stats`, so `engine.execute` and MCP `command_run` reach it; headless sessions return the engine part). `decode`: GOP-cache requests / hits / `cacheHitRate`, decoder seeks, samples decoded and skipped while catching up, decoder ms (total and per sample); `playback`: playing, shown / dropped frames and `dropRate` of the current or last play, resolution; `frames`: frame-worker jobs, cancelled, `requestHitRate`, `decodeMs` / `renderMs` (mean, p50, p95 of the last 256 jobs), queue, render-cost estimate, cache use; `ui`: fps and frame ms; `process`: CPU seconds; `media`, `jobs`. Counters are cumulative: diff two readings to measure an interval ([performance.md](performance.md)) |**Focus.** Driving the app never steals the user's keyboard. Started with `--control`, the app openswithout activating itself. UI requests and screenshots that need a rendered frame bring the windowdiff --git a/docs/performance.md b/docs/performance.mdnew file mode 100644index 000000000..3e2063eeb--- /dev/null+++ b/docs/performance.md@@ -0,0 +1,127 @@+# Performance++`cargo xtask bench` measures the whole app headlessly and writes `target/bench/bench-<label>.json`+and `.md` (options and sections: [testing.md](testing.md) §5). Agents read live counters with+`perf.stats` ([control-protocol.md](control-protocol.md)).++**Read the numbers with the load average.** These results come from a shared Apple M4 Pro+(14 cores, 48 GB, macOS 15 / Darwin 24.6) with parallel agent builds running: load average+**75–200** during every run below. Wall-clock columns (fps, shown/dropped frames, seek latency)+swing by 2–5× between back-to-back runs at that load and are only comparable within one run. CPU+time per frame, samples decoded and skipped, and peak RSS are much less sensitive, and are what+the before/after comparison relies on. Baseline = commit `457aca1` (the harness on unchanged+code); after = M4.8. Runs alternated base / after (2 rounds each, 2026-10-02).++## Results (M4.8, before → after)++### Decode (every frame through the media stack: container, GOP cache, decoder, conversion)++CPU ms per frame (both rounds; lower is better). fps is the best of the run at that moment's load.++| codec | size | CPU ms/frame before | after | fps before → after (same-round pairs) |+|---|---|---|---|---|+| H.264 | 1080p | 43.4 / 43.7 | 48.2 / 46.1 | 101, 105 → 51, 34 (load 99 → 127) |+| H.264 | 2160p | 169 / 166 | 171 / 178 | 17, 31 → 16, 9 |+| **HEVC** | 1080p | 80.5 / 76.4 | **31.4 / 34.5** | 25, 58 → 69, 41 |+| **HEVC** | 2160p | 325 / 314 | **122 / 136** | 8.2, 12 → 17, 11 |+| VP9 | 1080p / 2160p | 39.7 / 137.6 | 36.5 / 136.8 | 18 / 12 → 18 / 7.8 |+| AV1 | 1080p / 2160p | 20.2 / 78.2 | 19.7 / 72.6 | 106 / 23 → 50 / 9.4 |+| ProRes 422 HQ | 1080p / 2160p | 23.6 / 89.0 | 23.2 / 86.7 | 59 / 28 → 34 / 15 |++On a quieter moment earlier in the session (load ~70) the same binaries decoded H.264 at 100 fps+(1080p) / 24 fps (2160p), AV1 131 / 44 fps and ProRes 202 / 49 fps.++### Seeking (cold seek through the media stack, 12 random targets, modes interleaved, load ~150)++| fixture (GOP 250) | full decode from keyframe | skip non-reference > 2 s before (scrub) | skip all late non-reference (playback catch-up) |+|---|---|---|---|+| H.264 1080p | 1405 ms, 3.3 s CPU | 1276 ms, 3.1 s CPU | **789 ms, 2.3 s CPU** |+| H.264 2160p | 3394 ms, 8.5 s CPU | 2828 ms, 8.4 s CPU | **2274 ms, 6.3 s CPU** |+| HEVC 2160p | 4091 ms, 17.8 s CPU | 3058 ms, 12.3 s CPU | **2512 ms, 9.8 s CPU** |++The target frame is identical in every mode (only pictures nothing references are left out).++### Program-monitor playback (8 s, GPU path)++| scenario | shown/dropped before | after | CPU ms/frame before → after | non-ref samples skipped |+|---|---|---|---|---|+| H.264 1080p | 192/0, 192/0 | 191/1, 191/1 | 55 → 55 | 0 (keeps up) |+| 3 × 1080p stacked | 192/0, 190/2 | 188/4, 185/7 | 120 → 128 | 0 |+| H.264 2160p Full | 22/170, 192/0 | 0/192, 0/192 | 183 → **87** | 39–52 |+| H.264 2160p Half | 180/12, 192/0 | 0/192, 0/192 | 198 → **102** | 46–49 |+| HEVC 2160p Full | 0/192, 0/192 | 0/192, 0/192 | 164 → **90** | 88 |+| HEVC 2160p Half | 0/192, 0/192 | 0/192, 0/192 | 160 → **97** | 33–92 |++Shown/dropped at 2160p is decided by the load at the moment (base round 2 happened to play 192/0+at a quiet minute; a later three-way run at load 175–195 gave 0–21 shown for every binary, and+143/49 for HEVC once). CPU per displayed second halved at 2160p: frames that are already late are+no longer fully decoded, and HEVC decodes 2.5× cheaper.++### Scrubbing (24 random seeks + 8 playhead drags through the monitor's request path)++| scenario | seek p50 / p95 ms before | after | drag-stop p50 ms before → after |+|---|---|---|---|+| H.264 1080p | 357 / 940, 582 / 1535 | 840 / 1567, 770 / 1389 | 27, 62 → 281, 103 |+| H.264 2160p | 1063 / 2377, 1499 / 3028 | 2445 / 5357, 2390 / 4562 | 288, 513 → 560, 834 |+| HEVC 2160p | 130 / 4100 (9 timeouts), 318 / 1397 | 2466 / 6441, 2476 / 7596 (0 timeouts) | 9, 3872 → 462, 1893 |++These runs coincided with load rising from 99 to 170 for "after". A later interleaved three-way+run (base / after with catch-up disabled / after) at load 80–200 gave H.264 1080p seek p50 345 /+712 / 572 ms then 379 / 389 / 461 ms, and H.264 2160p 913 / 1312 / 2105 then 1946 / 931 / 840 ms:+within the noise. The cold-seek table above is the load-independent comparison.++### Timeline UI (1000 clips on 20 tracks, 1920×1080 window, `egui_kittest`)++| view | update p50 / p95 ms before | after | tessellate p50 ms | wgpu render p50 ms (incl. readback) | vertices |+|---|---|---|---|---|---|+| fit (all 1000 clips) | 3.1 / 4.9, 3.4 / 5.7 | 2.9 / 4.5, 2.9 / 3.3 | 0.3 | 15 | 35.7 k |+| zoomed, scrolling | 2.8 / 3.8, 2.8 / 4.8 | 2.9 / 4.9, 2.6 / 6.8 | 0.2 | 15 | 29.2 k |++The timeline is not a bottleneck: the whole app frame (all panels) costs ~3 ms with 1000 clips+visible; it already culls clips outside the view. The waveform display gain no longer rescans the+whole source's peaks for every clip every frame (cached per peak list).++### Export (8 s of 1080p23.976 H.264 + AAC source)++| format | fps before → after | CPU ms/frame before → after |+|---|---|---|+| H.264 + AAC | 10.6, 5.8 → 10.2, 11.9 | 256 → 250 |+| ProRes 422 | 4.7, 3.0 → 6.3, 9.6 | 249 → 232 |++Profile (`sample`): H.264 export is ~45 % encoder, ~30 % decoding the noisy 45 Mbit/s source,+~25 % CPU compositing; ProRes export spends most in `prores::encode::slice_bits` /+`choose_quantisers` (rate search), then source decode and compositing. Not changed in M4.8.++### Project save / open (5 sequences × 1000 clips, 3.7 MB)++save 24 / 68 → 36 / 21 ms, open 26 / 82 → 21 / 19 ms (p50 of 3; noise).++### Peak RSS per section (MB)++decode 2642 / 2925 → 2506 / 2064; playback 5246 / 7903 → 3379 / 3121; scrub 4205 / 5022 →+5390 / 4183; timeline 626 / 650 → 660 / 675; export 2367 / 2286 → 2606 / 2619; project 114 / 136 →+124 / 133.++## What M4.8 changed++1. **HEVC inverse transform** (largest hotspot: >50 % of HEVC decode CPU). Sums contiguous basis+ rows scaled by non-zero coefficients, size as a const generic so loops vectorise; bit-exact+ (exact integer sums), tested against the direct matrix product on random blocks and by the+ ffmpeg conformance fixtures. **SAO edge offset** gets a check-free inner loop. HEVC CPU per+ frame −60 %.+2. **No redundant plane copies**: H.264 / HEVC / VP9 pictures are moved into `VideoFrame`s instead+ of copied (12 MB per 2160p frame; HEVC 10-bit also lost a per-sample widening pass).+3. **Catch-up decoding**: frame jobs carry how far before their frame the playhead is+ (`filmcraft_media::cancel::with_catch_up`); the GOP cache skips non-reference samples of late+ frames (`VideoDecoder::is_disposable`: H.264 `nal_ref_idc` 0, HEVC sub-layer non-reference+ pictures of the top temporal layer). Scrub requests keep the last 2 s fully decoded so dragging+ back stays cached. The wanted frame is decoded exactly as before; a later request for a skipped+ frame re-seeks. ~50 % of the fixtures' pictures are non-reference.+4. **`perf.stats`** (engine query + UI/control method): decode counters (cache hit rate, seeks,+ samples decoded / skipped, decoder ms), playback shown / dropped, frame-worker decode / render+ ms (p50 / p95), request hit rate, cache use, UI fps, process CPU.+5. **Timeline**: waveform source peak cached.++Not feasible / not done: reduced-resolution decode for H.264 / HEVC (inter prediction needs+full-resolution references, so it cannot be bit-exact; ½/¼ playback already decimates after+decode); AV1 internals untouched (measured only); export encoders not optimised.diff --git a/docs/testing.md b/docs/testing.mdindex 3a6c49bf4..eaef895e6 100644--- a/docs/testing.md+++ b/docs/testing.md@@ -194,6 +194,18 @@ engine behaviour without a window.| Encoder speed / PSNR / bitrate | `cargo run --release -p filmcraft-h264enc --example h264enc_synth -- …` || Decode a real file through the media stack | `cargo run --release -p filmcraft-cli -- bench-decode file.mp4 --frames 120` || Coding-tool coverage of the fixtures | `cargo test --release -p filmcraft-h264 --test conformance coverage_report -- --ignored --nocapture` (same for `hevc`) |+| **Whole-app suite**: decode fps per codec, playback, scrubbing, timeline UI, export, project save/open, peak RSS | `cargo xtask bench` ([performance.md](performance.md)) |++`cargo xtask bench` (the example `crates/ui-egui/examples/bench/`) runs six sections, each in its+own process under `/usr/bin/time` so peak RSS is per section: `decode` (every frame of 1080p and+2160p H.264, HEVC, VP9, AV1 and ProRes through the media stack), `playback` (the scenarios below),+`scrub` (random seeks and playhead drags: time until the exact frame is on screen), `timeline`+(the real app under `egui_kittest` with a 1000-clip / 20-track sequence: update, tessellation and+wgpu render ms per frame), `export` (H.264 + AAC and ProRes) and `project` (save / open 5000 clips).+Options: `--sections decode,scrub`, `--only <substring>` (fixture or scenario), `--repeat N`,+`--quick`, `--cpu`, `--label NAME` (output `target/bench/bench-<label>.{json,md}`),+`--section NAME --json FILE` (one section in-process, e.g. under a profiler). Fixtures are made+with ffmpeg in `target/fixtures/playback/` (or `$FILMCRAFT_FIXTURES/playback`).The perf tests check bit-exactness before they time anything. Results go in the crate README'sperformance table, with machine and thread count. Headline numbers go in