Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions CHDStudio.Tests/ChdSharpEncoderServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,48 @@ public void CreateDvd_EncodesVerifiableDvdChd()
Assert.Equal(2048u, ReadHeader(chdPath).UnitBytes);
}

[Fact]
public void CreateDvd_Psp2048Hunk_EncodesVerifiableChd()
{
File.WriteAllBytes(PathFor("psp.iso"), new byte[2048 * 20]);
var chdPath = PathFor("psp.chd");

ChdSharpEncoderService.Encode(
"createdvd",
PathFor("psp.iso"),
chdPath,
false,
2,
CancellationToken.None,
hunkBytesOverride: 2048
);

AssertVerifies(chdPath);
var header = ReadHeader(chdPath);
Assert.Equal(2048u, header.UnitBytes);
Assert.Equal(2048u, header.HunkBytes);
}

[Fact]
public void CreateDvd_InvalidHunkSize_Throws()
{
File.WriteAllBytes(PathFor("invalid.iso"), new byte[2048 * 20]);

var ex = Assert.Throws<ArgumentException>(() =>
ChdSharpEncoderService.Encode(
"createdvd",
PathFor("invalid.iso"),
PathFor("invalid.chd"),
false,
2,
CancellationToken.None,
hunkBytesOverride: 3000
)
);

Assert.Contains("multiple of the", ex.Message, StringComparison.Ordinal);
}

[Fact]
public void CreateHd_EncodesVerifiableHardDiskChd()
{
Expand Down
5 changes: 5 additions & 0 deletions CHDStudio/MainWindow.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,11 @@
Content="Force DVD"
IsCheckedChanged="ForceCreateDvdCheckBox_IsCheckedChanged"
ToolTip.Tip="Force CHDMAN to use the 'createdvd' command" />
<CheckBox
x:Name="PspHunkSizeCheckBox"
Content="PSP 2048 hunk"
IsCheckedChanged="PspHunkSizeCheckBox_IsCheckedChanged"
ToolTip.Tip="Create a DVD-mode CHD with a 2048-byte hunk size (chdman createdvd -hs 2048), recommended for PSP ISOs in PPSSPP" />
</StackPanel>
<TextBlock
Text="Compression:"
Expand Down
54 changes: 48 additions & 6 deletions CHDStudio/MainWindow.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ internal partial class MainWindow : Window, IDisposable
private ChdCompressionPreset _conversionCompressionPreset = ChdCompressionPreset.Default;
private string? _conversionParentPath;
private bool _createDeltaChd;
private bool _pspHunkSize;

// Tracks whether a close was requested while an operation was running
private bool _pendingClose;
Expand Down Expand Up @@ -1776,9 +1777,20 @@ private async void StartConversionButton_ClickAsync(object sender, RoutedEventAr
return;
}

var pspHunk = PspHunkSizeCheckBox.IsChecked == true;
if (createDelta && pspHunk)
{
ShowError(
"The PSP 2048-byte hunk size cannot be combined with a delta CHD. "
+ "The parent CHD's hunk size must match, so uncheck one of the options."
);
return;
}

_conversionCompressionPreset = compressionPreset;
_createDeltaChd = createDelta;
_conversionParentPath = createDelta ? parentPath : null;
_pspHunkSize = pspHunk;

RenewCancellationTokenSource();

Expand Down Expand Up @@ -1808,6 +1820,10 @@ out var mins
: null;

LogMessage("--- Starting batch conversion process... ---");
if (pspHunk)
LogMessage(
"PSP mode: using createdvd with a 2048-byte hunk size (-hs 2048)."
);
_wasCancelled = false;

try
Expand Down Expand Up @@ -2044,6 +2060,7 @@ private void SetControlsState(bool enabled)
);
ForceCreateCdCheckBox.IsEnabled = enabled;
ForceCreateDvdCheckBox.IsEnabled = enabled;
PspHunkSizeCheckBox.IsEnabled = enabled;
ConversionCompressionComboBox.IsEnabled = enabled;
CreateDeltaChdCheckBox.IsEnabled = enabled;
ConversionParentChdTextBox.IsEnabled = enabled;
Expand Down Expand Up @@ -6825,11 +6842,15 @@ private async Task<bool> ConvertToChdAsync(
var isRaw = inputFile.EndsWith(FileExtensions.Raw, StringComparison.OrdinalIgnoreCase);
var isIso = inputFile.EndsWith(FileExtensions.Iso, StringComparison.OrdinalIgnoreCase);
var isAvi = inputFile.EndsWith(FileExtensions.Avi, StringComparison.OrdinalIgnoreCase);
// PSP ISOs are 2048-byte-sector images and PPSSPP expects a createdvd CHD with a
// 2048-byte hunk. Laserdisc input has its own verb/hunk layout, so the option does
// not apply to it.
var pspHunk = _pspHunkSize && !isAvi;

var command =
isAvi ? "createld"
: forceCd || (!forceDvd && !isIso && !isImg && !isRaw) ? "createcd"
: forceDvd || isIso ? "createdvd"
: !pspHunk && (forceCd || (!forceDvd && !isIso && !isImg && !isRaw)) ? "createcd"
: pspHunk || forceDvd || isIso ? "createdvd"
: isImg ? "createhd"
: "createraw";

Expand Down Expand Up @@ -6880,6 +6901,9 @@ private async Task<bool> ConvertToChdAsync(
args += " -us 2352";
}

if (pspHunk)
args += " -hs 2048";

if (codecArgument is not null)
args += $" -c {codecArgument}";

Expand Down Expand Up @@ -7692,7 +7716,8 @@ await Task.Run(
fallbackTimeoutCts.Token,
progress.ReportHunk,
codecTags: codecTags,
parentPath: _createDeltaChd ? _conversionParentPath : null
parentPath: _createDeltaChd ? _conversionParentPath : null,
hunkBytesOverride: pspHunk ? 2048u : null
),
fallbackTimeoutCts.Token
);
Expand Down Expand Up @@ -7874,7 +7899,8 @@ await Task.Run(
fallbackTimeoutCts.Token,
progress.ReportHunk,
conservativeCodecs: true,
parentPath: _createDeltaChd ? _conversionParentPath : null
parentPath: _createDeltaChd ? _conversionParentPath : null,
hunkBytesOverride: pspHunk ? 2048u : null
),
fallbackTimeoutCts.Token
);
Expand Down Expand Up @@ -7945,7 +7971,8 @@ await Task.Run(
progress.ReportHunk,
conservativeCodecs: false,
codecTags: [CodecTags.None],
parentPath: null
parentPath: null,
hunkBytesOverride: pspHunk ? 2048u : null
),
fallbackTimeoutCts.Token
);
Expand Down Expand Up @@ -9902,14 +9929,15 @@ private void SearchSubfoldersCheckBox_Changed(object sender, RoutedEventArgs e)
if (IsLoaded) RefreshFileListForActiveTab();
}

