chdlady-disc 0.2.2

Disc geometries and physical media formats for chdlady
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
//! Structured inspection information for media creation operations.

use crate::create::cd::CreateCdOptions;
use crate::create::common::{
    parse_cd_descriptor, DEFAULT_CD_CODECS, DEFAULT_HD_CODECS, DEFAULT_RAW_CODECS,
};
use crate::create::dvd::CreateDvdOptions;
use crate::create::hd::CreateHdOptions;
use crate::create::raw::CreateRawOptions;
use crate::error::DiscError;
use crate::hd::{guess_chs, HD_TEMPLATES};
use std::fs::File;
use std::path::{Path, PathBuf};

/// Helper to format a 64-bit integer with comma separators (e.g. 1,074,341,888).
pub fn format_with_commas(n: u64) -> String {
    let s = n.to_string();
    let bytes = s.as_bytes();
    let len = bytes.len();
    let mut res = String::with_capacity(len + len / 3);
    for (i, &b) in bytes.iter().enumerate() {
        if i > 0 && (len - i).is_multiple_of(3) {
            res.push(',');
        }
        res.push(b as char);
    }
    res
}

/// Helper to format CD frame count as MM:SS:FF.
pub fn msf_string_from_frames(frames: u32) -> String {
    let seconds = frames / 75;
    let rem_frames = frames % 75;
    let minutes = seconds / 60;
    let rem_seconds = seconds % 60;
    format!("{:02}:{:02}:{:02}", minutes, rem_seconds, rem_frames)
}

/// Helper to get the canonical codec name from a FourCC.
pub fn codec_name(codec: u32) -> &'static str {
    match &codec.to_be_bytes() {
        b"zlib" => "Deflate",
        b"zstd" => "Zstandard",
        b"lzma" => "LZMA",
        b"huff" => "Huffman",
        b"flac" => "FLAC",
        b"cdzl" => "CD Deflate",
        b"cdzs" => "CD Zstandard",
        b"cdlz" => "CD LZMA",
        b"cdfl" => "CD FLAC",
        b"avhu" => "A/V Huffman",
        _ => "unknown",
    }
}

/// Helper to format FourCC codec array into a friendly string matching chdman.
pub fn format_codecs(codecs: &[u32; 4]) -> String {
    if codecs[0] == 0 {
        return "none".to_string();
    }
    let mut parts = Vec::new();
    for &c in codecs {
        if c == 0 {
            break;
        }
        let fourcc = match std::str::from_utf8(&c.to_be_bytes()) {
            Ok(s) => s.to_string(),
            Err(_) => format!("{:#010x}", c),
        };
        let name = codec_name(c);
        parts.push(format!("{} ({})", fourcc, name));
    }
    parts.join(", ")
}

/// Structured inspection information for CD creation.
#[derive(Debug, Clone)]
pub struct CdCreateInfo {
    /// Target CHD output path.
    pub output_path: PathBuf,
    /// Optional parent CHD path.
    pub parent_path: Option<PathBuf>,
    /// Input descriptor path (CUE, TOC, or GDI).
    pub input_path: PathBuf,
    /// Number of audio/data tracks on disc.
    pub num_tracks: usize,
    /// Total original frames before track padding (origtotalsectors).
    pub total_frames: u32,
    /// Padded sectors written to CHD.
    pub padded_sectors: u32,
    /// Total logical bytes of disc content.
    pub logical_bytes: u64,
    /// CHD hunk size in bytes.
    pub hunk_size: u32,
    /// Compression codecs.
    pub codecs: [u32; 4],
}

