use crate::error::IronError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum VideoCodec {
H264,
H265,
H266,
VP8,
VP9,
AV1,
MPEG2,
MPEG4,
VC1,
JPEG,
ProRes,
Other(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CodecDirection {
Decode,
Encode,
Both,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum MaxResolution {
SD, HD, FullHD, QHD, UHD4K, UHD8K, Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BitDepth {
Bit8,
Bit10,
Bit12,
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CapabilitySource {
DirectQuery,
Inferred,
Manual,
}
#[cfg(target_os = "linux")]
const CONFIDENCE_VAINFO_QUERY: f32 = 1.0;
const CONFIDENCE_NVIDIA_BASE_CODECS: f32 = 0.85;
const CONFIDENCE_NVIDIA_AV1_RTX40: f32 = 0.9;
const CONFIDENCE_NVIDIA_AV1_RTX30: f32 = 0.85;
const CONFIDENCE_AMD_BASE_CODECS: f32 = 0.8;
const CONFIDENCE_AMD_AV1_RDNA3: f32 = 0.85;
const CONFIDENCE_AMD_AV1_RDNA2: f32 = 0.8;
const CONFIDENCE_INTEL_BASE_CODECS: f32 = 0.8;
const CONFIDENCE_INTEL_ARC_AV1: f32 = 0.85;
const CONFIDENCE_APPLE_BASE_CODECS: f32 = 0.9;
const CONFIDENCE_APPLE_AV1: f32 = 0.85;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodecCapability {
pub device: String,
pub codec: VideoCodec,
pub direction: CodecDirection,
pub max_resolution: Option<MaxResolution>,
pub max_bit_depth: BitDepth,
pub max_fps: Option<u32>,
pub engine: String,
pub source: CapabilitySource,
pub confidence: f32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComputeCapability {
pub device: String,
pub cuda_version: Option<String>,
pub opencl_version: Option<String>,
pub vulkan_compute: Option<bool>,
pub metal_compute: bool,
pub direct_compute: Option<String>,
pub estimated_tflops_fp32: Option<f32>,
pub estimated_tflops_fp16: Option<f32>,
pub has_tensor_cores: Option<bool>,
pub has_ray_tracing: Option<bool>,
pub source: CapabilitySource,
}
fn all_digits(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NvidiaLine {
Gtx,
Rtx,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NvidiaGen {
Pascal,
Turing,
Ampere,
Ada,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct NvidiaModel {
line: NvidiaLine,
number: String,
suffix: Option<String>,
}
impl NvidiaModel {
fn generation(&self) -> Option<NvidiaGen> {
if self.suffix.as_deref() == Some("ada") {
return Some(NvidiaGen::Ada);
}
if self.line == NvidiaLine::Rtx && self.number.starts_with('a') {
return Some(NvidiaGen::Ampere);
}
match (self.line, self.number.get(..2)?) {
(NvidiaLine::Gtx, "10") => Some(NvidiaGen::Pascal),
(NvidiaLine::Gtx, "16") => Some(NvidiaGen::Turing),
(NvidiaLine::Rtx, "20") => Some(NvidiaGen::Turing),
(NvidiaLine::Rtx, "30") => Some(NvidiaGen::Ampere),
(NvidiaLine::Rtx, "40") => Some(NvidiaGen::Ada),
_ => None,
}
}
}
fn parse_nvidia_model(name: &str) -> Option<NvidiaModel> {
let lower = name.to_lowercase();
let tokens: Vec<&str> = lower.split_whitespace().collect();
let (idx, line) = tokens.iter().enumerate().find_map(|(i, t)| match *t {
"rtx" => Some((i, NvidiaLine::Rtx)),
"gtx" => Some((i, NvidiaLine::Gtx)),
_ => None,
})?;
let number = *tokens.get(idx + 1)?;
let geforce = (3..=4).contains(&number.len()) && all_digits(number);
let a_series = line == NvidiaLine::Rtx
&& number.len() == 5
&& number.starts_with('a')
&& all_digits(&number[1..]);
if !geforce && !a_series {
return None;
}
let suffix = tokens
.get(idx + 2)
.filter(|s| s.bytes().all(|b| b.is_ascii_alphabetic()))
.map(|s| s.to_string());
Some(NvidiaModel {
line,
number: number.to_string(),
suffix,
})
}
fn nvidia_tflops(model: &NvidiaModel) -> Option<(f32, Option<f32>)> {
if model.suffix.is_some() {
return None;
}
match (model.line, model.number.as_str()) {
(NvidiaLine::Rtx, "4090") => Some((82.6, Some(165.2))),
(NvidiaLine::Rtx, "4080") => Some((48.7, Some(97.5))),
(NvidiaLine::Rtx, "4070") => Some((29.1, Some(58.3))),
(NvidiaLine::Rtx, "3090") => Some((35.6, Some(71.2))),
(NvidiaLine::Rtx, "3080") => Some((29.8, Some(59.6))),
(NvidiaLine::Rtx, "2080") => Some((14.2, Some(28.4))),
(NvidiaLine::Gtx, "1080") => Some((8.9, None)),
_ => None,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AmdGen {
Rdna1,
Rdna2,
Rdna3,
}
fn parse_amd_rx_generation(name: &str) -> Option<AmdGen> {
let lower = name.to_lowercase();
let tokens: Vec<&str> = lower.split_whitespace().collect();
let idx = tokens.iter().position(|t| *t == "rx")?;
let number = *tokens.get(idx + 1)?;
let digits = number.strip_suffix('m').unwrap_or(number);
if digits.len() != 4 || !all_digits(digits) {
return None;
}
match digits.as_bytes()[0] {
b'5' => Some(AmdGen::Rdna1),
b'6' => Some(AmdGen::Rdna2),
b'7' => Some(AmdGen::Rdna3),
_ => None,
}
}
pub struct CodecMonitor {
codec_caps: Vec<CodecCapability>,
compute_caps: Vec<ComputeCapability>,
unmatched_gpus: Vec<String>,
}
impl CodecMonitor {
pub fn new() -> Result<Self, IronError> {
let mut monitor = Self {
codec_caps: Vec::new(),
compute_caps: Vec::new(),
unmatched_gpus: Vec::new(),
};
monitor.refresh()?;
Ok(monitor)
}
pub fn refresh(&mut self) -> Result<(), IronError> {
self.codec_caps.clear();
self.compute_caps.clear();
self.unmatched_gpus.clear();
let gpu_names = Self::detect_gpu_names();
#[cfg(target_os = "linux")]
self.refresh_linux();
#[cfg(target_os = "windows")]
self.refresh_windows();
#[cfg(target_os = "macos")]
self.refresh_macos();
if self.codec_caps.is_empty() {
for name in &gpu_names {
let before = self.codec_caps.len();
self.infer_from_gpu_name(name);
if self.codec_caps.len() == before {
self.unmatched_gpus.push(name.clone());
}
}
}
for name in &gpu_names {
self.infer_compute_from_gpu(name);
}
Ok(())
}
pub fn capabilities(&self) -> &[CodecCapability] {
&self.codec_caps
}
pub fn compute_capabilities(&self) -> &[ComputeCapability] {
&self.compute_caps
}
pub fn unmatched_gpus(&self) -> &[String] {
&self.unmatched_gpus
}
pub fn can_decode(&self, codec: &VideoCodec) -> bool {
self.codec_caps.iter().any(|c| {
&c.codec == codec
&& matches!(c.direction, CodecDirection::Decode | CodecDirection::Both)
})
}
pub fn can_encode(&self, codec: &VideoCodec) -> bool {
self.codec_caps.iter().any(|c| {
&c.codec == codec
&& matches!(c.direction, CodecDirection::Encode | CodecDirection::Both)
})
}
pub fn max_decode_resolution(&self, codec: &VideoCodec) -> MaxResolution {
self.codec_caps
.iter()
.filter(|c| {
&c.codec == codec
&& matches!(c.direction, CodecDirection::Decode | CodecDirection::Both)
})
.filter_map(|c| c.max_resolution.clone())
.filter(|r| *r != MaxResolution::Unknown)
.max()
.unwrap_or(MaxResolution::Unknown)
}
pub fn total_tflops_fp32(&self) -> Option<f32> {
if self.compute_caps.is_empty() {
return None;
}
self.compute_caps
.iter()
.map(|c| c.estimated_tflops_fp32)
.sum()
}
fn detect_gpu_names() -> Vec<String> {
let mut names = Vec::new();
#[cfg(target_os = "linux")]
{
if let Ok(entries) = std::fs::read_dir("/sys/class/drm") {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with("card") && !name.contains('-') {
let label = std::fs::read_to_string(entry.path().join("device/label"))
.or_else(|_| {
std::fs::read_to_string(entry.path().join("device/product_name"))
})
.unwrap_or_default()
.trim()
.to_string();
if !label.is_empty() {
names.push(label);
}
}
}
}
if names.is_empty() {
if let Ok(output) = std::process::Command::new("lspci")
.args(["-d", "::0300", "-nn"])
.output()
{
let text = String::from_utf8(output.stdout).unwrap_or_default();
for line in text.lines() {
if let Some(pos) = line.find(": ") {
names.push(line[pos + 2..].to_string());
}
}
}
}
}
#[cfg(target_os = "windows")]
{
if let Ok(output) = std::process::Command::new("powershell")
.args([
"-NoProfile",
"-Command",
"Get-CimInstance Win32_VideoController | Select-Object -ExpandProperty Name",
])
.output()
{
let text = String::from_utf8(output.stdout).unwrap_or_default();
for line in text.lines() {
let n = line.trim();
if !n.is_empty() {
names.push(n.to_string());
}
}
}
}
#[cfg(target_os = "macos")]
{
if let Ok(output) = std::process::Command::new("system_profiler")
.args(["SPDisplaysDataType"])
.output()
{
let text = String::from_utf8(output.stdout).unwrap_or_default();
for line in text.lines() {
let line = line.trim();
if line.contains("Chipset Model:") {
if let Some(model) = line.split(':').nth(1) {
names.push(model.trim().to_string());
}
}
}
}
}
names
}
fn infer_from_gpu_name(&mut self, gpu_name: &str) {
let lower = gpu_name.to_lowercase();
if lower.contains("nvidia")
|| lower.contains("geforce")
|| lower.contains("quadro")
|| lower.contains("tesla")
|| lower.contains("rtx")
|| lower.contains("gtx")
{
self.infer_nvidia_codecs(gpu_name);
}
if lower.contains("amd") || lower.contains("radeon") || lower.contains("rx ") {
self.infer_amd_codecs(gpu_name);
}
if lower.contains("intel")
|| lower.contains("uhd")
|| lower.contains("iris")
|| lower.contains("arc")
{
self.infer_intel_codecs(gpu_name, &lower);
}
if lower.contains("apple")
|| lower.contains("m1")
|| lower.contains("m2")
|| lower.contains("m3")
|| lower.contains("m4")
{
self.infer_apple_codecs(gpu_name);
}
}
fn push_inferred_codec(
&mut self,
gpu_name: &str,
codec: VideoCodec,
direction: CodecDirection,
engine: &str,
confidence: f32,
) {
self.codec_caps.push(CodecCapability {
device: gpu_name.to_string(),
codec,
direction,
max_resolution: None,
max_bit_depth: BitDepth::Unknown,
max_fps: None,
engine: engine.to_string(),
source: CapabilitySource::Inferred,
confidence,
});
}
fn infer_nvidia_codecs(&mut self, gpu_name: &str) {
let Some(generation) = parse_nvidia_model(gpu_name).and_then(|m| m.generation()) else {
return;
};
for (codec, dir) in [
(VideoCodec::H264, CodecDirection::Both),
(VideoCodec::H265, CodecDirection::Both),
(VideoCodec::VP9, CodecDirection::Decode),
(VideoCodec::MPEG2, CodecDirection::Decode),
(VideoCodec::VC1, CodecDirection::Decode),
] {
self.push_inferred_codec(
gpu_name,
codec,
dir,
"NVENC/NVDEC",
CONFIDENCE_NVIDIA_BASE_CODECS,
);
}
match generation {
NvidiaGen::Ada => self.push_inferred_codec(
gpu_name,
VideoCodec::AV1,
CodecDirection::Both,
"NVENC/NVDEC",
CONFIDENCE_NVIDIA_AV1_RTX40,
),
NvidiaGen::Ampere => self.push_inferred_codec(
gpu_name,
VideoCodec::AV1,
CodecDirection::Decode,
"NVDEC",
CONFIDENCE_NVIDIA_AV1_RTX30,
),
NvidiaGen::Pascal | NvidiaGen::Turing => {}
}
}
fn infer_amd_codecs(&mut self, gpu_name: &str) {
let Some(generation) = parse_amd_rx_generation(gpu_name) else {
return;
};
let engine = match generation {
AmdGen::Rdna1 => "VCN 2.0",
AmdGen::Rdna2 => "VCN 3.0",
AmdGen::Rdna3 => "VCN 4.0",
};
for (codec, dir) in [
(VideoCodec::H264, CodecDirection::Both),
(VideoCodec::H265, CodecDirection::Both),
(VideoCodec::VP9, CodecDirection::Decode),
] {
self.push_inferred_codec(gpu_name, codec, dir, engine, CONFIDENCE_AMD_BASE_CODECS);
}
match generation {
AmdGen::Rdna1 => {}
AmdGen::Rdna2 => self.push_inferred_codec(
gpu_name,
VideoCodec::AV1,
CodecDirection::Decode,
engine,
CONFIDENCE_AMD_AV1_RDNA2,
),
AmdGen::Rdna3 => self.push_inferred_codec(
gpu_name,
VideoCodec::AV1,
CodecDirection::Both,
engine,
CONFIDENCE_AMD_AV1_RDNA3,
),
}
}
fn infer_intel_codecs(&mut self, gpu_name: &str, lower: &str) {
for codec in [VideoCodec::H264, VideoCodec::H265] {
self.push_inferred_codec(
gpu_name,
codec,
CodecDirection::Both,
"Quick Sync",
CONFIDENCE_INTEL_BASE_CODECS,
);
}
if lower.contains("arc") {
self.push_inferred_codec(
gpu_name,
VideoCodec::AV1,
CodecDirection::Both,
"Xe Media Engine",
CONFIDENCE_INTEL_ARC_AV1,
);
}
}
fn infer_apple_codecs(&mut self, gpu_name: &str) {
let codecs = vec![
(VideoCodec::H264, CodecDirection::Both),
(VideoCodec::H265, CodecDirection::Both),
(VideoCodec::VP9, CodecDirection::Decode),
(VideoCodec::ProRes, CodecDirection::Both),
];
for (codec, dir) in codecs {
self.codec_caps.push(CodecCapability {
device: gpu_name.to_string(),
codec,
direction: dir,
max_resolution: None,
max_bit_depth: BitDepth::Unknown,
max_fps: None,
engine: "Apple Media Engine".into(),
source: CapabilitySource::Inferred,
confidence: CONFIDENCE_APPLE_BASE_CODECS,
});
}
let lower = gpu_name.to_lowercase();
if lower.contains("m3")
|| lower.contains("m4")
|| (lower.contains("m2")
&& (lower.contains("pro") || lower.contains("max") || lower.contains("ultra")))
{
self.codec_caps.push(CodecCapability {
device: gpu_name.to_string(),
codec: VideoCodec::AV1,
direction: CodecDirection::Decode,
max_resolution: None,
max_bit_depth: BitDepth::Unknown,
max_fps: None,
engine: "Apple Media Engine".into(),
source: CapabilitySource::Inferred,
confidence: CONFIDENCE_APPLE_AV1,
});
}
}
fn infer_compute_from_gpu(&mut self, gpu_name: &str) {
let lower = gpu_name.to_lowercase();
if lower.contains("nvidia")
|| lower.contains("geforce")
|| lower.contains("rtx")
|| lower.contains("gtx")
|| lower.contains("quadro")
|| lower.contains("tesla")
{
let model = parse_nvidia_model(gpu_name);
let generation = model.as_ref().and_then(NvidiaModel::generation);
let cuda = generation.map(|g| match g {
NvidiaGen::Pascal => "6.1",
NvidiaGen::Turing => "7.5",
NvidiaGen::Ampere => "8.6",
NvidiaGen::Ada => "8.9",
});
let (tensor, rt) = match (&model, generation) {
(Some(m), Some(_)) => {
let rtx = m.line == NvidiaLine::Rtx;
(Some(rtx), Some(rtx))
}
_ => (None, None),
};
let (tflops_32, tflops_16) = match model.as_ref().and_then(nvidia_tflops) {
Some((fp32, fp16)) => (Some(fp32), fp16),
None => (None, None),
};
self.compute_caps.push(ComputeCapability {
device: gpu_name.to_string(),
cuda_version: cuda.map(String::from),
opencl_version: None,
vulkan_compute: None,
metal_compute: false,
direct_compute: None,
estimated_tflops_fp32: tflops_32,
estimated_tflops_fp16: tflops_16,
has_tensor_cores: tensor,
has_ray_tracing: rt,
source: CapabilitySource::Inferred,
});
}
if lower.contains("apple")
|| lower.contains("m1")
|| lower.contains("m2")
|| lower.contains("m3")
|| lower.contains("m4")
{
let tflops = if lower.contains("m4") || lower.contains("ultra") {
Some(27.0_f32)
} else if lower.contains("m3") || lower.contains("max") {
Some(14.2)
} else if lower.contains("m2") || lower.contains("pro") {
Some(6.8)
} else if lower.contains("m1") {
Some(2.6)
} else {
None
};
self.compute_caps.push(ComputeCapability {
device: gpu_name.to_string(),
cuda_version: None,
opencl_version: None,
vulkan_compute: None,
metal_compute: true,
direct_compute: None,
estimated_tflops_fp32: tflops,
estimated_tflops_fp16: tflops.map(|t| t * 2.0),
has_tensor_cores: ["m1", "m2", "m3", "m4"]
.iter()
.any(|m| lower.contains(m))
.then_some(false),
has_ray_tracing: if lower.contains("m3") || lower.contains("m4") {
Some(true)
} else if lower.contains("m1") || lower.contains("m2") {
Some(false)
} else {
None
},
source: CapabilitySource::Inferred,
});
}
}
#[cfg(target_os = "linux")]
fn refresh_linux(&mut self) {
if let Ok(output) = std::process::Command::new("vainfo")
.args(["--display", "drm"])
.output()
{
let text = String::from_utf8(output.stdout).unwrap_or_default();
let device = "VA-API";
for line in text.lines() {
let line = line.trim();
if !line.starts_with("VAProfile") {
continue;
}
let parts: Vec<&str> = line.split(':').collect();
if parts.len() < 2 {
continue;
}
let profile = parts[0].trim();
let entrypoint = parts[1].trim();
let codec = if profile.contains("H264") {
VideoCodec::H264
} else if profile.contains("HEVC") || profile.contains("H265") {
VideoCodec::H265
} else if profile.contains("VP9") {
VideoCodec::VP9
} else if profile.contains("VP8") {
VideoCodec::VP8
} else if profile.contains("AV1") {
VideoCodec::AV1
} else if profile.contains("MPEG2") {
VideoCodec::MPEG2
} else if profile.contains("JPEG") {
VideoCodec::JPEG
} else {
continue;
};
let direction = if entrypoint.contains("VLD") {
CodecDirection::Decode
} else if entrypoint.contains("Enc") {
CodecDirection::Encode
} else {
continue;
};
self.codec_caps.push(CodecCapability {
device: device.to_string(),
codec,
direction,
max_resolution: None,
max_bit_depth: vaapi_profile_bit_depth(profile),
max_fps: None,
engine: "VA-API".into(),
source: CapabilitySource::DirectQuery,
confidence: CONFIDENCE_VAINFO_QUERY,
});
}
}
}
#[cfg(target_os = "windows")]
fn refresh_windows(&mut self) {
}
#[cfg(target_os = "macos")]
fn refresh_macos(&mut self) {
}
}
impl Default for CodecMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self {
codec_caps: Vec::new(),
compute_caps: Vec::new(),
unmatched_gpus: Vec::new(),
})
}
}
impl std::fmt::Display for VideoCodec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::H264 => write!(f, "H.264/AVC"),
Self::H265 => write!(f, "H.265/HEVC"),
Self::H266 => write!(f, "H.266/VVC"),
Self::VP8 => write!(f, "VP8"),
Self::VP9 => write!(f, "VP9"),
Self::AV1 => write!(f, "AV1"),
Self::MPEG2 => write!(f, "MPEG-2"),
Self::MPEG4 => write!(f, "MPEG-4"),
Self::VC1 => write!(f, "VC-1"),
Self::JPEG => write!(f, "JPEG"),
Self::ProRes => write!(f, "ProRes"),
Self::Other(s) => write!(f, "{}", s),
}
}
}
impl std::fmt::Display for MaxResolution {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SD => write!(f, "SD (480p)"),
Self::HD => write!(f, "HD (720p)"),
Self::FullHD => write!(f, "Full HD (1080p)"),
Self::QHD => write!(f, "QHD (1440p)"),
Self::UHD4K => write!(f, "4K UHD"),
Self::UHD8K => write!(f, "8K UHD"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
#[cfg(any(target_os = "linux", test))]
fn vaapi_profile_bit_depth(profile: &str) -> BitDepth {
const EIGHT_BIT_ONLY: &[&str] = &[
"MPEG2Simple",
"MPEG2Main",
"H264Baseline",
"H264ConstrainedBaseline",
"H264Main",
"H264High",
"HEVCMain",
"VP8Version0_3",
"VP9Profile0",
"JPEGBaseline",
"VC1Simple",
"VC1Main",
"VC1Advanced",
];
let name = profile.trim().trim_start_matches("VAProfile");
if name.contains("12") {
BitDepth::Bit12
} else if name.contains("10") {
BitDepth::Bit10
} else if EIGHT_BIT_ONLY.contains(&name) {
BitDepth::Bit8
} else {
BitDepth::Unknown
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vaapi_profile_names_give_only_the_depth_they_state() {
let cases = [
("VAProfileMPEG2Simple", BitDepth::Bit8),
("VAProfileMPEG2Main", BitDepth::Bit8),
("VAProfileH264Main", BitDepth::Bit8),
("VAProfileH264High", BitDepth::Bit8),
("VAProfileH264High10", BitDepth::Bit10),
("VAProfileH264ConstrainedBaseline", BitDepth::Bit8),
("VAProfileHEVCMain", BitDepth::Bit8),
("VAProfileHEVCMain10", BitDepth::Bit10),
("VAProfileHEVCMain12", BitDepth::Bit12),
("VAProfileVP8Version0_3", BitDepth::Bit8),
("VAProfileVP9Profile0", BitDepth::Bit8),
("VAProfileVP9Profile2", BitDepth::Unknown),
("VAProfileAV1Profile0", BitDepth::Unknown),
("VAProfileJPEGBaseline", BitDepth::Bit8),
("VAProfileVC1Advanced", BitDepth::Bit8),
("VAProfileNone", BitDepth::Unknown),
];
for (name, expected) in cases {
assert_eq!(vaapi_profile_bit_depth(name), expected, "{name}");
}
}
fn decode_row(res: Option<MaxResolution>) -> CodecCapability {
CodecCapability {
device: "VA-API".into(),
codec: VideoCodec::H264,
direction: CodecDirection::Decode,
max_resolution: res,
max_bit_depth: BitDepth::Bit8,
max_fps: None,
engine: "VA-API".into(),
source: CapabilitySource::DirectQuery,
confidence: 1.0,
}
}
#[test]
fn test_unclassified_row_does_not_win_max_decode_resolution() {
let monitor = CodecMonitor {
codec_caps: vec![decode_row(None), decode_row(Some(MaxResolution::FullHD))],
compute_caps: Vec::new(),
unmatched_gpus: Vec::new(),
};
assert_eq!(
monitor.max_decode_resolution(&VideoCodec::H264),
MaxResolution::FullHD
);
let only_unknown = CodecMonitor {
codec_caps: vec![decode_row(None)],
compute_caps: Vec::new(),
unmatched_gpus: Vec::new(),
};
assert_eq!(
only_unknown.max_decode_resolution(&VideoCodec::H264),
MaxResolution::Unknown
);
}
#[test]
fn test_codec_monitor_creation() {
let monitor = CodecMonitor::new();
assert!(monitor.is_ok());
}
#[test]
fn test_codec_monitor_default() {
let monitor = CodecMonitor::default();
let _ = monitor.capabilities();
let _ = monitor.compute_capabilities();
let _ = monitor.total_tflops_fp32();
}
#[test]
fn test_nvidia_inference() {
let mut monitor = CodecMonitor {
codec_caps: Vec::new(),
compute_caps: Vec::new(),
unmatched_gpus: Vec::new(),
};
monitor.infer_from_gpu_name("NVIDIA GeForce RTX 4090");
assert!(!monitor.codec_caps.is_empty());
assert!(monitor.can_decode(&VideoCodec::H265));
assert!(monitor.can_encode(&VideoCodec::H264));
assert!(monitor.can_decode(&VideoCodec::AV1));
assert!(monitor.can_encode(&VideoCodec::AV1)); }
#[test]
fn test_compute_inference() {
let mut monitor = CodecMonitor {
codec_caps: Vec::new(),
compute_caps: Vec::new(),
unmatched_gpus: Vec::new(),
};
monitor.infer_compute_from_gpu("NVIDIA GeForce RTX 4090");
assert!(!monitor.compute_caps.is_empty());
assert_eq!(monitor.compute_caps[0].has_tensor_cores, Some(true));
assert_eq!(monitor.compute_caps[0].has_ray_tracing, Some(true));
assert!(matches!(
monitor.compute_caps[0].estimated_tflops_fp32,
Some(t) if t > 50.0
));
}
#[test]
fn test_compute_unknown_generation_has_no_figures() {
let mut monitor = CodecMonitor {
codec_caps: Vec::new(),
compute_caps: Vec::new(),
unmatched_gpus: Vec::new(),
};
monitor.infer_compute_from_gpu("NVIDIA Quadro Unknown 9000");
assert!(!monitor.compute_caps.is_empty());
assert_eq!(monitor.compute_caps[0].estimated_tflops_fp32, None);
assert_eq!(monitor.compute_caps[0].estimated_tflops_fp16, None);
assert_eq!(monitor.compute_caps[0].cuda_version, None);
assert_eq!(monitor.compute_caps[0].has_tensor_cores, None);
assert_eq!(monitor.compute_caps[0].has_ray_tracing, None);
assert_eq!(monitor.total_tflops_fp32(), None);
}
fn empty_monitor() -> CodecMonitor {
CodecMonitor {
codec_caps: Vec::new(),
compute_caps: Vec::new(),
unmatched_gpus: Vec::new(),
}
}
#[test]
fn test_parse_nvidia_model_names() {
let ti = parse_nvidia_model("NVIDIA GeForce RTX 3090 Ti").unwrap();
assert_eq!(ti.line, NvidiaLine::Rtx);
assert_eq!(ti.number, "3090");
assert_eq!(ti.suffix.as_deref(), Some("ti"));
assert_eq!(ti.generation(), Some(NvidiaGen::Ampere));
let sup = parse_nvidia_model("NVIDIA GeForce RTX 4070 SUPER").unwrap();
assert_eq!(sup.number, "4070");
assert_eq!(sup.suffix.as_deref(), Some("super"));
assert_eq!(sup.generation(), Some(NvidiaGen::Ada));
let a4000 = parse_nvidia_model("NVIDIA RTX A4000").unwrap();
assert_eq!(a4000.number, "a4000");
assert_eq!(a4000.suffix, None);
assert_eq!(a4000.generation(), Some(NvidiaGen::Ampere));
let gtx = parse_nvidia_model("NVIDIA GeForce GTX 1660 Ti").unwrap();
assert_eq!(gtx.line, NvidiaLine::Gtx);
assert_eq!(gtx.generation(), Some(NvidiaGen::Turing));
assert_eq!(parse_nvidia_model("AMD Radeon RX 570"), None);
assert_eq!(parse_nvidia_model("NVIDIA Quadro Unknown 9000"), None);
}
#[test]
fn test_parse_amd_rx_generation() {
assert_eq!(parse_amd_rx_generation("AMD Radeon RX 570"), None);
assert_eq!(parse_amd_rx_generation("AMD Radeon(TM) Graphics"), None);
assert_eq!(
parse_amd_rx_generation("AMD Radeon RX 5700 XT"),
Some(AmdGen::Rdna1)
);
assert_eq!(
parse_amd_rx_generation("AMD Radeon RX 7900 XTX"),
Some(AmdGen::Rdna3)
);
}
#[test]
fn test_nvidia_substring_does_not_place_a_model() {
let mut monitor = empty_monitor();
monitor.infer_from_gpu_name("NVIDIA RTX A4000");
assert!(!monitor.can_encode(&VideoCodec::AV1));
assert!(monitor.can_decode(&VideoCodec::AV1));
}
#[test]
fn test_amd_polaris_and_apu_get_no_rows() {
let mut monitor = empty_monitor();
monitor.infer_from_gpu_name("AMD Radeon RX 570");
monitor.infer_from_gpu_name("AMD Radeon(TM) Graphics");
assert!(monitor.capabilities().is_empty());
}
#[test]
fn test_amd_rdna_generation_from_model_number() {
let mut rdna1 = empty_monitor();
rdna1.infer_from_gpu_name("AMD Radeon RX 5700 XT");
assert!(rdna1.can_encode(&VideoCodec::H264));
assert!(!rdna1.can_decode(&VideoCodec::AV1));
let mut rdna3 = empty_monitor();
rdna3.infer_from_gpu_name("AMD Radeon RX 7900 XTX");
assert!(rdna3.can_encode(&VideoCodec::AV1));
assert!(rdna3.capabilities().iter().all(|c| c.engine == "VCN 4.0"));
}
#[test]
fn test_intel_has_no_vp9_row() {
let mut monitor = empty_monitor();
monitor.infer_from_gpu_name("Intel(R) UHD Graphics 770");
assert!(!monitor
.capabilities()
.iter()
.any(|c| c.codec == VideoCodec::VP9));
assert!(monitor.can_decode(&VideoCodec::H265));
}
#[test]
fn test_nvidia_ampere_has_no_av1_encode() {
let mut monitor = empty_monitor();
monitor.infer_from_gpu_name("NVIDIA GeForce RTX 3090 Ti");
assert!(monitor.can_decode(&VideoCodec::AV1));
assert!(!monitor.can_encode(&VideoCodec::AV1));
assert_eq!(
monitor.max_decode_resolution(&VideoCodec::H264),
MaxResolution::Unknown
);
}
#[test]
fn test_compute_suffix_model_gets_no_tflops() {
let mut monitor = empty_monitor();
monitor.infer_compute_from_gpu("NVIDIA GeForce RTX 3090 Ti");
let c = &monitor.compute_caps[0];
assert_eq!(c.cuda_version.as_deref(), Some("8.6"));
assert_eq!(c.has_tensor_cores, Some(true));
assert_eq!(c.estimated_tflops_fp32, None);
monitor.infer_compute_from_gpu("NVIDIA GeForce RTX 4070 SUPER");
assert_eq!(monitor.compute_caps[1].estimated_tflops_fp32, None);
}
#[test]
fn test_compute_base_model_and_gtx16_flags() {
let mut monitor = empty_monitor();
monitor.infer_compute_from_gpu("NVIDIA GeForce RTX 3090");
assert_eq!(monitor.compute_caps[0].estimated_tflops_fp32, Some(35.6));
let mut gtx = empty_monitor();
gtx.infer_compute_from_gpu("NVIDIA GeForce GTX 1660 Ti");
let c = >x.compute_caps[0];
assert_eq!(c.cuda_version.as_deref(), Some("7.5"));
assert_eq!(c.has_tensor_cores, Some(false));
assert_eq!(c.has_ray_tracing, Some(false));
}
#[test]
fn test_apple_rows_name_no_frame_class() {
let mut monitor = empty_monitor();
monitor.infer_apple_codecs("Apple M3 Max");
assert!(!monitor.codec_caps.is_empty());
assert!(monitor
.codec_caps
.iter()
.all(|c| c.max_resolution.is_none()));
assert!(monitor
.codec_caps
.iter()
.all(|c| c.max_bit_depth == BitDepth::Unknown));
assert!(monitor
.codec_caps
.iter()
.any(|c| c.codec == VideoCodec::AV1));
assert_eq!(
monitor.max_decode_resolution(&VideoCodec::H264),
MaxResolution::Unknown
);
}
#[test]
fn test_serialization() {
let cap = CodecCapability {
device: "Test GPU".into(),
codec: VideoCodec::AV1,
direction: CodecDirection::Decode,
max_resolution: Some(MaxResolution::UHD8K),
max_bit_depth: BitDepth::Bit10,
max_fps: Some(60),
engine: "NVDEC".into(),
source: CapabilitySource::Inferred,
confidence: 0.85,
};
let json = serde_json::to_string(&cap).unwrap();
assert!(json.contains("AV1"));
let _: CodecCapability = serde_json::from_str(&json).unwrap();
}
}