forked from kenzuya/unshackle
fix(subprocess): name the tool, exit and reason in external-tool errors
This commit is contained in:
@@ -266,4 +266,4 @@ class CencDrm:
|
||||
|
||||
def decrypt_with_shaka_packager(self, path: Path) -> None:
|
||||
"""Decrypt with shaka-packager."""
|
||||
shaka_decrypt(path, drm_key_args.shaka_keys(self.content_keys, self.own_kids()), self.NAME)
|
||||
shaka_decrypt(path, drm_key_args.shaka_keys(self.content_keys, self.own_kids()))
|
||||
|
||||
@@ -188,7 +188,7 @@ class ClearKeyCENC:
|
||||
keys = ",".join(
|
||||
f"label={i}:key_id={kid.hex}:key={key.lower()}" for i, (kid, key) in enumerate(self.content_keys.items())
|
||||
)
|
||||
shaka_decrypt(path, keys, "ClearKey")
|
||||
shaka_decrypt(path, keys)
|
||||
|
||||
class Exceptions:
|
||||
class KIDNotFound(Exception):
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import logging
|
||||
import shutil
|
||||
import subprocess
|
||||
import textwrap
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from time import monotonic
|
||||
@@ -11,11 +10,9 @@ from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
import click
|
||||
from rich.text import Text
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.console import console
|
||||
from unshackle.core.drm.key_args import shaka_noise
|
||||
from unshackle.core.drm.verify import (
|
||||
decrypter_for,
|
||||
@@ -25,6 +22,7 @@ from unshackle.core.drm.verify import (
|
||||
)
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.utilities import log_event
|
||||
from unshackle.core.utils.subprocess import ToolFailed, run_tool
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -90,17 +88,9 @@ def mp4decrypt(path: Path, key_args_for: Callable[[dict[int, UUID]], list[str]])
|
||||
cmd = [str(binaries.Mp4decrypt), "--show-progress", *key_args, str(path), str(output_path)]
|
||||
|
||||
try:
|
||||
subprocess.run(
|
||||
cmd,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
error_msg = e.stderr if e.stderr else f"mp4decrypt failed with exit code {e.returncode}"
|
||||
raise subprocess.CalledProcessError(e.returncode, cmd, output=e.stdout, stderr=error_msg) from None
|
||||
run_tool("mp4decrypt", cmd, "mp4decrypt")
|
||||
except ToolFailed as e:
|
||||
raise coded(e, APIErrorCode.DRM_ERROR) from None
|
||||
|
||||
if not output_path.exists():
|
||||
raise RuntimeError(f"mp4decrypt failed: output file {output_path} was not created")
|
||||
@@ -111,10 +101,10 @@ def mp4decrypt(path: Path, key_args_for: Callable[[dict[int, UUID]], list[str]])
|
||||
shutil.move(output_path, path)
|
||||
|
||||
|
||||
def shaka_decrypt(path: Path, keys: str, label: str) -> None:
|
||||
def shaka_decrypt(path: Path, keys: str) -> None:
|
||||
"""Decrypt ``path`` in place with shaka-packager and its ``--keys`` value ``keys``.
|
||||
|
||||
Only a non-zero exit is a failure; its non-noise log lines go to the console under ``[label]``.
|
||||
Only a non-zero exit is a failure; its error names the last non-noise log lines.
|
||||
A track that shaka-packager skips because it has no samples leaves ``path`` as it is.
|
||||
"""
|
||||
if not binaries.ShakaPackager:
|
||||
@@ -132,45 +122,38 @@ def shaka_decrypt(path: Path, keys: str, label: str) -> None:
|
||||
config.directories.temp,
|
||||
]
|
||||
|
||||
try:
|
||||
p = subprocess.Popen(
|
||||
[binaries.ShakaPackager, *arguments],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
cmd = [binaries.ShakaPackager, *arguments]
|
||||
p = subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
|
||||
stream_skipped = False
|
||||
shaka_log_buffer = ""
|
||||
assert p.stderr is not None
|
||||
for line in iter(p.stderr.readline, ""):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
if "Skip stream" in line:
|
||||
stream_skipped = True
|
||||
if shaka_noise(line):
|
||||
continue
|
||||
shaka_log_buffer += f"{line}\n"
|
||||
stream_skipped = False
|
||||
shaka_log_buffer = ""
|
||||
assert p.stderr is not None
|
||||
for line in iter(p.stderr.readline, ""):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
if "Skip stream" in line:
|
||||
stream_skipped = True
|
||||
if shaka_noise(line):
|
||||
continue
|
||||
shaka_log_buffer += f"{line}\n"
|
||||
|
||||
p.wait()
|
||||
p.wait()
|
||||
|
||||
if p.returncode != 0:
|
||||
if shaka_log_buffer:
|
||||
shaka_log_buffer = "\n ".join(
|
||||
textwrap.wrap(shaka_log_buffer.rstrip(), width=console.width - 22, initial_indent="")
|
||||
)
|
||||
console.log(Text.from_ansi(f"\n[{label}]: " + shaka_log_buffer))
|
||||
raise subprocess.CalledProcessError(p.returncode, [binaries.ShakaPackager, *arguments])
|
||||
if p.returncode == 0xC000013A: # STATUS_CONTROL_C_EXIT
|
||||
raise KeyboardInterrupt()
|
||||
if p.returncode != 0:
|
||||
raise coded(ToolFailed("shaka-packager", p.returncode, cmd, stderr=shaka_log_buffer), APIErrorCode.DRM_ERROR)
|
||||
|
||||
if stream_skipped:
|
||||
log.warning(f"shaka-packager found no samples in {path.name}, kept the file as it is")
|
||||
output_path.unlink(missing_ok=True)
|
||||
else:
|
||||
output_path.replace(path)
|
||||
except subprocess.CalledProcessError as e:
|
||||
if e.returncode == 0xC000013A: # STATUS_CONTROL_C_EXIT
|
||||
raise KeyboardInterrupt() from None
|
||||
raise
|
||||
if stream_skipped:
|
||||
log.warning(f"shaka-packager found no samples in {path.name}, kept the file as it is")
|
||||
output_path.unlink(missing_ok=True)
|
||||
else:
|
||||
output_path.replace(path)
|
||||
|
||||
@@ -2,8 +2,6 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable, Iterable, Sequence
|
||||
from enum import Enum
|
||||
@@ -27,7 +25,7 @@ from unshackle.core.config import config
|
||||
from unshackle.core.session import AnySession
|
||||
from unshackle.core.tracks.track import Track
|
||||
from unshackle.core.utilities import PYMP4_LOCK, try_ensure_utf8, with_script
|
||||
from unshackle.core.utils.subprocess import log_tool_run
|
||||
from unshackle.core.utils.subprocess import run_tool
|
||||
from unshackle.core.utils.webvtt import merge_segmented_webvtt, rebase_webvtt
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -1202,20 +1200,12 @@ class Subtitle(Track):
|
||||
|
||||
assert self.codec is not None
|
||||
output_format = SUBTITLE_EDIT_FORMATS.get(self.codec, self.codec.name.lower())
|
||||
se_start = time.monotonic()
|
||||
subprocess.run(
|
||||
run_tool(
|
||||
"SubtitleEdit",
|
||||
subtitleedit_args(
|
||||
binaries.SubtitleEdit, self.path, output_format, output_folder=self.path.parent, remove_hi=True
|
||||
),
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
log_tool_run(
|
||||
"SubtitleEdit strip SDH",
|
||||
"SubtitleEdit",
|
||||
0,
|
||||
duration_ms=round((time.monotonic() - se_start) * 1000, 1),
|
||||
format=output_format,
|
||||
)
|
||||
else:
|
||||
@@ -1267,20 +1257,12 @@ class Subtitle(Track):
|
||||
assert self.codec is not None
|
||||
output_format = SUBTITLE_EDIT_FORMATS.get(self.codec, self.codec.name.lower())
|
||||
|
||||
se_start = time.monotonic()
|
||||
subprocess.run(
|
||||
run_tool(
|
||||
"SubtitleEdit",
|
||||
subtitleedit_args(
|
||||
binaries.SubtitleEdit, self.path, output_format, output_folder=self.path.parent, reverse_rtl=True
|
||||
),
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
log_tool_run(
|
||||
"SubtitleEdit reverse RTL",
|
||||
"SubtitleEdit",
|
||||
0,
|
||||
duration_ms=round((time.monotonic() - se_start) * 1000, 1),
|
||||
format=output_format,
|
||||
)
|
||||
|
||||
|
||||
@@ -18,8 +18,6 @@ import html
|
||||
import logging
|
||||
import math
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from collections.abc import Mapping
|
||||
from itertools import pairwise
|
||||
from pathlib import Path
|
||||
@@ -31,7 +29,7 @@ from subby import CommonIssuesFixer, SAMIConverter, WebVTTConverter, WVTTConvert
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.utils.subprocess import log_tool_run
|
||||
from unshackle.core.utils.subprocess import run_tool
|
||||
|
||||
log = logging.getLogger("subtitle")
|
||||
|
||||
@@ -172,16 +170,7 @@ class SubtitleEditBackend:
|
||||
output_folder=out.parent,
|
||||
convert_colors=(target == Codec.SubRip),
|
||||
)
|
||||
se_start = time.monotonic()
|
||||
subprocess.run(args, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
log_tool_run(
|
||||
"SubtitleEdit convert",
|
||||
"SubtitleEdit",
|
||||
0,
|
||||
duration_ms=round((time.monotonic() - se_start) * 1000, 1),
|
||||
source=str(source),
|
||||
target=str(target),
|
||||
)
|
||||
run_tool("SubtitleEdit", args, "SubtitleEdit convert", source=str(source), target=str(target))
|
||||
# SE5 names the output <input-stem>.<format-ext>, which may differ from our target
|
||||
# suffix (e.g. timedtext1.0 -> .ttml). Normalise it onto `out`.
|
||||
if not out.exists():
|
||||
@@ -503,4 +492,4 @@ def run_conversion(sub: Subtitle, target: Codec, *, pin: str | None = None, forc
|
||||
if sorted_src:
|
||||
sorted_src.unlink(missing_ok=True)
|
||||
|
||||
raise RuntimeError(f"All subtitle backends failed for {source.name}->{target.name}") from last_exc
|
||||
raise RuntimeError(f"All subtitle backends failed for {source.name}->{target.name}: {last_exc}") from last_exc
|
||||
|
||||
@@ -44,6 +44,7 @@ from unshackle.core.temp import restore_segments, stash_segments
|
||||
from unshackle.core.tracks import resume
|
||||
from unshackle.core.utilities import language_name, log_event, try_ensure_utf8
|
||||
from unshackle.core.utils import run_proxy
|
||||
from unshackle.core.utils.subprocess import run_tool
|
||||
|
||||
DRM_PREFERENCE_TYPES: dict[str, type[Widevine] | type[PlayReady]] = {
|
||||
"wv": Widevine,
|
||||
@@ -1289,11 +1290,7 @@ class Track:
|
||||
args.extend(["-bsf:v", bsf, "-xerror"])
|
||||
args.append(str(output_path))
|
||||
|
||||
subprocess.run(
|
||||
args,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
run_tool("FFmpeg", args, "ffmpeg repackage")
|
||||
|
||||
log_event(
|
||||
"repackage",
|
||||
|
||||
@@ -19,7 +19,7 @@ from unshackle.core.drm.verify import has_second_view
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.tracks.track import Track
|
||||
from unshackle.core.utilities import FPS, get_boxes, log_event
|
||||
from unshackle.core.utils.subprocess import log_tool_run
|
||||
from unshackle.core.utils.subprocess import log_tool_run, run_tool
|
||||
|
||||
|
||||
class Video(Track):
|
||||
@@ -409,14 +409,14 @@ class Video(Track):
|
||||
original_path = self.path
|
||||
output_path = original_path.with_stem(f"{original_path.stem}_{['limited', 'full'][range_]}_range")
|
||||
|
||||
range_start = time.monotonic()
|
||||
subprocess.run(
|
||||
run_tool(
|
||||
"FFmpeg",
|
||||
[
|
||||
binaries.FFMPEG,
|
||||
"-nostdin",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"panic",
|
||||
"error",
|
||||
"-i",
|
||||
original_path,
|
||||
"-codec",
|
||||
@@ -427,13 +427,7 @@ class Video(Track):
|
||||
f"{filter_key}=video_full_range_flag={range_}",
|
||||
str(output_path),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
log_tool_run(
|
||||
"ffmpeg change range",
|
||||
"ffmpeg",
|
||||
0,
|
||||
duration_ms=round((time.monotonic() - range_start) * 1000, 1),
|
||||
codec=str(self.codec),
|
||||
full_range=bool(range_),
|
||||
)
|
||||
@@ -662,21 +656,14 @@ class Video(Track):
|
||||
ccextractor = binaries.CCExtractor
|
||||
|
||||
def run_ccextractor(video_path: Path, fallback: str) -> bool:
|
||||
cc_start = time.monotonic()
|
||||
try:
|
||||
subprocess.run(
|
||||
run_tool(
|
||||
"ccextractor",
|
||||
[ccextractor, "-trim", "-nobom", "-noru", "-ru1", "-o", out_path, video_path],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
"ccextractor",
|
||||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
out_path.unlink(missing_ok=True)
|
||||
log_tool_run(
|
||||
"ccextractor",
|
||||
"ccextractor",
|
||||
e.returncode,
|
||||
duration_ms=round((time.monotonic() - cc_start) * 1000, 1),
|
||||
)
|
||||
if e.returncode < 0:
|
||||
logging.getLogger("Video").warning(
|
||||
f"ccextractor crashed (signal {-e.returncode}) on {video_path.name}; {fallback}"
|
||||
@@ -685,12 +672,6 @@ class Video(Track):
|
||||
if e.returncode != 10: # 10 = No captions found
|
||||
raise
|
||||
return out_path.exists()
|
||||
log_tool_run(
|
||||
"ccextractor",
|
||||
"ccextractor",
|
||||
0,
|
||||
duration_ms=round((time.monotonic() - cc_start) * 1000, 1),
|
||||
)
|
||||
return out_path.exists()
|
||||
|
||||
# Try on the original file first (preserves container-level CC data like c608 boxes),
|
||||
@@ -786,14 +767,14 @@ class Video(Track):
|
||||
|
||||
original_path = self.path
|
||||
cleaned_path = original_path.with_suffix(f".cleaned{original_path.suffix}")
|
||||
eia_start = time.monotonic()
|
||||
subprocess.run(
|
||||
run_tool(
|
||||
"FFmpeg",
|
||||
[
|
||||
binaries.FFMPEG,
|
||||
"-nostdin",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"panic",
|
||||
"error",
|
||||
"-i",
|
||||
original_path,
|
||||
"-map_metadata",
|
||||
@@ -806,13 +787,7 @@ class Video(Track):
|
||||
"copy",
|
||||
str(cleaned_path),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
log_tool_run(
|
||||
"ffmpeg remove EIA-CC",
|
||||
"ffmpeg",
|
||||
0,
|
||||
duration_ms=round((time.monotonic() - eia_start) * 1000, 1),
|
||||
)
|
||||
|
||||
log.info(" + Removed")
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
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
|
||||
@@ -40,6 +42,61 @@ def log_tool_run(
|
||||
)
|
||||
|
||||
|
||||
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 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."""
|
||||
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)
|
||||
if error:
|
||||
raise error
|
||||
return p
|
||||
|
||||
|
||||
FFMPEG_INCONCLUSIVE = (
|
||||
"not found for",
|
||||
"no decoder found",
|
||||
|
||||
Reference in New Issue
Block a user