libchdman-rs 0.288.0

Rust wrapper around MAME's CHD (Compressed Hunks of Data) core. Supports CD/DVD/HD CHD read+write and ships pre-built static archives via the `prebuilt` feature for fast CI builds.
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
//! Hard-disk CHDs (chdman `createhd` / `extracthd` parity).
//!
//! Streams a raw disk image into a CHD with a `GDDD` geometry record,
//! and (optionally) an `IDNT` ident blob — matching chdman's
//! `do_create_hd` byte-for-byte for the same input. Geometry is either
//! supplied by the caller or derived via the same heuristic chdman uses
//! (`guess_chs` in `chdman.cpp`).
//!
//! For runtime sector-level reads and writes against an existing HD CHD
//! (the surface MAME's `harddisk_image_device` exposes to an emulated
//! machine) see [`HdImage`].

use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;

use crate::enhancements::metadata::tags::{HARD_DISK_IDENT_METADATA_TAG, HARD_DISK_METADATA_TAG};
use crate::streaming::{run_compression, StreamingSource};
use crate::{sys, Chd, ChdCompressor, ChdError, CompressionProgress, Result, CHD_CODEC_ZLIB};

/// Cylinder/head/sector geometry plus bytes-per-sector.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HdGeometry {
    pub cylinders: u32,
    pub heads: u32,
    pub sectors: u32,
    pub sector_bytes: u32,
}

impl HdGeometry {
    /// Total logical bytes implied by this geometry.
    pub fn logical_bytes(&self) -> u64 {
        u64::from(self.cylinders)
            * u64::from(self.heads)
            * u64::from(self.sectors)
            * u64::from(self.sector_bytes)
    }
}

/// Options for [`create_from_reader`].
#[derive(Debug, Clone)]
pub struct HdCreateOptions {
    /// Logical size of the destination CHD, in bytes. Must be a multiple
    /// of `unit_size`. The reader is zero-padded if it ends earlier; the
    /// CHD reports this exact size in `logical_bytes()`.
    pub logical_size: u64,
    /// Hunk size in bytes. chdman default is 4096. Must be a multiple of
    /// `unit_size`.
    pub hunk_size: u32,
    /// Unit (sector) size in bytes. chdman default is 512.
    pub unit_size: u32,
    /// Codec slots. Default `[zlib, 0, 0, 0]`. Use [`crate::parse_codec_spec`]
    /// to plumb chdman-style mnemonic strings.
    pub codecs: [u32; 4],
    /// If supplied, written verbatim into a `GDDD` record. Otherwise
    /// derived from `logical_size / unit_size` via the same heuristic
    /// chdman uses.
    pub geometry: Option<HdGeometry>,
    /// Optional identification blob written as an `IDNT` metadata record.
    pub ident: Option<Vec<u8>>,
}

impl Default for HdCreateOptions {
    fn default() -> Self {
        Self {
            logical_size: 0,
            hunk_size: 4096,
            unit_size: 512,
            codecs: [CHD_CODEC_ZLIB, 0, 0, 0],
            geometry: None,
            ident: None,
        }
    }
}

/// Heuristic from chdman's `guess_chs` (chdman.cpp:1115). Finds CHS
/// values whose product equals `total_sectors`, preferring large sector
/// counts (≤63) and head counts (≤16). If no clean factorization
/// exists, increments `total_sectors` and retries — i.e. allows a tiny
/// rounding-up to land on a factorable shape, just like chdman.
///
/// Always terminates for any positive input: at the limit, `(total, 1, 1)`
/// is always a valid factorization once we walk far enough.
pub fn compute_chs(logical_bytes: u64, sector_size: u32) -> Result<HdGeometry> {
    if logical_bytes == 0 || sector_size == 0 {
        return Err(ChdError::InvalidData);
    }
    if !logical_bytes.is_multiple_of(u64::from(sector_size)) {
        return Err(ChdError::InvalidData);
    }

    let initial = logical_bytes / u64::from(sector_size);
    let mut total: u64 = initial;
    loop {
        for cur_sectors in (2u32..=63).rev() {
            if total.is_multiple_of(u64::from(cur_sectors)) {
                let total_heads = total / u64::from(cur_sectors);
                for cur_heads in (2u32..=16).rev() {
                    if total_heads.is_multiple_of(u64::from(cur_heads)) {
                        let cylinders = (total_heads / u64::from(cur_heads)) as u32;
                        return Ok(HdGeometry {
                            cylinders,
                            heads: cur_heads,
                            sectors: cur_sectors,
                            sector_bytes: sector_size,
                        });
                    }
                }
            }
        }
        // No factorization at this total — bump and retry, mirroring
        // chdman's outer for-loop.
        total = total.checked_add(1).ok_or(ChdError::InvalidData)?;
    }
}

