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
//! SCSI/MMC physical optical media identification and topology inspection.
//!
//! Interfaces with hardware CD and DVD drives via OS pass-through transports
//! to inspect disc geometry, track layouts, volume descriptors, and console platform
//! signatures directly from physical media.

use std::path::{Path, PathBuf};

use chdlady_physical::{
    exec_read_10_sectors, exec_read_cd_sectors, inspect_disc as inspect_physical_media,
    is_optical_device_path, open_optical_transport, DiscCanonicalMap, MediaCategory, ScsiTransport,
};

use crate::iso::parse_iso_pvd;
use crate::types::{
    Confidence, DiscDescriptor, DiscError, DiscType, Platform, TrackDescriptor, TrackType,
    VolumeInfo,
};

/// Returns true if the path points to a physical optical drive device.
#[must_use]
pub fn is_physical_disc_path<P: AsRef<Path>>(path: P) -> bool {
    is_optical_device_path(path)
}

/// Discovers and lists available optical drive devices present on the system.
#[must_use]
pub fn list_optical_drives() -> Vec<PathBuf> {
    let mut drives = Vec::new();

    #[cfg(target_os = "linux")]
    {
        for i in 0..8 {
            let p = PathBuf::from(format!("/dev/sr{i}"));
            if p.exists() {
                drives.push(p);
            }
        }
        for alias in &["/dev/cdrom", "/dev/dvd"] {
            let p = PathBuf::from(alias);
            if p.exists() {
                if let Ok(canon) = p.canonicalize() {
                    if !drives.contains(&canon) {
                        drives.push(canon);
                    }
                } else if !drives.contains(&p) {
                    drives.push(p);
                }
            }
        }
    }

    #[cfg(target_os = "windows")]
    {
        for letter in 'A'..='Z' {
            if chdlady_physical::is_optical_drive_letter(letter) {
                drives.push(PathBuf::from(format!(r"\\.\{letter}:")));
            }
        }
    }

    drives
}

/// Inspects a physical optical drive at the specified device path.
///
/// # Errors
///
/// Returns [`DiscError::Io`] if optical transport creation, SCSI command execution,
/// or media identification fails.
pub fn inspect_physical_disc<P: AsRef<Path>>(path: P) -> Result<DiscDescriptor, DiscError> {
    let p = path.as_ref();
    let mut transport =
        open_optical_transport(p).map_err(|e| DiscError::Io(std::io::Error::other(e)))?;
    inspect_physical_transport(&mut transport, Some(p))
}

struct PhysicalDiscReader<'a, T: ScsiTransport> {
    transport: &'a mut T,
    start_lba: u64,
    total_lbas: u64,
    is_cd: bool,
}

impl<'a, T: ScsiTransport> crate::metadata::DiscReader for PhysicalDiscReader<'a, T> {
    fn read_sector(&mut self, lba: u64, buf: &mut [u8; 2048]) -> std::io::Result<()> {
        let actual_lba = self.start_lba + lba;
        if actual_lba >= self.total_lbas {
            return Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "LBA out of bounds",
            ));
        }
        if self.is_cd {
            let mut sec = vec![0u8; 2448];
            exec_read_cd_sectors(self.transport, actual_lba as u32, 1, &mut sec)
                .map_err(std::io::Error::other)?;
            if let Some(user) = crate::raw::extract_cd_user_data(&sec) {
                if user.len() >= 2048 {
                    buf.copy_from_slice(&user[..2048]);
                    return Ok(());
                }
            }
            Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "Failed to extract CD user data",
            ))
        } else {
            exec_read_10_sectors(self.transport, actual_lba as u32, 1, buf)
                .map_err(std::io::Error::other)
        }
    }

    fn total_sectors(&self) -> Option<u64> {
        Some(self.total_lbas)
    }
}

