disclady 0.4.0

Pure Rust library and CLI utility for optical and storage disc image heuristics, inspection, and format detection (CD, DVD, GDI, Hard Disk, LaserDisc, CHD).
Documentation
//! Core types and descriptors for optical disc image inspection.

use std::fmt;
use std::path::PathBuf;

/// The primary media categories recognized by the heuristics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DiscType {
    /// Compact Disc image (e.g. CD-ROM, CD-DA, CD-XA, Video CD, PS1, Saturn, Sega CD).
    Cd,
    /// Digital Versatile Disc image (e.g. DVD-ROM, DVD-Video, PS2 DVD, Xbox, GameCube, Wii).
    Dvd,
    /// Dreamcast Gigabyte Disc image (GD-ROM structured dump).
    Gdi,
    /// Raw Hard Disk image (e.g. MBR, GPT, Arcade raw IDE dump, 512 bytes/sector).
    HardDisk,
    /// LaserDisc video and audio image (e.g. MAME AVI capture with YUY2/UYVY).
    LaserDisc,
    /// Unrecognized format or non-media image.
    Unknown,
}

impl DiscType {
    /// Returns true if the disc is recognized as any known media format.
    pub fn is_known(&self) -> bool {
        !matches!(self, DiscType::Unknown)
    }
}

impl fmt::Display for DiscType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DiscType::Cd => write!(f, "CD"),
            DiscType::Dvd => write!(f, "DVD"),
            DiscType::Gdi => write!(f, "GDI"),
            DiscType::HardDisk => write!(f, "Hard Disk"),
            DiscType::LaserDisc => write!(f, "LaserDisc"),
            DiscType::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Level of confidence for a heuristic detection outcome.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Confidence {
    Low,
    Medium,
    High,
    Definitive,
}

impl fmt::Display for Confidence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Confidence::Low => write!(f, "Low"),
            Confidence::Medium => write!(f, "Medium"),
            Confidence::High => write!(f, "High"),
            Confidence::Definitive => write!(f, "Definitive"),
        }
    }
}

/// Specific gaming or multimedia platform identified on the disc.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Platform {
    PlayStation1,
    PlayStation2,
    PlayStationPortable,
    Dreamcast,
    SegaSaturn,
    MegaCd,
    ThreeDo,
    AmigaCd32,
    PcEngineCd,
    PcFx,
    NeoGeoCd,
    PhilipsCdi,
    Xbox,
    Xbox360,
    GameCube,
    Wii,
    DvdVideo,
    DvdAudio,
    StandardIso,
    ArcadeHardDisk,
    PcHardDisk,
    LaserDiscArcade,
    Generic,
}

impl fmt::Display for Platform {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Platform::PlayStation1 => write!(f, "Sony PlayStation"),
            Platform::PlayStation2 => write!(f, "Sony PlayStation 2"),
            Platform::PlayStationPortable => write!(f, "Sony PlayStation Portable"),
            Platform::Dreamcast => write!(f, "Sega Dreamcast"),
            Platform::SegaSaturn => write!(f, "Sega Saturn"),
            Platform::MegaCd => write!(f, "Sega Mega-CD / Sega CD"),
            Platform::ThreeDo => write!(f, "3DO Interactive Multiplayer"),
            Platform::AmigaCd32 => write!(f, "Amiga CD32"),
            Platform::PcEngineCd => write!(f, "PC Engine CD / TurboGrafx-CD"),
            Platform::PcFx => write!(f, "NEC PC-FX"),
            Platform::NeoGeoCd => write!(f, "SNK Neo Geo CD"),
            Platform::PhilipsCdi => write!(f, "Philips CD-i"),
            Platform::Xbox => write!(f, "Microsoft Xbox"),
            Platform::Xbox360 => write!(f, "Microsoft Xbox 360"),
            Platform::GameCube => write!(f, "Nintendo GameCube"),
            Platform::Wii => write!(f, "Nintendo Wii"),
            Platform::DvdVideo => write!(f, "DVD-Video"),
            Platform::DvdAudio => write!(f, "DVD-Audio"),
            Platform::StandardIso => write!(f, "Standard ISO 9660"),
            Platform::ArcadeHardDisk => write!(f, "Arcade Hard Disk"),
            Platform::PcHardDisk => write!(f, "PC Hard Disk"),
            Platform::LaserDiscArcade => write!(f, "LaserDisc Arcade"),
            Platform::Generic => write!(f, "Generic Optical Disc"),
        }
    }
}