/// <summary>Clears the force-DVD option when force-CD is checked.</summary>
/// <summary>Clears the force-DVD and PSP options when force-CD is checked.</summary>
private void ForceCreateCdCheckBox_IsCheckedChanged(object? sender, RoutedEventArgs e)
{
// Only react to the box becoming checked: IsCheckedChanged also fires when it is
// unchecked, and clearing the other box then would undo the user's selection.
if (ForceCreateCdCheckBox.IsChecked == true)
{
ForceCreateDvdCheckBox.IsChecked = false;
PspHunkSizeCheckBox.IsChecked = false;
}
}

Expand All @@ -9920,6 +9948,20 @@ private void ForceCreateDvdCheckBox_IsCheckedChanged(object? sender, RoutedEvent
{
ForceCreateCdCheckBox.IsChecked = false;
}
else if (PspHunkSizeCheckBox.IsChecked == true)
{
PspHunkSizeCheckBox.IsChecked = false;
}
}

/// <summary>Forces DVD mode when the PSP 2048-byte hunk option is checked.</summary>
private void PspHunkSizeCheckBox_IsCheckedChanged(object? sender, RoutedEventArgs e)
{
if (PspHunkSizeCheckBox.IsChecked == true)
{
ForceCreateCdCheckBox.IsChecked = false;
ForceCreateDvdCheckBox.IsChecked = true;
}
}

