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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//! Core detection engine and heuristics dispatcher.

use std::fs::File;
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::path::Path;

use crate::ccd::inspect_ccd;
use crate::chd::inspect_chd;
use crate::console::inspect_console_signatures;
use crate::cue::inspect_cue;
use crate::gdi::inspect_gdi;
use crate::harddisk::inspect_harddisk;
use crate::iso::{
    check_udf_avdp, parse_iso_pvd, scan_root_directory, scan_volume_recognition_sequence,
};
use crate::laserdisc::inspect_laserdisc;
use crate::mds::inspect_mds;
use crate::metadata::DiscReader;
use crate::nrg::{detect_nrg_from_reader, inspect_nrg, MAGIC_NER5, MAGIC_NERO};
use crate::raw::{detect_raw_cd_sector_size, inspect_raw_sector_mode};
use crate::types::{
    Confidence, DiscDescriptor, DiscError, DiscType, Platform, TrackDescriptor, TrackType,
    VolumeInfo,
};

/// 900 MiB threshold in bytes; any optical image exceeding this cannot physically be a standard CD.
pub const CD_MAX_PHYSICAL_BYTES: u64 = 900 * 1024 * 1024;

/// Minimum possible size for a hard disk sector (512 bytes).
pub const MIN_STORAGE_SECTOR_SIZE: u64 = 512;

/// Examines an image file and returns its detected [`DiscType`].
///
/// # Errors
///
/// Returns [`DiscError::InvalidPath`] if the path does not exist,
/// or [`DiscError::Io`] if reading fails.
///
/// # Examples
///
/// ```no_run
/// use disclady::{detect_disc_type, DiscType};
/// use std::path::Path;
///
/// let disc_type = detect_disc_type(Path::new("game.iso"))?;
/// println!("Media type: {disc_type}");
/// # Ok::<(), disclady::DiscError>(())
/// ```
pub fn detect_disc_type<P: AsRef<Path>>(path: P) -> Result<DiscType, DiscError> {
    inspect_disc(path).map(|desc| desc.disc_type)
}

/// Inspects an image file and returns a detailed [`DiscDescriptor`].
///
/// Evaluates headers, sector layout, partition tables, and filesystem descriptors.
///
/// # Errors
///
/// Returns [`DiscError::InvalidPath`] if the path does not exist,
/// or [`DiscError::Io`] if reading fails.
///
/// # Examples
///
/// ```no_run
/// use disclady::inspect_disc;
/// use std::path::Path;
///
/// let descriptor = inspect_disc(Path::new("game.cue"))?;
/// println!("Tracks found: {}", descriptor.tracks.len());
/// # Ok::<(), disclady::DiscError>(())
/// ```
pub fn inspect_disc<P: AsRef<Path>>(path: P) -> Result<DiscDescriptor, DiscError> {
    let p = path.as_ref();
    #[cfg(feature = "physical")]
    if crate::physical::is_physical_disc_path(p) {
        return crate::physical::inspect_physical_disc(p);
    }

    if !p.exists() {
        return Err(DiscError::InvalidPath(p.to_path_buf()));
    }
    if !p.is_file() {
        return Ok(DiscDescriptor::unknown(format!(
            "Path '{}' is not a regular file",
            p.display()
        )));
    }

    let ext = p
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();

    match ext.as_str() {
        "gdi" => inspect_gdi(p),
        "cue" => inspect_cue(p),
        "ccd" => inspect_ccd(p),
        "mds" => inspect_mds(p),
        "mdx" => crate::mdx::inspect_mdx(p),
        "nrg" => inspect_nrg(p),
        _ => {
            let file = File::open(p)?;
            let meta = file.metadata()?;
            let file_size = meta.len();
            let mut reader = BufReader::new(file);

            let mut desc = detect_disc_from_reader(&mut reader, file_size, Some(&ext))?;
            if let Some(ref mut vol) = desc.volume_info {
                if vol.title.is_none() && vol.platform.is_some() {
                    if let Some(stem) = p.file_stem().and_then(|s| s.to_str()) {
                        let lower = stem.to_ascii_lowercase();
                        if !lower.starts_with("track") && !lower.starts_with("image") {
                            vol.title = Some(stem.to_string());
                            if let Some(plat) = vol.platform {
                                let id_str = vol
                                    .disc_id
                                    .as_deref()
                                    .map(|id| format!(" [{id}]"))
                                    .unwrap_or_default();
                                desc.summary = format!("{plat} disc{id_str} \"{stem}\"");
                            }
                        }
                    }
                }
            }
            Ok(desc)
        }
    }
}

