forge
Explore
Log in

Don't you dare go Hollow

Multi-source traversal, import validation, cross-source export

Browse files at this commit

68b0ca2579faf82be0018d0fddff3f3f7d7870ffAhmet Kaan GümüşParent: 5593a9f
  • feat
    • multi-source traversal, import validation, cross-source export
Show full message
✨ feat(engine): multi-source traversal, import validation, cross-source export

Wave 2 of the import slice, two packages merged at one seam.

Playback traversal (S3): next_clip/seek open each clip against
project.sources()[clip.source]; audio switches to open_multi_segments over
the (source, start, end) triples segments_from now yields. New
PlaybackSession::import validates dimensions, fps and audio params against
the timeline before appending, and reseeks unconditionally so a running
audio worker learns the appended tail. clip_spans_by_source() added for the
app's per-source tint.

Cross-source export (S4): export::start drops its source path argument --
Project::sources() is the only path truth now -- and is pub so a test can
build a multi-source Project without a session. Each clip opens its own
ClipDecoder; the audio pass carries one bresenham accumulator across source
joins.

Seam: PlaybackSession::path is gone. It was kept only to feed export_to,
which no longer takes a path, so the field and its initialiser go with it.
crates/engine/src/export.rsmodified+22 -22
@@ -77,8 +77,10 @@ impl ExportHandle {
7777 }
7878
7979 /// Starts the worker. Failures are reported through the handle rather than
80-/// returned, so a caller has exactly one place to look.
81-pub(crate) fn start(source: &Path, project: Project, meta: VideoMeta, out: &Path) -> ExportHandle {
80+/// returned, so a caller has exactly one place to look. The files to read are
81+/// the project's own [`sources`](Project::sources) -- every clip names one --
82+/// so nothing but the edit list decides what is decoded.
83+pub fn start(project: Project, meta: VideoMeta, out: &Path) -> ExportHandle {
8284 let shared = Arc::new(Shared {
8385 progress: AtomicU32::new(0),
8486 cancel: AtomicBool::new(false),
@@ -86,7 +88,6 @@ pub(crate) fn start(source: &Path, project: Project, meta: VideoMeta, out: &Path
8688 outcome: Mutex::new(None),
8789 });
8890 let worker = Arc::clone(&shared);
89- let source = source.to_path_buf();
9091 let out = out.to_path_buf();
9192 // `<out>.part`, appended rather than substituted: the temporary of
9293 // `a.export.mp4` is `a.export.mp4.part`, which no other export claims.
@@ -97,7 +98,7 @@ pub(crate) fn start(source: &Path, project: Project, meta: VideoMeta, out: &Path
9798 // The rename is the last step and the only one that publishes a file
9899 // under the name the caller asked for; it stays on the same directory,
99100 // so it is atomic.
100- let result = run(&source, &project, &meta, &part, &worker)
101+ let result = run(&project, &meta, &part, &worker)
101102 .and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
102103 if result.is_err() {
103104 // The muxer -- and with it the file handle -- died with `run`.
@@ -117,28 +118,23 @@ fn settle(shared: &Shared, result: crate::Result<()>) {
117118 shared.finished.store(true, Ordering::Release);
118119 }
119120
120-fn run(
121- source: &Path,
122- project: &Project,
123- meta: &VideoMeta,
124- out: &Path,
125- shared: &Shared,
126-) -> crate::Result<()> {
121+fn run(project: &Project, meta: &VideoMeta, out: &Path, shared: &Shared) -> crate::Result<()> {
127122 let total = project.timeline_frames();
123+ let sources = project.sources();
128124 // Audio first: a track has to be declared when the muxer is created, which
129125 // happens as soon as the first coded picture arrives.
130126 //
131127 // ponytail: this holds the whole exported AAC track in memory (~3 kB per
132128 // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
133129 // `copy_segments` that yields packets instead of collecting them.
134- // Source indexes dropped: every clip is still source 0 until multi-source
135- // export lands, and `copy_segments` takes the one path above.
136- let segs: Vec<(f64, f64)> = project
137- .segments_from(0, meta.frame_rate)
138- .into_iter()
139- .map(|(_, start, end)| (start, end))
140- .collect();
141- let audio = AudioSession::copy_segments(source, &segs)?;
130+ //
131+ // The segments name their source, and the copy carries its packet-rounding
132+ // debt across a source join exactly as across a cut, so a timeline spanning
133+ // files stays in sync. A source whose AAC parameters disagree with the
134+ // first one is an `Err` from there -- import refuses those up front, this
135+ // is the backstop -- and the caller deletes the `.part`.
136+ let audio =
137+ AudioSession::copy_multi_segments(sources, &project.segments_from(0, meta.frame_rate))?;
142138 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
143139 freq_index: track.freq_index,
144140 chan_conf: track.chan_conf,
@@ -148,9 +144,13 @@ fn run(
148144 let mut muxer = None;
149145 let mut done = 0u32;
150146 for clip in project.clips() {
151- // Every clip reopens the file at its own in point; the encoder is *not*
152- // reopened, so the export is one continuous stream whose GOP boundaries
153- // need not line up with the cuts.
147+ // Every clip reopens its own source file at its own in point; the
148+ // encoder is *not* reopened, so the export is one continuous stream
149+ // whose GOP boundaries need not line up with the cuts -- nor with the
150+ // file boundaries, which are just cuts that change the path.
151+ let source = sources
152+ .get(clip.source)
153+ .ok_or_else(|| format!("clip names source {} of {}", clip.source, sources.len()))?;
154154 let mut pictures = ClipDecoder::open(source, clip.in_frame)?;
155155 for _ in 0..clip.len() {
156156 cancelled(shared)?;
crates/engine/src/lib.rsmodified+1 -1
@@ -12,7 +12,7 @@ pub mod mux;
1212 pub mod playback;
1313 pub mod project;
1414
15-pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioSession};
15+pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession};
1616 pub use clock::PlaybackClock;
1717 pub use decode::{DecodeSession, Frame};
1818 pub use demux::VideoMeta;
crates/engine/src/playback.rsmodified+78 -20
@@ -1,5 +1,6 @@
1-//! One file, one timeline: the decode workers, the audio output and the master
2-//! clock wired together so a front-end only has to render and call [`tick`].
1+//! One timeline over one or more files: the decode workers, the audio output
2+//! and the master clock wired together so a front-end only has to render and
3+//! call [`tick`].
34 //!
45 //! [`tick`]: PlaybackSession::tick
56 //!
@@ -10,7 +11,7 @@
1011 //! Drift policy stays with the caller -- this type answers "what time is it",
1112 //! the renderer decides which frame that means.
1213
13-use std::path::{Path, PathBuf};
14+use std::path::Path;
1415 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
1516 use std::sync::mpsc::{Receiver, TryRecvError};
1617 use std::sync::{Arc, Mutex};
@@ -21,7 +22,7 @@ use crate::ao::AoSession;
2122 use crate::audio::{AudioChunk, AudioSession};
2223 use crate::clock::{ClockSource, PlaybackClock};
2324 use crate::decode::{DecodeSession, Frame};
24-use crate::demux::VideoMeta;
25+use crate::demux::{Demuxer, VideoMeta};
2526 use crate::project::{Clip, Project};
2627
2728 /// How long the feeder waits out a full ring. The ring holds a second, so this
@@ -81,8 +82,6 @@ impl Audio {
8182
8283 /// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`].
8384 pub struct PlaybackSession {
84- /// Kept for [`PlaybackSession::seek`], which reopens both workers.
85- path: PathBuf,
8685 meta: VideoMeta,
8786 frames: Receiver<Frame>,
8887 /// Stops the current decode worker, so an abandoned one cannot outlive a
@@ -121,7 +120,6 @@ impl PlaybackSession {
121120 let project = Project::single(&path, meta.frame_count);
122121 let range = project.clips()[0];
123122 Ok(Self {
124- path,
125123 meta,
126124 frames,
127125 cancel,
@@ -184,7 +182,7 @@ impl PlaybackSession {
184182 };
185183 let clip = self.project.clips()[idx];
186184 let out = clip.out_frame;
187- match DecodeSession::open_range(&self.path, source, out) {
185+ match DecodeSession::open_range(&self.project.sources()[clip.source], source, out) {
188186 Ok((_, frames, cancel)) => {
189187 self.frames = frames;
190188 self.cancel = cancel;
@@ -219,6 +217,17 @@ impl PlaybackSession {
219217 .collect()
220218 }
221219
220+ /// [`clip_spans`](Self::clip_spans) plus the index into
221+ /// [`Project::sources`] each clip plays from -- what a lane needs to colour
222+ /// an imported clip differently from the file the session was opened with.
223+ pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> {
224+ self.clip_spans()
225+ .into_iter()
226+ .zip(self.project.clips())
227+ .map(|((start, len), clip)| (start, len, clip.source))
228+ .collect()
229+ }
230+
222231 /// Splits the clip under `timeline_secs` in two. Metadata only: a cut never
223232 /// changes the timeline->source mapping, so the running decoder stays
224233 /// correct and playback does not blink. `false` at a clip start or past the
@@ -255,6 +264,61 @@ impl PlaybackSession {
255264 self.edit(Project::undo)
256265 }
257266
267+ /// Appends the whole of `path` to the end of the timeline. One undo step,
268+ /// and the file becomes a source only if it is not one already.
269+ ///
270+ /// Refused unless it matches the timeline exactly -- same dimensions, same
271+ /// frame rate, same audio parameters or both silent -- because one timeline
272+ /// this slice means one set of encoder/device parameters; the `Err` names
273+ /// the property that disagrees, for a caller to show. Nothing is changed by
274+ /// a refusal.
275+ pub fn import(&mut self, path: &Path) -> crate::Result<()> {
276+ let (meta, _) = Demuxer::open(path)?;
277+ if (meta.width, meta.height) != (self.meta.width, self.meta.height) {
278+ return Err(format!(
279+ "{}x{} does not match the timeline's {}x{}",
280+ meta.width, meta.height, self.meta.width, self.meta.height
281+ )
282+ .into());
283+ }
284+ // Container frame rates are computed from timescales, so never `==`.
285+ if (meta.frame_rate - self.meta.frame_rate).abs() > 0.01 {
286+ return Err(format!(
287+ "{:.3} fps does not match the timeline's {:.3} fps",
288+ meta.frame_rate, self.meta.frame_rate
289+ )
290+ .into());
291+ }
292+ // Whole-probe equality: rate, layout and the esds fields, which the
293+ // audio worker holds every source to anyway. Both silent is a match.
294+ let probe = AudioSession::probe(path)?;
295+ let first = AudioSession::probe(&self.project.sources()[0])?;
296+ if probe != first {
297+ return Err(match (probe, first) {
298+ (None, _) => "the file is silent, the timeline has audio".to_string(),
299+ (_, None) => "the file has audio, the timeline is silent".to_string(),
300+ (Some(a), Some(b)) => format!(
301+ "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",
302+ a.params.sample_rate, a.channels, b.params.sample_rate, b.channels
303+ ),
304+ }
305+ .into());
306+ }
307+
308+ let old_end = self.timeline_duration();
309+ let source = self.project.import(path);
310+ // Refused only for an unknown index, and this one just came from `import`.
311+ self.project.append_clip(source, meta.frame_count);
312+ // Reseek like any other edit, even though nothing before the playhead
313+ // moved: the running audio worker's segment list stops at the old end,
314+ // so without this the appended clip would play silent. At EOS the wall
315+ // clock has run on past the timeline, so resume from the join instead
316+ // of wherever it got to -- and the seek is what clears `eos`.
317+ let at = if self.eos { old_end } else { self.now() };
318+ self.seek(at);
319+ Ok(())
320+ }
321+
258322 /// Applies an edit and, if it took, reseeks onto the new mapping. `seek`
259323 /// clamps to the new duration and keeps playing playing, so a delete that
260324 /// shortens the timeline past the playhead lands on the last frame.
@@ -340,7 +404,7 @@ impl PlaybackSession {
340404 if let Some((idx, source)) = self.project.map_timeline(target) {
341405 let clip = self.project.clips()[idx];
342406 let out = clip.out_frame;
343- match DecodeSession::open_range(&self.path, source, out) {
407+ match DecodeSession::open_range(&self.project.sources()[clip.source], source, out) {
344408 Ok((_, frames, cancel)) => {
345409 self.frames = frames;
346410 self.cancel = cancel;
@@ -370,16 +434,10 @@ impl PlaybackSession {
370434 audio.fed_all.store(false, Ordering::Release);
371435 // One worker for the whole rest of the timeline, so the joins
372436 // between clips are gapless: the video reopens at a boundary, the
373- // ear never hears it.
374- // Every source index is 0 until multi-source playback lands; the
375- // audio worker still takes one path plus bare `(start, end)`.
376- let segs: Vec<(f64, f64)> = self
377- .project
378- .segments_from(target, fps)
379- .into_iter()
380- .map(|(_, start, end)| (start, end))
381- .collect();
382- audio_running = match AudioSession::open_segments(&self.path, &segs) {
437+ // ear never hears it -- and a join between two *files* is just
438+ // another segment, because every segment names its own source.
439+ let segs = self.project.segments_from(target, fps);
440+ audio_running = match AudioSession::open_multi_segments(self.project.sources(), &segs) {
383441 Ok(Some((_, rx))) => audio.spawn_feeder(rx),
384442 _ => false,
385443 };
@@ -408,7 +466,7 @@ impl PlaybackSession {
408466 /// Later edits do not reach a running export: it works from a snapshot of
409467 /// the edit list taken here.
410468 pub fn export_to(&self, out: &Path) -> crate::ExportHandle {
411- crate::export::start(&self.path, self.project.clone(), self.meta, out)
469+ crate::export::start(self.project.clone(), self.meta, out)
412470 }
413471
414472 /// Moves the clock forward; the caller runs this once per rendered frame.
crates/engine/tests/export.rsmodified+141 -1
@@ -21,7 +21,7 @@ use std::time::{Duration, Instant};
2121
2222 use engine::hw::HwEncoder;
2323 use engine::mux::{Mp4Muxer, VideoParams, parameter_sets};
24-use engine::{DecodeSession, ExportHandle, PlaybackSession};
24+use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
2525
2626 const FPS: f64 = 30.0;
2727
@@ -170,6 +170,146 @@ fn exports_an_edited_timeline_in_hardware() {
170170 round_trip("hw", Duration::from_secs(60));
171171 }
172172
173+/// `test_av[0,120)` then the whole of `test_av2`: the last second of the first
174+/// source is deleted, so timeline frame 120 is both a cut and a file change --
175+/// the join the multi-source export exists for.
176+fn two_sources() -> Project {
177+ let (av, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).expect("open test_av");
178+ let (av2, _) = engine::demux::Demuxer::open(&asset("test_av2.mp4")).expect("open test_av2");
179+ assert_eq!((av.width, av.height), (av2.width, av2.height), "policy a");
180+
181+ let mut project = Project::single(asset("test_av.mp4"), av.frame_count);
182+ let second = project.import(asset("test_av2.mp4"));
183+ assert_eq!(second, 1, "a second file is a second source");
184+ assert!(project.append_clip(second, av2.frame_count));
185+ assert!(project.cut(120), "cut a second before the end of test_av");
186+ assert!(project.delete(1), "drop test_av's tail");
187+ assert_eq!(project.timeline_frames(), 120 + av2.frame_count);
188+ assert_eq!(
189+ project.clips().iter().map(|c| c.source).collect::<Vec<_>>(),
190+ vec![0, 1]
191+ );
192+ project
193+}
194+
195+/// A timeline spanning two files exports as one: every clip is decoded from its
196+/// own source, the audio is copied across the join, and the result reopens as a
197+/// single stream whose frame at the join is the second file's first frame.
198+fn multi_source_round_trip(name: &str, limit: Duration) {
199+ let project = two_sources();
200+ let total = project.timeline_frames();
201+ let (meta, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).unwrap();
202+ let out = out_path(name);
203+
204+ let started = Instant::now();
205+ let handle = engine::export::start(project.clone(), meta, &out);
206+ wait(&handle, limit).expect("export");
207+ println!(
208+ "{name}: {total} frames of two sources in {:.2} s",
209+ started.elapsed().as_secs_f64()
210+ );
211+
212+ let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen export");
213+ assert_eq!(written.frame_count, total, "timeline frames written");
214+ assert_eq!((written.width, written.height), (1280, 720));
215+
216+ let frames = decode_all(&out);
217+ assert_eq!(
218+ frames.len() as u32,
219+ total,
220+ "every written frame decodes back"
221+ );
222+ // The join: timeline 120 is test_av2's frame 0, timeline 119 still test_av's.
223+ for (timeline, source, source_frame) in [
224+ (0u32, "test_av.mp4", 0u32),
225+ (119, "test_av.mp4", 119),
226+ (120, "test_av2.mp4", 0),
227+ (total - 1, "test_av2.mp4", total - 121),
228+ ] {
229+ let diff = mean_abs_diff(
230+ &frames[timeline as usize],
231+ &frame_at(&asset(source), source_frame),
232+ );
233+ println!("timeline {timeline} vs {source} {source_frame}: mean abs diff {diff:.2}");
234+ assert!(
235+ diff < 6.0,
236+ "timeline frame {timeline} drifted by {diff:.2} from {source} frame {source_frame}"
237+ );
238+ }
239+
240+ // Audio across the join: 1 + 172 + 173. Both segments ask for 4.0 s =
241+ // 172.27 packets, and the head is test_av's own priming packet (the first
242+ // segment's alone -- the join must not add a second one). The first segment
243+ // copies 172 and owes 272 samples, and it is that *carried* debt that makes
244+ // the second copy 173: rounding each source on its own would give 345, so
245+ // this number is the proof the accumulator survives a source change.
246+ let file = File::open(&out).unwrap();
247+ let size = file.metadata().unwrap().len();
248+ let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
249+ let packets = reader.sample_count(2).expect("audio track");
250+ assert_eq!(packets, 346, "packet total across the source join");
251+ let wanted = f64::from(total) / FPS * 44_100.0;
252+ assert!(
253+ (f64::from(packets * 1024) - wanted).abs() < 3.0 * 1024.0,
254+ "audio length {} samples drifted from {wanted}",
255+ packets * 1024
256+ );
257+ let (audio, _) = engine::AudioSession::open(&out)
258+ .expect("reopen export audio")
259+ .expect("export has an audio track");
260+ assert_eq!((audio.sample_rate, audio.channels), (44_100, 2));
261+ std::fs::remove_file(&out).unwrap();
262+}
263+
264+#[test]
265+fn exports_two_sources_as_one_timeline_in_software() {
266+ pin_software();
267+ multi_source_round_trip("multi_sw", Duration::from_secs(180));
268+}
269+
270+#[test]
271+#[ignore]
272+fn exports_two_sources_as_one_timeline_in_hardware() {
273+ pin_hardware();
274+ multi_source_round_trip("multi_hw", Duration::from_secs(60));
275+}
276+
277+/// A source that disappears between the edit and the export fails the export
278+/// rather than silently writing a shorter file -- and leaves neither an output
279+/// nor a `.part`. Both sources are silent, so the failure is the per-clip open
280+/// (the audio pass never touches the second file).
281+#[test]
282+fn a_vanished_source_fails_the_export() {
283+ pin_software();
284+ let baseline = asset("test_baseline.mp4");
285+ let doomed = std::env::temp_dir().join("ve_export_vanished_source.mp4");
286+ std::fs::copy(&baseline, &doomed).expect("copy a second source");
287+ let (meta, _) = engine::demux::Demuxer::open(&baseline).unwrap();
288+
289+ // Five frames of each: the export has to get going and then fail.
290+ let mut project = Project::single(&baseline, meta.frame_count);
291+ assert!(project.cut(5));
292+ assert!(project.delete(1));
293+ let second = project.import(&doomed);
294+ assert!(project.append_clip(second, meta.frame_count));
295+ assert!(project.cut(10));
296+ assert!(project.delete(2));
297+ assert_eq!(project.timeline_frames(), 10);
298+
299+ std::fs::remove_file(&doomed).expect("unlink the second source");
300+ let out = out_path("vanished");
301+ let handle = engine::export::start(project, meta, &out);
302+ let result = wait(&handle, Duration::from_secs(60));
303+ let error = result.expect_err("an export of a missing file cannot succeed");
304+ println!("vanished source: {error}");
305+ assert!(
306+ !out.exists(),
307+ "a failed export still wrote {}",
308+ out.display()
309+ );
310+ assert!(!part_path(&out).exists(), "the .part outlived the failure");
311+}
312+
173313 /// A cancelled export leaves nothing behind -- the half-written file is the
174314 /// thing a user would otherwise try to play.
175315 #[test]
crates/engine/tests/playback.rsmodified+232 -0
@@ -533,3 +533,235 @@ fn edits_keep_the_audio_clock() {
533533 session.timeline_duration()
534534 );
535535 }
536+
537+/// Frame count straight from the container, without decoding anything.
538+fn frame_count(path: &Path) -> u32 {
539+ engine::demux::Demuxer::open(path)
540+ .expect("demux")
541+ .0
542+ .frame_count
543+}
544+
545+/// Import: a second file appended to the timeline, played through as one
546+/// stream. No audio needed for the pictures, so this runs anywhere.
547+#[test]
548+fn import_appends_a_second_source_and_plays_across_the_join() {
549+ let (av, av2) = (asset("test_av.mp4"), asset("test_av2.mp4"));
550+ let mut session = PlaybackSession::open(&av).expect("open");
551+ let (fps, first) = (session.meta().frame_rate, session.meta().frame_count);
552+ let second = frame_count(&av2);
553+ assert_eq!((first, second), (150, 120), "fixtures changed");
554+
555+ session.import(&av2).expect("test_av2 matches test_av");
556+ assert_eq!(session.clip_spans().len(), 2);
557+ assert_eq!(
558+ session
559+ .clip_spans_by_source()
560+ .iter()
561+ .map(|&(.., s)| s)
562+ .collect::<Vec<_>>(),
563+ vec![0, 1],
564+ "the appended clip plays the imported file"
565+ );
566+ assert!(
567+ (session.timeline_duration() - 9.0).abs() < 1e-9,
568+ "5 s + 4 s: {}",
569+ session.timeline_duration()
570+ );
571+
572+ // Play the joined timeline whole, keeping the picture at the join.
573+ session.seek(0.0);
574+ session.play();
575+ let deadline = Instant::now() + Duration::from_secs(30);
576+ let (mut expect, mut boundary) = (0, None);
577+ loop {
578+ session.tick();
579+ while let Some(frame) = session.try_frame() {
580+ assert_eq!(
581+ frame.index, expect,
582+ "timeline indices must be contiguous across a source join"
583+ );
584+ if frame.index == first {
585+ boundary = Some(frame.bgra);
586+ }
587+ expect += 1;
588+ }
589+ if session.is_eos() {
590+ break;
591+ }
592+ assert!(Instant::now() < deadline, "still draining after 30 s");
593+ sleep(Duration::from_millis(4));
594+ }
595+ assert_eq!(expect, first + second, "270 frames, whole and nothing but");
596+ // As everywhere else: stop the clock before asserting on landing frames.
597+ session.pause();
598+ assert!(
599+ boundary.expect("no frame at the join") == source_frame(&av2, 0),
600+ "timeline frame {first} is not the imported file's frame 0"
601+ );
602+
603+ // Edits across the join keep every clip pointing at its own file: cut one
604+ // second into the imported clip, then drop the whole original.
605+ assert!(session.cut_at(6.0), "cut 1 s into the imported clip");
606+ assert_eq!(session.clip_spans().len(), 3);
607+ assert!(session.delete_clip(0), "drop the first source");
608+ assert_eq!(session.clip_spans_by_source()[0].2, 1);
609+ assert!(
610+ (session.timeline_duration() - f64::from(second) / fps).abs() < 1e-9,
611+ "only the imported file is left: {}",
612+ session.timeline_duration()
613+ );
614+ session.seek(0.0);
615+ let landed = next_frame(&mut session, "seek(0.0) after the delete");
616+ assert_eq!(landed.index, 0);
617+ assert!(
618+ landed.bgra == source_frame(&av2, 0),
619+ "the delete lost the source mapping"
620+ );
621+
622+ assert!(session.undo(), "undo the delete");
623+ assert_eq!(session.clip_spans().len(), 3);
624+ let restored = next_frame(&mut session, "undo");
625+ assert_eq!(restored.index, 0);
626+ assert!(
627+ restored.bgra == source_frame(&av, 0),
628+ "undo did not restore the first source"
629+ );
630+}
631+
632+/// One timeline, one set of parameters: everything else is refused by name and
633+/// changes nothing.
634+#[test]
635+fn import_refuses_what_does_not_match() {
636+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
637+
638+ let err = session
639+ .import(&asset("test_mismatch.mp4"))
640+ .expect_err("640x360 must be refused")
641+ .to_string();
642+ assert!(err.contains("640x360"), "refusal must name the size: {err}");
643+
644+ // Same size and rate, no audio track: the timeline has one.
645+ let err = session
646+ .import(&asset("test_baseline.mp4"))
647+ .expect_err("a silent file must be refused")
648+ .to_string();
649+ assert!(err.contains("audio"), "refusal must name the audio: {err}");
650+
651+ assert!(
652+ session.import(&asset("no_such_file.mp4")).is_err(),
653+ "a missing file is an error, not a panic"
654+ );
655+ assert_eq!(session.clip_spans().len(), 1, "a refusal changes nothing");
656+ assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
657+
658+ // The mirror: audio into a silent timeline is refused just as loudly.
659+ let mut silent = PlaybackSession::open(asset("test_baseline.mp4")).expect("open");
660+ let err = silent
661+ .import(&asset("test_av.mp4"))
662+ .expect_err("audio into a silent timeline")
663+ .to_string();
664+ assert!(err.contains("audio"), "refusal must name the audio: {err}");
665+}
666+
667+/// The same file twice is two clips of one source -- a source index is handed
668+/// out once and reused, which is what keeps clipboard clips valid forever.
669+#[test]
670+fn importing_one_file_twice_reuses_its_source() {
671+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
672+ let av2 = asset("test_av2.mp4");
673+ session.import(&av2).expect("first import");
674+ session.import(&av2).expect("second import");
675+ assert_eq!(
676+ session
677+ .clip_spans_by_source()
678+ .iter()
679+ .map(|&(.., s)| s)
680+ .collect::<Vec<_>>(),
681+ vec![0, 1, 1],
682+ "one new source, two clips of it"
683+ );
684+ assert!(
685+ (session.timeline_duration() - 13.0).abs() < 1e-9,
686+ "5 s + 4 s + 4 s: {}",
687+ session.timeline_duration()
688+ );
689+}
690+
691+/// Importing after the timeline has been played out revives the session at the
692+/// join, not at wherever the free-running clock got to.
693+#[test]
694+fn import_at_eos_resumes_into_the_new_clip() {
695+ let av2 = asset("test_av2.mp4");
696+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
697+ let first = session.meta().frame_count;
698+
699+ session.play();
700+ assert_eq!(drain_to_eof(&mut session).1, Some(first - 1));
701+ assert!(session.is_eos());
702+
703+ session.import(&av2).expect("import at EOS");
704+ assert!(!session.is_eos(), "the import did not revive the session");
705+ let landed = next_frame(&mut session, "import at EOS");
706+ assert_eq!(landed.index, first, "resumed at the join");
707+ assert!(
708+ landed.bgra == source_frame(&av2, 0),
709+ "the resume is not showing the imported file"
710+ );
711+ assert_eq!(
712+ drain_to_eof(&mut session).1,
713+ Some(first + frame_count(&av2) - 1),
714+ "the appended clip did not play out"
715+ );
716+}
717+
718+/// A source deleted mid-session: the clip that names it contributes no pictures
719+/// and the timeline still ends, instead of stalling on the missing file.
720+#[test]
721+fn a_vanished_source_is_skipped() {
722+ let scratch =
723+ std::env::temp_dir().join(format!("video_editor_vanish_{}.mp4", std::process::id()));
724+ std::fs::copy(asset("test_av2.mp4"), &scratch).expect("copy the fixture");
725+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
726+ let first = session.meta().frame_count;
727+ session.import(&scratch).expect("import the copy");
728+ std::fs::remove_file(&scratch).expect("unlink");
729+
730+ session.seek(0.0);
731+ session.play();
732+ let (count, last) = drain_to_eof(&mut session);
733+ assert_eq!(last, Some(first - 1), "the vanished clip made pictures");
734+ assert_eq!(count, first, "the first source still played whole");
735+ assert!(session.is_eos(), "the timeline still ends");
736+}
737+
738+/// The audio path across a source join: one worker spans both files, so the
739+/// clock must keep running at real speed through the boundary. (Whether it is
740+/// still the *audio* clock is not observable from outside -- a device that ran
741+/// dry would fall back to wall time at the same speed -- so this catches a
742+/// stall, not a silent fallback.)
743+#[test]
744+#[ignore = "needs a running PipeWire daemon"]
745+fn audio_runs_across_a_source_join() {
746+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
747+ session.import(&asset("test_av2.mp4")).expect("import");
748+ let first = session.meta().frame_count;
749+
750+ session.seek(4.5); // half a second before the join
751+ session.play();
752+ let mut last_index = None;
753+ run_for(&mut session, &mut last_index, Duration::from_millis(1500));
754+ let now = session.now();
755+ eprintln!("join: clock {now:.3}s, frames ..={last_index:?}");
756+ assert!(
757+ (5.4..6.6).contains(&now),
758+ "the clock did not run at real speed across the join: {now:.3}s"
759+ );
760+ assert!(
761+ last_index.map(|i| i > first) == Some(true),
762+ "playback never crossed the join: {last_index:?}"
763+ );
764+ // No EOS assertion: `run_for` takes a frame per 8 ms call, far faster than
765+ // real time, so the decoder may well have reached 9 s while the clock is at
766+ // 6 s (ledger; same reason `edits_keep_the_audio_clock` has none).
767+}