forked from kenzuya/unshackle
fix(subprocess): log handled tool failures at debug and drop an empty ccextractor output
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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={
|
||||
|
||||
Reference in New Issue
Block a user