forge
Explore
Log in

Don't you dare go Hollow

Edit-list traversal — timeline frames, cut/delete/undo

Browse files at this commit

7d2251c5e2726d8bb245a34e92b2fb94cdc47cbaAhmet Kaan GümüşParent: e75a7ba
  • feat
    • edit-list traversal — timeline frames, cut/delete/undo
Show full message
✨ feat(playback): edit-list traversal — timeline frames, cut/delete/undo

PlaybackSession owns a Project. try_frame() rewrites every frame index from
source to timeline and reopens the next clip's range when a worker ends, so a
timeline of clips plays as one contiguous sequence; is_eos() is the real end.
seek() maps timeline seconds through the edit list and feeds the audio worker
one segment list for the whole rest of the timeline, so clip joins are gapless.
cut_at is metadata only, delete_clip/undo reseek onto the new mapping.

frames() stays for now: the app switches to try_frame in the UI slice.
crates/engine/src/playback.rsmodified+161 -12
@@ -12,7 +12,7 @@
12 12
13 use std::path::{Path, PathBuf};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, TryRecvError};
16 use std::sync::{Arc, Mutex};16 use std::sync::{Arc, Mutex};
17 use std::thread;17 use std::thread;
18 use std::time::Duration;18 use std::time::Duration;
@@ -22,6 +22,7 @@ use crate::audio::{AudioChunk, AudioSession};
22 use crate::clock::{ClockSource, PlaybackClock};22 use crate::clock::{ClockSource, PlaybackClock};
23 use crate::decode::{DecodeSession, Frame};23 use crate::decode::{DecodeSession, Frame};
24 use crate::demux::VideoMeta;24 use crate::demux::VideoMeta;
25+use crate::project::{Clip, Project};
25 26
26 /// How long the feeder waits out a full ring. The ring holds a second, so this27 /// How long the feeder waits out a full ring. The ring holds a second, so this
27 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.28 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.
@@ -89,6 +90,17 @@ pub struct PlaybackSession {
89 cancel: Arc<AtomicBool>,90 cancel: Arc<AtomicBool>,
90 clock: PlaybackClock,91 clock: PlaybackClock,
91 audio: Option<Audio>,92 audio: Option<Audio>,
93+ /// The edit list. Everything a caller says in seconds is a *timeline*
94+ /// position; only this maps it onto the file.
95+ project: Project,
96+ /// Source range the current decode worker was opened for, and where that
97+ /// range starts on the timeline -- together they rewrite a source frame
98+ /// index into a timeline one. Not a clip index: a `cut` splits the clip
99+ /// under a running worker, and only the mapping survives that.
100+ range: Clip,
101+ timeline_start: u32,
102+ /// The last clip has been played out; see [`PlaybackSession::is_eos`].
103+ eos: bool,
92 }104 }
93 105
94 impl PlaybackSession {106 impl PlaybackSession {
@@ -104,6 +116,10 @@ impl PlaybackSession {
104 Some(_) => ClockSource::Audio,116 Some(_) => ClockSource::Audio,
105 None => ClockSource::Wall,117 None => ClockSource::Wall,
106 };118 };
119+ // One clip covering the file, so timeline == source until the first
120+ // edit -- and `open_at(_, 0)` is exactly that clip's range.
121+ let project = Project::single(meta.frame_count);
122+ let range = project.clips()[0];
107 Ok(Self {123 Ok(Self {
108 path,124 path,
109 meta,125 meta,
@@ -111,6 +127,10 @@ impl PlaybackSession {
111 cancel,127 cancel,
112 clock: PlaybackClock::new(source),128 clock: PlaybackClock::new(source),
113 audio,129 audio,
130+ project,
131+ range,
132+ timeline_start: 0,
133+ eos: false,
114 })134 })
115 }135 }
116 136
@@ -124,6 +144,118 @@ impl PlaybackSession {
124 &self.frames144 &self.frames
125 }145 }
126 146
147+ /// The next decoded frame, its `index` rewritten from a source frame to a
148+ /// *timeline* frame -- the only frame space that leaves the engine, and the
149+ /// one [`PlaybackSession::now`] is in.
150+ ///
151+ /// `None` means "nothing right now": the decoder is behind, or a clip
152+ /// boundary is being reopened (~80 ms, during which the caller simply keeps
153+ /// showing its last frame). End of stream is [`PlaybackSession::is_eos`].
154+ pub fn try_frame(&mut self) -> Option<Frame> {
155+ loop {
156+ match self.frames.try_recv() {
157+ Ok(mut frame) => {
158+ frame.index =
159+ self.timeline_start + frame.index.saturating_sub(self.range.in_frame);
160+ return Some(frame);
161+ }
162+ Err(TryRecvError::Empty) => return None,
163+ // The worker stopped: at the end of its range, or on a decode
164+ // error -- which is why this skips the rest of a broken clip
165+ // rather than stalling on it.
166+ Err(TryRecvError::Disconnected) => {
167+ if !self.next_clip() {
168+ self.eos = true;
169+ return None;
170+ }
171+ }
172+ }
173+ }
174+ }
175+
176+ /// Whether the timeline has been played out. Any seek clears it, so an edit
177+ /// after the end (which reseeks) revives the session.
178+ pub fn is_eos(&self) -> bool {
179+ self.eos
180+ }
181+
182+ /// Starts decoding whatever follows the current range on the timeline;
183+ /// `false` past the end. The next timeline frame is derived rather than
184+ /// remembered as a clip index, because a `cut` while playing splits the
185+ /// clip under the running worker and only the mapping stays true.
186+ fn next_clip(&mut self) -> bool {
187+ let next = self.timeline_start + self.range.len();
188+ let Some((idx, source)) = self.project.map_timeline(next) else {
189+ return false;
190+ };
191+ let out = self.project.clips()[idx].out_frame;
192+ match DecodeSession::open_range(&self.path, source, out) {
193+ Ok((_, frames, cancel)) => {
194+ self.frames = frames;
195+ self.cancel = cancel;
196+ }
197+ // Disappearing-file case, as in `seek`. The old receiver is still
198+ // disconnected, so the next pass moves on to the clip after this.
199+ Err(e) => eprintln!("clip at timeline frame {next}: video open failed: {e}"),
200+ }
201+ self.range = Clip {
202+ in_frame: source,
203+ out_frame: out,
204+ };
205+ self.timeline_start = next;
206+ true
207+ }
208+
209+ /// Length of the edited timeline in seconds -- what a ruler shows, and it
210+ /// shrinks with every delete.
211+ pub fn timeline_duration(&self) -> f64 {
212+ f64::from(self.project.timeline_frames()) / self.meta.frame_rate
213+ }
214+
215+ /// `(start, len)` per clip in timeline seconds, in order: what a clips lane
216+ /// needs to lay itself out. Selection is the caller's business.
217+ pub fn clip_spans(&self) -> Vec<(f64, f64)> {
218+ let fps = self.meta.frame_rate;
219+ self.project
220+ .clip_spans()
221+ .iter()
222+ .map(|&(start, len)| (f64::from(start) / fps, f64::from(len) / fps))
223+ .collect()
224+ }
225+
226+ /// Splits the clip under `timeline_secs` in two. Metadata only: a cut never
227+ /// changes the timeline->source mapping, so the running decoder stays
228+ /// correct and playback does not blink. `false` at a clip start or past the
229+ /// end, where there would be nothing to split off.
230+ pub fn cut_at(&mut self, timeline_secs: f64) -> bool {
231+ self.project
232+ .cut((timeline_secs * self.meta.frame_rate) as u32)
233+ }
234+
235+ /// Removes a clip and closes the gap. Unlike a cut this *does* move every
236+ /// following frame, so the session reseeks to wherever the playhead now
237+ /// points. `false` for a bad index or the last remaining clip.
238+ pub fn delete_clip(&mut self, idx: usize) -> bool {
239+ self.edit(|p| p.delete(idx))
240+ }
241+
242+ /// Undoes the last successful cut or delete, and reseeks like a delete.
243+ pub fn undo(&mut self) -> bool {
244+ self.edit(Project::undo)
245+ }
246+
247+ /// Applies an edit and, if it took, reseeks onto the new mapping. `seek`
248+ /// clamps to the new duration and keeps playing playing, so a delete that
249+ /// shortens the timeline past the playhead lands on the last frame.
250+ fn edit(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool {
251+ if !f(&mut self.project) {
252+ return false;
253+ }
254+ let now = self.now();
255+ self.seek(now);
256+ true
257+ }
258+
127 /// Current timeline position in seconds.259 /// Current timeline position in seconds.
128 pub fn now(&self) -> f64 {260 pub fn now(&self) -> f64 {
129 self.clock.now()261 self.clock.now()
@@ -164,7 +296,7 @@ impl PlaybackSession {
164 }296 }
165 }297 }
166 298
167- /// Repositions the timeline to `secs`, clamped to the file. Both decode299+ /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
168 /// workers are replaced rather than steered: a fresh channel cannot hold a300 /// 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 workers301 /// stale frame, and it works just as well after EOF, where the old workers
170 /// have already exited.302 /// have already exited.
@@ -173,8 +305,9 @@ impl PlaybackSession {
173 /// decodes, so the caller can show the frame it landed on.305 /// decodes, so the caller can show the frame it landed on.
174 pub fn seek(&mut self, secs: f64) {306 pub fn seek(&mut self, secs: f64) {
175 let fps = self.meta.frame_rate;307 let fps = self.meta.frame_rate;
176- let t = secs.clamp(0.0, f64::from(self.meta.frame_count) / fps);308+ let total = self.project.timeline_frames();
177- let target = ((t * fps) as u32).min(self.meta.frame_count.saturating_sub(1));309+ let t = secs.clamp(0.0, f64::from(total) / fps);
310+ let target = ((t * fps) as u32).min(total.saturating_sub(1));
178 let was_playing = self.clock.is_playing();311 let was_playing = self.clock.is_playing();
179 312
180 if let Some(audio) = &self.audio {313 if let Some(audio) = &self.audio {
@@ -191,15 +324,27 @@ impl PlaybackSession {
191 // the bounded channel, where only the disconnect wakes it -- and it324 // the bounded channel, where only the disconnect wakes it -- and it
192 // then finds the flag already set.325 // then finds the flag already set.
193 self.cancel.store(true, Ordering::Release);326 self.cancel.store(true, Ordering::Release);
194- match DecodeSession::open_at(&self.path, target) {327+ // `target` is inside the timeline (never empty), so this always maps;
195- Ok((_, frames, cancel)) => {328+ // the range runs from there to the end of the clip it landed in.
196- self.frames = frames;329+ if let Some((idx, source)) = self.project.map_timeline(target) {
197- self.cancel = cancel;330+ let out = self.project.clips()[idx].out_frame;
331+ match DecodeSession::open_range(&self.path, source, out) {
332+ Ok((_, frames, cancel)) => {
333+ self.frames = frames;
334+ self.cancel = cancel;
335+ }
336+ // The file opened once already, so this is a disappearing-file
337+ // case: the timeline still moves, there are simply no more
338+ // pictures.
339+ Err(e) => eprintln!("seek: video reopen failed: {e}"),
198 }340 }
199- // The file opened once already, so this is a disappearing-file case:341+ self.range = Clip {
200- // the timeline still moves, there are simply no more pictures.342+ in_frame: source,
201- Err(e) => eprintln!("seek: video reopen failed: {e}"),343+ out_frame: out,
344+ };
345+ self.timeline_start = target;
202 }346 }
347+ self.eos = false;
203 348
204 let mut audio_running = false;349 let mut audio_running = false;
205 if let Some(audio) = &self.audio350 if let Some(audio) = &self.audio
@@ -210,7 +355,11 @@ impl PlaybackSession {
210 let played = audio.ao.lock().unwrap().position().unwrap_or(0).max(0) as u64;355 let played = audio.ao.lock().unwrap().position().unwrap_or(0).max(0) as u64;
211 audio.fed.store(played * audio.channels, Ordering::Relaxed);356 audio.fed.store(played * audio.channels, Ordering::Relaxed);
212 audio.fed_all.store(false, Ordering::Release);357 audio.fed_all.store(false, Ordering::Release);
213- audio_running = match AudioSession::open_at(&self.path, t) {358+ // One worker for the whole rest of the timeline, so the joins
359+ // between clips are gapless: the video reopens at a boundary, the
360+ // ear never hears it.
361+ let segs = self.project.segments_from(target, fps);
362+ audio_running = match AudioSession::open_segments(&self.path, &segs) {
214 Ok(Some((_, rx))) => audio.spawn_feeder(rx),363 Ok(Some((_, rx))) => audio.spawn_feeder(rx),
215 _ => false,364 _ => false,
216 };365 };
crates/engine/tests/playback.rsmodified+215 -40
@@ -7,12 +7,11 @@
7 //! cargo test -p engine --release --test playback -- --nocapture7 //! cargo test -p engine --release --test playback -- --nocapture
8 //! ```8 //! ```
9 9
10-use std::path::PathBuf;10+use std::path::{Path, PathBuf};
11-use std::sync::mpsc::TryRecvError;
12 use std::thread::sleep;11 use std::thread::sleep;
13 use std::time::{Duration, Instant};12 use std::time::{Duration, Instant};
14 13
15-use engine::PlaybackSession;14+use engine::{DecodeSession, Frame, PlaybackSession};
16 15
17 fn asset(name: &str) -> PathBuf {16 fn asset(name: &str) -> PathBuf {
18 PathBuf::from(env!("CARGO_MANIFEST_DIR"))17 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -25,24 +24,19 @@ fn asset(name: &str) -> PathBuf {
25 fn pump(session: &mut PlaybackSession, last_index: &mut Option<u32>) {24 fn pump(session: &mut PlaybackSession, last_index: &mut Option<u32>) {
26 session.tick();25 session.tick();
27 let target = session.now() * session.meta().frame_rate;26 let target = session.now() * session.meta().frame_rate;
28- loop {27+ while let Some(frame) = session.try_frame() {
29- match session.frames().try_recv() {28+ if let Some(previous) = *last_index {
30- Ok(frame) => {29+ assert_eq!(
31- if let Some(previous) = *last_index {30+ frame.index,
32- assert_eq!(31+ previous + 1,
33- frame.index,32+ "frames must arrive in index order"
34- previous + 1,33+ );
35- "frames must arrive in index order"34+ }
36- );35+ *last_index = Some(frame.index);
37- }36+ // Stop at the first frame past the clock; the real app holds it for the
38- *last_index = Some(frame.index);37+ // next tick, we simply stop draining.
39- // Stop at the first frame past the clock; the real app holds it38+ if f64::from(frame.index) > target {
40- // for the next tick, we simply stop draining.39+ return;
41- if f64::from(frame.index) > target {
42- return;
43- }
44- }
45- Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => return,
46 }40 }
47 }41 }
48 }42 }
@@ -108,35 +102,52 @@ fn audio_video_plays_at_real_speed() {
108 }102 }
109 103
110 /// The next frame off the (post-seek, freshly opened) channel.104 /// The next frame off the (post-seek, freshly opened) channel.
111-fn next_index(session: &PlaybackSession, what: &str) -> u32 {105+fn next_frame(session: &mut PlaybackSession, what: &str) -> Frame {
112- match session.frames().recv_timeout(Duration::from_secs(10)) {106+ let deadline = Instant::now() + Duration::from_secs(10);
113- Ok(frame) => frame.index,107+ loop {
114- Err(e) => panic!("no frame after {what}: {e:?}"),108+ if let Some(frame) = session.try_frame() {
109+ return frame;
110+ }
111+ assert!(Instant::now() < deadline, "no frame after {what}");
112+ sleep(Duration::from_millis(4));
115 }113 }
116 }114 }
117 115
116+fn next_index(session: &mut PlaybackSession, what: &str) -> u32 {
117+ next_frame(session, what).index
118+}
119+
118 /// Ticks like a front-end but takes every frame as fast as the decoder makes120 /// 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.121+/// them, until the timeline is played out. Returns how many arrived and the
122+/// last index.
120 fn drain_to_eof(session: &mut PlaybackSession) -> (u32, Option<u32>) {123 fn drain_to_eof(session: &mut PlaybackSession) -> (u32, Option<u32>) {
121 let deadline = Instant::now() + Duration::from_secs(20);124 let deadline = Instant::now() + Duration::from_secs(20);
122 let (mut count, mut last) = (0, None);125 let (mut count, mut last) = (0, None);
123 loop {126 loop {
124 session.tick();127 session.tick();
125- loop {128+ while let Some(frame) = session.try_frame() {
126- match session.frames().try_recv() {129+ count += 1;
127- Ok(frame) => {130+ last = Some(frame.index);
128- count += 1;131+ }
129- last = Some(frame.index);132+ if session.is_eos() {
130- }133+ return (count, last);
131- Err(TryRecvError::Empty) => break,
132- Err(TryRecvError::Disconnected) => return (count, last),
133- }
134 }134 }
135 assert!(Instant::now() < deadline, "still draining after 20 s");135 assert!(Instant::now() < deadline, "still draining after 20 s");
136 sleep(Duration::from_millis(4));136 sleep(Duration::from_millis(4));
137 }137 }
138 }138 }
139 139
140+/// The pixels of one source frame, decoded on its own -- the reference a
141+/// timeline frame is checked against.
142+fn source_frame(path: &Path, index: u32) -> Vec<u8> {
143+ let (_, rx, _cancel) = DecodeSession::open_range(path, index, index + 1).expect("open_range");
144+ let frame = rx
145+ .recv_timeout(Duration::from_secs(10))
146+ .expect("reference frame");
147+ assert_eq!(frame.index, index, "open_range starts where it is told");
148+ frame.bgra
149+}
150+
140 fn threads() -> usize {151 fn threads() -> usize {
141 std::fs::read_to_string("/proc/self/status")152 std::fs::read_to_string("/proc/self/status")
142 .unwrap()153 .unwrap()
@@ -163,7 +174,7 @@ fn seek_repositions_video_and_clock() {
163 session.now()174 session.now()
164 );175 );
165 assert_eq!(176 assert_eq!(
166- next_index(&session, "seek(3.0)"),177+ next_index(&mut session, "seek(3.0)"),
167 (3.0 * fps) as u32,178 (3.0 * fps) as u32,
168 "the first frame after a seek is the target frame"179 "the first frame after a seek is the target frame"
169 );180 );
@@ -174,7 +185,7 @@ fn seek_repositions_video_and_clock() {
174 let last_frame = session.meta().frame_count - 1;185 let last_frame = session.meta().frame_count - 1;
175 assert_eq!(drain_to_eof(&mut session).1, Some(last_frame));186 assert_eq!(drain_to_eof(&mut session).1, Some(last_frame));
176 session.seek(0.0);187 session.seek(0.0);
177- assert_eq!(next_index(&session, "seek(0.0) after EOF"), 0);188+ assert_eq!(next_index(&mut session, "seek(0.0) after EOF"), 0);
178 assert!(session.now() < 0.2, "clock at {}", session.now());189 assert!(session.now() < 0.2, "clock at {}", session.now());
179 }190 }
180 191
@@ -194,7 +205,10 @@ fn seek_past_the_end_clamps() {
194 "clock at {} for a {duration}s file",205 "clock at {} for a {duration}s file",
195 session.now()206 session.now()
196 );207 );
197- assert_eq!(next_index(&session, "seek(999.0)"), meta.frame_count - 1);208+ assert_eq!(
209+ next_index(&mut session, "seek(999.0)"),
210+ meta.frame_count - 1
211+ );
198 212
199 let landed = session.now();213 let landed = session.now();
200 let deadline = Instant::now() + Duration::from_secs(2);214 let deadline = Instant::now() + Duration::from_secs(2);
@@ -220,7 +234,10 @@ fn rapid_seeks_settle_on_the_last_one() {
220 for t in [4.0, 1.0, 3.5, 0.5, 2.0] {234 for t in [4.0, 1.0, 3.5, 0.5, 2.0] {
221 session.seek(t);235 session.seek(t);
222 }236 }
223- assert_eq!(next_index(&session, "5 rapid seeks"), (2.0 * fps) as u32);237+ assert_eq!(
238+ next_index(&mut session, "5 rapid seeks"),
239+ (2.0 * fps) as u32
240+ );
224 241
225 sleep(Duration::from_millis(500)); // abandoned workers exit within an AU242 sleep(Duration::from_millis(500)); // abandoned workers exit within an AU
226 let after = threads();243 let after = threads();
@@ -249,7 +266,7 @@ fn seek_keeps_the_audio_clock() {
249 "clock at {}",266 "clock at {}",
250 session.now()267 session.now()
251 );268 );
252- let first = next_index(&session, "seek(3.0)");269+ let first = next_index(&mut session, "seek(3.0)");
253 assert_eq!(first, (3.0 * meta.frame_rate) as u32);270 assert_eq!(first, (3.0 * meta.frame_rate) as u32);
254 let mut after_seek = None;271 let mut after_seek = None;
255 run_for(&mut session, &mut after_seek, Duration::from_millis(600));272 run_for(&mut session, &mut after_seek, Duration::from_millis(600));
@@ -284,3 +301,161 @@ fn seek_keeps_the_audio_clock() {
284 "second run did not finish"301 "second run did not finish"
285 );302 );
286 }303 }
304+
305+/// The edit list end to end: two cuts, drop the middle clip, play the result.
306+/// What comes out is one contiguous timeline whose *pictures* skip the hole --
307+/// no audio needed, so this runs anywhere.
308+#[test]
309+fn edits_traverse_cuts() {
310+ let path = asset("test_baseline.mp4");
311+ let mut session = PlaybackSession::open(&path).expect("open");
312+ let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
313+ let whole = f64::from(total) / fps;
314+ assert!((session.timeline_duration() - whole).abs() < 1e-9);
315+ assert_eq!(session.clip_spans(), vec![(0.0, whole)]);
316+
317+ assert!(session.cut_at(2.0), "cut at 2 s");
318+ assert!(session.cut_at(3.5), "cut at 3.5 s");
319+ assert!(
320+ !session.cut_at(2.0),
321+ "the same frame twice: already a boundary"
322+ );
323+ assert!(!session.cut_at(0.0), "nothing before the first frame");
324+ assert_eq!(session.clip_spans().len(), 3);
325+ // Cuts are metadata: the timeline is the same length as before.
326+ assert!((session.timeline_duration() - whole).abs() < 1e-9);
327+
328+ let (cut, hole_end) = ((2.0 * fps) as u32, (3.5 * fps) as u32);
329+ assert!(session.delete_clip(1), "drop the middle clip");
330+ let kept = total - (hole_end - cut);
331+ assert_eq!(session.clip_spans().len(), 2);
332+ assert!(
333+ (session.timeline_duration() - f64::from(kept) / fps).abs() < 1e-9,
334+ "duration after the delete: {}",
335+ session.timeline_duration()
336+ );
337+
338+ // Play the whole edited timeline from the top.
339+ session.seek(0.0);
340+ session.play();
341+ let deadline = Instant::now() + Duration::from_secs(20);
342+ let (mut expect, mut boundary) = (0, None);
343+ loop {
344+ session.tick();
345+ while let Some(frame) = session.try_frame() {
346+ assert_eq!(frame.index, expect, "timeline indices must be contiguous");
347+ if frame.index == cut {
348+ boundary = Some(frame.bgra);
349+ }
350+ expect += 1;
351+ }
352+ if session.is_eos() {
353+ break;
354+ }
355+ assert!(Instant::now() < deadline, "still draining after 20 s");
356+ sleep(Duration::from_millis(4));
357+ }
358+ assert_eq!(expect, kept, "the edited timeline, whole and nothing but");
359+ // From here the playhead has to stand still: an edit reseeks to *now*, so a
360+ // running clock would move the frame these assertions expect.
361+ session.pause();
362+
363+ // The frames behind those indices skipped the deleted range: the picture at
364+ // the boundary is source `hole_end`, not the source frame with that number.
365+ let boundary = boundary.expect("no frame at the cut");
366+ assert!(
367+ boundary == source_frame(&path, hole_end),
368+ "the boundary frame is not source {hole_end}"
369+ );
370+ assert!(
371+ boundary != source_frame(&path, cut),
372+ "the deleted range is still being decoded"
373+ );
374+
375+ // Seek into the surviving second clip: timeline 3.0 s is source 3.0 s + the
376+ // 1.5 s hole.
377+ session.seek(3.0);
378+ let landed = next_frame(&mut session, "seek(3.0) after edits");
379+ assert_eq!(landed.index, (3.0 * fps) as u32);
380+ assert!(
381+ landed.bgra == source_frame(&path, (4.5 * fps) as u32),
382+ "the seek landed on the wrong source frame"
383+ );
384+ assert!(!session.is_eos(), "a seek revives a played-out session");
385+
386+ assert!(session.undo(), "undo the delete");
387+ assert_eq!(session.clip_spans().len(), 3);
388+ assert!(
389+ (session.timeline_duration() - whole).abs() < 1e-9,
390+ "undo did not restore the duration: {}",
391+ session.timeline_duration()
392+ );
393+ // The undo reseeks to the (still paused) playhead, and on the restored
394+ // timeline 3.0 s is source 3.0 s again -- the hole is back.
395+ let restored = next_frame(&mut session, "undo");
396+ assert_eq!(restored.index, (3.0 * fps) as u32);
397+ assert!(
398+ restored.bgra == source_frame(&path, (3.0 * fps) as u32),
399+ "undo did not restore the mapping"
400+ );
401+}
402+
403+/// Editing while the device is running. A cut must not disturb playback at all
404+/// and a delete reseeks under it -- in both cases the audio keeps coming, which
405+/// is what stops `tick` from handing the timeline back to wall time.
406+#[test]
407+#[ignore = "needs a running PipeWire daemon"]
408+fn edits_keep_the_audio_clock() {
409+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
410+ let fps = session.meta().frame_rate;
411+ let mut last_index = None;
412+
413+ session.play();
414+ run_for(&mut session, &mut last_index, Duration::from_millis(700));
415+ let before = session.now();
416+ assert!(before > 0.3, "clock stalled at {before:.3}s");
417+
418+ // Metadata only: no worker is touched, so the indices stay contiguous
419+ // across the boundary `run_for` is about to cross.
420+ assert!(session.cut_at(1.5), "cut at 1.5 s");
421+ run_for(&mut session, &mut last_index, Duration::from_millis(900));
422+ let after_cut = session.now();
423+ assert!(
424+ after_cut > before + 0.6,
425+ "the clock stopped across the cut: {before:.3}s -> {after_cut:.3}s"
426+ );
427+ assert!(
428+ last_index.map(|i| f64::from(i) > 1.5 * fps) == Some(true),
429+ "playback never reached the cut: {last_index:?}"
430+ );
431+
432+ // Deleting the head clip moves everything after it, so the session reseeks
433+ // under the playhead: same timeline position, new source frame, and the
434+ // frame numbering restarts at the landing frame.
435+ assert!(session.delete_clip(0), "drop the head clip");
436+ let landed = session.now();
437+ assert!(
438+ (landed - after_cut).abs() < 0.2,
439+ "the delete moved the playhead: {after_cut:.3}s -> {landed:.3}s"
440+ );
441+ let first = next_frame(&mut session, "the delete reseek").index;
442+ assert!(
443+ first.abs_diff((landed * fps) as u32) <= 1,
444+ "the delete landed at {first} instead of the playhead ({landed:.3}s)"
445+ );
446+ // No EOS assertion here: `run_for` drains a frame per 8 ms call, far faster
447+ // than real time (ledger), so how much timeline is left after it is a race.
448+ let mut after_delete = Some(first);
449+ run_for(&mut session, &mut after_delete, Duration::from_millis(500));
450+ assert!(after_delete > Some(first), "no frames after the delete");
451+ assert!(
452+ session.now() > landed + 0.3,
453+ "the clock stopped after the delete: {landed:.3}s -> {:.3}s",
454+ session.now()
455+ );
456+ eprintln!(
457+ "edits: {before:.3}s -> cut -> {after_cut:.3}s -> delete -> {:.3}s of a {:.3}s timeline",
458+ session.now(),
459+ session.timeline_duration()
460+ );
461+}