From 07cd3d32486731be146f9b4ae77aaad89014f8e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 04:19:50 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(engine):=20group=20ids=20onl?= =?UTF-8?q?y=20where=20the=20lanes=20agree,=20priming=20for=20a=20leading?= =?UTF-8?q?=20gap?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two states the verifier panel reached that saved but would not load again. `split` and `regroup` handed one fresh id to whichever clip each lane had at that frame, but the lanes are edited apart: the clip being cut may start or end somewhere else in the other lane, and a group id whose two clips disagree about their span is not one take. Each side of the cut now asks the question separately, so the halves that do line up stay one take and the ones that do not get ids of their own. The exported audio of a timeline that opens on a hole played every sound after the hole 23 ms early: a reader drops the first packet of an AAC track as priming, and with no packet to spare that drop came out of the hole. The gap at the head now carries one extra silent packet, which owes the rounding debt nothing. Tests: both panel repros, a seeded random-op sweep that reloads the project after every edit, and the leading-gap onset measured off the exported file (44032 of an expected 44100; 43008 without the packet). --- crates/engine/src/audio.rs | 16 +++- crates/engine/src/project.rs | 138 ++++++++++++++++++++++++++++++---- crates/engine/tests/export.rs | 48 ++++++++++++ 3 files changed, 186 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index b123d38..9ede29f 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -272,7 +272,8 @@ impl AudioSession { /// A segment naming **no** source is a gap, and is copied as that many /// packets of [`silent_packet`] silence — the rounding debt carried through /// it like any other, so the hole occupies its exact duration and the audio - /// after it stays in sync with the picture. + /// after it stays in sync with the picture. A gap the track *opens* on gets + /// one silent packet more, which is the priming a reader drops. pub fn copy_multi_segments( sources: &[PathBuf], segs: &[(Option, f64, f64)], @@ -297,7 +298,14 @@ impl AudioSession { let Some(source) = source else { let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64; let bytes = silent_packet(params.chan_conf)?; - for _ in 0..packet_run(&mut err, ideal, u32::MAX) { + // A reader drops the first packet of an AAC track as the + // encoder's priming. When the track opens on a hole, that has to + // come out of one *extra* packet of silence: dropped out of the + // hole itself it would shorten it, and everything after the hole + // would play a packet early. It is not part of the run, so it + // owes the rounding debt nothing. + let priming = u32::from(packets.is_empty()); + for _ in 0..packet_run(&mut err, ideal, u32::MAX) + priming { packets.push(AacPacket { bytes: bytes.clone(), samples: SAMPLES_PER_PACKET, @@ -318,7 +326,9 @@ impl AudioSession { let ideal = ((end_secs - start_secs).max(0.0) * f64::from(track.sample_rate)) as i64; let available = track.sample_count.saturating_sub(start_id - 1); // The head packet is the priming of the first segment only: a reader - // drops exactly one, so an interior join must not add another. + // drops exactly one, so an interior join must not add another -- + // and neither must a segment behind a leading gap, which already + // paid the priming in silence. let head = (packets.is_empty() && start_id > 1).then(|| start_id - 1); let ids = head .into_iter() diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 70cbb4a..1fedd19 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -376,18 +376,43 @@ impl Project { /// placement's own start, in a gap, and past the end -- all of which would /// produce an empty clip or nothing at all. /// + /// The two lanes' halves share an id only where they are the *same* span: + /// the lanes are edited apart, so the clip being cut here may start (or + /// end) somewhere else in the other lane, and a group id whose two clips + /// disagree about their span is not one take (see [`links_are_consistent`], + /// which refuses to load one). + /// /// Metadata only: no mapping changes, in any lane. pub fn split(&mut self, timeline_frame: u32) -> bool { - if !self - .lanes - .iter() - .any(|lane| splittable(lane, timeline_frame).is_some()) - { + let cut = Lane::ALL + .map(|l| splittable(self.lane(l), timeline_frame).map(|idx| self.lane(l)[idx])); + if cut.iter().all(Option::is_none) { return false; } self.snapshot(); + let same = |f: fn(&Clip) -> u32| match cut { + [Some(a), Some(b)] => f(&a) == f(&b), + _ => false, + }; let (left, right) = (self.new_link(), self.new_link()); - for lane in &mut self.lanes { + // Each side is its own question: two clips may start together and end + // apart, and the halves that do line up stay one take. + let ids = [ + (left, right), + ( + if same(|c| c.start) { + left + } else { + self.new_link() + }, + if same(Clip::end) { + right + } else { + self.new_link() + }, + ), + ]; + for (lane, (left, right)) in self.lanes.iter_mut().zip(ids) { let Some(idx) = splittable(lane, timeline_frame) else { continue; }; @@ -407,18 +432,28 @@ impl Project { /// Only what a split could have produced is rejoined -- the two sides must /// touch on the timeline *and* be consecutive frames of the same source -- /// so the clip list comes back exactly as it was and traversal with it. - /// `false` when no lane has such a pair. + /// `false` when no lane has such a pair. The rejoined clips share one id + /// only when they rejoin into the same span, for [`split`](Project::split)'s + /// reason. pub fn regroup(&mut self, timeline_frame: u32) -> bool { - if !self - .lanes - .iter() - .any(|lane| joinable(lane, timeline_frame).is_some()) - { + // What each lane would end up covering, if it joins here at all. + let joined = Lane::ALL.map(|l| { + joinable(self.lane(l), timeline_frame) + .map(|idx| (self.lane(l)[idx].start, self.lane(l)[idx + 1].end())) + }); + if joined.iter().all(Option::is_none) { return false; } self.snapshot(); let link = self.new_link(); - for lane in &mut self.lanes { + let ids = [ + link, + match joined { + [Some(a), Some(b)] if a == b => link, + _ => self.new_link(), + }, + ]; + for (lane, link) in self.lanes.iter_mut().zip(ids) { let Some(idx) = joinable(lane, timeline_frame) else { continue; }; @@ -1456,4 +1491,81 @@ mod tests { assert!(p.undo()); consistent(&p, "undo"); } + + /// What an edit produces is what a save writes, so *every* state the public + /// API can reach has to load again. The two the verifier panel found where + /// it did not: a split and a regroup handed one group id to two clips that + /// were not the same span, because the lanes had been edited apart. + #[test] + fn every_reachable_state_reloads() { + let mut p = Project::single(FILE, 150); + assert!(p.place(Lane::Audio, 3, clip(0, 0, 50, 0))); + assert!(p.split(10), "the lanes are cut apart at 10"); + reloads(&p, "place on one lane, then split"); + + let mut p = Project::single(FILE, 150); + assert!(p.split(30)); + assert!(p.lift(Lane::Video, 0), "the picture goes, the sound stays"); + assert!(p.regroup(30), "only the audio lane can rejoin"); + assert!(p.split(60)); + reloads(&p, "lift, regroup one lane, split"); + } + + /// The same claim, swept: random op sequences off the public surface, the + /// project reloaded after every one of them. A failure prints its seed, and + /// the seed replays the whole sequence. + #[test] + fn random_edit_sequences_reload() { + for seed in 0..200u64 { + let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + let mut next = move |n: u32| { + // xorshift64*: no dependency, and the seed replays it exactly. + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + (rng >> 33) as u32 % n + }; + let mut p = Project::single(FILE, 40); + for step in 0..24 { + let frame = next(44); + // A clipboard copy carries the group id of the take it came from + // -- the input that made a placement duplicate an id. + let copied = *p + .lane(if next(2) == 0 { + Lane::Video + } else { + Lane::Audio + }) + .get(next(4) as usize) + .unwrap_or(&clip(0, 0, 5, 0)); + let lane = if next(2) == 0 { + Lane::Video + } else { + Lane::Audio + }; + let idx = next(4) as usize; + let _ = match next(9) { + 0 => p.split(frame), + 1 => p.regroup(frame), + 2 => p.lift(lane, idx), + 3 => p.place(lane, frame, copied), + 4 => p.paste(frame, copied), + 5 => p.ripple_delete(frame, next(9)), + 6 => p.delete(idx), + 7 => p.undo(), + _ => p.append_clip(0, 1 + next(9)), + }; + reloads(&p, &format!("seed {seed}, step {step}")); + } + } + } + + /// The save/load round trip a project must survive: the parts a save writes, + /// handed back to the constructor a load goes through. + fn reloads(p: &Project, what: &str) { + let (sources, video, audio) = p.clone().without_orphan_sources(); + if let Err(e) = Project::from_parts(sources, video, audio) { + panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes); + } + } } diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index e02bf1d..7736ecf 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -552,6 +552,54 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec, Vec, Vec< ) } +/// A timeline whose *first* second of sound was lifted. A reader drops the +/// first packet of an AAC track as encoder priming, so a track that opens on a +/// hole has to carry one extra packet of silence for it to drop -- without it +/// the drop comes out of the hole and every sound after the hole plays 23 ms +/// early, which is a lip sync error for the whole export. +#[test] +fn a_leading_audio_gap_keeps_the_sound_after_it_in_place() { + pin_software(); + let source = asset("test_av.mp4"); + let mut session = PlaybackSession::open(&source).expect("open source"); + assert!(session.cut_at(1.0), "cut at 1 s"); + assert!(session.lift_clip(Lane::Audio, 0), "lift the first second"); + session.pause(); + let out = out_path("leading_gap"); + let handle = session.export_to(&out); + wait(&handle, Duration::from_secs(180)).expect("export"); + + let (_, chunks) = engine::AudioSession::open(&out) + .expect("reopen export audio") + .expect("export has an audio track"); + let mut pcm: Vec = Vec::new(); + while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) { + pcm.resize(chunk.start_sample as usize * 2, 0.0); + pcm.extend_from_slice(&chunk.samples); + } + // Where the sound starts, measured in whole packets so the MDCT leak either + // side of the splice cannot be mistaken for the onset: the first block + // carrying a quarter of the export's own peak. + let block = 1024 * 2; + let peak = |b: &[f32]| b.iter().fold(0.0f32, |m, s| m.max(s.abs())); + let loud = peak(&pcm) / 4.0; + let onset = pcm + .chunks(block) + .position(|b| peak(b) > loud) + .expect("the export has no sound at all") as f64 + * 1024.0; + println!("leading gap: sound starts at sample {onset} of an expected 44100"); + assert!( + (onset - 44_100.0).abs() <= 1024.0, + "the sound after the gap is at {onset}, not at the 1 s hole's end" + ); + // ...and the hole really is a hole, not the first second played quietly. + let quiet = peak(&pcm[..(0.9 * 44_100.0) as usize * 2]); + assert!(quiet < 1e-3, "the lifted second is not silent: {quiet}"); + + std::fs::remove_file(&out).unwrap(); +} + /// A timeline with a hole in each lane, exported. The video gap is encoded as /// black rather than skipped -- the file is as long as the timeline, frame for /// frame -- and the audio gap is copied as real silent packets, so the audio