diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 20b8c27..bebcf4c 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -11,11 +11,12 @@ use std::time::{Duration, Instant}; use engine::audio::StreamInfo; use engine::color::ColorParams; +use engine::decode::Backend; use engine::eq::{Band, BandKind, EqParams}; use engine::export::{ExportSettings, Format}; use engine::project::{Edge, Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; -use engine::{Clip, ExportHandle, Frame, PlaybackSession}; +use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession}; use gpui::{ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, @@ -644,6 +645,19 @@ struct Player { /// `None` is a file with no picture to report (every source that is not an /// image, and one whose header would not read). sizes: HashMap>, + /// Which decoder each source will run on, probed once at import and kept: + /// the codec (`None` for a still) and the seat the engine picked for it. + /// What a library row says *before* anything plays; the running answer is + /// the session's own (`PlaybackSession::decode_backend`), which follows a + /// fallback this cannot. Filled like `sizes`: presence means "asked", and + /// `None` is a source with no decoder to name -- a song, or one the probe + /// refused -- which must stay in the map or every repaint would ask again. + decoders: HashMap, Backend)>>, + /// Which encoder an export of the picked settings would open, and what it + /// was asked about: the probe opens a real VA-API encoder (~100 ms), so it + /// runs off the render thread and only while the export card is up. The + /// inner `None` is "asked, not answered yet". + export_seat: Option<(ExportSettings, (u32, u32), Option<&'static str>)>, /// The copied clip. Frame ranges only, so it survives the clip it was taken /// from being deleted -- and it outlives the selection. clipboard: Option, @@ -2011,6 +2025,28 @@ impl Player { }) .detach(); } + // Which decoder each file will run on, for the row that says so before + // a frame of it plays. Off the render thread like the streams above: a + // stream the plugin takes costs one VA-API init (~90 ms) to answer. + for path in unseen_paths(session.sources(), &self.decoders) { + self.decoders.insert(path.clone(), None); + let probed = cx.background_executor().spawn({ + let path = path.clone(); + // A song and a source no decoder here takes are both `None`: + // the row says nothing about them rather than guessing, and + // import refused the second at the door anyway. + async move { engine::decode::probe(&path).ok() } + }); + cx.spawn(async move |this, cx| { + let probed = probed.await; + this.update(cx, |this, cx| { + this.decoders.insert(path, probed); + cx.notify(); + }) + .ok(); + }) + .detach(); + } for key in unseen_sources(session.sources(), &self.waves) { self.waves.insert(key.clone(), Wave::Loading); let decoded = cx.background_executor().spawn({ @@ -2043,6 +2079,51 @@ impl Player { } } + /// Probes the encoder an export would open, once per (settings, + /// resolution) and only while the export card is up -- it opens the very + /// VA-API encoder the export would, which is what makes the card's line a + /// measurement instead of a promise, and also what makes it too slow for + /// the render thread. Written before the spawn, like the probes above, so + /// the repaints during it start no second one. + fn cache_export_seat(&mut self, cx: &mut Context) { + let Some(session) = &self.session else { + return; + }; + let settings = export_settings(self.quality, self.custom_mbps, self.format); + if !self.export_open || !settings.format.has_video() { + return; + } + let meta = *session.meta(); + let key = (settings, (meta.width, meta.height)); + if self + .export_seat + .is_some_and(|(asked, size, _)| (asked, size) == key) + { + return; + } + self.export_seat = Some((key.0, key.1, None)); + let probed = cx + .background_executor() + .spawn(async move { engine::export::planned_video(&meta, &settings) }); + cx.spawn(async move |this, cx| { + let probed = probed.await; + this.update(cx, |this, cx| { + // Only if the card is still asking the same question: a format + // changed while the plugin opened has a probe of its own. + if let Some(seat) = this + .export_seat + .as_mut() + .filter(|(asked, size, _)| (*asked, *size) == key) + { + seat.2 = probed; + } + cx.notify(); + }) + .ok(); + }) + .detach(); + } + /// The group id of the clicked clip, which is what marks the other half. fn selected_link(&self) -> Option { let (lane, idx) = self.selected?; @@ -3152,6 +3233,7 @@ impl Render for Player { // has been through a repaint by the time its clips are drawn, so this // is the one place that has to notice a new one. self.cache_media(cx); + self.cache_export_seat(cx); // What the compositor calls this window. Pushed only when it changes: // it is a protocol round trip and this runs at vsync. let title = window_title(&self.name); @@ -3642,11 +3724,17 @@ impl Player { // Its own length, not one derived from what is on the lanes: a row // imported and never placed is a row with a length, and it is the // length a drag would put down. - let rows: Vec<_> = library_rows(sources, &self.streams, self.timeline_audio(), |path| { - self.session - .as_ref() - .map_or(0, |session| session.file_frames(path)) - }) + let rows: Vec<_> = library_rows( + sources, + &self.streams, + &self.decoders, + self.timeline_audio(), + |path| { + self.session + .as_ref() + .map_or(0, |session| session.file_frames(path)) + }, + ) .into_iter() .enumerate() .map(|(i, row)| { @@ -3883,6 +3971,30 @@ impl Player { )) } + /// What is decoding the picture right now, for the transport line: the + /// backend is the running worker's own (it is written where a hardware + /// session falls back to software, so this follows reality), and the codec + /// comes from the clip under the playhead. Empty when nothing is playing -- + /// the question is about what is happening, not about what would. + fn live_decode(&self, position: f64, playing: bool) -> String { + let Some(session) = self.session.as_ref().filter(|_| playing) else { + return String::new(); + }; + let backend = session.decode_backend(); + let codec = session + .video_clip_at(position) + .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| clip.source)) + .and_then(|source| session.sources().get(source)) + .and_then(|source| self.decoders.get(&source.path).copied().flatten()) + .and_then(|(codec, _)| codec); + match backend { + // Neither is a decode, and saying "SW" of them would be a lie. + Backend::Gap => "gap · nothing to decode".to_string(), + Backend::Still => "still · one decode, held".to_string(), + _ => format!("{} decode", decode_label(codec, backend)), + } + } + /// Transport, edit and file buttons, timecode, playhead, clips lane. fn panel( &self, @@ -3924,8 +4036,16 @@ impl Player { let progress = export.progress(); ( format!( - "EXPORTING {}% — {} cancels", + "EXPORTING {}% · {} · {} — {} cancels", (progress * 100.) as u32, + // The row that was picked; the engine's line below names the + // seats alone, since the library is what identifies a codec. + format_label(self.format), + // What the worker actually opened, so a fallback to the + // software encoder shows here rather than being invisible. + export + .encoders() + .unwrap_or_else(|| "opening the encoder".to_string()), key(ActionId::CancelExport) ), progress, @@ -3935,12 +4055,19 @@ impl Player { // tooltips. Keys first: at a 640 px window the tail is what a // truncation eats, and the two hints at the end are also on the // ruler's and Import's tooltips. + // While it plays, what is decoding it goes first: it is the + // answer that changes as the playhead crosses a cut, and the tail + // of this line is what a narrow window truncates. ( - format!( - "{} copy · {} paste · {} undo · click the bar to seek · drop a file to import", - key(ActionId::Copy), - key(ActionId::Paste), - key(ActionId::Undo) + join_detail( + &self.live_decode(position, playing), + &format!( + "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \ + import", + key(ActionId::Copy), + key(ActionId::Paste), + key(ActionId::Undo) + ), ), filled, ) @@ -4711,7 +4838,11 @@ impl Player { .px(px(6.)) .text_size(px(11.)) .text_color(rgb(INK_DIM)) - .child(export_line(self.format, self.session.as_ref())), + .child(export_line( + self.format, + self.session.as_ref(), + self.export_seat.and_then(|(.., seat)| seat), + )), ) .child( div() @@ -6576,6 +6707,7 @@ struct Row { fn library_rows( sources: &[Source], streams: &HashMap>, + decoders: &HashMap, Backend)>>, timeline_audio: Option<(u32, u16)>, frames: impl Fn(&Path) -> u32, ) -> Vec { @@ -6591,12 +6723,22 @@ fn library_rows( path: source.path.clone(), stream: source.audio_stream, name: row_name(&source.path, source.audio_stream, of_file.len() > 1), - // Only where there is a choice to describe: a file with one audio - // track is the row it has always been, name and length, and the - // length is what would be squeezed out at the panel's least width. - detail: info - .filter(|_| of_file.len() > 1) - .map_or_else(String::new, stream_detail), + // The decoder first: it is the same for every row of a file and + // it is what a person opening the panel is asking about. The + // stream half only where there is a choice to describe -- a file + // with one audio track is the row it has always been, name and + // length, and the length is what would be squeezed out at the + // panel's least width. + detail: join_detail( + &decoders + .get(&source.path) + .copied() + .flatten() + .map_or_else(String::new, |(codec, backend)| decode_label(codec, backend)), + &info + .filter(|_| of_file.len() > 1) + .map_or_else(String::new, stream_detail), + ), // A stream already on the timeline is playing: whatever a probe // would say about it now, it is usable by demonstration. unusable: None, @@ -6633,9 +6775,20 @@ fn library_rows( /// why it cannot be used, with the separator only where both halves exist (a /// single-stream file says nothing about its stream). fn join_detail(detail: &str, tail: &str) -> String { - match detail.is_empty() { - true => tail.to_string(), - false => format!("{detail} · {tail}"), + match (detail.is_empty(), tail.is_empty()) { + (true, _) => tail.to_string(), + (false, true) => detail.to_string(), + (false, false) => format!("{detail} · {tail}"), + } +} + +/// How a source's decoder reads: the codec and which seat has it, or the seat +/// alone for a still, which has no coded stream to name. The one place either +/// answer is spelled, so a row, a transport line and a card cannot disagree. +fn decode_label(codec: Option, backend: Backend) -> String { + match codec { + Some(codec) => format!("{} · {}", codec.name(), backend.label()), + None => backend.label().to_string(), } } @@ -6953,14 +7106,32 @@ fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) { /// [`format_line`] plus the project's resolution, which is what a video export /// is written at however many sizes the media on the timeline are. Only for the /// formats that carry a picture -- a WAV has no resolution to state. -fn export_line(format: Format, session: Option<&PlaybackSession>) -> String { +fn export_line( + format: Format, + session: Option<&PlaybackSession>, + seat: Option<&'static str>, +) -> String { let line = format_line(format); + // What it will really be encoded by, on the same line: the picture's seat + // as the probe found it (`…` until it lands, never a guess) and the sound's, + // which is decided without opening anything. Both are what a running export + // then names on its progress line, from the same two functions. + let encoders = match session { + Some(session) => join_detail( + seat.unwrap_or(match format.has_video() { + true => "encoder …", + false => "", + }), + session.planned_audio(format), + ), + None => String::new(), + }; match session.filter(|_| format.has_video()) { Some(session) => { let (w, h) = session.resolution(); - format!("{line} · project {w}x{h}") + format!("{line} · project {w}x{h} · {encoders}") } - None => line.to_string(), + None => join_detail(line, &encoders), } } @@ -8062,9 +8233,13 @@ mod tests { ); // The rows the panel draws: one per source, each its file's own length // -- source 1 has no clip anywhere and is still 4 s at 30 fps. - let rows = library_rows(session.sources(), &HashMap::new(), None, |path| { - session.file_frames(path) - }); + let rows = library_rows( + session.sources(), + &HashMap::new(), + &HashMap::new(), + None, + |path| session.file_frames(path), + ); assert_eq!(rows.len(), 2); assert_eq!(rows[0].frames, 150, "5 s at 30 fps"); assert_eq!(rows[1].frames, 120, "4 s at 30 fps, never placed"); @@ -8103,7 +8278,9 @@ mod tests { .find(|s| s.index == session.sources()[0].audio_stream) .map(|s| (s.sample_rate, s.channels)); let frames = session.file_frames(&path); - let rows = library_rows(session.sources(), &streams, rate, |_| frames); + let rows = library_rows(session.sources(), &streams, &HashMap::new(), rate, |_| { + frames + }); assert_eq!(rows.len(), 1); assert_eq!(rows[0].name, "test_tone.mp3"); assert_eq!(rows[0].unusable, None, "the row is placeable"); @@ -8170,7 +8347,13 @@ mod tests { info(3, 0, 0, None, false), ], ); - let rows = library_rows(&sources, &streams, Some((44_100, 2)), |_| 90); + let rows = library_rows( + &sources, + &streams, + &HashMap::new(), + Some((44_100, 2)), + |_| 90, + ); assert_eq!( rows.iter().map(|r| r.stream).collect::>(), [0, 1, 2, 3], @@ -8208,7 +8391,7 @@ mod tests { PathBuf::from("/m/plain.mp4"), vec![info(0, 44_100, 2, None, true)], ); - let rows = library_rows(&plain, &one, Some((44_100, 2)), |_| 90); + let rows = library_rows(&plain, &one, &HashMap::new(), Some((44_100, 2)), |_| 90); assert_eq!(rows.len(), 1); assert_eq!(rows[0].name, "plain.mp4"); assert_eq!( @@ -8219,7 +8402,7 @@ mod tests { let mut silent = HashMap::new(); silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new()); for probe in [silent, HashMap::new()] { - let rows = library_rows(&plain, &probe, None, |_| 90); + let rows = library_rows(&plain, &probe, &HashMap::new(), None, |_| 90); assert_eq!(rows.len(), 1); assert_eq!(rows[0].name, "plain.mp4"); assert_eq!(rows[0].detail, ""); @@ -8237,7 +8420,13 @@ mod tests { PathBuf::from("/m/other.mp4"), vec![info(0, 44_100, 2, None, true)], ); - let rows = library_rows(&placed, &streams, Some((44_100, 2)), |_| 90); + let rows = library_rows( + &placed, + &streams, + &HashMap::new(), + Some((44_100, 2)), + |_| 90, + ); assert_eq!( rows.iter() .map(|r| (file_name(&r.path), r.stream)) @@ -8640,7 +8829,7 @@ mod tests { ); let streams = HashMap::new(); let rows = |session: &PlaybackSession| { - library_rows(session.sources(), &streams, None, |_| 0).len() + library_rows(session.sources(), &streams, &HashMap::new(), None, |_| 0).len() }; assert_eq!(rows(&session), 2, "a row per source"); @@ -10033,7 +10222,9 @@ mod tests { // a title and a status line. let title = 17.; let status = 28.; - let fixed = 17.; + // Two lines of 11 px: the format line carries the encoders an export + // would open, which is what takes it past one at this width. + let fixed = 30.; let gaps = 4. * 2.; let padding = 24.; assert!( @@ -10581,6 +10772,8 @@ fn main() { waves: HashMap::new(), streams: HashMap::new(), sizes: HashMap::new(), + decoders: HashMap::new(), + export_seat: None, clipboard: None, scrubbing: false, trim: None, diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 5a8b170..c26256e 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::thread; @@ -25,6 +25,106 @@ pub struct Frame { pub bgra: Vec, } +/// Which decoder a source is really running on. Read-only introspection: it +/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose -- +/// a hardware session that opened and then failed before its first picture +/// falls back to software and this says so, because it is written where the +/// fallback happens rather than where it was hoped for. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Backend { + /// The worker has not reached its decoder yet: the plugin's VA-API init is + /// ~90 ms, and this is what a caller reads in that window. + #[default] + Opening, + /// The VA-API plugin (`libengine_hw.so`). + Hardware, + /// `rusty_h264`, in this process. + Software, + /// A still image: one `image` decode, no stream and no decoder to pick. + Still, + /// A gap: black frames, nothing decoded at all. + Gap, +} + +impl Backend { + /// Short enough for a library row and a transport line. + pub fn label(self) -> &'static str { + match self { + Self::Opening => "opening", + Self::Hardware => "HW", + Self::Software => "SW", + Self::Still => "still", + Self::Gap => "gap", + } + } + + fn code(self) -> u8 { + match self { + Self::Opening => 0, + Self::Hardware => 1, + Self::Software => 2, + Self::Still => 3, + Self::Gap => 4, + } + } + + fn from_code(code: u8) -> Self { + match code { + 1 => Self::Hardware, + 2 => Self::Software, + 3 => Self::Still, + 4 => Self::Gap, + _ => Self::Opening, + } + } +} + +/// Where a worker publishes the decoder it opened, for whoever holds the other +/// end of its channel. One atomic byte, written once at open (and once more if +/// hardware hands the range back to software), read whenever a caller repaints +/// -- never per frame on either side. +#[derive(Clone, Default)] +pub struct BackendCell(Arc); + +impl BackendCell { + fn new(backend: Backend) -> Self { + Self(Arc::new(AtomicU8::new(backend.code()))) + } + + fn set(&self, backend: Backend) { + self.0.store(backend.code(), Ordering::Relaxed); + } + + pub fn get(&self) -> Backend { + Backend::from_code(self.0.load(Ordering::Relaxed)) + } +} + +/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`] +/// decides it: the same `VE_SW` pin and the same plugin probe against this very +/// file. What lets a front-end name the decoder *before* anything plays. +/// +/// The codec is `None` for a still image, which has no coded stream. A stream +/// no decoder here can take is an `Err` naming the plugin, exactly as opening +/// it would be -- the same refusal, one VA-API init earlier. +/// +/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per +/// file, off a render thread, and keep the answer. +pub fn probe(path: &Path) -> crate::Result<(Option, Backend)> { + if crate::is_image(path) { + return Ok((None, Backend::Still)); + } + let path = path.to_path_buf(); + let (meta, _demuxer) = Demuxer::open(&path)?; + if open_hw(&path, 0).is_some() { + return Ok((Some(meta.codec), Backend::Hardware)); + } + if meta.codec != Codec::H264 { + return Err(meta.codec.needs_plugin().into()); + } + Ok((Some(meta.codec), Backend::Software)) +} + /// A running decode worker: the flag that stops it, and the handle to wait on. /// /// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize` @@ -85,6 +185,9 @@ impl Drop for Worker { pub(crate) struct FrameStream { pub(crate) frames: Receiver, pub(crate) worker: Worker, + /// What this stream's pictures are being decoded by. Dropped last and read + /// by the caller, so it outlives nothing and blocks nothing. + pub(crate) backend: BackendCell, } pub struct DecodeSession; @@ -152,6 +255,7 @@ impl DecodeSession { cancel, handle: None, }, + backend: BackendCell::new(Backend::Gap), }; } let worker_cancel = Arc::clone(&cancel); @@ -180,6 +284,7 @@ impl DecodeSession { FrameStream { frames: rx, worker: Worker { cancel, handle }, + backend: BackendCell::new(Backend::Gap), } } @@ -209,6 +314,7 @@ impl DecodeSession { cancel, handle: None, }, + backend: BackendCell::new(Backend::Still), }); } // The one conversion, on this thread: it is a few milliseconds and the @@ -245,6 +351,7 @@ impl DecodeSession { Ok(FrameStream { frames: rx, worker: Worker { cancel, handle }, + backend: BackendCell::new(Backend::Still), }) } @@ -285,6 +392,9 @@ impl DecodeSession { // decoder run ahead of the display without limit. let (tx, rx) = sync_channel(2); let cancel = Arc::new(AtomicBool::new(false)); + // Written by the worker below the moment it knows, so a caller reading + // it sees what opened rather than what was hoped for. + let backend = BackendCell::default(); if end_frame <= start_frame { // Nothing to decode: dropping `tx` here closes the channel cleanly, // so the caller sees an immediate end of stream rather than an error. @@ -296,10 +406,12 @@ impl DecodeSession { cancel, handle: None, }, + backend, }, )); } let worker_cancel = Arc::clone(&cancel); + let worker_backend = backend.clone(); let handle = thread::Builder::new() .name("decode".into()) .spawn(move || { @@ -320,6 +432,7 @@ impl DecodeSession { return; } eprintln!("decode backend: hardware (VA-API plugin)"); + worker_backend.set(Backend::Hardware); if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) { return; } @@ -334,6 +447,7 @@ impl DecodeSession { return; } eprintln!("decode backend: software (rusty_h264)"); + worker_backend.set(Backend::Software); run( demuxer, tx, @@ -351,6 +465,7 @@ impl DecodeSession { cancel, handle: Some(handle), }, + backend, }, )) } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 0acc07a..5329048 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -146,6 +146,10 @@ struct Shared { cancel: AtomicBool, finished: AtomicBool, outcome: Mutex>>, + /// The encoders this job really opened, published the moment they are + /// chosen and never changed after -- one seat for the whole file, which is + /// what [`Enc`] states. `None` until then. + encoders: Mutex>, } /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per @@ -174,6 +178,13 @@ impl ExportHandle { self.shared.finished.load(Ordering::Acquire) } + /// What this export is encoding with -- the video seat and what the sound + /// is doing -- as the worker chose them, hardware fallback included. + /// `None` for the first instants of a job, before the encoder is open. + pub fn encoders(&self) -> Option { + self.shared.encoders.lock().unwrap().clone() + } + /// The outcome, once — taken out of the handle, so a caller that already /// reported it sees `None` afterwards. `None` while the export is running. pub fn result(&self) -> Option> { @@ -197,6 +208,7 @@ pub fn start( cancel: AtomicBool::new(false), finished: AtomicBool::new(false), outcome: Mutex::new(None), + encoders: Mutex::new(None), }); let worker = Arc::clone(&shared); let out = out.to_path_buf(); @@ -261,6 +273,103 @@ fn has_picture(project: &Project) -> bool { .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty()) } +/// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a +/// timeline whose export will carry sound from one whose file has none. +fn has_sound(project: &Project) -> bool { + project + .lanes() + .into_iter() + .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty()) +} + +/// Whether any equalizer on the sound is doing something -- the one edit a +/// packet copy cannot carry, so an mp4 whose lane has one is decoded and +/// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane: +/// the copy path has exactly one by the time it asks, and [`planned_audio`] is +/// asked before that is settled. +fn equalized(project: &Project) -> bool { + project.audio_lanes().into_iter().any(|lane| { + (0..project.lane(lane).len()) + .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity())) + }) +} + +/// The bitrate an export codes at: the caller's number through the same clamp +/// as the computed one, for the reason [`Enc::open`] states. +fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 { + settings + .bitrate + .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)) +} + +/// The hardware seat for these settings, opened exactly as the export opens it +/// -- the same pins, the same AV1 opt-in, the same dimensions a driver may +/// refuse -- or `None` where the software encoder takes the file. The single +/// place that choice is made, which is what lets [`planned_video`] *measure* it +/// instead of promising it. +fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option { + if settings.force_sw || forced("VE_SW_ENC") { + return None; + } + let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?; + let bitrate = bitrate_of(meta, settings); + match settings.format { + // Opt-in only, for the reason [`Enc::open_av1`] states in full. + Format::Av1 if !forced("VE_HW_AV1") => None, + Format::Av1 => HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate), + _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate), + } +} + +/// How a front-end names a video seat: which of the two encoders has the file, +/// and which library that is. Not the codec -- a caller shows this beside the +/// format it picked, and `rav1e` names AV1 as `rusty_h264` names H.264. One +/// place, so what a card says before an export and what its progress line says +/// during one cannot drift apart. +fn video_label(format: Format, hw: bool) -> &'static str { + match (format, hw) { + (Format::Av1, true) => "HW encode (VA-API)", + (Format::Av1, false) => "SW encode (rav1e)", + (_, true) => "HW encode (VA-API)", + (_, false) => "SW encode (rusty_h264)", + } +} + +/// What the sound is written by. Every audio encoder here is software -- there +/// is no hardware AAC, PCM or FLAC seat -- so this names *which* one, and +/// whether an mp4 escapes encoding altogether by copying the packets it was +/// given. Empty for AV1, which carries no audio at all: a caller joins this to +/// a line that already says so, and repeating it would cost a line of card. +fn audio_label(project: &Project, format: Format, sound: bool) -> &'static str { + match format { + Format::Av1 => "", + _ if !sound => "no sound to write", + Format::Mp4 if equalized(project) => "AAC · SW encode (rusty_aac)", + Format::Mp4 => "AAC copy", + Format::Wav => "PCM · SW (hound)", + Format::Flac => "FLAC · SW (flacenc)", + } +} + +/// What [`start`] would write this timeline's sound with, before one is +/// started. Pure: no probe and no file opened, so a card may ask it per repaint. +pub fn planned_audio(project: &Project, format: Format) -> &'static str { + audio_label(project, format, has_sound(project)) +} + +/// What [`start`] would encode the picture with, probed the way the export +/// probes it -- the very encoder is opened and closed again -- so this is a +/// measurement and not a promise. `None` for a format that carries no picture. +/// +/// Costs that open (~100 ms here): ask it off a render thread and keep the +/// answer until the format, the resolution or the bitrate changes. +pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> { + settings + .format + .has_video() + .then(|| video_label(settings.format, hw_seat(meta, settings).is_some())) +} + fn settle(shared: &Shared, result: crate::Result<()>) { *shared.outcome.lock().unwrap() = Some(result); // Published last: a caller that sees the flag is guaranteed the outcome. @@ -367,9 +476,7 @@ fn copy_audio( // only this case is: a timeline nobody has equalized still leaves through // the copy below, packet for packet, so no passthrough quietly becomes a // generation of loss. - let equalized = (0..project.lane(lane).len()) - .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity())); - if equalized { + if equalized(project) { return encode_audio(project, meta); } AudioSession::copy_multi_streams(&project.audio_sources(), segments) @@ -495,6 +602,18 @@ fn run( .collect(); let mut encoder = Enc::open(meta, settings)?; + // What this file is really being written by, for a progress line to name. + // Published *after* the seat is open, so a hardware encoder the driver + // refused reads as the software one that took over rather than as the hope + // it replaced -- and the sound says whether it was copied or encoded, which + // `copy_audio` decided a few lines up. + *shared.encoders.lock().unwrap() = Some( + match audio_label(project, settings.format, audio.is_some()) { + // AV1: no sound in the file and none to name. + "" => encoder.label().to_string(), + sound => format!("{} · {sound}", encoder.label()), + }, + ); let mut muxer = None; let mut done = 0u32; let black = Black::new(meta); @@ -734,6 +853,9 @@ fn run_audio( else { return Err("this timeline has no audio to export".into()); }; + // The picture path's line, for a file that is sound alone: there is sound + // by the line above, so this names the encoder writing it. + *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true).to_string()); let channels = usize::from(audio.channels); let frames = (f64::from(project.timeline_frames()) / meta.frame_rate * f64::from(audio.sample_rate)) @@ -988,6 +1110,18 @@ enum Enc { } impl Enc { + /// Which seat this *is*, said the way [`video_label`] says it -- so the + /// name a running export shows is the name the card showed, or the honest + /// difference where the probe and the open disagreed. + fn label(&self) -> &'static str { + match self { + Self::Hw(_) => video_label(Format::Mp4, true), + Self::Sw { .. } => video_label(Format::Mp4, false), + Self::Av1Hw(_) => video_label(Format::Av1, true), + Self::Av1Sw { .. } => video_label(Format::Av1, false), + } + } + fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { if settings.format == Format::Av1 { return Self::open_av1(meta, settings); @@ -995,18 +1129,13 @@ impl Enc { // A caller's number goes through the same clamp as the computed one: a // zero bitrate switches the software encoder's lookahead on, which would // break the one-picture-per-call contract `encode` documents below. - let bitrate = settings - .bitrate - .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); + let bitrate = bitrate_of(meta, settings); // The plugin wants an exact rational, and the muxer already picks one // that is exact at every rate we can read -- `fps * 1000 / 1000` would // hand 24000/1001 over as a rounded 23.976, which is the same // truncation the container timing had. - let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; - if !settings.force_sw - && !forced("VE_SW_ENC") - && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate) - { + crate::mux::frame_timing(meta.frame_rate)?; + if let Some(hw) = hw_seat(meta, settings) { eprintln!("export encoder: hardware (VA-API plugin)"); return Ok(Self::Hw(hw)); } @@ -1047,19 +1176,12 @@ impl Enc { /// cros-codecs release that fixes it) plus a probe encode of one frame at /// open, after which this can prefer hardware the way H.264 does. fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { - let bitrate = settings - .bitrate - .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); + let bitrate = bitrate_of(meta, settings); let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; // Two seconds between keyframes, as the H.264 seat does: a seek may only // land on one, and this is what a cluster of the Matroska file is. let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64; - if forced("VE_HW_AV1") - && !settings.force_sw - && !forced("VE_SW_ENC") - && let Some(hw) = - HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate) - { + if let Some(hw) = hw_seat(meta, settings) { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); return Ok(Self::Av1Hw(hw)); } diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 54f45a5..45bbc2c 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -22,7 +22,7 @@ use crate::ao::AoSession; use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; use crate::color::ColorParams; -use crate::decode::{DecodeSession, Frame, Worker}; +use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::eq::EqParams; use crate::project::{Clip, Edge, Lane, LaneKind, Project, Rate, Source, Span, Speed}; @@ -161,6 +161,11 @@ pub struct PlaybackSession { frames: Receiver, /// The current decode worker. worker: Worker, + /// What that worker opened -- hardware, software, a still, a gap -- written + /// by the worker itself and read by [`decode_backend`](Self::decode_backend). + /// Replaced with the stream at every seek, so it always describes the + /// pictures currently arriving and never the clip before them. + backend: BackendCell, /// Workers cancelled by a seek or a clip change, waiting to be reaped. /// Joining one inline costs whatever VA-API init it is still inside (98 ms /// measured worst case), which is a visible hitch on the caller's thread; @@ -274,6 +279,7 @@ impl PlaybackSession { native: (meta.width, meta.height), frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), clock: PlaybackClock::new(source), audio, @@ -371,6 +377,7 @@ impl PlaybackSession { native: (width, height), frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), // The song keeps the clock, as a video's own sound does -- and wall // time keeps it on a machine with no device, where the picture @@ -446,6 +453,7 @@ impl PlaybackSession { native: (meta.width, meta.height), frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), clock: PlaybackClock::new(ClockSource::Wall), audio: None, @@ -681,6 +689,7 @@ impl PlaybackSession { native, frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), clock: PlaybackClock::new(match audio { Some(_) => ClockSource::Audio, @@ -708,6 +717,24 @@ impl PlaybackSession { &self.meta } + /// What the pictures now arriving are being decoded by: the clip under the + /// playhead, since one video worker feeds the composite at a time. An + /// atomic load -- a front-end may ask it every repaint -- and it is what + /// *opened*, so a clip whose hardware session fell back to software reads + /// [`Backend::Software`] from the frame that fallback happened. + pub fn decode_backend(&self) -> Backend { + self.backend.get() + } + + /// What an export of this timeline would encode the *sound* with, before + /// one is started: the copy an mp4 normally makes, or the software encoder + /// the format (or an equalized lane) forces. Pure -- no probe, no file + /// opened -- so a card may ask it per repaint; the picture's half costs a + /// plugin open and lives in [`crate::export::planned_video`]. + pub fn planned_audio(&self, format: crate::export::Format) -> &'static str { + crate::export::planned_audio(&self.project, format) + } + /// Why this session plays silent although the file has sound -- an audio /// track in a codec we cannot decode, or one the decoder refused. `None` /// when there is audio, and for a file that never had any. A front-end @@ -932,6 +959,7 @@ impl PlaybackSession { // then can it return and be reaped by a later sweep. Nothing here // joins, so this ordering costs the seek nothing. self.frames = stream.frames; + self.backend = stream.backend; self.retire(stream.worker); } self.span = span; diff --git a/crates/engine/tests/backends.rs b/crates/engine/tests/backends.rs new file mode 100644 index 0000000..35e1979 --- /dev/null +++ b/crates/engine/tests/backends.rs @@ -0,0 +1,187 @@ +//! Which decoder and which encoder a job really runs on -- the introspection a +//! front-end shows before an operation and while it runs. +//! +//! The point of every assertion here is *truthfulness*, not a particular seat: +//! this box may or may not have a working plugin, and a test that demanded +//! hardware would only be measuring the machine. What must hold is that the +//! answer given before an operation is the answer the operation then gives, and +//! that neither of them ever names a decoder that could not have run (software +//! HEVC, for one, does not exist here). + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use engine::Codec; +use engine::decode::{Backend, probe}; +use engine::export::{ExportSettings, Format}; +use engine::{ExportHandle, PlaybackSession}; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn out_path(name: &str, ext: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!("ve_backend_{name}_{}.{ext}", std::process::id())); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.part", path.display())); + path +} + +/// A still has no coded stream and no decoder to pick, and it must say so +/// rather than borrowing the picture path's answer. +#[test] +fn a_still_probes_as_a_still() { + let (codec, backend) = probe(&asset("test_still.png")).expect("probe the still"); + assert_eq!(codec, None, "an image has no coded stream to name"); + assert_eq!(backend, Backend::Still); +} + +/// H.264 has both seats, so the probe may legitimately answer either -- but it +/// must answer one of them, and it must name the codec. +#[test] +fn an_h264_source_probes_as_one_of_the_two_seats() { + let (codec, backend) = probe(&asset("test_baseline.mp4")).expect("probe the baseline fixture"); + assert_eq!(codec, Some(Codec::H264)); + assert!( + matches!(backend, Backend::Hardware | Backend::Software), + "a probe that returned must have picked a seat, got {backend:?}" + ); +} + +/// HEVC has no software decoder here at all. A box with the plugin answers +/// hardware; a box without it is refused by name -- and *never* told that +/// `rusty_h264` will take it, which is the one answer that would be a lie. +#[test] +fn hevc_probes_as_hardware_or_as_a_refusal() { + match probe(&asset("test_hevc.mkv")) { + Ok((codec, backend)) => { + assert_eq!(codec, Some(Codec::Hevc)); + assert_eq!(backend, Backend::Hardware, "there is no software HEVC here"); + } + Err(e) => assert!( + e.to_string().contains("plugin"), + "a refusal names the plugin, got {e}" + ), + } +} + +/// The running session reports the decoder its *worker* opened, and it agrees +/// with what the probe said before anything played. This is the whole point of +/// the cell: the worker writes it where the fallback happens, so a hardware +/// session that dropped to software could only be seen here. +#[test] +fn a_playing_session_reports_the_seat_the_probe_named() { + let path = asset("test_baseline.mp4"); + let (_codec, probed) = probe(&path).expect("probe the baseline fixture"); + let session = PlaybackSession::open(&path).expect("open the fixture"); + let started = Instant::now(); + loop { + let live = session.decode_backend(); + if live != Backend::Opening { + assert_eq!(live, probed, "the running seat is not the probed one"); + break; + } + assert!( + started.elapsed() < Duration::from_secs(20), + "the worker never published a decode backend" + ); + std::thread::sleep(Duration::from_millis(10)); + } +} + +/// What the export card says before the button and what the progress line says +/// during the job are the same two answers, from the same two functions: the +/// picture's seat is probed by opening the very encoder the export opens, and +/// the sound's is decided outright. A drift between them is a front-end lying +/// about the machine, which is exactly what this whole surface is for. +#[test] +fn the_planned_encoders_are_the_ones_the_job_opens() { + let settings = ExportSettings { + format: Format::Mp4, + ..ExportSettings::default() + }; + let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + let planned = format!( + "{} · {}", + engine::export::planned_video(session.meta(), &settings).expect("an mp4 carries picture"), + session.planned_audio(Format::Mp4) + ); + let out = out_path("planned", "mp4"); + let handle = session.export_to_with(&out, &settings); + let started = Instant::now(); + let opened = loop { + if let Some(line) = handle.encoders() { + break line; + } + assert!( + !handle.is_finished(), + "the export settled before it opened an encoder: {:?}", + handle.result().map(|r| r.err()) + ); + assert!( + started.elapsed() < Duration::from_secs(60), + "no encoder was published" + ); + std::thread::sleep(Duration::from_millis(10)); + }; + // Nothing here wants the file, only the seat it was going to be written + // with: cancelling deletes the `.part` the worker had started. + handle.cancel(); + wind_down(&handle); + assert_eq!(opened, planned); +} + +/// A WAV job has no picture at all and still names what writes it, so an audio +/// export is not a progress line with nothing to say. +#[test] +fn an_audio_only_job_names_its_encoder() { + let settings = ExportSettings { + format: Format::Wav, + ..ExportSettings::default() + }; + assert_eq!( + engine::export::planned_video( + &engine::demux::Demuxer::open(&asset("test_av.mp4")) + .expect("open the fixture") + .0, + &settings + ), + None, + "a WAV has no video seat to name" + ); + let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + let planned = session.planned_audio(Format::Wav); + let out = out_path("wav", "wav"); + let handle = session.export_to_with(&out, &settings); + let started = Instant::now(); + let opened = loop { + if let Some(line) = handle.encoders() { + break line; + } + assert!( + started.elapsed() < Duration::from_secs(60), + "no encoder was published" + ); + std::thread::sleep(Duration::from_millis(10)); + }; + handle.cancel(); + wind_down(&handle); + let _ = std::fs::remove_file(&out); + assert_eq!(opened, planned); +} + +/// Waits for a cancelled job to settle, so its `.part` is gone before the test +/// ends -- and so no worker outlives the process holding a VA-API session. +fn wind_down(handle: &ExportHandle) { + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < Duration::from_secs(60), + "a cancelled export did not settle" + ); + std::thread::sleep(Duration::from_millis(10)); + } + let _ = handle.result(); +}