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
//! Reverse heuristics and inspection for MAME CHD (Compressed Hunks of Data) containers.
//!
//! Inspects CHD v3, v4, and v5 containers by reading the header and traversing
//! metadata nodes without decompressing audio/data hunks.

use std::collections::HashSet;
use std::io::{Read, Seek, SeekFrom};

use crate::types::{Confidence, DiscDescriptor, DiscError, DiscType, TrackDescriptor, TrackType};

/// Expected 8-byte magic header signature for CHD containers.
pub const CHD_SIGNATURE: &[u8; 8] = b"MComprHD";

/// Standard header length for CHD v3 (120 bytes).
pub const CHD_V3_HEADER_SIZE: u32 = 120;
/// Standard header length for CHD v4 (108 bytes).
pub const CHD_V4_HEADER_SIZE: u32 = 108;
/// Standard header length for CHD v5 (124 bytes).
pub const CHD_V5_HEADER_SIZE: u32 = 124;

/// Size of each metadata entry header in bytes.
pub const CHD_METADATA_HEADER_SIZE: usize = 16;
/// Safety limit on metadata payload size (16 MiB).
pub const MAX_METADATA_ENTRY_SIZE: usize = 16 * 1024 * 1024;
/// Maximum number of metadata nodes to traverse to avoid malicious loops.
pub const MAX_METADATA_ENTRIES_COUNT: usize = 2048;

// FourCC metadata tags
pub const TAG_CDROM_TRACK2: u32 = u32::from_be_bytes(*b"CHT2");
pub const TAG_CDROM_TRACK: u32 = u32::from_be_bytes(*b"CHTR");
pub const TAG_CDROM_OLD: u32 = u32::from_be_bytes(*b"CHCD");
pub const TAG_GDROM_TRACK: u32 = u32::from_be_bytes(*b"CHGT");
pub const TAG_GDROM_OLD: u32 = u32::from_be_bytes(*b"CHGD");
pub const TAG_DVD: u32 = u32::from_be_bytes(*b"DVD ");
pub const TAG_HARD_DISK: u32 = u32::from_be_bytes(*b"GDDD");
pub const TAG_HARD_DISK_IDENT: u32 = u32::from_be_bytes(*b"IDNT");
pub const TAG_AV: u32 = 0x41564156; // b"AVAV"
pub const TAG_AV_LD: u32 = 0x41564c44; // b"AVLD"

/// Target format and extraction recommendations for a CHD container.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChdExtractionPlan {
    /// Target extraction operation verb (e.g. "extractcd", "extractdvd", "extracthd", "extractld", "extractraw").
    pub command: &'static str,
    /// Default output descriptor file extension, if applicable (e.g. Some("cue") for CD, Some("gdi") for GD-ROM).
    pub descriptor_ext: Option<&'static str>,
    /// Default output binary payload extension (e.g. "bin", "iso", "img", "avi", "raw").
    pub payload_ext: &'static str,
    /// CHD format version (3, 4, or 5).
    pub chd_version: u32,
    /// Uncompressed logical bytes stored in the container.
    pub logical_bytes: u64,
    /// Hunk size in bytes.
    pub hunk_bytes: u32,
    /// Unit size in bytes (e.g. 2448 for CD, 2048 for DVD, 512 for HDD).
    pub unit_bytes: u32,
    /// Matched FourCC metadata tag, if one was found (e.g. "CHT2", "CHGT", "DVD ", "GDDD", "AVAV").
    pub tag: Option<String>,
    /// Whether the CHD optical tracks contain raw subcode (RW_RAW).
    pub has_raw_subcode: bool,
}

impl ChdExtractionPlan {
    /// Human-readable description of target extraction format.
    pub fn description(&self) -> &'static str {
        match self.command {
            "extractcd" => {
                if self.descriptor_ext == Some("gdi") {
                    "Dreamcast GD-ROM (.gdi + tracks)"
                } else {
                    "CD-ROM Cue Sheet (.cue + .bin)"
                }
            }
            "extractdvd" => "DVD-ROM ISO 9660 (.iso)",
            "extracthd" => "Hard Disk Raw Image (.img)",
            "extractld" => "LaserDisc Audio/Video (.avi)",
            _ => "Raw Disc/Storage Image (.raw)",
        }
    }
}

/// Minimal parsed representation of a CHD container header.
#[derive(Debug, Clone, Copy)]
struct ParsedChdHeader {
    version: u32,
    logical_bytes: u64,
    meta_offset: u64,
    hunk_bytes: u32,
    unit_bytes: u32,
}