/// Inspects a physical optical disc via an active [`ScsiTransport`].
///
/// Queries drive profiles, TOC/PMA/ATIP, DVD structures, and probes initial sectors
/// (LBA 0, LBA 16, LBA 32) to extract track layouts, ISO 9660 PVDs, and console platform signatures.
///
/// # Errors
///
/// Returns [`DiscError::Io`] if SCSI commands fail or if the loaded medium is unrecognized.
pub fn inspect_physical_transport(
    transport: &mut impl ScsiTransport,
    device_path: Option<&Path>,
) -> Result<DiscDescriptor, DiscError> {
    let canonical_map =
        inspect_physical_media(transport).map_err(|e| DiscError::Io(std::io::Error::other(e)))?;

    let is_dvd = matches!(
        canonical_map.category,
        MediaCategory::DvdRomSingleLayer
            | MediaCategory::DvdRomDualLayerPtp
            | MediaCategory::DvdRomDualLayerOtp { .. }
    );

    let disc_type = if is_dvd { DiscType::Dvd } else { DiscType::Cd };

    let primary_sector_size = if is_dvd { 2048 } else { 2448 };

    let mut tracks = Vec::with_capacity(canonical_map.tracks.len());
    for t in &canonical_map.tracks {
        let track_type = if t.is_audio {
            TrackType::Audio
        } else if is_dvd {
            TrackType::DvdData
        } else {
            TrackType::Mode1_2352
        };

        tracks.push(TrackDescriptor {
            track_number: t.track_number as u32,
            track_type,
            sector_size: t.sector_size as u32,
            start_lba: t.start_lba as u64,
            sector_count: Some(t.sector_count as u64),
            file_path: device_path.map(|p| p.to_path_buf()),
            pregap_sectors: Some(t.pregap_sectors),
        });
    }

    let (start_lba, has_data) = if is_dvd {
        (0, canonical_map.total_lbas > 0)
    } else {
        match canonical_map.tracks.iter().find(|t| !t.is_audio) {
            Some(t) => (t.start_lba, true),
            None => (0, false),
        }
    };

    let mut volume_info: Option<Box<VolumeInfo>> = None;
    let mut detected_platform: Option<Platform> = None;

    if has_data {
        let mut phys_reader = PhysicalDiscReader {
            transport,
            start_lba: start_lba as u64,
            total_lbas: canonical_map.total_lbas as u64,
            is_cd: !is_dvd,
        };

        let meta = crate::metadata::inspect_metadata(&mut phys_reader, device_path);
        let mut pvd_sec = [0u8; 2048];
        let mut vol =
            if crate::metadata::DiscReader::read_sector(&mut phys_reader, 16, &mut pvd_sec).is_ok()
            {
                parse_iso_pvd(&pvd_sec).unwrap_or_default()
            } else {
                VolumeInfo::default()
            };

        meta.apply_to_volume_info(&mut vol);
        if vol.platform.is_none() && vol.has_iso9660 {
            vol.platform = Some(Platform::StandardIso);
        }
        detected_platform = vol.platform;
        if detected_platform.is_some()
            || vol.has_iso9660
            || vol.title.is_some()
            || vol.disc_id.is_some()
        {
            volume_info = Some(Box::new(vol));
        }
    }

    let summary = format_physical_summary(
        &canonical_map,
        tracks.len(),
        detected_platform,
        volume_info.as_deref(),
        device_path,
    );

    Ok(DiscDescriptor {
        disc_type,
        confidence: Confidence::Definitive,
        primary_sector_size,
        total_sectors: Some(canonical_map.total_lbas as u64),
        total_size_bytes: Some(canonical_map.total_bytes),
        tracks,
        volume_info,
        summary,
        chd_plan: None,
    })
}

fn format_physical_summary(
    canonical_map: &DiscCanonicalMap,
    track_count: usize,
    platform: Option<Platform>,
    volume_info: Option<&VolumeInfo>,
    device_path: Option<&Path>,
) -> String {
    let drive_str = device_path
        .map(|p| format!(" on {}", p.display()))
        .unwrap_or_default();

    let cat_str = match &canonical_map.category {
        MediaCategory::CdRom => "CD-ROM (Data)",
        MediaCategory::CdAudio => "CD-DA (Audio)",
        MediaCategory::CdMixedMode => "CD (Mixed Mode / Enhanced)",
        MediaCategory::DvdRomSingleLayer => "DVD-ROM (Single Layer)",
        MediaCategory::DvdRomDualLayerPtp => "DVD-ROM (Dual Layer PTP)",
        MediaCategory::DvdRomDualLayerOtp { .. } => "DVD-ROM (Dual Layer OTP)",
    };

    let disc_id = volume_info.and_then(|v| v.disc_id.as_deref());
    let title = volume_info.and_then(|v| v.title.as_deref());
    let id_str = disc_id.map(|id| format!(" [{id}]")).unwrap_or_default();
    let title_str = title.map(|t| format!(" \"{t}\"")).unwrap_or_default();
    let total_lbas = canonical_map.total_lbas;
    let total_bytes = canonical_map.total_bytes;

    if let Some(plat) = platform {
        format!(
            "Physical {cat_str}{drive_str}: {plat} disc{id_str}{title_str} with {track_count} track(s), {total_lbas} sectors ({total_bytes} bytes)"
        )
    } else {
        format!(
            "Physical {cat_str}{drive_str}{id_str}{title_str} with {track_count} track(s), {total_lbas} sectors ({total_bytes} bytes)"
        )
    }
}