forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(A4): the machine tells you what it can encode — vh_caps asks VA-API at runtime, old plugins stay welcome

Browse files at this commit

c674238544be8817c58edc02caaa91f14cabb484Ahmet Kaan GümüşParent: d1d6ffc0f37a18
crates/app/src/main.rsmodified+56 -0
@@ -952,6 +952,11 @@ struct Player {
952 /// runs off the render thread and only while the export card is up. The952 /// runs off the render thread and only while the export card is up. The
953 /// inner `None` is "asked, not answered yet".953 /// inner `None` is "asked, not answered yet".
954 export_seat: Option<(ExportSettings, (u32, u32), Option<&'static str>)>,954 export_seat: Option<(ExportSettings, (u32, u32), Option<&'static str>)>,
955+ /// What this machine's GPU decodes and encodes, as the plugin answered it:
956+ /// asked once, off the render thread like `export_seat` and for the same
957+ /// reason (a VA-API init), and kept for the life of the process because the
958+ /// answer cannot change while we run. `None` is "not asked yet".
959+ hw_caps: Option<SharedString>,
955 /// The copied clip. Frame ranges only, so it survives the clip it was taken960 /// The copied clip. Frame ranges only, so it survives the clip it was taken
956 /// from being deleted -- and it outlives the selection.961 /// from being deleted -- and it outlives the selection.
957 clipboard: Option<Clip>,962 clipboard: Option<Clip>,
@@ -2766,6 +2771,31 @@ impl Player {
2766 .detach();2771 .detach();
2767 }2772 }
2768 2773
2774+ /// Asks the plugin what this machine's GPU can do, once, the first time the
2775+ /// export card is up to show it. Off the render thread for `cache_export_seat`'s
2776+ /// reason: the plugin initialises VA-API to answer, and a driver that is
2777+ /// slow to load must not be a frame the user waits for.
2778+ fn cache_hw_caps(&mut self, cx: &mut Context<Self>) {
2779+ if !self.export_open || self.hw_caps.is_some() {
2780+ return;
2781+ }
2782+ // Written before the spawn, exactly as the probes above are, so the
2783+ // repaints during it start no second one.
2784+ self.hw_caps = Some("asking the driver…".into());
2785+ let asked = cx
2786+ .background_executor()
2787+ .spawn(async move { engine::caps::hardware() });
2788+ cx.spawn(async move |this, cx| {
2789+ let line = asked.await;
2790+ this.update(cx, |this, cx| {
2791+ this.hw_caps = Some(line.into());
2792+ cx.notify();
2793+ })
2794+ .ok();
2795+ })
2796+ .detach();
2797+ }
2798+
2769 /// The group id of the clicked clip, which is what marks the other half.2799 /// The group id of the clicked clip, which is what marks the other half.
2770 fn selected_link(&self) -> Option<u32> {2800 fn selected_link(&self) -> Option<u32> {
2771 let (lane, idx) = self.selected?;2801 let (lane, idx) = self.selected?;
@@ -4034,6 +4064,7 @@ impl Render for Player {
4034 // is the one place that has to notice a new one.4064 // is the one place that has to notice a new one.
4035 self.cache_media(cx);4065 self.cache_media(cx);
4036 self.cache_export_seat(cx);4066 self.cache_export_seat(cx);
4067+ self.cache_hw_caps(cx);
4037 // What the compositor calls this window. Pushed only when it changes:4068 // What the compositor calls this window. Pushed only when it changes:
4038 // it is a protocol round trip and this runs at vsync.4069 // it is a protocol round trip and this runs at vsync.
4039 let title = window_title(&self.name);4070 let title = window_title(&self.name);
@@ -5963,6 +5994,30 @@ impl Player {
5963 .into_any_element(),5994 .into_any_element(),
5964 );5995 );
5965 }5996 }
5997+ // What is doing the work, on this machine and in this build: the GPU
5998+ // half is asked of the driver through the plugin (a different answer on
5999+ // every machine, and "none" where there is no plugin at all), the build
6000+ // half is the crates that were compiled in. Last in the list, because it
6001+ // is what a user checks rather than what they pick -- and a listing
6002+ // rather than rows, since none of it can be clicked.
6003+ if self.export_grouped {
6004+ list.push(header("THIS MACHINE"));
6005+ }
6006+ let note = |text: String| {
6007+ div()
6008+ .flex_none()
6009+ .px(px(6.))
6010+ .py(px(2.))
6011+ .text_size(px(11.))
6012+ .text_color(rgb(INK_DIM))
6013+ .child(text)
6014+ .into_any_element()
6015+ };
6016+ list.push(note(format!(
6017+ "GPU: {}",
6018+ self.hw_caps.clone().unwrap_or_else(|| "asking…".into())
6019+ )));
6020+ list.push(note(format!("Built in: {}", engine::caps::software())));
5966 // What the rows add up to, which is the one thing that has to be right:6021 // What the rows add up to, which is the one thing that has to be right:
5967 // codec, box, size, rate, sound, where it goes and about how big. Two6022 // codec, box, size, rate, sound, where it goes and about how big. Two
5968 // lines, outside the scrolling list, so it is on screen whatever the6023 // lines, outside the scrolling list, so it is on screen whatever the
@@ -14441,6 +14496,7 @@ fn main() {
14441 sizes: HashMap::new(),14496 sizes: HashMap::new(),
14442 decoders: HashMap::new(),14497 decoders: HashMap::new(),
14443 export_seat: None,14498 export_seat: None,
14499+ hw_caps: None,
14444 clipboard: None,14500 clipboard: None,
14445 scrubbing: false,14501 scrubbing: false,
14446 trim: None,14502 trim: None,
crates/engine-hw/src/lib.rsmodified+132 -1
@@ -46,7 +46,7 @@ use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};
46 use gbm::{BufferObjectFlags, Format as GbmFormat};46 use gbm::{BufferObjectFlags, Format as GbmFormat};
47 47
48 use engine::demux::{Codec, Demuxer};48 use engine::demux::{Codec, Demuxer};
49-use engine::hw::{VhFrame, VhMeta};49+use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhFrame, VhMeta};
50 50
51 type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;51 type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
52 type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;52 type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;
@@ -560,6 +560,112 @@ pub unsafe extern "C" fn vh_close(session: *mut c_void) {
560 }));560 }));
561 }561 }
562 562
563+/// What each codec needs of the driver before this plugin can claim it: the
564+/// 8-bit decode profiles, the 10-bit ones, and the profile the *encoder* here
565+/// would open -- `None` for the two this plugin has no encoder for at all, so a
566+/// GPU with an HEVC or VP9 encode entrypoint is never reported as one edith can
567+/// reach. The encode profiles are the very ones [`EncSession::open_codec`]
568+/// asks for, which is what keeps this a description of the plugin rather than a
569+/// second opinion about it.
570+const CAP_TABLE: [(u32, &[VAProfile::Type], &[VAProfile::Type], Option<VAProfile::Type>); 4] = [
571+ (
572+ CAP_H264,
573+ &[
574+ VAProfile::VAProfileH264ConstrainedBaseline,
575+ VAProfile::VAProfileH264Main,
576+ VAProfile::VAProfileH264High,
577+ ],
578+ &[],
579+ Some(VAProfile::VAProfileH264Main),
580+ ),
581+ (
582+ CAP_HEVC,
583+ &[VAProfile::VAProfileHEVCMain],
584+ &[VAProfile::VAProfileHEVCMain10],
585+ None,
586+ ),
587+ (
588+ CAP_VP9,
589+ &[VAProfile::VAProfileVP9Profile0],
590+ &[VAProfile::VAProfileVP9Profile2],
591+ None,
592+ ),
593+ (
594+ CAP_AV1,
595+ &[VAProfile::VAProfileAV1Profile0],
596+ // AV1 carries 8- and 10-bit in the same profile 0, so the profile bit
597+ // is the same one and the P010 read-back is what decides.
598+ &[VAProfile::VAProfileAV1Profile0],
599+ Some(VAProfile::VAProfileAV1Profile0),
600+ ),
601+];
602+
603+/// This machine's decode and encode seats, asked of the driver rather than
604+/// assumed: which profiles it has, which entrypoints each of those carries, and
605+/// whether a P010 image exists to read a 10-bit picture back through. Only
606+/// codecs this plugin actually implements can light up -- `CAP_TABLE` is that
607+/// half of the intersection.
608+///
609+/// `None` when there is no display to ask at all, which is the same "software
610+/// only" a missing plugin means.
611+fn query_caps() -> Option<VhCaps> {
612+ let (display, _gbm) = open_devices()?;
613+ let profiles = display.query_config_profiles().ok()?;
614+ let p010 = display
615+ .query_image_formats()
616+ .is_ok_and(|formats| formats.iter().any(|f| f.fourcc == VA_FOURCC_P010));
617+ let has = |profile: VAProfile::Type, entrypoint: VAEntrypoint::Type| {
618+ profiles.contains(&profile)
619+ && display
620+ .query_config_entrypoints(profile)
621+ .is_ok_and(|e| e.contains(&entrypoint))
622+ };
623+ let decodes = |list: &[VAProfile::Type]| {
624+ list.iter()
625+ .any(|&p| has(p, VAEntrypoint::VAEntrypointVLD))
626+ };
627+ let mut caps = VhCaps::default();
628+ for (bit, eight, ten, encode) in CAP_TABLE {
629+ if decodes(eight) {
630+ caps.decode |= bit;
631+ }
632+ if p010 && decodes(ten) {
633+ caps.decode_10bit |= bit;
634+ }
635+ // Both entrypoints, exactly as the encoder's own open takes either.
636+ if encode.is_some_and(|p| {
637+ has(p, VAEntrypoint::VAEntrypointEncSlice) || has(p, VAEntrypoint::VAEntrypointEncSliceLP)
638+ }) {
639+ caps.encode |= bit;
640+ }
641+ }
642+ Some(caps)
643+}
644+
645+/// Fills `out` with what this machine and this plugin can do together. 0 on
646+/// success, negative when there is nothing to report -- an *optional* symbol on
647+/// purpose, so the caller resolving it is free to be older or newer than this.
648+///
649+/// Costs one VA-API init; the caller caches the answer.
650+///
651+/// # Safety
652+/// `out` must be writable.
653+#[unsafe(no_mangle)]
654+pub unsafe extern "C" fn vh_caps(out: *mut VhCaps) -> i32 {
655+ catch_unwind(AssertUnwindSafe(|| {
656+ if out.is_null() {
657+ return -1;
658+ }
659+ let Some(caps) = query_caps() else {
660+ return -1;
661+ };
662+ // SAFETY: caller-guaranteed writable destination.
663+ unsafe { *out = caps };
664+ 0
665+ }))
666+ .unwrap_or(-1)
667+}
668+
563 fn align16(v: u32) -> u32 {669 fn align16(v: u32) -> u32 {
564 v.div_ceil(16) * 16670 v.div_ceil(16) * 16
565 }671 }
@@ -993,3 +1099,28 @@ pub unsafe extern "C" fn vh_enc_close(session: *mut c_void) {
993 }1099 }
994 }));1100 }));
995 }1101 }
1102+
1103+#[cfg(test)]
1104+mod tests {
1105+ use super::*;
1106+
1107+ /// Runs against whatever GPU this machine has -- and passes on one with no
1108+ /// VA-API at all, which is exactly what `None` means here. What it pins is
1109+ /// the *shape* of the answer, the contents being the driver's: nothing may
1110+ /// be claimed that this plugin cannot actually reach.
1111+ #[test]
1112+ fn the_caps_query_never_claims_more_than_this_plugin_implements() {
1113+ let Some(caps) = query_caps() else {
1114+ return;
1115+ };
1116+ eprintln!("{caps:?}");
1117+ // Encode is this plugin's two seats and no others, whatever entrypoints
1118+ // the driver has: an HEVC or VP9 EncSlice is not an encoder here.
1119+ assert_eq!(caps.encode & !(CAP_H264 | CAP_AV1), 0, "{caps:?}");
1120+ // A 10-bit claim is a decode claim -- same profile family, read back
1121+ // through P010 -- and there is no 10-bit encode path at all.
1122+ assert_eq!(caps.decode_10bit & !caps.decode, 0, "{caps:?}");
1123+ // H.264 here is 8-bit 4:2:0; the table has no 10-bit profile for it.
1124+ assert_eq!(caps.decode_10bit & CAP_H264, 0, "{caps:?}");
1125+ }
1126+}
crates/engine/src/caps.rsadded+141 -0
@@ -0,0 +1,141 @@
1+//! What this editor can really decode and encode, in one place and in two
2+//! halves.
3+//!
4+//! The *software* half is what this binary was built with: a table, because
5+//! "is `rav1e` linked into this build" is a question the build already answered
6+//! and probing for it would only be a slower way of reading the manifest.
7+//!
8+//! The *hardware* half is a different answer on every machine and is therefore
9+//! never a table: [`crate::hw::caps`] asks the plugin, the plugin asks the
10+//! driver, and what comes back is the intersection of the GPU's entrypoints
11+//! with the codecs the plugin implements. No plugin, an older plugin or no
12+//! driver all read the same way -- "software only" -- because that is what they
13+//! mean for the file a user is about to write.
14+
15+use crate::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps};
16+
17+/// The codecs a hardware line can name, in the order it lists them.
18+const HW_CODECS: [(u32, &str); 4] = [
19+ (CAP_H264, "H.264"),
20+ (CAP_HEVC, "HEVC"),
21+ (CAP_VP9, "VP9"),
22+ (CAP_AV1, "AV1"),
23+];
24+
25+/// The software half: the codec, the crate that carries it here, and which
26+/// halves of the job that crate does. Named crates rather than a bare "SW",
27+/// because the answer to "why is my HEVC file so large" is `oxideav-h265
28+/// intra`, and the row that says so is the row that answers it.
29+const SW_CODECS: [(&str, &str, bool, bool); 10] = [
30+ ("H.264", "rusty_h264", true, true),
31+ ("HEVC", "oxideav-h265 intra", false, true),
32+ ("AV1", "rav1e", false, true),
33+ ("AAC", "rusty_aac", true, true),
34+ ("MP3", "symphonia / rusty_mp3", true, true),
35+ ("FLAC", "symphonia / flacenc", true, true),
36+ ("PCM", "symphonia / hound", true, true),
37+ ("AC-3", "oxideav-ac3", true, false),
38+ ("Vorbis", "symphonia", true, false),
39+ ("ALAC", "symphonia", true, false),
40+];
41+
42+/// The hardware line as a front-end shows it: one measurement per process,
43+/// costing the plugin's VA-API init (~90 ms) the first time. Ask it off a
44+/// render thread.
45+pub fn hardware() -> String {
46+ hw_line(crate::hw::caps())
47+}
48+
49+/// The software line. Pure and constant -- a caller may ask it per repaint.
50+pub fn software() -> String {
51+ SW_CODECS
52+ .iter()
53+ .map(|&(name, krate, decodes, encodes)| {
54+ format!("{name} {} ({krate})", seats(decodes, encodes))
55+ })
56+ .collect::<Vec<_>>()
57+ .join(" · ")
58+}
59+
60+/// What the plugin answered, in words. Separate from [`hardware`] so the
61+/// wording can be tested against a machine this test suite does not have.
62+fn hw_line(caps: Option<VhCaps>) -> String {
63+ let Some(caps) = caps else {
64+ return "none — no plugin, no driver, or a plugin too old to say".to_string();
65+ };
66+ let listed: Vec<String> = HW_CODECS
67+ .iter()
68+ .filter(|&&(bit, _)| caps.decode & bit != 0 || caps.encode & bit != 0)
69+ .map(|&(bit, name)| {
70+ let seats = seats(caps.decode & bit != 0, caps.encode & bit != 0);
71+ match caps.decode_10bit & bit != 0 {
72+ true => format!("{name} {seats} (10-bit)"),
73+ false => format!("{name} {seats}"),
74+ }
75+ })
76+ .collect();
77+ match listed.is_empty() {
78+ // A driver answered and takes none of the codecs this build carries:
79+ // not the same thing as no driver, and worth saying so.
80+ true => "none — the driver takes none of these codecs".to_string(),
81+ false => listed.join(" · "),
82+ }
83+}
84+
85+/// Which halves of the job one seat does. Never both empty: a codec with
86+/// neither is not listed at all.
87+fn seats(decodes: bool, encodes: bool) -> &'static str {
88+ match (decodes, encodes) {
89+ (true, true) => "dec+enc",
90+ (true, false) => "dec",
91+ _ => "enc",
92+ }
93+}
94+
95+#[cfg(test)]
96+mod tests {
97+ use super::*;
98+
99+ #[test]
100+ fn the_hardware_line_says_what_the_plugin_answered_and_nothing_more() {
101+ // No answer at all -- no plugin, no driver, or one older than the
102+ // symbol -- is one line, and never an empty listing that would read as
103+ // "still loading".
104+ assert!(hw_line(None).starts_with("none —"));
105+ // A driver that answers with nothing is its own sentence.
106+ assert!(hw_line(Some(VhCaps::default())).starts_with("none —"));
107+ // This project's own GPU as `vainfo` lists it: H.264 both ways, HEVC
108+ // and VP9 decode with their 10-bit profiles, AV1 both ways. HEVC has a
109+ // VA encode entrypoint here and is *not* an encode seat: the plugin has
110+ // no HEVC encoder, so the line must not offer one.
111+ let radeonsi = VhCaps {
112+ decode: CAP_H264 | CAP_HEVC | CAP_VP9 | CAP_AV1,
113+ encode: CAP_H264 | CAP_AV1,
114+ decode_10bit: CAP_HEVC | CAP_VP9 | CAP_AV1,
115+ };
116+ assert_eq!(
117+ hw_line(Some(radeonsi)),
118+ "H.264 dec+enc · HEVC dec (10-bit) · VP9 dec (10-bit) · AV1 dec+enc (10-bit)"
119+ );
120+ // A codec the driver has neither seat for is left out rather than
121+ // listed as a refusal: this line is what the machine *can* do.
122+ let h264_only = VhCaps {
123+ decode: CAP_H264,
124+ ..Default::default()
125+ };
126+ assert_eq!(hw_line(Some(h264_only)), "H.264 dec");
127+ }
128+
129+ #[test]
130+ fn the_software_line_names_every_encoder_this_build_carries() {
131+ let line = software();
132+ for name in ["rusty_h264", "oxideav-h265 intra", "rav1e", "rusty_aac"] {
133+ assert!(line.contains(name), "{name} missing from {line}");
134+ }
135+ // Decode-only crates must not read as encoders, and the seat words are
136+ // the only thing saying which is which.
137+ assert!(line.contains("AC-3 dec (oxideav-ac3)"));
138+ assert!(line.contains("H.264 dec+enc (rusty_h264)"));
139+ assert!(line.contains("HEVC enc (oxideav-h265 intra)"));
140+ }
141+}
crates/engine/src/hw.rsmodified+52 -0
@@ -62,11 +62,39 @@ impl Default for VhFrame {
62 }62 }
63 }63 }
64 64
65+/// What *this machine* takes, as far as the plugin implements it: one bit per
66+/// codec ([`CAP_H264`] and its three neighbours) in each mask, so a caller reads
67+/// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s.
68+///
69+/// The intersection is the plugin's to compute, never the driver's alone: a GPU
70+/// with an HEVC *encode* entrypoint is still not an HEVC encoder here -- the
71+/// plugin has no such entry point -- and a capability nothing can reach would be
72+/// a lie in whatever the front-end draws from this.
73+#[repr(C)]
74+#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
75+pub struct VhCaps {
76+ pub decode: u32,
77+ pub encode: u32,
78+ /// Codecs whose 10-bit profiles decode: the driver has the profile *and* a
79+ /// P010 image format for the read-back, which is the pair the plugin's
80+ /// 10-bit path needs.
81+ pub decode_10bit: u32,
82+}
83+
84+pub const CAP_H264: u32 = 1 << 0;
85+pub const CAP_HEVC: u32 = 1 << 1;
86+pub const CAP_VP9: u32 = 1 << 2;
87+pub const CAP_AV1: u32 = 1 << 3;
88+
65 struct Plugin {89 struct Plugin {
66 open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void,90 open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void,
67 meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32,91 meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32,
68 next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32,92 next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32,
69 close: unsafe extern "C" fn(*mut c_void),93 close: unsafe extern "C" fn(*mut c_void),
94+ /// The capability query, and the one symbol of this table that may be
95+ /// missing: a plugin built before it exports the four above and not this,
96+ /// which costs a front-end the listing and never a decode.
97+ caps: Option<unsafe extern "C" fn(*mut VhCaps) -> i32>,
70 // Never dropped (lives in a static), so the fn pointers above stay valid.98 // Never dropped (lives in a static), so the fn pointers above stay valid.
71 _lib: Library,99 _lib: Library,
72 }100 }
@@ -102,6 +130,7 @@ fn load() -> Option<Plugin> {
102 meta: *lib.get(b"vh_meta\0").ok()?,130 meta: *lib.get(b"vh_meta\0").ok()?,
103 next_frame: *lib.get(b"vh_next_frame\0").ok()?,131 next_frame: *lib.get(b"vh_next_frame\0").ok()?,
104 close: *lib.get(b"vh_close\0").ok()?,132 close: *lib.get(b"vh_close\0").ok()?,
133+ caps: lib.get(b"vh_caps\0").ok().map(|s| *s),
105 _lib: lib,134 _lib: lib,
106 })135 })
107 })()136 })()
@@ -113,6 +142,29 @@ fn load() -> Option<Plugin> {
113 None142 None
114 }143 }
115 144
145+/// What the plugin says this machine decodes and encodes, asked once per
146+/// process and cached: the answer cannot change while we run.
147+///
148+/// `None` on every way there is no answer -- no plugin, a plugin older than the
149+/// symbol (optional exactly as `vh_enc_av1_open` is: such a plugin still
150+/// decodes), no driver, a driver that refuses the query -- and a caller says
151+/// "software only" for all of them, which is what they mean.
152+///
153+/// Costs one VA-API init (~90 ms) the first time: ask it off a render thread.
154+pub fn caps() -> Option<VhCaps> {
155+ static CAPS: OnceLock<Option<VhCaps>> = OnceLock::new();
156+ *CAPS.get_or_init(|| {
157+ let query = plugin()?.caps?;
158+ let mut caps = VhCaps::default();
159+ // SAFETY: the plugin writes the struct it is handed and reports "no
160+ // answer" as a negative code; nothing is borrowed across the call.
161+ match unsafe { query(&mut caps) } {
162+ 0 => Some(caps),
163+ _ => None,
164+ }
165+ })
166+}
167+
116 /// An open hardware decode session. Dropping it closes the plugin session.168 /// An open hardware decode session. Dropping it closes the plugin session.
117 pub struct HwSession {169 pub struct HwSession {
118 plugin: &'static Plugin,170 plugin: &'static Plugin,
crates/engine/src/lib.rsmodified+1 -0
@@ -2,6 +2,7 @@
2 2
3 pub mod ao;3 pub mod ao;
4 pub mod audio;4 pub mod audio;
5+pub mod caps;
5 pub mod clock;6 pub mod clock;
6 pub mod color;7 pub mod color;
7 pub mod convert;8 pub mod convert;