impl ParsedChdHeader {
    fn read<R: Read + Seek>(reader: &mut R, file_size: u64) -> Result<Self, DiscError> {
        reader.seek(SeekFrom::Start(0))?;
        let mut magic = [0u8; 16];
        reader.read_exact(&mut magic)?;

        if &magic[0..8] != CHD_SIGNATURE {
            return Err(DiscError::InvalidDescriptor(
                "Invalid CHD signature (expected MComprHD)".into(),
            ));
        }

        let length = u32::from_be_bytes([magic[8], magic[9], magic[10], magic[11]]);
        let version = u32::from_be_bytes([magic[12], magic[13], magic[14], magic[15]]);

        match version {
            5 => {
                if length != CHD_V5_HEADER_SIZE || file_size < CHD_V5_HEADER_SIZE as u64 {
                    return Err(DiscError::InvalidDescriptor(format!(
                        "Invalid CHD v5 header size: {length}"
                    )));
                }
                let mut buf = [0u8; CHD_V5_HEADER_SIZE as usize];
                reader.seek(SeekFrom::Start(0))?;
                reader.read_exact(&mut buf)?;

                let logical_bytes = u64::from_be_bytes([
                    buf[32], buf[33], buf[34], buf[35], buf[36], buf[37], buf[38], buf[39],
                ]);
                let meta_offset = u64::from_be_bytes([
                    buf[48], buf[49], buf[50], buf[51], buf[52], buf[53], buf[54], buf[55],
                ]);
                let hunk_bytes = u32::from_be_bytes([buf[56], buf[57], buf[58], buf[59]]);
                let unit_bytes = u32::from_be_bytes([buf[60], buf[61], buf[62], buf[63]]);

                Ok(Self {
                    version,
                    logical_bytes,
                    meta_offset,
                    hunk_bytes,
                    unit_bytes,
                })
            }
            4 => {
                if length != CHD_V4_HEADER_SIZE || file_size < CHD_V4_HEADER_SIZE as u64 {
                    return Err(DiscError::InvalidDescriptor(format!(
                        "Invalid CHD v4 header size: {length}"
                    )));
                }
                let mut buf = [0u8; CHD_V4_HEADER_SIZE as usize];
                reader.seek(SeekFrom::Start(0))?;
                reader.read_exact(&mut buf)?;

                let logical_bytes = u64::from_be_bytes([
                    buf[28], buf[29], buf[30], buf[31], buf[32], buf[33], buf[34], buf[35],
                ]);
                let meta_offset = u64::from_be_bytes([
                    buf[36], buf[37], buf[38], buf[39], buf[40], buf[41], buf[42], buf[43],
                ]);
                let hunk_bytes = u32::from_be_bytes([buf[44], buf[45], buf[46], buf[47]]);
                let unit_bytes = if hunk_bytes.rem_euclid(2448) == 0 {
                    2448
                } else if hunk_bytes.rem_euclid(2048) == 0 {
                    2048
                } else {
                    512
                };

                Ok(Self {
                    version,
                    logical_bytes,
                    meta_offset,
                    hunk_bytes,
                    unit_bytes,
                })
            }
            3 => {
                if length != CHD_V3_HEADER_SIZE || file_size < CHD_V3_HEADER_SIZE as u64 {
                    return Err(DiscError::InvalidDescriptor(format!(
                        "Invalid CHD v3 header size: {length}"
                    )));
                }
                let mut buf = [0u8; CHD_V3_HEADER_SIZE as usize];
                reader.seek(SeekFrom::Start(0))?;
                reader.read_exact(&mut buf)?;

                let logical_bytes = u64::from_be_bytes([
                    buf[28], buf[29], buf[30], buf[31], buf[32], buf[33], buf[34], buf[35],
                ]);
                let meta_offset = u64::from_be_bytes([
                    buf[36], buf[37], buf[38], buf[39], buf[40], buf[41], buf[42], buf[43],
                ]);
                let hunk_bytes = u32::from_be_bytes([buf[76], buf[77], buf[78], buf[79]]);
                let unit_bytes = if hunk_bytes.rem_euclid(2448) == 0 {
                    2448
                } else if hunk_bytes.rem_euclid(2048) == 0 {
                    2048
                } else {
                    512
                };

                Ok(Self {
                    version,
                    logical_bytes,
                    meta_offset,
                    hunk_bytes,
                    unit_bytes,
                })
            }
            v => Err(DiscError::InvalidDescriptor(format!(
                "Unsupported CHD version: {v}"
            ))),
        }
    }
}

