diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs
index ab27aec..e4f96ba 100644
--- a/crates/app/src/main.rs
+++ b/crates/app/src/main.rs
@@ -1,48 +1,114 @@
use std::sync::Arc;
-use std::sync::mpsc::{Receiver, TryRecvError};
+use std::sync::mpsc::TryRecvError;
+use std::time::Instant;
-use engine::{DecodeSession, Frame};
+use engine::{Frame, PlaybackSession};
use gpui::{
- App, Application, Bounds, Context, RenderImage, TitlebarOptions, Window, WindowBounds,
- WindowOptions, div, img, prelude::*, px, rgb, size,
+ App, Application, Bounds, Context, FocusHandle, KeyDownEvent, RenderImage, TitlebarOptions,
+ Window, WindowBounds, WindowOptions, div, img, prelude::*, px, rgb, size,
};
struct Player {
- rx: Receiver,
+ session: PlaybackSession,
+ /// Timeline seconds -> frame index, so the clock can be compared to what
+ /// the decoder hands over.
+ fps: f64,
image: Option>,
- finished: bool,
+ /// A frame that arrived before its time; shown on the tick it comes due.
+ held: Option,
+ /// The decoder's channel closed. Frames may still be waiting in `held`.
+ eos: bool,
+ /// Last frame shown; nothing left to animate.
+ done: bool,
+ /// Playback was started once, on the first render. Space owns it after that.
+ launched: bool,
+ displayed: u32,
+ dropped: u32,
+ /// Wall clock of the first displayed frame -- the real-speed measurement.
+ started: Option,
+ focus: FocusHandle,
}
impl Player {
- /// Takes at most one frame per rendered frame; the decoder's channel is
- /// bounded so it simply waits for us.
+ /// Catches the display up to the clock: everything already due is taken off
+ /// the channel and only the last of them is shown, which *is* the
+ /// drop-when-behind policy. A frame that is not due yet waits in `held`.
fn pump(&mut self, window: &mut Window) {
- match self.rx.try_recv() {
- Ok(frame) => {
- let buf =
- image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)
- .expect("frame buffer sized width*height*4");
- let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
- if let Some(old) = self.image.replace(next) {
- // Every RenderImage gets a fresh id and its own atlas tile:
- // without this the sprite atlas grows for the whole video.
- let _ = window.drop_image(old);
- }
+ let target = self.session.now() * self.fps;
+ let mut newest: Option = None;
+ loop {
+ let frame = match self.held.take() {
+ Some(frame) => frame,
+ None => match self.session.frames().try_recv() {
+ Ok(frame) => frame,
+ Err(TryRecvError::Empty) => break,
+ Err(TryRecvError::Disconnected) => {
+ self.eos = true;
+ break;
+ }
+ },
+ };
+ if f64::from(frame.index) <= target {
+ self.dropped += u32::from(newest.is_some());
+ newest = Some(frame);
+ } else {
+ self.held = Some(frame);
+ break;
+ }
+ }
+
+ if let Some(frame) = newest {
+ self.displayed += 1;
+ self.started.get_or_insert_with(|| {
+ eprintln!("first frame displayed (index {})", frame.index);
+ Instant::now()
+ });
+ let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)
+ .expect("frame buffer sized width*height*4");
+ let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
+ if let Some(old) = self.image.replace(next) {
+ // Every RenderImage gets a fresh id and its own atlas tile:
+ // without this the sprite atlas grows for the whole video.
+ let _ = window.drop_image(old);
}
- Err(TryRecvError::Empty) => {}
- Err(TryRecvError::Disconnected) => self.finished = true,
+ }
+
+ if self.eos && self.held.is_none() && !self.done {
+ self.done = true;
+ let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
+ eprintln!(
+ "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
+ self.displayed,
+ self.dropped,
+ self.session.now()
+ );
}
}
}
impl Render for Player {
- fn render(&mut self, window: &mut Window, _cx: &mut Context) -> impl IntoElement {
+ fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement {
+ // Starts on launch: the session opens paused so the clock begins with
+ // the first rendered frame rather than with the process (which would
+ // charge window setup to the timeline and drop the frames it covers).
+ if !std::mem::replace(&mut self.launched, true) {
+ self.session.play();
+ }
+ self.session.tick();
self.pump(window);
- if !self.finished {
+ if !self.done {
window.request_animation_frame();
}
div()
+ .track_focus(&self.focus)
+ .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, _| {
+ // `is_held` filters auto-repeat, which would otherwise toggle
+ // playback many times a second.
+ if event.keystroke.key == "space" && !event.is_held {
+ this.session.toggle();
+ }
+ }))
.size_full()
.bg(rgb(0x101010))
.flex()
@@ -61,13 +127,14 @@ fn main() {
eprintln!("usage: app ");
std::process::exit(2);
};
- let (meta, rx) = match DecodeSession::open(&path) {
+ let session = match PlaybackSession::open(&path) {
Ok(v) => v,
Err(e) => {
eprintln!("cannot open {path}: {e}");
std::process::exit(1);
}
};
+ let meta = *session.meta();
println!(
"{path}: {}x{} @ {:.2} fps, {} samples",
meta.width, meta.height, meta.frame_rate, meta.frame_count
@@ -88,12 +155,24 @@ fn main() {
}),
..Default::default()
},
- |_, cx| {
- cx.new(|_| Player {
- rx,
+ |window, cx| {
+ let player = cx.new(|cx| Player {
+ session,
+ fps: meta.frame_rate,
image: None,
- finished: false,
- })
+ held: None,
+ eos: false,
+ done: false,
+ launched: false,
+ displayed: 0,
+ dropped: 0,
+ started: None,
+ focus: cx.focus_handle(),
+ });
+ // Nothing else takes focus, and without it the key listener
+ // above is never reached.
+ window.focus(&player.read(cx).focus);
+ player
},
)
.unwrap();
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 0f5e45f..8e1561a 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -7,9 +7,11 @@ pub mod convert;
pub mod decode;
pub mod demux;
pub mod hw;
+pub mod playback;
pub use audio::{AudioChunk, AudioMeta, AudioSession};
pub use clock::PlaybackClock;
+pub use playback::PlaybackSession;
pub use decode::{DecodeSession, Frame};
pub use demux::VideoMeta;
diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs
new file mode 100644
index 0000000..1cb53c5
--- /dev/null
+++ b/crates/engine/src/playback.rs
@@ -0,0 +1,217 @@
+//! One file, one timeline: the decode workers, the audio output and the master
+//! clock wired together so a front-end only has to render and call [`tick`].
+//!
+//! [`tick`]: PlaybackSession::tick
+//!
+//! Everything degrades to silent-but-correct: no audio track, no plugin, no
+//! PipeWire daemon and an unusable format all end up in [`ClockSource::Wall`],
+//! where the video is paced by real time instead of by the device.
+//!
+//! Drift policy stays with the caller -- this type answers "what time is it",
+//! the renderer decides which frame that means.
+
+use std::path::Path;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::mpsc::Receiver;
+use std::sync::{Arc, Mutex};
+use std::thread;
+use std::time::Duration;
+
+use crate::ao::AoSession;
+use crate::audio::{AudioChunk, AudioSession};
+use crate::clock::{ClockSource, PlaybackClock};
+use crate::decode::{DecodeSession, Frame};
+use crate::demux::VideoMeta;
+
+/// How long the feeder waits out a full ring. The ring holds a second, so this
+/// only has to be short next to that; it costs one wakeup per 10 ms of audio.
+const RING_FULL_WAIT: Duration = Duration::from_millis(10);
+
+/// The output half of a session: the device, plus what the feeder has handed it.
+struct Audio {
+ /// Shared because `write` runs on the feeder thread while `position` and
+ /// `set_active` are called from the caller's. The plugin serialises those
+ /// itself (atomics and a channel), but the lock is what makes it sayable in
+ /// Rust and it is never held for more than a memcpy.
+ ao: Arc>,
+ sample_rate: u32,
+ channels: u64,
+ /// Interleaved samples accepted by the device so far.
+ fed: Arc,
+ /// The decoder ran out and `fed` is final.
+ fed_all: Arc,
+}
+
+impl Audio {
+ /// Whether the device has played everything there will ever be, i.e. the
+ /// audio clock is about to stop meaning anything.
+ fn played_out(&self, position: i64) -> bool {
+ self.fed_all.load(Ordering::Acquire)
+ && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed)
+ }
+}
+
+/// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`].
+pub struct PlaybackSession {
+ meta: VideoMeta,
+ frames: Receiver,
+ clock: PlaybackClock,
+ audio: Option