diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 20be25f..0c6a271 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -687,6 +687,11 @@ struct Player { /// 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>)>, + /// What this machine's GPU decodes and encodes, as the plugin answered it: + /// asked once, off the render thread like `export_seat` and for the same + /// reason (a VA-API init), and kept for the life of the process because the + /// answer cannot change while we run. `None` is "not asked yet". + hw_caps: Option, /// The copied clip. Frame ranges only, so it survives the clip it was taken /// from being deleted -- and it outlives the selection. clipboard: Option, @@ -2257,6 +2262,31 @@ impl Player { .detach(); } + /// Asks the plugin what this machine's GPU can do, once, the first time the + /// export card is up to show it. Off the render thread for `cache_export_seat`'s + /// reason: the plugin initialises VA-API to answer, and a driver that is + /// slow to load must not be a frame the user waits for. + fn cache_hw_caps(&mut self, cx: &mut Context) { + if !self.export_open || self.hw_caps.is_some() { + return; + } + // Written before the spawn, exactly as the probes above are, so the + // repaints during it start no second one. + self.hw_caps = Some("asking the driver…".into()); + let asked = cx + .background_executor() + .spawn(async move { engine::caps::hardware() }); + cx.spawn(async move |this, cx| { + let line = asked.await; + this.update(cx, |this, cx| { + this.hw_caps = Some(line.into()); + 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?; @@ -3399,6 +3429,7 @@ impl Render for Player { // is the one place that has to notice a new one. self.cache_media(cx); self.cache_export_seat(cx); + self.cache_hw_caps(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); @@ -5135,6 +5166,30 @@ impl Player { .into_any_element(), ); } + // What is doing the work, on this machine and in this build: the GPU + // half is asked of the driver through the plugin (a different answer on + // every machine, and "none" where there is no plugin at all), the build + // half is the crates that were compiled in. Last in the list, because it + // is what a user checks rather than what they pick -- and a listing + // rather than rows, since none of it can be clicked. + if self.export_grouped { + list.push(header("THIS MACHINE")); + } + let note = |text: String| { + div() + .flex_none() + .px(px(6.)) + .py(px(2.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child(text) + .into_any_element() + }; + list.push(note(format!( + "GPU: {}", + self.hw_caps.clone().unwrap_or_else(|| "asking…".into()) + ))); + list.push(note(format!("Built in: {}", engine::caps::software()))); // What the rows add up to, which is the one thing that has to be right: // codec, box, size, rate, sound, where it goes and about how big. Two // lines, outside the scrolling list, so it is on screen whatever the @@ -11720,6 +11775,7 @@ fn main() { sizes: HashMap::new(), decoders: HashMap::new(), export_seat: None, + hw_caps: None, clipboard: None, scrubbing: false, trim: None, diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index c4e4b4b..adad406 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -46,7 +46,7 @@ use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution}; use gbm::{BufferObjectFlags, Format as GbmFormat}; use engine::demux::{Codec, Demuxer}; -use engine::hw::{VhFrame, VhMeta}; +use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhFrame, VhMeta}; type PooledFrame = PooledVideoFrame; type Dec = StatelessDecoder>; @@ -559,6 +559,112 @@ pub unsafe extern "C" fn vh_close(session: *mut c_void) { })); } +/// What each codec needs of the driver before this plugin can claim it: the +/// 8-bit decode profiles, the 10-bit ones, and the profile the *encoder* here +/// would open -- `None` for the two this plugin has no encoder for at all, so a +/// GPU with an HEVC or VP9 encode entrypoint is never reported as one edith can +/// reach. The encode profiles are the very ones [`EncSession::open_codec`] +/// asks for, which is what keeps this a description of the plugin rather than a +/// second opinion about it. +const CAP_TABLE: [(u32, &[VAProfile::Type], &[VAProfile::Type], Option); 4] = [ + ( + CAP_H264, + &[ + VAProfile::VAProfileH264ConstrainedBaseline, + VAProfile::VAProfileH264Main, + VAProfile::VAProfileH264High, + ], + &[], + Some(VAProfile::VAProfileH264Main), + ), + ( + CAP_HEVC, + &[VAProfile::VAProfileHEVCMain], + &[VAProfile::VAProfileHEVCMain10], + None, + ), + ( + CAP_VP9, + &[VAProfile::VAProfileVP9Profile0], + &[VAProfile::VAProfileVP9Profile2], + None, + ), + ( + CAP_AV1, + &[VAProfile::VAProfileAV1Profile0], + // AV1 carries 8- and 10-bit in the same profile 0, so the profile bit + // is the same one and the P010 read-back is what decides. + &[VAProfile::VAProfileAV1Profile0], + Some(VAProfile::VAProfileAV1Profile0), + ), +]; + +/// This machine's decode and encode seats, asked of the driver rather than +/// assumed: which profiles it has, which entrypoints each of those carries, and +/// whether a P010 image exists to read a 10-bit picture back through. Only +/// codecs this plugin actually implements can light up -- `CAP_TABLE` is that +/// half of the intersection. +/// +/// `None` when there is no display to ask at all, which is the same "software +/// only" a missing plugin means. +fn query_caps() -> Option { + let (display, _gbm) = open_devices()?; + let profiles = display.query_config_profiles().ok()?; + let p010 = display + .query_image_formats() + .is_ok_and(|formats| formats.iter().any(|f| f.fourcc == VA_FOURCC_P010)); + let has = |profile: VAProfile::Type, entrypoint: VAEntrypoint::Type| { + profiles.contains(&profile) + && display + .query_config_entrypoints(profile) + .is_ok_and(|e| e.contains(&entrypoint)) + }; + let decodes = |list: &[VAProfile::Type]| { + list.iter() + .any(|&p| has(p, VAEntrypoint::VAEntrypointVLD)) + }; + let mut caps = VhCaps::default(); + for (bit, eight, ten, encode) in CAP_TABLE { + if decodes(eight) { + caps.decode |= bit; + } + if p010 && decodes(ten) { + caps.decode_10bit |= bit; + } + // Both entrypoints, exactly as the encoder's own open takes either. + if encode.is_some_and(|p| { + has(p, VAEntrypoint::VAEntrypointEncSlice) || has(p, VAEntrypoint::VAEntrypointEncSliceLP) + }) { + caps.encode |= bit; + } + } + Some(caps) +} + +/// Fills `out` with what this machine and this plugin can do together. 0 on +/// success, negative when there is nothing to report -- an *optional* symbol on +/// purpose, so the caller resolving it is free to be older or newer than this. +/// +/// Costs one VA-API init; the caller caches the answer. +/// +/// # Safety +/// `out` must be writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_caps(out: *mut VhCaps) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if out.is_null() { + return -1; + } + let Some(caps) = query_caps() else { + return -1; + }; + // SAFETY: caller-guaranteed writable destination. + unsafe { *out = caps }; + 0 + })) + .unwrap_or(-1) +} + fn align16(v: u32) -> u32 { v.div_ceil(16) * 16 } @@ -992,3 +1098,28 @@ pub unsafe extern "C" fn vh_enc_close(session: *mut c_void) { } })); } + +#[cfg(test)] +mod tests { + use super::*; + + /// Runs against whatever GPU this machine has -- and passes on one with no + /// VA-API at all, which is exactly what `None` means here. What it pins is + /// the *shape* of the answer, the contents being the driver's: nothing may + /// be claimed that this plugin cannot actually reach. + #[test] + fn the_caps_query_never_claims_more_than_this_plugin_implements() { + let Some(caps) = query_caps() else { + return; + }; + eprintln!("{caps:?}"); + // Encode is this plugin's two seats and no others, whatever entrypoints + // the driver has: an HEVC or VP9 EncSlice is not an encoder here. + assert_eq!(caps.encode & !(CAP_H264 | CAP_AV1), 0, "{caps:?}"); + // A 10-bit claim is a decode claim -- same profile family, read back + // through P010 -- and there is no 10-bit encode path at all. + assert_eq!(caps.decode_10bit & !caps.decode, 0, "{caps:?}"); + // H.264 here is 8-bit 4:2:0; the table has no 10-bit profile for it. + assert_eq!(caps.decode_10bit & CAP_H264, 0, "{caps:?}"); + } +} diff --git a/crates/engine/src/caps.rs b/crates/engine/src/caps.rs new file mode 100644 index 0000000..6bb1187 --- /dev/null +++ b/crates/engine/src/caps.rs @@ -0,0 +1,141 @@ +//! What this editor can really decode and encode, in one place and in two +//! halves. +//! +//! The *software* half is what this binary was built with: a table, because +//! "is `rav1e` linked into this build" is a question the build already answered +//! and probing for it would only be a slower way of reading the manifest. +//! +//! The *hardware* half is a different answer on every machine and is therefore +//! never a table: [`crate::hw::caps`] asks the plugin, the plugin asks the +//! driver, and what comes back is the intersection of the GPU's entrypoints +//! with the codecs the plugin implements. No plugin, an older plugin or no +//! driver all read the same way -- "software only" -- because that is what they +//! mean for the file a user is about to write. + +use crate::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps}; + +/// The codecs a hardware line can name, in the order it lists them. +const HW_CODECS: [(u32, &str); 4] = [ + (CAP_H264, "H.264"), + (CAP_HEVC, "HEVC"), + (CAP_VP9, "VP9"), + (CAP_AV1, "AV1"), +]; + +/// The software half: the codec, the crate that carries it here, and which +/// halves of the job that crate does. Named crates rather than a bare "SW", +/// because the answer to "why is my HEVC file so large" is `oxideav-h265 +/// intra`, and the row that says so is the row that answers it. +const SW_CODECS: [(&str, &str, bool, bool); 10] = [ + ("H.264", "rusty_h264", true, true), + ("HEVC", "oxideav-h265 intra", false, true), + ("AV1", "rav1e", false, true), + ("AAC", "rusty_aac", true, true), + ("MP3", "symphonia / rusty_mp3", true, true), + ("FLAC", "symphonia / flacenc", true, true), + ("PCM", "symphonia / hound", true, true), + ("AC-3", "oxideav-ac3", true, false), + ("Vorbis", "symphonia", true, false), + ("ALAC", "symphonia", true, false), +]; + +/// The hardware line as a front-end shows it: one measurement per process, +/// costing the plugin's VA-API init (~90 ms) the first time. Ask it off a +/// render thread. +pub fn hardware() -> String { + hw_line(crate::hw::caps()) +} + +/// The software line. Pure and constant -- a caller may ask it per repaint. +pub fn software() -> String { + SW_CODECS + .iter() + .map(|&(name, krate, decodes, encodes)| { + format!("{name} {} ({krate})", seats(decodes, encodes)) + }) + .collect::>() + .join(" · ") +} + +/// What the plugin answered, in words. Separate from [`hardware`] so the +/// wording can be tested against a machine this test suite does not have. +fn hw_line(caps: Option) -> String { + let Some(caps) = caps else { + return "none — no plugin, no driver, or a plugin too old to say".to_string(); + }; + let listed: Vec = HW_CODECS + .iter() + .filter(|&&(bit, _)| caps.decode & bit != 0 || caps.encode & bit != 0) + .map(|&(bit, name)| { + let seats = seats(caps.decode & bit != 0, caps.encode & bit != 0); + match caps.decode_10bit & bit != 0 { + true => format!("{name} {seats} (10-bit)"), + false => format!("{name} {seats}"), + } + }) + .collect(); + match listed.is_empty() { + // A driver answered and takes none of the codecs this build carries: + // not the same thing as no driver, and worth saying so. + true => "none — the driver takes none of these codecs".to_string(), + false => listed.join(" · "), + } +} + +/// Which halves of the job one seat does. Never both empty: a codec with +/// neither is not listed at all. +fn seats(decodes: bool, encodes: bool) -> &'static str { + match (decodes, encodes) { + (true, true) => "dec+enc", + (true, false) => "dec", + _ => "enc", + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_hardware_line_says_what_the_plugin_answered_and_nothing_more() { + // No answer at all -- no plugin, no driver, or one older than the + // symbol -- is one line, and never an empty listing that would read as + // "still loading". + assert!(hw_line(None).starts_with("none —")); + // A driver that answers with nothing is its own sentence. + assert!(hw_line(Some(VhCaps::default())).starts_with("none —")); + // This project's own GPU as `vainfo` lists it: H.264 both ways, HEVC + // and VP9 decode with their 10-bit profiles, AV1 both ways. HEVC has a + // VA encode entrypoint here and is *not* an encode seat: the plugin has + // no HEVC encoder, so the line must not offer one. + let radeonsi = VhCaps { + decode: CAP_H264 | CAP_HEVC | CAP_VP9 | CAP_AV1, + encode: CAP_H264 | CAP_AV1, + decode_10bit: CAP_HEVC | CAP_VP9 | CAP_AV1, + }; + assert_eq!( + hw_line(Some(radeonsi)), + "H.264 dec+enc · HEVC dec (10-bit) · VP9 dec (10-bit) · AV1 dec+enc (10-bit)" + ); + // A codec the driver has neither seat for is left out rather than + // listed as a refusal: this line is what the machine *can* do. + let h264_only = VhCaps { + decode: CAP_H264, + ..Default::default() + }; + assert_eq!(hw_line(Some(h264_only)), "H.264 dec"); + } + + #[test] + fn the_software_line_names_every_encoder_this_build_carries() { + let line = software(); + for name in ["rusty_h264", "oxideav-h265 intra", "rav1e", "rusty_aac"] { + assert!(line.contains(name), "{name} missing from {line}"); + } + // Decode-only crates must not read as encoders, and the seat words are + // the only thing saying which is which. + assert!(line.contains("AC-3 dec (oxideav-ac3)")); + assert!(line.contains("H.264 dec+enc (rusty_h264)")); + assert!(line.contains("HEVC enc (oxideav-h265 intra)")); + } +} diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index 8a68b81..e1a465e 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -62,11 +62,39 @@ impl Default for VhFrame { } } +/// What *this machine* takes, as far as the plugin implements it: one bit per +/// codec ([`CAP_H264`] and its three neighbours) in each mask, so a caller reads +/// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s. +/// +/// The intersection is the plugin's to compute, never the driver's alone: a GPU +/// with an HEVC *encode* entrypoint is still not an HEVC encoder here -- the +/// plugin has no such entry point -- and a capability nothing can reach would be +/// a lie in whatever the front-end draws from this. +#[repr(C)] +#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)] +pub struct VhCaps { + pub decode: u32, + pub encode: u32, + /// Codecs whose 10-bit profiles decode: the driver has the profile *and* a + /// P010 image format for the read-back, which is the pair the plugin's + /// 10-bit path needs. + pub decode_10bit: u32, +} + +pub const CAP_H264: u32 = 1 << 0; +pub const CAP_HEVC: u32 = 1 << 1; +pub const CAP_VP9: u32 = 1 << 2; +pub const CAP_AV1: u32 = 1 << 3; + struct Plugin { open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void, meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32, next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32, close: unsafe extern "C" fn(*mut c_void), + /// The capability query, and the one symbol of this table that may be + /// missing: a plugin built before it exports the four above and not this, + /// which costs a front-end the listing and never a decode. + caps: Option i32>, // Never dropped (lives in a static), so the fn pointers above stay valid. _lib: Library, } @@ -102,6 +130,7 @@ fn load() -> Option { meta: *lib.get(b"vh_meta\0").ok()?, next_frame: *lib.get(b"vh_next_frame\0").ok()?, close: *lib.get(b"vh_close\0").ok()?, + caps: lib.get(b"vh_caps\0").ok().map(|s| *s), _lib: lib, }) })() @@ -113,6 +142,29 @@ fn load() -> Option { None } +/// What the plugin says this machine decodes and encodes, asked once per +/// process and cached: the answer cannot change while we run. +/// +/// `None` on every way there is no answer -- no plugin, a plugin older than the +/// symbol (optional exactly as `vh_enc_av1_open` is: such a plugin still +/// decodes), no driver, a driver that refuses the query -- and a caller says +/// "software only" for all of them, which is what they mean. +/// +/// Costs one VA-API init (~90 ms) the first time: ask it off a render thread. +pub fn caps() -> Option { + static CAPS: OnceLock> = OnceLock::new(); + *CAPS.get_or_init(|| { + let query = plugin()?.caps?; + let mut caps = VhCaps::default(); + // SAFETY: the plugin writes the struct it is handed and reports "no + // answer" as a negative code; nothing is borrowed across the call. + match unsafe { query(&mut caps) } { + 0 => Some(caps), + _ => None, + } + }) +} + /// An open hardware decode session. Dropping it closes the plugin session. pub struct HwSession { plugin: &'static Plugin, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index afca436..53397ec 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2,6 +2,7 @@ pub mod ao; pub mod audio; +pub mod caps; pub mod clock; pub mod color; pub mod convert;