chdlady 0.1.0

High-level facade API for reading and creating CHD files
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
use std::fs::{self, File};
use std::io::Read;
use std::path::Path;
use std::process::Command;
use std::time::Instant;

use chdlady::core::ChdFile;
use chdlady::disc::{extract_cd, extract_raw};
use sha1::{Digest, Sha1};

fn get_ref_dir() -> std::path::PathBuf {
    std::env::var("CHDLADY_TEST_REF_DIR")
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|_| std::path::PathBuf::from("reference_chds"))
}

fn get_base_tmp() -> std::path::PathBuf {
    std::env::temp_dir().join("chdlady_tmp_diff")
}

fn sha1_file(path: &Path) -> String {
    let mut file = File::open(path).expect("open file for sha1");
    let mut hasher = Sha1::new();
    let mut buf = [0u8; 65536];
    loop {
        let n = file.read(&mut buf).expect("read chunk");
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    format!("{:x}", hasher.finalize())
}

fn test_gdrom_gdi_parity() {
    println!("\n=== TEST 1: GD-ROM GDI MULTI-TRACK PARITY (4x4 Evo) ===");
    let gdrom_chd = get_ref_dir().join("4x4evo_gdrom.chd");
    if !gdrom_chd.exists() {
        println!("Skipping: 4x4evo_gdrom.chd not found");
        return;
    }

    let chdman_dir = get_base_tmp().join("gdrom_chdman");
    let chdlady_dir = get_base_tmp().join("gdrom_chdlady");
    fs::create_dir_all(&chdman_dir).unwrap();
    fs::create_dir_all(&chdlady_dir).unwrap();

    let gdi_chdman = chdman_dir.join("disc.gdi");
    let gdi_chdlady = chdlady_dir.join("disc.gdi");

    // Extract with chdman if not already extracted
    if !gdi_chdman.exists() {
        println!("Running chdman extractcd on GD-ROM...");
        let status = Command::new("chdman")
            .args([
                "extractcd",
                "-i",
                gdrom_chd.to_str().unwrap(),
                "-o",
                gdi_chdman.to_str().unwrap(),
                "-f",
            ])
            .status()
            .expect("run chdman extractcd");
        assert!(status.success());
    }

    // Extract with chdlady if not already extracted
    if !gdi_chdlady.exists() {
        println!("Running chdlady extract_cd on GD-ROM...");
        let t0 = Instant::now();
        let f = File::open(&gdrom_chd).unwrap();
        let mut chd = ChdFile::open(f).unwrap();
        extract_cd(&mut chd, &gdi_chdlady, None, true).expect("chdlady extract_cd GD-ROM");
        println!(
            "chdlady GD-ROM extraction completed in {:.2}s",
            t0.elapsed().as_secs_f64()
        );
    }

    // Compare all 11 track files
    for trk in 1..=11 {
        let ext = if matches!(trk, 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10) {
            "raw"
        } else {
            "bin"
        };
        let filename = format!("disc{:02}.{}", trk, ext);
        let p_chdman = chdman_dir.join(&filename);
        let p_chdlady = chdlady_dir.join(&filename);

        let sha_chdman = sha1_file(&p_chdman);
        let sha_chdlady = sha1_file(&p_chdlady);
        let size = fs::metadata(&p_chdlady).unwrap().len();

        print!("  Track {:02} ({:4} KB): ", trk, size / 1024);
        if sha_chdman == sha_chdlady {
            println!("MATCH [SHA-1: {}]", sha_chdman);
        } else {
            panic!(
                "MISMATCH on Track {:02}!\n  chdman:  {}\n  chdlady: {}",
                trk, sha_chdman, sha_chdlady
            );
        }
    }
    println!("GD-ROM GDI parity: ALL 11 TRACKS 100% IDENTICAL!");
}

fn test_wipeout_mixed_mode_parity() {
    println!("\n=== TEST 2: MIXED-MODE CD PARITY (WipEout: 1 Data + 8 Audio) ===");
    let wipeout_chd = get_ref_dir().join("wipeout_default.chd");
    if !wipeout_chd.exists() {
        println!("Skipping: wipeout_default.chd not found");
        return;
    }

    let wipeout_dir = get_base_tmp().join("wipeout_test");
    fs::create_dir_all(&wipeout_dir).unwrap();

    // 2A. Single-bin CUE/BIN
    println!("Testing 2A: Single-bin CUE/BIN...");
    let chdman_cue = wipeout_dir.join("chdman_single.cue");
    let chdman_bin = wipeout_dir.join("chdman_single.bin");
    let chdlady_cue = wipeout_dir.join("chdlady_single.cue");
    let chdlady_bin = wipeout_dir.join("chdlady_single.bin");

    if !chdman_bin.exists() {
        let status = Command::new("chdman")
            .args([
                "extractcd",
                "-i",
                wipeout_chd.to_str().unwrap(),
                "-o",
                chdman_cue.to_str().unwrap(),
                "-ob",
                chdman_bin.to_str().unwrap(),
                "-f",
            ])
            .status()
            .expect("chdman extractcd single");
        assert!(status.success());
    }

    if !chdlady_bin.exists() {
        let f = File::open(&wipeout_chd).unwrap();
        let mut chd = ChdFile::open(f).unwrap();
        extract_cd(&mut chd, &chdlady_cue, Some(&chdlady_bin), false).unwrap();
    }

    let sha_m_single = sha1_file(&chdman_bin);
    let sha_l_single = sha1_file(&chdlady_bin);
    assert_eq!(
        sha_m_single, sha_l_single,
        "WipEout single-bin SHA-1 mismatch!"
    );
    println!("  Single-bin SHA-1 match: {}", sha_l_single);

    // 2B. Split-bin CUE/BIN
    println!("Testing 2B: Split-bin CUE/BIN...");
    let chdman_split_cue = wipeout_dir.join("chdman_split.cue");
    let chdlady_split_cue = wipeout_dir.join("chdlady_split.cue");
    let chdman_split_sample = wipeout_dir.join("chdman_split (Track 1).bin");
    let chdlady_split_sample = wipeout_dir.join("chdlady_split (Track 1).bin");

    if !chdman_split_sample.exists() {
        let status = Command::new("chdman")
            .args([
                "extractcd",
                "-i",
                wipeout_chd.to_str().unwrap(),
                "-o",
                chdman_split_cue.to_str().unwrap(),
                "-sb",
                "-f",
            ])
            .status()
            .expect("chdman extractcd split");
        assert!(status.success());
    }

    if !chdlady_split_sample.exists() {
        let f = File::open(&wipeout_chd).unwrap();
        let mut chd = ChdFile::open(f).unwrap();
        extract_cd(&mut chd, &chdlady_split_cue, None, true).unwrap();
    }

    for trk in 1..=9 {
        let name_m = format!("chdman_split (Track {}).bin", trk);
        let name_l = format!("chdlady_split (Track {}).bin", trk);
        let p_m = wipeout_dir.join(&name_m);
        let p_l = wipeout_dir.join(&name_l);
        let sha_m = sha1_file(&p_m);
        let sha_l = sha1_file(&p_l);
        assert_eq!(sha_m, sha_l, "WipEout split track {} mismatch!", trk);
        println!("  Split Track {} MATCH [SHA-1: {}]", trk, sha_l);
    }

    // 2C. CDRDAO TOC
    println!("Testing 2C: CDRDAO TOC...");
    let chdman_toc = wipeout_dir.join("chdman.toc");
    let chdman_toc_bin = wipeout_dir.join("chdman_toc.bin");
    let chdlady_toc = wipeout_dir.join("chdlady.toc");
    let chdlady_toc_bin = wipeout_dir.join("chdlady_toc.bin");

    if !chdman_toc_bin.exists() {
        let status = Command::new("chdman")
            .args([
                "extractcd",
                "-i",
                wipeout_chd.to_str().unwrap(),
                "-o",
                chdman_toc.to_str().unwrap(),
                "-ob",
                chdman_toc_bin.to_str().unwrap(),
                "-f",
            ])
            .status()
            .expect("chdman extractcd toc");
        assert!(status.success());
    }

    if !chdlady_toc_bin.exists() {
        let f = File::open(&wipeout_chd).unwrap();
        let mut chd = ChdFile::open(f).unwrap();
        extract_cd(&mut chd, &chdlady_toc, Some(&chdlady_toc_bin), false).unwrap();
    }

    let sha_m_toc = sha1_file(&chdman_toc_bin);
    let sha_l_toc = sha1_file(&chdlady_toc_bin);
    assert_eq!(sha_m_toc, sha_l_toc, "WipEout TOC bin SHA-1 mismatch!");
    println!("  CDRDAO TOC bin MATCH [SHA-1: {}]", sha_l_toc);
}

fn test_slicing_flags_parity() {
    println!("\n=== TEST 3: PARTIAL EXTRACTION SLICING FLAGS (-isb, -ish, -ilb, -ilh) ===");
    let ref_dir = get_ref_dir();
    let zlib_chd = ref_dir.join("hd_zlib.chd");
    let lzma_chd = ref_dir.join("hd_lzma.chd");
    let huff_chd = ref_dir.join("hd_huff.chd");

    let slice_dir = get_base_tmp().join("slice_test");
    fs::create_dir_all(&slice_dir).unwrap();

    // 3A: start_byte + byte_count on zlib
    {
        println!("Testing 3A: start_byte=8192, byte_count=16384 on hd_zlib.chd...");
        let out_m = slice_dir.join("slice_3a_chdman.bin");
        let out_l = slice_dir.join("slice_3a_chdlady.bin");

        let status = Command::new("chdman")
            .args([
                "extractraw",
                "-i",
                zlib_chd.to_str().unwrap(),
                "-o",
                out_m.to_str().unwrap(),
                "-isb",
                "8192",
                "-ib",
                "16384",
                "-f",
            ])
            .status()
            .expect("chdman slice 3a");
        assert!(status.success());

        let f = File::open(&zlib_chd).unwrap();
        let mut chd = ChdFile::open(f).unwrap();
        let mut out_file = File::create(&out_l).unwrap();
        extract_raw(&mut chd, &mut out_file, Some(8192), None, Some(16384), None).unwrap();

        assert_eq!(sha1_file(&out_m), sha1_file(&out_l));
        println!("  Slice 3A MATCH [SHA-1: {}]", sha1_file(&out_l));
    }

    // 3B: start_hunk + hunk_count on lzma
    {
        println!("Testing 3B: start_hunk=3, hunk_count=5 on hd_lzma.chd...");
        let out_m = slice_dir.join("slice_3b_chdman.bin");
        let out_l = slice_dir.join("slice_3b_chdlady.bin");

        let status = Command::new("chdman")
            .args([
                "extractraw",
                "-i",
                lzma_chd.to_str().unwrap(),
                "-o",
                out_m.to_str().unwrap(),
                "-ish",
                "3",
                "-ih",
                "5",
                "-f",
            ])
            .status()
            .expect("chdman slice 3b");
        assert!(status.success());

        let f = File::open(&lzma_chd).unwrap();
        let mut chd = ChdFile::open(f).unwrap();
        let mut out_file = File::create(&out_l).unwrap();
        extract_raw(&mut chd, &mut out_file, None, Some(3), None, Some(5)).unwrap();

        assert_eq!(sha1_file(&out_m), sha1_file(&out_l));
        println!("  Slice 3B MATCH [SHA-1: {}]", sha1_file(&out_l));
    }

    // 3C: start_byte + hunk_count on huff
    {
        println!("Testing 3C: start_byte=4096, hunk_count=4 on hd_huff.chd...");
        let out_m = slice_dir.join("slice_3c_chdman.bin");
        let out_l = slice_dir.join("slice_3c_chdlady.bin");

        let status = Command::new("chdman")
            .args([
                "extractraw",
                "-i",
                huff_chd.to_str().unwrap(),
                "-o",
                out_m.to_str().unwrap(),
                "-isb",
                "4096",
                "-ih",
                "4",
                "-f",
            ])
            .status()
            .expect("chdman slice 3c");
        assert!(status.success());

        let f = File::open(&huff_chd).unwrap();
        let mut chd = ChdFile::open(f).unwrap();
        let mut out_file = File::create(&out_l).unwrap();
        extract_raw(&mut chd, &mut out_file, Some(4096), None, None, Some(4)).unwrap();

        assert_eq!(sha1_file(&out_m), sha1_file(&out_l));
        println!("  Slice 3C MATCH [SHA-1: {}]", sha1_file(&out_l));
    }
}

fn test_multi_codec_combinations() {
    println!("\n=== TEST 4: MULTI-CODEC COMBINATIONS (zlib,lzma | lzma,huff | cdlz,cdfl) ===");
    let multi_dir = get_base_tmp().join("multi_codec_test");
    fs::create_dir_all(&multi_dir).unwrap();

    let src_bin = multi_dir.join("src_64k.bin");
    let mut data = vec![0u8; 65536];
    for (i, b) in data.iter_mut().enumerate() {
        *b = ((i * 47) % 251) as u8;
    }
    fs::write(&src_bin, &data).unwrap();

    // 4A: zlib,lzma
    {
        println!("Testing 4A: Raw with codecs zlib,lzma...");
        let chd_path = multi_dir.join("multi_zlib_lzma.chd");
        let out_path = multi_dir.join("multi_zlib_lzma.out");
        let status = Command::new("chdman")
            .args([
                "createraw",
                "-i",
                src_bin.to_str().unwrap(),
                "-o",
                chd_path.to_str().unwrap(),
                "-hs",
                "4096",
                "-us",
                "4096",
                "-c",
                "zlib,lzma",
                "-f",
            ])
            .status()
            .unwrap();
        assert!(status.success());

        let f = File::open(&chd_path).unwrap();
        let mut chd = ChdFile::open(f).unwrap();
        let mut out_file = File::create(&out_path).unwrap();
        extract_raw(&mut chd, &mut out_file, None, None, None, None).unwrap();
        assert_eq!(sha1_file(&src_bin), sha1_file(&out_path));
        println!("  zlib,lzma MATCH [SHA-1: {}]", sha1_file(&out_path));
    }

    // 4B: lzma,huff
    {
        println!("Testing 4B: Raw with codecs lzma,huff...");
        let chd_path = multi_dir.join("multi_lzma_huff.chd");
        let out_path = multi_dir.join("multi_lzma_huff.out");
        let status = Command::new("chdman")
            .args([
                "createraw",
                "-i",
                src_bin.to_str().unwrap(),
                "-o",
                chd_path.to_str().unwrap(),
                "-hs",
                "4096",
                "-us",
                "4096",
                "-c",
                "lzma,huff",
                "-f",
            ])
            .status()
            .unwrap();
        assert!(status.success());

        let f = File::open(&chd_path).unwrap();
        let mut chd = ChdFile::open(f).unwrap();
        let mut out_file = File::create(&out_path).unwrap();
        extract_raw(&mut chd, &mut out_file, None, None, None, None).unwrap();
        assert_eq!(sha1_file(&src_bin), sha1_file(&out_path));
        println!("  lzma,huff MATCH [SHA-1: {}]", sha1_file(&out_path));
    }
}

fn test_various_hunk_sizes() {
    println!("\n=== TEST 5: VARIABLE HUNK SIZES (512, 1024, 2048, 4096, 8192, 16384, 65536) ===");
    let hs_dir = get_base_tmp().join("hunk_sizes_test");
    fs::create_dir_all(&hs_dir).unwrap();

    let src_bin = hs_dir.join("src_128k.bin");
    let mut data = vec![0u8; 131072];
    for (i, b) in data.iter_mut().enumerate() {
        *b = ((i * 19) % 256) as u8;
    }
    fs::write(&src_bin, &data).unwrap();

    let hunk_sizes = [512, 1024, 2048, 4096, 8192, 16384, 65536];
    for hs in hunk_sizes {
        let us = 512.min(hs);
        let chd_path = hs_dir.join(format!("test_hs_{}.chd", hs));
        let out_path = hs_dir.join(format!("test_hs_{}.out", hs));

        let status = Command::new("chdman")
            .args([
                "createraw",
                "-i",
                src_bin.to_str().unwrap(),
                "-o",
                chd_path.to_str().unwrap(),
                "-hs",
                &hs.to_string(),
                "-us",
                &us.to_string(),
                "-c",
                "zlib",
                "-f",
            ])
            .status()
            .unwrap();
        assert!(status.success());

        let f = File::open(&chd_path).unwrap();
        let mut chd = ChdFile::open(f).unwrap();
        let mut out_file = File::create(&out_path).unwrap();
        extract_raw(&mut chd, &mut out_file, None, None, None, None).unwrap();
        assert_eq!(sha1_file(&src_bin), sha1_file(&out_path));
        println!("  Hunk size {:5} bytes (unit {:4} bytes): MATCH", hs, us);
    }
}

fn main() {
    println!("############################################################");
    println!("### EXHAUSTIVE PARITY & CONFIGURATION COMBINATIONS SUITE ###");
    println!("############################################################");

    test_gdrom_gdi_parity();
    test_wipeout_mixed_mode_parity();
    test_slicing_flags_parity();
    test_multi_codec_combinations();
    test_various_hunk_sizes();

    println!("\nALL COMBINATIONS AND CONFIGURATIONS COMPLETED WITH 100% PARITY!");
}