/// Format a geometry record exactly as chdman writes it:
/// `"CYLS:%d,HEADS:%d,SECS:%d,BPS:%d"`. The shim writes a NUL terminator
/// alongside, matching MAME's `write_metadata` convention.
pub fn format_gddd(g: HdGeometry) -> Vec<u8> {
    let mut s = format!(
        "CYLS:{},HEADS:{},SECS:{},BPS:{}",
        g.cylinders, g.heads, g.sectors, g.sector_bytes
    )
    .into_bytes();
    s.push(0);
    s
}

/// Parse a `GDDD` payload back into geometry. Tolerant to a trailing
/// NUL (which `format_gddd` always writes, and chdman writes too).
pub fn read_geometry(chd: &Chd) -> Result<HdGeometry> {
    let raw = chd.read_metadata(HARD_DISK_METADATA_TAG, 0)?;
    let s = std::str::from_utf8(&raw)
        .map_err(|_| ChdError::InvalidMetadata)?
        .trim_end_matches('\0');
    let parts: Vec<_> = s.split(',').collect();
    if parts.len() != 4 {
        return Err(ChdError::InvalidMetadata);
    }
    fn parse_kv(s: &str, prefix: &str) -> Result<u32> {
        s.strip_prefix(prefix)
            .ok_or(ChdError::InvalidMetadata)?
            .parse::<u32>()
            .map_err(|_| ChdError::InvalidMetadata)
    }
    Ok(HdGeometry {
        cylinders: parse_kv(parts[0], "CYLS:")?,
        heads: parse_kv(parts[1], "HEADS:")?,
        sectors: parse_kv(parts[2], "SECS:")?,
        sector_bytes: parse_kv(parts[3], "BPS:")?,
    })
}

fn validate_options(o: &HdCreateOptions) -> Result<()> {
    if o.unit_size == 0 || o.hunk_size == 0 {
        return Err(ChdError::InvalidData);
    }
    if !o.hunk_size.is_multiple_of(o.unit_size) {
        return Err(ChdError::InvalidData);
    }
    if !o.logical_size.is_multiple_of(u64::from(o.unit_size)) {
        return Err(ChdError::InvalidData);
    }
    Ok(())
}

/// Stream `reader` into a hard-disk CHD at `out_path`.
///
/// The reader is consumed sequentially, never seeked, and never
/// buffered in full — only one hunk at a time. If it ends before
/// `opts.logical_size` bytes are produced, the tail is zero-padded.
///
/// On cancellation (i.e. `cancel()` returns true between hunks): drops
/// the partial output file and returns [`ChdError::Cancelled`].
pub fn create_from_reader<R: Read>(
    reader: R,
    out_path: &Path,
    opts: HdCreateOptions,
    progress: &mut dyn FnMut(CompressionProgress),
    cancel: &dyn Fn() -> bool,
) -> Result<()> {
    validate_options(&opts)?;

    let geom = match opts.geometry {
        Some(g) => g,
        None => compute_chs(opts.logical_size, opts.unit_size)?,
    };

    let source = StreamingSource::new(reader, opts.logical_size);
    let mut compressor = ChdCompressor::new(source);
    let path_str = out_path.to_str().ok_or(ChdError::InvalidFile)?.to_string();
    compressor.create_file(
        &path_str,
        opts.logical_size,
        opts.hunk_size,
        opts.unit_size,
        opts.codecs,
    )?;

    // Metadata must be written before compress_begin spins up workers,
    // so it lives in the on-disk header. chdman writes GDDD then IDNT
    // in that order; preserve.
    write_compressor_metadata(
        &mut compressor,
        HARD_DISK_METADATA_TAG,
        0,
        &format_gddd(geom),
        1,
    )?;
    if let Some(ident) = &opts.ident {
        write_compressor_metadata(&mut compressor, HARD_DISK_IDENT_METADATA_TAG, 0, ident, 1)?;
    }

    run_compression(compressor, out_path, progress, cancel)
}

/// File-input convenience. Equivalent to opening `in_path` and calling
/// [`create_from_reader`].
pub fn create_from_path(
    in_path: &Path,
    out_path: &Path,
    opts: HdCreateOptions,
    progress: &mut dyn FnMut(CompressionProgress),
    cancel: &dyn Fn() -> bool,
) -> Result<()> {
    let mut effective = opts;
    if effective.logical_size == 0 {
        // Caller didn't override: take the file's size.
        let meta = std::fs::metadata(in_path).map_err(|_| ChdError::InvalidFile)?;
        effective.logical_size = meta.len();
    }
    let f = File::open(in_path).map_err(|_| ChdError::InvalidFile)?;
    create_from_reader(f, out_path, effective, progress, cancel)
}

