From 64e09f91bb2cf54a70fa9b1925a4d59c4848e05b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 07:14:42 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(engine):=20the=20export=20st?= =?UTF-8?q?ops=20with=20the=20last=20picture,=20caption=20or=20no=20captio?= =?UTF-8?q?n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A caption hanging past the media held the timeline open and the picture loop walked it: 312 encoded frames under a 240-frame delivery, 72 of them black, the copied sound padded to match, and the plan card saying cues were "cut off there" of a file three seconds longer than it said. `export_spans` is now the one place that end is decided -- the composite walk cut to `media_frames` -- and both the encoding loop and the copy plan take it; `copy_audio` drops the trailing gap the same walk leaves on its play list. Playback still walks `timeline_frames`, so the transport parks on the tail. --- crates/engine/src/export.rs | 52 +++++++++++++++-- crates/engine/tests/export_subs.rs | 89 ++++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 50f1ed8..433f800 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -924,6 +924,27 @@ fn lane_subtitles(project: &Project, fps: f64) -> Vec { .collect() } +/// The composite spans an export *writes*: [`Project::composite_spans_from`] +/// cut to where the media runs out ([`Project::media_frames`]). +/// +/// The walk itself is the timeline's ([`Project::timeline_frames`]), because a +/// caption placed past the last picture holds the timeline open under it and +/// playback parks on that tail -- but there is nothing to *write* out there, so +/// an unbounded walk encoded and muxed black frames past the end of the media +/// and padded the sound to match. This is the one place that end is decided: +/// the frame count [`run`] publishes, the cues [`lane_subtitles`] clips and the +/// blocks [`CopyPlan`] copies are then the same number by construction, which +/// is what makes [`planned_lanes`]' "cut off there" true of the file. +fn export_spans(project: &Project) -> Vec { + let end = project.media_frames(); + let mut spans = project.composite_spans_from(0); + spans.retain(|span| span.start < end); + for span in &mut spans { + span.len = span.len.min(end - span.start); + } + spans +} + /// The track's cues where the *exported* timeline puts them, which is the only /// clock the file has: the export writes timeline frame 0 onwards and nothing /// else, exactly as the sound is mixed from frame 0 and resized to the @@ -1275,7 +1296,24 @@ fn copy_audio( // everything on `A2`), and copying `A1`'s list in that case would write a // file with no audio track at all -- silently, which is the failure this // whole comment is about. - let lanes = project.audio_segments_from(0, meta.frame_rate); + let mut lanes = project.audio_segments_from(0, meta.frame_rate); + // ...cut to what the picture writes ([`export_spans`]). The play list is + // the *timeline's* ([`Project::timeline_frames`]), so a caption hanging past + // the last picture ends every audio lane with a trailing gap -- silence this + // path would copy out past the last frame, three seconds of it on the film + // this was found on. Only a gap can be out there (`media_frames` is the last + // clip's own end), and the mixed paths already resize to the same length + // ([`encode_audio`]); a copy carries source packets and has no resize. + let over = f64::from(project.timeline_frames() - project.media_frames()) / meta.frame_rate; + for lane in &mut lanes { + match lane.last_mut() { + Some((None, _, len)) if *len > over => *len -= over, + Some((None, _, _)) if over > 0.0 => { + lane.pop(); + } + _ => {} + } + } let [segments] = &lanes[..] else { return encode_audio(project, meta, kbps, mkv, shared); }; @@ -1414,7 +1452,7 @@ impl CopyPlan { let mut sources: Vec> = (0..entries.len()).map(|_| None).collect(); let mut declared: Option<(Vec, ColorDescription)> = None; let mut regions: Vec = Vec::new(); - for span in project.composite_spans_from(0) { + for span in export_spans(project) { // A gap is black frames, which only an encoder makes. let (source, in_frame) = span.from?; if !span.speed.is_normal() { @@ -2230,10 +2268,12 @@ fn run( let black = Black::new(meta); // Spans, not clips: a gap in the video is part of the timeline and gets // encoded too, as black frames. The picture count is therefore - // `timeline_frames` however the lanes are arranged -- and *which* lane a - // span comes from is `composite_spans_from`'s answer, the same one playback - // shows, so an export is what was watched. - for span in project.composite_spans_from(0) { + // `media_frames` however the lanes are arranged -- [`export_spans`] is that + // walk cut to it, so `done` ends on the `total` above instead of running + // past it under a trailing caption -- and *which* lane a span comes from is + // `composite_spans_from`'s answer, the same one playback shows, so an + // export is what was watched. + for span in export_spans(project) { // 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 diff --git a/crates/engine/tests/export_subs.rs b/crates/engine/tests/export_subs.rs index d590bc5..4478265 100644 --- a/crates/engine/tests/export_subs.rs +++ b/crates/engine/tests/export_subs.rs @@ -156,6 +156,10 @@ fn exported_want( }, ); wait(&handle, Duration::from_secs(300)).expect("the export finishes"); + // The bar ends where it was told it would: the picture loop's own count and + // the total published for it are one number ([`export::export_spans`]), so a + // walk that ran past the media would show up here as well as in the file. + assert_eq!(handle.progress(), 1.0, "finished at full progress"); let tracks = subtitle::of_matroska(&out).expect("read the export back"); assert_eq!(tracks.len(), want, "exactly the tracks asked for: {tracks:?}"); for track in &tracks { @@ -218,6 +222,54 @@ fn ffmpeg_streams(path: &Path) -> Option { Some(listing) } +/// The average luma of the **last** picture in `path`, as ffmpeg's +/// `signalstats` measures it: what says a file's tail is a picture and not the +/// encoded black a walk past the media would leave. `None` where there is no +/// ffmpeg on the box, the same posture the readers above take. +fn ffmpeg_last_luma(path: &Path) -> Option { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args([ + "-vf", + "signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-", + "-f", + "null", + "-", + ]) + .output() + .ok()?; + assert!( + out.status.success(), + "ffmpeg refused the exported picture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let printed = String::from_utf8_lossy(&out.stdout).into_owned(); + let last = printed + .lines() + .filter_map(|line| line.split_once("YAVG=").map(|(_, v)| v.trim().to_string())) + .next_back() + .expect("signalstats printed a YAVG per frame"); + println!("last written picture: YAVG {last}"); + Some(last.parse().expect("YAVG is a number")) +} + +/// When the file's **last sound** is, as ffprobe reads the packets: the sound is +/// the other end that has to stop with the picture -- a copied lane's trailing +/// gap is silence written past the last frame. `None` where there is no ffprobe. +fn ffprobe_last_audio_pts(path: &Path) -> Option { + let out = Command::new("ffprobe") + .args(["-v", "error", "-select_streams", "a:0"]) + .args(["-show_entries", "packet=pts_time", "-of", "csv=p=0"]) + .arg(path) + .output() + .ok()?; + let printed = String::from_utf8_lossy(&out.stdout).into_owned(); + let last = printed.lines().filter(|l| !l.trim().is_empty()).next_back()?; + println!("last audio packet: {last} s"); + last.trim_end_matches(',').parse().ok() +} + fn near(got: i64, want: i64, what: &str) { assert!( (got - want).abs() <= SLACK_US, @@ -968,6 +1020,43 @@ fn a_caption_past_the_last_picture_is_cut_off_with_the_file() { assert_eq!(cues.len(), 1, "the one cue the window holds: {cues:?}"); near(cues[0].start_us, 4_500_000, "where the placement puts it"); near(cues[0].end_us, 5_000_000, "cut off with the last picture"); + + // ...and the *file* is that long, which is what makes the sentence above + // true rather than merely written: the picture stops with the media and the + // 60 frames the caption hangs over it are not encoded black. + let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen the export"); + assert_eq!( + written.frame_count, FRAMES, + "the pictures end with the media, not with the caption" + ); + // A count alone would pass on a file whose tail is black, so the last + // picture is *looked at*: a padded frame is 16/128/128 and reads back at + // YAVG 16. ffmpeg does the looking -- this file is HEVC and there is no + // software HEVC decoder here to read it back with. + match ffmpeg_last_luma(&out) { + Some(luma) => assert!( + luma > 20.0, + "the last written picture is black (YAVG {luma:.2}): the walk ran past the media" + ), + None => println!("no ffmpeg on this box: the frame count is the only witness"), + } + // ...and the sound stops with the picture: the copied lane's trailing gap + // is the same overhang, written as silence rather than as black. + let duration_s = f64::from(written.frame_count) / written.frame_rate; + match ffprobe_last_audio_pts(&out) { + Some(pts) => assert!( + pts <= duration_s, + "the sound runs to {pts:.3} s, past the picture's {duration_s:.3} s" + ), + None => println!("no ffprobe on this box: the picture is the only witness"), + } + // The cue is inside the file it was clipped to, by the file's own clock. + let duration_us = (duration_s * 1e6).round() as i64; + assert!( + cues[0].end_us <= duration_us + SLACK_US, + "the cue ends at {} us, past the file's {duration_us} us", + cues[0].end_us + ); std::fs::remove_file(&out).unwrap(); }