diff --git a/CHDStudio.Tests/BugReportServiceTests.cs b/CHDStudio.Tests/BugReportServiceTests.cs index d67d0eb..da590f5 100644 --- a/CHDStudio.Tests/BugReportServiceTests.cs +++ b/CHDStudio.Tests/BugReportServiceTests.cs @@ -454,6 +454,28 @@ public async Task SendBugReportAsyncReturnsFalseOnBadRequest() // A device that became unready mid-batch (removable card reader, network share). [InlineData(" Cannot create the output folder: The device is not ready. : 'H:\\roms\\ps1'.")] [InlineData(" Cannot convert 'game.iso': the source or output could not be read or written (The device is not ready. : 'F:\\CHDStudio_Temp\\x.iso').")] + // A .pbp whose header is not PBP magic and whose content is not a known image format. + [InlineData( + "Failed to extract PBP file: Bloody Roar.PBP (190,840,832 bytes) - Failed to open PBP file: InvalidHeader (code 1)" + )] + [InlineData( + " Bloody Roar.PBP is not a PBP (its header is missing) and its content is not a disc image the app recognises — skipping." + )] + // A genuinely damaged PBP block: the message already tells the user to re-download it. + [InlineData( + " Tekken.PBP: the PBP's disc data is damaged (a compressed block ends before a full 16-sector block) — skipping. Re-download the file." + )] + // No default browser / headless session: the app copies the URL instead. + [InlineData("Failed to open browser: An error occurred trying to start process 'https://example.com' with working directory 'C:\\app'. Class not registered")] + [InlineData("Error opening URL: https://example.com")] + // A release bundle missing the optional MDSSharp assembly. + [InlineData( + "Could not load file or assembly 'MDSSharp, Version=1.2.3.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified." + )] + // A Windows privilege failure while the encoder opens its output file. + [InlineData( + "Failed to convert 'Death Connection (Japan).iso': Error creating CHD file (I:\\Death Connection (Japan).6f9e52f6.chdtmp): A required privilege is not held by the client." + )] public void IsExcludedFromBugReport_KnownPatterns_ReturnsTrue(string message) { Assert.True(BugReportService.IsExcludedFromBugReport(message)); diff --git a/CHDStudio.Tests/ChdSharpLoggerFactoryTests.cs b/CHDStudio.Tests/ChdSharpLoggerFactoryTests.cs index 5c0f627..53fa5f6 100644 --- a/CHDStudio.Tests/ChdSharpLoggerFactoryTests.cs +++ b/CHDStudio.Tests/ChdSharpLoggerFactoryTests.cs @@ -67,4 +67,21 @@ public void LatestWarningReplacesEarlierOne() Assert.NotNull(captured); Assert.Contains("second", captured); } + + /// + /// Hunk-level failures in a user's CHD are diagnostics, not application errors. They are + /// captured for the caller's classified message but must not be forwarded to the + /// bug-report sink as Error events. + /// + [Theory] + [InlineData(LogLevel.Warning, Serilog.Events.LogEventLevel.Information)] + [InlineData(LogLevel.Error, Serilog.Events.LogEventLevel.Information)] + [InlineData(LogLevel.Critical, Serilog.Events.LogEventLevel.Fatal)] + public void LibraryFailuresDoNotBecomeBugReportLevels( + LogLevel input, + Serilog.Events.LogEventLevel expected + ) + { + Assert.Equal(expected, ChdSharpLoggerFactory.MapLevel(input)); + } } diff --git a/CHDStudio.Tests/DiscImageSignatureTests.cs b/CHDStudio.Tests/DiscImageSignatureTests.cs index 1cbafa6..277a0de 100644 --- a/CHDStudio.Tests/DiscImageSignatureTests.cs +++ b/CHDStudio.Tests/DiscImageSignatureTests.cs @@ -86,6 +86,23 @@ public void CookedIsoDataIsNotMistakenForRawCd() Assert.Equal(DiscImageKind.Unknown, DiscImageSignature.Classify(header)); } + [Fact] + public void DetectRecognisesCookedIsoVolumeDescriptor() + { + // A plain 2048-byte-sector ISO has no signature in its first sector; the ISO9660 primary + // volume descriptor at sector 16 is what identifies it. This is the shape of the .pbp + // files that were really renamed ISOs and failed with InvalidHeader. + var path = Path.Combine(_tempDir, "game.pbp"); + var data = new byte[16 * 2048 + 8]; + data[16 * 2048] = 1; + "CD001"u8.CopyTo(data.AsSpan(16 * 2048 + 1)); + data[16 * 2048 + 6] = 1; + File.WriteAllBytes(path, data); + + Assert.Equal(DiscImageKind.Iso, DiscImageSignature.Detect(path)); + Assert.Equal("an ISO9660 disc image", DiscImageSignature.Describe(DiscImageKind.Iso)); + } + [Fact] public void DetectReadsFromDiskAndSurvivesAMissingFile() { diff --git a/CHDStudio.Tests/MainWindowHelperTests.cs b/CHDStudio.Tests/MainWindowHelperTests.cs index 8145506..1908421 100644 --- a/CHDStudio.Tests/MainWindowHelperTests.cs +++ b/CHDStudio.Tests/MainWindowHelperTests.cs @@ -320,6 +320,20 @@ public void IsChdWriteFailure_ClassifiesWriteErrors(string? message, bool expect Assert.Equal(expected, MainWindow.IsChdWriteFailure(message)); } + [Theory] + [InlineData( + "Error creating CHD file (I:\\Game.chdtmp): A required privilege is not held by the client.", + true + )] + [InlineData("Error creating CHD file: Access denied", true)] + [InlineData("Error creating CHD file: Permission denied", true)] + [InlineData("Error creating CHD file: UnauthorizedAccessException", true)] + [InlineData("Error creating CHD file: The disk is full", false)] + public void IsPermissionError_ClassifiesWindowsPrivilegeFailure(string message, bool expected) + { + Assert.Equal(expected, MainWindow.IsPermissionError(message)); + } + [Fact] public void IsDamagedPbpBlock_ShortDeflateStream_ReturnsTrue() { diff --git a/CHDStudio.Tests/MdsTests.cs b/CHDStudio.Tests/MdsTests.cs index 1c5c65d..8056f45 100644 --- a/CHDStudio.Tests/MdsTests.cs +++ b/CHDStudio.Tests/MdsTests.cs @@ -816,7 +816,7 @@ public async Task CookedMode2Form1CdIsCuedAsMode2At2048Bytes() { var mds = WriteMds("CookedMode2.mds", 0x00, new TrackSpec(0x04, 1, 2048, 0)); WriteMdf("CookedMode2.mdf", 2048, 4); - var workDir = Path.Combine(_tempDir, "workmode2"); + var workDir = Path.Join(_tempDir, "workmode2"); Directory.CreateDirectory(workDir); var disc = MdsParser.Parse(mds); @@ -840,7 +840,7 @@ public async Task Mode2Form2CdIsCuedAsMode2At2324Bytes() { var mds = WriteMds("Form2.mds", 0x00, new TrackSpec(0x05, 1, 2324, 0)); WriteMdf("Form2.mdf", 2324, 4); - var workDir = Path.Combine(_tempDir, "workform2"); + var workDir = Path.Join(_tempDir, "workform2"); Directory.CreateDirectory(workDir); var disc = MdsParser.Parse(mds); diff --git a/CHDStudio.Tests/PbpFileTests.cs b/CHDStudio.Tests/PbpFileTests.cs index 9b56b80..07a509b 100644 --- a/CHDStudio.Tests/PbpFileTests.cs +++ b/CHDStudio.Tests/PbpFileTests.cs @@ -251,6 +251,38 @@ public void ExtractToBinCueWithTruncatedDataReturnsTruncatedPsar() } } + [Fact] + public void ExtractToAcceptsAShortFinalBlock() + { + // A disc whose sector count is not a multiple of 16 can store its last index block with + // only the sectors the image actually contains. The block is complete at its own declared + // size, not at the padded 16-sector size, and must extract successfully. + var path = Path.Combine(_tempDir, $"shortfinal_{Guid.NewGuid():N}.pbp"); + new PbpTestFileBuilder() + .WithBlockCount(3) + .WithFinalBlockSectors(7) + .BuildTo(path); + + var error = PbpFile.Open(path, out var pbp); + Assert.Equal(PbpError.None, error); + Assert.NotNull(pbp); + + using (pbp) + { + const uint expectedIsoSize = 39 * PbpDiscInfo.IsoBlockSize; + Assert.Equal(expectedIsoSize, pbp.Discs[0].IsoSize); + + using var outputStream = new MemoryStream(); + pbp.Discs[0].ExtractTo(outputStream); + Assert.Equal(expectedIsoSize, (uint)outputStream.Length); + + var binPath = Path.Combine(_tempDir, $"{Guid.NewGuid():N}.bin"); + var result = pbp.Discs[0].ExtractToBinCue(binPath); + Assert.Equal(PbpError.None, result); + Assert.Equal(expectedIsoSize, (uint)new FileInfo(binPath).Length); + } + } + [Fact] public void ExtractToIgnoresIndexEntriesBeyondDeclaredIsoSize() { diff --git a/CHDStudio.Tests/PbpTestFileBuilder.cs b/CHDStudio.Tests/PbpTestFileBuilder.cs index 4e59f11..c684999 100644 --- a/CHDStudio.Tests/PbpTestFileBuilder.cs +++ b/CHDStudio.Tests/PbpTestFileBuilder.cs @@ -39,6 +39,7 @@ internal sealed class PbpTestFileBuilder private int _trailingPaddingBytes; private int _shortIndexBlockIndex = -1; private int _shortIndexBytes; + private int _finalBlockSectors = -1; private string _title = "Test Game"; @@ -220,6 +221,21 @@ public PbpTestFileBuilder WithShortIndexLength(int blockIndex, int count) return this; } + /// + /// Writes the final ISO index block with only sectors (1-16) + /// instead of a padded 16-sector block, and records the matching total sector count in the + /// ISO9660 volume descriptor. Several PBP authoring tools store the disc's partially filled + /// last block this way; extraction must accept the short final block. + /// + /// Number of sectors stored in the final block, 1-16. + public PbpTestFileBuilder WithFinalBlockSectors(int sectors) + { + _finalBlockSectors = sectors is >= 1 and <= 16 + ? sectors + : throw new ArgumentOutOfRangeException(nameof(sectors)); + return this; + } + /// /// Builds the PBP file and writes it to the specified path. /// @@ -448,7 +464,7 @@ private List WriteIsoIndex(Stream stream, int blockCount) continue; } - var storedLength = _compressBlocks ? GetStoredBlock(blockData, i).Length : BlockSize; + var storedLength = _compressBlocks ? GetStoredBlock(blockData, i).Length : blockData.Length; var entryLength = storedLength; if (i == _shortIndexBlockIndex) entryLength = Math.Max(0, entryLength - _shortIndexBytes); @@ -462,7 +478,7 @@ private List WriteIsoIndex(Stream stream, int blockCount) // uncompressed block, set by pop-fe with compression disabled), SHA-1 at 8. BinaryPrimitives.WriteUInt16LittleEndian( entry.Slice(4, 2), - (ushort)(_compressBlocks ? entryLength : BlockSize) + (ushort)(_compressBlocks ? entryLength : blockData.Length) ); if (!_compressBlocks) entry[6] = 0x01; @@ -471,13 +487,13 @@ private List WriteIsoIndex(Stream stream, int blockCount) { BinaryPrimitives.WriteInt32LittleEndian( entry[4..8], - _compressBlocks ? entryLength : BlockSize + _compressBlocks ? entryLength : blockData.Length ); } stream.Write(entry); - currentOffset += (uint)(_compressBlocks ? storedLength : BlockSize); + currentOffset += (uint)storedLength; } return offsets; @@ -542,11 +558,13 @@ private byte[] GetStoredBlock(byte[] blockData, int blockIndex) private byte[] GetBlockData(int blockIndex) { + var length = GetBlockLength(blockIndex); + if (_incompressibleBlocks) { - var randomBlock = new byte[BlockSize]; + var randomBlock = new byte[length]; var seed = 0x2F6E2B1 ^ (blockIndex * 0x9E3779B1); - for (var i = 0; i < BlockSize; i++) + for (var i = 0; i < length; i++) { seed = seed * 1103515245 + 12345; randomBlock[i] = (byte)((seed >> 16) & 0xFF); @@ -554,10 +572,9 @@ private byte[] GetBlockData(int blockIndex) if (blockIndex == 1) { - var sectorCount = (uint)(_blockCount * 16); BinaryPrimitives.WriteUInt32LittleEndian( randomBlock.AsSpan(104, 4), - sectorCount + TotalSectorCount() ); } @@ -569,13 +586,13 @@ private byte[] GetBlockData(int blockIndex) // Block index 1 (the second block) carries the ISO9660 volume information: // PbpDiscInfo.ReadIsoSize reads the sector count from bytes 104..107 of this // block, exactly like the reference implementation's GetIsoSize(). - var data = new byte[BlockSize]; + var data = new byte[length]; // Fill with a recognizable pattern - for (var i = 0; i < BlockSize; i++) + for (var i = 0; i < length; i++) data[i] = (byte)((i + blockIndex) & 0xFF); - if (_customIsoBlock1Data?.Length <= BlockSize) + if (_customIsoBlock1Data?.Length <= length) { Buffer.BlockCopy(_customIsoBlock1Data, 0, data, 0, _customIsoBlock1Data.Length); } @@ -583,21 +600,36 @@ private byte[] GetBlockData(int blockIndex) { // ISO size in sectors at bytes 104-107 (little-endian uint32) // Total ISO size = sectorCount * IsoBlockSize - // We want _blockCount blocks, each with 16 sectors - var sectorCount = (uint)(_blockCount * 16); - BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(104, 4), sectorCount); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(104, 4), TotalSectorCount()); } return data; } // Other blocks: fill with pattern - var block = new byte[BlockSize]; - for (var i = 0; i < BlockSize; i++) + var block = new byte[length]; + for (var i = 0; i < length; i++) block[i] = (byte)((i + blockIndex * 17) & 0xFF); return block; } + /// Returns the uncompressed byte length of one ISO block (the final one may be short). + /// Zero-based block index. + private int GetBlockLength(int blockIndex) + { + return blockIndex == _blockCount - 1 && _finalBlockSectors > 0 + ? _finalBlockSectors * IsoBlockSize + : BlockSize; + } + + /// Returns the total number of sectors the ISO9660 volume descriptor declares. + private uint TotalSectorCount() + { + return _finalBlockSectors > 0 + ? (uint)((_blockCount - 1) * 16 + _finalBlockSectors) + : (uint)(_blockCount * 16); + } + private byte[] CompressBlock(byte[] data) { byte[] raw; diff --git a/CHDStudio/AboutWindow.axaml.cs b/CHDStudio/AboutWindow.axaml.cs index cf6b724..fe610ac 100644 --- a/CHDStudio/AboutWindow.axaml.cs +++ b/CHDStudio/AboutWindow.axaml.cs @@ -1,4 +1,3 @@ -using System.Diagnostics; using System.Reflection; using Avalonia.Controls; using Avalonia.Input; @@ -6,6 +5,7 @@ using CHDStudio.Dialogs; using CHDStudio.Models; using CHDStudio.Services; +using CHDStudio.Utilities; namespace CHDStudio; @@ -55,27 +55,15 @@ private void OpenUrl_Click(object? sender, RoutedEventArgs e) { if (sender is not Button { Tag: string url } || string.IsNullOrWhiteSpace(url)) return; - try - { - using var process = Process.Start( - new ProcessStartInfo { FileName = url, UseShellExecute = true } - ); - } - catch (Exception ex) - { - if (App.SharedBugReportService != null) - { - _ = App.SharedBugReportService.SendBugReportAsync($"Error opening URL: {url}", ex); - } + if (UrlLauncher.TryOpen(url, out var error)) return; - _ = MessageBox.ShowAsync( - this, - $"Unable to open link: {ex.Message}", - "Error", - MessageBoxButton.Ok, - MessageBoxImage.Error - ); - } + _ = MessageBox.ShowAsync( + this, + $"Unable to open link: {error}", + "Error", + MessageBoxButton.Ok, + MessageBoxImage.Error + ); } private static string GetApplicationVersion() diff --git a/CHDStudio/CHDStudio.csproj b/CHDStudio/CHDStudio.csproj index 671a010..39e3ebb 100644 --- a/CHDStudio/CHDStudio.csproj +++ b/CHDStudio/CHDStudio.csproj @@ -33,10 +33,10 @@ - - - - + + + + diff --git a/CHDStudio/MainWindow.axaml.cs b/CHDStudio/MainWindow.axaml.cs index a835fd3..0fd10c3 100644 --- a/CHDStudio/MainWindow.axaml.cs +++ b/CHDStudio/MainWindow.axaml.cs @@ -4333,10 +4333,20 @@ or PbpError.InvalidSfo // defect: extracting the short block would shift every later block and produce // a corrupt image, so the file is skipped with actionable guidance instead of // filing a bug report for the user's data. - LogWarning( + LogMessage( $" {originalName}: the PBP's disc data is damaged (a compressed block ends before a full 16-sector block) — skipping. Re-download the file." ); } + else if (result.ErrorCode == PbpError.InvalidHeader) + { + // The file does not start with PBP magic and content inspection could not route + // it to any known image format. That is a property of the user's file (renamed, + // incomplete, or unrelated data), not an application defect, so it belongs in + // the activity log without a bug report. + LogMessage( + $" {originalName} is not a PBP (its header is missing) and its content is not a disc image the app recognises — skipping." + ); + } else { var errorDetail = string.IsNullOrWhiteSpace(result.Error) @@ -4347,11 +4357,6 @@ or PbpError.InvalidSfo switch (result.ErrorCode) { - case PbpError.InvalidHeader: - LogMessage( - " The file does not begin with a PBP header - it is not a PlayStation EBOOT." - ); - break; case PbpError.CorruptFile or PbpError.DecompressionError or PbpError.InvalidSfo: LogMessage( " The file may be truncated or corrupt (re-download it), or it may not be a PSX PBP." @@ -4413,9 +4418,10 @@ or PbpError.InvalidSfo /// /// Handles a .pbp whose content is not a PBP at all: an archive is extracted, a CSO is - /// decompressed, an ISZ/ECM is restored, and a plain disc image is converted directly. - /// Returns null when the content is not a format the app knows, so the caller keeps the - /// original PBP error report. + /// decompressed, an ISZ/ECM is restored, and a plain disc image (including a cooked + /// ISO9660 image, which has no signature in its first sector) is converted directly. + /// Returns null only when the content is itself detected as a PBP, so the caller keeps + /// the original PBP error report. /// /// The mislabelled .pbp input. /// File name used in log messages. @@ -4445,7 +4451,7 @@ bool deleteOriginal ) { var kind = DiscImageSignature.Detect(inputFile); - if (kind is DiscImageKind.Pbp or DiscImageKind.Unknown) return null; + if (kind == DiscImageKind.Pbp) return null; var outputChd = ComputeOutputChdPath(inputFile, inputFolder, outputFolder); @@ -9431,14 +9437,18 @@ private static bool IsIoError(string? errorOutput) /// Returns whether chdman's error output indicates a permission error. /// Captured chdman error output. /// True when the output mentions denied access. - private static bool IsPermissionError(string? errorOutput) + internal static bool IsPermissionError(string? errorOutput) { if (string.IsNullOrEmpty(errorOutput)) return false; return errorOutput.Contains("Permission denied", StringComparison.OrdinalIgnoreCase) || errorOutput.Contains("Access denied", StringComparison.OrdinalIgnoreCase) - || errorOutput.Contains("UnauthorizedAccess", StringComparison.OrdinalIgnoreCase); + || errorOutput.Contains("UnauthorizedAccess", StringComparison.OrdinalIgnoreCase) + || errorOutput.Contains( + "A required privilege is not held by the client", + StringComparison.OrdinalIgnoreCase + ); } /// @@ -10052,37 +10062,30 @@ private async Task ShowUpdatePromptCoreAsync(GitHubRelease release) if (result != MessageBoxResult.Yes) return; + if (UrlLauncher.TryOpen(release.HtmlUrl, out var urlError)) return; + + LogMessage($"Failed to open browser: {urlError}"); + try { - Process.Start(new ProcessStartInfo(release.HtmlUrl) { UseShellExecute = true }); - } - catch (Exception urlEx) - { - LogMessage($"Failed to open browser: {urlEx.Message}"); - await ReportBugAsync("Failed to open browser", urlEx); - - try - { - var clipboard = GetTopLevel(this)?.Clipboard; - if (clipboard is not null) - { - await clipboard.SetTextAsync(release.HtmlUrl); - } - } - catch (Exception clipboardEx) + var clipboard = GetTopLevel(this)?.Clipboard; + if (clipboard is not null) { - LogMessage($"Failed to copy URL to clipboard: {clipboardEx.Message}"); - await ReportBugAsync("Failed to copy URL to clipboard", clipboardEx); + await clipboard.SetTextAsync(release.HtmlUrl); } - - await MessageBox.ShowAsync( - this, - $"Unable to open browser automatically. The update URL has been copied to your clipboard.\n\nURL: {release.HtmlUrl}\n\nPlease paste it into your browser manually.", - "Browser Launch Failed", - MessageBoxButton.Ok, - MessageBoxImage.Information - ); } + catch (Exception clipboardEx) + { + LogMessage($"Failed to copy URL to clipboard: {clipboardEx.Message}"); + } + + await MessageBox.ShowAsync( + this, + $"Unable to open browser automatically. The update URL has been copied to your clipboard.\n\nURL: {release.HtmlUrl}\n\nPlease paste it into your browser manually.", + "Browser Launch Failed", + MessageBoxButton.Ok, + MessageBoxImage.Information + ); } /// @@ -10157,16 +10160,8 @@ private void ExitMenuItem_Click(object sender, RoutedEventArgs e) /// Opens the project's donation page in the default browser. private void DonateMenuItem_Click(object? sender, RoutedEventArgs e) { - try - { - Process.Start( - new ProcessStartInfo { FileName = AppConfig.DonationUrl, UseShellExecute = true } - ); - } - catch (Exception ex) - { - LogError("Failed to open the donation page", ex); - } + if (!UrlLauncher.TryOpen(AppConfig.DonationUrl, out var error)) + LogMessage($"Failed to open the donation page: {error}"); } /// Opens the About window. diff --git a/CHDStudio/Models/DiscImageKind.cs b/CHDStudio/Models/DiscImageKind.cs index 58472e6..ccef6af 100644 --- a/CHDStudio/Models/DiscImageKind.cs +++ b/CHDStudio/Models/DiscImageKind.cs @@ -9,6 +9,9 @@ internal enum DiscImageKind /// Raw CD sectors: the 12-byte sync mark is present. RawCd, + /// A cooked ISO9660 image with 2048-byte sectors. + Iso, + /// Alcohol 120% .mds descriptor. AlcoholDescriptor, diff --git a/CHDStudio/Services/BugReportService.cs b/CHDStudio/Services/BugReportService.cs index be86d29..aee6650 100644 --- a/CHDStudio/Services/BugReportService.cs +++ b/CHDStudio/Services/BugReportService.cs @@ -137,6 +137,23 @@ internal class BugReportService // known at the collision preflight. The batch keeps the first product and warns about the // duplicate, which is the intended behaviour, not an app bug. "was already produced earlier in this batch", + // A .pbp whose magic is wrong and whose bytes are not a disc image is a renamed or + // incomplete user file. Content inspection has already tried every format the app knows. + "Failed to open PBP file: InvalidHeader", + "is not a PBP (its header is missing)", + // A PBP whose PSAR block is short is damaged download data; the message tells the user + // to re-download it. The decoder is not at fault. + "the PBP's disc data is damaged", + // The OS has no handler registered for the URL (a Windows install with no default + // browser, or a headless Linux session). The app copies the URL and tells the user. + "Failed to open browser", + "Error opening URL", + // A release bundle missing one of the app's own managed libraries cannot load optional + // functionality. The size pre-flight degrades gracefully; this is an installation issue. + "Could not load file or assembly 'MDSSharp", + // Windows privilege failures while opening the output file are storage/permission + // conditions (for example a restricted root directory), not an encoder defect. + "A required privilege is not held by the client", // CHDSharp hitting a device or permission error (drive unplugged, disk failing, full disk, // denied access) is an environment condition, not an encoder defect. "CHDSharp could not read or write", diff --git a/CHDStudio/Services/ChdSharpLoggerFactory.cs b/CHDStudio/Services/ChdSharpLoggerFactory.cs index 83cf15b..da49fd4 100644 --- a/CHDStudio/Services/ChdSharpLoggerFactory.cs +++ b/CHDStudio/Services/ChdSharpLoggerFactory.cs @@ -57,6 +57,17 @@ public void Dispose() } } + /// + /// Maps a CHDSharp level to the Serilog level the application writes. Exposed for tests so + /// the rule that library-level decode errors do not reach the bug-report sink stays covered. + /// + /// CHDSharp level to map. + /// The equivalent Serilog level. + internal static LogEventLevel MapLevel(LogLevel logLevel) + { + return ChdSharpLogger.MapToSerilog(logLevel); + } + /// Stores a warning-or-above message for the caller to attach to its own report. /// The rendered message. private static void Capture(string message) @@ -121,7 +132,7 @@ public void Log( var message = formatter(state, exception); Serilog.Log.Write( - Map(logLevel), + MapToSerilog(logLevel), exception, "{ChdSharpCategory}: {Message}", _category, @@ -137,16 +148,17 @@ public void Log( /// /// Maps a to the matching Serilog level. CHDSharp's - /// is deliberately written at - /// : the library also uses it for user-data - /// notices (for example "track has subcode data, it will be omitted"), and every - /// Warning-and-above Serilog event is forwarded to the bug-report API. Genuine - /// failures are reported by the application's own classified error message, which - /// carries the captured detail. + /// and are deliberately + /// written at : the library uses Error for + /// hunk-level decode/CRC failures in a user's CHD and Warning for user-data notices, + /// and every Warning-and-above Serilog event is forwarded to the bug-report API. + /// Genuine failures are reported by the application's own classified error message, + /// which carries the captured detail; a corrupt input must not file a library-internal + /// error report. /// /// Level to map. /// The equivalent Serilog level. - private static LogEventLevel Map(LogLevel logLevel) + internal static LogEventLevel MapToSerilog(LogLevel logLevel) { return logLevel switch { @@ -154,7 +166,7 @@ private static LogEventLevel Map(LogLevel logLevel) LogLevel.Debug => LogEventLevel.Debug, LogLevel.Information => LogEventLevel.Information, LogLevel.Warning => LogEventLevel.Information, - LogLevel.Error => LogEventLevel.Error, + LogLevel.Error => LogEventLevel.Information, LogLevel.Critical => LogEventLevel.Fatal, _ => LogEventLevel.Debug }; diff --git a/CHDStudio/Utilities/ConversionReport.cs b/CHDStudio/Utilities/ConversionReport.cs index ced6302..27e472f 100644 --- a/CHDStudio/Utilities/ConversionReport.cs +++ b/CHDStudio/Utilities/ConversionReport.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Runtime.CompilerServices; using CCDSharp; using CHDStudio.Models; using MDSSharp; @@ -314,17 +315,16 @@ private static void AddFile(string file, HashSet sourceFiles) List? volumes; try { - volumes = SplitImageJoiner.TryGetVolumeSet(file); + volumes = TryGetSplitImageVolumes(file); } - catch (Exception ex) - when (ex is FileNotFoundException or FileLoadException or TypeLoadException - or BadImageFormatException - ) + catch (Exception ex) when (ex is not OutOfMemoryException) { // The size pre-flight only feeds the savings summary, and MDSSharp owns // SplitImageJoiner. A deployment where that assembly cannot be resolved must not // abort the whole batch before the first conversion; count the input itself and // let the conversion path report the real problem if the input needs MDSSharp. + // The call lives in a separate non-inlined method because a JIT failure resolving + // MDSSharp happens before this method's own try block becomes active. Logger.Information(ex, "Could not inspect {File} for split-image volumes", file); sourceFiles.Add(file); return; @@ -339,4 +339,18 @@ or BadImageFormatException foreach (var volume in volumes) sourceFiles.Add(volume); } + + /// + /// Calls MDSSharp's split-volume detector. This is deliberately a separate, non-inlined + /// method: when MDSSharp is missing from the deployment, JIT resolution of its type fails + /// at the call site inside 's try block instead of while JITting + /// itself, so the size pre-flight can degrade to counting the input. + /// + /// The input path to inspect. + /// The split volumes, or null when the path is not a split-image set. + [MethodImpl(MethodImplOptions.NoInlining)] + private static List? TryGetSplitImageVolumes(string file) + { + return SplitImageJoiner.TryGetVolumeSet(file); + } } diff --git a/CHDStudio/Utilities/DiscImageSignature.cs b/CHDStudio/Utilities/DiscImageSignature.cs index 283522b..84afd46 100644 --- a/CHDStudio/Utilities/DiscImageSignature.cs +++ b/CHDStudio/Utilities/DiscImageSignature.cs @@ -15,6 +15,12 @@ internal static class DiscImageSignature /// Bytes read from the front of a file; enough for every signature below. private const int HeaderLength = 32; + /// First sector that can hold the ISO9660 volume descriptor (2048-byte sectors). + private const int IsoFirstVolumeDescriptorSector = 16; + + /// The ISO9660 volume descriptor identifier at bytes 1-5 of sector 16. + private static ReadOnlySpan IsoVolumeDescriptorId => "CD001"u8; + /// The 12-byte sync pattern that opens every raw CD sector. private static readonly byte[] CdSyncMark = [ @@ -52,9 +58,12 @@ internal static DiscImageKind Detect(string path) ) { read = stream.ReadAtLeast(header, header.Length, false); - } + var kind = Classify(header.AsSpan(0, read)); + if (kind != DiscImageKind.Unknown) + return kind; - return Classify(header.AsSpan(0, read)); + return HasIsoVolumeDescriptor(stream) ? DiscImageKind.Iso : DiscImageKind.Unknown; + } } catch (Exception) { @@ -62,6 +71,51 @@ internal static DiscImageKind Detect(string path) } } + /// + /// Returns whether the stream holds an ISO9660 volume descriptor where a cooked image places + /// it. A plain 2048-byte-sector ISO has no signature in its first sector, so this deeper + /// probe is what distinguishes it from an unknown file (and lets a mislabelled .pbp that is + /// really an ISO be routed to conversion instead of being rejected as a PBP). + /// + /// The seekable file stream to inspect. + /// True when sector 16 carries an ISO9660 primary or supplementary descriptor. + private static bool HasIsoVolumeDescriptor(Stream stream) + { + try + { + Span descriptor = stackalloc byte[8]; + // The primary descriptor normally sits at sector 16; a boot record at 16 pushes it + // to 17. Checking the next two sectors covers both layouts at negligible cost. + for (var sector = IsoFirstVolumeDescriptorSector; sector <= 18; sector++) + { + var offset = sector * 2048L; + if (stream.Length < offset + descriptor.Length) + return false; + + stream.Seek(offset, SeekOrigin.Begin); + stream.ReadExactly(descriptor); + + // Match the 8-byte descriptor prefix the reference ISO parsers test for: + // type (primary/supplementary), "CD001", version 1, reserved 0. + if ( + descriptor[0] is 1 or 2 + && descriptor[1..6].SequenceEqual(IsoVolumeDescriptorId) + && descriptor[6] == 1 + && descriptor[7] == 0 + ) + { + return true; + } + } + + return false; + } + catch (Exception ex) when (ex is IOException or NotSupportedException) + { + return false; + } + } + /// /// Classifies an already-read header. Separated from so it can be tested /// without touching the filesystem. @@ -144,6 +198,7 @@ internal static string Describe(DiscImageKind kind) return kind switch { DiscImageKind.RawCd => "a raw CD disc image", + DiscImageKind.Iso => "an ISO9660 disc image", DiscImageKind.AlcoholDescriptor => "an Alcohol 120% .mds descriptor", DiscImageKind.Rar => "a RAR archive", DiscImageKind.Zip => "a ZIP archive", diff --git a/CHDStudio/Utilities/UrlLauncher.cs b/CHDStudio/Utilities/UrlLauncher.cs new file mode 100644 index 0000000..08ae144 --- /dev/null +++ b/CHDStudio/Utilities/UrlLauncher.cs @@ -0,0 +1,96 @@ +using System.ComponentModel; +using System.Diagnostics; + +namespace CHDStudio.Utilities; + +/// +/// Opens an HTTP(S) URL with the user's default browser. Windows refuses the shell request +/// with "Class not registered" when no default browser is associated with the protocol, so a +/// direct platform opener is tried as a fallback. Failures are returned as a message instead +/// of being reported as application bugs: the browser association is an installation detail. +/// +internal static class UrlLauncher +{ + /// + /// Tries to open , first through the shell association and then + /// through the platform's standard opener. + /// + /// The URL to open. + /// A description of the failure when the URL could not be opened. + /// True when a process was started for the URL. + internal static bool TryOpen(string url, out string? error) + { + if (string.IsNullOrWhiteSpace(url)) + { + error = "the URL is empty"; + return false; + } + + if (TryStartShell(url, out error)) + return true; + + var (fileName, arguments) = OperatingSystem.IsWindows() + ? ("explorer.exe", new[] { url }) + : OperatingSystem.IsMacOS() + ? ("open", new[] { url }) + : ("xdg-open", new[] { url }); + + if (TryStartProcess(fileName, arguments, out var fallbackError)) + { + error = null; + return true; + } + + error = $"{error}; {fallbackError}"; + return false; + } + + /// Starts the URL through the operating system's shell association. + /// The URL to open. + /// The shell failure message, or null on success. + /// True when a process was started. + private static bool TryStartShell(string url, out string? error) + { + try + { + using var process = Process.Start( + new ProcessStartInfo { FileName = url, UseShellExecute = true } + ); + error = process is null ? "the shell returned no process" : null; + return process is not null; + } + catch ( + Exception ex + ) when (ex is Win32Exception or InvalidOperationException or PlatformNotSupportedException) + { + error = ex.Message; + return false; + } + } + + /// Starts a platform opener executable with the URL as its argument. + /// Executable to start. + /// Arguments to pass. + /// The failure message, or null on success. + /// True when a process was started. + private static bool TryStartProcess(string fileName, string[] arguments, out string? error) + { + try + { + var startInfo = new ProcessStartInfo(fileName) { UseShellExecute = false }; + foreach (var argument in arguments) + startInfo.ArgumentList.Add(argument); + + using var process = Process.Start(startInfo); + error = process is null ? $"'{fileName}' returned no process" : null; + return process is not null; + } + catch ( + Exception ex + ) when (ex is Win32Exception or InvalidOperationException or PlatformNotSupportedException) + { + error = ex.Message; + return false; + } + } +} diff --git a/PBPSharp/PBPSharp.csproj b/PBPSharp/PBPSharp.csproj index 1a62535..d002f36 100644 --- a/PBPSharp/PBPSharp.csproj +++ b/PBPSharp/PBPSharp.csproj @@ -6,8 +6,8 @@ 15.0 en PureLogicCode.com - 1.1.8 - 1.1.8 + 1.1.9 + 1.1.9 embedded true true @@ -16,7 +16,7 @@ true PBPSharp - 1.1.8 + 1.1.9 PureLogicCode.com PBPSharp A managed C# read-only library for reading and extracting PlayStation Portable PBP (EBOOT.PBP) files. Supports single-disc and multi-disc PBP, SFO metadata parsing, and ISO extraction with CUE sheet generation. Designed as an intermediate step for converting PBP discs to other formats (e.g. CHD). Read-only: it can open and extract, but cannot create or modify PBP files. diff --git a/PBPSharp/PbpDiscInfo.cs b/PBPSharp/PbpDiscInfo.cs index bf7210f..d13d73a 100644 --- a/PBPSharp/PbpDiscInfo.cs +++ b/PBPSharp/PbpDiscInfo.cs @@ -345,6 +345,15 @@ public void ReadBlock(int blockIndex, byte[] buffer, out int bytesRead) // 64-bit math: the PSAR offset plus a large block offset can overflow int32 on // multi-gigabyte files. var thisOffset = _psarOffset + PsarIsoOffset + entry.Offset; + + // The final index entry may represent fewer than 16 sectors: an ISO whose sector count + // is not a multiple of 16 is written by several authoring tools as a short final block, + // and the public API documents that the last block may be shorter. Use the ISO9660 + // sector count to know exactly how many bytes that block should produce; when the size + // is unknown, keep the historical full-block requirement. Resolve it before seeking: + // the lazy size probe reads block 1 and moves the stream. + var expectedLength = GetExpectedBlockLength(blockIndex); + _stream.Seek(thisOffset, SeekOrigin.Begin); // A full-size block, or any block explicitly flagged as stored/uncompressed, is @@ -370,18 +379,28 @@ public void ReadBlock(int blockIndex, byte[] buffer, out int bytesRead) // The index length is not always exactly the stored stream length: writers pad a // block, leave a few bytes of the next stream in the range, or record a length that // lags the next entry. The next entry's offset is where this block's data really - // ends, so read up to it. The inflater stops as soon as one full 16-sector block has - // been produced, so trailing bytes inside that range are never parsed as deflate + // ends, so read up to it. The inflater stops as soon as the expected output length + // has been produced, so trailing bytes inside that range are never parsed as deflate // data; they only make a cut-short stream whole. var readLength = GetStoredBlockLength(blockIndex, entry); var inBuffer = ArrayPool.Shared.Rent(readLength); try { - _stream.ReadExactly(inBuffer, 0, readLength); try { - bytesRead = DecompressBlock(inBuffer, readLength, buffer); + _stream.ReadExactly(inBuffer, 0, readLength); + } + catch (EndOfStreamException ex) + { + var detail = + $"block {blockIndex} of {_isoIndex.Count} (disc {Index}, id {DiscId}) needs {readLength} bytes at file offset 0x{thisOffset:X}, but the stream ended at 0x{_stream.Position:X} (length 0x{_stream.Length:X})."; + PbpDiagnostics.SetDetail(detail); + throw new EndOfStreamException(detail, ex); + } + try + { + bytesRead = DecompressBlock(inBuffer, readLength, buffer, expectedLength); } catch (Exception ex) { @@ -422,6 +441,27 @@ private int GetStoredBlockLength(int blockIndex, IsoIndexEntry entry) return (int)Math.Min(distance, MaxBlockEntrySize); } + /// + /// Returns the number of decompressed bytes the indexed block should produce. Every block + /// but the last holds 16 sectors. The last block is shorter when the disc's ISO9660 sector + /// count is not a multiple of 16, as several authoring tools write it; in that case the + /// declared image size is the only way to know the exact length. When the size cannot be + /// derived, the historical full-block requirement is kept. + /// + /// Zero-based block index. + /// The expected number of decompressed bytes for the block. + private int GetExpectedBlockLength(int blockIndex) + { + const int fullBlockSize = 16 * IsoBlockSize; + var isoSize = IsoSize; + if (isoSize == 0 || blockIndex != _isoIndex.Count - 1) + return fullBlockSize; + + var blockStart = (long)blockIndex * fullBlockSize; + var remaining = isoSize - blockStart; + return remaining is > 0 and < fullBlockSize ? (int)remaining : fullBlockSize; + } + /// /// Builds the diagnostic text for a failed block: where the block lives in the file, its /// index entry, the image geometry and a preview of the stored bytes. @@ -614,32 +654,64 @@ private static void TryDeletePartial(string binPath) /// The buffer holding the compressed block. /// The number of valid bytes in . /// The buffer that receives the decompressed data. + /// The number of bytes this block must produce (a full 16-sector + /// block, or the shorter length of the final block). /// The number of bytes written to . /// /// Thrown when the block cannot be inflated as either raw deflate or a zlib stream. /// - private static int DecompressBlock(byte[] compressed, int compressedLength, byte[] output) + private static int DecompressBlock( + byte[] compressed, + int compressedLength, + byte[] output, + int expectedLength + ) { - if (TryInflate(compressed, compressedLength, output, noHeader: true, out var size, out var rawFailure)) + if ( + TryInflate( + compressed, + compressedLength, + output, + expectedLength, + noHeader: true, + out var size, + out var rawFailure + ) + ) return size; var zlibFailure = "not attempted (stream too short)"; if ( compressedLength > 2 - && TryInflate(compressed, compressedLength, output, noHeader: false, out size, out zlibFailure) + && TryInflate( + compressed, + compressedLength, + output, + expectedLength, + noHeader: false, + out size, + out zlibFailure + ) ) return size; // Some valid streams trip SharpZipLib's inflater (its state machine is stricter than // zlib's) even though the data is complete. Retry with the .NET zlib implementation: // it accepts a few stream shapes SharpZipLib rejects, and a block is only accepted when - // it produces exactly one full 16-sector block. - if (TrySystemInflate(compressed, compressedLength, output, noHeader: true, out size)) + // it produces exactly the expected output length. + if (TrySystemInflate(compressed, compressedLength, output, expectedLength, noHeader: true, out size)) return size; if ( compressedLength > 2 - && TrySystemInflate(compressed, compressedLength, output, noHeader: false, out size) + && TrySystemInflate( + compressed, + compressedLength, + output, + expectedLength, + noHeader: false, + out size + ) ) return size; @@ -656,19 +728,20 @@ private static int DecompressBlock(byte[] compressed, int compressedLength, byte /// The buffer holding the compressed block. /// The number of valid bytes in . /// The buffer that receives the decompressed data. + /// The number of bytes this block must produce. /// True for raw deflate, false for a zlib-wrapped stream. /// The number of bytes written when inflation succeeds. - /// when the block inflated to a full block. + /// when the block inflated to the expected length. private static bool TrySystemInflate( byte[] compressed, int compressedLength, byte[] output, + int expectedLength, bool noHeader, out int size ) { size = 0; - var blockSize = 16 * IsoBlockSize; var written = 0; try @@ -678,9 +751,9 @@ out int size ? new DeflateStream(input, CompressionMode.Decompress) : new ZLibStream(input, CompressionMode.Decompress); - while (written < blockSize) + while (written < expectedLength) { - var read = inflater.Read(output, written, blockSize - written); + var read = inflater.Read(output, written, expectedLength - written); if (read == 0) break; written += read; } @@ -689,11 +762,11 @@ out int size { // The runtime's zlib-backed stream needs a clean end-of-stream marker and throws when // the writer never finished the stream (Z_SYNC_FLUSH). Everything up to the throw is - // valid output, so a block that already reached its full size is still good. - if (written < blockSize) return false; + // valid output, so a block that already reached its expected size is still good. + if (written < expectedLength) return false; } - if (written != blockSize) return false; + if (written != expectedLength) return false; size = written; return true; @@ -706,6 +779,7 @@ out int size /// The buffer holding the compressed block. /// The number of valid bytes in . /// The buffer that receives the decompressed data. + /// The number of bytes this block must produce. /// True for raw deflate, false for a zlib-wrapped stream. /// The number of bytes written when inflation succeeds. /// The failure message when inflation fails. @@ -714,6 +788,7 @@ private static bool TryInflate( byte[] compressed, int compressedLength, byte[] output, + int expectedLength, bool noHeader, out int size, out string error @@ -721,7 +796,7 @@ out string error { try { - size = Inflate(compressed, compressedLength, output, noHeader); + size = Inflate(compressed, compressedLength, output, expectedLength, noHeader); error = string.Empty; return true; } @@ -734,52 +809,54 @@ out string error } /// - /// Inflates one block with SharpZipLib's raw inflater, bounded to exactly one full block. + /// Inflates one block with SharpZipLib's raw inflater, bounded to the expected output length. /// The stream wrapper is deliberately not used: it reports a stream whose final block never /// sets BFINAL as "Unexpected EOF" even though every byte has been decoded. Inflation stops - /// the moment the output block is full; a stream that ends before then is rejected so a + /// the moment the expected block is full; a stream that ends before then is rejected so a /// short block can never shift every later block in the extracted image. /// /// The buffer holding the compressed block. /// The number of valid bytes in . /// The buffer that receives the decompressed data. + /// The number of bytes this block must produce. /// True for raw deflate, false for a zlib-wrapped stream. /// The number of bytes written to . private static int Inflate( byte[] compressed, int compressedLength, byte[] output, + int expectedLength, bool noHeader ) { var inflater = new Inflater(noHeader); inflater.SetInput(compressed, 0, compressedLength); - var blockSize = 16 * IsoBlockSize; var written = 0; try { - while (written < blockSize) + while (written < expectedLength) { - var read = inflater.Inflate(output, written, blockSize - written); + var read = inflater.Inflate(output, written, expectedLength - written); if (read == 0) break; written += read; } - // A full block is complete regardless of what follows in the input: trailing padding, - // the next entry's stream, or a final deflate block that never set BFINAL because the - // writer flushed with Z_SYNC_FLUSH. Parsing past this point would reject valid blocks. - if (written == blockSize) + // The expected block is complete regardless of what follows in the input: trailing + // padding, the next entry's stream, or a final deflate block that never set BFINAL + // because the writer flushed with Z_SYNC_FLUSH. Parsing past this point would reject + // valid blocks. + if (written == expectedLength) return written; if (inflater.IsNeedingDictionary) throw new InvalidDataException("the deflate stream needs a preset dictionary."); throw new InvalidDataException( - $"the deflate stream produced only {written:N0} of {blockSize:N0} bytes." + $"the deflate stream produced only {written:N0} of {expectedLength:N0} bytes." ); } catch (IndexOutOfRangeException ex) diff --git a/PBPSharp/README.md b/PBPSharp/README.md index d157a68..e4d00b1 100644 --- a/PBPSharp/README.md +++ b/PBPSharp/README.md @@ -77,7 +77,7 @@ The library is the PBP extraction engine used by [CHD Studio](https://github.com - **ISO extraction with CUE generation** — `ExtractToBinCue` writes the disc as a BIN file and generates a matching CUE sheet, including `INDEX 00` positions for audio tracks. - **Stream-friendly** — extract to any writable `Stream`, or open a PBP from a `Stream` you own, so it works with archives, network streams, and in-memory data. - **Progress and cancellation** — every long-running extraction accepts a byte-progress callback and a `CancellationToken`. -- **Authoring-tool compatibility** — reads PSAR block indexes written by popstation, PSX2PSP, iPoPS and pop-fe (both the 16-bit and 32-bit index layouts, stored/uncompressed blocks, and zlib-wrapped or raw-deflate blocks). A block is accepted as soon as one full 16-sector block has been decoded, so writer padding after the stream, a length that lags the next index entry, or a stream that never sets BFINAL do not fail the file. +- **Authoring-tool compatibility** - reads PSAR block indexes written by popstation, PSX2PSP, iPoPS and pop-fe (both the 16-bit and 32-bit index layouts, stored/uncompressed blocks, and zlib-wrapped or raw-deflate blocks). A block is accepted as soon as its expected output length has been decoded, so writer padding after the stream, a length that lags the next index entry, a stream that never sets BFINAL, or a short final block (fewer than 16 sectors) do not fail the file. - **No native dependencies** — pure managed code, cross-platform, read-only by design. ## Requirements @@ -519,7 +519,8 @@ PBP files are produced by several authoring tools, and PBPSharp reads the layout - **popstation / PSX2PSP / iPoPS** — 32-bit ISO index size field, raw deflate blocks. - **pop-fe** — official 16-bit index size field with a stored/uncompressed flag byte, uncompressed (stored) blocks when compression is disabled, zlib-wrapped deflate blocks, and multi-disc `PSTITLEIMG` headers with zeroed template fields. -- **Unfinished deflate streams** — a raw stream whose final block never sets BFINAL (a writer that flushed with `Z_SYNC_FLUSH` instead of finishing the stream) is accepted once a full 16-sector block has been decoded; SharpZipLib's stream wrapper would report it as "Unexpected EOF" even though every byte is present. +- **Unfinished deflate streams** - a raw stream whose final block never sets BFINAL (a writer that flushed with `Z_SYNC_FLUSH` instead of finishing the stream) is accepted once the expected output length has been decoded; SharpZipLib's stream wrapper would report it as "Unexpected EOF" even though every byte is present. +- **Short final blocks** - the last index entry may store fewer than 16 sectors when the disc's ISO9660 sector count is not a multiple of 16. The expected length comes from the declared image size, so the block is complete at that shorter length while a cut-short earlier block is still rejected. - **Trailing bytes after a block** — padding a writer appended to a block, or the first bytes of the next stream when an index length overstates the block, are not parsed as a continuation. Inflation stops at the full 16-sector block, so those bytes cannot turn a valid block into a bogus "unknown block type"/"invalid codelength" error. - **Under-stated index lengths** — when the next index entry starts after the declared length, the reader takes the block's stored data up to that offset, so a length recorded before the writer's last flush still yields the whole stream. - **Incompressible blocks** — deflate streams a few bytes larger than the raw 16-sector block are accepted. @@ -558,6 +559,13 @@ dotnet test CHDStudio.Tests/CHDStudio.Tests.csproj -c Release --filter "FullyQua ## Version history +### 1.1.9 + +- The final ISO index block may now decompress to fewer than 16 sectors. When the ISO9660 volume descriptor declares a sector count that is not a multiple of 16, the expected length of the last block is derived from the image size, so a PBP that stores only the sectors it actually contains no longer fails with `DecompressionError` ("the deflate stream produced only N of 37,632 bytes"). This matches the documented `ReadBlock` contract that the last block may be shorter. +- A truncated compressed block still fails: short output is accepted only for the final index entry and only when the declared image size says that shorter length is complete. +- `EndOfStreamException` while reading a block now carries the block index, disc, file offset, requested length and stream length, so a truncated PBP is immediately identifiable in diagnostics. +- No public API changes. + ### 1.1.8 - `PbpFile.Open(string path, out PbpFile?)` now disposes the file stream when the container is rejected, so a failed open no longer leaves the PBP locked until process exit. diff --git a/docs/05-conversion-pipeline.md b/docs/05-conversion-pipeline.md index ed7e8fd..8f1f6bc 100644 --- a/docs/05-conversion-pipeline.md +++ b/docs/05-conversion-pipeline.md @@ -48,7 +48,7 @@ The order matters: |-----------|---------|--------------| | `.cso` | `ProcessCsoFileForConversionAsync` | `_archiveService.ExtractCsoAsync` decompresses to a temp `.iso`, then converts. | | `.zip`/`.7z`/`.rar` | `ProcessArchiveFileForConversionAsync` | Extracts to a temp dir; drops raw images already covered by a descriptor in the archive and a `.ccd` already described by a same-named `.cue` (`InputFileFilter.RemoveCompanionDataFilesAsync`); maps auto-cue outputs; validates cue/gdi/toc dependencies; converts each supported file. `.ccd` goes through CCDSharp, `.mds` through the Alcohol parser, `.isz` through `ConvertIszViaImageAsync`. | -| `.pbp` | `ProcessPbpFileForConversionAsync` | `ExtractPbpToCueBinAsync` via PBPSharp; `PbpError.InvalidPsarHeader`/`TruncatedPsar` → informational skip (user-data conditions, not reported); `PbpError.InvalidHeader` → the bytes are sniffed and a mislabelled archive/CSO/ISZ/ECM/disc image is routed by content; converts each disc cue. | +| `.pbp` | `ProcessPbpFileForConversionAsync` | `ExtractPbpToCueBinAsync` via PBPSharp; `PbpError.InvalidPsarHeader`/`TruncatedPsar` → informational skip (user-data conditions, not reported); `PbpError.InvalidHeader` → the bytes are sniffed and a mislabelled archive/CSO/ISZ/ECM/disc image is routed by content (a cooked ISO9660 image is identified from its volume descriptor even though its first sector has no signature); converts each disc cue. A short final ISO block is accepted when the declared sector count says it is complete. | | `.ccd` | `ProcessCcdFileForConversionAsync` | `CcdConverter.Parse` + `ConvertToCueBin` into a temp dir, then converts the cue. TOC-only (trurip) descriptors get their tracks rebuilt from `[Entry N]` rows. | | `.mds` | `ProcessMdsFileForConversionAsync` | `MdsParser` + `MdsInputPreparer` produce a cue (or a stripped image, or a DVD image), then convert. | | everything else | direct path | `TryStageCueForRawImageAsync` may generate a cue for a raw CD image, then `ValidateDependentFilesAsync` → `TryDirectConversionAsync`. | diff --git a/docs/10-libraries.md b/docs/10-libraries.md index 2d4c3bd..5a1420b 100644 --- a/docs/10-libraries.md +++ b/docs/10-libraries.md @@ -5,7 +5,7 @@ nav_order: 11 # 10. Embedded Libraries -The solution ships five in-house libraries that replace external tools (maxcso, psxpackager), add CloneCD support, and cover Alcohol 120% and UltraISO images. The app references them as project references. All five are published as NuGet packages for outside consumers — **PBPSharp** (, 1.1.8), **CSOSharp** (, 1.0.2), **CCDSharp** (, 1.0.3), **MDSSharp** (, 1.3.0) and **ISZSharp** (, 1.0.3) — and they all multi-target `net8.0;net9.0;net10.0;net11.0`, each shipping its XML docs, README and icon; releases are manual (see the repository's AGENTS.md). All five expose internals to `CHDStudio.Tests` via `InternalsVisibleTo`. A sixth in-house library, **CHDSharp**, is consumed as a NuGet package and is covered in [§10.4](#104-chdsharp-nuget). +The solution ships five in-house libraries that replace external tools (maxcso, psxpackager), add CloneCD support, and cover Alcohol 120% and UltraISO images. The app references them as project references. All five are published as NuGet packages for outside consumers - **PBPSharp** (, 1.1.9), **CSOSharp** (, 1.0.2), **CCDSharp** (, 1.0.3), **MDSSharp** (, 1.3.0) and **ISZSharp** (, 1.0.3) — and they all multi-target `net8.0;net9.0;net10.0;net11.0`, each shipping its XML docs, README and icon; releases are manual (see the repository's AGENTS.md). All five expose internals to `CHDStudio.Tests` via `InternalsVisibleTo`. A sixth in-house library, **CHDSharp**, is consumed as a NuGet package and is covered in [§10.4](#104-chdsharp-nuget). | Library | Purpose | Replaces | |---------|---------|----------| diff --git a/docs/13-troubleshooting.md b/docs/13-troubleshooting.md index 6e07d5b..95b9cbc 100644 --- a/docs/13-troubleshooting.md +++ b/docs/13-troubleshooting.md @@ -49,7 +49,7 @@ Common messages, their meaning, and what to do. | `CHDSharp could not read or write the image: ...` | The built-in encoder hit a device or permission error (drive unplugged, disk failing, full disk, denied access), not an encoder defect. | Check the source and output drives, free space and permissions, then retry. | | `Repaired .wav: its WAV header declares N more audio bytes than the file contains; using the audio that is present.` | Informational. The cue's `WAVE` track claimed more audio than the file holds (truncated or mislabelled rip — the Policenauts Saturn English patch ships one CD frame over-declared on every disc). This used to fail conversion with chdman's `Error reading input file (...wav)` and, on the fallback, `Unexpected end of file (...wav)`. | Nothing to do. The app clamps the header in a private work copy and converts the audio that exists; the original file is never modified. `Error reading input file (...wav)` / `Unexpected end of file (...wav)` no longer appear for this cause in current versions. | | `Normalizing .wav to 44100 Hz stereo 16-bit PCM (source: N Hz, N channel(s), N-bit)...` | Informational. The cue's `WAVE` track is not in the format both encoders require: chdman rejects any rate other than 44100 Hz, and CHDSharp reports `Unsupported samplerate - only 44100 is supported`. Common with Sega CD rips and other non-CD-standard audio tracks. | Nothing to do. The app re-encodes the track in a private work copy (NAudio on Windows, ffmpeg on Linux/macOS) and leaves the original untouched. If the message is followed by a normalization error, the source WAV is corrupt or uses a codec neither decoder supports; re-rip or convert that track manually to 44.1 kHz stereo 16-bit PCM. | -| ` is named .pbp but contains ; extracting/decompressing it instead.` | The `.pbp` extension disagreed with the content. Instead of reporting "InvalidHeader", the file is routed by what its bytes actually are. | Nothing to do — the conversion proceeds from the real content. | +| ` is named .pbp but contains ; extracting/decompressing it instead.` | The `.pbp` extension disagreed with the content. Instead of reporting "InvalidHeader", the file is routed by what its bytes actually are, including a cooked ISO9660 image identified from its volume descriptor. | Nothing to do — the conversion proceeds from the real content. | | `this file is already a CHD. Copy it to the output folder rather than converting it.` | An input (often an image renamed to `.iso`/`.bin`) already contains a CHD. Skipping is intentional so outputs cannot be reprocessed; the notice is excluded from bug reports. | Nothing to do. Copy the existing CHD to the output folder yourself if it belongs in the converted set. | | A `.pbp` extracts but the log shows no game title / disc ID | The PARAM.SFO inside the PBP is missing or corrupt. Extraction no longer requires the SFO — only the metadata is empty. | Informational; the disc converts anyway. | | `Retrying with createdvd (unrecognized track type)...` | A CD attempt failed; the app retries as DVD. | Usually succeeds automatically. If it fails again, force CD/DVD manually. |