/// Structured inspection information for DVD creation.
#[derive(Debug, Clone)]
pub struct DvdCreateInfo {
    /// Target CHD output path.
    pub output_path: PathBuf,
    /// Optional parent CHD path.
    pub parent_path: Option<PathBuf>,
    /// Input ISO image path.
    pub input_path: PathBuf,
    /// Starting byte offset in source file.
    pub input_start: u64,
    /// Total byte length from source file.
    pub input_length: u64,
    /// Total source file byte size.
    pub input_total_size: u64,
    /// Total logical bytes of DVD image.
    pub logical_bytes: u64,
    /// CHD hunk size in bytes.
    pub hunk_size: u32,
    /// Compression codecs.
    pub codecs: [u32; 4],
}

/// Structured inspection information for hard disk creation.
#[derive(Debug, Clone)]
pub struct HdCreateInfo {
    /// Target CHD output path.
    pub output_path: PathBuf,
    /// Optional parent CHD path.
    pub parent_path: Option<PathBuf>,
    /// Optional input raw image path.
    pub input_path: Option<PathBuf>,
    /// Starting byte offset in source file.
    pub input_start: u64,
    /// Total byte length from source file.
    pub input_length: u64,
    /// Total source file byte size.
    pub input_total_size: u64,
    /// Hard disk template name if specified.
    pub template_name: Option<String>,
    /// Physical cylinders.
    pub cylinders: u32,
    /// Physical heads.
    pub heads: u32,
    /// Physical sectors.
    pub sectors: u32,
    /// Sector size in bytes.
    pub sector_size: u32,
    /// CHD hunk size in bytes.
    pub hunk_size: u32,
    /// Total logical bytes of hard disk.
    pub logical_bytes: u64,
    /// Compression codecs.
    pub codecs: [u32; 4],
}

/// Structured inspection information for raw binary creation.
#[derive(Debug, Clone)]
pub struct RawCreateInfo {
    /// Target CHD output path.
    pub output_path: PathBuf,
    /// Optional parent CHD path.
    pub parent_path: Option<PathBuf>,
    /// Input raw binary file path.
    pub input_path: PathBuf,
    /// Starting byte offset in source file.
    pub input_start: u64,
    /// Total byte length from source file.
    pub input_length: u64,
    /// Total source file byte size.
    pub input_total_size: u64,
    /// Total logical bytes.
    pub logical_bytes: u64,
    /// CHD hunk size in bytes.
    pub hunk_size: u32,
    /// Media unit size in bytes.
    pub unit_size: u32,
    /// Compression codecs.
    pub codecs: [u32; 4],
}

/// Inspects and validates CD creation parameters without modifying filesystem.
pub fn inspect_create_cd(
    input_path: &Path,
    output_path: &Path,
    options: &CreateCdOptions,
) -> Result<CdCreateInfo, DiscError> {
    let toc = parse_cd_descriptor(input_path)?;

    let mut origtotalsectors = 0u32;
    let mut totalsectors = 0u32;
    for track in &toc.tracks {
        let padded = track.frames.div_ceil(4);
        let extra_frames = padded * 4 - track.frames;
        origtotalsectors += track.frames;
        totalsectors += track.frames + extra_frames;
    }

    let unit_size = 2448u32;
    let hunk_size = options.hunk_size.unwrap_or(8 * 2448);
    let logical_bytes = totalsectors as u64 * unit_size as u64;
    let codecs = options.codecs.unwrap_or(DEFAULT_CD_CODECS);

    Ok(CdCreateInfo {
        output_path: output_path.to_path_buf(),
        parent_path: options.parent_path.clone(),
        input_path: input_path.to_path_buf(),
        num_tracks: toc.tracks.len(),
        total_frames: origtotalsectors,
        padded_sectors: totalsectors,
        logical_bytes,
        hunk_size,
        codecs,
    })
}

