1use crate::error::IronError;
27use serde::{Deserialize, Serialize};
28
29#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub enum CodecDirection {
49 Decode,
50 Encode,
51 Both,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
56pub enum MaxResolution {
57 SD, HD, FullHD, QHD, UHD4K, UHD8K, Unknown,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub enum BitDepth {
69 Bit8,
70 Bit10,
71 Bit12,
72 Unknown,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub enum CapabilitySource {
78 DirectQuery,
80 Inferred,
82 Manual,
84}
85
86#[cfg(target_os = "linux")]
88const CONFIDENCE_VAINFO_QUERY: f32 = 1.0;
89const CONFIDENCE_NVIDIA_BASE_CODECS: f32 = 0.85;
91const CONFIDENCE_NVIDIA_AV1_RTX40: f32 = 0.9;
93const CONFIDENCE_NVIDIA_AV1_RTX30: f32 = 0.85;
95const CONFIDENCE_AMD_BASE_CODECS: f32 = 0.8;
97const CONFIDENCE_AMD_AV1_RDNA3: f32 = 0.85;
99const CONFIDENCE_AMD_AV1_RDNA2: f32 = 0.8;
101const CONFIDENCE_INTEL_BASE_CODECS: f32 = 0.8;
103const CONFIDENCE_INTEL_ARC_AV1: f32 = 0.85;
105const CONFIDENCE_APPLE_BASE_CODECS: f32 = 0.9;
107const CONFIDENCE_APPLE_AV1: f32 = 0.85;
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct CodecCapability {
113 pub device: String,
115 pub codec: VideoCodec,
117 pub direction: CodecDirection,
119 pub max_resolution: Option<MaxResolution>,
123 pub max_bit_depth: BitDepth,
125 pub max_fps: Option<u32>,
133 pub engine: String,
135 pub source: CapabilitySource,
137 pub confidence: f32,
142}
143
144#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct ComputeCapability {
147 pub device: String,
149 pub cuda_version: Option<String>,
152 pub opencl_version: Option<String>,
156 pub vulkan_compute: Option<bool>,
159 pub metal_compute: bool,
161 pub direct_compute: Option<String>,
164 pub estimated_tflops_fp32: Option<f32>,
166 pub estimated_tflops_fp16: Option<f32>,
168 pub has_tensor_cores: Option<bool>,
170 pub has_ray_tracing: Option<bool>,
172 pub source: CapabilitySource,
174}
175
176fn all_digits(s: &str) -> bool {
178 !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184enum NvidiaLine {
185 Gtx,
186 Rtx,
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191enum NvidiaGen {
192 Pascal,
193 Turing,
194 Ampere,
195 Ada,
196}
197
198#[derive(Debug, Clone, PartialEq, Eq)]
201struct NvidiaModel {
202 line: NvidiaLine,
203 number: String,
205 suffix: Option<String>,
207}
208
209impl NvidiaModel {
210 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 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
231fn 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
263fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284enum AmdGen {
285 Rdna1,
286 Rdna2,
287 Rdna3,
288}
289
290fn 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 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
312pub struct CodecMonitor {
314 codec_caps: Vec<CodecCapability>,
315 compute_caps: Vec<ComputeCapability>,
316 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 let gpu_names = Self::detect_gpu_names();
338
339 #[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 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 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 pub fn unmatched_gpus(&self) -> &[String] {
379 &self.unmatched_gpus
380 }
381
382 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 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 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 .filter_map(|c| c.max_resolution.clone())
410 .filter(|r| *r != MaxResolution::Unknown)
411 .max()
412 .unwrap_or(MaxResolution::Unknown)
413 }
414
415 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 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 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 fn infer_from_gpu_name(&mut self, gpu_name: &str) {
510 let lower = gpu_name.to_lowercase();
511
512 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 if lower.contains("amd") || lower.contains("radeon") || lower.contains("rx ") {
525 self.infer_amd_codecs(gpu_name);
526 }
527
528 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 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 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 let Some(generation) = parse_nvidia_model(gpu_name).and_then(|m| m.generation()) else {
577 return;
578 };
579
580 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 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 let Some(generation) = parse_amd_rx_generation(gpu_name) else {
623 return;
624 };
625
626 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 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 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 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 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 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 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 has_tensor_cores: ["m1", "m2", "m3", "m4"]
816 .iter()
817 .any(|m| lower.contains(m))
818 .then_some(false),
819 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 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 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 max_resolution: None,
888 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 }
905
906 #[cfg(target_os = "macos")]
907 fn refresh_macos(&mut self) {
908 }
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#[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 ("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 #[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)); }
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 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 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 = >x.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 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 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}