diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md index 4a69b33e..3c542761 100644 --- a/docs/guide/troubleshooting.md +++ b/docs/guide/troubleshooting.md @@ -376,4 +376,4 @@ The debug log is tuned for **developers troubleshooting pipeline flow** (maximum Give every entry a single-sentence `message` that stands on its own. Put all structured data (`context`, counts, ids, `duration_ms`) in **fields**, not in the prose. This separation lets the log be both human-scannable and machine-filterable. A message like `"Parsed DASH manifest"` with `context={"video": 4, "audio": 2}` beats `"Parsed manifest with 4 video and 2 audio tracks"`. !!! tip "Let tool runs log themselves" - For external-tool calls (FFmpeg, mkvmerge, `dovi_tool`, and friends), route through `run_step` / `run_tool` / `ffprobe`, which auto-emit a `tool_run` entry capturing the binary's version, return code, and duration consistently. `run_tool` also raises `ToolFailed`, whose message names the tool, the exit code and the last lines the tool wrote. Only fall back to calling `log_tool_run` manually for a direct `subprocess.run` you genuinely cannot route through those helpers. Auto-logging is the preferred path precisely because it captures those fields the same way every time. + For external-tool calls (FFmpeg, mkvmerge, `dovi_tool`, and friends), route through `run_step` / `run_tool` / `ffprobe`, which auto-emit a `tool_run` entry capturing the binary's version, return code, and duration consistently. `run_tool` also raises `ToolFailed`, whose message names the tool, the exit code and the last lines the tool wrote. A failure that the caller recovers from (a retry, a fallback) is named with `handled=` (exit codes or stderr text): its `tool_run` entry is `DEBUG`, not `ERROR`, and the call still raises. Only fall back to calling `log_tool_run` manually for a direct `subprocess.run` you genuinely cannot route through those helpers. Auto-logging is the preferred path precisely because it captures those fields the same way every time. diff --git a/tests/core/test_tool_failed.py b/tests/core/test_tool_failed.py index d89e68a7..207fc456 100644 --- a/tests/core/test_tool_failed.py +++ b/tests/core/test_tool_failed.py @@ -1,5 +1,7 @@ +import json import subprocess import sys +from collections.abc import Callable, Iterator from pathlib import Path from types import SimpleNamespace @@ -7,12 +9,15 @@ import pytest from unshackle.core import binaries from unshackle.core.api.errors import categorize_exception +from unshackle.core.config import config from unshackle.core.drm import decrypters from unshackle.core.remote_protocol import APIErrorCode -from unshackle.core.tracks import Audio, Subtitle +from unshackle.core.tracks import Audio, Hybrid, Subtitle, Video +from unshackle.core.tracks import hybrid as hybrid_module from unshackle.core.tracks.subtitle_convert import SubtitleEditBackend +from unshackle.core.utilities import close_debug_logger, init_debug_logger from unshackle.core.utils import subprocess as subprocess_module -from unshackle.core.utils.subprocess import ToolFailed, run_tool, tool_reason +from unshackle.core.utils.subprocess import ToolFailed, run_step, run_tool, tool_reason KEY = "b5df2ae3f63b8dda9049d6e41422e075" POSIX_STUBS = pytest.mark.skipif(sys.platform == "win32", reason="the tool stubs are shell scripts") @@ -138,3 +143,106 @@ def test_an_mp4decrypt_failure_names_the_reason_and_keeps_the_key( assert message.startswith("mp4decrypt failed (exit 1): ERROR: cannot open output file (out.mp4) -5; command: ") assert f"1:{KEY}" in message assert categorize_exception(caught.value).error_code == APIErrorCode.DRM_ERROR + + +@pytest.fixture +def debug_entries(tmp_path: Path) -> Iterator[Callable[[], list[dict]]]: + """An enabled debug logger; the fixture value reads its entries back.""" + path = tmp_path / "debug.jsonl" + init_debug_logger(log_path=path, enabled=True) + yield lambda: [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + close_debug_logger() + + +def levels(entries: list[dict], operation: str | None = "tool_run") -> list[str]: + """The levels of the entries of operation, or of every entry when operation is None.""" + return [e["level"] for e in entries if operation is None or e.get("operation") == operation] + + +@pytest.mark.parametrize(("code", "level"), [(10, "DEBUG"), (3, "ERROR")]) +def test_run_tool_logs_a_handled_exit_code_at_debug( + debug_entries: Callable[[], list[dict]], code: int, level: str +) -> None: + with pytest.raises(ToolFailed): + run_tool("tool", exits(code), "tool step", handled=(10,)) + assert levels(debug_entries()) == [level] + + +@pytest.mark.parametrize(("stderr", "level"), [("bad MAX_PQ_LUMINANCE value", "DEBUG"), ("Invalid PPS index", "ERROR")]) +def test_run_step_logs_a_handled_stderr_marker_at_debug( + debug_entries: Callable[[], list[dict]], stderr: str, level: str +) -> None: + with pytest.raises(RuntimeError, match=stderr): + run_step(exits(1, stderr=stderr), label="tool step", handled=("MAX_PQ_LUMINANCE",)) + assert levels(debug_entries()) == [level] + + +def dovi_stub(tmp_path: Path, mode_3_error: str) -> Path: + """A dovi_tool that fails with mode_3_error under -m and writes the RPU without it.""" + return stub( + tmp_path, + "dovi_tool", + f'if [ "$1" = "-m" ]; then echo {mode_3_error!r} >&2; exit 1; fi\nprintf rpu > "$4"', + ) + + +@POSIX_STUBS +def test_a_max_pq_rpu_retries_untouched_without_an_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, debug_entries: Callable[[], list[dict]] +) -> None: + monkeypatch.setattr(config.directories, "temp", tmp_path) + monkeypatch.setattr(binaries, "DoviTool", dovi_stub(tmp_path, "Error: invalid MAX_PQ_LUMINANCE in RPU")) + + Hybrid.__new__(Hybrid).extract_rpu(None, untouched=False) # type: ignore[arg-type] + + assert (tmp_path / "RPU_UNT.bin").read_bytes() == b"rpu" + assert "ERROR" not in levels(debug_entries(), None) + + +@POSIX_STUBS +def test_a_real_rpu_failure_still_logs_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, debug_entries: Callable[[], list[dict]] +) -> None: + monkeypatch.setattr(config.directories, "temp", tmp_path) + monkeypatch.setattr(binaries, "DoviTool", dovi_stub(tmp_path, "Error: Invalid PPS index")) + + with pytest.raises(ValueError, match="corrupt"): + Hybrid.__new__(Hybrid).extract_rpu(None, untouched=False) # type: ignore[arg-type] + + entries = debug_entries() + assert levels(entries) == ["ERROR"] and levels(entries, "hybrid_extract_rpu") == ["ERROR"] + + +@POSIX_STUBS +def test_a_stream_without_hdr10plus_metadata_logs_no_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, debug_entries: Callable[[], list[dict]] +) -> None: + monkeypatch.setattr(config.directories, "temp", tmp_path) + tool = stub(tmp_path, "hdr10plus_tool", 'echo "File doesn\'t contain dynamic metadata, stopping." >&2; exit 1') + monkeypatch.setattr(hybrid_module, "HDR10PlusTool", tool) + hybrid = Hybrid.__new__(Hybrid) + hybrid.hdr10plus_file = "HDR10Plus.json" + + with pytest.raises(hybrid_module.NoHDR10PlusMetadata): + hybrid.extract_hdr10plus(None) # type: ignore[arg-type] + + assert "ERROR" not in levels(debug_entries(), None) + + +@pytest.mark.skipif(not (binaries.CCExtractor and binaries.FFMPEG), reason="needs ccextractor and FFmpeg") +@pytest.mark.parametrize("suffix", ["mp4", "ts"]) +def test_a_video_without_captions_gives_no_cc_track( + tmp_path: Path, debug_entries: Callable[[], list[dict]], suffix: str +) -> None: + clip = tmp_path / f"v.{suffix}" + subprocess.run( + [binaries.FFMPEG, "-v", "error", "-f", "lavfi", "-i", "testsrc=size=320x240:rate=25", "-t", "2"] + + ["-c:v", "mpeg4", clip], + check=True, + ) + video = Video(url="", codec=Video.Codec.AVC, language="en", id_="v") + video.path = clip + + assert video.ccextractor(track_id="cc", out_path=tmp_path / "cc.srt", language="en") is None + assert not (tmp_path / "cc.srt").exists() + assert "ERROR" not in levels(debug_entries()) diff --git a/tests/tracks/test_ccextractor_retry.py b/tests/tracks/test_ccextractor_retry.py index 6e5b1b7f..0c5cf526 100644 --- a/tests/tracks/test_ccextractor_retry.py +++ b/tests/tracks/test_ccextractor_retry.py @@ -13,7 +13,22 @@ from unshackle.core.tracks import Video from unshackle.core.tracks import video as video_module -def test_retry_runs_on_the_repackaged_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: +def no_captions_exit(args: list[Any]) -> subprocess.CompletedProcess: + """ccextractor exits 2 when the input file is missing and 10 when it finds no captions.""" + if not Path(args[-1]).exists(): + raise subprocess.CalledProcessError(2, args) + raise subprocess.CalledProcessError(10, args) + + +def empty_output(args: list[Any]) -> subprocess.CompletedProcess: + Path(args[-2]).write_bytes(b"") + return subprocess.CompletedProcess(args, 0, b"", b"") + + +@pytest.mark.parametrize("ccextractor", [no_captions_exit, empty_output]) +def test_no_captions_retries_on_the_repackaged_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ccextractor: Any +) -> None: original = tmp_path / "v.mp4" original.write_bytes(b"x") repacked = tmp_path / "v_repack.mp4" @@ -27,11 +42,9 @@ def test_retry_runs_on_the_repackaged_file(tmp_path: Path, monkeypatch: pytest.M inputs: list[Path] = [] - def fake_run(args: list[Any], **_: Any) -> None: + def fake_run(args: list[Any], **_: Any) -> subprocess.CompletedProcess: inputs.append(Path(args[-1])) - if not Path(args[-1]).exists(): - raise subprocess.CalledProcessError(2, args) # ccextractor: no input file - raise subprocess.CalledProcessError(10, args) # ccextractor: no captions found + return ccextractor(args) monkeypatch.setattr(video_module.binaries, "CCExtractor", Path("/usr/bin/ccextractor")) monkeypatch.setattr(video_module.subprocess, "run", fake_run) @@ -39,3 +52,4 @@ def test_retry_runs_on_the_repackaged_file(tmp_path: Path, monkeypatch: pytest.M assert track.ccextractor("cc", tmp_path / "cc.srt", Language.get("en")) is None assert inputs == [original, repacked] + assert not (tmp_path / "cc.srt").exists() diff --git a/unshackle/core/tracks/hybrid.py b/unshackle/core/tracks/hybrid.py index 85f2ff50..74692230 100644 --- a/unshackle/core/tracks/hybrid.py +++ b/unshackle/core/tracks/hybrid.py @@ -420,19 +420,32 @@ class Hybrid: dv_stream = config.directories.temp / "DV.hevc" spinner = f"Extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream..." + max_pq = "MAX_PQ_LUMINANCE" try: - dovi.extract_rpu(dv_stream, rpu_path, mode=None if untouched else 3, status=spinner) + dovi.extract_rpu( + dv_stream, + rpu_path, + mode=None if untouched else 3, + status=spinner, + handled=() if untouched else (max_pq,), + ) except RuntimeError as e: stderr_text = str(e) + if not untouched and max_pq in stderr_text: + log_event( + "hybrid_extract_rpu", + level="DEBUG", + message="RPU -m 3 rejects MAX_PQ_LUMINANCE, extracting untouched", + context={"error": stderr_text}, + ) + self.extract_rpu(video, untouched=True) + return log_event( "hybrid_extract_rpu", level="ERROR", message=f"Failed extracting{' untouched ' if untouched else ' '}RPU", context={"untouched": untouched, "error": stderr_text}, ) - if "MAX_PQ_LUMINANCE" in stderr_text: - self.extract_rpu(video, untouched=True) - return if "Invalid PPS index" in stderr_text: raise ValueError("Dolby Vision VideoTrack seems to be corrupt") from None raise ValueError( @@ -846,6 +859,7 @@ class Hybrid: if not HDR10PlusTool: raise ValueError("HDR10Plus_tool not found, HDR10+ to DV conversion needs it") + no_metadata = "dynamic metadata" try: run_step( [ @@ -858,16 +872,17 @@ class Hybrid: status="Extracting HDR10+ metadata...", output=config.directories.temp / self.hdr10plus_file, label="hdr10plus_tool extract", + handled=(no_metadata,), ) except RuntimeError as e: + if no_metadata in str(e): + raise NoHDR10PlusMetadata("No HDR10+ metadata found in the stream") from None log_event( "hybrid_extract_hdr10plus", level="ERROR", message="Failed extracting HDR10+ metadata", context={"error": str(e)}, ) - if "dynamic metadata" in str(e): - raise NoHDR10PlusMetadata("No HDR10+ metadata found in the stream") from None raise ValueError("Failed extracting HDR10+ metadata") from None file_size = os.path.getsize(config.directories.temp / self.hdr10plus_file) diff --git a/unshackle/core/tracks/video.py b/unshackle/core/tracks/video.py index eafa73a8..75e894f2 100644 --- a/unshackle/core/tracks/video.py +++ b/unshackle/core/tracks/video.py @@ -652,7 +652,11 @@ class Video(Track): def ccextractor( self, track_id: Any, out_path: Path | str, language: Language, original: bool = False ) -> Subtitle | None: - """Return a TextTrack object representing CC track extracted by CCExtractor.""" + """Return the CC track that CCExtractor extracts, or None when the video has no captions. + + CCExtractor reports no captions with exit 10. Version 0.93 exits 0 with an empty file when it cannot read + an MP4, so an empty file also counts as no captions. + """ if not self.path: raise ValueError("You must download the track first.") @@ -662,12 +666,15 @@ class Video(Track): out_path = Path(out_path) ccextractor = binaries.CCExtractor + no_captions = 10 + def run_ccextractor(video_path: Path, fallback: str) -> bool: try: run_tool( "ccextractor", [ccextractor, "-trim", "-nobom", "-noru", "-ru1", "-o", out_path, video_path], "ccextractor", + handled=(no_captions,), ) except subprocess.CalledProcessError as e: out_path.unlink(missing_ok=True) @@ -676,9 +683,11 @@ class Video(Track): f"ccextractor crashed (signal {-e.returncode}) on {video_path.name}; {fallback}" ) return out_path.exists() - if e.returncode != 10: # 10 = No captions found + if e.returncode != no_captions: raise return out_path.exists() + if out_path.exists() and not out_path.stat().st_size: + out_path.unlink() return out_path.exists() # Try on the original file first (preserves container-level CC data like c608 boxes), diff --git a/unshackle/core/utils/dovi.py b/unshackle/core/utils/dovi.py index 8290713b..d6580d20 100644 --- a/unshackle/core/utils/dovi.py +++ b/unshackle/core/utils/dovi.py @@ -34,6 +34,7 @@ def extract_rpu( mode: int | None = 3, status: str | None = "Extracting DV RPU...", label: str = "dovi_tool extract-rpu", + handled: tuple[int | str, ...] = (), ) -> bytes: """Extract DV RPU NALs from a raw HEVC bitstream. `mode=None` skips the -m flag (untouched).""" tool = require_dovi_tool() @@ -41,7 +42,7 @@ def extract_rpu( if mode is not None: args += ["-m", str(mode)] args += ["extract-rpu", source, "-o", output] - return run_step(args, status=status, output=output, label=label) + return run_step(args, status=status, output=output, label=label, handled=handled) def inject_rpu( @@ -145,23 +146,8 @@ def generate( ) -def extract_rpu_with_fallback(source: Path, output: Path, *, label: str = "dovi_tool extract-rpu") -> bytes: - """Try `-m 3` first. On a MAX_PQ_LUMINANCE error, retry untouched (no -m). Returns stderr. - - Used when the caller wants automatic normalization but cannot abort if the source - rejects mode-3 conversion. - """ - try: - return extract_rpu(source, output, mode=3, label=label) - except RuntimeError as e: - if "MAX_PQ_LUMINANCE" not in str(e): - raise - return extract_rpu(source, output, mode=None, status="Extracting DV RPU (untouched)...", label=label) - - __all__ = ( "extract_rpu", - "extract_rpu_with_fallback", "inject_rpu", "editor", "info_summary", diff --git a/unshackle/core/utils/subprocess.py b/unshackle/core/utils/subprocess.py index 466052f6..5cae9ed5 100644 --- a/unshackle/core/utils/subprocess.py +++ b/unshackle/core/utils/subprocess.py @@ -17,19 +17,21 @@ def log_tool_run( returncode: int | None, *, duration_ms: float | None = None, + handled: bool = False, **context: object, ) -> None: """Send a structured ``tool_run`` debug-log entry for an external tool invocation. Central helper so every binary call (FFmpeg, mkvpropedit, dovi_tool, and the other - tools) logs the same shape. No-op when debug logging is off. + tools) logs the same shape. A failure logs ERROR, or DEBUG when the caller handles it. + No-op when debug logging is off. """ dl = get_debug_logger() if not dl: return failed = bool(returncode) dl.log( - level="ERROR" if failed else "DEBUG", + level="ERROR" if failed and not handled else "DEBUG", operation="tool_run", message=f"{label} {'failed' if failed else 'ok'}", context={ @@ -84,14 +86,31 @@ class ToolFailed(subprocess.CalledProcessError): return f"{self.tool} failed ({exit_text}){f': {reason}' if reason else ''}; command: {command}" -def run_tool(tool: str, args: Sequence[str | Path], label: str, **context: object) -> subprocess.CompletedProcess: - """Run args with its output captured as bytes, log a tool_run entry under label, and raise ToolFailed on a non-zero exit.""" +def is_handled(returncode: int, stderr: bytes, handled: tuple[int | str, ...]) -> bool: + """True when ``handled`` names the exit code, or a text that stderr contains.""" + return any(h == returncode if isinstance(h, int) else h.encode() in stderr for h in handled) + + +def run_tool( + tool: str, args: Sequence[str | Path], label: str, *, handled: tuple[int | str, ...] = (), **context: object +) -> subprocess.CompletedProcess: + """Run args with its output captured as bytes, log a tool_run entry under label, and raise ToolFailed on a non-zero exit. + + A failure that ``handled`` names (an exit code or a stderr text) still raises, but logs at DEBUG. + """ start = time.monotonic() p = subprocess.run(args, capture_output=True) error = ToolFailed(tool, p.returncode, args, p.stdout, p.stderr) if p.returncode else None if error: context["reason"] = error.reason - log_tool_run(label, tool, p.returncode, duration_ms=round((time.monotonic() - start) * 1000, 1), **context) + log_tool_run( + label, + tool, + p.returncode, + duration_ms=round((time.monotonic() - start) * 1000, 1), + handled=bool(error) and is_handled(p.returncode, p.stderr, handled), + **context, + ) if error: raise error return p @@ -245,12 +264,14 @@ def run_step( output: Path | None = None, label: str = "subprocess step", timeout: float | None = None, + handled: tuple[int | str, ...] = (), ) -> bytes: """Operate a CLI step that writes to `output` (when provided). Returns stderr bytes. Raises RuntimeError with the stderr tail when the process exits non-zero, or when you give `output` and it does not exist or is empty after the step. A timeout also - raises RuntimeError. + raises RuntimeError. A failure that `handled` names (an exit code or a stderr text) + still raises, but logs at DEBUG. """ if output is not None: output.unlink(missing_ok=True) @@ -275,7 +296,7 @@ def run_step( if dl := get_debug_logger(): dl.log( - level="ERROR" if failed else "DEBUG", + level="ERROR" if failed and not is_handled(p.returncode, stderr, handled) else "DEBUG", operation="tool_run", message=f"{label} {'failed' if failed else 'ok'}", context={