/// Track data mode or content type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TrackType {
    /// Red Book audio (CD-DA, 2352 bytes/sector).
    Audio,
    /// Yellow Book Mode 1 data with error correction (2048 bytes user data).
    Mode1_2048,
    /// Raw Mode 1 data with header, sync, and ECC/EDC (2352 bytes/sector).
    Mode1_2352,
    /// Mode 2 data without sync/header (2336 bytes/sector).
    Mode2_2336,
    /// Mode 2 raw data (XA Form 1 / Form 2, 2352 bytes/sector).
    Mode2_2352,
    /// CD-i format (2352 bytes/sector).
    Cdi2352,
    /// Standard DVD-ROM 2048-byte user sector.
    DvdData,
    /// GD-ROM high-density or low-density data track.
    GdiData,
    /// Hard disk 512-byte sector data.
    HardDiskSector512,
    /// LaserDisc video and audio stream.
    LaserDiscFrame,
    /// Unspecified or unknown track mode.
    Unknown,
}

impl fmt::Display for TrackType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Audio => write!(f, "AUDIO"),
            Self::Mode1_2048 => write!(f, "MODE1/2048"),
            Self::Mode1_2352 => write!(f, "MODE1/2352"),
            Self::Mode2_2336 => write!(f, "MODE2/2336"),
            Self::Mode2_2352 => write!(f, "MODE2/2352"),
            Self::Cdi2352 => write!(f, "CDI/2352"),
            Self::DvdData => write!(f, "DVD/2048"),
            Self::GdiData => write!(f, "GDI/DATA"),
            Self::HardDiskSector512 => write!(f, "HD/512"),
            Self::LaserDiscFrame => write!(f, "LASERDISC"),
            Self::Unknown => write!(f, "UNKNOWN"),
        }
    }
}

/// Descriptor for an individual track on the disc.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TrackDescriptor {
    /// 1-based track sequence number.
    pub track_number: u32,
    /// Data mode or content type.
    pub track_type: TrackType,
    /// Sector size in bytes.
    pub sector_size: u32,
    /// Starting Logical Block Address (LBA).
    pub start_lba: u64,
    /// Total sector count for this track, if known.
    pub sector_count: Option<u64>,
    /// Path to the data file corresponding to this track.
    pub file_path: Option<PathBuf>,
    /// Pre-gap sectors preceding this track, if known.
    pub pregap_sectors: Option<u32>,
}

/// Volume descriptor and filesystem metadata extracted from the image.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct VolumeInfo {
    /// System identifier string from ISO 9660 PVD.
    pub system_identifier: Option<String>,
    /// Volume identifier string from ISO 9660 PVD.
    pub volume_identifier: Option<String>,
    /// Volume set identifier string.
    pub volume_set_identifier: Option<String>,
    /// Publisher identifier string.
    pub publisher_identifier: Option<String>,
    /// Application identifier string.
    pub application_identifier: Option<String>,
    /// Volume space size in logical sectors.
    pub volume_space_size: Option<u64>,
    /// Logical block size in bytes (normally 2048).
    pub logical_block_size: Option<u32>,
    /// True if an ISO 9660 Primary Volume Descriptor was found.
    pub has_iso9660: bool,
    /// True if UDF recognition descriptors or anchors were found.
    pub has_udf: bool,
    /// True if `VIDEO_TS` directory or DVD-Video IFO files are present.
    pub has_dvd_video: bool,
    /// True if `AUDIO_TS` directory or DVD-Audio IFO files are present.
    pub has_dvd_audio: bool,
    /// Detected console or format platform.
    pub platform: Option<Platform>,
    /// Alphanumeric game serial, product code, or disc identifier (e.g. SLUS-20002, GM8E01, HDR-0010, T-13301G).
    pub disc_id: Option<String>,
    /// Human-readable game or volume title.
    pub title: Option<String>,
    /// Detailed optical media metadata extracted by the Tiered Fallback Pipeline.
    pub metadata: Option<crate::metadata::DiscMetadata>,
}