/// <summary>Logs the operation result summary and awaits the completion message box.</summary>
Expand Down
61 changes: 54 additions & 7 deletions CHDStudio/Services/ChdSharpEncoderService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,12 @@ internal static class ChdSharpEncoderService
/// Optional parent CHD for delta (child) output. The parent's hunk and unit sizes must
/// match the command's; the library throws when they do not.
/// </param>
/// <exception cref="ArgumentException">The command is not a supported creation command.</exception>
/// <param name="hunkBytesOverride">
/// Optional hunk size for the output. Used for the PSP/PPSSPP-compatible
/// <c>createdvd -hs 2048</c> mode; the value must be a whole multiple of the command's unit
/// size. When null the command's chdman-compatible default is used.
/// </param>
/// <exception cref="ArgumentException">The command or hunk size is not supported.</exception>
internal static void Encode(
string command,
string inputPath,
Expand All @@ -90,7 +95,8 @@ internal static void Encode(
Action<HunkProgress>? onHunkCompleted = null,
bool conservativeCodecs = false,
IReadOnlyList<uint>? codecTags = null,
string? parentPath = null
string? parentPath = null,
uint? hunkBytesOverride = null
)
{
var options = new ChdEncodeOptions
Expand All @@ -103,6 +109,9 @@ internal static void Encode(
var cdCodecs = conservativeCodecs ? CdCodecsCompatible : codecTags ?? CdCodecs;
var rawCodecs = conservativeCodecs ? RawCodecsCompatible : codecTags ?? RawCodecs;

if (hunkBytesOverride is { } requestedHunk)
ValidateHunkSize(command, rawUnits2352, requestedHunk);

// chdman refuses inputs whose size is not a whole number of units for the raw commands.
// The built-in encoder has to reject them too: encoding a partial trailing unit would drop
// the tail and still report success, after which the source could be deleted.
Expand Down Expand Up @@ -133,7 +142,7 @@ internal static void Encode(
ChdEncoder.EncodeCd(
inputPath,
outputPath,
CdHunkBytes,
hunkBytesOverride ?? CdHunkBytes,
CdUnitBytes,
cdCodecs,
options,
Expand All @@ -147,7 +156,7 @@ internal static void Encode(
ChdEncoder.EncodeRaw(
inputPath,
outputPath,
RawHunkBytes,
hunkBytesOverride ?? RawHunkBytes,
DvdUnitBytes,
rawCodecs,
options,
Expand Down Expand Up @@ -178,7 +187,7 @@ internal static void Encode(
ChdEncoder.EncodeRaw(
inputPath,
outputPath,
RawHunkBytes,
hunkBytesOverride ?? RawHunkBytes,
HardDiskUnitBytes,
rawCodecs,
options,
Expand All @@ -190,7 +199,8 @@ internal static void Encode(
case "createraw":
{
var unitBytes = rawUnits2352 ? RawCdUnitBytes : HardDiskUnitBytes;
var hunkBytes = Math.Max(RawHunkBytes / unitBytes * unitBytes, unitBytes);
var hunkBytes =
hunkBytesOverride ?? Math.Max(RawHunkBytes / unitBytes * unitBytes, unitBytes);
ChdEncoder.EncodeRaw(
inputPath,
outputPath,
Expand Down Expand Up @@ -225,4 +235,41 @@ internal static void Encode(
);
}
}
}

/// <summary>
/// Rejects a requested hunk size that cannot be represented for the selected command.
/// chdman requires the hunk size to be a whole multiple of the unit size; the built-in
/// encoder enforces the same rule instead of writing a file it cannot describe correctly.
/// </summary>
/// <param name="command">The chdman-compatible creation command.</param>
/// <param name="rawUnits2352">Whether a raw source uses 2352-byte units.</param>
/// <param name="hunkBytes">The requested hunk size in bytes.</param>
private static void ValidateHunkSize(string command, bool rawUnits2352, uint hunkBytes)
{
var unitBytes = command switch
{
"createcd" => CdUnitBytes,
"createdvd" => DvdUnitBytes,
"createhd" => HardDiskUnitBytes,
"createraw" => rawUnits2352 ? RawCdUnitBytes : HardDiskUnitBytes,
_ => 0u,
};

if (unitBytes == 0)
{
throw new ArgumentException(
$"A custom hunk size is not supported for '{command}'.",
nameof(command)
);
}

if (hunkBytes is < 16 or > 1024 * 1024 || hunkBytes % unitBytes != 0)
{
throw new ArgumentException(
$"Hunk size {hunkBytes:N0} must be a multiple of the {unitBytes:N0}-byte unit size and between 16 and 1,048,576 bytes.",
nameof(hunkBytes)
);
}
}
}

2 changes: 1 addition & 1 deletion ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ CHDStudio.exe "C:\ROMs\MyGames"
2. Select your **Source Folder** (containing images or archives).
3. Select your **Output Folder**.
4. *(Optional)* Check "Process smaller files first" to sort by file size.
5. *(Optional)* Check "Force CD" or "Force DVD" to override automatic command detection.
5. *(Optional)* Check "Force CD" or "Force DVD" to override automatic command detection. For PSP ISOs intended for PPSSPP, enable **PSP 2048 hunk** (forces `createdvd -hs 2048`).
6. *(Optional)* Choose a **Compression** preset (Default, Smallest, Most compatible, Auto or Uncompressed).
7. *(Optional)* Enable **Create a delta (child) CHD against a parent** and select the parent CHD.
8. *(Optional)* Set a time limit per file to abort conversions that exceed the specified duration.
Expand Down
2 changes: 1 addition & 1 deletion docs/01-overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ Content is inspected first; the extension only decides the outcome for files who
7. **`.raw` (raw data)** → `createraw` (with an explicit unit size `-us 2352`). Cue descriptors referencing `.raw` audio tracks convert through the cue, whose track types already carry the 2352-byte unit size (`createcd` rejects `-us`).
8. **`.avi` (laserdisc)** → `createld` (A/V `avhu` codec, one frame per hunk), always, regardless of the Force CD/DVD checkboxes.

The user can override 5–7 via **Force CD** / **Force DVD** checkboxes. PBP always extracts first.
The user can override 5-7 via **Force CD** / **Force DVD** checkboxes. The **PSP 2048 hunk** checkbox selects `createdvd -hs 2048` for PPSSPP-compatible PSP ISOs. PBP always extracts first.

Generated cue sheets reference the disc image where it already lies rather than copying it, because chdman resolves a cue's `FILE` entry against the cue's own directory. That also means such a cue must be written on the **same volume** as the image: chdman joins the `FILE` string to the cue's directory unconditionally, so an absolute path becomes `C:\temp\D:\game.iso` and fails.

Expand Down
1 change: 1 addition & 0 deletions docs/04-user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Title-bar buttons: **Donate** (opens the project's donation page), **About** (in
| **Process smaller files first** | Sorts the batch by ascending file size so quick conversions finish first. |
| **Time limit per file** (minutes, default 15) | Aborts a single conversion that exceeds the limit; the file is marked failed and the batch continues. The app enforces a hard cap of 4 hours (`AppConfig.MaxConversionTimeoutHours`). |
| **Force CD** / **Force DVD** | Overrides automatic command detection (`createcd` / `createdvd`). The two checkboxes are mutually exclusive. |
| **PSP 2048 hunk** | Forces `createdvd` with `-hs 2048`, the hunk size PPSSPP recommends for PSP ISOs. The option checks **Force DVD** automatically and is disabled for delta CHDs, whose parent hunk size must match. |
| **Compression** | Codec preset for new CHDs: **Default** (chdman-compatible), **Smallest** (zstd/cdzs, requires a recent MAME/libchdr reader), **Most compatible** (zlib/cdzl), **Auto** (per-platform preset), or **Uncompressed** (raw/DVD/HDD/CD; laserdisc output always uses AVHuff). |
| **Create a delta (child) CHD against a parent** | Stores only the hunks that differ from the selected parent. The parent's hunk and unit sizes must match the selected command. |

Expand Down
7 changes: 5 additions & 2 deletions docs/05-conversion-pipeline.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,17 +113,20 @@ The conversion writes to `<name>.<8hex>.chdtmp` next to the destination and move

```csharp
command = isAvi ? "createld"
: forceCd || (!forceDvd && !isIso && !isImg && !isRaw) ? "createcd"
: forceDvd || isIso ? "createdvd"
: !pspHunk && (forceCd || (!forceDvd && !isIso && !isImg && !isRaw)) ? "createcd"
: pspHunk || forceDvd || isIso ? "createdvd"
: isImg ? "createhd"
: "createraw";
```

- `pspHunk` — the **PSP 2048 hunk** option forces `createdvd` and adds `-hs 2048`, the hunk size PPSSPP recommends for PSP ISOs. The built-in CHDSharp encoder receives the same override. The option is not applied to laserdisc input and is rejected with a delta CHD, whose parent hunk size must match.

- `isAvi` — a laserdisc `.avi` always converts with `createld` (A/V `avhu` codec, one frame per hunk), regardless of the Force CD/DVD checkboxes; `-us` is not added.

- `hasCue = isImg && File.Exists(Path.ChangeExtension(input, ".cue"))` — an `.img` with a sibling `.cue` is treated as a CD image.
- **Verb choice is still extension-driven here**, but this code is now only reached for images that content inspection (§5.2) did not claim. So `Data size ... is not divisible by sector size` should now mean a genuinely broken file rather than a mislabelled one.
- Base args: `{command} -i "<in>" -o "<out>" -f -np {cores}`.
- **PSP 2048 hunk** adds `-hs 2048` on `createdvd`; the built-in encoder uses the same hunk size on its first attempt and both verification retries.
- **`.raw` inputs get `-us 2352` only when the command is `createraw`** — chdman's `createraw` requires an explicit unit size when no parent CHD is supplied ("Unit size must be specified if no output parent CHD is supplied"). A `.raw` input combined with Force CD or Force DVD runs `createcd`/`createdvd`, which reject the option, so it is not appended there.
- **`.cue`/`.toc` descriptors referencing `.raw` tracks do not get `-us`** — `createcd` does not accept the option ("Option '-us' not valid for this command"); it derives the 2352-byte unit size from the cue's own `MODE1/2352`/`MODE2/2352` track types, so the cue is handed over unchanged.
- `-np` (processors) comes from a UI/core setting.
Expand Down
Loading
Loading