forge
Explore
Log in

Don't you dare go Hollow

One bar, two threads, and it may only ever go forwards

Browse files at this commit

e5b7da5560b2655337217a4f919985ad987f4cebAhmet Kaan GümüşParent: cd31ad1
  • fix
    • one bar, two threads, and it may only ever go forwards
Show full message
🐛 fix(export): one bar, two threads, and it may only ever go forwards

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.rsmodified+8 -1
@@ -434,7 +434,14 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) {
434 let handle = engine::export::start(project.clone(), meta, &out, &settings);434 let handle = engine::export::start(project.clone(), meta, &out, &settings);
435 let t = Instant::now();435 let t = Instant::now();
436 let mut capped = false;436 let mut capped = false;
437+ // The highest the bar was ever seen at, not wherever it happens to
438+ // stand when the clock stops: an export publishes one bar from two
439+ // stages, and a capped run's rate is derived from this number. Taking
440+ // the maximum over the poll loop means a single unlucky read cannot
441+ // under-report the work that was really done.
442+ let mut peak = 0.0f64;
437 while !handle.is_finished() {443 while !handle.is_finished() {
444+ peak = peak.max(f64::from(handle.progress()));
438 if t.elapsed() >= cap {445 if t.elapsed() >= cap {
439 capped = true;446 capped = true;
440 handle.cancel();447 handle.cancel();
@@ -444,7 +451,7 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) {
444 }451 }
445 // A cancel is answered at the worker's next checkpoint; the rate is452 // A cancel is answered at the worker's next checkpoint; the rate is
446 // read from the progress at the moment the clock stopped either way.453 // read from the progress at the moment the clock stopped either way.
447- let progress = f64::from(handle.progress());454+ let progress = peak.max(f64::from(handle.progress()));
448 let elapsed = t.elapsed().as_secs_f64();455 let elapsed = t.elapsed().as_secs_f64();
449 let done = Instant::now() + Duration::from_secs(60);456 let done = Instant::now() + Duration::from_secs(60);
450 while !handle.is_finished() && Instant::now() < done {457 while !handle.is_finished() && Instant::now() < done {
crates/engine/src/export.rsmodified+39 -1
@@ -303,6 +303,17 @@ pub struct ExportSettings {
303 }303 }
304 304
305 struct Shared {305 struct Shared {
306+ /// Fraction of the job done, in [`PROGRESS_SCALE`]ths.
307+ ///
308+ /// **Every stage that can run beside another writes this with `fetch_max`,
309+ /// never `store`.** The sound and the picture are two threads publishing
310+ /// two bands of one bar ([`AUDIO_BAND`]): a `store` from the lower band
311+ /// pulls the bar backwards every time the other thread has already moved
312+ /// it on, which is what a person sees as a progress bar that stutters
313+ /// backwards -- 5,458 backward steps over one film export before this rule
314+ /// was written down. A `store` is only correct where nothing else can be
315+ /// publishing at all, which now means the terminal [`PROGRESS_SCALE`] and
316+ /// the audio-only export ([`run_audio`]) that has no second thread.
306 progress: AtomicU32,317 progress: AtomicU32,
307 cancel: AtomicBool,318 cancel: AtomicBool,
308 finished: AtomicBool,319 finished: AtomicBool,
@@ -1325,10 +1336,21 @@ fn encode_audio(
1325 * channels;1336 * channels;
1326 let mut samples: Vec<f32> = Vec::with_capacity(total);1337 let mut samples: Vec<f32> = Vec::with_capacity(total);
1327 for chunk in chunks {1338 for chunk in chunks {
1339+ // The only place a cancelled export can be answered before the whole
1340+ // timeline has been mixed. This pass runs on a thread of its own now
1341+ // ([`run`]), so without this a cancel left it mixing a feature film
1342+ // for minutes behind a job nobody is waiting for any more, writing
1343+ // into a `Shared` whose outcome was already settled.
1344+ cancelled(shared)?;
1328 samples.extend(chunk.samples);1345 samples.extend(chunk.samples);
1329 // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of1346 // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of
1330 // the three stages and the only one that can be counted as it goes.1347 // the three stages and the only one that can be counted as it goes.
1331- shared.progress.store(1348+ //
1349+ // `fetch_max` and not `store`, for the reason [`Shared::progress`]
1350+ // states: this runs on the audio thread while the picture publishes
1351+ // numbers above [`AUDIO_BAND`] from the other, and a `store` of this
1352+ // small one pulled the bar backwards 5,458 times over one film export.
1353+ shared.progress.fetch_max(
1332 (samples.len().min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32,1354 (samples.len().min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32,
1333 Ordering::Relaxed,1355 Ordering::Relaxed,
1334 );1356 );
@@ -1351,6 +1373,10 @@ fn encode_audio(
1351 // there is no resampler on this path, and inventing one to reach 48 kHz1373 // there is no resampler on this path, and inventing one to reach 48 kHz
1352 // would resample a whole timeline to satisfy a codec, which is a bigger1374 // would resample a whole timeline to satisfy a codec, which is a bigger
1353 // change to the sound than the codec is.1375 // change to the sound than the codec is.
1376+ // ...and again before either encoder is entered: both of them run to the
1377+ // end of the mix without a checkpoint of their own, so this is the last
1378+ // moment a cancel costs seconds rather than the whole encode.
1379+ cancelled(shared)?;
1354 if mkv1380 if mkv
1355 && audio.sample_rate == OPUS_RATE1381 && audio.sample_rate == OPUS_RATE
1356 && channels == 21382 && channels == 2
@@ -1380,6 +1406,7 @@ fn encode_audio(
1380 // `next_packet` after `finish` yields packets until `Eof` and nothing else,1406 // `next_packet` after `finish` yields packets until `Eof` and nothing else,
1381 // so the loop ends on the only error it can see.1407 // so the loop ends on the only error it can see.
1382 while let Ok(packet) = encoder.next_packet() {1408 while let Ok(packet) = encoder.next_packet() {
1409+ cancelled(shared)?;
1383 packets.push(crate::AacPacket {1410 packets.push(crate::AacPacket {
1384 bytes: packet.data,1411 bytes: packet.data,
1385 samples: packet.duration,1412 samples: packet.duration,
@@ -1756,6 +1783,17 @@ fn run(
1756 // A Matroska file (and a copied one, whose muxer is the same) collects it1783 // A Matroska file (and a copied one, whose muxer is the same) collects it
1757 // here; an mp4 leaves it running and collects it under the picture below.1784 // here; an mp4 leaves it running and collects it under the picture below.
1758 let mut audio_job = Some(audio_job);1785 let mut audio_job = Some(audio_job);
1786+ // The condition is the *format*, and the copied-picture path below relies
1787+ // on that covering it too: `plan` hands its packets straight to a Matroska
1788+ // muxer, so it may only exist where this has already collected them --
1789+ // which holds because [`CopyPlan::of`] returns `None` for every format
1790+ // that is not `Hevc` or `Av1`, both of which are `is_mkv`. Said out loud
1791+ // because a copy plan for an mp4 would otherwise reach `plan.run` with the
1792+ // sound still being mixed on the other thread.
1793+ debug_assert!(
1794+ settings.format.is_mkv() || plan.is_none(),
1795+ "a copy plan outside Matroska would run before its sound is collected"
1796+ );
1759 let audio = match settings.format.is_mkv() {1797 let audio = match settings.format.is_mkv() {
1760 true => join_audio(audio_job.take().expect("the job was just made"))?,1798 true => join_audio(audio_job.take().expect("the job was just made"))?,
1761 false => None,1799 false => None,