/// Inspects a disc or storage image from a seekable byte stream.
///
/// An optional file extension hint (such as `"cue"`, `"iso"`, or `"chd"`) can be
/// passed to help prioritize appropriate format decoders.
///
/// # Examples
///
/// ```
/// use disclady::{detect_disc_from_reader, DiscType};
/// use std::io::Cursor;
///
/// let mut cursor = Cursor::new(Vec::new());
/// let desc = detect_disc_from_reader(&mut cursor, 0, None).unwrap();
/// assert_eq!(desc.disc_type, DiscType::Unknown);
/// ```
pub fn detect_disc_from_reader<R: Read + Seek>(
    reader: &mut R,
    file_size: u64,
    hint_ext: Option<&str>,
) -> Result<DiscDescriptor, DiscError> {
    if file_size == 0 {
        return Ok(DiscDescriptor::unknown("Image file is empty (0 bytes)"));
    }

    // Early triage: detect CHD container (Compressed Hunks of Data)
    if file_size >= 16 && reader.seek(SeekFrom::Start(0)).is_ok() {
        let mut magic = [0u8; 8];
        if reader.read_exact(&mut magic).is_ok() && &magic == crate::chd::CHD_SIGNATURE {
            return inspect_chd(reader, file_size);
        }
    }

    if file_size < MIN_STORAGE_SECTOR_SIZE {
        return Ok(DiscDescriptor::unknown(format!(
            "File size ({} bytes) is smaller than the minimum storage sector ({} bytes)",
            file_size, MIN_STORAGE_SECTOR_SIZE
        )));
    }

    // Early triage: detect RIFF AVI container (LaserDisc video capture)
    if file_size >= 12 && reader.seek(SeekFrom::Start(0)).is_ok() {
        let mut riff_head = [0u8; 12];
        if reader.read_exact(&mut riff_head).is_ok()
            && &riff_head[0..4] == b"RIFF"
            && &riff_head[8..12] == b"AVI "
        {
            if let Some(desc) = inspect_laserdisc(reader, file_size) {
                return Ok(desc);
            } else {
                return Ok(DiscDescriptor::unknown(
                    "Unrecognized media: AVI file contains no video streams for LaserDisc emulation",
                ));
            }
        }
    }

    // Early triage: detect Alcohol 120% MDS descriptor
    if file_size >= 80 && reader.seek(SeekFrom::Start(0)).is_ok() {
        let mut mds_magic = [0u8; 16];
        if reader.read_exact(&mut mds_magic).is_ok() && &mds_magic == crate::mds::MDS_MAGIC {
            let mut full_data = Vec::with_capacity(file_size.min(1024 * 1024) as usize);
            if reader.seek(SeekFrom::Start(0)).is_ok()
                && reader.take(1024 * 1024).read_to_end(&mut full_data).is_ok()
            {
                let is_mdx = hint_ext.is_some_and(|e| e.eq_ignore_ascii_case("mdx"));
                let mut desc = crate::mds::parse_mds_descriptor(&full_data, None, None);
                if is_mdx {
                    desc.summary = format!(
                        "DAEMON Tools disc container (.mdx): {} medium with {} track(s)",
                        if desc.disc_type == DiscType::Dvd {
                            "DVD"
                        } else {
                            "CD"
                        },
                        desc.tracks.len()
                    );
                }
                return Ok(desc);
            }
        }
    }

    // Early triage: detect Nero Burning ROM (.nrg) container
    if file_size >= 12 && reader.seek(SeekFrom::End(-12)).is_ok() {
        let mut tail12 = [0u8; 12];
        if reader.read_exact(&mut tail12).is_ok()
            && (tail12[0..4] == MAGIC_NER5 || tail12[4..8] == MAGIC_NERO)
        {
            return detect_nrg_from_reader(reader, file_size);
        }
    }

    if let Some(sector_size) = detect_raw_cd_sector_size(reader, file_size) {
        let total_sectors = file_size / (sector_size as u64);
        let mut volume_info = None;

        let lba16_start = 16u64 * (sector_size as u64);
        if file_size >= lba16_start + (sector_size as u64)
            && reader.seek(SeekFrom::Start(lba16_start)).is_ok()
        {
            let mut sec16 = vec![0u8; sector_size as usize];
            if reader.read_exact(&mut sec16).is_ok() {
                if let Some(user_data) = crate::raw::extract_cd_user_data(&sec16) {
                    if let Some(mut vol) = parse_iso_pvd(user_data) {
                        let is_ps = vol
                            .system_identifier
                            .as_deref()
                            .map(|s| s.contains("PLAYSTATION"))
                            .unwrap_or(false);
                        if is_ps {
                            vol.platform = Some(Platform::PlayStation1);

                            let root_record = &user_data[156..190];
                            let root_lba = u32::from_le_bytes(
                                root_record[2..6].try_into().unwrap_or_default(),
                            ) as u64;
                            let root_start = root_lba * (sector_size as u64);
                            if file_size >= root_start + (sector_size as u64)
                                && reader.seek(SeekFrom::Start(root_start)).is_ok()
                            {
                                let mut root_sec = vec![0u8; sector_size as usize];
                                if reader.read_exact(&mut root_sec).is_ok() {
                                    if let Some(root_data) =
                                        crate::raw::extract_cd_user_data(&root_sec)
                                    {
                                        if let Some(serial) =
                                            crate::console::scan_root_dir_for_ps_serial(root_data)
                                        {
                                            vol.disc_id = Some(serial);
                                        }
                                    }
                                }
                            }
                        }
                        volume_info = Some(Box::new(vol));
                    }
                }
            }
        }

        if file_size >= (sector_size as u64) {
            let mut disc_reader =
                crate::metadata::StreamDiscReader::new(&mut *reader, sector_size, file_size);
            let meta = crate::metadata::inspect_metadata(&mut disc_reader, None);
            if meta.platform != crate::metadata::PlatformKind::Unknown
                || meta.title.is_some()
                || meta.game_id.is_some()
            {
                let mut vol = volume_info.map(|v| *v).unwrap_or_default();
                meta.apply_to_volume_info(&mut vol);
                if vol.system_identifier.is_none() {
                    vol.system_identifier = match meta.platform {
                        crate::metadata::PlatformKind::ThreeDo => {
                            Some("3DO Opera File System".to_string())
                        }
                        crate::metadata::PlatformKind::SegaDreamcast => {
                            Some("SEGA SEGAKATANA".to_string())
                        }
                        crate::metadata::PlatformKind::SegaSaturn => {
                            Some("SEGA SEGASATURN".to_string())
                        }
                        crate::metadata::PlatformKind::SegaMegaCd => {
                            Some("SEGA MEGA DRIVE / SEGA CD".to_string())
                        }
                        _ => None,
                    };
                }
                if meta.platform == crate::metadata::PlatformKind::ThreeDo {
                    let mut sec0 = [0u8; 2048];
                    if disc_reader.read_sector(0, &mut sec0).is_ok() {
                        let block_size =
                            u32::from_be_bytes(sec0[76..80].try_into().unwrap_or_default());
                        let block_count =
                            u32::from_be_bytes(sec0[80..84].try_into().unwrap_or_default());
                        if block_size > 0 {
                            vol.logical_block_size = Some(block_size);
                        }
                        if block_count > 0 {
                            vol.volume_space_size = Some(block_count as u64);
                        }
                        let label = crate::metadata::clean_ascii_string(&sec0[40..72]);
                        if !label.is_empty() {
                            vol.volume_identifier = Some(label);
                        }
                    }
                }
                volume_info = Some(Box::new(vol));
            }
        }

        let track_type = if sector_size == 2448 {
            TrackType::Audio
        } else {
            let mut sec_hdr = [0u8; 16];
            let mode = if reader.seek(SeekFrom::Start(0)).is_ok()
                && reader.read_exact(&mut sec_hdr).is_ok()
            {
                inspect_raw_sector_mode(&sec_hdr)
            } else {
                None
            };

            let mode = mode.or_else(|| {
                if file_size >= 17 * 2352
                    && reader.seek(SeekFrom::Start(16 * 2352)).is_ok()
                    && reader.read_exact(&mut sec_hdr).is_ok()
                {
                    inspect_raw_sector_mode(&sec_hdr)
                } else {
                    None
                }
            });

            mode.unwrap_or(TrackType::Mode1_2352)
        };

        let tracks = vec![TrackDescriptor {
            track_number: 1,
            track_type,
            sector_size,
            start_lba: 0,
            sector_count: Some(total_sectors),
            file_path: None,
            pregap_sectors: None,
        }];

        let mut summary = format!(
            "Raw CD image with {} bytes/sector identified by Red Book sync pattern",
            sector_size
        );
        if let Some(ref vol) = volume_info {
            if let Some(plat) = vol.platform {
                let id_str = vol
                    .disc_id
                    .as_deref()
                    .map(|id| format!(" [{id}]"))
                    .unwrap_or_default();
                let title_str = vol
                    .title
                    .as_deref()
                    .map(|t| format!(" \"{t}\""))
                    .unwrap_or_default();
                summary = format!("{plat} disc{id_str}{title_str} ({summary})");
            }
        }

        return Ok(DiscDescriptor {
            disc_type: DiscType::Cd,
            confidence: Confidence::Definitive,
            primary_sector_size: sector_size,
            total_sectors: Some(total_sectors),
            total_size_bytes: Some(file_size),
            tracks,
            volume_info,
            summary,
            chd_plan: None,
        });
    }

    if let Some(cs) = inspect_console_signatures(reader, file_size) {
        let sector_size = 2048;
        let total_sectors = file_size / (sector_size as u64);
        let track_type = match cs.disc_type {
            DiscType::Cd => TrackType::Mode1_2048,
            DiscType::Dvd => TrackType::DvdData,
            DiscType::Gdi => TrackType::GdiData,
            DiscType::HardDisk => TrackType::HardDiskSector512,
            DiscType::LaserDisc => TrackType::LaserDiscFrame,
            DiscType::Unknown => TrackType::Unknown,
        };

        let tracks = vec![TrackDescriptor {
            track_number: 1,
            track_type,
            sector_size,
            start_lba: 0,
            sector_count: Some(total_sectors),
            file_path: None,
            pregap_sectors: None,
        }];

        let vol_info = VolumeInfo {
            platform: Some(cs.platform),
            disc_id: cs.disc_id.clone(),
            title: cs.title.clone(),
            publisher_identifier: cs.publisher.clone(),
            application_identifier: cs.boot_file.clone(),
            system_identifier: cs.system_identifier.clone(),
            volume_identifier: cs.volume_identifier.clone(),
            volume_space_size: cs.volume_space_size,
            logical_block_size: cs.logical_block_size,
            ..Default::default()
        };

        let mut summary = format!("{} identified by console header signature", cs.description);
        if let Some(ref id) = cs.disc_id {
            summary.push_str(&format!(" [{id}]"));
        }
        if let Some(ref t) = cs.title {
            summary.push_str(&format!(" \"{t}\""));
        }

        return Ok(DiscDescriptor {
            disc_type: cs.disc_type,
            confidence: Confidence::Definitive,
            primary_sector_size: sector_size,
            total_sectors: Some(total_sectors),
            total_size_bytes: Some(file_size),
            tracks,
            volume_info: Some(Box::new(vol_info)),
            summary,
            chd_plan: None,
        });
    }

    let sector_size = 2048u32;
    let lba16_offset = 16u64 * (sector_size as u64);

    if file_size >= lba16_offset + 2048 && reader.seek(SeekFrom::Start(lba16_offset)).is_ok() {
        let mut pvd_buf = [0u8; 2048];
        if reader.read_exact(&mut pvd_buf).is_ok() {
            let pvd_info = parse_iso_pvd(&pvd_buf);
            let (_has_iso_vrs, has_udf_vrs) = scan_volume_recognition_sequence(reader, sector_size);

            if pvd_info.is_some() || has_udf_vrs {
                let mut vol = pvd_info.unwrap_or_default();
                vol.has_udf = vol.has_udf || has_udf_vrs;

                let mut disc_reader =
                    crate::metadata::StreamDiscReader::new(&mut *reader, sector_size, file_size);
                let meta = crate::metadata::inspect_metadata(&mut disc_reader, None);
                meta.apply_to_volume_info(&mut vol);

                let root_meta = scan_root_directory(reader, &pvd_buf, sector_size);
                vol.has_dvd_video = root_meta.has_video_ts;
                vol.has_dvd_audio = root_meta.has_audio_ts;
                if vol.disc_id.is_none() {
                    if let Some(serial) = root_meta.ps_serial {
                        vol.disc_id = Some(serial);
                    }
                }

                let total_sectors = file_size / (sector_size as u64);

                let is_playstation = vol
                    .system_identifier
                    .as_deref()
                    .map(|s| s.contains("PLAYSTATION"))
                    .unwrap_or(false);

                let is_psp = vol.platform == Some(Platform::PlayStationPortable);

                let (disc_type, confidence, summary) = if file_size > CD_MAX_PHYSICAL_BYTES {
                    if is_playstation && !is_psp {
                        vol.platform = Some(Platform::PlayStation2);
                    }
                    let base_dvd = format!(
                        "DVD image: 2048-byte sectors, size ({} MiB) exceeds maximum CD capacity",
                        file_size / (1024 * 1024)
                    );
                    let final_summary = if let Some(plat) = vol.platform {
                        if plat != Platform::StandardIso {
                            let id_str = vol
                                .disc_id
                                .as_deref()
                                .map(|id| format!(" [{id}]"))
                                .unwrap_or_default();
                            let title_str = vol
                                .title
                                .as_deref()
                                .map(|t| format!(" \"{t}\""))
                                .unwrap_or_default();
                            format!("{plat} disc{id_str}{title_str} ({base_dvd})")
                        } else {
                            base_dvd
                        }
                    } else {
                        base_dvd
                    };
                    (DiscType::Dvd, Confidence::Definitive, final_summary)
                } else if vol.has_dvd_video || vol.has_dvd_audio {
                    vol.platform = Some(Platform::DvdVideo);
                    (
                        DiscType::Dvd,
                        Confidence::Definitive,
                        "DVD-Video / DVD-Audio image with VIDEO_TS/AUDIO_TS structures".to_string(),
                    )
                } else if vol.has_udf && !vol.has_iso9660 {
                    (
                        DiscType::Dvd,
                        Confidence::High,
                        "Pure UDF image detected without ISO 9660 (DVD/BD filesystem standard)"
                            .to_string(),
                    )
                } else if vol.has_udf && file_size > 700 * 1024 * 1024 {
                    if is_playstation && !is_psp {
                        vol.platform = Some(Platform::PlayStation2);
                    }
                    (
                        DiscType::Dvd,
                        Confidence::High,
                        "UDF Bridge image exceeding 700 MiB (characteristic of DVD-ROM)"
                            .to_string(),
                    )
                } else {
                    if is_playstation && !is_psp {
                        if vol.has_udf {
                            vol.platform = Some(Platform::PlayStation2);
                        } else {
                            vol.platform = Some(Platform::PlayStation1);
                        }
                    } else if (vol.platform.is_none()
                        || vol.platform == Some(Platform::StandardIso))
                        && reader.seek(SeekFrom::Start(0)).is_ok()
                    {
                        let mut sec0 = [0u8; 512];
                        if reader.read_exact(&mut sec0).is_ok() {
                            if sec0.starts_with(&crate::console::DREAMCAST_MAGIC) {
                                let dc_meta =
                                    crate::console::extract_dreamcast_full_metadata(&sec0);
                                vol.platform = Some(Platform::Dreamcast);
                                if vol.disc_id.is_none() {
                                    vol.disc_id = dc_meta.disc_id;
                                }
                                if dc_meta.title.is_some() {
                                    vol.title = dc_meta.title;
                                }
                                if vol.publisher_identifier.is_none() {
                                    vol.publisher_identifier = dc_meta.publisher;
                                }
                                if vol.application_identifier.is_none() {
                                    vol.application_identifier = dc_meta.boot_file;
                                }
                                if vol.system_identifier.is_none() {
                                    vol.system_identifier = Some("SEGA SEGAKATANA".to_string());
                                }
                            } else if sec0.starts_with(&crate::console::SATURN_MAGIC) {
                                let (disc_id, title) =
                                    crate::console::extract_saturn_metadata(&sec0);
                                vol.platform = Some(Platform::SegaSaturn);
                                if vol.disc_id.is_none() {
                                    vol.disc_id = disc_id;
                                }
                                if title.is_some() {
                                    vol.title = title;
                                }
                            } else if sec0.starts_with(&crate::console::MEGACD_MAGIC) {
                                let (disc_id, title) =
                                    crate::console::extract_megacd_metadata(&sec0);
                                vol.platform = Some(Platform::MegaCd);
                                if vol.disc_id.is_none() {
                                    vol.disc_id = disc_id;
                                }
                                if title.is_some() {
                                    vol.title = title;
                                }
                            } else if vol.platform.is_none() {
                                vol.platform = Some(Platform::StandardIso);
                            }
                        } else if vol.platform.is_none() {
                            vol.platform = Some(Platform::StandardIso);
                        }
                    } else if vol.platform.is_none() {
                        vol.platform = Some(Platform::StandardIso);
                    }
                    let base_summary = format!(
                        "Standard ISO 9660 image ({} MiB) without DVD indicators (classified as CD)",
                        file_size / (1024 * 1024)
                    );
                    let final_summary = if let Some(plat) = vol.platform {
                        if plat != Platform::StandardIso {
                            let id_str = vol
                                .disc_id
                                .as_deref()
                                .map(|id| format!(" [{id}]"))
                                .unwrap_or_default();
                            let title_str = vol
                                .title
                                .as_deref()
                                .map(|t| format!(" \"{t}\""))
                                .unwrap_or_default();
                            format!("{plat} disc{id_str}{title_str} ({base_summary})")
                        } else {
                            base_summary
                        }
                    } else {
                        base_summary
                    };
                    (DiscType::Cd, Confidence::High, final_summary)
                };

                let tracks = vec![TrackDescriptor {
                    track_number: 1,
                    track_type: if disc_type == DiscType::Dvd {
                        TrackType::DvdData
                    } else {
                        TrackType::Mode1_2048
                    },
                    sector_size,
                    start_lba: 0,
                    sector_count: Some(total_sectors),
                    file_path: None,
                    pregap_sectors: None,
                }];

                return Ok(DiscDescriptor {
                    disc_type,
                    confidence,
                    primary_sector_size: sector_size,
                    total_sectors: Some(total_sectors),
                    total_size_bytes: Some(file_size),
                    tracks,
                    volume_info: Some(Box::new(vol)),
                    summary,
                    chd_plan: None,
                });
            }
        }
    }

    if check_udf_avdp(reader, sector_size) {
        let total_sectors = file_size / (sector_size as u64);
        let disc_type = DiscType::Dvd;

        let tracks = vec![TrackDescriptor {
            track_number: 1,
            track_type: TrackType::DvdData,
            sector_size,
            start_lba: 0,
            sector_count: Some(total_sectors),
            file_path: None,
            pregap_sectors: None,
        }];

        let vol = VolumeInfo {
            has_udf: true,
            ..Default::default()
        };

        return Ok(DiscDescriptor {
            disc_type,
            confidence: Confidence::High,
            primary_sector_size: sector_size,
            total_sectors: Some(total_sectors),
            total_size_bytes: Some(file_size),
            tracks,
            volume_info: Some(Box::new(vol)),
            summary: "Optical image containing UDF AVDP descriptor at LBA 256 (DVD)".to_string(),
            chd_plan: None,
        });
    }

    let mode2_lba16_offset = 16u64 * 2336;
    if file_size >= mode2_lba16_offset + 2048
        && reader.seek(SeekFrom::Start(mode2_lba16_offset)).is_ok()
    {
        let mut buf = [0u8; 2048];
        if reader.read_exact(&mut buf).is_ok() {
            if let Some(vol) = parse_iso_pvd(&buf) {
                let total_sectors = file_size / 2336;
                let tracks = vec![TrackDescriptor {
                    track_number: 1,
                    track_type: TrackType::Mode2_2336,
                    sector_size: 2336,
                    start_lba: 0,
                    sector_count: Some(total_sectors),
                    file_path: None,
                    pregap_sectors: None,
                }];

                return Ok(DiscDescriptor {
                    disc_type: DiscType::Cd,
                    confidence: Confidence::High,
                    primary_sector_size: 2336,
                    total_sectors: Some(total_sectors),
                    total_size_bytes: Some(file_size),
                    tracks,
                    volume_info: Some(Box::new(vol)),
                    summary: "Raw Mode 2 CD-ROM image with 2336 bytes/sector".to_string(),
                    chd_plan: None,
                });
            }
        }
    }

    if let Some(desc) = inspect_harddisk(reader, file_size) {
        return Ok(desc);
    }

    let mut start_bytes = [0u8; 16];
    let non_disc_format =
        if reader.seek(SeekFrom::Start(0)).is_ok() && reader.read_exact(&mut start_bytes).is_ok() {
            identify_non_disc_format(&start_bytes)
        } else {
            None
        };

    let ext_hint = hint_ext.unwrap_or("unknown");
    let summary = if let Some(format_name) = non_disc_format {
        format!("Unrecognized media: file is a {format_name}, not a supported storage image")
    } else {
        format!(
            "File does not match any recognized CD, DVD, GDI, Hard Disk, or LaserDisc structures (extension: '.{ext_hint}', size: {file_size} bytes)"
        )
    };

    Ok(DiscDescriptor::unknown(summary))
}