/// Stream the logical contents of `chd_path` to `writer`. Reports bytes
/// written via the progress callback.
pub fn extract_to_writer<W: Write>(
    chd_path: &Path,
    mut writer: W,
    progress: &mut dyn FnMut(u64),
) -> Result<()> {
    let chd = Chd::open(chd_path.to_str().ok_or(ChdError::InvalidFile)?, false, None)?;
    let total = chd.logical_bytes();
    let hunk = chd.hunk_bytes() as usize;
    let mut buf = vec![0u8; hunk];
    let mut written: u64 = 0;
    let mut offset: u64 = 0;
    while offset < total {
        let chunk = std::cmp::min(hunk as u64, total - offset) as usize;
        chd.read_bytes(offset, &mut buf[..chunk])?;
        writer
            .write_all(&buf[..chunk])
            .map_err(|_| ChdError::CompressionError)?;
        offset += chunk as u64;
        written += chunk as u64;
        progress(written);
    }
    Ok(())
}

/// File-output convenience for [`extract_to_writer`].
pub fn extract_to_path(
    chd_path: &Path,
    out_path: &Path,
    progress: &mut dyn FnMut(u64),
) -> Result<()> {
    let f = File::create(out_path).map_err(|_| ChdError::InvalidFile)?;
    extract_to_writer(chd_path, f, progress)
}

// `ChdCompressor` has no public `write_metadata`; reach through the
// shim using its underlying chd_file pointer. The compressor is a
// subclass, so the cast is safe.
fn write_compressor_metadata(
    compressor: &mut ChdCompressor,
    tag: u32,
    index: u32,
    data: &[u8],
    flags: u8,
) -> Result<()> {
    // Internal: ChdCompressor wraps the C++ chd_file_compressor which
    // inherits from chd_file. The shim uses the same chd_file_t pointer
    // type, so we can call chd_shim_write_metadata against it.
    let raw = compressor.as_chd_file_ptr();
    let err = unsafe {
        sys::chd_shim_write_metadata(
            raw,
            tag,
            index,
            data.as_ptr() as *const _,
            data.len() as u32,
            flags,
        )
    };
    if err == ChdError::NoError {
        Ok(())
    } else {
        Err(err)
    }
}

/// Block-device view over a hard-disk CHD — the API surface MAME's
/// `harddisk_image_device` exposes to a running emulated machine.
/// Wraps a writeable [`Chd`] and its parsed [`HdGeometry`] (from the
/// `GDDD` record), and routes per-sector reads/writes through
/// `read_bytes` / `write_bytes`.
///
/// Use [`HdImage::open`] for an uncompressed CHD that should be modified
/// in place. For a compressed source CHD, use [`HdImage::open_with_diff`]
/// — it opens the source read-only as the parent and routes writes into
/// a fresh uncompressed child CHD, which is exactly the strategy MAME
/// uses for runtime writes against a compressed image.
pub struct HdImage {
    // Field order is load-bearing: Rust drops fields in declaration
    // order, so `chd` (the diff/child) must come before `parent` so the
    // child is freed first. MAME's `chd_file` stores `m_parent` as a
    // *non-owning* aliasing shared_ptr (chd.cpp:681,841), so the child
    // would dereference a freed parent if we dropped them in the wrong
    // order — writes return InvalidData when that happens.
    chd: Chd,
    // Held purely for its Drop side effect — see field-order comment
    // above. Read access not exposed.
    #[allow(dead_code)]
    parent: Option<Chd>,
    geometry: HdGeometry,
}

impl HdImage {
    /// Open an uncompressed HD CHD writeable. Fails if the CHD is
    /// compressed (MAME's `write_hunk` / `write_bytes` reject compressed
    /// targets) or has no `GDDD` record.
    pub fn open(path: &Path) -> Result<Self> {
        let chd = Chd::open(path.to_str().ok_or(ChdError::InvalidFile)?, true, None)?;
        let geometry = read_geometry(&chd)?;
        Ok(Self {
            chd,
            parent: None,
            geometry,
        })
    }

