From e5b7da5560b2655337217a4f919985ad987f4ceb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 13 Aug 2026 16:40:52 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(export):=20one=20bar,=20two?= =?UTF-8?q?=20threads,=20and=20it=20may=20only=20ever=20go=20forwards?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Moving the audio pass onto a thread of its own put two stages on one progress number, and `encode_audio` still wrote its share of the band with `store`: every chunk of the mix pulled the bar back to the sound's small figure while the picture was publishing a large one. Measured on the film's AC-3 track, 12,000 frames: 4,489 backward steps, the worst of them from 5% to 0%. `fetch_max`, and 0 backward steps over the same run. The rule is written on `Shared::progress` rather than only at the call site, because it is the class and not the instance: any stage that can run beside another writes that field with `fetch_max`, never `store`. A `store` is left only where nothing else can be publishing at all -- the terminal `PROGRESS_SCALE`, and the audio-only export that has no second thread. `encode_audio` also had no cancellation checkpoint anywhere in it, which nobody could see while it ran in front of the picture: cancelling an export then left a detached thread mixing the whole timeline behind a job whose outcome was already settled, still writing into its `Shared`. Measured before the fix, cancelling a 12,000-frame export one second in: the mixer went on to finish all 500 s of sound and the process was still busy 1.45 s after the export reported itself finished -- minutes, on a feature film. With the poll in the mix loop, and two more before the encoders that have no checkpoint of their own, the same cancel leaves no thread behind at all (quiet in 0.00 s, and the "mixed ... s of sound" line the mixer prints on completion never appears). And the mp4 muxer's fps on a capped bench run is derived from the highest progress the poll loop saw rather than from one read at the end, which is the same fragility one layer up. --- crates/engine/examples/bench.rs | 9 +++++++- crates/engine/src/export.rs | 40 ++++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs index aee986c..14e663a 100644 --- a/crates/engine/examples/bench.rs +++ b/crates/engine/examples/bench.rs @@ -434,7 +434,14 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { let handle = engine::export::start(project.clone(), meta, &out, &settings); let t = Instant::now(); let mut capped = false; + // The highest the bar was ever seen at, not wherever it happens to + // stand when the clock stops: an export publishes one bar from two + // stages, and a capped run's rate is derived from this number. Taking + // the maximum over the poll loop means a single unlucky read cannot + // under-report the work that was really done. + let mut peak = 0.0f64; while !handle.is_finished() { + peak = peak.max(f64::from(handle.progress())); if t.elapsed() >= cap { capped = true; handle.cancel(); @@ -444,7 +451,7 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { } // A cancel is answered at the worker's next checkpoint; the rate is // read from the progress at the moment the clock stopped either way. - let progress = f64::from(handle.progress()); + let progress = peak.max(f64::from(handle.progress())); let elapsed = t.elapsed().as_secs_f64(); let done = Instant::now() + Duration::from_secs(60); while !handle.is_finished() && Instant::now() < done { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index fc4cb0c..a3e84ad 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -303,6 +303,17 @@ pub struct ExportSettings { } struct Shared { + /// Fraction of the job done, in [`PROGRESS_SCALE`]ths. + /// + /// **Every stage that can run beside another writes this with `fetch_max`, + /// never `store`.** The sound and the picture are two threads publishing + /// two bands of one bar ([`AUDIO_BAND`]): a `store` from the lower band + /// pulls the bar backwards every time the other thread has already moved + /// it on, which is what a person sees as a progress bar that stutters + /// backwards -- 5,458 backward steps over one film export before this rule + /// was written down. A `store` is only correct where nothing else can be + /// publishing at all, which now means the terminal [`PROGRESS_SCALE`] and + /// the audio-only export ([`run_audio`]) that has no second thread. progress: AtomicU32, cancel: AtomicBool, finished: AtomicBool, @@ -1325,10 +1336,21 @@ fn encode_audio( * channels; let mut samples: Vec = Vec::with_capacity(total); for chunk in chunks { + // The only place a cancelled export can be answered before the whole + // timeline has been mixed. This pass runs on a thread of its own now + // ([`run`]), so without this a cancel left it mixing a feature film + // for minutes behind a job nobody is waiting for any more, writing + // into a `Shared` whose outcome was already settled. + cancelled(shared)?; samples.extend(chunk.samples); // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of // the three stages and the only one that can be counted as it goes. - shared.progress.store( + // + // `fetch_max` and not `store`, for the reason [`Shared::progress`] + // states: this runs on the audio thread while the picture publishes + // numbers above [`AUDIO_BAND`] from the other, and a `store` of this + // small one pulled the bar backwards 5,458 times over one film export. + shared.progress.fetch_max( (samples.len().min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32, Ordering::Relaxed, ); @@ -1351,6 +1373,10 @@ fn encode_audio( // there is no resampler on this path, and inventing one to reach 48 kHz // would resample a whole timeline to satisfy a codec, which is a bigger // change to the sound than the codec is. + // ...and again before either encoder is entered: both of them run to the + // end of the mix without a checkpoint of their own, so this is the last + // moment a cancel costs seconds rather than the whole encode. + cancelled(shared)?; if mkv && audio.sample_rate == OPUS_RATE && channels == 2 @@ -1380,6 +1406,7 @@ fn encode_audio( // `next_packet` after `finish` yields packets until `Eof` and nothing else, // so the loop ends on the only error it can see. while let Ok(packet) = encoder.next_packet() { + cancelled(shared)?; packets.push(crate::AacPacket { bytes: packet.data, samples: packet.duration, @@ -1756,6 +1783,17 @@ fn run( // A Matroska file (and a copied one, whose muxer is the same) collects it // here; an mp4 leaves it running and collects it under the picture below. let mut audio_job = Some(audio_job); + // The condition is the *format*, and the copied-picture path below relies + // on that covering it too: `plan` hands its packets straight to a Matroska + // muxer, so it may only exist where this has already collected them -- + // which holds because [`CopyPlan::of`] returns `None` for every format + // that is not `Hevc` or `Av1`, both of which are `is_mkv`. Said out loud + // because a copy plan for an mp4 would otherwise reach `plan.run` with the + // sound still being mixed on the other thread. + debug_assert!( + settings.format.is_mkv() || plan.is_none(), + "a copy plan outside Matroska would run before its sound is collected" + ); let audio = match settings.format.is_mkv() { true => join_audio(audio_job.take().expect("the job was just made"))?, false => None,