fn identify_non_disc_format(header: &[u8]) -> Option<&'static str> {
    if header.len() >= 4 && header[0..4] == [0x7F, b'E', b'L', b'F'] {
        return Some("ELF executable");
    }
    if header.len() >= 2 && &header[0..2] == b"MZ" {
        return Some("PE / Windows executable");
    }
    if header.len() >= 4 && header[0..4] == [b'P', b'K', 0x03, 0x04] {
        return Some("ZIP archive");
    }
    if header.len() >= 6 && header[0..6] == [b'7', b'z', 0xBC, 0xAF, 0x27, 0x1C] {
        return Some("7-Zip archive");
    }
    if header.len() >= 4 && &header[0..4] == b"Rar!" {
        return Some("RAR archive");
    }
    if header.len() >= 8 && header[0..8] == [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A] {
        return Some("PNG image");
    }
    if header.len() >= 3 && header[0..3] == [0xFF, 0xD8, 0xFF] {
        return Some("JPEG image");
    }
    if header.len() >= 5 && &header[0..5] == b"%PDF-" {
        return Some("PDF document");
    }
    if header.len() >= 16 && &header[0..16] == b"SQLite format 3\0" {
        return Some("SQLite database");
    }
    if header.len() >= 4 && &header[0..4] == b"fLaC" {
        return Some("FLAC audio file");
    }
    if header.len() >= 4 && &header[0..4] == b"OggS" {
        return Some("Ogg container");
    }
    if header.len() >= 4 && &header[0..4] == b"QFI\xFB" {
        return Some("QEMU QCOW2 virtual disk image (convert to raw for CHD creation)");
    }
    if header.len() >= 4 && &header[0..4] == b"KDMV" {
        return Some("VMware VMDK virtual disk image (convert to raw for CHD creation)");
    }
    if header.len() >= 12 && &header[0..4] == b"RIFF" && &header[8..12] == b"AVI " {
        return Some("AVI multimedia video");
    }
    None
}