mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-03 06:25:10 +00:00
319 lines
12 KiB
Python
319 lines
12 KiB
Python
import json
|
|
import re
|
|
import subprocess
|
|
import time
|
|
from collections.abc import Sequence
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from unshackle.core import binaries
|
|
from unshackle.core.console import console
|
|
from unshackle.core.utilities import get_debug_logger
|
|
|
|
|
|
def log_tool_run(
|
|
label: str,
|
|
tool: str | None,
|
|
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. 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 and not handled else "DEBUG",
|
|
operation="tool_run",
|
|
message=f"{label} {'failed' if failed else 'ok'}",
|
|
context={
|
|
"label": label,
|
|
"tool": tool,
|
|
"returncode": returncode,
|
|
"duration_ms": duration_ms,
|
|
**context,
|
|
},
|
|
)
|
|
|
|
|
|
GLOG_PREFIX = re.compile(r"^(?:\[\d{4}/\d{6}(?:\.\d+)?:[A-Z]+:[^\]]*\]|[IWEF]\d{4} [^\]]*\])\s*")
|
|
REASON_LINES = 3
|
|
REASON_LINE_CHARS = 200
|
|
|
|
|
|
def tool_reason(text: str | bytes | None) -> str:
|
|
"""The last REASON_LINES non-empty lines of a tool's output, glog prefixes removed, as one line.
|
|
|
|
A long line keeps its start and its end, where a tool puts the cause after a long path.
|
|
"""
|
|
if isinstance(text, bytes):
|
|
text = text.decode("utf-8", errors="replace")
|
|
lines = [GLOG_PREFIX.sub("", line.strip()) for line in (text or "").splitlines() if line.strip()]
|
|
half = REASON_LINE_CHARS // 2
|
|
return "; ".join(
|
|
line if len(line) <= REASON_LINE_CHARS else f"{line[:half]} ... {line[-half:]}"
|
|
for line in lines[-REASON_LINES:]
|
|
)
|
|
|
|
|
|
class ToolFailed(subprocess.CalledProcessError):
|
|
"""A non-zero tool exit; its message names the tool, the exit code, the reason (stderr, else stdout) and the command.
|
|
|
|
A negative exit is the POSIX signal that stopped the tool; a Windows NTSTATUS code shows in hex.
|
|
"""
|
|
|
|
def __init__(self, tool: str, returncode: int, cmd: Sequence[Any], output: Any = None, stderr: Any = None) -> None:
|
|
super().__init__(returncode, cmd, output, stderr)
|
|
self.tool = tool
|
|
|
|
@property
|
|
def reason(self) -> str:
|
|
return tool_reason(self.stderr) or tool_reason(self.output)
|
|
|
|
def __str__(self) -> str:
|
|
reason = self.reason
|
|
command = " ".join(str(arg) for arg in self.cmd)
|
|
code = self.returncode
|
|
exit_text = f"signal {-code}" if code < 0 else f"exit {code:#x}" if code > 0xFFFF else f"exit {code}"
|
|
return f"{self.tool} failed ({exit_text}){f': {reason}' if reason else ''}; command: {command}"
|
|
|
|
|
|
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),
|
|
handled=bool(error) and is_handled(p.returncode, p.stderr, handled),
|
|
**context,
|
|
)
|
|
if error:
|
|
raise error
|
|
return p
|
|
|
|
|
|
FFMPEG_INCONCLUSIVE = (
|
|
"not found for",
|
|
"no decoder found",
|
|
"sub-sample encryption info",
|
|
"error reading header",
|
|
"not a decoding option",
|
|
)
|
|
|
|
FFMPEG_MISSING_REFERENCE = (
|
|
"mmco",
|
|
"missing reference",
|
|
"co located pocs unavailable",
|
|
"reference picture missing",
|
|
"could not find ref with poc",
|
|
)
|
|
FFMPEG_CHECK_TIMEOUT = 120
|
|
FFMPEG_CHECK_TAIL = 8 # seconds
|
|
|
|
|
|
def ffmpeg_decodes(path: Path, start: float | None = None, seconds: float = 3, video: bool | None = None) -> bool:
|
|
"""Return True when FFmpeg decodes a window of the file without an error.
|
|
|
|
A wrong content key leaves the container intact and the samples as noise, which the
|
|
decoders reject. ``-xerror`` stops at the first error so the check stays short.
|
|
|
|
With ``start``, the check decodes ``seconds`` from that time. An FFmpeg copy cuts the
|
|
window first, so no sample after the window gets to the decoder. Without ``start``, the
|
|
check decodes the first seconds and the last seconds, because a title can open with
|
|
a clear or separately keyed lead.
|
|
|
|
Every frame is decoded, because an HEVC keyframe decrypted with a wrong key can decode
|
|
without an error. A pass is not proof: HEVC noise can decode clean for seconds, most
|
|
often in small frames, so a longer window finds more wrong keys. When a window starts
|
|
inside a GOP and the only error is a missing reference frame, the check decodes the
|
|
keyframes of that window again and uses that verdict. ``video=False`` skips that second
|
|
pass.
|
|
|
|
A file this FFmpeg build cannot judge counts as a pass, never as a wrong key, and so
|
|
does a check that does not finish in time.
|
|
"""
|
|
if not binaries.FFMPEG:
|
|
raise OSError('FFmpeg executable "ffmpeg" not found but is required.')
|
|
ffmpeg = str(binaries.FFMPEG)
|
|
|
|
def decode(window: list[str], keyframes: bool) -> bool:
|
|
check = [ffmpeg, "-nostdin", "-v", "error", "-err_detect", "explode", "-xerror"]
|
|
if keyframes:
|
|
check += ["-skip_frame:v", "nokey"]
|
|
cut = None
|
|
try:
|
|
if start is None:
|
|
ff = subprocess.run(
|
|
[*check, *window, "-i", str(path), "-f", "null", "-"],
|
|
capture_output=True,
|
|
text=True,
|
|
encoding="utf-8",
|
|
errors="replace",
|
|
timeout=FFMPEG_CHECK_TIMEOUT,
|
|
)
|
|
else:
|
|
# -ignore_editlist: the windows come from tfdt, and an elst would shift FFmpeg's clock off them
|
|
cut = subprocess.Popen(
|
|
[ffmpeg, "-nostdin", "-v", "error", "-ignore_editlist", "1", *window, "-i", str(path)]
|
|
+ ["-map", "0:v?", "-map", "0:a?", "-c", "copy", "-f", "nut", "pipe:1"],
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL,
|
|
)
|
|
ff = subprocess.run(
|
|
[*check, "-i", "pipe:", "-f", "null", "-"],
|
|
stdin=cut.stdout,
|
|
capture_output=True,
|
|
text=True,
|
|
encoding="utf-8",
|
|
errors="replace",
|
|
timeout=FFMPEG_CHECK_TIMEOUT,
|
|
)
|
|
except subprocess.TimeoutExpired:
|
|
return True
|
|
finally:
|
|
if cut:
|
|
if cut.stdout:
|
|
cut.stdout.close()
|
|
cut.kill()
|
|
cut.wait()
|
|
err = ff.stderr.lower()
|
|
if cut and cut.returncode not in (0, -9) and "error opening input" in err:
|
|
return True # the cut failed, so no sample got to the decoder
|
|
if ff.returncode == 0 or any(m in err for m in FFMPEG_INCONCLUSIVE):
|
|
return True
|
|
if not keyframes and video is not False and any(m in err for m in FFMPEG_MISSING_REFERENCE):
|
|
return decode(window, keyframes=True)
|
|
log_tool_run("FFmpeg decode check", ffmpeg, ff.returncode, window=window, stderr=ff.stderr[-2000:])
|
|
return False
|
|
|
|
tail = ["-sseof", f"-{FFMPEG_CHECK_TAIL}", "-t", str(FFMPEG_CHECK_TAIL)]
|
|
if start is not None:
|
|
return decode(["-ss", f"{start:.6f}", "-t", f"{max(seconds - 0.5, seconds / 2):.6f}"], keyframes=False)
|
|
return decode(["-t", str(seconds)], keyframes=False) and decode(tail, keyframes=False)
|
|
|
|
|
|
def ffprobe(uri: bytes | Path) -> dict:
|
|
"""Use FFprobe on the provided data to get its track information (``-show_streams``)."""
|
|
if not binaries.FFProbe:
|
|
raise OSError('FFProbe executable "ffprobe" not found but is required.')
|
|
|
|
args: list[str | Path] = [binaries.FFProbe, "-v", "quiet", "-of", "json", "-show_streams"]
|
|
if isinstance(uri, Path):
|
|
args.extend(
|
|
["-f", "lavfi", "-i", "movie={}[out+subcc]".format(str(uri).replace("\\", "/").replace(":", "\\\\:"))]
|
|
)
|
|
elif isinstance(uri, bytes):
|
|
args.append("pipe:")
|
|
|
|
dl = get_debug_logger()
|
|
start = time.monotonic()
|
|
try:
|
|
ff = subprocess.run(args, input=uri if isinstance(uri, bytes) else None, check=True, capture_output=True)
|
|
except subprocess.CalledProcessError:
|
|
if dl:
|
|
dl.log(
|
|
level="DEBUG",
|
|
operation="tool_run",
|
|
message="ffprobe failed",
|
|
context={"tool": "ffprobe", "duration_ms": round((time.monotonic() - start) * 1000, 1)},
|
|
)
|
|
return {}
|
|
result = json.loads(ff.stdout.decode("utf-8", errors="replace"))
|
|
if dl:
|
|
dl.log(
|
|
level="DEBUG",
|
|
operation="tool_run",
|
|
message=f"ffprobe found {len(result.get('streams', []))} stream(s)",
|
|
context={
|
|
"tool": "ffprobe",
|
|
"streams": len(result.get("streams", [])),
|
|
"duration_ms": round((time.monotonic() - start) * 1000, 1),
|
|
},
|
|
)
|
|
return result
|
|
|
|
|
|
def run_step(
|
|
args: Sequence[str | Path],
|
|
*,
|
|
status: str | None = None,
|
|
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. 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)
|
|
|
|
str_args = [str(a) for a in args]
|
|
start = time.monotonic()
|
|
try:
|
|
if status:
|
|
with console.status(status, spinner="dots"):
|
|
p = subprocess.run(str_args, capture_output=True, timeout=timeout)
|
|
else:
|
|
p = subprocess.run(str_args, capture_output=True, timeout=timeout)
|
|
except subprocess.TimeoutExpired:
|
|
if output is not None:
|
|
output.unlink(missing_ok=True)
|
|
# from None: the TimeoutExpired text holds the whole command line, which can carry a content key
|
|
raise RuntimeError(f"{label} timed out after {timeout}s") from None
|
|
|
|
stderr = p.stderr or b""
|
|
bad_output = output is not None and (not output.exists() or output.stat().st_size == 0)
|
|
failed = bool(p.returncode or bad_output)
|
|
|
|
if dl := get_debug_logger():
|
|
dl.log(
|
|
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={
|
|
"label": label,
|
|
"tool": Path(str_args[0]).name if str_args else None,
|
|
"arg_count": len(str_args),
|
|
"returncode": p.returncode,
|
|
"duration_ms": round((time.monotonic() - start) * 1000, 1),
|
|
"output": str(output) if output else None,
|
|
"output_size": output.stat().st_size if output and output.exists() else 0,
|
|
"bad_output": bad_output,
|
|
},
|
|
)
|
|
|
|
if failed:
|
|
if output is not None:
|
|
output.unlink(missing_ok=True)
|
|
raise RuntimeError(f"{label} failed: {stderr.decode(errors='replace')[-400:]}")
|
|
return stderr
|