/// Inspects a CHD container from a seekable reader and produces a `DiscDescriptor`.
pub fn inspect_chd<R: Read + Seek>(
    reader: &mut R,
    file_size: u64,
) -> Result<DiscDescriptor, DiscError> {
    let header = ParsedChdHeader::read(reader, file_size)?;

    let mut visited_offsets = HashSet::new();
    let mut current_offset = header.meta_offset;
    let mut matched_tag: Option<u32> = None;
    let mut track_metadata_strings = Vec::new();
    let mut entries_count = 0;

    while current_offset != 0 && entries_count < MAX_METADATA_ENTRIES_COUNT {
        entries_count += 1;
        if !visited_offsets.insert(current_offset) {
            break; // Loop detected
        }
        if current_offset + (CHD_METADATA_HEADER_SIZE as u64) > file_size {
            break;
        }

        if reader.seek(SeekFrom::Start(current_offset)).is_err() {
            break;
        }

        let mut node_buf = [0u8; CHD_METADATA_HEADER_SIZE];
        if reader.read_exact(&mut node_buf).is_err() {
            break;
        }

        let metatag = u32::from_be_bytes([node_buf[0], node_buf[1], node_buf[2], node_buf[3]]);
        let length = u32::from_be_bytes([0, node_buf[5], node_buf[6], node_buf[7]]) as usize;
        let next = u64::from_be_bytes([
            node_buf[8],
            node_buf[9],
            node_buf[10],
            node_buf[11],
            node_buf[12],
            node_buf[13],
            node_buf[14],
            node_buf[15],
        ]);

        if matched_tag.is_none() {
            match metatag {
                TAG_CDROM_TRACK2 | TAG_CDROM_TRACK | TAG_CDROM_OLD | TAG_GDROM_TRACK
                | TAG_GDROM_OLD | TAG_DVD | TAG_HARD_DISK | TAG_HARD_DISK_IDENT | TAG_AV
                | TAG_AV_LD => {
                    matched_tag = Some(metatag);
                }
                _ => {}
            }
        }

        // Collect track metadata for CD / GD-ROM
        if matches!(
            metatag,
            TAG_CDROM_TRACK2 | TAG_CDROM_TRACK | TAG_CDROM_OLD | TAG_GDROM_TRACK | TAG_GDROM_OLD
        ) && length > 0
            && length <= MAX_METADATA_ENTRY_SIZE
            && current_offset + (CHD_METADATA_HEADER_SIZE as u64) + (length as u64) <= file_size
        {
            let mut val_buf = vec![0u8; length];
            if reader.read_exact(&mut val_buf).is_ok() {
                let s = String::from_utf8_lossy(&val_buf);
                track_metadata_strings.push(s.to_string());
            }
        }

        current_offset = next;
    }

    // Determine DiscType and extraction parameters based on metadata tags or unit/hunk heuristics
    let (disc_type, command, descriptor_ext, payload_ext, primary_sector_size) = match matched_tag {
        Some(TAG_GDROM_TRACK | TAG_GDROM_OLD) => {
            (DiscType::Gdi, "extractcd", Some("gdi"), "bin", 2352)
        }
        Some(TAG_CDROM_TRACK2 | TAG_CDROM_TRACK | TAG_CDROM_OLD) => {
            (DiscType::Cd, "extractcd", Some("cue"), "bin", 2352)
        }
        Some(TAG_DVD) => (DiscType::Dvd, "extractdvd", None, "iso", 2048),
        Some(TAG_HARD_DISK | TAG_HARD_DISK_IDENT) => {
            (DiscType::HardDisk, "extracthd", None, "img", 512)
        }
        Some(TAG_AV | TAG_AV_LD) => (DiscType::LaserDisc, "extractld", None, "avi", 2048),
        _ => {
            // Fallback heuristic based on unit and hunk dimensions
            if header.unit_bytes == 2448 {
                (DiscType::Cd, "extractcd", Some("cue"), "bin", 2352)
            } else if header.unit_bytes == 2048 {
                (DiscType::Dvd, "extractdvd", None, "iso", 2048)
            } else if header.unit_bytes == 512 {
                (DiscType::HardDisk, "extracthd", None, "img", 512)
            } else if header.hunk_bytes > 0 && header.hunk_bytes.rem_euclid(2448) == 0 {
                (DiscType::Cd, "extractcd", Some("cue"), "bin", 2352)
            } else if header.hunk_bytes > 0 && header.hunk_bytes.rem_euclid(2048) == 0 {
                (DiscType::Dvd, "extractdvd", None, "iso", 2048)
            } else if header.hunk_bytes > 0 && header.hunk_bytes.rem_euclid(512) == 0 {
                (DiscType::HardDisk, "extracthd", None, "img", 512)
            } else {
                (DiscType::Unknown, "extractraw", None, "raw", 2048)
            }
        }
    };

    let mut tracks = Vec::new();
    let mut current_lba = 0u64;

    for s in &track_metadata_strings {
        if let Some(track) = parse_chd_track_descriptor(s, &mut current_lba) {
            tracks.push(track);
        }
    }

    let total_sectors = if primary_sector_size > 0 {
        Some(header.logical_bytes / (primary_sector_size as u64))
    } else {
        None
    };

    let tag_str = matched_tag.map(|t| {
        let b = t.to_be_bytes();
        String::from_utf8_lossy(&b).to_string()
    });

    let hunk_count = if header.hunk_bytes > 0 {
        header.logical_bytes.div_ceil(header.hunk_bytes as u64)
    } else {
        0
    };

    let has_raw_subcode = track_metadata_strings.iter().any(|s| {
        let upper = s.to_ascii_uppercase();
        upper.contains("SUBTYPE:RW_RAW") || upper.contains("PGSUB:RW_RAW")
    });

    let summary = format!(
        "MAME CHD v{} container ({}, {} hunks). Extraction target: {} via {}.",
        header.version,
        tag_str.as_deref().unwrap_or("Raw"),
        hunk_count,
        descriptor_ext.unwrap_or(payload_ext).to_ascii_uppercase(),
        command
    );

    let plan = ChdExtractionPlan {
        command,
        descriptor_ext,
        payload_ext,
        chd_version: header.version,
        logical_bytes: header.logical_bytes,
        hunk_bytes: header.hunk_bytes,
        unit_bytes: header.unit_bytes,
        tag: tag_str,
        has_raw_subcode,
    };

    Ok(DiscDescriptor {
        disc_type,
        confidence: Confidence::Definitive,
        primary_sector_size,
        total_sectors,
        total_size_bytes: Some(header.logical_bytes),
        tracks,
        volume_info: None,
        summary,
        chd_plan: Some(plan),
    })
}

