# GPU Codec Detection

This document provides comprehensive information about GPU codec detection in the MPV.Rocks Installer project.

## Overview

The GPU codec detection system identifies supported video codecs based on GPU model, vendor, and platform. This information is displayed in the System Information page and used for hardware acceleration configuration.

## Table of Contents

- [Detection Methods](#detection-methods)
- [GPU Database](#gpu-database)
- [Codec Mapping](#codec-mapping)
- [Platform-Specific Detection](#platform-specific-detection)
- [Lookup Algorithm](#lookup-algorithm)

---

## Detection Methods

### Platform Detection Priority

**Linux:**
1. **glxinfo** - Best format (Mesa + model + driver + codename)
2. **vulkaninfo** - Multiple GPUs, good format
3. **lspci** - Existing fallback
4. **sysfs DRM** - Last resort

**Windows:**
- **PowerShell** - GPU detection via `Get-WmiObject Win32_VideoController`
- **CSV lookup** - Uses GPU model info for codec support

**macOS:**
- **CGO (Primary)** - VideoToolbox framework `VTIsHardwareDecodeSupported()`
- **Model-based (Fallback)** - Apple Silicon specifications (for cross-compilation)

### Detection Command Examples

**Linux - glxinfo:**
```bash
glxinfo -B | grep "Device"
# Output: Device: AMD Radeon RX 7900 XTX (radeonsi, navi31, LLVM 21.1.6, DRM 3.64, 6.18.6-2-cachyos) (0x744c)
# Extracts: "AMD Radeon RX 7900 XTX"
```

**Linux - vulkaninfo:**
```bash
vulkaninfo --summary | grep deviceName
# Output: deviceName = AMD Radeon RX 7900 XTX (RADV NAVI31)
# Extracts: "AMD Radeon RX 7900 XTX"
# CPU iGPUs filtered when only one GPU detected
```

**Windows - PowerShell:**
```powershell
Get-WmiObject Win32_VideoController | Select-Object Name, DriverVersion
# Output: NVIDIA GeForce RTX 4090 30.0.15.2872
```

---

## GPU Database

### Data Structure

```go
type GPUModelEntry struct {
    ModelNames   []string  // Specific model names: "Radeon RX 7900 XTX"
    SeriesNames  []string  // Series matches: "RX 7900", "RTX 40" (no standalone numbers)
    Codename     string    // Primary codename: "Navi 31", "GK104"
    AltCodenames []string  // Additional codenames: ["AD103", "AD104"]
    Architecture string    // For reference/debugging
    Codecs       []string  // MPV-format codec list
}
```

### Database Entries

**AMD Radeon (16 entries):**

| Codename | Architecture | Model Examples | Supported Codecs |
|-----------|---------------|---------------|-------------------|
| Polaris 10 | GCN 4.0 | RX 480, RX 470 | avc, hevc, vp8, vc1, mpeg2 |
| Polaris 11 | GCN 4.0 | RX 560, RX 550 | avc, hevc, vp8, vc1, mpeg2 |
| Vega 10 | GCN 5.0 | RX Vega 64, Radeon VII | avc, hevc, vp8, vc1, mpeg2 |
| Vega 20 | GCN 5.0 | RX Vega 56 | avc, hevc, vp8, vc1, mpeg2 |
| Navi 10 | RDNA 1 | RX 5700, RX 5500 | avc, hevc, vp9, vp8, vc1, mpeg2 |
| Navi 14 | RDNA 1 | RX 5500 XT | avc, hevc, vp9, vp8, vc1, mpeg2 |
| Navi 21 | RDNA 2 | RX 6800 XT, RX 6700 XT | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |
| Navi 22 | RDNA 2 | RX 6700 | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |
| Navi 23 | RDNA 2 | RX 6600 | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |
| Navi 24 | RDNA 2 | RX 6500 XT | avc, hevc, vp9, vp8, vc1, mpeg2 (NO AV1) |
| Navi 31 | RDNA 3 | RX 7900 XTX, RX 7900 XT | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |
| Navi 32 | RDNA 3 | RX 7800 XT | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |
| Navi 33 | RDNA 3 | RX 7700 XT | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |
| Navi 48 | RDNA 4 | RX 9070 XT | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |
| Navi 44 | RDNA 4 | RX 9060 | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |

**Intel (11 entries):**

| Gen | Architecture | Model Examples | Supported Codecs |
|-----|---------------|---------------|-------------------|
| Gen 6 | Sandy Bridge | HD 2000, HD 3000 | avc, vc1, mpeg2 |
| Gen 7 | Ivy Bridge | HD 2500, HD 4000 | avc, vc1, mpeg2 |
| Gen 7.5 | Haswell | HD 4200-5200 | avc, vc1, mpeg2 |
| Gen 8 | Broadwell | HD 5300-6300 | avc, vc1, mpeg2 |
| Gen 9 | Skylake | HD 500 series | avc, vc1, mpeg2 |
| Gen 9.5 | Kaby Lake, Coffee Lake | UHD 600 series | avc, vc1, mpeg2 |
| Gen 11 | Ice Lake | Iris Plus Graphics | avc, vc1, mpeg2 |
| Gen 12.1 | Tiger Lake, Alder Lake, Raptor Lake | UHD 700, Iris Xe (with AV1) | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |
| Xe-HPG | Alchemist, Meteor Lake | Arc A-Series (with AV1) | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |
| Xe2-LPG | Lunar Lake | Core Ultra (with VVC) | avc, hevc, vp9, vp8, vc1, mpeg2, vvc |
| Xe2-HPG | Battlemage | Arc B-Series (with AV1) | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |

**NVIDIA (10 entries):**

| Codename | Architecture | Model Examples | Supported Codecs |
|-----------|---------------|---------------|-------------------|
| Kepler | GK104-208 | GTX 600/700/Titan | avc, vc1, mpeg2 (NO HEVC/VP9) |
| Maxwell 1st | GM107-108 | GTX 750/750 Ti | avc, vc1, mpeg2 (NO HEVC/VP9) |
| Maxwell 2nd | GM200-206 | GTX 950/980/Titan X | avc, hevc, vp9, vc1, mpeg2 (950 has HEVC/VP9) |
| Pascal | GP102-108 | GTX 1000/GT 1030 | avc, hevc, vp9, vp8, vc1, mpeg2 |
| Volta | GV100 | Titan V | avc, hevc, vp9, vp8, vc1, mpeg2 |
| Turing | TU102-117 | RTX 20/GTX 16 | avc, hevc, vp9, vp8, vc1, mpeg2 (NO AV1) |
| Ampere | GA102-107 | RTX 30 | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |
| Ada Lovelace | AD102-107 | RTX 40 | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |
| Blackwell | GB202-205 | RTX 50 | avc, hevc, vp9, vp8, vc1, mpeg2, av1 |

---

## Codec Mapping

### CSV to MPV Format

| CSV Format | MPV Format |
|------------|-------------|
| H.264 | avc |
| HEVC | hevc |
| VP9 | vp9 |
| AV1 | av1 |
| VP8 | vp8 |
| VC-1 | vc1 |
| MPEG-2 | mpeg2 |
| VVC | vvc |
| ProRes | prores |

### Conversion Function

```go
func convertCodecsToMPVFormat(csvCodecs []string) []string {
    mpvCodecs := make([]string, 0, len(csvCodecs))
    
    codecMap := map[string]string{
        "H.264":  "avc",
        "HEVC":  "hevc",
        "VP9":  "vp9",
        "AV1":  "av1",
        "VP8":  "vp8",
        "VC-1": "vc1",
        "MPEG-2": "mpeg2",
        "VVC": "vvc",
        "ProRes": "prores",
    }
    
    for _, codec := range csvCodecs {
        if mpvCodec, exists := codecMap[codec]; exists {
            mpvCodecs = append(mpvCodecs, mpvCodec)
        }
    }
    
    return mpvCodecs
}
```

---

## Platform-Specific Detection

### Linux Detection

**Priority Order:**
1. glxinfo (best format)
2. vulkaninfo (multiple GPUs)
3. lspci (existing fallback)
4. sysfs DRM (last resort)

**CPU iGPU Filtering:**
- Only filter CPU iGPUs (Ryzen, Core, etc.) when exactly one GPU detected
- Prevents false negatives on dual-GPU systems
- Uses heuristic patterns in GPU names

**Parser Functions:**
- `parseGlxInfo()` - Extracts GPU model from glxinfo output
- `parseVulkanInfo()` - Extracts GPU model from vulkaninfo output
- `parseVainfo()` - Returns codec list from VAAPI
- `parseVDPAUInfo()` - Returns codec list from VDPAU

### Windows Detection

**Method:**
1. Detect GPU model and vendor via PowerShell
2. Use CSV lookup for codec support
3. Returns ["unknown"] if no match found

**PowerShell Command:**
```powershell
Get-WmiObject Win32_VideoController | Select-Object Name, DriverVersion
```

### macOS Detection

**CGO Detection (Primary):**
- Uses `VTIsHardwareDecodeSupported()` from VideoToolbox framework
- FourCC codes checked: av01, vp09, hvc1, apcn, avc1
- Available when building directly on macOS with CGO

**Model-Based Fallback:**
- Used when CGO unavailable (cross-compilation)
- Apple Silicon specifications:
  - M1/M1 Pro/M1 Max/M1 Ultra: HEVC, AVC, ProRes
  - M2/M2 Pro/M2 Max/M2 Ultra: HEVC, AVC, ProRes
  - M3/M3 Pro/M3 Max/M3 Ultra: HEVC, AVC, AV1, ProRes
  - M4/M4 Pro/M4 Max/M4 Ultra: HEVC, AVC, AV1, ProRes
  - Unknown/Future: AV1, HEVC, AVC, ProRes (optimistic)

**Build Tags:**
- `gpu_darwin_cgo.go` - `//go:build darwin && cgo`
- `gpu_darwin_fallback.go` - `//go:build darwin && !cgo`

---

## Lookup Algorithm

### Multi-Level Matching

4-priority matching in `lookupGPUCodecs()`:

**Priority 1: Exact Model Name Match**
- "Radeon RX 7900 XTX" matches exact entry in `ModelNames` array
- Highest priority match

**Priority 2: Series Name Match**
- "RX 7900" matches series-level entry in `SeriesNames` array
- No standalone numbers (e.g., "7900" alone - must be "RX 7900")
- Medium priority match

**Priority 3: Primary Codename Match**
- "Navi 31" matches primary codename field
- Good for Linux detections that report codename
- Low priority match

**Priority 4: Alternative Codename Match**
- "AD102" matches entry in `AltCodenames` array
- Useful for GPUs with multiple codename variants
- Lowest priority match

### Brand-Specific with Fallback

**`lookupGPUCodecsWithFallback()` Logic:**
1. Check brand-specific data first (AMD/Intel/NVIDIA)
2. Falls back to searching all vendor data if brand detection fails
- Critical for Linux where brand detection may be unreliable
- Returns ["unknown"] if no match found

**Fallback Example:**
```
Input: "NVIDIA GeForce RTX 4090" (detected as "Unknown" brand)
Priority 1: No exact match in NVIDIA data
Priority 2: No series match in NVIDIA data
Priority 3: No codename match in NVIDIA data
Priority 4: "AD102" found in NVIDIA data
Result: ["avc", "hevc", "vp9", "vp8", "vc1", "mpeg2", "av1"]
```

---

## Hardware Acceleration Methods

### Platform-Specific Options

**Windows:**
- **auto** - Automatic selection
- **auto-safe** - Safe auto-detection with fallback (NVIDIA only)
- **nvdec** - NVIDIA Video Decode (NVIDIA only)
- **nvdec-copy** - NVIDIA Video Decode with copy (NVIDIA only)
- **d3d11va** - Direct3D 11 Video Acceleration
- **d3d11va-copy** - Direct3D 11 Video Acceleration with copy
- **vulkan** - Vulkan video decoding
- **vulkan-copy** - Vulkan video decoding with copy
- **no** - Disable hardware decoding

**Linux:**
- **auto** - Automatic selection
- **nvdec** - NVIDIA Video Decode (NVIDIA only)
- **nvdec-copy** - NVIDIA Video Decode with copy (NVIDIA only)
- **vaapi** - Video Acceleration API (AMD/Intel only)
- **vaapi-copy** - Video Acceleration API with copy (AMD/Intel only)
- **vulkan** - Vulkan video decoding
- **vulkan-copy** - Vulkan video decoding with copy
- **drm** - Direct Rendering Manager (AMD/Intel only)
- **drm-copy** - Direct Rendering Manager with copy (AMD/Intel only)
- **no** - Disable hardware decoding

**macOS:**
- **auto** - Automatic selection
- **videotoolbox** - Apple VideoToolbox
- **videotoolbox-copy** - Apple VideoToolbox with copy
- **no** - Disable hardware decoding

### GPU-Specific Filtering

**HWA methods are filtered by:**
1. Operating system (Windows/Linux/macOS)
2. GPU vendor (AMD/Intel/NVIDIA/Apple)
3. GPU capabilities (codec support)

**Example:**
- NVIDIA on Windows: Shows nvdec, nvdec-copy options
- AMD on Windows: Shows vaapi, vaapi-copy options are hidden
- Intel on Linux: Shows vaapi, vaapi-copy options
- NVIDIA on Linux: Shows nvdec, nvdec-copy options

---

## Code Location

### Package: `pkg/platform/gpu.go`

**Key Functions:**
- `DetectCodecs(platform PlatformInfo) ([]string, error)` - Main detection entry point
- `detectCodecsLinux()` - Linux-specific codec detection
- `detectCodecsWindows()` - Windows-specific codec detection
- `detectCodecsMacOS()` - macOS-specific codec detection
- `parseCodecSupportLinux()` - Parse Linux codec support output
- `parseCodecSupportWindows()` - Parse Windows GPU info
- `lookupGPUCodecs()` - 4-priority matching algorithm
- `lookupGPUCodecsWithFallback()` - Brand-specific with all-vendor fallback
- `convertCodecsToMPVFormat()` - CSV to MPV format conversion

**Files:**
- `pkg/platform/gpu.go` - Main GPU detection logic (~500 lines)
- `pkg/platform/gpu_darwin_cgo.go` - CGO-based VideoToolbox detection (~65 lines)
- `pkg/platform/gpu_darwin_fallback.go` - Model-based detection (~78 lines)

### Constant Definitions

**Valid HWA Methods (from `pkg/platform/gpu.go`):**
```go
var validHWAMethods = []string{
    "auto",
    "auto-safe",
    "nvdec", "nvdec-copy",
    "d3d11va", "d3d11va-copy",
    "vaapi", "vaapi-copy",
    "vulkan", "vulkan-copy",
    "videotoolbox", "videotoolbox-copy",
    "drm", "drm-copy",
    "no",
}
```

---

## Testing GPU Detection

### Manual Testing Procedures

**Windows:**
```powershell
# Check GPU detection
.\mpv-manager.exe --debug

# Verify GPU model and vendor displayed correctly in System Information
# Verify codec list is accurate
# Test with various GPUs (NVIDIA, AMD, Intel)
```

**Linux:**
```bash
# Check GPU detection
./mpv-manager --debug

# Test with different GPUs:
# - AMD Radeon RX 6000 series (should show AV1)
# - NVIDIA RTX 40 series (should show AV1)
# - Intel Arc series (should show AV1)
# - AMD RX 6500 XT (should NOT show AV1)
```

**macOS:**
```bash
# Check GPU detection
./mpv-manager --debug

# Test with Apple Silicon:
# - M1/M2 (should show HEVC, AVC, ProRes)
# - M3/M4 (should show HEVC, AVC, AV1, ProRes)
# Test with Intel Macs (should show HEVC, AVC, no AV1)
```

### Expected Results

**AMD RX 6500 XT:**
- ❌ AV1 support (Navi 24 vs Navi 21-23)
- ✅ HEVC support
- ✅ VP9 support
- ✅ VP8 support
- ✅ AVC support

**Intel HD Graphics (older):**
- ❌ AV1 support (Gen 12.0 and earlier)
- ❌ HEVC support (Gen 12.0 and earlier)
- ✅ AVC support
- ✅ VC-1 support
- ✅ MPEG-2 support

**NVIDIA RTX 40:**
- ✅ AV1 support
- ✅ HEVC support
- ✅ VP9 support
- ✅ VP8 support
- ✅ AVC support
- ✅ VC-1 support
- ✅ MPEG-2 support

**NVIDIA GTX 950:**
- ✅ HEVC support (Maxwell 2nd gen variant)
- ✅ VP9 support (Maxwell 2nd gen variant)
- ❌ AV1 support (Pascal architecture)

---

## Troubleshooting

### Common Issues

**Issue: GPU not detected**
- **Cause:** Detection command failed or not installed
- **Solution:** Install detection tools (vainfo, vdpauinfo, glxinfo, vulkaninfo)
- **Linux:** `sudo apt install mesa-utils mesa-dri-utils vulkan-tools`
- **Enable debug mode:** `./mpv-manager --debug`

**Issue: Codec list shows ["unknown"]**
- **Cause:** GPU model not in database or brand not detected
- **Solution:**
  1. Check GPU model name in System Information page
  2. Verify brand detection (AMD/Intel/NVIDIA)
  3. Add GPU model to database if new or missing
  4. Report issue with GPU model and detection logs

**Issue: Wrong codec list displayed**
- **Cause:** Incorrect GPU model detected or database lookup error
- **Solution:**
  1. Verify GPU detection command output
  2. Check model name parsing logic
  3. Verify codename matching
  4. Test with different detection tools

**Issue: Missing AV1 support on supported GPU**
- **Cause:** GPU database entry missing or incorrect
- **Solution:**
  1. Verify GPU supports AV1 (check vendor documentation)
  2. Check database entry has correct codec list
  3. Verify GPU model matches correct database entry
  4. Add or update database entry if needed

### Debug Mode

**Enable debug logging:**
```bash
./mpv-manager --debug
```

**Check log file:**
```bash
# Linux/macOS
cat ~/.config/mpv/mpv-manager.log

# Windows (portable config)
cat ~/mpv/portable_config/mpv-manager.log

# Windows (fallback)
cat ./mpv-manager.log
```

**Look for GPU detection logs:**
```
[DEBUG] Starting GPU detection...
[DEBUG] Detected GPU model: AMD Radeon RX 7900 XTX
[DEBUG] Detected GPU brand: AMD
[DEBUG] Detected GPU vendor: AMD
[DEBUG] Lookup result: Found in AMD database (Navi 31)
[DEBUG] Supported codecs: avc, hevc, vp9, vp8, vc1, mpeg2, av1
[DEBUG] Codec detection complete
```

---

## Future Enhancements

### Database Expansion

- Add more GPU models as they're discovered
- Expand codename coverage for obscure GPUs
- Add more Intel integrated graphics entries
- Add more AMD APU entries

### Detection Improvements

- Improve GPU name parsing for exotic GPUs
- Add support for multi-GPU systems with different vendors
- Add better CPU iGPU detection and filtering
- Add support for external GPUs (Thunderbolt, USB)

### Performance Improvements

- Cache lookup results for multiple GPU checks
- Lazy load GPU database (load on first access)
- Parallelize detection for multiple GPUs

### Feature Enhancements

- Add DirectX feature detection (Windows)
- Add Vulkan feature level detection
- Add OpenCL support detection
- Add video memory amount detection
- Add driver version tracking for NVIDIA

---

## Related Documentation

For more information about GPU detection, see:
- [Session Summaries](docs/SESSION_SUMMARIES.md) - Session 2026-01-28: GPU Codec Lookup System Refactoring
- [Troubleshooting](docs/TROUBLESHOOTING.md) - GPU Detection Issues
- [Architecture](docs/ARCHITECTURE.md) - Platform Detection

---

## Quick Reference

### GPU Detection Flow

```
Start → Detect OS/Platform
   ↓
Detect GPU (platform-specific method)
   ↓
Parse GPU model and vendor
   ↓
Lookup codecs in database (multi-level matching)
   ↓
Return codec list (MPV format)
```

### Codec Display Format

In System Information page, codecs are displayed as:
- Individual badges: `[AV1] [HEVC] [VP9]`
- Colored by support level:
  - **Green:** Latest codecs (AV1, HEVC)
  - **Blue:** Standard codecs (AVC, VP9, VP8)
  - **Gray:** Legacy codecs (VC-1, MPEG-2)

### Hardware Acceleration

HWA methods are filtered based on:
- Operating system support
- GPU vendor (NVIDIA/AMD/Intel/Apple)
- Codec support detected via GPU database

For example:
- NVIDIA on Windows with AV1 support → nvdec, nvdec-copy options shown
- AMD on Windows with AV1 support → vaapi, vaapi-copy options hidden (Windows doesn't support)
- Intel on Linux without AV1 → vaapi, vaapi-copy options shown

---

## Conclusion

This GPU codec detection system provides accurate codec information across all major GPU vendors and platforms. The multi-level lookup algorithm with brand fallback ensures broad coverage and accurate results.

For issues or feature requests, please report with:
- GPU model and vendor
- Detected codec list
- Expected codec list
- Platform and OS version
- Debug logs (if available)
