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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 outside Windows"]
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.

Expand Down Expand Up @@ -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. 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
Expand All @@ -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"])
Expand All @@ -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"]
Expand Down Expand Up @@ -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
```
Expand Down Expand Up @@ -742,7 +744,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

Expand Down
3 changes: 3 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ 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 still runs the repair.
- Outside Windows, the media file and its sidecar stay in place when that repair fails.
Comment thread
ptr727 marked this conversation as resolved.
Resolved
- 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:
Expand Down
10 changes: 10 additions & 0 deletions PlexCleaner/FfMpegTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,12 @@ internal static Command GetVerifyMediaCommand(string toolPath, string fileName)
)
.Build();

// 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 <= 159) or 255;

public VerifyResult VerifyMedia(string fileName)
{
Command command = GetVerifyMediaCommand(GetToolPath(), fileName);
Expand All @@ -190,6 +196,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.
Expand Down
19 changes: 15 additions & 4 deletions PlexCleaner/ProcessFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1794,6 +1794,7 @@ public bool DeleteFailedFile()
if (
!Program.Config.VerifyOptions.DeleteInvalidFiles
|| ToolErrorScope.Count > 0
|| ToolErrorScope.SignalCount > 0
|| Program.IsCancelledError()
)
{
Expand Down Expand Up @@ -1852,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))
{
Expand Down Expand Up @@ -1890,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;
}
Expand Down Expand Up @@ -2276,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;
}
Expand Down
12 changes: 12 additions & 0 deletions PlexCleaner/ToolErrorScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ internal static class ToolErrorScope

public static int Count => s_current.Value?.Count ?? 0;

// 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()
{
Session? previous = s_current.Value;
Expand All @@ -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
Expand Down
11 changes: 11 additions & 0 deletions PlexCleanerTests/ToolErrorScopeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
142 changes: 142 additions & 0 deletions PlexCleanerTests/VerifyToolErrorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,148 @@ private string CopyUnverifiedSample()
public void VerifyMedia_ToolDoesNotRun_IsToolError() =>
_ = Tools.FfMpeg.VerifyMedia(CreateFile("name.mkv")).Should().Be(VerifyResult.ToolError);

[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 -{signal} $$\n", true);

_ = Tools.FfMpeg.VerifyMedia(CreateFile("name.mkv")).Should().Be(VerifyResult.DecodeError);
_ = ToolErrorScope.SignalCount.Should().Be(1);
_ = ToolErrorScope.Count.Should().Be(0);
}

[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 {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(153, true)]
[InlineData(159, true)]
[InlineData(160, false)]
[InlineData(166, 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);
}

[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");
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 ] && {{firstVerify}}
exit 1

""",
true
);

bool modified = false;
_ = processFile.VerifyAndRepair(ref modified).Should().BeFalse();
_ = ToolErrorScope.SignalCount.Should().Be(deleted ? 0 : 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);
_ = 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()
{
Expand Down
Loading