/// Parses a CHD text metadata track line (e.g. `TRACK:1 TYPE:MODE1/2352 SUBTYPE:NONE FRAMES:12345`)
/// into a `TrackDescriptor`.
fn parse_chd_track_descriptor(s: &str, current_lba: &mut u64) -> Option<TrackDescriptor> {
    let clean = s.trim().trim_matches('\0');
    let mut track_num: Option<u32> = None;
    let mut track_type_str: Option<&str> = None;
    let mut frames: Option<u32> = None;
    let mut pregap_frames: Option<u32> = None;

    for token in clean.split_whitespace() {
        if let Some((key, val)) = token.split_once(':') {
            match key {
                "TRACK" => track_num = val.parse().ok(),
                "TYPE" => track_type_str = Some(val),
                "FRAMES" => frames = val.parse().ok(),
                "PREGAP" => pregap_frames = val.parse().ok(),
                _ => {}
            }
        }
    }

    let track_number = track_num?;
    let (track_type, sector_size) = match track_type_str.unwrap_or("").to_ascii_uppercase().as_str()
    {
        "MODE1" | "MODE1/2048" => (TrackType::Mode1_2048, 2048),
        "MODE1_RAW" | "MODE1/2352" => (TrackType::Mode1_2352, 2352),
        "MODE2" | "MODE2/2336" => (TrackType::Mode2_2336, 2336),
        "MODE2_FORM1" | "MODE2_FORM2" | "MODE2_RAW" | "MODE2/2352" => (TrackType::Mode2_2352, 2352),
        "AUDIO" => (TrackType::Audio, 2352),
        "CDI/2352" => (TrackType::Cdi2352, 2352),
        _ => (TrackType::Unknown, 2352),
    };

    let start_lba = *current_lba;
    if let Some(f) = frames {
        *current_lba += f as u64;
    }

    Some(TrackDescriptor {
        track_number,
        track_type,
        sector_size,
        start_lba,
        sector_count: frames.map(|f| f as u64),
        file_path: None,
        pregap_sectors: pregap_frames,
    })
}