Skip to main content

ironmonitor/codec/
mod.rs

1//! Hardware codec and media capability detection — video encode/decode, GPU compute.
2//!
3//! # Platform Support
4//!
5//! - **Linux**: Reads `/sys/class/drm/card*/device/`, `vainfo`, `vdpauinfo`
6//! - **Windows**: Uses WMI (`Win32_VideoController`), DXVA queries
7//! - **macOS**: Uses `VTIsHardwareDecodeSupported`, system_profiler
8//!
9//! ## Inference
10//!
11//! When direct API queries aren't available, codec support is *inferred* from
12//! GPU model name and generation using a built-in capability database.
13//!
14//! # Examples
15//!
16//! ```no_run
17//! use ironmonitor::codec::CodecMonitor;
18//!
19//! let monitor = CodecMonitor::new().unwrap();
20//! for cap in monitor.capabilities() {
21//!     println!("{}: {} {:?} (max {:?})",
22//!         cap.device, cap.codec, cap.direction, cap.max_resolution);
23//! }
24//! ```
25
26use crate::error::IronError;
27use serde::{Deserialize, Serialize};
28
29/// Video codec type
30#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
31pub enum VideoCodec {
32    H264,
33    H265,
34    H266,
35    VP8,
36    VP9,
37    AV1,
38    MPEG2,
39    MPEG4,
40    VC1,
41    JPEG,
42    ProRes,
43    Other(String),
44}
45
46/// Codec direction — encode, decode, or both
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub enum CodecDirection {
49    Decode,
50    Encode,
51    Both,
52}
53
54/// Maximum supported resolution
55#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
56pub enum MaxResolution {
57    SD,     // 720x480
58    HD,     // 1280x720
59    FullHD, // 1920x1080
60    QHD,    // 2560x1440
61    UHD4K,  // 3840x2160
62    UHD8K,  // 7680x4320
63    Unknown,
64}
65
66/// Color depth / bit depth support
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub enum BitDepth {
69    Bit8,
70    Bit10,
71    Bit12,
72    Unknown,
73}
74
75/// Source of the capability information
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub enum CapabilitySource {
78    /// Detected via hardware/driver API
79    DirectQuery,
80    /// Inferred from GPU model/generation
81    Inferred,
82    /// User-provided override
83    Manual,
84}
85
86/// Fixed confidence for a row read from `vainfo`, a direct driver query. Not a probability.
87#[cfg(target_os = "linux")]
88const CONFIDENCE_VAINFO_QUERY: f32 = 1.0;
89/// Fixed confidence for the NVIDIA base codec table, inferred from the GPU name.
90const CONFIDENCE_NVIDIA_BASE_CODECS: f32 = 0.85;
91/// Fixed confidence for AV1 encode and decode on RTX 40-series, inferred from the GPU name.
92const CONFIDENCE_NVIDIA_AV1_RTX40: f32 = 0.9;
93/// Fixed confidence for AV1 decode on RTX 30-series, inferred from the GPU name.
94const CONFIDENCE_NVIDIA_AV1_RTX30: f32 = 0.85;
95/// Fixed confidence for the AMD base codec table, inferred from the GPU name.
96const CONFIDENCE_AMD_BASE_CODECS: f32 = 0.8;
97/// Fixed confidence for AV1 on RDNA 3 (VCN 4.0), inferred from the GPU name.
98const CONFIDENCE_AMD_AV1_RDNA3: f32 = 0.85;
99/// Fixed confidence for AV1 decode on RDNA 2 (VCN 3.0), inferred from the GPU name.
100const CONFIDENCE_AMD_AV1_RDNA2: f32 = 0.8;
101/// Fixed confidence for the Intel base codec table, inferred from the GPU name.
102const CONFIDENCE_INTEL_BASE_CODECS: f32 = 0.8;
103/// Fixed confidence for AV1 on Intel Arc (Xe Media Engine), inferred from the GPU name.
104const CONFIDENCE_INTEL_ARC_AV1: f32 = 0.85;
105/// Fixed confidence for the Apple Media Engine codec table, inferred from the chip name.
106const CONFIDENCE_APPLE_BASE_CODECS: f32 = 0.9;
107/// Fixed confidence for AV1 decode on M3, M4 and M2 Pro/Max/Ultra, inferred from the chip name.
108const CONFIDENCE_APPLE_AV1: f32 = 0.85;
109
110/// A single codec capability
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct CodecCapability {
113    /// Device name (e.g., "NVIDIA RTX 4090", "Intel UHD 770")
114    pub device: String,
115    /// Codec type
116    pub codec: VideoCodec,
117    /// Direction (encode/decode/both)
118    pub direction: CodecDirection,
119    /// Maximum supported resolution, or `None` where no frame class was read.
120    /// The Apple rows used to hold literal 4K and 8K classes for every chip, and
121    /// the VA-API rows a literal 4K, neither of which any platform query reports.
122    pub max_resolution: Option<MaxResolution>,
123    /// Maximum bit depth
124    pub max_bit_depth: BitDepth,
125    /// Maximum FPS at the maximum resolution.
126    ///
127    /// `None` on every path this crate has, and that is the honest value. The
128    /// field held a literal `60` at all twelve construction sites while the
129    /// ontology declared it `Derived` *from* `codec` and `max_resolution` --
130    /// arithmetic that does not exist. 60 is also not a frame rate an 8K HEVC
131    /// engine reaches, so the constant was not even a safe floor.
132    pub max_fps: Option<u32>,
133    /// Hardware engine name (e.g., "NVENC", "NVDEC", "VCE", "QuickSync")
134    pub engine: String,
135    /// How this capability was determined
136    pub source: CapabilitySource,
137    /// Confidence (0.0-1.0) that this row is right. Not a measured probability:
138    /// it is the fixed constant of the detection rule that produced the row (one
139    /// of the `CONFIDENCE_*` constants in this module), chosen by the code. Only a
140    /// driver query carries 1.0. Rows are built only inside a rule that matched.
141    pub confidence: f32,
142}
143
144/// Compute capability for GPGPU workloads
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct ComputeCapability {
147    /// Device name
148    pub device: String,
149    /// CUDA compute capability (e.g., "8.9") — NVIDIA only; `None` when the
150    /// generation is not known
151    pub cuda_version: Option<String>,
152    /// OpenCL version supported. `None` where it was not read. The NVIDIA
153    /// rows used to hold the literal "3.0" for every card, whatever its
154    /// generation, and the Apple rows an empty string.
155    pub opencl_version: Option<String>,
156    /// Vulkan compute supported. `None` where it was not read: the NVIDIA rows
157    /// used to hold `true` unconditionally.
158    pub vulkan_compute: Option<bool>,
159    /// Metal compute supported (Apple)
160    pub metal_compute: bool,
161    /// DirectCompute version (Windows). `None` where it was not read: the
162    /// NVIDIA rows used to hold the literal "5.0" for every card.
163    pub direct_compute: Option<String>,
164    /// Estimated TFLOPS (FP32); `None` for a generation the table does not know
165    pub estimated_tflops_fp32: Option<f32>,
166    /// Estimated TFLOPS (FP16 / half precision); `None` when FP32 is unknown
167    pub estimated_tflops_fp16: Option<f32>,
168    /// Tensor core / AI accelerator present; `None` when not known
169    pub has_tensor_cores: Option<bool>,
170    /// Ray tracing hardware acceleration; `None` when not known
171    pub has_ray_tracing: Option<bool>,
172    /// Source of capability info
173    pub source: CapabilitySource,
174}
175
176/// Whether `s` is a non-empty run of ASCII digits.
177fn all_digits(s: &str) -> bool {
178    !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
179}
180
181/// NVIDIA product line. The line decides tensor cores and ray tracing: the RTX
182/// line has both from Turing on, and the GTX 10 and 16 series have neither.
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184enum NvidiaLine {
185    Gtx,
186    Rtx,
187}
188
189/// NVIDIA GPU generation, as the model number places it.
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191enum NvidiaGen {
192    Pascal,
193    Turing,
194    Ampere,
195    Ada,
196}
197
198/// The parts of an NVIDIA model name this module reads. "NVIDIA GeForce RTX 3090 Ti"
199/// is `Rtx`, `3090`, and suffix `ti`.
200#[derive(Debug, Clone, PartialEq, Eq)]
201struct NvidiaModel {
202    line: NvidiaLine,
203    /// The model number token: `3090`, `1660`, or `a4000` for an RTX A-series part.
204    number: String,
205    /// The lower-case word after the number, if any: `ti`, `super`, `ada`.
206    suffix: Option<String>,
207}
208
209impl NvidiaModel {
210    /// The generation this model number places the part in, or `None` for a
211    /// number the table does not place.
212    fn generation(&self) -> Option<NvidiaGen> {
213        if self.suffix.as_deref() == Some("ada") {
214            return Some(NvidiaGen::Ada);
215        }
216        if self.line == NvidiaLine::Rtx && self.number.starts_with('a') {
217            // RTX A-series workstation parts (A2000 to A6000) are Ampere.
218            return Some(NvidiaGen::Ampere);
219        }
220        match (self.line, self.number.get(..2)?) {
221            (NvidiaLine::Gtx, "10") => Some(NvidiaGen::Pascal),
222            (NvidiaLine::Gtx, "16") => Some(NvidiaGen::Turing),
223            (NvidiaLine::Rtx, "20") => Some(NvidiaGen::Turing),
224            (NvidiaLine::Rtx, "30") => Some(NvidiaGen::Ampere),
225            (NvidiaLine::Rtx, "40") => Some(NvidiaGen::Ada),
226            _ => None,
227        }
228    }
229}
230
231/// Parse an NVIDIA model name. The model is the token after "GTX" or "RTX": a
232/// GeForce number is three or four digits, and an RTX A-series number is an "A"
233/// and four digits. Anything else (Tesla, "Quadro P4000", a name with no model)
234/// is `None`, so a substring such as "40" can never place a part by accident.
235fn parse_nvidia_model(name: &str) -> Option<NvidiaModel> {
236    let lower = name.to_lowercase();
237    let tokens: Vec<&str> = lower.split_whitespace().collect();
238    let (idx, line) = tokens.iter().enumerate().find_map(|(i, t)| match *t {
239        "rtx" => Some((i, NvidiaLine::Rtx)),
240        "gtx" => Some((i, NvidiaLine::Gtx)),
241        _ => None,
242    })?;
243    let number = *tokens.get(idx + 1)?;
244    let geforce = (3..=4).contains(&number.len()) && all_digits(number);
245    let a_series = line == NvidiaLine::Rtx
246        && number.len() == 5
247        && number.starts_with('a')
248        && all_digits(&number[1..]);
249    if !geforce && !a_series {
250        return None;
251    }
252    let suffix = tokens
253        .get(idx + 2)
254        .filter(|s| s.bytes().all(|b| b.is_ascii_alphabetic()))
255        .map(|s| s.to_string());
256    Some(NvidiaModel {
257        line,
258        number: number.to_string(),
259        suffix,
260    })
261}
262
263/// FP32 and FP16 TFLOPS for the base models listed here, matched on the exact
264/// model number with no suffix. A "Ti" or "SUPER" part has its own figures, and
265/// none is taken from its base model.
266fn nvidia_tflops(model: &NvidiaModel) -> Option<(f32, Option<f32>)> {
267    if model.suffix.is_some() {
268        return None;
269    }
270    match (model.line, model.number.as_str()) {
271        (NvidiaLine::Rtx, "4090") => Some((82.6, Some(165.2))),
272        (NvidiaLine::Rtx, "4080") => Some((48.7, Some(97.5))),
273        (NvidiaLine::Rtx, "4070") => Some((29.1, Some(58.3))),
274        (NvidiaLine::Rtx, "3090") => Some((35.6, Some(71.2))),
275        (NvidiaLine::Rtx, "3080") => Some((29.8, Some(59.6))),
276        (NvidiaLine::Rtx, "2080") => Some((14.2, Some(28.4))),
277        (NvidiaLine::Gtx, "1080") => Some((8.9, None)),
278        _ => None,
279    }
280}
281
282/// RDNA generation of an AMD Radeon RX model, as the model number places it.
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284enum AmdGen {
285    Rdna1,
286    Rdna2,
287    Rdna3,
288}
289
290/// Parse the RDNA generation from an AMD RX model name. RDNA models carry four
291/// digits after "RX" (RX 5700 XT, RX 6800M, RX 7900 XTX). The three-digit RX 500
292/// series is Polaris and is not placed here, and a name with no RX model number
293/// (an APU's "Radeon(TM) Graphics") is not placed either.
294fn parse_amd_rx_generation(name: &str) -> Option<AmdGen> {
295    let lower = name.to_lowercase();
296    let tokens: Vec<&str> = lower.split_whitespace().collect();
297    let idx = tokens.iter().position(|t| *t == "rx")?;
298    let number = *tokens.get(idx + 1)?;
299    // Mobile parts end in "M" and share their desktop family's generation.
300    let digits = number.strip_suffix('m').unwrap_or(number);
301    if digits.len() != 4 || !all_digits(digits) {
302        return None;
303    }
304    match digits.as_bytes()[0] {
305        b'5' => Some(AmdGen::Rdna1),
306        b'6' => Some(AmdGen::Rdna2),
307        b'7' => Some(AmdGen::Rdna3),
308        _ => None,
309    }
310}
311
312/// Monitor for codec and compute capabilities
313pub struct CodecMonitor {
314    codec_caps: Vec<CodecCapability>,
315    compute_caps: Vec<ComputeCapability>,
316    /// GPUs whose names the inference rules did not place. They get no codec rows.
317    unmatched_gpus: Vec<String>,
318}
319
320impl CodecMonitor {
321    pub fn new() -> Result<Self, IronError> {
322        let mut monitor = Self {
323            codec_caps: Vec::new(),
324            compute_caps: Vec::new(),
325            unmatched_gpus: Vec::new(),
326        };
327        monitor.refresh()?;
328        Ok(monitor)
329    }
330
331    pub fn refresh(&mut self) -> Result<(), IronError> {
332        self.codec_caps.clear();
333        self.compute_caps.clear();
334        self.unmatched_gpus.clear();
335
336        // Detect GPU names for inference
337        let gpu_names = Self::detect_gpu_names();
338
339        // Try direct query first, then fall back to inference
340        #[cfg(target_os = "linux")]
341        self.refresh_linux();
342
343        #[cfg(target_os = "windows")]
344        self.refresh_windows();
345
346        #[cfg(target_os = "macos")]
347        self.refresh_macos();
348
349        // Inference: if no capabilities detected directly, infer from GPU names
350        if self.codec_caps.is_empty() {
351            for name in &gpu_names {
352                let before = self.codec_caps.len();
353                self.infer_from_gpu_name(name);
354                if self.codec_caps.len() == before {
355                    self.unmatched_gpus.push(name.clone());
356                }
357            }
358        }
359
360        // Always infer compute capabilities from GPU names
361        for name in &gpu_names {
362            self.infer_compute_from_gpu(name);
363        }
364
365        Ok(())
366    }
367
368    pub fn capabilities(&self) -> &[CodecCapability] {
369        &self.codec_caps
370    }
371
372    pub fn compute_capabilities(&self) -> &[ComputeCapability] {
373        &self.compute_caps
374    }
375
376    /// GPU names the codec inference could not place. Each carries no codec rows,
377    /// and the ontology reports it as unavailable instead of leaving it out.
378    pub fn unmatched_gpus(&self) -> &[String] {
379        &self.unmatched_gpus
380    }
381
382    /// Check if a specific codec is supported for decode.
383    pub fn can_decode(&self, codec: &VideoCodec) -> bool {
384        self.codec_caps.iter().any(|c| {
385            &c.codec == codec
386                && matches!(c.direction, CodecDirection::Decode | CodecDirection::Both)
387        })
388    }
389
390    /// Check if a specific codec is supported for encode.
391    pub fn can_encode(&self, codec: &VideoCodec) -> bool {
392        self.codec_caps.iter().any(|c| {
393            &c.codec == codec
394                && matches!(c.direction, CodecDirection::Encode | CodecDirection::Both)
395        })
396    }
397
398    /// Get max decode resolution for a codec.
399    pub fn max_decode_resolution(&self, codec: &VideoCodec) -> MaxResolution {
400        self.codec_caps
401            .iter()
402            .filter(|c| {
403                &c.codec == codec
404                    && matches!(c.direction, CodecDirection::Decode | CodecDirection::Both)
405            })
406            // A row with no frame class is `None`, and so is `Unknown`. Neither
407            // may reach `max()`: `Unknown` sorts above every real class in the
408            // derived ordering.
409            .filter_map(|c| c.max_resolution.clone())
410            .filter(|r| *r != MaxResolution::Unknown)
411            .max()
412            .unwrap_or(MaxResolution::Unknown)
413    }
414
415    /// Get estimated TFLOPS (FP32) across all devices. `None` unless every
416    /// device has a figure: a partial sum would read as the machine's total.
417    pub fn total_tflops_fp32(&self) -> Option<f32> {
418        if self.compute_caps.is_empty() {
419            return None;
420        }
421        self.compute_caps
422            .iter()
423            .map(|c| c.estimated_tflops_fp32)
424            .sum()
425    }
426
427    fn detect_gpu_names() -> Vec<String> {
428        let mut names = Vec::new();
429
430        #[cfg(target_os = "linux")]
431        {
432            // Read from /sys/class/drm/card*/device/
433            if let Ok(entries) = std::fs::read_dir("/sys/class/drm") {
434                for entry in entries.flatten() {
435                    let name = entry.file_name().to_string_lossy().to_string();
436                    if name.starts_with("card") && !name.contains('-') {
437                        let label = std::fs::read_to_string(entry.path().join("device/label"))
438                            .or_else(|_| {
439                                std::fs::read_to_string(entry.path().join("device/product_name"))
440                            })
441                            .unwrap_or_default()
442                            .trim()
443                            .to_string();
444                        if !label.is_empty() {
445                            names.push(label);
446                        }
447                    }
448                }
449            }
450
451            // Also try lspci for GPU names
452            if names.is_empty() {
453                if let Ok(output) = std::process::Command::new("lspci")
454                    .args(["-d", "::0300", "-nn"])
455                    .output()
456                {
457                    let text = String::from_utf8(output.stdout).unwrap_or_default();
458                    for line in text.lines() {
459                        if let Some(pos) = line.find(": ") {
460                            names.push(line[pos + 2..].to_string());
461                        }
462                    }
463                }
464            }
465        }
466
467        #[cfg(target_os = "windows")]
468        {
469            if let Ok(output) = std::process::Command::new("powershell")
470                .args([
471                    "-NoProfile",
472                    "-Command",
473                    "Get-CimInstance Win32_VideoController | Select-Object -ExpandProperty Name",
474                ])
475                .output()
476            {
477                let text = String::from_utf8(output.stdout).unwrap_or_default();
478                for line in text.lines() {
479                    let n = line.trim();
480                    if !n.is_empty() {
481                        names.push(n.to_string());
482                    }
483                }
484            }
485        }
486
487        #[cfg(target_os = "macos")]
488        {
489            if let Ok(output) = std::process::Command::new("system_profiler")
490                .args(["SPDisplaysDataType"])
491                .output()
492            {
493                let text = String::from_utf8(output.stdout).unwrap_or_default();
494                for line in text.lines() {
495                    let line = line.trim();
496                    if line.contains("Chipset Model:") {
497                        if let Some(model) = line.split(':').nth(1) {
498                            names.push(model.trim().to_string());
499                        }
500                    }
501                }
502            }
503        }
504
505        names
506    }
507
508    /// Infer codec capabilities from GPU model name.
509    fn infer_from_gpu_name(&mut self, gpu_name: &str) {
510        let lower = gpu_name.to_lowercase();
511
512        // NVIDIA inference
513        if lower.contains("nvidia")
514            || lower.contains("geforce")
515            || lower.contains("quadro")
516            || lower.contains("tesla")
517            || lower.contains("rtx")
518            || lower.contains("gtx")
519        {
520            self.infer_nvidia_codecs(gpu_name);
521        }
522
523        // AMD inference
524        if lower.contains("amd") || lower.contains("radeon") || lower.contains("rx ") {
525            self.infer_amd_codecs(gpu_name);
526        }
527
528        // Intel inference
529        if lower.contains("intel")
530            || lower.contains("uhd")
531            || lower.contains("iris")
532            || lower.contains("arc")
533        {
534            self.infer_intel_codecs(gpu_name, &lower);
535        }
536
537        // Apple inference
538        if lower.contains("apple")
539            || lower.contains("m1")
540            || lower.contains("m2")
541            || lower.contains("m3")
542            || lower.contains("m4")
543        {
544            self.infer_apple_codecs(gpu_name);
545        }
546    }
547
548    /// Push one inferred row. Resolution and bit depth are `Unknown`: the
549    /// per-generation figures these rows used to carry were not taken from a
550    /// vendor matrix, so the reader no longer claims them.
551    fn push_inferred_codec(
552        &mut self,
553        gpu_name: &str,
554        codec: VideoCodec,
555        direction: CodecDirection,
556        engine: &str,
557        confidence: f32,
558    ) {
559        self.codec_caps.push(CodecCapability {
560            device: gpu_name.to_string(),
561            codec,
562            direction,
563            max_resolution: None,
564            max_bit_depth: BitDepth::Unknown,
565            max_fps: None,
566            engine: engine.to_string(),
567            source: CapabilitySource::Inferred,
568            confidence,
569        });
570    }
571
572    fn infer_nvidia_codecs(&mut self, gpu_name: &str) {
573        // A name the model-number rule does not place gets no rows; `refresh`
574        // records it as unmatched. The rule this replaces matched substrings, so
575        // "RTX A4000" was placed in the RTX 40 generation.
576        let Some(generation) = parse_nvidia_model(gpu_name).and_then(|m| m.generation()) else {
577            return;
578        };
579
580        // H.264, H.265, VP9, MPEG-2 and VC-1 across the generations placed above,
581        // per the NVIDIA Video Encode and Decode GPU Support Matrix.
582        for (codec, dir) in [
583            (VideoCodec::H264, CodecDirection::Both),
584            (VideoCodec::H265, CodecDirection::Both),
585            (VideoCodec::VP9, CodecDirection::Decode),
586            (VideoCodec::MPEG2, CodecDirection::Decode),
587            (VideoCodec::VC1, CodecDirection::Decode),
588        ] {
589            self.push_inferred_codec(
590                gpu_name,
591                codec,
592                dir,
593                "NVENC/NVDEC",
594                CONFIDENCE_NVIDIA_BASE_CODECS,
595            );
596        }
597
598        // AV1: Ada decodes and encodes, Ampere decodes only, Turing has neither.
599        match generation {
600            NvidiaGen::Ada => self.push_inferred_codec(
601                gpu_name,
602                VideoCodec::AV1,
603                CodecDirection::Both,
604                "NVENC/NVDEC",
605                CONFIDENCE_NVIDIA_AV1_RTX40,
606            ),
607            NvidiaGen::Ampere => self.push_inferred_codec(
608                gpu_name,
609                VideoCodec::AV1,
610                CodecDirection::Decode,
611                "NVDEC",
612                CONFIDENCE_NVIDIA_AV1_RTX30,
613            ),
614            NvidiaGen::Pascal | NvidiaGen::Turing => {}
615        }
616    }
617
618    fn infer_amd_codecs(&mut self, gpu_name: &str) {
619        // Only the RDNA families are placed, by RX model number. Polaris (RX 500)
620        // and older parts, and APU names with no model number, get no rows. The
621        // rule this replaces read any 6 or 7 in the name as an RDNA generation.
622        let Some(generation) = parse_amd_rx_generation(gpu_name) else {
623            return;
624        };
625
626        // The media engine version is AMD's own naming for each family:
627        // RDNA 1 = VCN 2.0, RDNA 2 = VCN 3.0, RDNA 3 = VCN 4.0.
628        let engine = match generation {
629            AmdGen::Rdna1 => "VCN 2.0",
630            AmdGen::Rdna2 => "VCN 3.0",
631            AmdGen::Rdna3 => "VCN 4.0",
632        };
633        for (codec, dir) in [
634            (VideoCodec::H264, CodecDirection::Both),
635            (VideoCodec::H265, CodecDirection::Both),
636            (VideoCodec::VP9, CodecDirection::Decode),
637        ] {
638            self.push_inferred_codec(gpu_name, codec, dir, engine, CONFIDENCE_AMD_BASE_CODECS);
639        }
640
641        match generation {
642            AmdGen::Rdna1 => {}
643            AmdGen::Rdna2 => self.push_inferred_codec(
644                gpu_name,
645                VideoCodec::AV1,
646                CodecDirection::Decode,
647                engine,
648                CONFIDENCE_AMD_AV1_RDNA2,
649            ),
650            AmdGen::Rdna3 => self.push_inferred_codec(
651                gpu_name,
652                VideoCodec::AV1,
653                CodecDirection::Both,
654                engine,
655                CONFIDENCE_AMD_AV1_RDNA3,
656            ),
657        }
658    }
659
660    fn infer_intel_codecs(&mut self, gpu_name: &str, lower: &str) {
661        // H.264 and H.265 for the Quick Sync names matched here. VP9 is not
662        // emitted: its support depends on the generation, which a name such as
663        // "Intel UHD Graphics" does not carry. The rule this replaces gave every
664        // Intel GPU VP9 at 4K.
665        for codec in [VideoCodec::H264, VideoCodec::H265] {
666            self.push_inferred_codec(
667                gpu_name,
668                codec,
669                CodecDirection::Both,
670                "Quick Sync",
671                CONFIDENCE_INTEL_BASE_CODECS,
672            );
673        }
674
675        if lower.contains("arc") {
676            self.push_inferred_codec(
677                gpu_name,
678                VideoCodec::AV1,
679                CodecDirection::Both,
680                "Xe Media Engine",
681                CONFIDENCE_INTEL_ARC_AV1,
682            );
683        }
684    }
685
686    fn infer_apple_codecs(&mut self, gpu_name: &str) {
687        // No frame class or bit depth is read for these rows, so `max_resolution`
688        // and `max_bit_depth` are `None`. The rows used to name a literal 4K or
689        // 8K class per codec, and a literal 8- or 10-bit depth per codec, which no
690        // platform query reported for this chip.
691        let codecs = vec![
692            (VideoCodec::H264, CodecDirection::Both),
693            (VideoCodec::H265, CodecDirection::Both),
694            (VideoCodec::VP9, CodecDirection::Decode),
695            (VideoCodec::ProRes, CodecDirection::Both),
696        ];
697
698        for (codec, dir) in codecs {
699            self.codec_caps.push(CodecCapability {
700                device: gpu_name.to_string(),
701                codec,
702                direction: dir,
703                max_resolution: None,
704                max_bit_depth: BitDepth::Unknown,
705                max_fps: None,
706                engine: "Apple Media Engine".into(),
707                source: CapabilitySource::Inferred,
708                confidence: CONFIDENCE_APPLE_BASE_CODECS,
709            });
710        }
711
712        // M3+ and M2 Pro/Max/Ultra have AV1 decode
713        let lower = gpu_name.to_lowercase();
714        if lower.contains("m3")
715            || lower.contains("m4")
716            || (lower.contains("m2")
717                && (lower.contains("pro") || lower.contains("max") || lower.contains("ultra")))
718        {
719            self.codec_caps.push(CodecCapability {
720                device: gpu_name.to_string(),
721                codec: VideoCodec::AV1,
722                direction: CodecDirection::Decode,
723                max_resolution: None,
724                // Not read from the chip. The AV1 engine's bit depth is not
725                // queried here, so it is `Unknown`. This used to be a literal
726                // `Bit10`, which the resolver published as a specification.
727                max_bit_depth: BitDepth::Unknown,
728                max_fps: None,
729                engine: "Apple Media Engine".into(),
730                source: CapabilitySource::Inferred,
731                confidence: CONFIDENCE_APPLE_AV1,
732            });
733        }
734    }
735
736    /// Infer compute capabilities from GPU name.
737    fn infer_compute_from_gpu(&mut self, gpu_name: &str) {
738        let lower = gpu_name.to_lowercase();
739
740        if lower.contains("nvidia")
741            || lower.contains("geforce")
742            || lower.contains("rtx")
743            || lower.contains("gtx")
744            || lower.contains("quadro")
745            || lower.contains("tesla")
746        {
747            // The generation fixes the CUDA compute capability and the two feature
748            // flags. The TFLOPS figures are per model, and only for the base models
749            // in `nvidia_tflops`. A name the rules do not place gets no figures.
750            let model = parse_nvidia_model(gpu_name);
751            let generation = model.as_ref().and_then(NvidiaModel::generation);
752            let cuda = generation.map(|g| match g {
753                NvidiaGen::Pascal => "6.1",
754                NvidiaGen::Turing => "7.5",
755                NvidiaGen::Ampere => "8.6",
756                NvidiaGen::Ada => "8.9",
757            });
758            let (tensor, rt) = match (&model, generation) {
759                (Some(m), Some(_)) => {
760                    let rtx = m.line == NvidiaLine::Rtx;
761                    (Some(rtx), Some(rtx))
762                }
763                _ => (None, None),
764            };
765            let (tflops_32, tflops_16) = match model.as_ref().and_then(nvidia_tflops) {
766                Some((fp32, fp16)) => (Some(fp32), fp16),
767                None => (None, None),
768            };
769
770            self.compute_caps.push(ComputeCapability {
771                device: gpu_name.to_string(),
772                cuda_version: cuda.map(String::from),
773                opencl_version: None,
774                vulkan_compute: None,
775                metal_compute: false,
776                direct_compute: None,
777                estimated_tflops_fp32: tflops_32,
778                estimated_tflops_fp16: tflops_16,
779                has_tensor_cores: tensor,
780                has_ray_tracing: rt,
781                source: CapabilitySource::Inferred,
782            });
783        }
784
785        if lower.contains("apple")
786            || lower.contains("m1")
787            || lower.contains("m2")
788            || lower.contains("m3")
789            || lower.contains("m4")
790        {
791            let tflops = if lower.contains("m4") || lower.contains("ultra") {
792                Some(27.0_f32)
793            } else if lower.contains("m3") || lower.contains("max") {
794                Some(14.2)
795            } else if lower.contains("m2") || lower.contains("pro") {
796                Some(6.8)
797            } else if lower.contains("m1") {
798                Some(2.6)
799            } else {
800                None
801            };
802
803            self.compute_caps.push(ComputeCapability {
804                device: gpu_name.to_string(),
805                cuda_version: None,
806                opencl_version: None,
807                vulkan_compute: None,
808                metal_compute: true,
809                direct_compute: None,
810                estimated_tflops_fp32: tflops,
811                estimated_tflops_fp16: tflops.map(|t| t * 2.0),
812                // The Neural Engine is a separate block, not tensor cores in the
813                // GPU, which this used to claim. M1-M4 GPUs have no such units;
814                // later or unrecognised parts are not guessed.
815                has_tensor_cores: ["m1", "m2", "m3", "m4"]
816                    .iter()
817                    .any(|m| lower.contains(m))
818                    .then_some(false),
819                // Ray tracing arrived with M3; M1/M2 are known not to have it.
820                has_ray_tracing: if lower.contains("m3") || lower.contains("m4") {
821                    Some(true)
822                } else if lower.contains("m1") || lower.contains("m2") {
823                    Some(false)
824                } else {
825                    None
826                },
827                source: CapabilitySource::Inferred,
828            });
829        }
830    }
831
832    #[cfg(target_os = "linux")]
833    fn refresh_linux(&mut self) {
834        // Try vainfo for VA-API capabilities
835        if let Ok(output) = std::process::Command::new("vainfo")
836            .args(["--display", "drm"])
837            .output()
838        {
839            let text = String::from_utf8(output.stdout).unwrap_or_default();
840            let device = "VA-API";
841            for line in text.lines() {
842                let line = line.trim();
843                if !line.starts_with("VAProfile") {
844                    continue;
845                }
846                // "VAProfileH264Main            : VAEntrypointVLD"
847                let parts: Vec<&str> = line.split(':').collect();
848                if parts.len() < 2 {
849                    continue;
850                }
851                let profile = parts[0].trim();
852                let entrypoint = parts[1].trim();
853
854                let codec = if profile.contains("H264") {
855                    VideoCodec::H264
856                } else if profile.contains("HEVC") || profile.contains("H265") {
857                    VideoCodec::H265
858                } else if profile.contains("VP9") {
859                    VideoCodec::VP9
860                } else if profile.contains("VP8") {
861                    VideoCodec::VP8
862                } else if profile.contains("AV1") {
863                    VideoCodec::AV1
864                } else if profile.contains("MPEG2") {
865                    VideoCodec::MPEG2
866                } else if profile.contains("JPEG") {
867                    VideoCodec::JPEG
868                } else {
869                    continue;
870                };
871
872                let direction = if entrypoint.contains("VLD") {
873                    CodecDirection::Decode
874                } else if entrypoint.contains("Enc") {
875                    CodecDirection::Encode
876                } else {
877                    continue;
878                };
879
880                self.codec_caps.push(CodecCapability {
881                    device: device.to_string(),
882                    codec,
883                    direction,
884                    // vainfo's profile and entrypoint lines carry no frame size,
885                    // and this reader does not query one. It used to be the
886                    // literal UHD4K on every row.
887                    max_resolution: None,
888                    // The depth follows from the profile name vainfo printed.
889                    // An unrecognised name is `Unknown`, not 8-bit.
890                    max_bit_depth: vaapi_profile_bit_depth(profile),
891                    max_fps: None,
892                    engine: "VA-API".into(),
893                    source: CapabilitySource::DirectQuery,
894                    confidence: CONFIDENCE_VAINFO_QUERY,
895                });
896            }
897        }
898    }
899
900    #[cfg(target_os = "windows")]
901    fn refresh_windows(&mut self) {
902        // Query DXVA capabilities is complex; we rely on inference primarily
903        // But we can check for basic GPU info
904    }
905
906    #[cfg(target_os = "macos")]
907    fn refresh_macos(&mut self) {
908        // macOS: VideoToolbox capabilities are best inferred from chip name
909    }
910}
911
912impl Default for CodecMonitor {
913    fn default() -> Self {
914        Self::new().unwrap_or(Self {
915            codec_caps: Vec::new(),
916            compute_caps: Vec::new(),
917            unmatched_gpus: Vec::new(),
918        })
919    }
920}
921
922impl std::fmt::Display for VideoCodec {
923    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
924        match self {
925            Self::H264 => write!(f, "H.264/AVC"),
926            Self::H265 => write!(f, "H.265/HEVC"),
927            Self::H266 => write!(f, "H.266/VVC"),
928            Self::VP8 => write!(f, "VP8"),
929            Self::VP9 => write!(f, "VP9"),
930            Self::AV1 => write!(f, "AV1"),
931            Self::MPEG2 => write!(f, "MPEG-2"),
932            Self::MPEG4 => write!(f, "MPEG-4"),
933            Self::VC1 => write!(f, "VC-1"),
934            Self::JPEG => write!(f, "JPEG"),
935            Self::ProRes => write!(f, "ProRes"),
936            Self::Other(s) => write!(f, "{}", s),
937        }
938    }
939}
940
941impl std::fmt::Display for MaxResolution {
942    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
943        match self {
944            Self::SD => write!(f, "SD (480p)"),
945            Self::HD => write!(f, "HD (720p)"),
946            Self::FullHD => write!(f, "Full HD (1080p)"),
947            Self::QHD => write!(f, "QHD (1440p)"),
948            Self::UHD4K => write!(f, "4K UHD"),
949            Self::UHD8K => write!(f, "8K UHD"),
950            Self::Unknown => write!(f, "Unknown"),
951        }
952    }
953}
954
955/// Bit depth implied by a vainfo profile name such as `VAProfileHEVCMain10`.
956///
957/// Only names that state the depth, or that are known to be 8-bit only, get a
958/// value. Anything else, such as `VAProfileVP9Profile2` (10-bit) or
959/// `VAProfileAV1Profile0`, is `Unknown`: the name does not say what the engine
960/// supports, and an 8-bit guess would be wrong for those.
961#[cfg(any(target_os = "linux", test))]
962fn vaapi_profile_bit_depth(profile: &str) -> BitDepth {
963    const EIGHT_BIT_ONLY: &[&str] = &[
964        "MPEG2Simple",
965        "MPEG2Main",
966        "H264Baseline",
967        "H264ConstrainedBaseline",
968        "H264Main",
969        "H264High",
970        "HEVCMain",
971        "VP8Version0_3",
972        "VP9Profile0",
973        "JPEGBaseline",
974        "VC1Simple",
975        "VC1Main",
976        "VC1Advanced",
977    ];
978    let name = profile.trim().trim_start_matches("VAProfile");
979    if name.contains("12") {
980        BitDepth::Bit12
981    } else if name.contains("10") {
982        BitDepth::Bit10
983    } else if EIGHT_BIT_ONLY.contains(&name) {
984        BitDepth::Bit8
985    } else {
986        BitDepth::Unknown
987    }
988}
989
990#[cfg(test)]
991mod tests {
992    use super::*;
993
994    #[test]
995    fn vaapi_profile_names_give_only_the_depth_they_state() {
996        let cases = [
997            ("VAProfileMPEG2Simple", BitDepth::Bit8),
998            ("VAProfileMPEG2Main", BitDepth::Bit8),
999            ("VAProfileH264Main", BitDepth::Bit8),
1000            ("VAProfileH264High", BitDepth::Bit8),
1001            ("VAProfileH264High10", BitDepth::Bit10),
1002            ("VAProfileH264ConstrainedBaseline", BitDepth::Bit8),
1003            ("VAProfileHEVCMain", BitDepth::Bit8),
1004            ("VAProfileHEVCMain10", BitDepth::Bit10),
1005            ("VAProfileHEVCMain12", BitDepth::Bit12),
1006            ("VAProfileVP8Version0_3", BitDepth::Bit8),
1007            ("VAProfileVP9Profile0", BitDepth::Bit8),
1008            // VP9 profile 2 is 10-bit, but the name is not read as a depth here.
1009            ("VAProfileVP9Profile2", BitDepth::Unknown),
1010            ("VAProfileAV1Profile0", BitDepth::Unknown),
1011            ("VAProfileJPEGBaseline", BitDepth::Bit8),
1012            ("VAProfileVC1Advanced", BitDepth::Bit8),
1013            ("VAProfileNone", BitDepth::Unknown),
1014        ];
1015        for (name, expected) in cases {
1016            assert_eq!(vaapi_profile_bit_depth(name), expected, "{name}");
1017        }
1018    }
1019
1020    fn decode_row(res: Option<MaxResolution>) -> CodecCapability {
1021        CodecCapability {
1022            device: "VA-API".into(),
1023            codec: VideoCodec::H264,
1024            direction: CodecDirection::Decode,
1025            max_resolution: res,
1026            max_bit_depth: BitDepth::Bit8,
1027            max_fps: None,
1028            engine: "VA-API".into(),
1029            source: CapabilitySource::DirectQuery,
1030            confidence: 1.0,
1031        }
1032    }
1033
1034    /// A VA-API row whose frame size was never read must not win the maximum,
1035    /// and a row with no size at all must not make the answer `Unknown` when a
1036    /// classified row exists.
1037    #[test]
1038    fn test_unclassified_row_does_not_win_max_decode_resolution() {
1039        let monitor = CodecMonitor {
1040            codec_caps: vec![decode_row(None), decode_row(Some(MaxResolution::FullHD))],
1041            compute_caps: Vec::new(),
1042            unmatched_gpus: Vec::new(),
1043        };
1044        assert_eq!(
1045            monitor.max_decode_resolution(&VideoCodec::H264),
1046            MaxResolution::FullHD
1047        );
1048        let only_unknown = CodecMonitor {
1049            codec_caps: vec![decode_row(None)],
1050            compute_caps: Vec::new(),
1051            unmatched_gpus: Vec::new(),
1052        };
1053        assert_eq!(
1054            only_unknown.max_decode_resolution(&VideoCodec::H264),
1055            MaxResolution::Unknown
1056        );
1057    }
1058
1059    #[test]
1060    fn test_codec_monitor_creation() {
1061        let monitor = CodecMonitor::new();
1062        assert!(monitor.is_ok());
1063    }
1064
1065    #[test]
1066    fn test_codec_monitor_default() {
1067        let monitor = CodecMonitor::default();
1068        let _ = monitor.capabilities();
1069        let _ = monitor.compute_capabilities();
1070        let _ = monitor.total_tflops_fp32();
1071    }
1072
1073    #[test]
1074    fn test_nvidia_inference() {
1075        let mut monitor = CodecMonitor {
1076            codec_caps: Vec::new(),
1077            compute_caps: Vec::new(),
1078            unmatched_gpus: Vec::new(),
1079        };
1080        monitor.infer_from_gpu_name("NVIDIA GeForce RTX 4090");
1081        assert!(!monitor.codec_caps.is_empty());
1082        assert!(monitor.can_decode(&VideoCodec::H265));
1083        assert!(monitor.can_encode(&VideoCodec::H264));
1084        assert!(monitor.can_decode(&VideoCodec::AV1));
1085        assert!(monitor.can_encode(&VideoCodec::AV1)); // RTX 40xx
1086    }
1087
1088    #[test]
1089    fn test_compute_inference() {
1090        let mut monitor = CodecMonitor {
1091            codec_caps: Vec::new(),
1092            compute_caps: Vec::new(),
1093            unmatched_gpus: Vec::new(),
1094        };
1095        monitor.infer_compute_from_gpu("NVIDIA GeForce RTX 4090");
1096        assert!(!monitor.compute_caps.is_empty());
1097        assert_eq!(monitor.compute_caps[0].has_tensor_cores, Some(true));
1098        assert_eq!(monitor.compute_caps[0].has_ray_tracing, Some(true));
1099        assert!(matches!(
1100            monitor.compute_caps[0].estimated_tflops_fp32,
1101            Some(t) if t > 50.0
1102        ));
1103    }
1104
1105    #[test]
1106    fn test_compute_unknown_generation_has_no_figures() {
1107        let mut monitor = CodecMonitor {
1108            codec_caps: Vec::new(),
1109            compute_caps: Vec::new(),
1110            unmatched_gpus: Vec::new(),
1111        };
1112        monitor.infer_compute_from_gpu("NVIDIA Quadro Unknown 9000");
1113        assert!(!monitor.compute_caps.is_empty());
1114        assert_eq!(monitor.compute_caps[0].estimated_tflops_fp32, None);
1115        assert_eq!(monitor.compute_caps[0].estimated_tflops_fp16, None);
1116        assert_eq!(monitor.compute_caps[0].cuda_version, None);
1117        assert_eq!(monitor.compute_caps[0].has_tensor_cores, None);
1118        assert_eq!(monitor.compute_caps[0].has_ray_tracing, None);
1119        assert_eq!(monitor.total_tflops_fp32(), None);
1120    }
1121
1122    fn empty_monitor() -> CodecMonitor {
1123        CodecMonitor {
1124            codec_caps: Vec::new(),
1125            compute_caps: Vec::new(),
1126            unmatched_gpus: Vec::new(),
1127        }
1128    }
1129
1130    #[test]
1131    fn test_parse_nvidia_model_names() {
1132        let ti = parse_nvidia_model("NVIDIA GeForce RTX 3090 Ti").unwrap();
1133        assert_eq!(ti.line, NvidiaLine::Rtx);
1134        assert_eq!(ti.number, "3090");
1135        assert_eq!(ti.suffix.as_deref(), Some("ti"));
1136        assert_eq!(ti.generation(), Some(NvidiaGen::Ampere));
1137
1138        let sup = parse_nvidia_model("NVIDIA GeForce RTX 4070 SUPER").unwrap();
1139        assert_eq!(sup.number, "4070");
1140        assert_eq!(sup.suffix.as_deref(), Some("super"));
1141        assert_eq!(sup.generation(), Some(NvidiaGen::Ada));
1142
1143        let a4000 = parse_nvidia_model("NVIDIA RTX A4000").unwrap();
1144        assert_eq!(a4000.number, "a4000");
1145        assert_eq!(a4000.suffix, None);
1146        assert_eq!(a4000.generation(), Some(NvidiaGen::Ampere));
1147
1148        let gtx = parse_nvidia_model("NVIDIA GeForce GTX 1660 Ti").unwrap();
1149        assert_eq!(gtx.line, NvidiaLine::Gtx);
1150        assert_eq!(gtx.generation(), Some(NvidiaGen::Turing));
1151
1152        assert_eq!(parse_nvidia_model("AMD Radeon RX 570"), None);
1153        assert_eq!(parse_nvidia_model("NVIDIA Quadro Unknown 9000"), None);
1154    }
1155
1156    #[test]
1157    fn test_parse_amd_rx_generation() {
1158        // Polaris (three digits) and an APU name are not placed.
1159        assert_eq!(parse_amd_rx_generation("AMD Radeon RX 570"), None);
1160        assert_eq!(parse_amd_rx_generation("AMD Radeon(TM) Graphics"), None);
1161        assert_eq!(
1162            parse_amd_rx_generation("AMD Radeon RX 5700 XT"),
1163            Some(AmdGen::Rdna1)
1164        );
1165        assert_eq!(
1166            parse_amd_rx_generation("AMD Radeon RX 7900 XTX"),
1167            Some(AmdGen::Rdna3)
1168        );
1169    }
1170
1171    #[test]
1172    fn test_nvidia_substring_does_not_place_a_model() {
1173        // "RTX A4000" contains "40" and "rtx", but it is Ampere, not RTX 40.
1174        let mut monitor = empty_monitor();
1175        monitor.infer_from_gpu_name("NVIDIA RTX A4000");
1176        assert!(!monitor.can_encode(&VideoCodec::AV1));
1177        assert!(monitor.can_decode(&VideoCodec::AV1));
1178    }
1179
1180    #[test]
1181    fn test_amd_polaris_and_apu_get_no_rows() {
1182        let mut monitor = empty_monitor();
1183        monitor.infer_from_gpu_name("AMD Radeon RX 570");
1184        monitor.infer_from_gpu_name("AMD Radeon(TM) Graphics");
1185        assert!(monitor.capabilities().is_empty());
1186    }
1187
1188    #[test]
1189    fn test_amd_rdna_generation_from_model_number() {
1190        let mut rdna1 = empty_monitor();
1191        rdna1.infer_from_gpu_name("AMD Radeon RX 5700 XT");
1192        assert!(rdna1.can_encode(&VideoCodec::H264));
1193        assert!(!rdna1.can_decode(&VideoCodec::AV1));
1194
1195        let mut rdna3 = empty_monitor();
1196        rdna3.infer_from_gpu_name("AMD Radeon RX 7900 XTX");
1197        assert!(rdna3.can_encode(&VideoCodec::AV1));
1198        assert!(rdna3.capabilities().iter().all(|c| c.engine == "VCN 4.0"));
1199    }
1200
1201    #[test]
1202    fn test_intel_has_no_vp9_row() {
1203        let mut monitor = empty_monitor();
1204        monitor.infer_from_gpu_name("Intel(R) UHD Graphics 770");
1205        assert!(!monitor
1206            .capabilities()
1207            .iter()
1208            .any(|c| c.codec == VideoCodec::VP9));
1209        assert!(monitor.can_decode(&VideoCodec::H265));
1210    }
1211
1212    #[test]
1213    fn test_nvidia_ampere_has_no_av1_encode() {
1214        let mut monitor = empty_monitor();
1215        monitor.infer_from_gpu_name("NVIDIA GeForce RTX 3090 Ti");
1216        assert!(monitor.can_decode(&VideoCodec::AV1));
1217        assert!(!monitor.can_encode(&VideoCodec::AV1));
1218        assert_eq!(
1219            monitor.max_decode_resolution(&VideoCodec::H264),
1220            MaxResolution::Unknown
1221        );
1222    }
1223
1224    #[test]
1225    fn test_compute_suffix_model_gets_no_tflops() {
1226        let mut monitor = empty_monitor();
1227        monitor.infer_compute_from_gpu("NVIDIA GeForce RTX 3090 Ti");
1228        let c = &monitor.compute_caps[0];
1229        assert_eq!(c.cuda_version.as_deref(), Some("8.6"));
1230        assert_eq!(c.has_tensor_cores, Some(true));
1231        assert_eq!(c.estimated_tflops_fp32, None);
1232
1233        monitor.infer_compute_from_gpu("NVIDIA GeForce RTX 4070 SUPER");
1234        assert_eq!(monitor.compute_caps[1].estimated_tflops_fp32, None);
1235    }
1236
1237    #[test]
1238    fn test_compute_base_model_and_gtx16_flags() {
1239        let mut monitor = empty_monitor();
1240        monitor.infer_compute_from_gpu("NVIDIA GeForce RTX 3090");
1241        assert_eq!(monitor.compute_caps[0].estimated_tflops_fp32, Some(35.6));
1242
1243        let mut gtx = empty_monitor();
1244        gtx.infer_compute_from_gpu("NVIDIA GeForce GTX 1660 Ti");
1245        let c = &gtx.compute_caps[0];
1246        assert_eq!(c.cuda_version.as_deref(), Some("7.5"));
1247        assert_eq!(c.has_tensor_cores, Some(false));
1248        assert_eq!(c.has_ray_tracing, Some(false));
1249    }
1250
1251    #[test]
1252    fn test_apple_rows_name_no_frame_class() {
1253        // The Apple table is inferred from the chip name, which fixes the codecs
1254        // and not a frame size. No row may carry a resolution it did not read.
1255        let mut monitor = empty_monitor();
1256        monitor.infer_apple_codecs("Apple M3 Max");
1257        assert!(!monitor.codec_caps.is_empty());
1258        assert!(monitor
1259            .codec_caps
1260            .iter()
1261            .all(|c| c.max_resolution.is_none()));
1262        // Nor a bit depth: the chip name does not fix one, so none is published.
1263        assert!(monitor
1264            .codec_caps
1265            .iter()
1266            .all(|c| c.max_bit_depth == BitDepth::Unknown));
1267        assert!(monitor
1268            .codec_caps
1269            .iter()
1270            .any(|c| c.codec == VideoCodec::AV1));
1271        assert_eq!(
1272            monitor.max_decode_resolution(&VideoCodec::H264),
1273            MaxResolution::Unknown
1274        );
1275    }
1276
1277    #[test]
1278    fn test_serialization() {
1279        let cap = CodecCapability {
1280            device: "Test GPU".into(),
1281            codec: VideoCodec::AV1,
1282            direction: CodecDirection::Decode,
1283            max_resolution: Some(MaxResolution::UHD8K),
1284            max_bit_depth: BitDepth::Bit10,
1285            max_fps: Some(60),
1286            engine: "NVDEC".into(),
1287            source: CapabilitySource::Inferred,
1288            confidence: 0.85,
1289        };
1290        let json = serde_json::to_string(&cap).unwrap();
1291        assert!(json.contains("AV1"));
1292        let _: CodecCapability = serde_json::from_str(&json).unwrap();
1293    }
1294}