use std::fmt;
use std::io::{self, Read, Seek, SeekFrom};
use std::path::Path;
use crate::types::Platform;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MetadataSource {
NativeHeader,
Iso9660Pvd,
DatabaseLookup,
FilenameFallback,
}
impl fmt::Display for MetadataSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MetadataSource::NativeHeader => write!(f, "Native Header"),
MetadataSource::Iso9660Pvd => write!(f, "ISO 9660 PVD"),
MetadataSource::DatabaseLookup => write!(f, "Database Lookup"),
MetadataSource::FilenameFallback => write!(f, "Filename Fallback"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GameId {
pub raw: String,
pub normalized: String,
}
impl fmt::Display for GameId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.normalized)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PlatformKind {
ThreeDo,
AmigaCd32,
PcEngineCd,
PcFx,
PhilipsCdi,
SegaMegaCd,
SegaSaturn,
SegaDreamcast,
NeoGeoCd,
PlayStation1,
PlayStation2,
PlayStationPortable,
GameCube,
Wii,
Xbox,
Xbox360,
Unknown,
}
impl PlatformKind {
pub fn to_platform(self) -> Option<Platform> {
match self {
PlatformKind::ThreeDo => Some(Platform::ThreeDo),
PlatformKind::AmigaCd32 => Some(Platform::AmigaCd32),
PlatformKind::PcEngineCd => Some(Platform::PcEngineCd),
PlatformKind::PcFx => Some(Platform::PcFx),
PlatformKind::PhilipsCdi => Some(Platform::PhilipsCdi),
PlatformKind::SegaMegaCd => Some(Platform::MegaCd),
PlatformKind::SegaSaturn => Some(Platform::SegaSaturn),
PlatformKind::SegaDreamcast => Some(Platform::Dreamcast),
PlatformKind::NeoGeoCd => Some(Platform::NeoGeoCd),
PlatformKind::PlayStation1 => Some(Platform::PlayStation1),
PlatformKind::PlayStation2 => Some(Platform::PlayStation2),
PlatformKind::PlayStationPortable => Some(Platform::PlayStationPortable),
PlatformKind::GameCube => Some(Platform::GameCube),
PlatformKind::Wii => Some(Platform::Wii),
PlatformKind::Xbox => Some(Platform::Xbox),
PlatformKind::Xbox360 => Some(Platform::Xbox360),
PlatformKind::Unknown => None,
}
}
}
impl fmt::Display for PlatformKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PlatformKind::ThreeDo => write!(f, "3DO Interactive Multiplayer"),
PlatformKind::AmigaCd32 => write!(f, "Amiga CD32"),
PlatformKind::PcEngineCd => write!(f, "PC Engine CD / TurboGrafx-CD"),
PlatformKind::PcFx => write!(f, "NEC PC-FX"),
PlatformKind::PhilipsCdi => write!(f, "Philips CD-i"),
PlatformKind::SegaMegaCd => write!(f, "Sega Mega-CD / Sega CD"),
PlatformKind::SegaSaturn => write!(f, "Sega Saturn"),
PlatformKind::SegaDreamcast => write!(f, "Sega Dreamcast"),
PlatformKind::NeoGeoCd => write!(f, "SNK Neo Geo CD"),
PlatformKind::PlayStation1 => write!(f, "Sony PlayStation"),
PlatformKind::PlayStation2 => write!(f, "Sony PlayStation 2"),
PlatformKind::PlayStationPortable => write!(f, "Sony PlayStation Portable"),
PlatformKind::GameCube => write!(f, "Nintendo GameCube"),
PlatformKind::Wii => write!(f, "Nintendo Wii"),
PlatformKind::Xbox => write!(f, "Microsoft Xbox"),
PlatformKind::Xbox360 => write!(f, "Microsoft Xbox 360"),
PlatformKind::Unknown => write!(f, "Unknown Platform"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscMetadata {
pub platform: PlatformKind,
pub title: Option<String>,
pub game_id: Option<GameId>,
pub title_source: MetadataSource,
pub game_id_source: MetadataSource,
}
impl Default for DiscMetadata {
fn default() -> Self {
Self {
platform: PlatformKind::Unknown,
title: None,
game_id: None,
title_source: MetadataSource::NativeHeader,
game_id_source: MetadataSource::NativeHeader,
}
}
}
impl DiscMetadata {
pub fn apply_to_volume_info(&self, vol: &mut crate::types::VolumeInfo) {
if let Some(plat) = self.platform.to_platform() {
vol.platform = Some(plat);
}
if let Some(ref gid) = self.game_id {
vol.disc_id = Some(gid.normalized.clone());
}
if let Some(ref t) = self.title {
vol.title = Some(t.clone());
}
vol.metadata = Some(self.clone());
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RawMetadata {
pub title: Option<String>,
pub game_id: Option<String>,
}
#[derive(Debug)]
pub enum InspectionError {
Io(io::Error),
SignatureNotFound,
CorruptedHeader(&'static str),
}
impl From<io::Error> for InspectionError {
fn from(e: io::Error) -> Self {
Self::Io(e)
}
}
pub trait DiscReader {
fn read_sector(&mut self, lba: u64, buf: &mut [u8; 2048]) -> io::Result<()>;
fn total_sectors(&self) -> Option<u64> {
None
}
}
pub struct StreamDiscReader<R> {
reader: R,
base_offset: u64,
sector_size: u32,
total_sectors: Option<u64>,
}
impl<R: Read + Seek> StreamDiscReader<R> {
pub fn new(reader: R, sector_size: u32, total_size: u64) -> Self {
Self::new_with_offset(reader, 0, sector_size, total_size)
}
pub fn new_with_offset(reader: R, base_offset: u64, sector_size: u32, total_size: u64) -> Self {
let sec_size = if sector_size == 0 { 2048 } else { sector_size };
let total_sectors = if sec_size > 0 {
Some(total_size / (sec_size as u64))
} else {
None
};
Self {
reader,
base_offset,
sector_size: sec_size,
total_sectors,
}
}
}
impl<R: Read + Seek> DiscReader for StreamDiscReader<R> {
fn read_sector(&mut self, lba: u64, buf: &mut [u8; 2048]) -> io::Result<()> {
let sector_offset = lba
.checked_mul(self.sector_size as u64)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "LBA overflow"))?;
let file_pos = self
.base_offset
.checked_add(sector_offset)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Offset overflow"))?;
self.reader.seek(SeekFrom::Start(file_pos))?;
if self.sector_size == 2048 {
self.reader.read_exact(buf)?;
Ok(())
} else if (self.sector_size as usize) <= 2448 {
let mut raw = [0u8; 2448];
let raw_slice = &mut raw[..self.sector_size as usize];
self.reader.read_exact(raw_slice)?;
let offset = crate::raw::cd_user_data_offset(raw_slice);
if raw_slice.len() >= offset + 2048 {
buf.copy_from_slice(&raw_slice[offset..offset + 2048]);
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"Sector payload truncated",
))
}
} else {
let mut raw = vec![0u8; self.sector_size as usize];
self.reader.read_exact(&mut raw)?;
let offset = crate::raw::cd_user_data_offset(&raw);
if raw.len() >= offset + 2048 {
buf.copy_from_slice(&raw[offset..offset + 2048]);
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"Sector payload truncated",
))
}
}
}
fn total_sectors(&self) -> Option<u64> {
self.total_sectors
}
}
pub struct SliceDiscReader<'a> {
data: &'a [u8],
sector_size: usize,
user_offset: usize,
}
impl<'a> SliceDiscReader<'a> {
pub fn new(data: &'a [u8], sector_size: usize) -> Self {
let sec_size = if sector_size == 0 { 2048 } else { sector_size };
let user_offset = if sec_size == 2048 {
0
} else if data.len() >= sec_size {
crate::raw::cd_user_data_offset(&data[..sec_size])
} else {
16
};
Self {
data,
sector_size: sec_size,
user_offset,
}
}
}
impl<'a> DiscReader for SliceDiscReader<'a> {
fn read_sector(&mut self, lba: u64, buf: &mut [u8; 2048]) -> io::Result<()> {
let start = (lba as usize)
.checked_mul(self.sector_size)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "LBA overflow"))?;
let user_start = start + self.user_offset;
let user_end = user_start + 2048;
if user_end <= self.data.len() {
buf.copy_from_slice(&self.data[user_start..user_end]);
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"Sector out of bounds in slice reader",
))
}
}
fn total_sectors(&self) -> Option<u64> {
self.data
.len()
.checked_div(self.sector_size)
.map(|s| s as u64)
}
}
pub fn clean_ascii_string(bytes: &[u8]) -> String {
let raw = String::from_utf8_lossy(bytes);
let trimmed = raw.trim_matches(|c: char| c == '\0' || c.is_whitespace() || c == '\u{fffd}');
let mut result = String::with_capacity(trimmed.len());
let mut prev_space = false;
for c in trimmed.chars() {
if c.is_whitespace() {
if !prev_space {
result.push(' ');
prev_space = true;
}
} else {
result.push(c);
prev_space = false;
}
}
result
}
pub fn normalize_psx_serial(path: &str) -> Option<GameId> {
let clean_path = path.split(';').next().unwrap_or(path).trim();
let filename = clean_path
.split(&['\\', '/'][..])
.next_back()
.unwrap_or(clean_path)
.trim();
let bytes = filename.as_bytes();
if bytes.len() < 8 {
return None;
}
if !bytes[0..4].iter().all(u8::is_ascii_alphabetic) {
return None;
}
let prefix = filename[0..4].to_ascii_uppercase();
let sep = bytes[4];
if sep == b'_' || sep == b'-' {
let rest = &filename[5..];
let digits: String = rest.chars().filter(|c| c.is_ascii_digit()).collect();
if digits.len() < 4 || digits.len() > 6 {
return None;
}
let normalized = format!("{prefix}-{digits}");
return Some(GameId {
raw: filename.to_string(),
normalized,
});
}
let rest = &filename[4..];
if rest.chars().all(|c| c.is_ascii_digit()) && rest.len() >= 4 && rest.len() <= 6 {
let normalized = format!("{prefix}-{rest}");
return Some(GameId {
raw: filename.to_string(),
normalized,
});
}
None
}
pub fn sanitize_image_basename(path: &Path) -> Option<String> {
let stem = path.file_stem().and_then(|s| s.to_str())?;
let lower = stem.to_ascii_lowercase();
if lower.starts_with("track") || lower.starts_with("image") {
return None;
}
let trimmed = stem.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
pub trait PlatformDiscInspector: Send + Sync {
fn platform(&self) -> PlatformKind;
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError>;
}
pub struct ThreeDoInspector;
impl PlatformDiscInspector for ThreeDoInspector {
fn platform(&self) -> PlatformKind {
PlatformKind::ThreeDo
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut sec0 = [0u8; 2048];
let mut found_header = false;
if reader.read_sector(0, &mut sec0).is_ok()
&& sec0.starts_with(&crate::console::THREEDO_MAGIC)
{
found_header = true;
}
if !found_header
&& reader.read_sector(225, &mut sec0).is_ok()
&& sec0.starts_with(&crate::console::THREEDO_MAGIC)
{
found_header = true;
}
if !found_header {
return Err(InspectionError::SignatureNotFound);
}
let label = clean_ascii_string(&sec0[40..72]);
let title = if !label.is_empty() && label != "CD-ROM" {
Some(label)
} else {
None
};
let vol_id = u32::from_be_bytes(
sec0[72..76]
.try_into()
.map_err(|_| InspectionError::CorruptedHeader("Invalid 3DO volume unique ID"))?,
);
let game_id = if vol_id != 0 && vol_id != 0xFFFF_FFFF {
Some(format!("{vol_id:08X}"))
} else {
None
};
Ok(RawMetadata { title, game_id })
}
}
pub struct SegaMegaCdInspector;
impl PlatformDiscInspector for SegaMegaCdInspector {
fn platform(&self) -> PlatformKind {
PlatformKind::SegaMegaCd
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut sec0 = [0u8; 2048];
reader.read_sector(0, &mut sec0)?;
let has_magic = sec0.starts_with(b"SEGADISCSYSTEM")
|| (sec0.len() >= 0x110 && sec0[0x100..].starts_with(b"SEGADISCSYSTEM"));
if !has_magic {
return Err(InspectionError::SignatureNotFound);
}
let mut serial = if sec0.len() >= 0x190 {
let s = clean_ascii_string(&sec0[0x180..0x190]);
if !s.is_empty() {
Some(s)
} else {
None
}
} else {
None
};
if serial.is_none() && sec0.len() >= 0x90 {
let s = clean_ascii_string(&sec0[0x80..0x90]);
if !s.is_empty() {
serial = Some(s);
}
}
let mut title = None;
if sec0.len() >= 0x180 {
let overseas = clean_ascii_string(&sec0[0x150..0x180]);
let domestic = clean_ascii_string(&sec0[0x120..0x150]);
if !overseas.is_empty() {
title = Some(overseas);
} else if !domestic.is_empty() {
title = Some(domestic);
}
}
if title.is_none() && sec0.len() >= 0x80 {
let overseas = clean_ascii_string(&sec0[0x50..0x80]);
let domestic = clean_ascii_string(&sec0[0x20..0x50]);
if !overseas.is_empty() {
title = Some(overseas);
} else if !domestic.is_empty() {
title = Some(domestic);
}
}
Ok(RawMetadata {
title,
game_id: serial,
})
}
}
pub struct SegaSaturnInspector;
impl PlatformDiscInspector for SegaSaturnInspector {
fn platform(&self) -> PlatformKind {
PlatformKind::SegaSaturn
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut sec0 = [0u8; 2048];
reader.read_sector(0, &mut sec0)?;
if !sec0.starts_with(b"SEGA SEGASATURN ") {
return Err(InspectionError::SignatureNotFound);
}
let prod_10 = clean_ascii_string(&sec0[0x20..0x2A]);
let game_id = if !prod_10.is_empty() {
Some(prod_10)
} else {
let prod_16 = clean_ascii_string(&sec0[0x20..0x30]);
if !prod_16.is_empty() {
Some(prod_16)
} else {
None
}
};
let t = clean_ascii_string(&sec0[0x60..0xD0]);
let title = if !t.is_empty() { Some(t) } else { None };
Ok(RawMetadata { title, game_id })
}
}
pub struct SegaDreamcastInspector;
impl PlatformDiscInspector for SegaDreamcastInspector {
fn platform(&self) -> PlatformKind {
PlatformKind::SegaDreamcast
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut sec = [0u8; 2048];
let mut matched = false;
if reader.read_sector(0, &mut sec).is_ok() && sec.starts_with(b"SEGA SEGAKATANA ") {
matched = true;
}
if !matched
&& reader.read_sector(45000, &mut sec).is_ok()
&& sec.starts_with(b"SEGA SEGAKATANA ")
{
matched = true;
}
if !matched {
return Err(InspectionError::SignatureNotFound);
}
let mut disc_id = clean_ascii_string(&sec[0x40..0x4A]);
if disc_id.is_empty() {
disc_id = clean_ascii_string(&sec[0x40..0x50]);
}
let game_id = if !disc_id.is_empty() {
Some(disc_id)
} else {
None
};
let t = clean_ascii_string(&sec[0x80..0x100]);
let title = if !t.is_empty() { Some(t) } else { None };
Ok(RawMetadata { title, game_id })
}
}
pub struct PlayStationPortableInspector;
impl PlatformDiscInspector for PlayStationPortableInspector {
fn platform(&self) -> PlatformKind {
PlatformKind::PlayStationPortable
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut pvd = [0u8; 2048];
reader.read_sector(16, &mut pvd)?;
if pvd[0] != 0x01 || &pvd[1..6] != b"CD001" {
return Err(InspectionError::SignatureNotFound);
}
let sys_id = clean_ascii_string(&pvd[8..40]);
let app_id = clean_ascii_string(&pvd[128..256]);
let is_psp = sys_id.contains("PSP GAME") || app_id.contains("PSP GAME");
let root_lba = u32::from_le_bytes(
pvd[158..162]
.try_into()
.map_err(|_| InspectionError::CorruptedHeader("Corrupted root LBA"))?,
) as u64;
let mut root_sec = [0u8; 2048];
reader.read_sector(root_lba, &mut root_sec)?;
let mut psp_game_lba = None;
let mut umd_data_lba = None;
let mut pos = 0;
while pos < root_sec.len() {
let len = root_sec[pos] as usize;
if len == 0 || pos + len > root_sec.len() || len < 33 {
break;
}
let name_len = root_sec[pos + 32] as usize;
if pos + 33 + name_len <= root_sec.len() {
let name = &root_sec[pos + 33..pos + 33 + name_len];
let name_str = String::from_utf8_lossy(name);
let clean_name = name_str.split(';').next().unwrap_or(&name_str);
if clean_name.eq_ignore_ascii_case("PSP_GAME") {
let lba = u32::from_le_bytes(
root_sec[pos + 2..pos + 6].try_into().unwrap_or_default(),
) as u64;
psp_game_lba = Some(lba);
} else if clean_name.eq_ignore_ascii_case("UMD_DATA.BIN") {
let lba = u32::from_le_bytes(
root_sec[pos + 2..pos + 6].try_into().unwrap_or_default(),
) as u64;
umd_data_lba = Some(lba);
}
}
pos += len;
}
if !is_psp && psp_game_lba.is_none() && umd_data_lba.is_none() {
return Err(InspectionError::SignatureNotFound);
}
let mut title = None;
let mut game_id = None;
if let Some(psp_lba) = psp_game_lba {
let mut psp_sec = [0u8; 2048];
if reader.read_sector(psp_lba, &mut psp_sec).is_ok() {
let mut sfo_lba = None;
let mut pos = 0;
while pos < psp_sec.len() {
let len = psp_sec[pos] as usize;
if len == 0 || pos + len > psp_sec.len() || len < 33 {
break;
}
let name_len = psp_sec[pos + 32] as usize;
if pos + 33 + name_len <= psp_sec.len() {
let name = &psp_sec[pos + 33..pos + 33 + name_len];
let name_str = String::from_utf8_lossy(name);
let clean_name = name_str.split(';').next().unwrap_or(&name_str);
if clean_name.eq_ignore_ascii_case("PARAM.SFO") {
let lba = u32::from_le_bytes(
psp_sec[pos + 2..pos + 6].try_into().unwrap_or_default(),
) as u64;
sfo_lba = Some(lba);
break;
}
}
pos += len;
}
if let Some(sfo_lba) = sfo_lba {
let mut sfo_sec = [0u8; 2048];
if reader.read_sector(sfo_lba, &mut sfo_sec).is_ok()
&& &sfo_sec[0..4] == b"\0PSF"
{
let key_table_offset =
u32::from_le_bytes(sfo_sec[8..12].try_into().unwrap_or_default())
as usize;
let data_table_offset =
u32::from_le_bytes(sfo_sec[12..16].try_into().unwrap_or_default())
as usize;
let count =
u32::from_le_bytes(sfo_sec[16..20].try_into().unwrap_or_default())
as usize;
for i in 0..count {
let entry_off = 20 + i * 16;
if entry_off + 16 > sfo_sec.len() {
break;
}
let k_off = u16::from_le_bytes(
sfo_sec[entry_off..entry_off + 2]
.try_into()
.unwrap_or_default(),
) as usize;
let param_len = u32::from_le_bytes(
sfo_sec[entry_off + 4..entry_off + 8]
.try_into()
.unwrap_or_default(),
) as usize;
let d_off = u32::from_le_bytes(
sfo_sec[entry_off + 12..entry_off + 16]
.try_into()
.unwrap_or_default(),
) as usize;
let key_start = key_table_offset + k_off;
if key_start < sfo_sec.len() {
let key_end = sfo_sec[key_start..]
.iter()
.position(|&b| b == 0)
.map(|p| key_start + p)
.unwrap_or(sfo_sec.len());
let key = String::from_utf8_lossy(&sfo_sec[key_start..key_end]);
let val_start = data_table_offset + d_off;
let val_end = (val_start + param_len).min(sfo_sec.len());
if val_start < val_end {
let val_slice = &sfo_sec[val_start..val_end];
let val_str = clean_ascii_string(val_slice);
if key == "DISC_ID" && game_id.is_none() {
game_id = Some(val_str);
} else if key == "TITLE" && title.is_none() {
let cleaned_title = val_str
.trim_end_matches(['\u{2122}', '\u{00ae}'])
.trim();
if !cleaned_title.is_empty() {
title = Some(cleaned_title.to_string());
}
}
}
}
}
}
}
}
}
if game_id.is_none() {
if let Some(lba) = umd_data_lba {
let mut umd_sec = [0u8; 2048];
if reader.read_sector(lba, &mut umd_sec).is_ok() {
let text = String::from_utf8_lossy(&umd_sec);
if let Some(id_part) = text.split('|').next() {
let cleaned = clean_ascii_string(id_part.as_bytes());
if !cleaned.is_empty() {
game_id = Some(cleaned);
}
}
}
}
}
if game_id.is_none() && pvd.len() >= 0x373 + 16 {
let text = String::from_utf8_lossy(&pvd[0x373..0x373 + 32]);
if let Some(id_part) = text.split('|').next() {
let cleaned = clean_ascii_string(id_part.as_bytes());
if cleaned.len() >= 8 && cleaned[0..4].chars().all(|c| c.is_ascii_alphabetic()) {
game_id = Some(cleaned);
}
}
}
Ok(RawMetadata { title, game_id })
}
}
pub struct PlayStationInspector;
impl PlatformDiscInspector for PlayStationInspector {
fn platform(&self) -> PlatformKind {
PlatformKind::PlayStation1
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut pvd = [0u8; 2048];
reader.read_sector(16, &mut pvd)?;
if pvd[0] != 0x01 || &pvd[1..6] != b"CD001" {
return Err(InspectionError::SignatureNotFound);
}
let sys_id = clean_ascii_string(&pvd[8..40]);
if !sys_id.contains("PLAYSTATION") {
return Err(InspectionError::SignatureNotFound);
}
let root_lba = u32::from_le_bytes(
pvd[158..162]
.try_into()
.map_err(|_| InspectionError::CorruptedHeader("Corrupted root LBA"))?,
) as u64;
let mut root_sec = [0u8; 2048];
reader.read_sector(root_lba, &mut root_sec)?;
let mut cnf_lba = None;
let mut serial = None;
let mut pos = 0;
while pos < root_sec.len() {
let len = root_sec[pos] as usize;
if len == 0 {
break;
}
if pos + len > root_sec.len() || len < 33 {
break;
}
let name_len = root_sec[pos + 32] as usize;
if pos + 33 + name_len <= root_sec.len() {
let name = &root_sec[pos + 33..pos + 33 + name_len];
let name_str = String::from_utf8_lossy(name);
let clean_name = name_str.split(';').next().unwrap_or(&name_str);
if clean_name.eq_ignore_ascii_case("SYSTEM.CNF") {
let lba = u32::from_le_bytes(
root_sec[pos + 2..pos + 6].try_into().unwrap_or_default(),
) as u64;
cnf_lba = Some(lba);
} else if serial.is_none() {
if let Some(gid) = normalize_psx_serial(&name_str) {
serial = Some(gid.normalized);
}
}
}
pos += len;
}
if let Some(lba) = cnf_lba {
let mut cnf_sec = [0u8; 2048];
if reader.read_sector(lba, &mut cnf_sec).is_ok() {
let text = String::from_utf8_lossy(&cnf_sec);
for line in text.lines() {
let trimmed = line.trim();
if trimmed.starts_with("BOOT") {
for part in trimmed.split(|c: char| {
c == '\\'
|| c == '/'
|| c == ':'
|| c == ' '
|| c == '='
|| c == ';'
|| c == '"'
}) {
if let Some(gid) = normalize_psx_serial(part) {
serial = Some(gid.normalized);
break;
}
}
}
}
}
}
Ok(RawMetadata {
title: None,
game_id: serial,
})
}
}
pub struct NintendoInspector;
impl PlatformDiscInspector for NintendoInspector {
fn platform(&self) -> PlatformKind {
PlatformKind::GameCube
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut sec0 = [0u8; 2048];
reader.read_sector(0, &mut sec0)?;
if sec0.len() < 0x1C || sec0[0x18..0x1C] != [0x5D, 0x1C, 0x9E, 0xA3] {
return Err(InspectionError::SignatureNotFound);
}
let code = &sec0[0..6];
let game_id = if code.iter().all(|&b| b.is_ascii_graphic()) {
Some(clean_ascii_string(code))
} else {
None
};
let t = clean_ascii_string(&sec0[0x20..0x60]);
let title = if !t.is_empty() { Some(t) } else { None };
Ok(RawMetadata { title, game_id })
}
}
pub struct XboxInspector;
impl PlatformDiscInspector for XboxInspector {
fn platform(&self) -> PlatformKind {
PlatformKind::Xbox
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut sec32 = [0u8; 2048];
if reader.read_sector(32, &mut sec32).is_ok() && sec32.starts_with(b"MICROSOFT*XBOX*MEDIA")
{
Ok(RawMetadata::default())
} else {
Err(InspectionError::SignatureNotFound)
}
}
}
pub struct AmigaCd32Inspector;
impl PlatformDiscInspector for AmigaCd32Inspector {
fn platform(&self) -> PlatformKind {
PlatformKind::AmigaCd32
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut pvd = [0u8; 2048];
reader.read_sector(16, &mut pvd)?;
if pvd[0] != 0x01 || &pvd[1..6] != b"CD001" {
return Err(InspectionError::SignatureNotFound);
}
let sys_id = clean_ascii_string(&pvd[8..40]);
let app_id = clean_ascii_string(&pvd[128..256]);
let is_amiga = sys_id.contains("CDTV")
|| sys_id.contains("AMIGA")
|| sys_id.contains("CD32")
|| app_id.contains("CD32")
|| app_id.contains("CDTV");
if !is_amiga {
return Err(InspectionError::SignatureNotFound);
}
let vol_id = clean_ascii_string(&pvd[40..72]);
let title = if !vol_id.is_empty() && vol_id != "CD-ROM" {
Some(vol_id)
} else {
None
};
Ok(RawMetadata {
title,
game_id: None,
})
}
}
pub struct NeoGeoCdInspector;
impl PlatformDiscInspector for NeoGeoCdInspector {
fn platform(&self) -> PlatformKind {
PlatformKind::NeoGeoCd
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut pvd = [0u8; 2048];
reader.read_sector(16, &mut pvd)?;
if pvd[0] != 0x01 || &pvd[1..6] != b"CD001" {
return Err(InspectionError::SignatureNotFound);
}
let sys_id = clean_ascii_string(&pvd[8..40]);
let vol_id = clean_ascii_string(&pvd[40..72]);
let root_lba = u32::from_le_bytes(
pvd[158..162]
.try_into()
.map_err(|_| InspectionError::CorruptedHeader("Corrupted root LBA"))?,
) as u64;
let mut root_sec = [0u8; 2048];
reader.read_sector(root_lba, &mut root_sec)?;
let mut has_ipl = false;
let mut ipl_lba = None;
let mut ngh_serial = None;
let mut pos = 0;
while pos < root_sec.len() {
let len = root_sec[pos] as usize;
if len == 0 || pos + len > root_sec.len() || len < 33 {
break;
}
let name_len = root_sec[pos + 32] as usize;
if pos + 33 + name_len <= root_sec.len() {
let name = &root_sec[pos + 33..pos + 33 + name_len];
let name_str = String::from_utf8_lossy(name);
let clean_name = name_str.split(';').next().unwrap_or(&name_str);
if clean_name.eq_ignore_ascii_case("IPL.TXT") {
has_ipl = true;
let lba = u32::from_le_bytes(
root_sec[pos + 2..pos + 6].try_into().unwrap_or_default(),
) as u64;
ipl_lba = Some(lba);
}
if ngh_serial.is_none()
&& clean_name.starts_with('P')
&& clean_name.len() > 4
&& clean_name.get(clean_name.len() - 4..).is_some_and(|ext| {
ext.eq_ignore_ascii_case(".prg") || ext.eq_ignore_ascii_case(".fix")
})
{
let num_part = &clean_name[1..clean_name.len() - 4];
if let Ok(num) = num_part.parse::<u32>() {
ngh_serial = Some(format!("NGH-{num:03}"));
}
}
}
pos += len;
}
if !has_ipl && !sys_id.contains("NEO-GEO") && !vol_id.contains("NEOGEO") {
return Err(InspectionError::SignatureNotFound);
}
if ngh_serial.is_none() {
if let Some(lba) = ipl_lba {
let mut ipl_sec = [0u8; 2048];
if reader.read_sector(lba, &mut ipl_sec).is_ok() {
let text = String::from_utf8_lossy(&ipl_sec);
for line in text.lines() {
let trimmed = line.trim();
if trimmed.starts_with('P') {
if let Some(token) = trimmed.split(',').next() {
let file_name = token.trim();
if file_name.starts_with('P')
&& file_name.len() > 4
&& file_name.get(file_name.len() - 4..).is_some_and(|ext| {
ext.eq_ignore_ascii_case(".prg")
|| ext.eq_ignore_ascii_case(".fix")
})
{
let num_part = &file_name[1..file_name.len() - 4];
if let Ok(num) = num_part.parse::<u32>() {
ngh_serial = Some(format!("NGH-{num:03}"));
break;
}
}
}
}
}
}
}
}
let title = if !vol_id.is_empty() && vol_id != "CD-ROM" {
Some(vol_id)
} else {
None
};
Ok(RawMetadata {
title,
game_id: ngh_serial,
})
}
}
pub struct PcFxInspector;
impl PlatformDiscInspector for PcFxInspector {
fn platform(&self) -> PlatformKind {
PlatformKind::PcFx
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut sec = [0u8; 2048];
let mut matched = false;
for lba in [0, 225] {
if reader.read_sector(lba, &mut sec).is_ok()
&& (sec.starts_with(b"PC-FX")
|| sec.windows(16).any(|w| w.starts_with(b"PC-FX:Hu_CD-ROM")))
{
matched = true;
break;
}
}
if !matched {
return Err(InspectionError::SignatureNotFound);
}
Ok(RawMetadata {
title: None,
game_id: None,
})
}
}
pub struct PcEngineCdInspector;
impl PlatformDiscInspector for PcEngineCdInspector {
fn platform(&self) -> PlatformKind {
PlatformKind::PcEngineCd
}
fn inspect_native(&self, reader: &mut dyn DiscReader) -> Result<RawMetadata, InspectionError> {
let mut sec = [0u8; 2048];
let mut matched = false;
for lba in [0, 225] {
if reader.read_sector(lba, &mut sec).is_ok() {
let has_nec = sec.windows(22).any(|w| {
w == b"NEC Home Electoronics" || w.starts_with(b"NEC Home Electronics")
});
let has_hudson = sec.windows(12).any(|w| {
w.starts_with(&[
0x82, 0xb1, 0x82, 0xcc, 0x83, 0x76, 0x83, 0x8d, 0x83, 0x4f, 0x83, 0x89,
])
});
if has_nec || has_hudson {
matched = true;
break;
}
}
}
if !matched {
return Err(InspectionError::SignatureNotFound);
}
Ok(RawMetadata {
title: None,
game_id: None,
})
}
}
pub fn inspect_metadata(reader: &mut dyn DiscReader, file_path: Option<&Path>) -> DiscMetadata {
let mut metadata = DiscMetadata::default();
let inspectors: [&dyn PlatformDiscInspector; 12] = [
&ThreeDoInspector,
&SegaDreamcastInspector,
&SegaSaturnInspector,
&SegaMegaCdInspector,
&PlayStationPortableInspector,
&PlayStationInspector,
&NintendoInspector,
&XboxInspector,
&AmigaCd32Inspector,
&NeoGeoCdInspector,
&PcFxInspector,
&PcEngineCdInspector,
];
for inspector in &inspectors {
if let Ok(raw) = inspector.inspect_native(reader) {
let mut matched_platform = inspector.platform();
if matched_platform == PlatformKind::PlayStation1 {
if let Some(total) = reader.total_sectors() {
if total > 400_000 {
matched_platform = PlatformKind::PlayStation2;
}
}
}
if matched_platform == PlatformKind::GameCube {
if let Some(total) = reader.total_sectors() {
if total > 1_000_000 {
matched_platform = PlatformKind::Wii;
}
}
}
metadata.platform = matched_platform;
if let Some(title) = raw.title {
let cleaned = clean_ascii_string(title.as_bytes());
if !cleaned.is_empty() {
metadata.title = Some(cleaned);
metadata.title_source = MetadataSource::NativeHeader;
}
}
if let Some(id) = raw.game_id {
let cleaned = clean_ascii_string(id.as_bytes());
if !cleaned.is_empty() {
let normalized = if let Some(gid) = normalize_psx_serial(&cleaned) {
gid.normalized
} else {
cleaned.clone()
};
metadata.game_id = Some(GameId {
raw: cleaned,
normalized,
});
metadata.game_id_source = MetadataSource::NativeHeader;
}
}
break;
}
}
if metadata.title.is_none() {
let mut pvd = [0u8; 2048];
if reader.read_sector(16, &mut pvd).is_ok() && pvd[0] == 0x01 && &pvd[1..6] == b"CD001" {
let vol_id = clean_ascii_string(&pvd[40..72]);
if !vol_id.is_empty() && vol_id != "CD-ROM" {
metadata.title = Some(vol_id);
metadata.title_source = MetadataSource::Iso9660Pvd;
}
}
}
if metadata.title.is_none() {
if let Some(path) = file_path {
if let Some(sanitized) = sanitize_image_basename(path) {
metadata.title = Some(sanitized);
metadata.title_source = MetadataSource::FilenameFallback;
}
}
}
metadata
}