use crate::types::{DiscType, Platform};
use std::io::{Read, Seek, SeekFrom};
pub const NINTENDO_DISC_MAGIC: [u8; 4] = [0x5D, 0x1C, 0x9E, 0xA3];
pub const XDVDFS_MAGIC: [u8; 20] = *b"MICROSOFT*XBOX*MEDIA";
pub const DREAMCAST_MAGIC: [u8; 16] = *b"SEGA SEGAKATANA ";
pub const SATURN_MAGIC: [u8; 16] = *b"SEGA SEGASATURN ";
pub const MEGACD_MAGIC: [u8; 15] = *b"SEGADISCSYSTEM ";
pub const THREEDO_MAGIC: [u8; 7] = [0x01, b'Z', b'Z', b'Z', b'Z', b'Z', 0x01];
pub(crate) fn clean_console_string(bytes: &[u8]) -> String {
let s = String::from_utf8_lossy(bytes);
s.trim_matches(|c: char| c.is_whitespace() || c == '\0')
.to_string()
}
pub(crate) fn extract_nintendo_metadata(header: &[u8]) -> (Option<String>, Option<String>) {
let disc_id = if header.len() >= 6 {
let code = &header[0..6];
if code.iter().all(|&b| b.is_ascii_graphic()) {
Some(String::from_utf8_lossy(code).to_string())
} else {
None
}
} else {
None
};
let title = if header.len() >= 0x60 {
let t = clean_console_string(&header[0x20..0x60]);
if !t.is_empty() {
Some(t)
} else {
None
}
} else {
None
};
(disc_id, title)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct DreamcastMetadata {
pub disc_id: Option<String>,
pub title: Option<String>,
pub publisher: Option<String>,
pub boot_file: Option<String>,
}
pub(crate) fn extract_dreamcast_full_metadata(header: &[u8]) -> DreamcastMetadata {
let mut meta = DreamcastMetadata::default();
if header.len() < 0x4A {
return meta;
}
let id = clean_console_string(&header[0x40..0x4A]);
if !id.is_empty() {
meta.disc_id = Some(id);
} else if header.len() >= 0x50 {
let id = clean_console_string(&header[0x40..0x50]);
if !id.is_empty() {
meta.disc_id = Some(id);
}
}
if header.len() >= 0x20 {
let pub_id = clean_console_string(&header[0x10..0x20]);
if !pub_id.is_empty() {
meta.publisher = Some(pub_id);
}
}
if header.len() >= 0x70 {
let boot = clean_console_string(&header[0x60..0x70]);
if !boot.is_empty() {
meta.boot_file = Some(boot);
}
}
if header.len() >= 0x80 {
let max_end = header.len().min(0x100);
let t = clean_console_string(&header[0x80..max_end]);
if !t.is_empty() {
meta.title = Some(t);
}
}
meta
}
pub(crate) fn extract_saturn_metadata(header: &[u8]) -> (Option<String>, Option<String>) {
let disc_id = if header.len() >= 0x30 {
let id = clean_console_string(&header[0x20..0x30]);
if !id.is_empty() {
Some(id)
} else {
None
}
} else {
None
};
let title = if header.len() >= 0x80 {
let t = clean_console_string(&header[0x60..0x80]);
if !t.is_empty() {
Some(t)
} else {
None
}
} else {
None
};
(disc_id, title)
}
pub(crate) fn extract_megacd_metadata(header: &[u8]) -> (Option<String>, Option<String>) {
let title = if header.len() >= 0x150 {
let t = clean_console_string(&header[0x120..0x150]);
if !t.is_empty() {
Some(t)
} else if header.len() >= 0x180 {
let domestic = clean_console_string(&header[0x150..0x180]);
if !domestic.is_empty() {
Some(domestic)
} else {
None
}
} else {
None
}
} else {
None
};
let disc_id = if header.len() >= 0x190 {
let id = clean_console_string(&header[0x180..0x190]);
if !id.is_empty() {
Some(id)
} else {
None
}
} else {
None
};
(disc_id, title)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct ThreeDoMetadata {
pub disc_id: Option<String>,
pub volume_identifier: Option<String>,
pub commentary: Option<String>,
pub block_size: u32,
pub block_count: u32,
pub root_unique_id: Option<String>,
pub root_block_count: u32,
}
pub(crate) fn extract_3do_metadata(header: &[u8]) -> Option<ThreeDoMetadata> {
if header.len() < 100 || !header.starts_with(&THREEDO_MAGIC) {
return None;
}
let com = clean_console_string(&header[8..40]);
let commentary = if !com.is_empty() { Some(com) } else { None };
let vol_id = clean_console_string(&header[40..72]);
let volume_identifier = if !vol_id.is_empty() {
Some(vol_id)
} else {
None
};
let vol_unique_id = u32::from_be_bytes(header[72..76].try_into().ok()?);
let block_size = u32::from_be_bytes(header[76..80].try_into().ok()?);
let block_count = u32::from_be_bytes(header[80..84].try_into().ok()?);
let root_unique_id = u32::from_be_bytes(header[84..88].try_into().ok()?);
let root_block_count = u32::from_be_bytes(header[88..92].try_into().ok()?);
Some(ThreeDoMetadata {
disc_id: Some(format!("{vol_unique_id:08X}")),
volume_identifier,
commentary,
block_size,
block_count,
root_unique_id: Some(format!("{root_unique_id:08X}")),
root_block_count,
})
}
pub(crate) fn parse_ps_serial(name_bytes: &[u8]) -> Option<String> {
let clean = if let Some(pos) = name_bytes.iter().position(|&b| b == b';') {
&name_bytes[..pos]
} else {
name_bytes
};
if clean.len() == 11
&& clean[0..4].iter().all(u8::is_ascii_alphabetic)
&& clean[4] == b'_'
&& clean[5..8].iter().all(u8::is_ascii_digit)
&& clean[8] == b'.'
&& clean[9..11].iter().all(u8::is_ascii_digit)
{
let prefix = std::str::from_utf8(&clean[0..4]).ok()?.to_ascii_uppercase();
let num1 = std::str::from_utf8(&clean[5..8]).ok()?;
let num2 = std::str::from_utf8(&clean[9..11]).ok()?;
return Some(format!("{prefix}-{num1}{num2}"));
}
if clean.len() == 10
&& clean[0..4].iter().all(u8::is_ascii_alphabetic)
&& (clean[4] == b'_' || clean[4] == b'-')
&& clean[5..10].iter().all(u8::is_ascii_digit)
{
let prefix = std::str::from_utf8(&clean[0..4]).ok()?.to_ascii_uppercase();
let num = std::str::from_utf8(&clean[5..10]).ok()?;
return Some(format!("{prefix}-{num}"));
}
None
}
pub(crate) fn parse_ps_serial_from_system_cnf(cnf_content: &[u8]) -> Option<String> {
let text = String::from_utf8_lossy(cnf_content);
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(serial) = parse_ps_serial(part.as_bytes()) {
return Some(serial);
}
}
}
}
None
}
pub(crate) fn scan_root_dir_for_ps_serial(dir_buf: &[u8]) -> Option<String> {
let mut pos = 0;
while pos < dir_buf.len() {
let len = dir_buf[pos] as usize;
if len == 0 {
pos = (pos + 2048) / 2048 * 2048;
continue;
}
if pos + len > dir_buf.len() || len < 33 {
break;
}
let name_len = dir_buf[pos + 32] as usize;
if pos + 33 + name_len <= dir_buf.len() {
let name_bytes = &dir_buf[pos + 33..pos + 33 + name_len];
if let Some(serial) = parse_ps_serial(name_bytes) {
return Some(serial);
}
}
pos += len;
}
None
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ConsoleSignatureMatch {
pub disc_type: DiscType,
pub platform: Platform,
pub description: &'static str,
pub disc_id: Option<String>,
pub title: Option<String>,
pub publisher: Option<String>,
pub boot_file: Option<String>,
pub volume_identifier: Option<String>,
pub system_identifier: Option<String>,
pub volume_space_size: Option<u64>,
pub logical_block_size: Option<u32>,
}
pub(crate) fn inspect_console_signatures<R: Read + Seek>(
reader: &mut R,
file_size: u64,
) -> Option<ConsoleSignatureMatch> {
let mut header = [0u8; 512];
if reader.seek(SeekFrom::Start(0)).is_ok() && reader.read_exact(&mut header).is_ok() {
let payload = if header.starts_with(&crate::raw::CD_SYNC_PATTERN) {
&header[16..]
} else {
&header[..]
};
if payload.len() >= 0x1C && payload[0x18..0x1C] == NINTENDO_DISC_MAGIC {
let (disc_id, title) = extract_nintendo_metadata(payload);
let is_wii = file_size > 2_000_000_000;
return Some(ConsoleSignatureMatch {
disc_type: DiscType::Dvd,
platform: if is_wii {
Platform::Wii
} else {
Platform::GameCube
},
description: if is_wii {
"Nintendo Wii optical disc"
} else {
"Nintendo GameCube optical disc"
},
disc_id,
title,
publisher: None,
boot_file: None,
volume_identifier: None,
system_identifier: Some("Nintendo Optical Disc".to_string()),
volume_space_size: None,
logical_block_size: Some(2048),
});
}
if payload.starts_with(&DREAMCAST_MAGIC) {
let dc_meta = extract_dreamcast_full_metadata(payload);
let is_gdrom =
payload.len() >= 0x30 && payload[0x20..0x30].windows(6).any(|w| w == b"GD-ROM");
return Some(ConsoleSignatureMatch {
disc_type: if is_gdrom {
DiscType::Gdi
} else {
DiscType::Cd
},
platform: Platform::Dreamcast,
description: if is_gdrom {
"Sega Dreamcast GD-ROM"
} else {
"Sega Dreamcast MIL-CD"
},
disc_id: dc_meta.disc_id,
title: dc_meta.title,
publisher: dc_meta.publisher,
boot_file: dc_meta.boot_file,
volume_identifier: None,
system_identifier: Some("SEGA SEGAKATANA".to_string()),
volume_space_size: None,
logical_block_size: Some(2048),
});
}
if payload.starts_with(&SATURN_MAGIC) {
let (disc_id, title) = extract_saturn_metadata(payload);
return Some(ConsoleSignatureMatch {
disc_type: DiscType::Cd,
platform: Platform::SegaSaturn,
description: "Sega Saturn CD",
disc_id,
title,
publisher: None,
boot_file: None,
volume_identifier: None,
system_identifier: Some("SEGA SEGASATURN".to_string()),
volume_space_size: None,
logical_block_size: Some(2048),
});
}
if payload.starts_with(&MEGACD_MAGIC) {
let (disc_id, title) = extract_megacd_metadata(payload);
return Some(ConsoleSignatureMatch {
disc_type: DiscType::Cd,
platform: Platform::MegaCd,
description: "Sega Mega-CD / Sega CD",
disc_id,
title,
publisher: None,
boot_file: None,
volume_identifier: None,
system_identifier: Some("SEGA MEGA DRIVE / SEGA CD".to_string()),
volume_space_size: None,
logical_block_size: Some(2048),
});
}
if payload.starts_with(&THREEDO_MAGIC) {
if let Some(td_meta) = extract_3do_metadata(payload) {
let title = if td_meta.volume_identifier.as_deref() != Some("CD-ROM") {
td_meta.volume_identifier.clone()
} else {
None
};
return Some(ConsoleSignatureMatch {
disc_type: DiscType::Cd,
platform: Platform::ThreeDo,
description: "3DO Interactive Multiplayer disc",
disc_id: td_meta.disc_id,
title,
publisher: None,
boot_file: None,
volume_identifier: td_meta.volume_identifier,
system_identifier: Some("3DO Opera File System".to_string()),
volume_space_size: Some(td_meta.block_count as u64),
logical_block_size: Some(td_meta.block_size),
});
}
}
}
if file_size >= 0x10000 + 20 {
let mut xdvdfs_buf = [0u8; 20];
if reader.seek(SeekFrom::Start(0x10000)).is_ok()
&& reader.read_exact(&mut xdvdfs_buf).is_ok()
&& xdvdfs_buf == XDVDFS_MAGIC
{
return Some(ConsoleSignatureMatch {
disc_type: DiscType::Dvd,
platform: Platform::Xbox,
description: "Microsoft Xbox DVD",
disc_id: None,
title: None,
publisher: None,
boot_file: None,
volume_identifier: None,
system_identifier: Some("MICROSOFT*XBOX*MEDIA".to_string()),
volume_space_size: None,
logical_block_size: Some(2048),
});
}
}
None
}