use std::env;
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use disclady::{inspect_disc, DiscDescriptor};
fn main() -> ExitCode {
let args: Vec<String> = env::args().skip(1).collect();
if args.is_empty() {
print_usage();
return ExitCode::FAILURE;
}
let mut json_mode = false;
let mut online_mode = false;
let mut targets = Vec::new();
for arg in &args {
match arg.as_str() {
"-h" | "--help" => {
print_help();
return ExitCode::SUCCESS;
}
"-v" | "--version" => {
println!("disclady {}", env!("CARGO_PKG_VERSION"));
return ExitCode::SUCCESS;
}
"-o" | "--online" => {
online_mode = true;
}
"--drives" | "--list-drives" => {
#[cfg(feature = "physical")]
{
let drives = disclady::list_optical_drives();
if drives.is_empty() {
println!("No optical drives detected.");
} else {
println!("Detected optical drive(s):");
for d in drives {
println!(" {}", d.display());
}
}
return ExitCode::SUCCESS;
}
#[cfg(not(feature = "physical"))]
{
eprintln!("disclady: physical drive detection disabled in this build");
return ExitCode::FAILURE;
}
}
"--json" => {
json_mode = true;
}
other if other.starts_with('-') => {
eprintln!("disclady: unrecognized option '{other}'");
eprintln!("Try 'disclady --help' for more information.");
return ExitCode::FAILURE;
}
_ => {
targets.push(expand_tilde(arg));
}
}
}
if targets.is_empty() {
eprintln!("disclady: missing file or directory operand");
eprintln!("Try 'disclady --help' for more information.");
return ExitCode::FAILURE;
}
let mut any_error = false;
let mut files_to_probe = Vec::new();
for target in &targets {
#[cfg(feature = "physical")]
if disclady::is_physical_disc_path(target) {
files_to_probe.push(target.clone());
continue;
}
if !target.exists() {
eprintln!(
"disclady: cannot access '{}': No such file or directory",
target.display()
);
any_error = true;
continue;
}
if target.is_dir() {
collect_files_recursive(target, &mut files_to_probe);
} else {
files_to_probe.push(target.clone());
}
}
files_to_probe.sort();
files_to_probe.dedup();
#[cfg(feature = "online")]
let online_db = if online_mode {
match disclady::OnlineDatabase::fetch_or_load_cached(None) {
Ok(db) => Some(db),
Err(err) => {
eprintln!("disclady: online database error: {err}");
None
}
}
} else {
None
};
#[cfg(not(feature = "online"))]
if online_mode {
eprintln!("disclady: online matching is disabled in this build");
}
for (idx, path) in files_to_probe.iter().enumerate() {
if idx > 0 && !json_mode {
println!();
}
match inspect_disc(path) {
Ok(desc) => {
#[cfg(feature = "online")]
let online_match = online_db
.as_ref()
.and_then(|db| db.find_best_match(&desc, Some(path)));
if json_mode {
#[cfg(feature = "online")]
print_json(path, &desc, online_mode, online_match.as_ref());
#[cfg(not(feature = "online"))]
print_json(path, &desc);
} else {
#[cfg(feature = "online")]
print_descriptor(path, &desc, online_mode, online_match.as_ref());
#[cfg(not(feature = "online"))]
print_descriptor(path, &desc);
}
}
Err(err) => {
eprintln!("disclady: error inspecting '{}': {err}", path.display());
any_error = true;
}
}
}
if any_error {
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
}
}
fn print_usage() {
println!("Usage: disclady [OPTIONS] <FILE-OR-DIRECTORY>...");
println!("Try 'disclady --help' for more information.");
}
fn print_help() {
println!(
"disclady {} - Optical and Storage Disc Image Inspection Utility",
env!("CARGO_PKG_VERSION")
);
println!();
println!("USAGE:");
println!(" disclady [OPTIONS] <PATH>...");
println!();
println!("ARGS:");
println!(" <PATH>... One or more disc image files, directories, or optical drive paths to inspect");
println!();
println!("OPTIONS:");
println!(" -o, --online Match metadata against online database to suggest filename");
println!(" --json Output raw structured JSON metadata");
println!(" --drives List available optical drive devices");
println!(" -h, --help Print this help information");
println!(" -v, --version Print version information");
println!();
println!("SUPPORTED FORMATS:");
println!(" - Cue Sheets: .cue with .bin / .wav audio tracks");
println!(" - Raw Disc Images: .bin, .img (2048, 2336, 2352, 2448 bytes/sector)");
println!(" - Standard ISO Images: .iso (ISO 9660, UDF, DVD-Video, DVD-Audio)");
println!(" - Dreamcast GD-ROM: .gdi with track binaries");
println!(" - Hard Disk Images: .img, .raw (MBR, GPT, Arcade partitions)");
println!(" - LaserDisc Captures: .avi (uncompressed audio and YUY2/UYVY video)");
println!(" - MAME CHD Containers: .chd (v3, v4, v5 reverse inspection)");
println!(" - Physical Optical Discs: /dev/sr0, /dev/cdrom, D:, \\\\.\\D: (SCSI/MMC)");
}
#[cfg(feature = "online")]
fn print_descriptor(
path: &Path,
desc: &DiscDescriptor,
online_enabled: bool,
online_match: Option<&disclady::OnlineMatch>,
) {
print_descriptor_impl(path, desc, online_enabled, online_match);
}
#[cfg(not(feature = "online"))]
fn print_descriptor(path: &Path, desc: &DiscDescriptor) {
print_descriptor_impl(path, desc);
}
fn print_descriptor_impl(
path: &Path,
desc: &DiscDescriptor,
#[cfg(feature = "online")] online_enabled: bool,
#[cfg(feature = "online")] online_match: Option<&disclady::OnlineMatch>,
) {
let file_size_str = fs::metadata(path)
.ok()
.filter(|m| m.len() > 0)
.map(|m| format_bytes(m.len()))
.or_else(|| desc.total_size_bytes.map(format_bytes))
.unwrap_or_else(|| "Unknown".to_string());
println!("================================================================================");
println!("File: {}", path.display());
println!("File Size: {file_size_str}");
println!("================================================================================");
println!("Classification:");
println!(" Media Type: {}", desc.disc_type);
println!(" Confidence: {}", desc.confidence);
if desc.primary_sector_size > 0 {
println!(" Primary Sector Size: {} bytes", desc.primary_sector_size);
}
if let Some(sectors) = desc.total_sectors {
println!(" Total Sectors: {}", format_number(sectors));
}
if let Some(bytes) = desc.total_size_bytes {
println!(" Total Calculated: {}", format_bytes(bytes));
}
if let Some(ref vol) = desc.volume_info {
println!();
println!("Filesystem & Volume Info:");
#[cfg(feature = "online")]
if online_enabled {
if let Some(m) = online_match {
println!(" Suggested Filename: {}", m.suggested_filename);
println!(" Matched Game: {} [{}]", m.clean_title, m.db_serial);
} else {
println!(" Suggested Filename: [No match in database]");
}
}
if let Some(ref title) = vol.title {
println!(" Title: {title}");
}
if let Some(ref disc_id) = vol.disc_id {
println!(" Disc ID / Serial: {disc_id}");
}
if let Some(ref platform) = vol.platform {
println!(" Identified Platform: {platform}");
}
if let Some(ref id) = vol.volume_identifier {
println!(" Volume Identifier: {id}");
}
if let Some(ref sys) = vol.system_identifier {
println!(" System Identifier: {sys}");
}
if let Some(ref set) = vol.volume_set_identifier {
println!(" Volume Set: {set}");
}
if let Some(ref pub_id) = vol.publisher_identifier {
println!(" Publisher: {pub_id}");
}
if let Some(ref app_id) = vol.application_identifier {
println!(" Application: {app_id}");
}
if let Some(sectors) = vol.volume_space_size {
println!(" Volume Space Size: {} sectors", format_number(sectors));
}
if let Some(block_size) = vol.logical_block_size {
println!(" Logical Block Size: {} bytes", block_size);
}
println!(" ISO 9660: {}", vol.has_iso9660);
println!(" UDF: {}", vol.has_udf);
if vol.has_dvd_video {
println!(" DVD-Video (VIDEO_TS): true");
}
if vol.has_dvd_audio {
println!(" DVD-Audio (AUDIO_TS): true");
}
}
#[cfg(feature = "online")]
if online_enabled && desc.volume_info.is_none() {
println!();
println!("Database Match:");
if let Some(m) = online_match {
println!(" Suggested Filename: {}", m.suggested_filename);
println!(" Matched Game: {} [{}]", m.clean_title, m.db_serial);
} else {
println!(" Suggested Filename: [No match in database]");
}
}
if let Some(ref chd) = desc.chd_plan {
println!();
println!("CHD Container:");
println!(" CHD Version: v{}", chd.chd_version);
if let Some(ref tag) = chd.tag {
println!(" Metadata Tag: {tag}");
}
println!(" Logical Bytes: {}", format_bytes(chd.logical_bytes));
println!(
" Hunk Size: {} bytes",
format_number(u64::from(chd.hunk_bytes))
);
println!(
" Unit Size: {} bytes",
format_number(u64::from(chd.unit_bytes))
);
println!(" Target Operation: {}", chd.command);
if let Some(desc_ext) = chd.descriptor_ext {
println!(" Default Descriptor: .{desc_ext}");
}
println!(" Default Payload: .{}", chd.payload_ext);
}
if !desc.tracks.is_empty() {
println!();
println!("Track Layout ({} tracks):", desc.tracks.len());
println!(
" {:<4} {:<12} {:<11} {:<12} {:<10} {:<8} File",
"Trk", "Type", "Sector Size", "Start LBA", "Sectors", "Pregap"
);
println!(
" {:<4} {:<12} {:<11} {:<12} {:<10} {:<8} ----",
"---", "----", "-----------", "---------", "-------", "------"
);
for t in &desc.tracks {
let sectors_str = t
.sector_count
.map(format_number)
.unwrap_or_else(|| "-".to_string());
let pregap_str = t
.pregap_sectors
.map(|p| format_number(u64::from(p)))
.unwrap_or_else(|| "-".to_string());
let file_str = t
.file_path
.as_ref()
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| "-".to_string());
println!(
" {:02} {:<12} {:<11} {:<12} {:<10} {:<8} {}",
t.track_number,
format!("{}", t.track_type),
format!("{} B", t.sector_size),
format_number(t.start_lba),
sectors_str,
pregap_str,
file_str
);
}
}
println!();
println!("Diagnostic Verdict:");
println!(" {}", desc.summary);
println!("================================================================================");
}
#[cfg(feature = "online")]
fn print_json(
path: &Path,
desc: &DiscDescriptor,
online_enabled: bool,
online_match: Option<&disclady::OnlineMatch>,
) {
print_json_impl(path, desc, online_enabled, online_match);
}
#[cfg(not(feature = "online"))]
fn print_json(path: &Path, desc: &DiscDescriptor) {
print_json_impl(path, desc);
}
fn print_json_impl(
path: &Path,
desc: &DiscDescriptor,
#[cfg(feature = "online")] online_enabled: bool,
#[cfg(feature = "online")] online_match: Option<&disclady::OnlineMatch>,
) {
let file_size = fs::metadata(path)
.ok()
.filter(|m| m.len() > 0)
.map(|m| m.len())
.or(desc.total_size_bytes);
println!("{{");
println!(
" \"file\": {},",
json_escape(path.to_string_lossy().as_ref())
);
if let Some(size) = file_size {
println!(" \"file_size_bytes\": {size},");
}
println!(
" \"disc_type\": {},",
json_escape(&desc.disc_type.to_string())
);
println!(
" \"confidence\": {},",
json_escape(&desc.confidence.to_string())
);
println!(" \"primary_sector_size\": {},", desc.primary_sector_size);
if let Some(sectors) = desc.total_sectors {
println!(" \"total_sectors\": {sectors},");
}
if let Some(bytes) = desc.total_size_bytes {
println!(" \"total_size_bytes\": {bytes},");
}
println!(" \"summary\": {},", json_escape(&desc.summary));
#[cfg(feature = "online")]
if online_enabled {
if let Some(m) = online_match {
println!(
" \"suggested_filename\": {},",
json_escape(&m.suggested_filename)
);
println!(" \"matched_game\": {},", json_escape(&m.clean_title));
println!(" \"matched_serial\": {},", json_escape(&m.db_serial));
println!(" \"match_score\": {},", m.score);
} else {
println!(" \"suggested_filename\": null,");
println!(" \"matched_game\": null,");
println!(" \"matched_serial\": null,");
println!(" \"match_score\": null,");
}
}
if let Some(ref vol) = desc.volume_info {
println!(" \"volume_info\": {{");
if let Some(ref title) = vol.title {
println!(" \"title\": {},", json_escape(title));
}
if let Some(ref disc_id) = vol.disc_id {
println!(" \"disc_id\": {},", json_escape(disc_id));
}
if let Some(ref p) = vol.platform {
println!(" \"platform\": {},", json_escape(&p.to_string()));
}
if let Some(ref id) = vol.volume_identifier {
println!(" \"volume_identifier\": {},", json_escape(id));
}
if let Some(ref sys) = vol.system_identifier {
println!(" \"system_identifier\": {},", json_escape(sys));
}
if let Some(ref set) = vol.volume_set_identifier {
println!(" \"volume_set_identifier\": {},", json_escape(set));
}
if let Some(ref pub_id) = vol.publisher_identifier {
println!(" \"publisher_identifier\": {},", json_escape(pub_id));
}
if let Some(ref app_id) = vol.application_identifier {
println!(" \"application_identifier\": {},", json_escape(app_id));
}
if let Some(s) = vol.volume_space_size {
println!(" \"volume_space_size\": {s},");
}
if let Some(b) = vol.logical_block_size {
println!(" \"logical_block_size\": {b},");
}
println!(" \"has_iso9660\": {},", vol.has_iso9660);
println!(" \"has_udf\": {},", vol.has_udf);
println!(" \"has_dvd_video\": {},", vol.has_dvd_video);
println!(" \"has_dvd_audio\": {}", vol.has_dvd_audio);
println!(" }},");
}
if let Some(ref chd) = desc.chd_plan {
println!(" \"chd_plan\": {{");
println!(" \"version\": {},", chd.chd_version);
if let Some(ref tag) = chd.tag {
println!(" \"tag\": {},", json_escape(tag));
}
println!(" \"logical_bytes\": {},", chd.logical_bytes);
println!(" \"hunk_bytes\": {},", chd.hunk_bytes);
println!(" \"unit_bytes\": {},", chd.unit_bytes);
println!(" \"command\": {},", json_escape(chd.command));
if let Some(ext) = chd.descriptor_ext {
println!(" \"descriptor_ext\": {},", json_escape(ext));
}
println!(" \"payload_ext\": {}", json_escape(chd.payload_ext));
println!(" }},");
}
println!(" \"tracks\": [");
for (i, t) in desc.tracks.iter().enumerate() {
let is_last = i + 1 == desc.tracks.len();
println!(" {{");
println!(" \"track_number\": {},", t.track_number);
println!(
" \"track_type\": {},",
json_escape(&t.track_type.to_string())
);
println!(" \"sector_size\": {},", t.sector_size);
println!(" \"start_lba\": {},", t.start_lba);
if let Some(s) = t.sector_count {
println!(" \"sector_count\": {s},");
}
if let Some(p) = t.pregap_sectors {
println!(" \"pregap_sectors\": {p},");
}
if let Some(ref f) = t.file_path {
println!(
" \"file_path\": {},",
json_escape(&f.to_string_lossy())
);
}
println!(
" \"is_audio\": {}",
t.track_type == disclady::TrackType::Audio
);
print!(" }}");
if is_last {
println!();
} else {
println!(",");
}
}
println!(" ]");
println!("}}");
}
fn json_escape(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\u{08}' => out.push_str("\\b"),
'\u{0c}' => out.push_str("\\f"),
c if c < ' ' => {
let _ = write!(out, "\\u{:04x}", c as u32);
}
c => out.push(c),
}
}
out.push('"');
out
}
fn format_bytes(bytes: u64) -> String {
let num_str = format_number(bytes);
if bytes < 1024 {
format!("{num_str} bytes")
} else if bytes < 1024 * 1024 {
let kib = bytes as f64 / 1024.0;
format!("{num_str} bytes ({kib:.2} KiB)")
} else if bytes < 1024 * 1024 * 1024 {
let mib = bytes as f64 / (1024.0 * 1024.0);
format!("{num_str} bytes ({mib:.2} MiB)")
} else {
let gib = bytes as f64 / (1024.0 * 1024.0 * 1024.0);
format!("{num_str} bytes ({gib:.2} GiB)")
}
}
fn format_number(n: u64) -> String {
let s = n.to_string();
let mut result = String::with_capacity(s.len() + s.len() / 3);
let offset = s.len() % 3;
for (i, ch) in s.chars().enumerate() {
if i > 0 && (i % 3 == offset || (offset == 0 && i % 3 == 0)) {
result.push(',');
}
result.push(ch);
}
result
}
fn collect_files_recursive(dir: &Path, files: &mut Vec<PathBuf>) {
if let Ok(read_dir) = fs::read_dir(dir) {
for entry in read_dir.flatten() {
let Ok(file_type) = entry.file_type() else {
continue;
};
if file_type.is_dir() {
collect_files_recursive(&entry.path(), files);
} else if file_type.is_file() {
files.push(entry.path());
}
}
}
}
fn expand_tilde(path_str: &str) -> PathBuf {
if path_str == "~" {
if let Ok(home) = env::var("HOME") {
return PathBuf::from(home);
}
} else if let Some(rest) = path_str.strip_prefix("~/") {
if let Ok(home) = env::var("HOME") {
return PathBuf::from(home).join(rest);
}
}
PathBuf::from(path_str)
}