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
19 changes: 11 additions & 8 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -357,10 +357,10 @@ 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"]
G5 -->|no| DF["DeleteFailedFile(): DeleteInvalidFiles deletes the media file, and the sidecar of an MKV file, unless cancelled or the file's own stream verify is a tool error, S16"]
DF --> RET
classDef suspect stroke:#c00,stroke-width:2px,stroke-dasharray:5 3
class P02,CLEAN suspect
class P02,CLEAN,DF suspect
```

`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 @@ -638,7 +638,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`. An FfMpeg run that does not complete also yields `DecodeError`, S15.
`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 and is not deleted. A re-verify inside the repair ladder reads `ToolError` as a failed repair, S16.

```mermaid
flowchart TD
Expand All @@ -654,7 +654,8 @@ 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 a run that did not complete, S15"| REP["Verify fails, repair possible"]
V7 -->|"TimestampOnly, or DecodeError including any non-zero exit, S17"| 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"])
P1 -->|no| P2["Set Verified, clear VerifyFailed, save state"]
Expand All @@ -663,28 +664,29 @@ flowchart TD
C0 -->|yes| FAIL(["Fail, state unchanged"])
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 -->|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"]
T1 --> T2["FfMpeg rewrites timestamps to .tmp14"]
T2 --> T3["TimestampRepairRegressionGate(): stream hashes equal, start and duration within 40 ms"]
T3 --> T4{"Re-verify Clean?"}
T3 --> T4{"Re-verify Clean? ToolError reads as no, S16"}:::suspect
T4 -->|yes| T5["Move over the original"]
T5 --> RS
T1 -->|"not audio only, or any step fails"| T6["Remux only when the original or the rewritten file shows a DTS issue only after decode"]
T4 -->|no| T6
T6 --> R0
C2 -->|"no, DecodeError"| R0["RepairAndReVerify()"]
R0 --> R1["TryRemuxRepair(): MkvMerge to .tmp11, re-verify Clean"]
R0 --> R1["TryRemuxRepair(): MkvMerge to .tmp11, re-verify Clean, ToolError reads as fail, S16"]:::suspect
R1 -->|pass| R6["Move over the original"]
R1 -->|fail| R2{"Cancelled, or remux only?"}
R2 -->|yes| RF
R2 -->|no| R3["FfMpeg re-encode to .tmp12"]
R3 -->|"fail, not cancelled"| R4["HandBrake re-encode to .tmp12, subtitles included"]
R3 -->|"fail, cancelled"| RF
R4 -->|fail| RF
R3 --> R5["Convert.ReMux(), then re-verify Clean"]
R3 --> R5["Convert.ReMux(), then re-verify Clean, ToolError reads as fail, S16"]:::suspect
R4 --> R5
R5 -->|fail| RF
R5 -->|pass| R6
Expand Down Expand Up @@ -738,7 +740,8 @@ 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.
- **S15** ([#1084](https://github.com/ptr727/PlexCleaner/issues/1084)): `FfMpegTool.VerifyMedia()` returns `DecodeError` when FfMpeg does not run to completion. A verification that never ran then enters the repair ladder, and can end in `VerifyFailed`, `RepairFailed` and a delete.
- **S16** ([#1088](https://github.com/ptr727/PlexCleaner/issues/1088)): A step whose tool did not run fails as if the media failed. `DeleteFailedFile()` keeps the file only after a `ToolError` from the file's own stream verify, in `Verify()` or `RepairTimestamps()`. A launch failure on a re-verify in the repair ladder fails the repair and sets `VerifyFailed` and `RepairFailed`. `DeleteInvalidFiles` then deletes the file. A tool that fails to launch in any other step aborts the file, and `DeleteInvalidFiles` deletes it.
- **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
2 changes: 1 addition & 1 deletion PlexCleaner/FfMpegTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ public VerifyResult VerifyMedia(string fileName)
{
// Process could not run
Metrics.OpAborted();
return VerifyResult.DecodeError;
return VerifyResult.ToolError;
}
Metrics.OpCompleted();

Expand Down
25 changes: 20 additions & 5 deletions PlexCleaner/ProcessFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class ProcessFile

private SidecarFile _sidecarFile;

// Classification of the most recent stream verify, used to choose the repair strategy
// Classification of the file's own stream verify, it chooses the repair and a tool error blocks the delete
private VerifyResult _lastVerifyResult;

public ProcessFile(string mediaFile)
Expand Down Expand Up @@ -1708,6 +1708,7 @@ public bool Verify(bool conditional, out bool canRepair)

// Init
canRepair = false;
_lastVerifyResult = VerifyResult.Clean;

// Conditional
if (conditional && !Program.Config.ProcessOptions.Verify)
Expand Down Expand Up @@ -1748,7 +1749,7 @@ public bool Verify(bool conditional, out bool canRepair)
// Will update sidecar state if bitrate exceeded
_ = VerifyBitrate();

// Verify media streams, both failure kinds are repairable
// Verify media streams, VerifyAndRepair() stops on a tool error before it reads canRepair
canRepair = true;
_lastVerifyResult = VerifyMediaStreams(FileInfo);

Expand All @@ -1768,6 +1769,13 @@ public static VerifyResult VerifyMediaStreams(FileInfo fileInfo)
{
Log.Error("Failed to verify media streams : {FileName}", fileInfo.FullName);
}
else if (verifyResult == VerifyResult.ToolError)
{
Log.Error(
"Failed to run media stream verification : {FileName}",
fileInfo.FullName
);
}
else if (verifyResult == VerifyResult.TimestampOnly)
{
// Correctable failure, the decision Warning is emitted later if the repair runs
Expand All @@ -1783,7 +1791,11 @@ public static VerifyResult VerifyMediaStreams(FileInfo fileInfo)
public bool DeleteFailedFile()
{
// Conditional
if (!Program.Config.VerifyOptions.DeleteInvalidFiles || Program.IsCancelledError())
if (
!Program.Config.VerifyOptions.DeleteInvalidFiles
|| _lastVerifyResult == VerifyResult.ToolError
|| Program.IsCancelledError()
)
Comment thread
ptr727 marked this conversation as resolved.
Resolved
{
// Return false if not deleted
return false;
Expand Down Expand Up @@ -1825,8 +1837,8 @@ public bool VerifyAndRepair(ref bool modified)
return true;
}

// Cancel requested
if (Program.IsCancelled())
// Cancel requested, or the verify did not run, leave the state unchanged
if (Program.IsCancelled() || _lastVerifyResult == VerifyResult.ToolError)
{
return false;
}
Expand Down Expand Up @@ -2229,6 +2241,9 @@ public bool RepairTimestamps(ref bool modified)
case VerifyResult.DecodeError:
// Genuine decode corruption, not repairable here, leave the state unchanged
return true;
case VerifyResult.ToolError:
// The verify did not run, leave the state unchanged and report the failure
return false;
default:
throw new NotImplementedException();
}
Expand Down
3 changes: 3 additions & 0 deletions PlexCleaner/VerifyResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,7 @@ public enum VerifyResult

// A genuine decode or demux corruption signature, or any unrecognized diagnostic, verify fails
DecodeError,

// FfMpeg failed to launch, was cancelled, or its execution threw, so the media is unchecked
ToolError,
}
113 changes: 113 additions & 0 deletions PlexCleanerTests/VerifyToolErrorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
using System.Text.Json.Nodes;
using AwesomeAssertions;
using PlexCleaner;
using Xunit;

namespace PlexCleanerTests;

[Collection("Sequential")]
public sealed class VerifyToolErrorTests : IDisposable
{
private readonly string _directory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
private readonly ToolsOptions1 _toolsOptions = Program.Config.ToolsOptions;
private readonly bool _verify = Program.Config.ProcessOptions.Verify;
private readonly bool _useSidecarFiles = Program.Config.ProcessOptions.UseSidecarFiles;
private readonly bool _autoRepair = Program.Config.VerifyOptions.AutoRepair;
private readonly bool _deleteInvalidFiles = Program.Config.VerifyOptions.DeleteInvalidFiles;
private readonly MediaToolInfo _ffProbeInfo = Tools.FfProbe.Info;
private readonly MediaToolInfo _mkvMergeInfo = Tools.MkvMerge.Info;
private readonly MediaToolInfo _mediaInfoInfo = Tools.MediaInfo.Info;

public VerifyToolErrorTests()
{
_ = Directory.CreateDirectory(_directory);
Program.Config.ProcessOptions.Verify = true;
Program.Config.ProcessOptions.UseSidecarFiles = true;
Program.Config.VerifyOptions.AutoRepair = true;
Program.Config.VerifyOptions.DeleteInvalidFiles = true;

// An empty tools folder makes every tool fail to launch
Program.Config.ToolsOptions = new ToolsOptions1
{
UseSystem = false,
RootRelative = false,
RootPath = _directory,
};
}

public void Dispose()
{
Program.Config.ToolsOptions = _toolsOptions;
Tools.FfProbe.Info = _ffProbeInfo;
Tools.MkvMerge.Info = _mkvMergeInfo;
Tools.MediaInfo.Info = _mediaInfoInfo;
Program.Config.ProcessOptions.Verify = _verify;
Program.Config.ProcessOptions.UseSidecarFiles = _useSidecarFiles;
Program.Config.VerifyOptions.AutoRepair = _autoRepair;
Program.Config.VerifyOptions.DeleteInvalidFiles = _deleteInvalidFiles;
Directory.Delete(_directory, true);
}

private string CreateFile(string name)
{
string fileName = Path.Combine(_directory, name);
File.WriteAllText(fileName, "");
return fileName;
}

// The sample sidecar supplies the media props, so only the verify needs a tool
private string CopyUnverifiedSample()
{
Tools.FfProbe.Info = new MediaToolInfo(Tools.FfProbe) { Version = "8.0.1" };
Tools.MkvMerge.Info = new MediaToolInfo(Tools.MkvMerge) { Version = "96.0" };
Tools.MediaInfo.Info = new MediaToolInfo(Tools.MediaInfo) { Version = "25.10" };

string sampleDirectory = PlexCleanerFixture.GetSamplesAbsoluteDirectory();
string mediaFile = Path.Combine(_directory, "name.mkv");
File.Copy(Path.Combine(sampleDirectory, "Sidecar.v5.mkv"), mediaFile);

JsonNode sidecar = JsonNode.Parse(
File.ReadAllText(Path.Combine(sampleDirectory, "Sidecar.v5.PlexCleaner"))
)!;
sidecar["State"] = (int)SidecarFile.StatesType.None;
File.WriteAllText(Path.Combine(_directory, "name.PlexCleaner"), sidecar.ToJsonString());
return mediaFile;
}

[Fact]
public void VerifyMedia_ToolDoesNotRun_IsToolError() =>
_ = Tools.FfMpeg.VerifyMedia(CreateFile("name.mkv")).Should().Be(VerifyResult.ToolError);

[Fact]
public void VerifyAndRepair_ToolError_KeepsStateAndFiles()
{
string mediaFile = CopyUnverifiedSample();
string sidecarFile = Path.ChangeExtension(mediaFile, ".PlexCleaner");
ProcessFile processFile = new(mediaFile);
_ = processFile.GetMediaProps().Should().BeTrue();

bool modified = false;
_ = processFile.VerifyAndRepair(ref modified).Should().BeFalse();
_ = 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 RepairTimestamps_ToolError_KeepsFiles()
{
string mediaFile = CreateFile("name.mkv");
string sidecarFile = CreateFile("name.PlexCleaner");
ProcessFile processFile = new(mediaFile);

bool modified = false;
_ = processFile.RepairTimestamps(ref modified).Should().BeFalse();
_ = processFile.DeleteFailedFile().Should().BeFalse();

_ = File.Exists(mediaFile).Should().BeTrue();
_ = File.Exists(sidecarFile).Should().BeTrue();
}
}
Loading