/// Detailed inspection descriptor intended for downstream consumption (such as by chdlady).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscDescriptor {
    /// Classified media type (CD, DVD, GDI, or Unknown).
    pub disc_type: DiscType,
    /// Confidence level of the heuristic determination.
    pub confidence: Confidence,
    /// Primary sector size in bytes (e.g. 2048, 2352, 2448, 2336).
    pub primary_sector_size: u32,
    /// Total sector count calculated across the image or descriptor.
    pub total_sectors: Option<u64>,
    /// Total physical size in bytes of all referenced data.
    pub total_size_bytes: Option<u64>,
    /// List of tracks identified on the media.
    pub tracks: Vec<TrackDescriptor>,
    /// Filesystem and volume metadata, if present.
    pub volume_info: Option<Box<VolumeInfo>>,
    /// Human-readable diagnostic summary explaining the heuristic verdict.
    pub summary: String,
    /// Extraction parameters if this image is a CHD container.
    pub chd_plan: Option<crate::chd::ChdExtractionPlan>,
}

impl DiscDescriptor {
    /// Returns the alphanumeric disc/game ID if available.
    #[must_use]
    pub fn disc_id(&self) -> Option<&str> {
        self.volume_info.as_ref().and_then(|v| v.disc_id.as_deref())
    }

    /// Returns the disc or volume title if available.
    #[must_use]
    pub fn title(&self) -> Option<&str> {
        self.volume_info.as_ref().and_then(|v| v.title.as_deref())
    }

    /// Returns detailed disc metadata extracted by the Tiered Fallback Pipeline if available.
    #[must_use]
    pub fn metadata(&self) -> Option<&crate::metadata::DiscMetadata> {
        self.volume_info.as_ref().and_then(|v| v.metadata.as_ref())
    }

    /// Creates a minimal descriptor for unrecognized media.
    pub fn unknown(reason: impl Into<String>) -> Self {
        Self {
            disc_type: DiscType::Unknown,
            confidence: Confidence::Definitive,
            primary_sector_size: 0,
            total_sectors: None,
            total_size_bytes: None,
            tracks: Vec::new(),
            volume_info: None,
            summary: reason.into(),
            chd_plan: None,
        }
    }

    /// Returns true if this descriptor represents a CHD container.
    #[must_use]
    pub const fn is_chd(&self) -> bool {
        self.chd_plan.is_some()
    }

    /// Returns true if this descriptor or CHD container has raw subcode (e.g. `RW_RAW`).
    #[must_use]
    pub fn has_raw_subcode(&self) -> bool {
        self.chd_plan.as_ref().is_some_and(|p| p.has_raw_subcode)
    }

    /// Returns the viable extraction format file extensions for this descriptor if it is a CHD.
    #[must_use]
    pub fn viable_extraction_formats(&self) -> Vec<&'static str> {
        match self.disc_type {
            DiscType::Cd => {
                if self.has_raw_subcode() {
                    vec!["cue", "ccd", "mds", "mdx", "nrg"]
                } else {
                    vec!["cue", "mds", "mdx", "nrg"]
                }
            }
            DiscType::Dvd => vec!["iso"],
            DiscType::Gdi => vec!["gdi"],
            DiscType::HardDisk => vec!["img", "raw"],
            DiscType::LaserDisc => vec!["avi"],
            DiscType::Unknown => vec!["raw"],
        }
    }

    /// Checks if a specific extraction format extension is viable for this descriptor.
    #[must_use]
    pub fn is_extraction_format_viable(&self, ext: &str) -> bool {
        let clean = ext.trim().trim_start_matches('.').to_ascii_lowercase();
        self.viable_extraction_formats().iter().any(|&f| f == clean)
    }
}

/// Errors occurring during disc inspection.
#[derive(Debug)]
pub enum DiscError {
    Io(std::io::Error),
    InvalidPath(PathBuf),
    InvalidDescriptor(String),
    OnlineError(String),
}

impl fmt::Display for DiscError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(e) => write!(f, "I/O error during disc inspection: {e}"),
            Self::InvalidPath(p) => write!(f, "Invalid file path: {}", p.display()),
            Self::InvalidDescriptor(msg) => write!(f, "Invalid disc descriptor: {msg}"),
            Self::OnlineError(msg) => write!(f, "Online database error: {msg}"),
        }
    }
}

impl std::error::Error for DiscError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<std::io::Error> for DiscError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}