/// Inspects and validates DVD creation parameters without modifying filesystem.
pub fn inspect_create_dvd(
    input_path: &Path,
    output_path: &Path,
    options: &CreateDvdOptions,
) -> Result<DvdCreateInfo, DiscError> {
    let input_file = File::open(input_path)?;
    let total_size = input_file.metadata()?.len();

    let unit_size = 2048u32;
    let hunk_size = options.hunk_size.unwrap_or(4096);

    let start = match (options.start_byte, options.start_hunk) {
        (Some(b), _) => b,
        (None, Some(h)) => h * hunk_size as u64,
        (None, None) => 0,
    };
    let length = match (options.length_bytes, options.length_hunks) {
        (Some(b), _) => b,
        (None, Some(h)) => h * hunk_size as u64,
        (None, None) => total_size.saturating_sub(start),
    };

    let end = start
        .checked_add(length)
        .ok_or_else(|| DiscError::InvalidMetadata("specified range overflows u64".into()))?;
    if end > total_size {
        return Err(DiscError::InvalidMetadata(
            "specified range exceeds input file size".into(),
        ));
    }
    if !length.is_multiple_of(unit_size as u64) {
        return Err(DiscError::InvalidMetadata(format!(
            "data length {} is not divisible by DVD sector size 2048",
            length
        )));
    }

    let codecs = options.codecs.unwrap_or(DEFAULT_HD_CODECS);

    Ok(DvdCreateInfo {
        output_path: output_path.to_path_buf(),
        parent_path: options.parent_path.clone(),
        input_path: input_path.to_path_buf(),
        input_start: start,
        input_length: length,
        input_total_size: total_size,
        logical_bytes: length,
        hunk_size,
        codecs,
    })
}

/// Inspects and validates hard disk creation parameters without modifying filesystem.
pub fn inspect_create_hd(
    input_path: Option<&Path>,
    output_path: &Path,
    options: &CreateHdOptions,
) -> Result<HdCreateInfo, DiscError> {
    let mut sector_size = options.sector_size.unwrap_or(512);
    if sector_size == 0 {
        return Err(DiscError::InvalidMetadata(
            "sector size must be non-zero".into(),
        ));
    }
    let mut cylinders = 0u32;
    let mut heads = 0u32;
    let mut sectors = 0u32;
    let mut template_name = None;

    if let Some(t_idx) = options.template {
        if t_idx >= HD_TEMPLATES.len() {
            return Err(DiscError::InvalidMetadata(format!(
                "invalid hard disk template index {}",
                t_idx
            )));
        }
        let t = &HD_TEMPLATES[t_idx];
        cylinders = t.cylinders;
        heads = t.heads;
        sectors = t.sectors;
        sector_size = t.sector_size;
        template_name = Some(format!("{} {}", t.manufacturer, t.model));
    } else if let Some((c, h, s)) = options.chs {
        cylinders = c;
        heads = h;
        sectors = s;
    }

    if let Some(ref id_path) = options.ident_path {
        let ident_data = std::fs::read(id_path)?;
        if ident_data.len() < 14 {
            return Err(DiscError::InvalidMetadata(
                "ident file too short (< 14 bytes)".into(),
            ));
        }
        if cylinders == 0 {
            let c = u16::from_le_bytes([ident_data[2], ident_data[3]]) as u32;
            let h = u16::from_le_bytes([ident_data[6], ident_data[7]]) as u32;
            let s = u16::from_le_bytes([ident_data[12], ident_data[13]]) as u32;
            if (c as u64 * h as u64 * s as u64) < 16_514_064 {
                cylinders = c;
                heads = h;
                sectors = s;
            }
        }
    }

    let hunk_size = options
        .hunk_size
        .unwrap_or_else(|| ((4096 / sector_size) * sector_size).max(sector_size));

    let (input_start, input_length, total_file_size, logical_bytes) =
        if let Some(in_path) = input_path {
            let file = File::open(in_path)?;
            let total_file_size = file.metadata()?.len();
            let start = match (options.start_byte, options.start_hunk) {
                (Some(b), _) => b,
                (None, Some(h)) => h * hunk_size as u64,
                (None, None) => 0,
            };
            let length = match (options.length_bytes, options.length_hunks) {
                (Some(b), _) => b,
                (None, Some(h)) => h * hunk_size as u64,
                (None, None) => total_file_size.saturating_sub(start),
            };
            let end = start.checked_add(length).ok_or_else(|| {
                DiscError::InvalidMetadata("specified range overflows u64".into())
            })?;
            if end > total_file_size {
                return Err(DiscError::InvalidMetadata(
                    "specified range exceeds input file size".into(),
                ));
            }
            if cylinders == 0 {
                let geo = guess_chs(length, sector_size)?;
                cylinders = geo.cylinders;
                heads = geo.heads;
                sectors = geo.sectors;
            }
            let totalsectors = cylinders as u64 * heads as u64 * sectors as u64;
            let expected_bytes = totalsectors * sector_size as u64;
            (start, length, total_file_size, expected_bytes)
        } else {
            let capacity = if cylinders != 0 {
                (cylinders as u64 * heads as u64 * sectors as u64) * sector_size as u64
            } else if let Some(sz) = options.size {
                let geo = guess_chs(sz, sector_size)?;
                cylinders = geo.cylinders;
                heads = geo.heads;
                sectors = geo.sectors;
                (cylinders as u64 * heads as u64 * sectors as u64) * sector_size as u64
            } else {
                return Err(DiscError::InvalidMetadata(
                    "length or CHS geometry must be specified for blank hard disk".into(),
                ));
            };
            (0, capacity, capacity, capacity)
        };

    let codecs = if input_path.is_none() {
        [0, 0, 0, 0]
    } else {
        options.codecs.unwrap_or(DEFAULT_HD_CODECS)
    };

    Ok(HdCreateInfo {
        output_path: output_path.to_path_buf(),
        parent_path: options.parent_path.clone(),
        input_path: input_path.map(|p| p.to_path_buf()),
        input_start,
        input_length,
        input_total_size: total_file_size,
        template_name,
        cylinders,
        heads,
        sectors,
        sector_size,
        hunk_size,
        logical_bytes,
        codecs,
    })
}

