forge
Explore
Log in

Don't you dare go Hollow

Seek — rebuild workers, epoch-guarded feeder, clock re-anchor

Browse files at this commit

e4ca3bd2b6f19a4ffe170a2766d0d952d2196999Ahmet Kaan GümüşParent: 96ae365
  • feat
    • seek — rebuild workers, epoch-guarded feeder, clock re-anchor
Show full message
✨ feat(playback): seek — rebuild workers, epoch-guarded feeder, clock re-anchor

PlaybackSession::seek(secs) replaces both decode workers instead of
steering them: a fresh channel cannot hold a stale frame, and it works
after EOF where the old workers have already exited.

The audio device stays open across a seek. An epoch counter, bumped and
flushed while holding the device lock and re-checked by the feeder inside
that same lock right before every write, is what stops a superseded feeder
from landing stale PCM behind the flush. `fed` is re-based on the device
position, which keeps counting across a flush, so the audio-EOF test stays
exact.
crates/engine/src/playback.rsmodified+123 -26
@@ -10,7 +10,7 @@
10 //! Drift policy stays with the caller -- this type answers "what time is it",10 //! Drift policy stays with the caller -- this type answers "what time is it",
11 //! the renderer decides which frame that means.11 //! the renderer decides which frame that means.
12 12
13-use std::path::Path;13+use std::path::{Path, PathBuf};
14 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};14 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15 use std::sync::mpsc::Receiver;15 use std::sync::mpsc::Receiver;
16 use std::sync::{Arc, Mutex};16 use std::sync::{Arc, Mutex};
@@ -28,6 +28,8 @@ use crate::demux::VideoMeta;
28 const RING_FULL_WAIT: Duration = Duration::from_millis(10);28 const RING_FULL_WAIT: Duration = Duration::from_millis(10);
29 29
30 /// The output half of a session: the device, plus what the feeder has handed it.30 /// The output half of a session: the device, plus what the feeder has handed it.
31+/// Cloned into the feeder thread; every field that matters is shared.
32+#[derive(Clone)]
31 struct Audio {33 struct Audio {
32 /// Shared because `write` runs on the feeder thread while `position` and34 /// Shared because `write` runs on the feeder thread while `position` and
33 /// `set_active` are called from the caller's. The plugin serialises those35 /// `set_active` are called from the caller's. The plugin serialises those
@@ -44,6 +46,9 @@ struct Audio {
44 /// so it can never satisfy [`Audio::played_out`] -- the flag is what lets46 /// so it can never satisfy [`Audio::played_out`] -- the flag is what lets
45 /// [`PlaybackSession::tick`] hand the timeline to wall time instead.47 /// [`PlaybackSession::tick`] hand the timeline to wall time instead.
46 died: Arc<AtomicBool>,48 died: Arc<AtomicBool>,
49+ /// Bumped by every seek. A feeder only owns the device while this still
50+ /// matches the value it started with; see [`feed`].
51+ epoch: Arc<AtomicU64>,
47 }52 }
48 53
49 impl Audio {54 impl Audio {
@@ -53,12 +58,35 @@ impl Audio {
53 self.fed_all.load(Ordering::Acquire)58 self.fed_all.load(Ordering::Acquire)
54 && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed)59 && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed)
55 }60 }
61+
62+ /// Starts a feeder for the current epoch, draining `rx` into the device.
63+ /// `false` if the thread would not start, i.e. nothing will ever be fed.
64+ fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool {
65+ let me = self.clone();
66+ let epoch = self.epoch.load(Ordering::Acquire);
67+ thread::Builder::new()
68+ .name("audio-feed".into())
69+ .spawn(move || {
70+ feed(rx, &me, epoch);
71+ // Only the current feeder gets to declare the end of the audio:
72+ // a superseded one is finished, the stream is not.
73+ if me.epoch.load(Ordering::Acquire) == epoch {
74+ me.fed_all.store(true, Ordering::Release);
75+ }
76+ })
77+ .is_ok()
78+ }
56 }79 }
57 80
58 /// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`].81 /// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`].
59 pub struct PlaybackSession {82 pub struct PlaybackSession {
83+ /// Kept for [`PlaybackSession::seek`], which reopens both workers.
84+ path: PathBuf,
60 meta: VideoMeta,85 meta: VideoMeta,
61 frames: Receiver<Frame>,86 frames: Receiver<Frame>,
87+ /// Stops the current decode worker, so an abandoned one cannot outlive a
88+ /// seek by more than one access unit.
89+ cancel: Arc<AtomicBool>,
62 clock: PlaybackClock,90 clock: PlaybackClock,
63 audio: Option<Audio>,91 audio: Option<Audio>,
64 }92 }
@@ -67,16 +95,20 @@ impl PlaybackSession {
67 /// Opens `path` and starts both decode workers. Only video failure is fatal:95 /// Opens `path` and starts both decode workers. Only video failure is fatal:
68 /// a file we cannot hear is still a file we can watch.96 /// a file we cannot hear is still a file we can watch.
69 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {97 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {
70- let path = path.as_ref();98+ let path = path.as_ref().to_path_buf();
71- let (meta, frames) = DecodeSession::open(path)?;99+ // `open_at(_, 0)` rather than `open` purely for the cancel handle: the
72- let audio = open_audio(path);100+ // field has to exist from the start for the first seek to use it.
101+ let (meta, frames, cancel) = DecodeSession::open_at(&path, 0)?;
102+ let audio = open_audio(&path);
73 let source = match audio {103 let source = match audio {
74 Some(_) => ClockSource::Audio,104 Some(_) => ClockSource::Audio,
75 None => ClockSource::Wall,105 None => ClockSource::Wall,
76 };106 };
77 Ok(Self {107 Ok(Self {
108+ path,
78 meta,109 meta,
79 frames,110 frames,
111+ cancel,
80 clock: PlaybackClock::new(source),112 clock: PlaybackClock::new(source),
81 audio,113 audio,
82 })114 })
@@ -132,6 +164,73 @@ impl PlaybackSession {
132 }164 }
133 }165 }
134 166
167+ /// Repositions the timeline to `secs`, clamped to the file. Both decode
168+ /// workers are replaced rather than steered: a fresh channel cannot hold a
169+ /// stale frame, and it works just as well after EOF, where the old workers
170+ /// have already exited.
171+ ///
172+ /// Playing stays playing and paused stays paused -- but a paused seek still
173+ /// decodes, so the caller can show the frame it landed on.
174+ pub fn seek(&mut self, secs: f64) {
175+ let fps = self.meta.frame_rate;
176+ let t = secs.clamp(0.0, f64::from(self.meta.frame_count) / fps);
177+ let target = ((t * fps) as u32).min(self.meta.frame_count.saturating_sub(1));
178+ let was_playing = self.clock.is_playing();
179+
180+ if let Some(audio) = &self.audio {
181+ let ao = audio.ao.lock().unwrap();
182+ ao.set_active(false);
183+ // Bumped and flushed while holding the device lock, because the
184+ // feeder re-checks the epoch inside that same lock: whatever it is
185+ // carrying can no longer reach the ring after this point.
186+ audio.epoch.fetch_add(1, Ordering::Release);
187+ ao.flush();
188+ }
189+
190+ // Cancel first, drop second: the old worker may be parked in `send` on
191+ // the bounded channel, where only the disconnect wakes it -- and it
192+ // then finds the flag already set.
193+ self.cancel.store(true, Ordering::Release);
194+ match DecodeSession::open_at(&self.path, target) {
195+ Ok((_, frames, cancel)) => {
196+ self.frames = frames;
197+ self.cancel = cancel;
198+ }
199+ // The file opened once already, so this is a disappearing-file case:
200+ // the timeline still moves, there are simply no more pictures.
201+ Err(e) => eprintln!("seek: video reopen failed: {e}"),
202+ }
203+
204+ let mut audio_running = false;
205+ if let Some(audio) = &self.audio
206+ && !audio.died.load(Ordering::Acquire)
207+ {
208+ // The device position keeps counting across a flush, so re-basing
209+ // `fed` on it is what keeps `played_out` exact for the new stream.
210+ let played = audio.ao.lock().unwrap().position().unwrap_or(0).max(0) as u64;
211+ audio.fed.store(played * audio.channels, Ordering::Relaxed);
212+ audio.fed_all.store(false, Ordering::Release);
213+ audio_running = match AudioSession::open_at(&self.path, t) {
214+ Ok(Some((_, rx))) => audio.spawn_feeder(rx),
215+ _ => false,
216+ };
217+ if !audio_running {
218+ // Nothing will ever be fed again; let `tick` fall to wall time
219+ // instead of waiting on a device that has no more work coming.
220+ audio.fed_all.store(true, Ordering::Release);
221+ }
222+ }
223+
224+ // Same invariant as `play`: position the clock before audio restarts.
225+ if audio_running && self.clock.source() != ClockSource::Audio {
226+ self.clock.switch_to_audio();
227+ }
228+ self.clock.seek_to(t);
229+ if was_playing && let Some(audio) = &self.audio {
230+ audio.ao.lock().unwrap().set_active(true);
231+ }
232+ }
233+
135 /// Moves the clock forward; the caller runs this once per rendered frame.234 /// Moves the clock forward; the caller runs this once per rendered frame.
136 /// Costs an atomic load, and once per session a mode switch.235 /// Costs an atomic load, and once per session a mode switch.
137 pub fn tick(&mut self) {236 pub fn tick(&mut self) {
@@ -189,26 +288,15 @@ fn open_audio(path: &Path) -> Option<Audio> {
189 fed: Arc::new(AtomicU64::new(0)),288 fed: Arc::new(AtomicU64::new(0)),
190 fed_all: Arc::new(AtomicBool::new(false)),289 fed_all: Arc::new(AtomicBool::new(false)),
191 died: Arc::new(AtomicBool::new(false)),290 died: Arc::new(AtomicBool::new(false)),
291+ epoch: Arc::new(AtomicU64::new(0)),
192 };292 };
193- let (ao, fed, fed_all, died) = (293+ audio.spawn_feeder(rx).then_some(audio)
194- audio.ao.clone(),
195- audio.fed.clone(),
196- audio.fed_all.clone(),
197- audio.died.clone(),
198- );
199- thread::Builder::new()
200- .name("audio-feed".into())
201- .spawn(move || {
202- feed(rx, &ao, &fed, &died);
203- fed_all.store(true, Ordering::Release);
204- })
205- .ok()?;
206- Some(audio)
207 }294 }
208 295
209 /// Pours decoded chunks into the device, keeping whatever the ring would not296 /// Pours decoded chunks into the device, keeping whatever the ring would not
210-/// take. Ends when the decoder is done or the output dies.297+/// take. Ends when the decoder is done, the output dies, or a seek supersedes
211-fn feed(rx: Receiver<AudioChunk>, ao: &Mutex<AoSession>, fed: &AtomicU64, died: &AtomicBool) {298+/// this feeder.
299+fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
212 let mut pending: Vec<f32> = Vec::new();300 let mut pending: Vec<f32> = Vec::new();
213 loop {301 loop {
214 if pending.is_empty() {302 if pending.is_empty() {
@@ -217,15 +305,24 @@ fn feed(rx: Receiver<AudioChunk>, ao: &Mutex<AoSession>, fed: &AtomicU64, died:
217 Err(_) => return, // decoder finished or went away305 Err(_) => return, // decoder finished or went away
218 }306 }
219 }307 }
220- let accepted = match ao.lock().unwrap().write(&pending) {308+ let accepted = {
221- Some(n) => n,309+ let mut ao = audio.ao.lock().unwrap();
222- None => {310+ // Under the lock, immediately before the write: `seek` bumps the
223- // Output died; flag it so `tick` moves the clock to wall time.311+ // epoch and flushes the ring holding this very lock, so past this
224- died.store(true, Ordering::Release);312+ // check no stale sample can be queued behind the flush.
313+ if audio.epoch.load(Ordering::Acquire) != epoch {
225 return;314 return;
226 }315 }
316+ match ao.write(&pending) {
317+ Some(n) => n,
318+ None => {
319+ // Output died; flag it so `tick` moves the clock to wall time.
320+ audio.died.store(true, Ordering::Release);
321+ return;
322+ }
323+ }
227 };324 };
228- fed.fetch_add(accepted as u64, Ordering::Relaxed);325+ audio.fed.fetch_add(accepted as u64, Ordering::Relaxed);
229 pending.drain(..accepted);326 pending.drain(..accepted);
230 if !pending.is_empty() {327 if !pending.is_empty() {
231 // Ring full: nothing to do but let the device drain it.328 // Ring full: nothing to do but let the device drain it.
crates/engine/tests/playback.rsmodified+178 -0
@@ -106,3 +106,181 @@ fn video_only_plays_at_real_speed() {
106 fn audio_video_plays_at_real_speed() {106 fn audio_video_plays_at_real_speed() {
107 plays_at_real_speed("test_av.mp4");107 plays_at_real_speed("test_av.mp4");
108 }108 }
109+
110+/// The next frame off the (post-seek, freshly opened) channel.
111+fn next_index(session: &PlaybackSession, what: &str) -> u32 {
112+ match session.frames().recv_timeout(Duration::from_secs(10)) {
113+ Ok(frame) => frame.index,
114+ Err(e) => panic!("no frame after {what}: {e:?}"),
115+ }
116+}
117+
118+/// Ticks like a front-end but takes every frame as fast as the decoder makes
119+/// them, until the worker exits. Returns how many arrived and the last index.
120+fn drain_to_eof(session: &mut PlaybackSession) -> (u32, Option<u32>) {
121+ let deadline = Instant::now() + Duration::from_secs(20);
122+ let (mut count, mut last) = (0, None);
123+ loop {
124+ session.tick();
125+ loop {
126+ match session.frames().try_recv() {
127+ Ok(frame) => {
128+ count += 1;
129+ last = Some(frame.index);
130+ }
131+ Err(TryRecvError::Empty) => break,
132+ Err(TryRecvError::Disconnected) => return (count, last),
133+ }
134+ }
135+ assert!(Instant::now() < deadline, "still draining after 20 s");
136+ sleep(Duration::from_millis(4));
137+ }
138+}
139+
140+fn threads() -> usize {
141+ std::fs::read_to_string("/proc/self/status")
142+ .unwrap()
143+ .lines()
144+ .find_map(|l| l.strip_prefix("Threads:"))
145+ .and_then(|n| n.trim().parse().ok())
146+ .expect("Threads: in /proc/self/status")
147+}
148+
149+/// Wall-clock seek: no audio track, so this runs anywhere.
150+#[test]
151+fn seek_repositions_video_and_clock() {
152+ let mut session = PlaybackSession::open(asset("test_baseline.mp4")).expect("open");
153+ let fps = session.meta().frame_rate;
154+ let mut last_index = None;
155+
156+ session.play();
157+ run_for(&mut session, &mut last_index, Duration::from_millis(500));
158+
159+ session.seek(3.0);
160+ assert!(
161+ (session.now() - 3.0).abs() < 0.05,
162+ "clock at {}",
163+ session.now()
164+ );
165+ assert_eq!(
166+ next_index(&session, "seek(3.0)"),
167+ (3.0 * fps) as u32,
168+ "the first frame after a seek is the target frame"
169+ );
170+ sleep(Duration::from_millis(200));
171+ assert!(session.now() > 3.05, "clock stalled at {}", session.now());
172+
173+ // Run it out, then seek back: the old workers are gone, not steered.
174+ let last_frame = session.meta().frame_count - 1;
175+ assert_eq!(drain_to_eof(&mut session).1, Some(last_frame));
176+ session.seek(0.0);
177+ assert_eq!(next_index(&session, "seek(0.0) after EOF"), 0);
178+ assert!(session.now() < 0.2, "clock at {}", session.now());
179+}
180+
181+/// Past the end lands on the last frame instead of hanging, and the clock keeps
182+/// running -- with audio that means falling through to wall time, because the
183+/// device is never fed another sample.
184+#[test]
185+fn seek_past_the_end_clamps() {
186+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
187+ let meta = *session.meta();
188+ let duration = f64::from(meta.frame_count) / meta.frame_rate;
189+
190+ session.play();
191+ session.seek(999.0);
192+ assert!(
193+ (session.now() - duration).abs() < 0.05,
194+ "clock at {} for a {duration}s file",
195+ session.now()
196+ );
197+ assert_eq!(next_index(&session, "seek(999.0)"), meta.frame_count - 1);
198+
199+ let landed = session.now();
200+ let deadline = Instant::now() + Duration::from_secs(2);
201+ while session.now() <= landed + 0.05 {
202+ session.tick();
203+ assert!(Instant::now() < deadline, "clock froze at {landed}");
204+ sleep(Duration::from_millis(8));
205+ }
206+}
207+
208+/// Scrubbing: seeks with no time in between must neither panic nor leave the
209+/// abandoned workers behind, and the last one still wins.
210+#[test]
211+fn rapid_seeks_settle_on_the_last_one() {
212+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
213+ let fps = session.meta().frame_rate;
214+ let mut last_index = None;
215+
216+ session.play();
217+ run_for(&mut session, &mut last_index, Duration::from_millis(300));
218+ let before = threads();
219+
220+ for t in [4.0, 1.0, 3.5, 0.5, 2.0] {
221+ session.seek(t);
222+ }
223+ assert_eq!(next_index(&session, "5 rapid seeks"), (2.0 * fps) as u32);
224+
225+ sleep(Duration::from_millis(500)); // abandoned workers exit within an AU
226+ let after = threads();
227+ eprintln!("rapid seeks: {before} threads -> {after}");
228+ assert!(
229+ after <= before + 3,
230+ "workers piled up: {before} threads -> {after}"
231+ );
232+}
233+
234+/// The audio path proper: needs a PipeWire daemon and the output plugin next to
235+/// the test binary (`LD_LIBRARY_PATH=target/release`).
236+#[test]
237+#[ignore = "needs a running PipeWire daemon"]
238+fn seek_keeps_the_audio_clock() {
239+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
240+ let meta = *session.meta();
241+ let mut last_index = None;
242+
243+ session.play();
244+ run_for(&mut session, &mut last_index, Duration::from_secs(1));
245+
246+ session.seek(3.0);
247+ assert!(
248+ (session.now() - 3.0).abs() < 0.05,
249+ "clock at {}",
250+ session.now()
251+ );
252+ let first = next_index(&session, "seek(3.0)");
253+ assert_eq!(first, (3.0 * meta.frame_rate) as u32);
254+ let mut after_seek = None;
255+ run_for(&mut session, &mut after_seek, Duration::from_millis(600));
256+ let advanced = session.now();
257+ eprintln!("seek(3.0) -> {advanced:.3}s, frames {first}..={after_seek:?}");
258+ assert!(
259+ (3.3..3.9).contains(&advanced),
260+ "clock did not run at real speed after the seek: {advanced:.3}s"
261+ );
262+
263+ // Everything from the target on, and nothing before it: ~2 s of frames.
264+ let (drained, last) = drain_to_eof(&mut session);
265+ let total = 1 + after_seek.map_or(0, |i| i - first) + drained;
266+ eprintln!("frames from 3.0s to EOF: {total}");
267+ // `run_for` pumps faster than real time, so it may have hit EOF by itself.
268+ assert_eq!(last.or(after_seek), Some(meta.frame_count - 1), "no EOF");
269+ assert!(
270+ (55..=65).contains(&total),
271+ "expected ~60 frames left, got {total}"
272+ );
273+
274+ // A full second run after EOF, from zero.
275+ session.seek(0.0);
276+ session.play();
277+ let mut second = None;
278+ run_for(&mut session, &mut second, Duration::from_millis(800));
279+ assert_eq!(second.map(|i| i > 0), Some(true), "second run stalled");
280+ assert!(session.now() > 0.5, "second run clock at {}", session.now());
281+ assert_eq!(
282+ drain_to_eof(&mut session).1.or(second),
283+ Some(meta.frame_count - 1),
284+ "second run did not finish"
285+ );
286+}