From 68b0ca2579faf82be0018d0fddff3f3f7d7870ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 9 Aug 2026 21:52:21 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20multi-source=20trav?= =?UTF-8?q?ersal,=20import=20validation,=20cross-source=20export?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 44 +++--- crates/engine/src/lib.rs | 2 +- crates/engine/src/playback.rs | 98 +++++++++++--- crates/engine/tests/export.rs | 142 ++++++++++++++++++- crates/engine/tests/playback.rs | 232 ++++++++++++++++++++++++++++++++ 5 files changed, 474 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 0dbfc75..6d1a127 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -77,8 +77,10 @@ impl ExportHandle { } /// Starts the worker. Failures are reported through the handle rather than -/// returned, so a caller has exactly one place to look. -pub(crate) fn start(source: &Path, project: Project, meta: VideoMeta, out: &Path) -> ExportHandle { +/// returned, so a caller has exactly one place to look. The files to read are +/// the project's own [`sources`](Project::sources) -- every clip names one -- +/// so nothing but the edit list decides what is decoded. +pub fn start(project: Project, meta: VideoMeta, out: &Path) -> ExportHandle { let shared = Arc::new(Shared { progress: AtomicU32::new(0), cancel: AtomicBool::new(false), @@ -86,7 +88,6 @@ pub(crate) fn start(source: &Path, project: Project, meta: VideoMeta, out: &Path outcome: Mutex::new(None), }); let worker = Arc::clone(&shared); - let source = source.to_path_buf(); let out = out.to_path_buf(); // `.part`, appended rather than substituted: the temporary of // `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 // The rename is the last step and the only one that publishes a file // under the name the caller asked for; it stays on the same directory, // so it is atomic. - let result = run(&source, &project, &meta, &part, &worker) + let result = run(&project, &meta, &part, &worker) .and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); if result.is_err() { // The muxer -- and with it the file handle -- died with `run`. @@ -117,28 +118,23 @@ fn settle(shared: &Shared, result: crate::Result<()>) { shared.finished.store(true, Ordering::Release); } -fn run( - source: &Path, - project: &Project, - meta: &VideoMeta, - out: &Path, - shared: &Shared, -) -> crate::Result<()> { +fn run(project: &Project, meta: &VideoMeta, out: &Path, shared: &Shared) -> crate::Result<()> { let total = project.timeline_frames(); + let sources = project.sources(); // Audio first: a track has to be declared when the muxer is created, which // happens as soon as the first coded picture arrives. // // ponytail: this holds the whole exported AAC track in memory (~3 kB per // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming // `copy_segments` that yields packets instead of collecting them. - // Source indexes dropped: every clip is still source 0 until multi-source - // export lands, and `copy_segments` takes the one path above. - let segs: Vec<(f64, f64)> = project - .segments_from(0, meta.frame_rate) - .into_iter() - .map(|(_, start, end)| (start, end)) - .collect(); - let audio = AudioSession::copy_segments(source, &segs)?; + // + // The segments name their source, and the copy carries its packet-rounding + // debt across a source join exactly as across a cut, so a timeline spanning + // files stays in sync. A source whose AAC parameters disagree with the + // first one is an `Err` from there -- import refuses those up front, this + // is the backstop -- and the caller deletes the `.part`. + let audio = + AudioSession::copy_multi_segments(sources, &project.segments_from(0, meta.frame_rate))?; let audio_params = audio.as_ref().map(|(track, _)| AudioParams { freq_index: track.freq_index, chan_conf: track.chan_conf, @@ -148,9 +144,13 @@ fn run( let mut muxer = None; let mut done = 0u32; for clip in project.clips() { - // Every clip reopens the file at its own in point; the encoder is *not* - // reopened, so the export is one continuous stream whose GOP boundaries - // need not line up with the cuts. + // Every clip reopens its own source file at its own in point; the + // encoder is *not* reopened, so the export is one continuous stream + // whose GOP boundaries need not line up with the cuts -- nor with the + // file boundaries, which are just cuts that change the path. + let source = sources + .get(clip.source) + .ok_or_else(|| format!("clip names source {} of {}", clip.source, sources.len()))?; let mut pictures = ClipDecoder::open(source, clip.in_frame)?; for _ in 0..clip.len() { cancelled(shared)?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index afdae27..7900765 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -12,7 +12,7 @@ pub mod mux; pub mod playback; pub mod project; -pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioSession}; +pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession}; pub use clock::PlaybackClock; pub use decode::{DecodeSession, Frame}; pub use demux::VideoMeta; diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index ea8f3e0..73b5296 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -1,5 +1,6 @@ -//! 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`]. +//! One timeline over one or more files: 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 //! @@ -10,7 +11,7 @@ //! Drift policy stays with the caller -- this type answers "what time is it", //! the renderer decides which frame that means. -use std::path::{Path, PathBuf}; +use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, TryRecvError}; use std::sync::{Arc, Mutex}; @@ -21,7 +22,7 @@ use crate::ao::AoSession; use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; use crate::decode::{DecodeSession, Frame}; -use crate::demux::VideoMeta; +use crate::demux::{Demuxer, VideoMeta}; use crate::project::{Clip, Project}; /// How long the feeder waits out a full ring. The ring holds a second, so this @@ -81,8 +82,6 @@ impl Audio { /// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`]. pub struct PlaybackSession { - /// Kept for [`PlaybackSession::seek`], which reopens both workers. - path: PathBuf, meta: VideoMeta, frames: Receiver, /// Stops the current decode worker, so an abandoned one cannot outlive a @@ -121,7 +120,6 @@ impl PlaybackSession { let project = Project::single(&path, meta.frame_count); let range = project.clips()[0]; Ok(Self { - path, meta, frames, cancel, @@ -184,7 +182,7 @@ impl PlaybackSession { }; let clip = self.project.clips()[idx]; let out = clip.out_frame; - match DecodeSession::open_range(&self.path, source, out) { + match DecodeSession::open_range(&self.project.sources()[clip.source], source, out) { Ok((_, frames, cancel)) => { self.frames = frames; self.cancel = cancel; @@ -219,6 +217,17 @@ impl PlaybackSession { .collect() } + /// [`clip_spans`](Self::clip_spans) plus the index into + /// [`Project::sources`] each clip plays from -- what a lane needs to colour + /// an imported clip differently from the file the session was opened with. + pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> { + self.clip_spans() + .into_iter() + .zip(self.project.clips()) + .map(|((start, len), clip)| (start, len, clip.source)) + .collect() + } + /// Splits the clip under `timeline_secs` in two. Metadata only: a cut never /// changes the timeline->source mapping, so the running decoder stays /// correct and playback does not blink. `false` at a clip start or past the @@ -255,6 +264,61 @@ impl PlaybackSession { self.edit(Project::undo) } + /// Appends the whole of `path` to the end of the timeline. One undo step, + /// and the file becomes a source only if it is not one already. + /// + /// Refused unless it matches the timeline exactly -- same dimensions, same + /// frame rate, same audio parameters or both silent -- because one timeline + /// this slice means one set of encoder/device parameters; the `Err` names + /// the property that disagrees, for a caller to show. Nothing is changed by + /// a refusal. + pub fn import(&mut self, path: &Path) -> crate::Result<()> { + let (meta, _) = Demuxer::open(path)?; + if (meta.width, meta.height) != (self.meta.width, self.meta.height) { + return Err(format!( + "{}x{} does not match the timeline's {}x{}", + meta.width, meta.height, self.meta.width, self.meta.height + ) + .into()); + } + // Container frame rates are computed from timescales, so never `==`. + if (meta.frame_rate - self.meta.frame_rate).abs() > 0.01 { + return Err(format!( + "{:.3} fps does not match the timeline's {:.3} fps", + meta.frame_rate, self.meta.frame_rate + ) + .into()); + } + // Whole-probe equality: rate, layout and the esds fields, which the + // audio worker holds every source to anyway. Both silent is a match. + let probe = AudioSession::probe(path)?; + let first = AudioSession::probe(&self.project.sources()[0])?; + if probe != first { + return Err(match (probe, first) { + (None, _) => "the file is silent, the timeline has audio".to_string(), + (_, None) => "the file has audio, the timeline is silent".to_string(), + (Some(a), Some(b)) => format!( + "audio {} Hz {} ch does not match the timeline's {} Hz {} ch", + a.params.sample_rate, a.channels, b.params.sample_rate, b.channels + ), + } + .into()); + } + + let old_end = self.timeline_duration(); + let source = self.project.import(path); + // Refused only for an unknown index, and this one just came from `import`. + self.project.append_clip(source, meta.frame_count); + // Reseek like any other edit, even though nothing before the playhead + // moved: the running audio worker's segment list stops at the old end, + // so without this the appended clip would play silent. At EOS the wall + // clock has run on past the timeline, so resume from the join instead + // of wherever it got to -- and the seek is what clears `eos`. + let at = if self.eos { old_end } else { self.now() }; + self.seek(at); + Ok(()) + } + /// Applies an edit and, if it took, reseeks onto the new mapping. `seek` /// clamps to the new duration and keeps playing playing, so a delete that /// shortens the timeline past the playhead lands on the last frame. @@ -340,7 +404,7 @@ impl PlaybackSession { if let Some((idx, source)) = self.project.map_timeline(target) { let clip = self.project.clips()[idx]; let out = clip.out_frame; - match DecodeSession::open_range(&self.path, source, out) { + match DecodeSession::open_range(&self.project.sources()[clip.source], source, out) { Ok((_, frames, cancel)) => { self.frames = frames; self.cancel = cancel; @@ -370,16 +434,10 @@ impl PlaybackSession { audio.fed_all.store(false, Ordering::Release); // One worker for the whole rest of the timeline, so the joins // between clips are gapless: the video reopens at a boundary, the - // ear never hears it. - // Every source index is 0 until multi-source playback lands; the - // audio worker still takes one path plus bare `(start, end)`. - let segs: Vec<(f64, f64)> = self - .project - .segments_from(target, fps) - .into_iter() - .map(|(_, start, end)| (start, end)) - .collect(); - audio_running = match AudioSession::open_segments(&self.path, &segs) { + // ear never hears it -- and a join between two *files* is just + // another segment, because every segment names its own source. + let segs = self.project.segments_from(target, fps); + audio_running = match AudioSession::open_multi_segments(self.project.sources(), &segs) { Ok(Some((_, rx))) => audio.spawn_feeder(rx), _ => false, }; @@ -408,7 +466,7 @@ impl PlaybackSession { /// Later edits do not reach a running export: it works from a snapshot of /// the edit list taken here. pub fn export_to(&self, out: &Path) -> crate::ExportHandle { - crate::export::start(&self.path, self.project.clone(), self.meta, out) + crate::export::start(self.project.clone(), self.meta, out) } /// Moves the clock forward; the caller runs this once per rendered frame. diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 0b84f18..c0b5bc1 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -21,7 +21,7 @@ use std::time::{Duration, Instant}; use engine::hw::HwEncoder; use engine::mux::{Mp4Muxer, VideoParams, parameter_sets}; -use engine::{DecodeSession, ExportHandle, PlaybackSession}; +use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; const FPS: f64 = 30.0; @@ -170,6 +170,146 @@ fn exports_an_edited_timeline_in_hardware() { round_trip("hw", Duration::from_secs(60)); } +/// `test_av[0,120)` then the whole of `test_av2`: the last second of the first +/// source is deleted, so timeline frame 120 is both a cut and a file change -- +/// the join the multi-source export exists for. +fn two_sources() -> Project { + let (av, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).expect("open test_av"); + let (av2, _) = engine::demux::Demuxer::open(&asset("test_av2.mp4")).expect("open test_av2"); + assert_eq!((av.width, av.height), (av2.width, av2.height), "policy a"); + + let mut project = Project::single(asset("test_av.mp4"), av.frame_count); + let second = project.import(asset("test_av2.mp4")); + assert_eq!(second, 1, "a second file is a second source"); + assert!(project.append_clip(second, av2.frame_count)); + assert!(project.cut(120), "cut a second before the end of test_av"); + assert!(project.delete(1), "drop test_av's tail"); + assert_eq!(project.timeline_frames(), 120 + av2.frame_count); + assert_eq!( + project.clips().iter().map(|c| c.source).collect::>(), + vec![0, 1] + ); + project +} + +/// A timeline spanning two files exports as one: every clip is decoded from its +/// own source, the audio is copied across the join, and the result reopens as a +/// single stream whose frame at the join is the second file's first frame. +fn multi_source_round_trip(name: &str, limit: Duration) { + let project = two_sources(); + let total = project.timeline_frames(); + let (meta, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).unwrap(); + let out = out_path(name); + + let started = Instant::now(); + let handle = engine::export::start(project.clone(), meta, &out); + wait(&handle, limit).expect("export"); + println!( + "{name}: {total} frames of two sources in {:.2} s", + started.elapsed().as_secs_f64() + ); + + let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen export"); + assert_eq!(written.frame_count, total, "timeline frames written"); + assert_eq!((written.width, written.height), (1280, 720)); + + let frames = decode_all(&out); + assert_eq!( + frames.len() as u32, + total, + "every written frame decodes back" + ); + // The join: timeline 120 is test_av2's frame 0, timeline 119 still test_av's. + for (timeline, source, source_frame) in [ + (0u32, "test_av.mp4", 0u32), + (119, "test_av.mp4", 119), + (120, "test_av2.mp4", 0), + (total - 1, "test_av2.mp4", total - 121), + ] { + let diff = mean_abs_diff( + &frames[timeline as usize], + &frame_at(&asset(source), source_frame), + ); + println!("timeline {timeline} vs {source} {source_frame}: mean abs diff {diff:.2}"); + assert!( + diff < 6.0, + "timeline frame {timeline} drifted by {diff:.2} from {source} frame {source_frame}" + ); + } + + // Audio across the join: 1 + 172 + 173. Both segments ask for 4.0 s = + // 172.27 packets, and the head is test_av's own priming packet (the first + // segment's alone -- the join must not add a second one). The first segment + // copies 172 and owes 272 samples, and it is that *carried* debt that makes + // the second copy 173: rounding each source on its own would give 345, so + // this number is the proof the accumulator survives a source change. + let file = File::open(&out).unwrap(); + let size = file.metadata().unwrap().len(); + let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); + let packets = reader.sample_count(2).expect("audio track"); + assert_eq!(packets, 346, "packet total across the source join"); + let wanted = f64::from(total) / FPS * 44_100.0; + assert!( + (f64::from(packets * 1024) - wanted).abs() < 3.0 * 1024.0, + "audio length {} samples drifted from {wanted}", + packets * 1024 + ); + let (audio, _) = engine::AudioSession::open(&out) + .expect("reopen export audio") + .expect("export has an audio track"); + assert_eq!((audio.sample_rate, audio.channels), (44_100, 2)); + std::fs::remove_file(&out).unwrap(); +} + +#[test] +fn exports_two_sources_as_one_timeline_in_software() { + pin_software(); + multi_source_round_trip("multi_sw", Duration::from_secs(180)); +} + +#[test] +#[ignore] +fn exports_two_sources_as_one_timeline_in_hardware() { + pin_hardware(); + multi_source_round_trip("multi_hw", Duration::from_secs(60)); +} + +/// A source that disappears between the edit and the export fails the export +/// rather than silently writing a shorter file -- and leaves neither an output +/// nor a `.part`. Both sources are silent, so the failure is the per-clip open +/// (the audio pass never touches the second file). +#[test] +fn a_vanished_source_fails_the_export() { + pin_software(); + let baseline = asset("test_baseline.mp4"); + let doomed = std::env::temp_dir().join("ve_export_vanished_source.mp4"); + std::fs::copy(&baseline, &doomed).expect("copy a second source"); + let (meta, _) = engine::demux::Demuxer::open(&baseline).unwrap(); + + // Five frames of each: the export has to get going and then fail. + let mut project = Project::single(&baseline, meta.frame_count); + assert!(project.cut(5)); + assert!(project.delete(1)); + let second = project.import(&doomed); + assert!(project.append_clip(second, meta.frame_count)); + assert!(project.cut(10)); + assert!(project.delete(2)); + assert_eq!(project.timeline_frames(), 10); + + std::fs::remove_file(&doomed).expect("unlink the second source"); + let out = out_path("vanished"); + let handle = engine::export::start(project, meta, &out); + let result = wait(&handle, Duration::from_secs(60)); + let error = result.expect_err("an export of a missing file cannot succeed"); + println!("vanished source: {error}"); + assert!( + !out.exists(), + "a failed export still wrote {}", + out.display() + ); + assert!(!part_path(&out).exists(), "the .part outlived the failure"); +} + /// A cancelled export leaves nothing behind -- the half-written file is the /// thing a user would otherwise try to play. #[test] diff --git a/crates/engine/tests/playback.rs b/crates/engine/tests/playback.rs index 80a76ca..eb2ab8f 100644 --- a/crates/engine/tests/playback.rs +++ b/crates/engine/tests/playback.rs @@ -533,3 +533,235 @@ fn edits_keep_the_audio_clock() { session.timeline_duration() ); } + +/// Frame count straight from the container, without decoding anything. +fn frame_count(path: &Path) -> u32 { + engine::demux::Demuxer::open(path) + .expect("demux") + .0 + .frame_count +} + +/// Import: a second file appended to the timeline, played through as one +/// stream. No audio needed for the pictures, so this runs anywhere. +#[test] +fn import_appends_a_second_source_and_plays_across_the_join() { + let (av, av2) = (asset("test_av.mp4"), asset("test_av2.mp4")); + let mut session = PlaybackSession::open(&av).expect("open"); + let (fps, first) = (session.meta().frame_rate, session.meta().frame_count); + let second = frame_count(&av2); + assert_eq!((first, second), (150, 120), "fixtures changed"); + + session.import(&av2).expect("test_av2 matches test_av"); + assert_eq!(session.clip_spans().len(), 2); + assert_eq!( + session + .clip_spans_by_source() + .iter() + .map(|&(.., s)| s) + .collect::>(), + vec![0, 1], + "the appended clip plays the imported file" + ); + assert!( + (session.timeline_duration() - 9.0).abs() < 1e-9, + "5 s + 4 s: {}", + session.timeline_duration() + ); + + // Play the joined timeline whole, keeping the picture at the join. + session.seek(0.0); + session.play(); + let deadline = Instant::now() + Duration::from_secs(30); + let (mut expect, mut boundary) = (0, None); + loop { + session.tick(); + while let Some(frame) = session.try_frame() { + assert_eq!( + frame.index, expect, + "timeline indices must be contiguous across a source join" + ); + if frame.index == first { + boundary = Some(frame.bgra); + } + expect += 1; + } + if session.is_eos() { + break; + } + assert!(Instant::now() < deadline, "still draining after 30 s"); + sleep(Duration::from_millis(4)); + } + assert_eq!(expect, first + second, "270 frames, whole and nothing but"); + // As everywhere else: stop the clock before asserting on landing frames. + session.pause(); + assert!( + boundary.expect("no frame at the join") == source_frame(&av2, 0), + "timeline frame {first} is not the imported file's frame 0" + ); + + // Edits across the join keep every clip pointing at its own file: cut one + // second into the imported clip, then drop the whole original. + assert!(session.cut_at(6.0), "cut 1 s into the imported clip"); + assert_eq!(session.clip_spans().len(), 3); + assert!(session.delete_clip(0), "drop the first source"); + assert_eq!(session.clip_spans_by_source()[0].2, 1); + assert!( + (session.timeline_duration() - f64::from(second) / fps).abs() < 1e-9, + "only the imported file is left: {}", + session.timeline_duration() + ); + session.seek(0.0); + let landed = next_frame(&mut session, "seek(0.0) after the delete"); + assert_eq!(landed.index, 0); + assert!( + landed.bgra == source_frame(&av2, 0), + "the delete lost the source mapping" + ); + + assert!(session.undo(), "undo the delete"); + assert_eq!(session.clip_spans().len(), 3); + let restored = next_frame(&mut session, "undo"); + assert_eq!(restored.index, 0); + assert!( + restored.bgra == source_frame(&av, 0), + "undo did not restore the first source" + ); +} + +/// One timeline, one set of parameters: everything else is refused by name and +/// changes nothing. +#[test] +fn import_refuses_what_does_not_match() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + + let err = session + .import(&asset("test_mismatch.mp4")) + .expect_err("640x360 must be refused") + .to_string(); + assert!(err.contains("640x360"), "refusal must name the size: {err}"); + + // Same size and rate, no audio track: the timeline has one. + let err = session + .import(&asset("test_baseline.mp4")) + .expect_err("a silent file must be refused") + .to_string(); + assert!(err.contains("audio"), "refusal must name the audio: {err}"); + + assert!( + session.import(&asset("no_such_file.mp4")).is_err(), + "a missing file is an error, not a panic" + ); + assert_eq!(session.clip_spans().len(), 1, "a refusal changes nothing"); + assert!((session.timeline_duration() - 5.0).abs() < 1e-9); + + // The mirror: audio into a silent timeline is refused just as loudly. + let mut silent = PlaybackSession::open(asset("test_baseline.mp4")).expect("open"); + let err = silent + .import(&asset("test_av.mp4")) + .expect_err("audio into a silent timeline") + .to_string(); + assert!(err.contains("audio"), "refusal must name the audio: {err}"); +} + +/// The same file twice is two clips of one source -- a source index is handed +/// out once and reused, which is what keeps clipboard clips valid forever. +#[test] +fn importing_one_file_twice_reuses_its_source() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + let av2 = asset("test_av2.mp4"); + session.import(&av2).expect("first import"); + session.import(&av2).expect("second import"); + assert_eq!( + session + .clip_spans_by_source() + .iter() + .map(|&(.., s)| s) + .collect::>(), + vec![0, 1, 1], + "one new source, two clips of it" + ); + assert!( + (session.timeline_duration() - 13.0).abs() < 1e-9, + "5 s + 4 s + 4 s: {}", + session.timeline_duration() + ); +} + +/// Importing after the timeline has been played out revives the session at the +/// join, not at wherever the free-running clock got to. +#[test] +fn import_at_eos_resumes_into_the_new_clip() { + let av2 = asset("test_av2.mp4"); + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + let first = session.meta().frame_count; + + session.play(); + assert_eq!(drain_to_eof(&mut session).1, Some(first - 1)); + assert!(session.is_eos()); + + session.import(&av2).expect("import at EOS"); + assert!(!session.is_eos(), "the import did not revive the session"); + let landed = next_frame(&mut session, "import at EOS"); + assert_eq!(landed.index, first, "resumed at the join"); + assert!( + landed.bgra == source_frame(&av2, 0), + "the resume is not showing the imported file" + ); + assert_eq!( + drain_to_eof(&mut session).1, + Some(first + frame_count(&av2) - 1), + "the appended clip did not play out" + ); +} + +/// A source deleted mid-session: the clip that names it contributes no pictures +/// and the timeline still ends, instead of stalling on the missing file. +#[test] +fn a_vanished_source_is_skipped() { + let scratch = + std::env::temp_dir().join(format!("video_editor_vanish_{}.mp4", std::process::id())); + std::fs::copy(asset("test_av2.mp4"), &scratch).expect("copy the fixture"); + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + let first = session.meta().frame_count; + session.import(&scratch).expect("import the copy"); + std::fs::remove_file(&scratch).expect("unlink"); + + session.seek(0.0); + session.play(); + let (count, last) = drain_to_eof(&mut session); + assert_eq!(last, Some(first - 1), "the vanished clip made pictures"); + assert_eq!(count, first, "the first source still played whole"); + assert!(session.is_eos(), "the timeline still ends"); +} + +/// The audio path across a source join: one worker spans both files, so the +/// clock must keep running at real speed through the boundary. (Whether it is +/// still the *audio* clock is not observable from outside -- a device that ran +/// dry would fall back to wall time at the same speed -- so this catches a +/// stall, not a silent fallback.) +#[test] +#[ignore = "needs a running PipeWire daemon"] +fn audio_runs_across_a_source_join() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + session.import(&asset("test_av2.mp4")).expect("import"); + let first = session.meta().frame_count; + + session.seek(4.5); // half a second before the join + session.play(); + let mut last_index = None; + run_for(&mut session, &mut last_index, Duration::from_millis(1500)); + let now = session.now(); + eprintln!("join: clock {now:.3}s, frames ..={last_index:?}"); + assert!( + (5.4..6.6).contains(&now), + "the clock did not run at real speed across the join: {now:.3}s" + ); + assert!( + last_index.map(|i| i > first) == Some(true), + "playback never crossed the join: {last_index:?}" + ); + // No EOS assertion: `run_for` takes a frame per 8 ms call, far faster than + // real time, so the decoder may well have reached 9 s while the clock is at + // 6 s (ledger; same reason `edits_keep_the_audio_clock` has none). +}