Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

Video playback without the hitch every 300 frames: the Mac decoder's reader is recycled at a keyframe play has reached (a cursor stepped back to it, nothing decoded), so it no longer decodes a GOP first; frame 299 went from 46 ms (1080p60) and 163 ms (4K30, 250-frame GOPs) to about 20 ms at the next keyframe, open-GOP HEVC too, every frame's time checked (io/apple/tests/play_timing.rs). The page's video picture shares the frame's pixels instead of copying them again (Shane 11-09: playback starts to get weird)

shinyobjectze1b7a97ebd78
diff --git a/io/apple/src/decode.rs b/io/apple/src/decode.rs
index 7b5e35e2..38c48ba0 100644
--- a/io/apple/src/decode.rs
+++ b/io/apple/src/decode.rs
@@ -19,6 +19,8 @@ pub(crate) struct Decoder {
pub(crate) surface: bool,
/// the presentation times, read once from the compressed samples (for index_at)
pub(crate) sample_pts: Option<Vec<f64>>,
+ /// the edit list's shift from the track's sample times to the reader's (as read_pts and vtseek have it), read once
+ pub(crate) shift: Option<f64>,
pub(crate) watch: Watch,
/// the file, for a seek on VideoToolbox directly
pub(crate) path: std::path::PathBuf,
@@ -88,7 +90,13 @@ impl Drop for Decoder {
}
impl Decoder {
+ /// A fresh reader for the frame at `t`, started half a frame before it.
pub(crate) fn restart(&mut self, t: f64) -> R<()> {
+ self.restart_from((t - 0.5 / self.info.fps).max(0.0))
+ }
+
+ /// A fresh reader whose time range starts at `start`: it decodes from the keyframe at or before it.
+ pub(crate) fn restart_from(&mut self, start: f64) -> R<()> {
// the old reader's VideoToolbox session goes now, not whenever its last reference does (and the watch lets go
// of it first)
self.watch.set(None);
@@ -135,9 +143,8 @@ impl Decoder {
};
let reader = AVAssetReader::assetReaderWithAsset_error(&self.asset)
.map_err(|e| format!("AVAssetReader: {}", e.localizedDescription()))?;
- let start = (t - 0.5 / self.info.fps).max(0.0);
reader.setTimeRange(CMTimeRange {
- start: CMTime::with_seconds(start, 600),
+ start: CMTime::with_seconds(start, 1_000_000),
duration: kCMTimePositiveInfinity,
});
reader.addOutput(&out);
@@ -396,11 +403,48 @@ impl Decoder {
}
}
+ /// The latest keyframe at or before `t`, in the reader's times: a cursor at `t` stepped back in decode order to a
+ /// sync sample shown by then (a GOP's steps or two, nothing decoded; an open GOP's keyframe is decoded before the
+ /// leading frames shown ahead of it, so one found first may not be due yet); None when the track has no cursor.
+ pub(crate) fn key_before(&mut self, t: f64) -> Option<f64> {
+ objc2::rc::autoreleasepool(|_| unsafe {
+ let media = AVMediaTypeVideo?;
+ #[allow(deprecated)]
+ let tracks = self.asset.tracksWithMediaType(media);
+ let track = tracks.firstObject()?;
+ let shift = *self.shift.get_or_insert_with(|| {
+ track.segments().iter().find(|s| !s.isEmpty()).map(|s| s.timeMapping()).map(|m| m.target.start.seconds() - m.source.start.seconds()).unwrap_or(0.0)
+ });
+ let cur = track.makeSampleCursorWithPresentationTimeStamp(CMTime::with_seconds(t - shift, 1_000_000))?;
+ for _ in 0..2000 {
+ let pts = cur.presentationTimeStamp().seconds() + shift;
+ if cur.currentSampleSyncInfo().sampleIsFullSync.as_bool() && pts <= t {
+ return Some(pts);
+ }
+ if cur.stepInDecodeOrderByCount(-1) != -1 {
+ return None;
+ }
+ }
+ None
+ })
+ }
+
pub(crate) fn frame_at_once(&mut self, t: f64) -> R<Slot> {
let eps = 1e-4;
if self.since_restart >= RECYCLE_FRAMES {
- self.restart(t)?;
- self.cur = self.read()?;
+ // a fresh reader (it bounds VideoToolbox's memory) started at a keyframe play has reached, so it decodes
+ // nothing it won't show. Started between keyframes, it first decoded the GOP up to there: in play a hitch
+ // every 300 frames (46 ms at 1080p60, 163 ms at 4K30 with 250-frame GOPs; tests/play_timing.rs). Until a
+ // keyframe comes the old reader goes on, up to twice as long.
+ let held = self.cur.as_ref().map(|c| c.0.pts);
+ let key = held.and_then(|h| self.key_before(t + eps).filter(|&k| k > h + eps));
+ if let Some(k) = key {
+ self.restart_from(k + 1e-4)?;
+ self.cur = self.read()?;
+ } else if self.since_restart >= 2 * RECYCLE_FRAMES {
+ self.restart(t)?;
+ self.cur = self.read()?;
+ }
}
let usable = match (&self.cur, &self.reader) {
(Some(c), Some(_)) => c.0.pts <= t + eps && t < c.0.pts + 2.0,
diff --git a/io/apple/src/lib.rs b/io/apple/src/lib.rs
index 221cd338..2b51de6d 100644
--- a/io/apple/src/lib.rs
+++ b/io/apple/src/lib.rs
@@ -153,6 +153,7 @@ fn open_decoder(path: &Path) -> R<Decoder> {
nv12: false,
surface: false,
sample_pts: None,
+ shift: None,
watch: Watch::new(),
path: path.to_path_buf(),
seeker: None,
diff --git a/io/apple/tests/play_timing.rs b/io/apple/tests/play_timing.rs
new file mode 100644
index 00000000..7d74545b
--- /dev/null
+++ b/io/apple/tests/play_timing.rs
@@ -0,0 +1,24 @@
+//! How long each frame of playback takes from the Mac decoder (frame_at at each frame's time, as the live player asks),
+//! across the reader's recycle: RAEA_PLAY_TIMING=FILE.mp4 cargo test --release -p raea-io-apple --test play_timing -- --nocapture
+#![cfg(target_vendor = "apple")]
+use raea_io_codec::Backend;
+
+#[test]
+fn play_timing() {
+ let Ok(path) = std::env::var("RAEA_PLAY_TIMING") else { return eprintln!("RAEA_PLAY_TIMING unset: skipped") };
+ let mut d = raea_io_apple::Apple.open_video(std::path::Path::new(&path)).expect("open");
+ let fps = d.info().fps;
+ let n = ((d.info().duration * fps) as usize).min(420);
+ let mut ms = Vec::with_capacity(n);
+ for i in 0..n {
+ let t0 = std::time::Instant::now();
+ let f = d.frame_at((i as f64 + 0.5) / fps).expect("frame");
+ // the frame showing at that time, never one from before a recycle or after it
+ assert!((f.pts - i as f64 / fps).abs() < 0.5 / fps, "frame {i}: pts {:.4} for {:.4}", f.pts, i as f64 / fps);
+ ms.push(t0.elapsed().as_secs_f64() * 1e3);
+ }
+ let mut sorted = ms.clone();
+ sorted.sort_by(f64::total_cmp);
+ let worst: Vec<_> = { let mut w: Vec<_> = ms.iter().enumerate().collect(); w.sort_by(|a, b| b.1.total_cmp(a.1)); w.into_iter().take(5).map(|(i, m)| format!("#{i} {m:.1} ms")).collect() };
+ eprintln!("{path}: {n} frames at {fps} fps (budget {:.1} ms): median {:.1} ms, p95 {:.1} ms, worst {}", 1e3 / fps, sorted[n / 2], sorted[n * 95 / 100], worst.join(", "));
+}
diff --git a/runtime/dom/media/src/lib.rs b/runtime/dom/media/src/lib.rs
index 8434b59d..0fdb4cae 100644
--- a/runtime/dom/media/src/lib.rs
+++ b/runtime/dom/media/src/lib.rs
@@ -153,10 +153,11 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mu
}
if redraw && m.video && draw {
let pic = match (&m.poster, m.seeked) {
- (Some(p), false) => poster_image(p),
+ (Some(p), false) => poster_image(p).map(|(w, h, px)| (w, h, Arc::new(px))),
_ => None,
}
- .or_else(|| m.frame.as_ref().map(|(w, h, px)| (*w, *h, px.as_ref().clone())));
+ // the frame's pixels shared, not copied again (a 4K frame is 33 MB)
+ .or_else(|| m.frame.as_ref().map(|(w, h, px)| (*w, *h, px.clone())));
if let (Some((w, h, px)), Some(n)) = (pic, nodes.by_id.get(&id)) {
set_image(doc, *n, w, h, px);
}
@@ -189,10 +190,10 @@ fn poster_image(src: &str) -> Option<(u32, u32, Vec<u8>)> {
}
/// Node `n` drawn as an image: `rgba` as its raster, its layout made again for the picture's size.
-fn set_image(doc: &mut BaseDocument, n: blitz_dom::NodeId, w: u32, h: u32, rgba: Vec<u8>) {
+fn set_image(doc: &mut BaseDocument, n: blitz_dom::NodeId, w: u32, h: u32, rgba: Arc<Vec<u8>>) {
let Some(node) = doc.get_node_mut(n) else { return };
let Some(el) = node.element_data_mut() else { return };
- el.special_data = SpecialElementData::Image(Box::new(ImageData::Raster(RasterImageData { width: w, height: h, data: vello::peniko::Blob::new(Arc::new(rgba)) })));
+ el.special_data = SpecialElementData::Image(Box::new(ImageData::Raster(RasterImageData { width: w, height: h, data: vello::peniko::Blob::new(rgba) })));
node.clear_layout_cache();
node.insert_damage(raea_sys_page::ALL_DAMAGE);
node.mark_ancestors_dirty();