Skip to main content

alpha2_gpu/
adapter_choice.rs

1//! Which adapter a host renders on when a machine has several. The same rule applies on every
2//! OS and is decided once at host start.
3//!
4//! Under `auto` the adapters that render are ranked by:
5//! 1. how many of H.264, HEVC and AV1 the adapter encodes on the GPU,
6//! 2. whether it decodes on the GPU, when the decode policy allows it,
7//! 3. the high-performance order of the records.
8//!
9//! Capability leads because neither GPU of a hybrid machine is faster for every project: the
10//! discrete GPU renders heavy compositions faster, while an integrated GPU with a video encoder
11//! exports video-led projects faster at a fraction of the host CPU. `performance` takes the first
12//! hardware adapter in high-performance order. A number or name pins one adapter, and a pin that
13//! matches nothing is refused. Software adapters come last under every policy except a pin.
14//!
15//! The choice is a pure function over per-adapter records, so every policy is testable without a
16//! device.
17
18use crate::AdapterPolicy;
19
20/// The codecs a GPU encoder is asked about, in the order a report lists them.
21pub const GPU_ENCODE_CODECS: [&str; 3] = ["h264", "hevc", "av1"];
22
23/// What one adapter was found to do. Checks that were not made are `Err`, so the choice never
24/// assumes a capability.
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct AdapterRecord {
27    /// Its position in the backend's enumeration, which an index pin names.
28    pub index: usize,
29    /// The adapter's name, which a name pin matches.
30    pub name: String,
31    /// `dx12`, `vulkan` or `metal`.
32    pub backend: &'static str,
33    /// The DXGI adapter LUID, where the backend has one.
34    pub luid: Option<u64>,
35    /// WARP, lavapipe, llvmpipe or another adapter the backend flags as software.
36    pub software: bool,
37    /// Whether a device opens on it, or why not.
38    pub renders: Result<(), String>,
39    /// Whether hardware decode imports into its device, or why not.
40    pub decodes: Result<(), String>,
41    /// Per codec asked about, whether the device encodes it on the GPU, or why not.
42    pub gpu_encodes: Vec<(&'static str, Result<(), String>)>,
43}
44
45impl AdapterRecord {
46    /// A record of an adapter nothing has been asked of yet.
47    #[must_use]
48    pub fn unasked(index: usize, name: String, backend: &'static str, software: bool) -> Self {
49        Self {
50            index,
51            name,
52            backend,
53            luid: None,
54            software,
55            renders: Err("not opened".to_owned()),
56            decodes: Err("not asked".to_owned()),
57            gpu_encodes: Vec::new(),
58        }
59    }
60
61    /// Whether the device encodes `codec` on the GPU.
62    #[must_use]
63    pub fn encodes(&self, codec: &str) -> bool {
64        self.gpu_encodes
65            .iter()
66            .any(|(asked, answer)| *asked == codec && answer.is_ok())
67    }
68
69    /// The codecs the device encodes on the GPU.
70    #[must_use]
71    pub fn encoded_codecs(&self) -> Vec<&'static str> {
72        self.gpu_encodes
73            .iter()
74            .filter(|(_, answer)| answer.is_ok())
75            .map(|(codec, _)| *codec)
76            .collect()
77    }
78
79    /// Why the device encodes no codec on the GPU: the first refusal, or that none was asked.
80    #[must_use]
81    pub fn gpu_encode_reason(&self) -> Option<String> {
82        if !self.encoded_codecs().is_empty() {
83            return None;
84        }
85        Some(
86            match self
87                .gpu_encodes
88                .iter()
89                .find_map(|(_, answer)| answer.as_ref().err())
90            {
91                Some(reason) => reason.clone(),
92                None => "not asked".to_owned(),
93            },
94        )
95    }
96
97    /// `[index] name`, with a note for a software adapter.
98    #[must_use]
99    pub fn label(&self) -> String {
100        format!(
101            "[{}] {}{}",
102            self.index,
103            self.name,
104            if self.software {
105                " (a software adapter)"
106            } else {
107                ""
108            }
109        )
110    }
111
112    /// One line describing this adapter, for the start diagnostic of a passed-over adapter.
113    #[must_use]
114    pub fn summary(&self) -> String {
115        let label = self.label();
116        if let Err(reason) = &self.renders {
117            return format!("{label}: does not render ({reason})");
118        }
119        let decodes = match &self.decodes {
120            Ok(()) => "yes".to_owned(),
121            Err(reason) => format!("no ({reason})"),
122        };
123        let encodes = match self.gpu_encode_reason() {
124            None => self.encoded_codecs().join(","),
125            Some(reason) => format!("none ({reason})"),
126        };
127        format!("{label}: renders, decodes: {decodes}, encodes on the GPU: {encodes}")
128    }
129
130    fn renders_in_hardware(&self) -> bool {
131        self.renders.is_ok() && !self.software
132    }
133}
134
135/// Why the chosen adapter was taken.
136#[derive(Clone, Copy, Debug, Eq, PartialEq)]
137pub enum ChoiceReason {
138    /// `ALPHA2_GPU_ADAPTER` names it.
139    Pinned,
140    /// It is the only hardware adapter that renders, or the only adapter at all.
141    OnlyAdapter,
142    /// It encodes more codecs on the GPU than the next one.
143    MostGpuEncoders,
144    /// It encodes as many codecs as the next one, and decodes on the GPU where that one does not.
145    Decodes,
146    /// Nothing else tells it from the next one: it comes first in the high-performance order.
147    HighPerformanceOrder,
148    /// `ALPHA2_GPU_ADAPTER=performance`: the first hardware adapter in the high-performance order.
149    PerformancePolicy,
150    /// No adapter could share a device with the video codecs, so decode and encode run without
151    /// the GPU.
152    NoSharedDevice,
153    /// No hardware adapter renders, and `ALPHA2_GPU_ADAPTER` pins no software one: a renderer
154    /// that asks for the GPU does not start.
155    NoHardwareAdapter,
156}
157
158impl ChoiceReason {
159    /// The reason as a capability report names it.
160    #[must_use]
161    pub const fn as_str(self) -> &'static str {
162        match self {
163            Self::Pinned => "pinned",
164            Self::OnlyAdapter => "only-adapter",
165            Self::MostGpuEncoders => "most-gpu-encoders",
166            Self::Decodes => "decodes",
167            Self::HighPerformanceOrder => "high-performance-order",
168            Self::PerformancePolicy => "performance-policy",
169            Self::NoSharedDevice => "no-shared-device",
170            Self::NoHardwareAdapter => "no-hardware-adapter",
171        }
172    }
173}
174
175/// The adapters a policy takes, best first, and why the first one leads.
176#[derive(Clone, Debug, Eq, PartialEq)]
177pub struct AdapterOrder {
178    /// Positions in the records: every adapter that renders and that the policy accepts.
179    pub order: Vec<usize>,
180    /// Why the first leads.
181    pub reason: ChoiceReason,
182}
183
184/// The adapters `policy` accepts among `records` (in high-performance order), best first.
185/// `decode_allowed` says whether the decode policy allows GPU decoding. Software adapters always
186/// rank after hardware ones.
187///
188/// # Errors
189/// Returns why no adapter can be taken: none renders, or the pin matches no rendering adapter.
190pub fn rank_adapters(
191    records: &[AdapterRecord],
192    policy: &AdapterPolicy,
193    decode_allowed: bool,
194) -> Result<AdapterOrder, String> {
195    // Hardware adapters in the order given, then software ones.
196    let considered: Vec<usize> = (0..records.len())
197        .filter(|&at| !records[at].software)
198        .chain((0..records.len()).filter(|&at| records[at].software))
199        .collect();
200    if policy.is_pin() {
201        let named: Vec<usize> = considered
202            .iter()
203            .copied()
204            .filter(|&at| policy.names(records[at].index, &records[at].name))
205            .collect();
206        if named.is_empty() {
207            return Err(format!(
208                "{} matches no adapter; the adapters are {}",
209                policy.setting(),
210                adapter_list(records)
211            ));
212        }
213        let order: Vec<usize> = named
214            .iter()
215            .copied()
216            .filter(|&at| records[at].renders.is_ok())
217            .collect();
218        if order.is_empty() {
219            return Err(format!(
220                "{} names {}, which does not render",
221                policy.setting(),
222                named
223                    .iter()
224                    .map(|&at| records[at].summary())
225                    .collect::<Vec<_>>()
226                    .join("; ")
227            ));
228        }
229        return Ok(AdapterOrder {
230            order,
231            reason: ChoiceReason::Pinned,
232        });
233    }
234    let mut order: Vec<usize> = considered
235        .into_iter()
236        .filter(|&at| records[at].renders.is_ok())
237        .collect();
238    if order.is_empty() {
239        return Err(format!(
240            "no adapter renders: {}",
241            records
242                .iter()
243                .map(AdapterRecord::summary)
244                .collect::<Vec<_>>()
245                .join("; ")
246        ));
247    }
248    if *policy == AdapterPolicy::Performance {
249        return Ok(AdapterOrder {
250            order,
251            reason: ChoiceReason::PerformancePolicy,
252        });
253    }
254    let decodes = |at: usize| decode_allowed && records[at].decodes.is_ok();
255    // Stable, so ties keep the high-performance order.
256    order.sort_by_key(|&at| {
257        let record = &records[at];
258        let hardware = !record.software;
259        (
260            !hardware,
261            std::cmp::Reverse(if hardware {
262                record.encoded_codecs().len()
263            } else {
264                0
265            }),
266            !(hardware && decodes(at)),
267        )
268    });
269    let reason = match order.get(1) {
270        // A software adapter is no alternative to a hardware one.
271        None => ChoiceReason::OnlyAdapter,
272        Some(&next) if !records[order[0]].software && records[next].software => {
273            ChoiceReason::OnlyAdapter
274        }
275        Some(&next) => {
276            let (first, second) = (&records[order[0]], &records[next]);
277            let encoders = |record: &AdapterRecord| {
278                if record.software {
279                    0
280                } else {
281                    record.encoded_codecs().len()
282                }
283            };
284            if encoders(first) > encoders(second) {
285                ChoiceReason::MostGpuEncoders
286            } else if first.renders_in_hardware()
287                && decodes(order[0])
288                && !(second.renders_in_hardware() && decodes(next))
289            {
290                ChoiceReason::Decodes
291            } else {
292                ChoiceReason::HighPerformanceOrder
293            }
294        }
295    };
296    Ok(AdapterOrder { order, reason })
297}
298
299/// One sentence explaining why `chosen` was taken, naming the runner-up `next` where relevant.
300#[must_use]
301pub fn explain_choice(
302    records: &[AdapterRecord],
303    chosen: usize,
304    next: Option<usize>,
305    reason: ChoiceReason,
306    policy: &AdapterPolicy,
307) -> String {
308    let Some(record) = records.get(chosen) else {
309        return "no adapter was chosen".to_owned();
310    };
311    let encodes = |record: &AdapterRecord| match record.gpu_encode_reason() {
312        None => format!("encodes {} on the GPU", record.encoded_codecs().join(",")),
313        Some(why) => format!("encodes nothing on the GPU ({why})"),
314    };
315    let next = next.and_then(|at| records.get(at));
316    match (reason, next) {
317        (ChoiceReason::Pinned, _) => format!("{} names {}", policy.setting(), record.name),
318        (ChoiceReason::OnlyAdapter, _) => format!(
319            "{} is the only {}adapter that renders",
320            record.name,
321            if record.software { "" } else { "hardware " }
322        ),
323        (ChoiceReason::PerformancePolicy, _) if record.software => format!(
324            "{} renders in software: no hardware adapter renders here",
325            record.name
326        ),
327        (ChoiceReason::PerformancePolicy, _) => format!(
328            "{} is the first hardware adapter in the high-performance order",
329            record.name
330        ),
331        (ChoiceReason::NoHardwareAdapter, _) => format!(
332            "{} renders in software, and {} pins no software adapter",
333            record.name,
334            policy.setting()
335        ),
336        (ChoiceReason::NoSharedDevice, _) => format!(
337            "{} renders without a device shared with the video decoder and encoder",
338            record.name
339        ),
340        (ChoiceReason::MostGpuEncoders, Some(next)) => format!(
341            "{} {}, more codecs than {}, which {}",
342            record.name,
343            encodes(record),
344            next.name,
345            encodes(next)
346        ),
347        (ChoiceReason::Decodes, Some(next)) => format!(
348            "{} decodes on the GPU and {} does not ({}); both encode as many codecs on the GPU",
349            record.name,
350            next.name,
351            next.decodes
352                .as_ref()
353                .err()
354                .map_or("decode is in software", String::as_str)
355        ),
356        (ChoiceReason::HighPerformanceOrder, Some(next)) => format!(
357            "{} comes before {} in the high-performance order, and does no less on the GPU",
358            record.name, next.name
359        ),
360        (_, None) => format!("{} is the only adapter that renders", record.name),
361    }
362}
363
364/// `[0] name, [1] name, ...`.
365fn adapter_list(records: &[AdapterRecord]) -> String {
366    if records.is_empty() {
367        return "none".to_owned();
368    }
369    records
370        .iter()
371        .map(|record| format!("[{}] {}", record.index, record.name))
372        .collect::<Vec<_>>()
373        .join(", ")
374}
375
376/// For each codec `chosen` does not encode on the GPU, another hardware adapter that does and
377/// the `ALPHA2_GPU_ADAPTER` setting that selects it.
378#[must_use]
379pub fn encode_elsewhere(records: &[AdapterRecord], chosen: usize) -> Vec<(&'static str, String)> {
380    let Some(current) = records.get(chosen) else {
381        return Vec::new();
382    };
383    GPU_ENCODE_CODECS
384        .iter()
385        .filter(|codec| !current.encodes(codec))
386        .filter_map(|&codec| {
387            let other = records
388                .iter()
389                .enumerate()
390                .find(|(at, record)| {
391                    *at != chosen && record.renders_in_hardware() && record.encodes(codec)
392                })
393                .map(|(_, record)| record)?;
394            Some((
395                codec,
396                format!(
397                    "{} encodes {codec} on the GPU ({} renders there)",
398                    other.name,
399                    AdapterPolicy::Index(other.index).setting()
400                ),
401            ))
402        })
403        .collect()
404}
405
406/// Why `chosen` cannot decode, from the records of every hardware adapter considered.
407#[must_use]
408pub fn decode_refusals(records: &[AdapterRecord], chosen: usize, pinned: bool) -> String {
409    let considered: Vec<&AdapterRecord> = if pinned {
410        records.get(chosen).into_iter().collect()
411    } else {
412        records
413            .iter()
414            .filter(|record| record.renders_in_hardware())
415            .collect()
416    };
417    considered
418        .into_iter()
419        .filter_map(|record| {
420            record
421                .decodes
422                .as_ref()
423                .err()
424                .map(|reason| format!("{}: {reason}", record.name))
425        })
426        .collect::<Vec<_>>()
427        .join("; ")
428}
429
430/// What a host's adapter choice was, as its capabilities and failure reports state it.
431#[derive(Clone, Debug, PartialEq, Eq)]
432pub struct AdapterChoiceReport {
433    /// The `ALPHA2_GPU_ADAPTER` policy the choice was made under.
434    pub policy: AdapterPolicy,
435    /// The renderer's adapter in `records`; `None` for a device from elsewhere.
436    pub chosen: Option<usize>,
437    /// Why the renderer is on that adapter.
438    pub reason: ChoiceReason,
439    /// One sentence naming the chosen adapter, and the runner-up where the reason compares them.
440    pub explanation: String,
441    /// Every adapter the choice considered, in the high-performance order.
442    pub records: Vec<AdapterRecord>,
443}
444
445impl AdapterChoiceReport {
446    /// The report for `records` ranked into `order` under `policy`, taking the first.
447    #[must_use]
448    pub fn ranked(
449        policy: AdapterPolicy,
450        records: Vec<AdapterRecord>,
451        order: &AdapterOrder,
452    ) -> Self {
453        let chosen = order.order.first().copied();
454        let explanation = chosen.map_or_else(
455            || "no adapter was chosen".to_owned(),
456            |chosen| {
457                explain_choice(
458                    &records,
459                    chosen,
460                    order.order.get(1).copied(),
461                    order.reason,
462                    &policy,
463                )
464            },
465        );
466        Self {
467            policy,
468            chosen,
469            reason: order.reason,
470            explanation,
471            records,
472        }
473    }
474
475    /// The record of the adapter the renderer is on.
476    #[must_use]
477    pub fn chosen_record(&self) -> Option<&AdapterRecord> {
478        self.chosen.and_then(|at| self.records.get(at))
479    }
480}
481
482#[cfg(test)]
483#[path = "adapter_choice_tests.rs"]
484mod tests;