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
//! Console and platform-specific media signatures.

use crate::types::{DiscType, Platform};
use std::io::{Read, Seek, SeekFrom};

/// GameCube / Wii disc magic number at offset 0x18.
pub const NINTENDO_DISC_MAGIC: [u8; 4] = [0x5D, 0x1C, 0x9E, 0xA3];

/// Xbox XDVDFS filesystem magic at sector 32 (offset 0x10000).
pub const XDVDFS_MAGIC: [u8; 20] = *b"MICROSOFT*XBOX*MEDIA";

/// Dreamcast hardware identifier at sector 0.
pub const DREAMCAST_MAGIC: [u8; 16] = *b"SEGA SEGAKATANA ";

/// Sega Saturn identifier at sector 0.
pub const SATURN_MAGIC: [u8; 16] = *b"SEGA SEGASATURN ";

/// Sega Mega-CD / Sega CD identifier at sector 0.
pub const MEGACD_MAGIC: [u8; 15] = *b"SEGADISCSYSTEM ";

/// 3DO Interactive Multiplayer volume header magic at sector 0.
pub const THREEDO_MAGIC: [u8; 7] = [0x01, b'Z', b'Z', b'Z', b'Z', b'Z', 0x01];

/// Cleans an ASCII byte slice into a trimmed String.
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()
}

/// Extracts GameCube / Wii disc code (e.g. `GM8E01`) and game title from LBA 0 header.
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)
}

/// Detailed Dreamcast IP.BIN metadata.
#[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>,
}

/// Extracts full Dreamcast IP.BIN metadata from sector 0 user data.
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
}

/// Extracts Sega Saturn product number (e.g. `T-13301G`) and title from LBA 0 header.
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)
}

/// Extracts Sega Mega-CD / Sega CD product code and game title from LBA 0 header.
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)
}

/// Detailed 3DO Opera filesystem metadata.
#[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,
}

/// Extracts 3DO OperaFS DiscLabel metadata from sector 0 user data.
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,
    })
}

/// Parses PlayStation game serial (e.g. `SLUS-00594`, `SLES-50001`, `SCUS-94228`) from a file identifier.
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
}

/// Parses PlayStation serial from `SYSTEM.CNF` file content (e.g. `BOOT = cdrom:\SLUS_005.94;1`).
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
}

/// Scans an ISO 9660 directory sector buffer for a PlayStation serial file record.
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
}

/// Discovered console signature match containing metadata.
#[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>,
}

/// Inspects known console disc headers to detect platform, media type, disc ID, and title.
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
}