From 4f4fb85d3236000c280a03833ccfa22b813641ff Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 29 Oct 2026 21:46:35 -0700 Subject: [PATCH 1/8] Keep a File When a Signal Kills Its FfMpeg Verify A verify run killed by a signal stays DecodeError so the repair ladder still runs, but DeleteFailedFile() never deletes on it, since an external kill and a crash on corrupt media exit alike. ToolErrorScope counts such runs separately from tool errors, so a failed repair still records VerifyFailed and RepairFailed. Co-Authored-By: Claude Opus 5.5 --- ARCHITECTURE.md | 9 ++-- PlexCleaner/FfMpegTool.cs | 8 +++ PlexCleaner/ProcessFile.cs | 1 + PlexCleaner/ToolErrorScope.cs | 12 +++++ PlexCleanerTests/ToolErrorScopeTests.cs | 11 +++++ PlexCleanerTests/VerifyToolErrorTests.cs | 63 ++++++++++++++++++++++++ 6 files changed, 99 insertions(+), 5 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 2243022e..4a331cd2 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -357,13 +357,13 @@ flowchart TD CLEAN -.->|"any step false or cancel"| AB AB["Abort the file, failedOperation names the step"] --> G5{"Skipped as read-only?"} G5 -->|yes| RET(["Result false, return the state and final path"]) - G5 -->|no| DF["DeleteFailedFile(): DeleteInvalidFiles deletes the media file, and the sidecar of an MKV file, unless cancelled or a tool run for the file failed to launch or threw"] + G5 -->|no| DF["DeleteFailedFile(): DeleteInvalidFiles deletes the media file, and the sidecar of an MKV file, unless cancelled, a tool run for the file failed to launch or threw, or an FfMpeg verify run was killed by a signal"] DF --> RET classDef suspect stroke:#c00,stroke-width:2px,stroke-dasharray:5 3 class P02,CLEAN suspect ``` -`ProcessDriver.ProcessFiles()` counts the tool runs of each file that fail to launch, are cancelled, or throw, since such a run leaves the media unjudged. `DeleteFailedFile()` does not delete a file that had any such tool run. +`ProcessDriver.ProcessFiles()` counts the tool runs of each file that fail to launch, are cancelled, or throw, since such a run leaves the media unjudged. Outside Windows, it also counts each file's FfMpeg verify runs that a signal terminates. Such a run may be an external kill rather than corrupt media, since both exit alike. `DeleteFailedFile()` does not delete a file that had any such tool run. `VerifyTrackCounts()` fails a file with no video track or more than one, and only warns when there is no audio track. `VerifyMediaInfo()` fails a file when FfProbe, MkvMerge and MediaInfo disagree on the track count of any type. A rename from a remux or the lowercase step reaches the result as the new path. @@ -640,7 +640,7 @@ The `ConvertOptions` settings shape the FfMpeg and HandBrake command lines, and ### Verify and Repair -`VerifyAndRepair()` verifies the media streams with FfMpeg and repairs what fails. `VerifyClassifier` reads the FfMpeg error output. A non-monotonic DTS line alone yields `TimestampOnly`, any other error line or a non-zero exit yields `DecodeError`, S17, and no line yields `Clean`. An FfMpeg run that fails to launch, is cancelled, or whose execution throws yields `ToolError`, which leaves the media unchecked. On the first verify the file then fails with its state unchanged. A repair that fails while any of its tool runs failed to launch, was cancelled, or threw also leaves the state unchanged. +`VerifyAndRepair()` verifies the media streams with FfMpeg and repairs what fails. `VerifyClassifier` reads the FfMpeg error output. A non-monotonic DTS line alone yields `TimestampOnly`, any other error line or a non-zero exit yields `DecodeError`, and no line yields `Clean`. A run a signal terminates also yields `DecodeError`, so the repair ladder still runs, and the file is never deleted on it. An FfMpeg run that fails to launch, is cancelled, or whose execution throws yields `ToolError`, which leaves the media unchecked. On the first verify the file then fails with its state unchanged. A repair that fails while any of its tool runs failed to launch, was cancelled, or threw also leaves the state unchanged. ```mermaid flowchart TD @@ -656,7 +656,7 @@ flowchart TD V5 --> V6["VerifyBitrate(): MaximumBitrate, skipped with --quickscan, sets BitrateExceeded, S11"]:::suspect V6 --> V7["VerifyMediaStreams(): FfMpeg decode"] V7 -->|Clean| PASS - V7 -->|"TimestampOnly, or DecodeError including any non-zero exit, S17"| REP["Verify fails, repair possible"] + V7 -->|"TimestampOnly, or DecodeError including any non-zero exit"| REP["Verify fails, repair possible"] V7 -->|"ToolError, FfMpeg did not launch, was cancelled, or threw"| TE["Verify fails, the media unchecked"] PASS --> P1{"Verified already set?"} P1 -->|yes| OK(["Continue"]) @@ -742,7 +742,6 @@ Each entry describes a branch the diagrams mark, as the code behaves today, and - **S12** ([#1080](https://github.com/ptr727/PlexCleaner/issues/1080)): `RegisterInvalidFiles` adds a `VerifyFailed` file to `FileIgnoreList` even when `DeleteFailedFile()` already deleted it. - **S13** ([#1081](https://github.com/ptr727/PlexCleaner/issues/1081)): `Process.ProcessFiles()` writes the settings file and the results file without exception handling. The System.CommandLine default handler turns a write failure into exit code 1. The exception reaches stderr rather than the log, and `DeleteEmptyFolders()` does not run. - **S14** ([#1082](https://github.com/ptr727/PlexCleaner/issues/1082)): When a rename lands on a name that already has a sidecar, `SidecarFile.Read()` replaces the in-memory state with the stored one. That drops `FileReNamed` and any flag the renaming step set. -- **S17** ([#1090](https://github.com/ptr727/PlexCleaner/issues/1090)): `FfMpegTool.VerifyMedia()` reads any non-zero FfMpeg exit as `DecodeError`. A run killed by a signal is then repaired as corrupt media, and can end in `VerifyFailed`, `RepairFailed` and a delete. ## Code Conventions diff --git a/PlexCleaner/FfMpegTool.cs b/PlexCleaner/FfMpegTool.cs index d4d5df6f..799ac269 100644 --- a/PlexCleaner/FfMpegTool.cs +++ b/PlexCleaner/FfMpegTool.cs @@ -167,6 +167,10 @@ internal static Command GetVerifyMediaCommand(string toolPath, string fileName) ) .Build(); + // A process killed by a signal exits with 128 plus the signal number + internal static bool IsSignalExit(int exitCode) => + !OperatingSystem.IsWindows() && exitCode > 128; + public VerifyResult VerifyMedia(string fileName) { Command command = GetVerifyMediaCommand(GetToolPath(), fileName); @@ -190,6 +194,10 @@ public VerifyResult VerifyMedia(string fileName) { verifyResult = VerifyResult.DecodeError; } + if (IsSignalExit(exitCode)) + { + ToolErrorScope.RecordSignal(); + } if (verifyResult == VerifyResult.DecodeError) { // Log the unique error lines, a silent non-zero exit has none so omit the empty field. diff --git a/PlexCleaner/ProcessFile.cs b/PlexCleaner/ProcessFile.cs index 5e9e7548..e88b07ad 100644 --- a/PlexCleaner/ProcessFile.cs +++ b/PlexCleaner/ProcessFile.cs @@ -1794,6 +1794,7 @@ public bool DeleteFailedFile() if ( !Program.Config.VerifyOptions.DeleteInvalidFiles || ToolErrorScope.Count > 0 + || ToolErrorScope.SignalCount > 0 || Program.IsCancelledError() ) { diff --git a/PlexCleaner/ToolErrorScope.cs b/PlexCleaner/ToolErrorScope.cs index 5669a435..8c3a34d1 100644 --- a/PlexCleaner/ToolErrorScope.cs +++ b/PlexCleaner/ToolErrorScope.cs @@ -7,6 +7,9 @@ internal static class ToolErrorScope public static int Count => s_current.Value?.Count ?? 0; + // Counts the file's tool runs terminated by a signal, an external kill reads the same as a crash on corrupt media + public static int SignalCount => s_current.Value?.SignalCount ?? 0; + public static IDisposable BeginScope() { Session? previous = s_current.Value; @@ -22,9 +25,18 @@ public static void Record() } } + public static void RecordSignal() + { + if (s_current.Value is { } session) + { + session.SignalCount++; + } + } + private sealed class Session { public int Count { get; set; } + public int SignalCount { get; set; } } private sealed class Scope(Session? previous) : IDisposable diff --git a/PlexCleanerTests/ToolErrorScopeTests.cs b/PlexCleanerTests/ToolErrorScopeTests.cs index 211ec1f3..20bf85f5 100644 --- a/PlexCleanerTests/ToolErrorScopeTests.cs +++ b/PlexCleanerTests/ToolErrorScopeTests.cs @@ -25,6 +25,17 @@ public void Record_OutsideScope_IsIgnored() _ = ToolErrorScope.Count.Should().Be(0); } + [Fact] + public void RecordSignal_LeavesCountUnchanged() + { + using IDisposable toolErrorScope = ToolErrorScope.BeginScope(); + + ToolErrorScope.RecordSignal(); + + _ = ToolErrorScope.SignalCount.Should().Be(1); + _ = ToolErrorScope.Count.Should().Be(0); + } + [Fact] public void ProcessFiles_BeginsScopePerFile() { diff --git a/PlexCleanerTests/VerifyToolErrorTests.cs b/PlexCleanerTests/VerifyToolErrorTests.cs index cfba6d37..42a56227 100644 --- a/PlexCleanerTests/VerifyToolErrorTests.cs +++ b/PlexCleanerTests/VerifyToolErrorTests.cs @@ -93,6 +93,69 @@ private string CopyUnverifiedSample() public void VerifyMedia_ToolDoesNotRun_IsToolError() => _ = Tools.FfMpeg.VerifyMedia(CreateFile("name.mkv")).Should().Be(VerifyResult.ToolError); + [Fact] + public void VerifyMedia_SignalExit_IsDecodeErrorAndRecordsSignal() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "The fake FfMpeg is a shell script"); + using IDisposable toolErrorScope = ToolErrorScope.BeginScope(); + WriteScript(Tools.FfMpeg.GetToolPath(), "kill -9 $$\n", true); + + _ = Tools.FfMpeg.VerifyMedia(CreateFile("name.mkv")).Should().Be(VerifyResult.DecodeError); + _ = ToolErrorScope.SignalCount.Should().Be(1); + _ = ToolErrorScope.Count.Should().Be(0); + } + + [Fact] + public void VerifyMedia_ErrorExit_RecordsNoSignal() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "The fake FfMpeg is a shell script"); + using IDisposable toolErrorScope = ToolErrorScope.BeginScope(); + WriteScript(Tools.FfMpeg.GetToolPath(), "exit 1\n", true); + + _ = Tools.FfMpeg.VerifyMedia(CreateFile("name.mkv")).Should().Be(VerifyResult.DecodeError); + _ = ToolErrorScope.SignalCount.Should().Be(0); + } + + [Fact] + public void VerifyAndRepair_SignalExitRepairFails_SetsStateAndKeepsFiles() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "The fake tools are shell scripts"); + using IDisposable toolErrorScope = ToolErrorScope.BeginScope(); + string mediaFile = CopyUnverifiedSample(); + string sidecarFile = Path.ChangeExtension(mediaFile, ".PlexCleaner"); + ProcessFile processFile = new(mediaFile); + _ = processFile.GetMediaProps().Should().BeTrue(); + + WriteScript(Tools.MkvMerge.GetToolPath(), "exit 2\n", true); + WriteScript(Tools.HandBrake.GetToolPath(), "exit 1\n", true); + string ffMpeg = Tools.FfMpeg.GetToolPath(); + WriteScript( + ffMpeg, + """ + step=$(($(cat "$0.step" 2>/dev/null || echo 0) + 1)) + echo $step > "$0.step" + [ $step -eq 1 ] && kill -9 $$ + exit 1 + + """, + true + ); + + bool modified = false; + _ = processFile.VerifyAndRepair(ref modified).Should().BeFalse(); + _ = ToolErrorScope.SignalCount.Should().Be(1); + _ = ToolErrorScope.Count.Should().Be(0); + _ = processFile + .State.Should() + .HaveFlag(SidecarFile.StatesType.VerifyFailed) + .And.HaveFlag(SidecarFile.StatesType.RepairFailed); + _ = processFile.DeleteFailedFile().Should().BeFalse(); + + _ = modified.Should().BeFalse(); + _ = File.Exists(mediaFile).Should().BeTrue(); + _ = File.Exists(sidecarFile).Should().BeTrue(); + } + [Fact] public void VerifyAndRepair_ToolError_KeepsStateAndFiles() { From b24439d89dc2ea04f208bf7ee0824227f0bd1fbb Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 29 Oct 2026 21:47:26 -0700 Subject: [PATCH 2/8] Note the Signal-Killed Verify Keep in the 3.23 History Co-Authored-By: Claude Opus 5.5 --- HISTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/HISTORY.md b/HISTORY.md index 77e5b036..c7a02afb 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -46,6 +46,7 @@ Utility to optimize media files for Direct Play in Plex, Emby, Jellyfin, etc. - A cancel, a read-only media file, and a read-only sidecar file leave the media file and its sidecar in place. - A failed non-MKV file keeps the sidecar of a sibling MKV file with the same name. - A tool that fails to launch or throws leaves the media file and its sidecar in place, in any processing step. + - An FfMpeg verify run killed by a signal, outside Windows, still runs the repair, and leaves the media file and its sidecar in place when the repair fails. - A failed repair whose tool fails to launch or throws leaves the file's state unchanged, rather than marking it `VerifyFailed` and `RepairFailed`. - The next run retries the repair. - Version 3.22: From bfa6d568cf2b4299c7c041cf989c069cc18fa083 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 29 Oct 2026 21:52:39 -0700 Subject: [PATCH 3/8] Read Only Signal Exit Codes as a Signal-Killed Verify FFmpeg exits a decode failure as its negative error code cut to a byte, 183 for invalid data, so any exit above 128 kept corrupt files. Only signals 1 to 15 and FFmpeg's own 255 now count. Co-Authored-By: Claude Opus 5.5 --- ARCHITECTURE.md | 4 ++-- HISTORY.md | 3 ++- PlexCleaner/FfMpegTool.cs | 5 +++-- PlexCleaner/ToolErrorScope.cs | 2 +- PlexCleanerTests/VerifyToolErrorTests.cs | 25 +++++++++++++++++++++--- 5 files changed, 30 insertions(+), 9 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 4a331cd2..34951c36 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -357,7 +357,7 @@ flowchart TD CLEAN -.->|"any step false or cancel"| AB AB["Abort the file, failedOperation names the step"] --> G5{"Skipped as read-only?"} G5 -->|yes| RET(["Result false, return the state and final path"]) - G5 -->|no| DF["DeleteFailedFile(): DeleteInvalidFiles deletes the media file, and the sidecar of an MKV file, unless cancelled, a tool run for the file failed to launch or threw, or an FfMpeg verify run was killed by a signal"] + G5 -->|no| DF["DeleteFailedFile(): DeleteInvalidFiles deletes the media file, and the sidecar of an MKV file, unless cancelled, a tool run for the file failed to launch or threw, or an FfMpeg verify run was killed by a signal outside Windows"] DF --> RET classDef suspect stroke:#c00,stroke-width:2px,stroke-dasharray:5 3 class P02,CLEAN suspect @@ -640,7 +640,7 @@ The `ConvertOptions` settings shape the FfMpeg and HandBrake command lines, and ### Verify and Repair -`VerifyAndRepair()` verifies the media streams with FfMpeg and repairs what fails. `VerifyClassifier` reads the FfMpeg error output. A non-monotonic DTS line alone yields `TimestampOnly`, any other error line or a non-zero exit yields `DecodeError`, and no line yields `Clean`. A run a signal terminates also yields `DecodeError`, so the repair ladder still runs, and the file is never deleted on it. An FfMpeg run that fails to launch, is cancelled, or whose execution throws yields `ToolError`, which leaves the media unchecked. On the first verify the file then fails with its state unchanged. A repair that fails while any of its tool runs failed to launch, was cancelled, or threw also leaves the state unchanged. +`VerifyAndRepair()` verifies the media streams with FfMpeg and repairs what fails. `VerifyClassifier` reads the FfMpeg error output. A non-monotonic DTS line alone yields `TimestampOnly`, any other error line or a non-zero exit yields `DecodeError`, and no line yields `Clean`. A run a signal terminates also yields `DecodeError`, so the repair ladder still runs. Outside Windows, the file is never deleted on it. An FfMpeg run that fails to launch, is cancelled, or whose execution throws yields `ToolError`, which leaves the media unchecked. On the first verify the file then fails with its state unchanged. A repair that fails while any of its tool runs failed to launch, was cancelled, or threw also leaves the state unchanged. ```mermaid flowchart TD diff --git a/HISTORY.md b/HISTORY.md index c7a02afb..670bd8a6 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -46,7 +46,8 @@ Utility to optimize media files for Direct Play in Plex, Emby, Jellyfin, etc. - A cancel, a read-only media file, and a read-only sidecar file leave the media file and its sidecar in place. - A failed non-MKV file keeps the sidecar of a sibling MKV file with the same name. - A tool that fails to launch or throws leaves the media file and its sidecar in place, in any processing step. - - An FfMpeg verify run killed by a signal, outside Windows, still runs the repair, and leaves the media file and its sidecar in place when the repair fails. + - An FfMpeg verify run killed by a signal still runs the repair. + - Outside Windows, the media file and its sidecar stay in place when that repair fails. - A failed repair whose tool fails to launch or throws leaves the file's state unchanged, rather than marking it `VerifyFailed` and `RepairFailed`. - The next run retries the repair. - Version 3.22: diff --git a/PlexCleaner/FfMpegTool.cs b/PlexCleaner/FfMpegTool.cs index 799ac269..e0bdda98 100644 --- a/PlexCleaner/FfMpegTool.cs +++ b/PlexCleaner/FfMpegTool.cs @@ -167,9 +167,10 @@ internal static Command GetVerifyMediaCommand(string toolPath, string fileName) ) .Build(); - // A process killed by a signal exits with 128 plus the signal number + // Signals 1 to 15 exit 129 to 143, and FFmpeg exits 255 once it handles a signal + // FFmpeg exits any other error as its negative code cut to a byte, such as 183 for invalid data internal static bool IsSignalExit(int exitCode) => - !OperatingSystem.IsWindows() && exitCode > 128; + !OperatingSystem.IsWindows() && exitCode is (>= 129 and <= 143) or 255; public VerifyResult VerifyMedia(string fileName) { diff --git a/PlexCleaner/ToolErrorScope.cs b/PlexCleaner/ToolErrorScope.cs index 8c3a34d1..dbe1b2a9 100644 --- a/PlexCleaner/ToolErrorScope.cs +++ b/PlexCleaner/ToolErrorScope.cs @@ -7,7 +7,7 @@ internal static class ToolErrorScope public static int Count => s_current.Value?.Count ?? 0; - // Counts the file's tool runs terminated by a signal, an external kill reads the same as a crash on corrupt media + // Counts the file's FfMpeg verify runs a signal ended, an external kill reads the same as a crash on corrupt media public static int SignalCount => s_current.Value?.SignalCount ?? 0; public static IDisposable BeginScope() diff --git a/PlexCleanerTests/VerifyToolErrorTests.cs b/PlexCleanerTests/VerifyToolErrorTests.cs index 42a56227..13cc9a73 100644 --- a/PlexCleanerTests/VerifyToolErrorTests.cs +++ b/PlexCleanerTests/VerifyToolErrorTests.cs @@ -105,17 +105,36 @@ public void VerifyMedia_SignalExit_IsDecodeErrorAndRecordsSignal() _ = ToolErrorScope.Count.Should().Be(0); } - [Fact] - public void VerifyMedia_ErrorExit_RecordsNoSignal() + [Theory] + [InlineData(1)] + [InlineData(183)] + [InlineData(234)] + public void VerifyMedia_ErrorExit_RecordsNoSignal(int exitCode) { Assert.SkipWhen(OperatingSystem.IsWindows(), "The fake FfMpeg is a shell script"); using IDisposable toolErrorScope = ToolErrorScope.BeginScope(); - WriteScript(Tools.FfMpeg.GetToolPath(), "exit 1\n", true); + WriteScript(Tools.FfMpeg.GetToolPath(), $"exit {exitCode}\n", true); _ = Tools.FfMpeg.VerifyMedia(CreateFile("name.mkv")).Should().Be(VerifyResult.DecodeError); _ = ToolErrorScope.SignalCount.Should().Be(0); } + [Theory] + [InlineData(1, false)] + [InlineData(128, false)] + [InlineData(129, true)] + [InlineData(137, true)] + [InlineData(143, true)] + [InlineData(144, false)] + [InlineData(183, false)] + [InlineData(244, false)] + [InlineData(255, true)] + public void IsSignalExit_MatchesSignalExitCodes(int exitCode, bool isSignal) + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "Signal exit codes are not read on Windows"); + _ = FfMpeg.Tool.IsSignalExit(exitCode).Should().Be(isSignal); + } + [Fact] public void VerifyAndRepair_SignalExitRepairFails_SetsStateAndKeepsFiles() { From 9e21bdeeb496d6237337b82e047a1d5305b638b4 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 29 Oct 2026 21:54:35 -0700 Subject: [PATCH 4/8] State Why a 255 Verify Exit Counts as a Signal Co-Authored-By: Claude Opus 5.5 --- PlexCleaner/FfMpegTool.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/PlexCleaner/FfMpegTool.cs b/PlexCleaner/FfMpegTool.cs index e0bdda98..95e808a3 100644 --- a/PlexCleaner/FfMpegTool.cs +++ b/PlexCleaner/FfMpegTool.cs @@ -168,7 +168,8 @@ internal static Command GetVerifyMediaCommand(string toolPath, string fileName) .Build(); // Signals 1 to 15 exit 129 to 143, and FFmpeg exits 255 once it handles a signal - // FFmpeg exits any other error as its negative code cut to a byte, such as 183 for invalid data + // FFmpeg exits an error as its negative code cut to a byte, such as 183 for invalid data + // A rare error that also exits 255 only keeps the file internal static bool IsSignalExit(int exitCode) => !OperatingSystem.IsWindows() && exitCode is (>= 129 and <= 143) or 255; From fa4e0dcde56f80d7d47bd62bca7bc5ad3d592b42 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 29 Oct 2026 22:01:53 -0700 Subject: [PATCH 5/8] Read Signals 1 to 31 as a Signal-Killed Verify SIGXCPU, SIGXFSZ and the Linux SIGSYS exit 152 to 159, above the earlier range. FFmpeg's own error codes cut to a byte start at 166, so a corrupt file still deletes. Co-Authored-By: Claude Opus 5.5 --- PlexCleaner/FfMpegTool.cs | 4 ++-- PlexCleaner/ToolErrorScope.cs | 2 +- PlexCleanerTests/VerifyToolErrorTests.cs | 14 ++++++++++---- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/PlexCleaner/FfMpegTool.cs b/PlexCleaner/FfMpegTool.cs index 95e808a3..d9a03669 100644 --- a/PlexCleaner/FfMpegTool.cs +++ b/PlexCleaner/FfMpegTool.cs @@ -167,11 +167,11 @@ internal static Command GetVerifyMediaCommand(string toolPath, string fileName) ) .Build(); - // Signals 1 to 15 exit 129 to 143, and FFmpeg exits 255 once it handles a signal + // Signals 1 to 31 exit 129 to 159, and FFmpeg exits 255 once it handles a signal // FFmpeg exits an error as its negative code cut to a byte, such as 183 for invalid data // A rare error that also exits 255 only keeps the file internal static bool IsSignalExit(int exitCode) => - !OperatingSystem.IsWindows() && exitCode is (>= 129 and <= 143) or 255; + !OperatingSystem.IsWindows() && exitCode is (>= 129 and <= 159) or 255; public VerifyResult VerifyMedia(string fileName) { diff --git a/PlexCleaner/ToolErrorScope.cs b/PlexCleaner/ToolErrorScope.cs index dbe1b2a9..64c9f543 100644 --- a/PlexCleaner/ToolErrorScope.cs +++ b/PlexCleaner/ToolErrorScope.cs @@ -7,7 +7,7 @@ internal static class ToolErrorScope public static int Count => s_current.Value?.Count ?? 0; - // Counts the file's FfMpeg verify runs a signal ended, an external kill reads the same as a crash on corrupt media + // Counts the file's FfMpeg verify runs that a signal ended, an external kill reads the same as a crash on corrupt media public static int SignalCount => s_current.Value?.SignalCount ?? 0; public static IDisposable BeginScope() diff --git a/PlexCleanerTests/VerifyToolErrorTests.cs b/PlexCleanerTests/VerifyToolErrorTests.cs index 13cc9a73..7fadd429 100644 --- a/PlexCleanerTests/VerifyToolErrorTests.cs +++ b/PlexCleanerTests/VerifyToolErrorTests.cs @@ -93,12 +93,15 @@ private string CopyUnverifiedSample() public void VerifyMedia_ToolDoesNotRun_IsToolError() => _ = Tools.FfMpeg.VerifyMedia(CreateFile("name.mkv")).Should().Be(VerifyResult.ToolError); - [Fact] - public void VerifyMedia_SignalExit_IsDecodeErrorAndRecordsSignal() + [Theory] + [InlineData("KILL")] + [InlineData("TERM")] + [InlineData("PROF")] + public void VerifyMedia_SignalExit_IsDecodeErrorAndRecordsSignal(string signal) { Assert.SkipWhen(OperatingSystem.IsWindows(), "The fake FfMpeg is a shell script"); using IDisposable toolErrorScope = ToolErrorScope.BeginScope(); - WriteScript(Tools.FfMpeg.GetToolPath(), "kill -9 $$\n", true); + WriteScript(Tools.FfMpeg.GetToolPath(), $"kill -{signal} $$\n", true); _ = Tools.FfMpeg.VerifyMedia(CreateFile("name.mkv")).Should().Be(VerifyResult.DecodeError); _ = ToolErrorScope.SignalCount.Should().Be(1); @@ -125,7 +128,10 @@ public void VerifyMedia_ErrorExit_RecordsNoSignal(int exitCode) [InlineData(129, true)] [InlineData(137, true)] [InlineData(143, true)] - [InlineData(144, false)] + [InlineData(153, true)] + [InlineData(159, true)] + [InlineData(160, false)] + [InlineData(166, false)] [InlineData(183, false)] [InlineData(244, false)] [InlineData(255, true)] From 08fa06282d572632a195f93ba1ab2860dd6bd4c4 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Fri, 30 Oct 2026 06:39:23 -0700 Subject: [PATCH 6/8] Leave the State Unchanged After a Signal-Killed Verify A failed or skipped repair after a signal-ended verify saved VerifyFailed, so the next run skipped verify and DeleteFailedFile() deleted the file. The state now stays unchanged, so the next run verifies again, and a genuine decode error on that run still deletes. Co-Authored-By: Claude Opus 5.5 --- ARCHITECTURE.md | 8 ++++-- HISTORY.md | 1 + PlexCleaner/ProcessFile.cs | 18 +++++++++--- PlexCleanerTests/VerifyToolErrorTests.cs | 36 ++++++++++++++++-------- 4 files changed, 44 insertions(+), 19 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 34951c36..d2b875ef 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -640,7 +640,7 @@ The `ConvertOptions` settings shape the FfMpeg and HandBrake command lines, and ### Verify and Repair -`VerifyAndRepair()` verifies the media streams with FfMpeg and repairs what fails. `VerifyClassifier` reads the FfMpeg error output. A non-monotonic DTS line alone yields `TimestampOnly`, any other error line or a non-zero exit yields `DecodeError`, and no line yields `Clean`. A run a signal terminates also yields `DecodeError`, so the repair ladder still runs. Outside Windows, the file is never deleted on it. An FfMpeg run that fails to launch, is cancelled, or whose execution throws yields `ToolError`, which leaves the media unchecked. On the first verify the file then fails with its state unchanged. A repair that fails while any of its tool runs failed to launch, was cancelled, or threw also leaves the state unchanged. +`VerifyAndRepair()` verifies the media streams with FfMpeg and repairs what fails. `VerifyClassifier` reads the FfMpeg error output. A non-monotonic DTS line alone yields `TimestampOnly`, any other error line or a non-zero exit yields `DecodeError`, and no line yields `Clean`. A run a signal terminates also yields `DecodeError`, so the repair ladder still runs. Outside Windows, the file is never deleted on it. A failed or skipped repair after such a run leaves the state unchanged, so the next run verifies the file again. An FfMpeg run that fails to launch, is cancelled, or whose execution throws yields `ToolError`, which leaves the media unchecked. On the first verify the file then fails with its state unchanged. A repair that fails while any of its tool runs failed to launch, was cancelled, or threw also leaves the state unchanged. ```mermaid flowchart TD @@ -667,7 +667,9 @@ flowchart TD C0 -->|no| C1{"canRepair, AutoRepair option on, and no RepairFailed?"} NOREP --> C0 TE --> FAIL - C1 -->|no| NF["Set VerifyFailed, clear Verified, save state, fail"] + C1 -->|no| NS{"A signal ended a verify?"} + NS -->|yes| FAIL + NS -->|no| NF["Set VerifyFailed, clear Verified, save state, fail"] C1 -->|yes| C2{"Result was TimestampOnly?"} C2 -->|yes| T0["RepairTimestampsAndSetState(): GetPacketAnalysis() result ignored, S11"]:::suspect T0 --> T1["TryLosslessTimestampRepair(): only when every non-monotonic stream is audio"] @@ -696,7 +698,7 @@ flowchart TD R6 -->|"DecodeError path"| RC{"Cancelled?"} RC -->|"yes, the repaired file already replaced the original, S5"| FAIL RC -->|no| RS["Set Verified and Repaired, clear VerifyFailed and RepairFailed, Refresh(), continue"] - RF{"Cancelled, or a repair tool failed to launch or threw?"} -->|yes| FAIL + RF{"Cancelled, a repair tool failed to launch or threw, or a signal ended a verify?"} -->|yes| FAIL RF -->|no| RFF["Set VerifyFailed and RepairFailed, clear Verified and Repaired, save state, fail"] classDef suspect stroke:#c00,stroke-width:2px,stroke-dasharray:5 3 ``` diff --git a/HISTORY.md b/HISTORY.md index 670bd8a6..2ac130e7 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -48,6 +48,7 @@ Utility to optimize media files for Direct Play in Plex, Emby, Jellyfin, etc. - A tool that fails to launch or throws leaves the media file and its sidecar in place, in any processing step. - An FfMpeg verify run killed by a signal still runs the repair. - Outside Windows, the media file and its sidecar stay in place when that repair fails. + - A failed or skipped repair leaves the file's state unchanged, so the next run verifies it again. - A failed repair whose tool fails to launch or throws leaves the file's state unchanged, rather than marking it `VerifyFailed` and `RepairFailed`. - The next run retries the repair. - Version 3.22: diff --git a/PlexCleaner/ProcessFile.cs b/PlexCleaner/ProcessFile.cs index e88b07ad..6e03b8cf 100644 --- a/PlexCleaner/ProcessFile.cs +++ b/PlexCleaner/ProcessFile.cs @@ -1853,6 +1853,12 @@ public bool VerifyAndRepair(ref bool modified) || !Program.Config.VerifyOptions.AutoRepair ) { + // A signal ended a verify, leave the state unchanged so the next run verifies again + if (ToolErrorScope.SignalCount > 0) + { + return false; + } + // Set VerifyFailed state if not already set if (!_sidecarFile.State.HasFlag(SidecarFile.StatesType.VerifyFailed)) { @@ -1891,8 +1897,8 @@ public bool VerifyAndRepair(ref bool modified) // Repair failed if (!repaired) { - // A repair tool did not run, leave the state unchanged - if (ToolErrorScope.Count != toolErrors) + // A repair tool did not run or a signal ended a verify, leave the state unchanged + if (ToolErrorScope.Count != toolErrors || ToolErrorScope.SignalCount > 0) { return false; } @@ -2277,8 +2283,12 @@ private bool RepairTimestampsAndSetState(ref bool modified) return Refresh(true); } - // Do not touch state on cancellation or when a tool did not run, the caller retries next run - if (Program.IsCancelled() || ToolErrorScope.Count != toolErrors) + // Do not touch state on cancellation, a tool that did not run, or a signal-ended verify + if ( + Program.IsCancelled() + || ToolErrorScope.Count != toolErrors + || ToolErrorScope.SignalCount > 0 + ) { return false; } diff --git a/PlexCleanerTests/VerifyToolErrorTests.cs b/PlexCleanerTests/VerifyToolErrorTests.cs index 7fadd429..83d73651 100644 --- a/PlexCleanerTests/VerifyToolErrorTests.cs +++ b/PlexCleanerTests/VerifyToolErrorTests.cs @@ -141,10 +141,25 @@ public void IsSignalExit_MatchesSignalExitCodes(int exitCode, bool isSignal) _ = FfMpeg.Tool.IsSignalExit(exitCode).Should().Be(isSignal); } - [Fact] - public void VerifyAndRepair_SignalExitRepairFails_SetsStateAndKeepsFiles() + [Theory] + [InlineData("kill -9 $$", true, SidecarFile.StatesType.None, false)] + [InlineData("kill -9 $$", false, SidecarFile.StatesType.None, false)] + [InlineData( + "exit 183", + true, + SidecarFile.StatesType.VerifyFailed | SidecarFile.StatesType.RepairFailed, + true + )] + [InlineData("exit 183", false, SidecarFile.StatesType.VerifyFailed, true)] + public void VerifyAndRepair_VerifyFails_SetsStateAndDeletesOnlyWithoutSignal( + string firstVerify, + bool autoRepair, + SidecarFile.StatesType state, + bool deleted + ) { Assert.SkipWhen(OperatingSystem.IsWindows(), "The fake tools are shell scripts"); + Program.Config.VerifyOptions.AutoRepair = autoRepair; using IDisposable toolErrorScope = ToolErrorScope.BeginScope(); string mediaFile = CopyUnverifiedSample(); string sidecarFile = Path.ChangeExtension(mediaFile, ".PlexCleaner"); @@ -156,10 +171,10 @@ public void VerifyAndRepair_SignalExitRepairFails_SetsStateAndKeepsFiles() string ffMpeg = Tools.FfMpeg.GetToolPath(); WriteScript( ffMpeg, - """ + $$""" step=$(($(cat "$0.step" 2>/dev/null || echo 0) + 1)) echo $step > "$0.step" - [ $step -eq 1 ] && kill -9 $$ + [ $step -eq 1 ] && {{firstVerify}} exit 1 """, @@ -168,17 +183,14 @@ exit 1 bool modified = false; _ = processFile.VerifyAndRepair(ref modified).Should().BeFalse(); - _ = ToolErrorScope.SignalCount.Should().Be(1); + _ = ToolErrorScope.SignalCount.Should().Be(deleted ? 0 : 1); _ = ToolErrorScope.Count.Should().Be(0); - _ = processFile - .State.Should() - .HaveFlag(SidecarFile.StatesType.VerifyFailed) - .And.HaveFlag(SidecarFile.StatesType.RepairFailed); - _ = processFile.DeleteFailedFile().Should().BeFalse(); + _ = processFile.State.Should().Be(state); + _ = processFile.DeleteFailedFile().Should().Be(deleted); _ = modified.Should().BeFalse(); - _ = File.Exists(mediaFile).Should().BeTrue(); - _ = File.Exists(sidecarFile).Should().BeTrue(); + _ = File.Exists(mediaFile).Should().Be(!deleted); + _ = File.Exists(sidecarFile).Should().Be(!deleted); } [Fact] From 46ab8b4dd3f20999a8c2e3949c224b6d7206b00a Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Fri, 30 Oct 2026 06:42:14 -0700 Subject: [PATCH 7/8] Pin the Timestamp Ladder Signal Guard and Scope the Docs to Non-Windows Co-Authored-By: Claude Opus 5.5 --- ARCHITECTURE.md | 2 +- HISTORY.md | 2 +- PlexCleanerTests/VerifyToolErrorTests.cs | 41 ++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index d2b875ef..458bea92 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -640,7 +640,7 @@ The `ConvertOptions` settings shape the FfMpeg and HandBrake command lines, and ### Verify and Repair -`VerifyAndRepair()` verifies the media streams with FfMpeg and repairs what fails. `VerifyClassifier` reads the FfMpeg error output. A non-monotonic DTS line alone yields `TimestampOnly`, any other error line or a non-zero exit yields `DecodeError`, and no line yields `Clean`. A run a signal terminates also yields `DecodeError`, so the repair ladder still runs. Outside Windows, the file is never deleted on it. A failed or skipped repair after such a run leaves the state unchanged, so the next run verifies the file again. An FfMpeg run that fails to launch, is cancelled, or whose execution throws yields `ToolError`, which leaves the media unchecked. On the first verify the file then fails with its state unchanged. A repair that fails while any of its tool runs failed to launch, was cancelled, or threw also leaves the state unchanged. +`VerifyAndRepair()` verifies the media streams with FfMpeg and repairs what fails. `VerifyClassifier` reads the FfMpeg error output. A non-monotonic DTS line alone yields `TimestampOnly`, any other error line or a non-zero exit yields `DecodeError`, and no line yields `Clean`. A run a signal terminates also yields `DecodeError`, so the repair ladder still runs. Outside Windows, the file is never deleted on it. Outside Windows, a failed or skipped repair after such a run also leaves the state unchanged, so the next run verifies the file again. An FfMpeg run that fails to launch, is cancelled, or whose execution throws yields `ToolError`, which leaves the media unchecked. On the first verify the file then fails with its state unchanged. A repair that fails while any of its tool runs failed to launch, was cancelled, or threw also leaves the state unchanged. ```mermaid flowchart TD diff --git a/HISTORY.md b/HISTORY.md index 2ac130e7..21fd3d7b 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -48,7 +48,7 @@ Utility to optimize media files for Direct Play in Plex, Emby, Jellyfin, etc. - A tool that fails to launch or throws leaves the media file and its sidecar in place, in any processing step. - An FfMpeg verify run killed by a signal still runs the repair. - Outside Windows, the media file and its sidecar stay in place when that repair fails. - - A failed or skipped repair leaves the file's state unchanged, so the next run verifies it again. + - A failed or skipped repair leaves the file's state unchanged, so the next run verifies it again. - A failed repair whose tool fails to launch or throws leaves the file's state unchanged, rather than marking it `VerifyFailed` and `RepairFailed`. - The next run retries the repair. - Version 3.22: diff --git a/PlexCleanerTests/VerifyToolErrorTests.cs b/PlexCleanerTests/VerifyToolErrorTests.cs index 83d73651..f53881a8 100644 --- a/PlexCleanerTests/VerifyToolErrorTests.cs +++ b/PlexCleanerTests/VerifyToolErrorTests.cs @@ -193,6 +193,47 @@ exit 1 _ = File.Exists(sidecarFile).Should().Be(!deleted); } + [Fact] + public void VerifyAndRepair_TimestampReVerifySignalExit_KeepsStateAndFiles() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "The fake tools are shell scripts"); + using IDisposable toolErrorScope = ToolErrorScope.BeginScope(); + string mediaFile = CopyUnverifiedSample(); + string sidecarFile = Path.ChangeExtension(mediaFile, ".PlexCleaner"); + ProcessFile processFile = new(mediaFile); + _ = processFile.GetMediaProps().Should().BeTrue(); + + WriteScript(Tools.FfProbe.GetToolPath(), "exit 1\n", true); + WriteScript(Tools.MkvMerge.GetToolPath(), "for a; do out=$a; done\n: > \"$out\"\n", true); + WriteScript(Tools.HandBrake.GetToolPath(), "exit 1\n", true); + string ffMpeg = Tools.FfMpeg.GetToolPath(); + WriteScript( + ffMpeg, + """ + step=$(($(cat "$0.step" 2>/dev/null || echo 0) + 1)) + echo $step > "$0.step" + case $step in + 1) echo "non monotonically increasing dts to muxer" >&2 && exit 0 ;; + 2) kill -9 $$ ;; + esac + exit 1 + + """, + true + ); + + bool modified = false; + _ = processFile.VerifyAndRepair(ref modified).Should().BeFalse(); + _ = ToolErrorScope.SignalCount.Should().Be(1); + _ = ToolErrorScope.Count.Should().Be(0); + _ = processFile.State.Should().Be(SidecarFile.StatesType.None); + _ = processFile.DeleteFailedFile().Should().BeFalse(); + + _ = modified.Should().BeFalse(); + _ = File.Exists(mediaFile).Should().BeTrue(); + _ = File.Exists(sidecarFile).Should().BeTrue(); + } + [Fact] public void VerifyAndRepair_ToolError_KeepsStateAndFiles() { From 81a53a6a709dabb87d795d8201209cfc5dff5aed Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Fri, 30 Oct 2026 06:54:27 -0700 Subject: [PATCH 8/8] Assert the Repair Ladder Ran in the Signal Verify Theory Co-Authored-By: Claude Opus 5.5 --- PlexCleanerTests/VerifyToolErrorTests.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/PlexCleanerTests/VerifyToolErrorTests.cs b/PlexCleanerTests/VerifyToolErrorTests.cs index f53881a8..c9b83c95 100644 --- a/PlexCleanerTests/VerifyToolErrorTests.cs +++ b/PlexCleanerTests/VerifyToolErrorTests.cs @@ -187,6 +187,7 @@ exit 1 _ = ToolErrorScope.Count.Should().Be(0); _ = processFile.State.Should().Be(state); _ = processFile.DeleteFailedFile().Should().Be(deleted); + _ = File.ReadAllText(ffMpeg + ".step").Trim().Should().Be(autoRepair ? "2" : "1"); _ = modified.Should().BeFalse(); _ = File.Exists(mediaFile).Should().Be(!deleted);