/// Inspects and validates raw binary creation parameters without modifying filesystem.
pub fn inspect_create_raw(
    input_path: &Path,
    output_path: &Path,
    options: &CreateRawOptions,
) -> Result<RawCreateInfo, DiscError> {
    let input_file = File::open(input_path)?;
    let total_size = input_file.metadata()?.len();

    let unit_size = options.unit_size;
    if unit_size == 0 {
        return Err(DiscError::InvalidMetadata(
            "unit size must be non-zero".into(),
        ));
    }
    let hunk_size = options
        .hunk_size
        .unwrap_or_else(|| ((4096 / unit_size) * unit_size).max(unit_size));

    let start = match (options.start_byte, options.start_hunk) {
        (Some(b), _) => b,
        (None, Some(h)) => h * hunk_size as u64,
        (None, None) => 0,
    };
    let length = match (options.length_bytes, options.length_hunks) {
        (Some(b), _) => b,
        (None, Some(h)) => h * hunk_size as u64,
        (None, None) => total_size.saturating_sub(start),
    };

    let end = start
        .checked_add(length)
        .ok_or_else(|| DiscError::InvalidMetadata("specified range overflows u64".into()))?;
    if end > total_size {
        return Err(DiscError::InvalidMetadata(
            "specified range exceeds input file size".into(),
        ));
    }
    if !length.is_multiple_of(unit_size as u64) {
        return Err(DiscError::InvalidMetadata(format!(
            "data length {} is not divisible by unit size {}",
            length, unit_size
        )));
    }

    let codecs = options.codecs.unwrap_or(DEFAULT_RAW_CODECS);

    Ok(RawCreateInfo {
        output_path: output_path.to_path_buf(),
        parent_path: options.parent_path.clone(),
        input_path: input_path.to_path_buf(),
        input_start: start,
        input_length: length,
        input_total_size: total_size,
        logical_bytes: length,
        hunk_size,
        unit_size,
        codecs,
    })
}