    /// Open `parent_path` read-only and create `diff_path` as an
    /// uncompressed child CHD (writes land in the diff). Mirrors what
    /// MAME does at runtime when an emulated machine writes to a
    /// compressed CHD: the parent stays untouched, all modifications
    /// flow into the diff.
    ///
    /// `diff_path` is created fresh; if it already exists the call
    /// fails. To re-open an existing diff against the same parent,
    /// use [`HdImage::reopen_diff`].
    ///
    /// Internally clones every metadata record from the parent into the
    /// diff (MAME's `create(..., parent)` doesn't propagate metadata —
    /// chdman's `do_create_hd` does this clone explicitly, chdman.cpp:1939).
    pub fn open_with_diff(parent_path: &Path, diff_path: &Path) -> Result<Self> {
        let parent = Chd::open(
            parent_path.to_str().ok_or(ChdError::InvalidFile)?,
            false,
            None,
        )?;
        let logical = parent.logical_bytes();
        let hunk_bytes = parent.hunk_bytes();
        // Create + clone metadata in this scope so the writer handle is
        // dropped (and the file flushed/closed) before we re-open it
        // writeable below.
        {
            let mut diff = Chd::create_with_parent(
                diff_path.to_str().ok_or(ChdError::InvalidFile)?,
                logical,
                hunk_bytes,
                [0; 4],
                &parent,
            )?;
            diff.clone_all_metadata(&parent)?;
        }
        // Drop the read-only parent handle here so reopen_diff can take
        // its own; reopen_diff will keep the new parent alive for the
        // lifetime of the returned HdImage.
        drop(parent);
        Self::reopen_diff(parent_path, diff_path)
    }

    /// Re-open a previously-created diff against its parent. The
    /// returned `HdImage` keeps the parent `Chd` alive for its full
    /// lifetime — MAME's child holds a non-owning pointer at the parent,
    /// so dropping the parent early would dangle.
    pub fn reopen_diff(parent_path: &Path, diff_path: &Path) -> Result<Self> {
        let parent = Chd::open(
            parent_path.to_str().ok_or(ChdError::InvalidFile)?,
            false,
            None,
        )?;
        let chd = Chd::open(
            diff_path.to_str().ok_or(ChdError::InvalidFile)?,
            true,
            Some(&parent),
        )?;
        let geometry = read_geometry(&chd)?;
        Ok(Self {
            chd,
            parent: Some(parent),
            geometry,
        })
    }

    /// Parsed `GDDD` geometry record (cylinders / heads / sectors /
    /// bytes-per-sector).
    pub fn geometry(&self) -> HdGeometry {
        self.geometry
    }

    /// Bytes per sector, from the `GDDD` record. Read/write buffers must
    /// match this exactly.
    pub fn sector_size(&self) -> u32 {
        self.geometry.sector_bytes
    }

    /// Total addressable sectors — `logical_bytes / sector_size`. Valid
    /// LBAs are `0..sector_count()`.
    pub fn sector_count(&self) -> u64 {
        self.chd.logical_bytes() / u64::from(self.geometry.sector_bytes)
    }

    /// Read one sector at logical block address `lba`. `buf` must be
    /// exactly [`sector_size`](Self::sector_size) bytes.
    pub fn read_sector(&self, lba: u64, buf: &mut [u8]) -> Result<()> {
        let ss = self.geometry.sector_bytes as usize;
        if buf.len() != ss {
            return Err(ChdError::InvalidData);
        }
        if lba >= self.sector_count() {
            return Err(ChdError::InvalidData);
        }
        self.chd.read_bytes(lba * ss as u64, buf)
    }

    /// Write one sector at `lba`. `buf` must be exactly
    /// [`sector_size`](Self::sector_size) bytes.
    pub fn write_sector(&mut self, lba: u64, buf: &[u8]) -> Result<()> {
        let ss = self.geometry.sector_bytes as usize;
        if buf.len() != ss {
            return Err(ChdError::InvalidData);
        }
        if lba >= self.sector_count() {
            return Err(ChdError::InvalidData);
        }
        self.chd.write_bytes(lba * ss as u64, buf)
    }

    /// Borrow the underlying [`Chd`] for lower-level reads
    /// (`read_metadata`, `read_hunk`, etc.) without giving up the
    /// `HdImage`. Returning a borrow rather than consuming `self` keeps
    /// the parent (if any) alive — handing out an owned `Chd` for a
    /// diff would dangle the moment the parent dropped.
    pub fn as_chd(&self) -> &Chd {
        &self.chd
    }

    /// Mutable variant of [`Self::as_chd`] for `write_metadata`,
    /// `write_hunk`, etc.
    pub fn as_chd_mut(&mut self) -> &mut Chd {
        &mut self.chd
    }
}