forge
Explore
Log in

Don't you dare go Hollow

The decoder and the encoder say which one is running

Browse files at this commit

bdcc2fb140ba69c613d5d19f64a95fa6d7bedd12Ahmet Kaan GümüşParent: aa9c851
  • feat
    • the decoder and the encoder say which one is running
Show full message
✨ feat(backends): the decoder and the encoder say which one is running

A source names its decoder in the library row before anything plays, the
transport line names the running one while it does, and the export card
names the encoders it would open before the button — the progress line
naming the ones it did.

Every answer is measured, never promised: `decode::probe` picks a seat by
the very rules `open_worker` picks one, the worker publishes what it
actually opened (so a hardware session that falls back to software says
so), and `export::planned_video` opens the very VA-API encoder the export
would and closes it again. `hw_seat` is now the single place that choice
is made, so a card and a running job cannot drift apart.
crates/app/src/main.rsmodified+228 -35
@@ -11,11 +11,12 @@ use std::time::{Duration, Instant};
1111
1212 use engine::audio::StreamInfo;
1313 use engine::color::ColorParams;
14+use engine::decode::Backend;
1415 use engine::eq::{Band, BandKind, EqParams};
1516 use engine::export::{ExportSettings, Format};
1617 use engine::project::{Edge, Lane, LaneKind, Source, Speed};
1718 use engine::scale::FitPolicy;
18-use engine::{Clip, ExportHandle, Frame, PlaybackSession};
19+use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};
1920 use gpui::{
2021 AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,
2122 KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,
@@ -637,6 +638,19 @@ struct Player {
637638 /// `None` is a file with no picture to report (every source that is not an
638639 /// image, and one whose header would not read).
639640 sizes: HashMap<PathBuf, Option<(u32, u32)>>,
641+ /// Which decoder each source will run on, probed once at import and kept:
642+ /// the codec (`None` for a still) and the seat the engine picked for it.
643+ /// What a library row says *before* anything plays; the running answer is
644+ /// the session's own (`PlaybackSession::decode_backend`), which follows a
645+ /// fallback this cannot. Filled like `sizes`: presence means "asked", and
646+ /// `None` is a source with no decoder to name -- a song, or one the probe
647+ /// refused -- which must stay in the map or every repaint would ask again.
648+ decoders: HashMap<PathBuf, Option<(Option<Codec>, Backend)>>,
649+ /// Which encoder an export of the picked settings would open, and what it
650+ /// was asked about: the probe opens a real VA-API encoder (~100 ms), so it
651+ /// runs off the render thread and only while the export card is up. The
652+ /// inner `None` is "asked, not answered yet".
653+ export_seat: Option<(ExportSettings, (u32, u32), Option<&'static str>)>,
640654 /// The copied clip. Frame ranges only, so it survives the clip it was taken
641655 /// from being deleted -- and it outlives the selection.
642656 clipboard: Option<Clip>,
@@ -1997,6 +2011,28 @@ impl Player {
19972011 })
19982012 .detach();
19992013 }
2014+ // Which decoder each file will run on, for the row that says so before
2015+ // a frame of it plays. Off the render thread like the streams above: a
2016+ // stream the plugin takes costs one VA-API init (~90 ms) to answer.
2017+ for path in unseen_paths(session.sources(), &self.decoders) {
2018+ self.decoders.insert(path.clone(), None);
2019+ let probed = cx.background_executor().spawn({
2020+ let path = path.clone();
2021+ // A song and a source no decoder here takes are both `None`:
2022+ // the row says nothing about them rather than guessing, and
2023+ // import refused the second at the door anyway.
2024+ async move { engine::decode::probe(&path).ok() }
2025+ });
2026+ cx.spawn(async move |this, cx| {
2027+ let probed = probed.await;
2028+ this.update(cx, |this, cx| {
2029+ this.decoders.insert(path, probed);
2030+ cx.notify();
2031+ })
2032+ .ok();
2033+ })
2034+ .detach();
2035+ }
20002036 for key in unseen_sources(session.sources(), &self.waves) {
20012037 self.waves.insert(key.clone(), Wave::Loading);
20022038 let decoded = cx.background_executor().spawn({
@@ -2029,6 +2065,51 @@ impl Player {
20292065 }
20302066 }
20312067
2068+ /// Probes the encoder an export would open, once per (settings,
2069+ /// resolution) and only while the export card is up -- it opens the very
2070+ /// VA-API encoder the export would, which is what makes the card's line a
2071+ /// measurement instead of a promise, and also what makes it too slow for
2072+ /// the render thread. Written before the spawn, like the probes above, so
2073+ /// the repaints during it start no second one.
2074+ fn cache_export_seat(&mut self, cx: &mut Context<Self>) {
2075+ let Some(session) = &self.session else {
2076+ return;
2077+ };
2078+ let settings = export_settings(self.quality, self.custom_mbps, self.format);
2079+ if !self.export_open || !settings.format.has_video() {
2080+ return;
2081+ }
2082+ let meta = *session.meta();
2083+ let key = (settings, (meta.width, meta.height));
2084+ if self
2085+ .export_seat
2086+ .is_some_and(|(asked, size, _)| (asked, size) == key)
2087+ {
2088+ return;
2089+ }
2090+ self.export_seat = Some((key.0, key.1, None));
2091+ let probed = cx
2092+ .background_executor()
2093+ .spawn(async move { engine::export::planned_video(&meta, &settings) });
2094+ cx.spawn(async move |this, cx| {
2095+ let probed = probed.await;
2096+ this.update(cx, |this, cx| {
2097+ // Only if the card is still asking the same question: a format
2098+ // changed while the plugin opened has a probe of its own.
2099+ if let Some(seat) = this
2100+ .export_seat
2101+ .as_mut()
2102+ .filter(|(asked, size, _)| (*asked, *size) == key)
2103+ {
2104+ seat.2 = probed;
2105+ }
2106+ cx.notify();
2107+ })
2108+ .ok();
2109+ })
2110+ .detach();
2111+ }
2112+
20322113 /// The group id of the clicked clip, which is what marks the other half.
20332114 fn selected_link(&self) -> Option<u32> {
20342115 let (lane, idx) = self.selected?;
@@ -3055,6 +3136,7 @@ impl Render for Player {
30553136 // has been through a repaint by the time its clips are drawn, so this
30563137 // is the one place that has to notice a new one.
30573138 self.cache_media(cx);
3139+ self.cache_export_seat(cx);
30583140 // What the compositor calls this window. Pushed only when it changes:
30593141 // it is a protocol round trip and this runs at vsync.
30603142 let title = window_title(&self.name);
@@ -3545,11 +3627,17 @@ impl Player {
35453627 // Its own length, not one derived from what is on the lanes: a row
35463628 // imported and never placed is a row with a length, and it is the
35473629 // length a drag would put down.
3548- let rows: Vec<_> = library_rows(sources, &self.streams, self.timeline_audio(), |path| {
3549- self.session
3550- .as_ref()
3551- .map_or(0, |session| session.file_frames(path))
3552- })
3630+ let rows: Vec<_> = library_rows(
3631+ sources,
3632+ &self.streams,
3633+ &self.decoders,
3634+ self.timeline_audio(),
3635+ |path| {
3636+ self.session
3637+ .as_ref()
3638+ .map_or(0, |session| session.file_frames(path))
3639+ },
3640+ )
35533641 .into_iter()
35543642 .enumerate()
35553643 .map(|(i, row)| {
@@ -3780,6 +3868,30 @@ impl Player {
37803868 ))
37813869 }
37823870
3871+ /// What is decoding the picture right now, for the transport line: the
3872+ /// backend is the running worker's own (it is written where a hardware
3873+ /// session falls back to software, so this follows reality), and the codec
3874+ /// comes from the clip under the playhead. Empty when nothing is playing --
3875+ /// the question is about what is happening, not about what would.
3876+ fn live_decode(&self, position: f64, playing: bool) -> String {
3877+ let Some(session) = self.session.as_ref().filter(|_| playing) else {
3878+ return String::new();
3879+ };
3880+ let backend = session.decode_backend();
3881+ let codec = session
3882+ .video_clip_at(position)
3883+ .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| clip.source))
3884+ .and_then(|source| session.sources().get(source))
3885+ .and_then(|source| self.decoders.get(&source.path).copied().flatten())
3886+ .and_then(|(codec, _)| codec);
3887+ match backend {
3888+ // Neither is a decode, and saying "SW" of them would be a lie.
3889+ Backend::Gap => "gap · nothing to decode".to_string(),
3890+ Backend::Still => "still · one decode, held".to_string(),
3891+ _ => format!("{} decode", decode_label(codec, backend)),
3892+ }
3893+ }
3894+
37833895 /// Transport, edit and file buttons, timecode, playhead, clips lane.
37843896 fn panel(
37853897 &self,
@@ -3821,8 +3933,16 @@ impl Player {
38213933 let progress = export.progress();
38223934 (
38233935 format!(
3824- "EXPORTING {}% — {} cancels",
3936+ "EXPORTING {}% · {} · {} — {} cancels",
38253937 (progress * 100.) as u32,
3938+ // The row that was picked; the engine's line below names the
3939+ // seats alone, since the library is what identifies a codec.
3940+ format_label(self.format),
3941+ // What the worker actually opened, so a fallback to the
3942+ // software encoder shows here rather than being invisible.
3943+ export
3944+ .encoders()
3945+ .unwrap_or_else(|| "opening the encoder".to_string()),
38263946 key(ActionId::CancelExport)
38273947 ),
38283948 progress,
@@ -3832,12 +3952,19 @@ impl Player {
38323952 // tooltips. Keys first: at a 640 px window the tail is what a
38333953 // truncation eats, and the two hints at the end are also on the
38343954 // ruler's and Import's tooltips.
3955+ // While it plays, what is decoding it goes first: it is the
3956+ // answer that changes as the playhead crosses a cut, and the tail
3957+ // of this line is what a narrow window truncates.
38353958 (
3836- format!(
3837- "{} copy · {} paste · {} undo · click the bar to seek · drop a file to import",
3838- key(ActionId::Copy),
3839- key(ActionId::Paste),
3840- key(ActionId::Undo)
3959+ join_detail(
3960+ &self.live_decode(position, playing),
3961+ &format!(
3962+ "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \
3963+ import",
3964+ key(ActionId::Copy),
3965+ key(ActionId::Paste),
3966+ key(ActionId::Undo)
3967+ ),
38413968 ),
38423969 filled,
38433970 )
@@ -4608,7 +4735,11 @@ impl Player {
46084735 .px(px(6.))
46094736 .text_size(px(11.))
46104737 .text_color(rgb(INK_DIM))
4611- .child(export_line(self.format, self.session.as_ref())),
4738+ .child(export_line(
4739+ self.format,
4740+ self.session.as_ref(),
4741+ self.export_seat.and_then(|(.., seat)| seat),
4742+ )),
46124743 )
46134744 .child(
46144745 div()
@@ -6457,6 +6588,7 @@ struct Row {
64576588 fn library_rows(
64586589 sources: &[Source],
64596590 streams: &HashMap<PathBuf, Vec<StreamInfo>>,
6591+ decoders: &HashMap<PathBuf, Option<(Option<Codec>, Backend)>>,
64606592 timeline_audio: Option<(u32, u16)>,
64616593 frames: impl Fn(&Path) -> u32,
64626594 ) -> Vec<Row> {
@@ -6472,12 +6604,22 @@ fn library_rows(
64726604 path: source.path.clone(),
64736605 stream: source.audio_stream,
64746606 name: row_name(&source.path, source.audio_stream, of_file.len() > 1),
6475- // Only where there is a choice to describe: a file with one audio
6476- // track is the row it has always been, name and length, and the
6477- // length is what would be squeezed out at the panel's least width.
6478- detail: info
6479- .filter(|_| of_file.len() > 1)
6480- .map_or_else(String::new, stream_detail),
6607+ // The decoder first: it is the same for every row of a file and
6608+ // it is what a person opening the panel is asking about. The
6609+ // stream half only where there is a choice to describe -- a file
6610+ // with one audio track is the row it has always been, name and
6611+ // length, and the length is what would be squeezed out at the
6612+ // panel's least width.
6613+ detail: join_detail(
6614+ &decoders
6615+ .get(&source.path)
6616+ .copied()
6617+ .flatten()
6618+ .map_or_else(String::new, |(codec, backend)| decode_label(codec, backend)),
6619+ &info
6620+ .filter(|_| of_file.len() > 1)
6621+ .map_or_else(String::new, stream_detail),
6622+ ),
64816623 // A stream already on the timeline is playing: whatever a probe
64826624 // would say about it now, it is usable by demonstration.
64836625 unusable: None,
@@ -6514,9 +6656,20 @@ fn library_rows(
65146656 /// why it cannot be used, with the separator only where both halves exist (a
65156657 /// single-stream file says nothing about its stream).
65166658 fn join_detail(detail: &str, tail: &str) -> String {
6517- match detail.is_empty() {
6518- true => tail.to_string(),
6519- false => format!("{detail} · {tail}"),
6659+ match (detail.is_empty(), tail.is_empty()) {
6660+ (true, _) => tail.to_string(),
6661+ (false, true) => detail.to_string(),
6662+ (false, false) => format!("{detail} · {tail}"),
6663+ }
6664+}
6665+
6666+/// How a source's decoder reads: the codec and which seat has it, or the seat
6667+/// alone for a still, which has no coded stream to name. The one place either
6668+/// answer is spelled, so a row, a transport line and a card cannot disagree.
6669+fn decode_label(codec: Option<Codec>, backend: Backend) -> String {
6670+ match codec {
6671+ Some(codec) => format!("{} · {}", codec.name(), backend.label()),
6672+ None => backend.label().to_string(),
65206673 }
65216674 }
65226675
@@ -6834,14 +6987,32 @@ fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) {
68346987 /// [`format_line`] plus the project's resolution, which is what a video export
68356988 /// is written at however many sizes the media on the timeline are. Only for the
68366989 /// formats that carry a picture -- a WAV has no resolution to state.
6837-fn export_line(format: Format, session: Option<&PlaybackSession>) -> String {
6990+fn export_line(
6991+ format: Format,
6992+ session: Option<&PlaybackSession>,
6993+ seat: Option<&'static str>,
6994+) -> String {
68386995 let line = format_line(format);
6996+ // What it will really be encoded by, on the same line: the picture's seat
6997+ // as the probe found it (`…` until it lands, never a guess) and the sound's,
6998+ // which is decided without opening anything. Both are what a running export
6999+ // then names on its progress line, from the same two functions.
7000+ let encoders = match session {
7001+ Some(session) => join_detail(
7002+ seat.unwrap_or(match format.has_video() {
7003+ true => "encoder …",
7004+ false => "",
7005+ }),
7006+ session.planned_audio(format),
7007+ ),
7008+ None => String::new(),
7009+ };
68397010 match session.filter(|_| format.has_video()) {
68407011 Some(session) => {
68417012 let (w, h) = session.resolution();
6842- format!("{line} · project {w}x{h}")
7013+ format!("{line} · project {w}x{h} · {encoders}")
68437014 }
6844- None => line.to_string(),
7015+ None => join_detail(line, &encoders),
68457016 }
68467017 }
68477018
@@ -7921,9 +8092,13 @@ mod tests {
79218092 );
79228093 // The rows the panel draws: one per source, each its file's own length
79238094 // -- source 1 has no clip anywhere and is still 4 s at 30 fps.
7924- let rows = library_rows(session.sources(), &HashMap::new(), None, |path| {
7925- session.file_frames(path)
7926- });
8095+ let rows = library_rows(
8096+ session.sources(),
8097+ &HashMap::new(),
8098+ &HashMap::new(),
8099+ None,
8100+ |path| session.file_frames(path),
8101+ );
79278102 assert_eq!(rows.len(), 2);
79288103 assert_eq!(rows[0].frames, 150, "5 s at 30 fps");
79298104 assert_eq!(rows[1].frames, 120, "4 s at 30 fps, never placed");
@@ -7962,7 +8137,9 @@ mod tests {
79628137 .find(|s| s.index == session.sources()[0].audio_stream)
79638138 .map(|s| (s.sample_rate, s.channels));
79648139 let frames = session.file_frames(&path);
7965- let rows = library_rows(session.sources(), &streams, rate, |_| frames);
8140+ let rows = library_rows(session.sources(), &streams, &HashMap::new(), rate, |_| {
8141+ frames
8142+ });
79668143 assert_eq!(rows.len(), 1);
79678144 assert_eq!(rows[0].name, "test_tone.mp3");
79688145 assert_eq!(rows[0].unusable, None, "the row is placeable");
@@ -8029,7 +8206,13 @@ mod tests {
80298206 info(3, 0, 0, None, false),
80308207 ],
80318208 );
8032- let rows = library_rows(&sources, &streams, Some((44_100, 2)), |_| 90);
8209+ let rows = library_rows(
8210+ &sources,
8211+ &streams,
8212+ &HashMap::new(),
8213+ Some((44_100, 2)),
8214+ |_| 90,
8215+ );
80338216 assert_eq!(
80348217 rows.iter().map(|r| r.stream).collect::<Vec<_>>(),
80358218 [0, 1, 2, 3],
@@ -8067,7 +8250,7 @@ mod tests {
80678250 PathBuf::from("/m/plain.mp4"),
80688251 vec![info(0, 44_100, 2, None, true)],
80698252 );
8070- let rows = library_rows(&plain, &one, Some((44_100, 2)), |_| 90);
8253+ let rows = library_rows(&plain, &one, &HashMap::new(), Some((44_100, 2)), |_| 90);
80718254 assert_eq!(rows.len(), 1);
80728255 assert_eq!(rows[0].name, "plain.mp4");
80738256 assert_eq!(
@@ -8078,7 +8261,7 @@ mod tests {
80788261 let mut silent = HashMap::new();
80798262 silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new());
80808263 for probe in [silent, HashMap::new()] {
8081- let rows = library_rows(&plain, &probe, None, |_| 90);
8264+ let rows = library_rows(&plain, &probe, &HashMap::new(), None, |_| 90);
80828265 assert_eq!(rows.len(), 1);
80838266 assert_eq!(rows[0].name, "plain.mp4");
80848267 assert_eq!(rows[0].detail, "");
@@ -8096,7 +8279,13 @@ mod tests {
80968279 PathBuf::from("/m/other.mp4"),
80978280 vec![info(0, 44_100, 2, None, true)],
80988281 );
8099- let rows = library_rows(&placed, &streams, Some((44_100, 2)), |_| 90);
8282+ let rows = library_rows(
8283+ &placed,
8284+ &streams,
8285+ &HashMap::new(),
8286+ Some((44_100, 2)),
8287+ |_| 90,
8288+ );
81008289 assert_eq!(
81018290 rows.iter()
81028291 .map(|r| (file_name(&r.path), r.stream))
@@ -8499,7 +8688,7 @@ mod tests {
84998688 );
85008689 let streams = HashMap::new();
85018690 let rows = |session: &PlaybackSession| {
8502- library_rows(session.sources(), &streams, None, |_| 0).len()
8691+ library_rows(session.sources(), &streams, &HashMap::new(), None, |_| 0).len()
85038692 };
85048693 assert_eq!(rows(&session), 2, "a row per source");
85058694
@@ -9820,7 +10009,9 @@ mod tests {
982010009 // a title and a status line.
982110010 let title = 17.;
982210011 let status = 28.;
9823- let fixed = 17.;
10012+ // Two lines of 11 px: the format line carries the encoders an export
10013+ // would open, which is what takes it past one at this width.
10014+ let fixed = 30.;
982410015 let gaps = 4. * 2.;
982510016 let padding = 24.;
982610017 assert!(
@@ -10365,6 +10556,8 @@ fn main() {
1036510556 waves: HashMap::new(),
1036610557 streams: HashMap::new(),
1036710558 sizes: HashMap::new(),
10559+ decoders: HashMap::new(),
10560+ export_seat: None,
1036810561 clipboard: None,
1036910562 scrubbing: false,
1037010563 trim: None,
crates/engine/src/decode.rsmodified+116 -1
@@ -3,7 +3,7 @@
33
44 use std::path::{Path, PathBuf};
55 use std::sync::Arc;
6-use std::sync::atomic::{AtomicBool, Ordering};
6+use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
77 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
88 use std::thread;
99
@@ -25,6 +25,106 @@ pub struct Frame {
2525 pub bgra: Vec<u8>,
2626 }
2727
28+/// Which decoder a source is really running on. Read-only introspection: it
29+/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose --
30+/// a hardware session that opened and then failed before its first picture
31+/// falls back to software and this says so, because it is written where the
32+/// fallback happens rather than where it was hoped for.
33+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34+pub enum Backend {
35+ /// The worker has not reached its decoder yet: the plugin's VA-API init is
36+ /// ~90 ms, and this is what a caller reads in that window.
37+ #[default]
38+ Opening,
39+ /// The VA-API plugin (`libengine_hw.so`).
40+ Hardware,
41+ /// `rusty_h264`, in this process.
42+ Software,
43+ /// A still image: one `image` decode, no stream and no decoder to pick.
44+ Still,
45+ /// A gap: black frames, nothing decoded at all.
46+ Gap,
47+}
48+
49+impl Backend {
50+ /// Short enough for a library row and a transport line.
51+ pub fn label(self) -> &'static str {
52+ match self {
53+ Self::Opening => "opening",
54+ Self::Hardware => "HW",
55+ Self::Software => "SW",
56+ Self::Still => "still",
57+ Self::Gap => "gap",
58+ }
59+ }
60+
61+ fn code(self) -> u8 {
62+ match self {
63+ Self::Opening => 0,
64+ Self::Hardware => 1,
65+ Self::Software => 2,
66+ Self::Still => 3,
67+ Self::Gap => 4,
68+ }
69+ }
70+
71+ fn from_code(code: u8) -> Self {
72+ match code {
73+ 1 => Self::Hardware,
74+ 2 => Self::Software,
75+ 3 => Self::Still,
76+ 4 => Self::Gap,
77+ _ => Self::Opening,
78+ }
79+ }
80+}
81+
82+/// Where a worker publishes the decoder it opened, for whoever holds the other
83+/// end of its channel. One atomic byte, written once at open (and once more if
84+/// hardware hands the range back to software), read whenever a caller repaints
85+/// -- never per frame on either side.
86+#[derive(Clone, Default)]
87+pub struct BackendCell(Arc<AtomicU8>);
88+
89+impl BackendCell {
90+ fn new(backend: Backend) -> Self {
91+ Self(Arc::new(AtomicU8::new(backend.code())))
92+ }
93+
94+ fn set(&self, backend: Backend) {
95+ self.0.store(backend.code(), Ordering::Relaxed);
96+ }
97+
98+ pub fn get(&self) -> Backend {
99+ Backend::from_code(self.0.load(Ordering::Relaxed))
100+ }
101+}
102+
103+/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`]
104+/// decides it: the same `VE_SW` pin and the same plugin probe against this very
105+/// file. What lets a front-end name the decoder *before* anything plays.
106+///
107+/// The codec is `None` for a still image, which has no coded stream. A stream
108+/// no decoder here can take is an `Err` naming the plugin, exactly as opening
109+/// it would be -- the same refusal, one VA-API init earlier.
110+///
111+/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per
112+/// file, off a render thread, and keep the answer.
113+pub fn probe(path: &Path) -> crate::Result<(Option<Codec>, Backend)> {
114+ if crate::is_image(path) {
115+ return Ok((None, Backend::Still));
116+ }
117+ let path = path.to_path_buf();
118+ let (meta, _demuxer) = Demuxer::open(&path)?;
119+ if open_hw(&path, 0).is_some() {
120+ return Ok((Some(meta.codec), Backend::Hardware));
121+ }
122+ if meta.codec != Codec::H264 {
123+ return Err(meta.codec.needs_plugin().into());
124+ }
125+ Ok((Some(meta.codec), Backend::Software))
126+}
127+
28128 /// A running decode worker: the flag that stops it, and the handle to wait on.
29129 ///
30130 /// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize`
@@ -85,6 +185,9 @@ impl Drop for Worker {
85185 pub(crate) struct FrameStream {
86186 pub(crate) frames: Receiver<Frame>,
87187 pub(crate) worker: Worker,
188+ /// What this stream's pictures are being decoded by. Dropped last and read
189+ /// by the caller, so it outlives nothing and blocks nothing.
190+ pub(crate) backend: BackendCell,
88191 }
89192
90193 pub struct DecodeSession;
@@ -152,6 +255,7 @@ impl DecodeSession {
152255 cancel,
153256 handle: None,
154257 },
258+ backend: BackendCell::new(Backend::Gap),
155259 };
156260 }
157261 let worker_cancel = Arc::clone(&cancel);
@@ -180,6 +284,7 @@ impl DecodeSession {
180284 FrameStream {
181285 frames: rx,
182286 worker: Worker { cancel, handle },
287+ backend: BackendCell::new(Backend::Gap),
183288 }
184289 }
185290
@@ -209,6 +314,7 @@ impl DecodeSession {
209314 cancel,
210315 handle: None,
211316 },
317+ backend: BackendCell::new(Backend::Still),
212318 });
213319 }
214320 // The one conversion, on this thread: it is a few milliseconds and the
@@ -245,6 +351,7 @@ impl DecodeSession {
245351 Ok(FrameStream {
246352 frames: rx,
247353 worker: Worker { cancel, handle },
354+ backend: BackendCell::new(Backend::Still),
248355 })
249356 }
250357
@@ -285,6 +392,9 @@ impl DecodeSession {
285392 // decoder run ahead of the display without limit.
286393 let (tx, rx) = sync_channel(2);
287394 let cancel = Arc::new(AtomicBool::new(false));
395+ // Written by the worker below the moment it knows, so a caller reading
396+ // it sees what opened rather than what was hoped for.
397+ let backend = BackendCell::default();
288398 if end_frame <= start_frame {
289399 // Nothing to decode: dropping `tx` here closes the channel cleanly,
290400 // so the caller sees an immediate end of stream rather than an error.
@@ -296,10 +406,12 @@ impl DecodeSession {
296406 cancel,
297407 handle: None,
298408 },
409+ backend,
299410 },
300411 ));
301412 }
302413 let worker_cancel = Arc::clone(&cancel);
414+ let worker_backend = backend.clone();
303415 let handle = thread::Builder::new()
304416 .name("decode".into())
305417 .spawn(move || {
@@ -320,6 +432,7 @@ impl DecodeSession {
320432 return;
321433 }
322434 eprintln!("decode backend: hardware (VA-API plugin)");
435+ worker_backend.set(Backend::Hardware);
323436 if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) {
324437 return;
325438 }
@@ -334,6 +447,7 @@ impl DecodeSession {
334447 return;
335448 }
336449 eprintln!("decode backend: software (rusty_h264)");
450+ worker_backend.set(Backend::Software);
337451 run(
338452 demuxer,
339453 tx,
@@ -351,6 +465,7 @@ impl DecodeSession {
351465 cancel,
352466 handle: Some(handle),
353467 },
468+ backend,
354469 },
355470 ))
356471 }
crates/engine/src/export.rsmodified+142 -20
@@ -144,6 +144,10 @@ struct Shared {
144144 cancel: AtomicBool,
145145 finished: AtomicBool,
146146 outcome: Mutex<Option<crate::Result<()>>>,
147+ /// The encoders this job really opened, published the moment they are
148+ /// chosen and never changed after -- one seat for the whole file, which is
149+ /// what [`Enc`] states. `None` until then.
150+ encoders: Mutex<Option<String>>,
147151 }
148152
149153 /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
@@ -172,6 +176,13 @@ impl ExportHandle {
172176 self.shared.finished.load(Ordering::Acquire)
173177 }
174178
179+ /// What this export is encoding with -- the video seat and what the sound
180+ /// is doing -- as the worker chose them, hardware fallback included.
181+ /// `None` for the first instants of a job, before the encoder is open.
182+ pub fn encoders(&self) -> Option<String> {
183+ self.shared.encoders.lock().unwrap().clone()
184+ }
185+
175186 /// The outcome, once — taken out of the handle, so a caller that already
176187 /// reported it sees `None` afterwards. `None` while the export is running.
177188 pub fn result(&self) -> Option<crate::Result<()>> {
@@ -195,6 +206,7 @@ pub fn start(
195206 cancel: AtomicBool::new(false),
196207 finished: AtomicBool::new(false),
197208 outcome: Mutex::new(None),
209+ encoders: Mutex::new(None),
198210 });
199211 let worker = Arc::clone(&shared);
200212 let out = out.to_path_buf();
@@ -259,6 +271,103 @@ fn has_picture(project: &Project) -> bool {
259271 .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty())
260272 }
261273
274+/// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a
275+/// timeline whose export will carry sound from one whose file has none.
276+fn has_sound(project: &Project) -> bool {
277+ project
278+ .lanes()
279+ .into_iter()
280+ .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty())
281+}
282+
283+/// Whether any equalizer on the sound is doing something -- the one edit a
284+/// packet copy cannot carry, so an mp4 whose lane has one is decoded and
285+/// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane:
286+/// the copy path has exactly one by the time it asks, and [`planned_audio`] is
287+/// asked before that is settled.
288+fn equalized(project: &Project) -> bool {
289+ project.audio_lanes().into_iter().any(|lane| {
290+ (0..project.lane(lane).len())
291+ .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity()))
292+ })
293+}
294+
295+/// The bitrate an export codes at: the caller's number through the same clamp
296+/// as the computed one, for the reason [`Enc::open`] states.
297+fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 {
298+ settings
299+ .bitrate
300+ .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE))
301+}
302+
303+/// The hardware seat for these settings, opened exactly as the export opens it
304+/// -- the same pins, the same AV1 opt-in, the same dimensions a driver may
305+/// refuse -- or `None` where the software encoder takes the file. The single
306+/// place that choice is made, which is what lets [`planned_video`] *measure* it
307+/// instead of promising it.
308+fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
309+ if settings.force_sw || forced("VE_SW_ENC") {
310+ return None;
311+ }
312+ let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
313+ let bitrate = bitrate_of(meta, settings);
314+ match settings.format {
315+ // Opt-in only, for the reason [`Enc::open_av1`] states in full.
316+ Format::Av1 if !forced("VE_HW_AV1") => None,
317+ Format::Av1 => HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate),
318+ _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate),
319+ }
320+}
321+
322+/// How a front-end names a video seat: which of the two encoders has the file,
323+/// and which library that is. Not the codec -- a caller shows this beside the
324+/// format it picked, and `rav1e` names AV1 as `rusty_h264` names H.264. One
325+/// place, so what a card says before an export and what its progress line says
326+/// during one cannot drift apart.
327+fn video_label(format: Format, hw: bool) -> &'static str {
328+ match (format, hw) {
329+ (Format::Av1, true) => "HW encode (VA-API)",
330+ (Format::Av1, false) => "SW encode (rav1e)",
331+ (_, true) => "HW encode (VA-API)",
332+ (_, false) => "SW encode (rusty_h264)",
333+ }
334+}
335+
336+/// What the sound is written by. Every audio encoder here is software -- there
337+/// is no hardware AAC, PCM or FLAC seat -- so this names *which* one, and
338+/// whether an mp4 escapes encoding altogether by copying the packets it was
339+/// given. Empty for AV1, which carries no audio at all: a caller joins this to
340+/// a line that already says so, and repeating it would cost a line of card.
341+fn audio_label(project: &Project, format: Format, sound: bool) -> &'static str {
342+ match format {
343+ Format::Av1 => "",
344+ _ if !sound => "no sound to write",
345+ Format::Mp4 if equalized(project) => "AAC · SW encode (rusty_aac)",
346+ Format::Mp4 => "AAC copy",
347+ Format::Wav => "PCM · SW (hound)",
348+ Format::Flac => "FLAC · SW (flacenc)",
349+ }
350+}
351+
352+/// What [`start`] would write this timeline's sound with, before one is
353+/// started. Pure: no probe and no file opened, so a card may ask it per repaint.
354+pub fn planned_audio(project: &Project, format: Format) -> &'static str {
355+ audio_label(project, format, has_sound(project))
356+}
357+
358+/// What [`start`] would encode the picture with, probed the way the export
359+/// probes it -- the very encoder is opened and closed again -- so this is a
360+/// measurement and not a promise. `None` for a format that carries no picture.
361+///
362+/// Costs that open (~100 ms here): ask it off a render thread and keep the
363+/// answer until the format, the resolution or the bitrate changes.
364+pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> {
365+ settings
366+ .format
367+ .has_video()
368+ .then(|| video_label(settings.format, hw_seat(meta, settings).is_some()))
369+}
370+
262371 fn settle(shared: &Shared, result: crate::Result<()>) {
263372 *shared.outcome.lock().unwrap() = Some(result);
264373 // Published last: a caller that sees the flag is guaranteed the outcome.
@@ -352,9 +461,7 @@ fn copy_audio(
352461 // only this case is: a timeline nobody has equalized still leaves through
353462 // the copy below, packet for packet, so no passthrough quietly becomes a
354463 // generation of loss.
355- let equalized = (0..project.lane(lane).len())
356- .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity()));
357- if equalized {
464+ if equalized(project) {
358465 return encode_audio(project, meta);
359466 }
360467 AudioSession::copy_multi_streams(&project.audio_sources(), segments)
@@ -470,6 +577,18 @@ fn run(
470577 });
471578
472579 let mut encoder = Enc::open(meta, settings)?;
580+ // What this file is really being written by, for a progress line to name.
581+ // Published *after* the seat is open, so a hardware encoder the driver
582+ // refused reads as the software one that took over rather than as the hope
583+ // it replaced -- and the sound says whether it was copied or encoded, which
584+ // `copy_audio` decided a few lines up.
585+ *shared.encoders.lock().unwrap() = Some(
586+ match audio_label(project, settings.format, audio.is_some()) {
587+ // AV1: no sound in the file and none to name.
588+ "" => encoder.label().to_string(),
589+ sound => format!("{} · {sound}", encoder.label()),
590+ },
591+ );
473592 let mut muxer = None;
474593 let mut done = 0u32;
475594 let black = Black::new(meta);
@@ -673,6 +792,9 @@ fn run_audio(
673792 else {
674793 return Err("this timeline has no audio to export".into());
675794 };
795+ // The picture path's line, for a file that is sound alone: there is sound
796+ // by the line above, so this names the encoder writing it.
797+ *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true).to_string());
676798 let channels = usize::from(audio.channels);
677799 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate
678800 * f64::from(audio.sample_rate))
@@ -927,6 +1049,18 @@ enum Enc {
9271049 }
9281050
9291051 impl Enc {
1052+ /// Which seat this *is*, said the way [`video_label`] says it -- so the
1053+ /// name a running export shows is the name the card showed, or the honest
1054+ /// difference where the probe and the open disagreed.
1055+ fn label(&self) -> &'static str {
1056+ match self {
1057+ Self::Hw(_) => video_label(Format::Mp4, true),
1058+ Self::Sw { .. } => video_label(Format::Mp4, false),
1059+ Self::Av1Hw(_) => video_label(Format::Av1, true),
1060+ Self::Av1Sw { .. } => video_label(Format::Av1, false),
1061+ }
1062+ }
1063+
9301064 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
9311065 if settings.format == Format::Av1 {
9321066 return Self::open_av1(meta, settings);
@@ -934,18 +1068,13 @@ impl Enc {
9341068 // A caller's number goes through the same clamp as the computed one: a
9351069 // zero bitrate switches the software encoder's lookahead on, which would
9361070 // break the one-picture-per-call contract `encode` documents below.
937- let bitrate = settings
938- .bitrate
939- .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE));
1071+ let bitrate = bitrate_of(meta, settings);
9401072 // The plugin wants an exact rational, and the muxer already picks one
9411073 // that is exact at every rate we can read -- `fps * 1000 / 1000` would
9421074 // hand 24000/1001 over as a rounded 23.976, which is the same
9431075 // truncation the container timing had.
944- let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
945- if !settings.force_sw
946- && !forced("VE_SW_ENC")
947- && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate)
948- {
1076+ crate::mux::frame_timing(meta.frame_rate)?;
1077+ if let Some(hw) = hw_seat(meta, settings) {
9491078 eprintln!("export encoder: hardware (VA-API plugin)");
9501079 return Ok(Self::Hw(hw));
9511080 }
@@ -986,19 +1115,12 @@ impl Enc {
9861115 /// cros-codecs release that fixes it) plus a probe encode of one frame at
9871116 /// open, after which this can prefer hardware the way H.264 does.
9881117 fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
989- let bitrate = settings
990- .bitrate
991- .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE));
1118+ let bitrate = bitrate_of(meta, settings);
9921119 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
9931120 // Two seconds between keyframes, as the H.264 seat does: a seek may only
9941121 // land on one, and this is what a cluster of the Matroska file is.
9951122 let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64;
996- if forced("VE_HW_AV1")
997- && !settings.force_sw
998- && !forced("VE_SW_ENC")
999- && let Some(hw) =
1000- HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate)
1001- {
1123+ if let Some(hw) = hw_seat(meta, settings) {
10021124 eprintln!("export encoder: hardware AV1 (VA-API plugin)");
10031125 return Ok(Self::Av1Hw(hw));
10041126 }
crates/engine/src/playback.rsmodified+29 -1
@@ -22,7 +22,7 @@ use crate::ao::AoSession;
2222 use crate::audio::{AudioChunk, AudioSession};
2323 use crate::clock::{ClockSource, PlaybackClock};
2424 use crate::color::ColorParams;
25-use crate::decode::{DecodeSession, Frame, Worker};
25+use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};
2626 use crate::demux::{Codec, Demuxer, VideoMeta};
2727 use crate::eq::EqParams;
2828 use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span, Speed};
@@ -160,6 +160,11 @@ pub struct PlaybackSession {
160160 frames: Receiver<Frame>,
161161 /// The current decode worker.
162162 worker: Worker,
163+ /// What that worker opened -- hardware, software, a still, a gap -- written
164+ /// by the worker itself and read by [`decode_backend`](Self::decode_backend).
165+ /// Replaced with the stream at every seek, so it always describes the
166+ /// pictures currently arriving and never the clip before them.
167+ backend: BackendCell,
163168 /// Workers cancelled by a seek or a clip change, waiting to be reaped.
164169 /// Joining one inline costs whatever VA-API init it is still inside (98 ms
165170 /// measured worst case), which is a visible hitch on the caller's thread;
@@ -259,6 +264,7 @@ impl PlaybackSession {
259264 native: (meta.width, meta.height),
260265 frames: stream.frames,
261266 worker: stream.worker,
267+ backend: stream.backend,
262268 retired: Vec::new(),
263269 clock: PlaybackClock::new(source),
264270 audio,
@@ -353,6 +359,7 @@ impl PlaybackSession {
353359 native: (width, height),
354360 frames: stream.frames,
355361 worker: stream.worker,
362+ backend: stream.backend,
356363 retired: Vec::new(),
357364 // The song keeps the clock, as a video's own sound does -- and wall
358365 // time keeps it on a machine with no device, where the picture
@@ -425,6 +432,7 @@ impl PlaybackSession {
425432 native: (meta.width, meta.height),
426433 frames: stream.frames,
427434 worker: stream.worker,
435+ backend: stream.backend,
428436 retired: Vec::new(),
429437 clock: PlaybackClock::new(ClockSource::Wall),
430438 audio: None,
@@ -647,6 +655,7 @@ impl PlaybackSession {
647655 native,
648656 frames: stream.frames,
649657 worker: stream.worker,
658+ backend: stream.backend,
650659 retired: Vec::new(),
651660 clock: PlaybackClock::new(match audio {
652661 Some(_) => ClockSource::Audio,
@@ -672,6 +681,24 @@ impl PlaybackSession {
672681 &self.meta
673682 }
674683
684+ /// What the pictures now arriving are being decoded by: the clip under the
685+ /// playhead, since one video worker feeds the composite at a time. An
686+ /// atomic load -- a front-end may ask it every repaint -- and it is what
687+ /// *opened*, so a clip whose hardware session fell back to software reads
688+ /// [`Backend::Software`] from the frame that fallback happened.
689+ pub fn decode_backend(&self) -> Backend {
690+ self.backend.get()
691+ }
692+
693+ /// What an export of this timeline would encode the *sound* with, before
694+ /// one is started: the copy an mp4 normally makes, or the software encoder
695+ /// the format (or an equalized lane) forces. Pure -- no probe, no file
696+ /// opened -- so a card may ask it per repaint; the picture's half costs a
697+ /// plugin open and lives in [`crate::export::planned_video`].
698+ pub fn planned_audio(&self, format: crate::export::Format) -> &'static str {
699+ crate::export::planned_audio(&self.project, format)
700+ }
701+
675702 /// Why this session plays silent although the file has sound -- an audio
676703 /// track in a codec we cannot decode, or one the decoder refused. `None`
677704 /// when there is audio, and for a file that never had any. A front-end
@@ -875,6 +902,7 @@ impl PlaybackSession {
875902 // then can it return and be reaped by a later sweep. Nothing here
876903 // joins, so this ordering costs the seek nothing.
877904 self.frames = stream.frames;
905+ self.backend = stream.backend;
878906 self.retire(stream.worker);
879907 }
880908 self.span = span;
crates/engine/tests/backends.rsadded+187 -0
@@ -0,0 +1,187 @@
1+//! Which decoder and which encoder a job really runs on -- the introspection a
2+//! front-end shows before an operation and while it runs.
3+//!
4+//! The point of every assertion here is *truthfulness*, not a particular seat:
5+//! this box may or may not have a working plugin, and a test that demanded
6+//! hardware would only be measuring the machine. What must hold is that the
7+//! answer given before an operation is the answer the operation then gives, and
8+//! that neither of them ever names a decoder that could not have run (software
9+//! HEVC, for one, does not exist here).
10+
11+use std::path::PathBuf;
12+use std::time::{Duration, Instant};
13+
14+use engine::Codec;
15+use engine::decode::{Backend, probe};
16+use engine::export::{ExportSettings, Format};
17+use engine::{ExportHandle, PlaybackSession};
18+
19+fn asset(name: &str) -> PathBuf {
20+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
21+ .join("../../assets")
22+ .join(name)
23+}
24+
25+fn out_path(name: &str, ext: &str) -> PathBuf {
26+ let path = std::env::temp_dir().join(format!("ve_backend_{name}_{}.{ext}", std::process::id()));
27+ let _ = std::fs::remove_file(&path);
28+ let _ = std::fs::remove_file(format!("{}.part", path.display()));
29+ path
30+}
31+
32+/// A still has no coded stream and no decoder to pick, and it must say so
33+/// rather than borrowing the picture path's answer.
34+#[test]
35+fn a_still_probes_as_a_still() {
36+ let (codec, backend) = probe(&asset("test_still.png")).expect("probe the still");
37+ assert_eq!(codec, None, "an image has no coded stream to name");
38+ assert_eq!(backend, Backend::Still);
39+}
40+
41+/// H.264 has both seats, so the probe may legitimately answer either -- but it
42+/// must answer one of them, and it must name the codec.
43+#[test]
44+fn an_h264_source_probes_as_one_of_the_two_seats() {
45+ let (codec, backend) = probe(&asset("test_baseline.mp4")).expect("probe the baseline fixture");
46+ assert_eq!(codec, Some(Codec::H264));
47+ assert!(
48+ matches!(backend, Backend::Hardware | Backend::Software),
49+ "a probe that returned must have picked a seat, got {backend:?}"
50+ );
51+}
52+
53+/// HEVC has no software decoder here at all. A box with the plugin answers
54+/// hardware; a box without it is refused by name -- and *never* told that
55+/// `rusty_h264` will take it, which is the one answer that would be a lie.
56+#[test]
57+fn hevc_probes_as_hardware_or_as_a_refusal() {
58+ match probe(&asset("test_hevc.mkv")) {
59+ Ok((codec, backend)) => {
60+ assert_eq!(codec, Some(Codec::Hevc));
61+ assert_eq!(backend, Backend::Hardware, "there is no software HEVC here");
62+ }
63+ Err(e) => assert!(
64+ e.to_string().contains("plugin"),
65+ "a refusal names the plugin, got {e}"
66+ ),
67+ }
68+}
69+
70+/// The running session reports the decoder its *worker* opened, and it agrees
71+/// with what the probe said before anything played. This is the whole point of
72+/// the cell: the worker writes it where the fallback happens, so a hardware
73+/// session that dropped to software could only be seen here.
74+#[test]
75+fn a_playing_session_reports_the_seat_the_probe_named() {
76+ let path = asset("test_baseline.mp4");
77+ let (_codec, probed) = probe(&path).expect("probe the baseline fixture");
78+ let session = PlaybackSession::open(&path).expect("open the fixture");
79+ let started = Instant::now();
80+ loop {
81+ let live = session.decode_backend();
82+ if live != Backend::Opening {
83+ assert_eq!(live, probed, "the running seat is not the probed one");
84+ break;
85+ }
86+ assert!(
87+ started.elapsed() < Duration::from_secs(20),
88+ "the worker never published a decode backend"
89+ );
90+ std::thread::sleep(Duration::from_millis(10));
91+ }
92+}
93+
94+/// What the export card says before the button and what the progress line says
95+/// during the job are the same two answers, from the same two functions: the
96+/// picture's seat is probed by opening the very encoder the export opens, and
97+/// the sound's is decided outright. A drift between them is a front-end lying
98+/// about the machine, which is exactly what this whole surface is for.
99+#[test]
100+fn the_planned_encoders_are_the_ones_the_job_opens() {
101+ let settings = ExportSettings {
102+ format: Format::Mp4,
103+ ..ExportSettings::default()
104+ };
105+ let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
106+ let planned = format!(
107+ "{} · {}",
108+ engine::export::planned_video(session.meta(), &settings).expect("an mp4 carries picture"),
109+ session.planned_audio(Format::Mp4)
110+ );
111+ let out = out_path("planned", "mp4");
112+ let handle = session.export_to_with(&out, &settings);
113+ let started = Instant::now();
114+ let opened = loop {
115+ if let Some(line) = handle.encoders() {
116+ break line;
117+ }
118+ assert!(
119+ !handle.is_finished(),
120+ "the export settled before it opened an encoder: {:?}",
121+ handle.result().map(|r| r.err())
122+ );
123+ assert!(
124+ started.elapsed() < Duration::from_secs(60),
125+ "no encoder was published"
126+ );
127+ std::thread::sleep(Duration::from_millis(10));
128+ };
129+ // Nothing here wants the file, only the seat it was going to be written
130+ // with: cancelling deletes the `.part` the worker had started.
131+ handle.cancel();
132+ wind_down(&handle);
133+ assert_eq!(opened, planned);
134+}
135+
136+/// A WAV job has no picture at all and still names what writes it, so an audio
137+/// export is not a progress line with nothing to say.
138+#[test]
139+fn an_audio_only_job_names_its_encoder() {
140+ let settings = ExportSettings {
141+ format: Format::Wav,
142+ ..ExportSettings::default()
143+ };
144+ assert_eq!(
145+ engine::export::planned_video(
146+ &engine::demux::Demuxer::open(&asset("test_av.mp4"))
147+ .expect("open the fixture")
148+ .0,
149+ &settings
150+ ),
151+ None,
152+ "a WAV has no video seat to name"
153+ );
154+ let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
155+ let planned = session.planned_audio(Format::Wav);
156+ let out = out_path("wav", "wav");
157+ let handle = session.export_to_with(&out, &settings);
158+ let started = Instant::now();
159+ let opened = loop {
160+ if let Some(line) = handle.encoders() {
161+ break line;
162+ }
163+ assert!(
164+ started.elapsed() < Duration::from_secs(60),
165+ "no encoder was published"
166+ );
167+ std::thread::sleep(Duration::from_millis(10));
168+ };
169+ handle.cancel();
170+ wind_down(&handle);
171+ let _ = std::fs::remove_file(&out);
172+ assert_eq!(opened, planned);
173+}
174+
175+/// Waits for a cancelled job to settle, so its `.part` is gone before the test
176+/// ends -- and so no worker outlives the process holding a VA-API session.
177+fn wind_down(handle: &ExportHandle) {
178+ let started = Instant::now();
179+ while !handle.is_finished() {
180+ assert!(
181+ started.elapsed() < Duration::from_secs(60),
182+ "a cancelled export did not settle"
183+ );
184+ std::thread::sleep(Duration::from_millis(10));
185+ }
186+ let _ = handle.result();
187+}