fix(subprocess): name the tool, exit and reason in external-tool errors

This commit is contained in:
imSp4rky
2026-11-28 14:43:29 -07:00
parent 7856d53950
commit 0bd5c4de4f
12 changed files with 305 additions and 165 deletions
+1 -1
View File
@@ -362,4 +362,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"`. 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" !!! tip "Let tool runs log themselves"
For external-tool calls (FFmpeg, mkvmerge, `dovi_tool`, and friends), route through `run_step` / `ffprobe`, which auto-emit a `tool_run` entry capturing the binary's version, return code, and duration consistently. Only fall back to calling `log_tool_run` manually for a direct `subprocess.run` you genuinely cannot route through `run_step`. 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. 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.
+1 -1
View File
@@ -120,7 +120,7 @@ def test_a_missing_decrypter_is_a_drm_error(monkeypatch: pytest.MonkeyPatch) ->
monkeypatch.setattr(binaries, "Mp4decrypt", None) monkeypatch.setattr(binaries, "Mp4decrypt", None)
monkeypatch.setattr(binaries, "ShakaPackager", None) monkeypatch.setattr(binaries, "ShakaPackager", None)
assert code_of(lambda: decrypters.mp4decrypt(Path("x.mp4"), lambda kids: [])) == APIErrorCode.DRM_ERROR assert code_of(lambda: decrypters.mp4decrypt(Path("x.mp4"), lambda kids: [])) == APIErrorCode.DRM_ERROR
assert code_of(lambda: decrypters.shaka_decrypt(Path("x.mp4"), "", "Widevine")) == APIErrorCode.DRM_ERROR assert code_of(lambda: decrypters.shaka_decrypt(Path("x.mp4"), "")) == APIErrorCode.DRM_ERROR
def http_failure(status: Any) -> requests.ConnectionError: def http_failure(status: Any) -> requests.ConnectionError:
+29 -30
View File
@@ -14,6 +14,7 @@ from tests.core.test_kid_windows import A, B, box, clear_audio, encv, moof, movi
from tests.core.test_zero_kid_fallback import _playready, _widevine from tests.core.test_zero_kid_fallback import _playready, _widevine
from tests.test_segment_decrypt import read_argv from tests.test_segment_decrypt import read_argv
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.api.errors import categorize_exception
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.drm import ClearKeyCENC from unshackle.core.drm import ClearKeyCENC
from unshackle.core.drm import decrypters as decrypters_module from unshackle.core.drm import decrypters as decrypters_module
@@ -21,6 +22,7 @@ from unshackle.core.drm.decrypters import mp4decrypt_or_shaka
from unshackle.core.drm.key_args import shaka_noise, track_key_args from unshackle.core.drm.key_args import shaka_noise, track_key_args
from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
from unshackle.core.drm.verify import kidless_track_kids from unshackle.core.drm.verify import kidless_track_kids
from unshackle.core.remote_protocol import APIErrorCode
KEY = "b5df2ae3f63b8dda9049d6e41422e075" KEY = "b5df2ae3f63b8dda9049d6e41422e075"
OTHER_KEY = "11" * 16 OTHER_KEY = "11" * 16
@@ -251,59 +253,55 @@ class FakePackager:
@pytest.fixture @pytest.fixture
def fake_packager(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> list[str]: def fake_packager(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Route shaka-packager to ``FakePackager`` and collect what the console prints.""" """Route shaka-packager to ``FakePackager``."""
printed: list[str] = []
FakePackager.code, FakePackager.log = 0, "" FakePackager.code, FakePackager.log = 0, ""
monkeypatch.setattr(decrypters_module.subprocess, "Popen", FakePackager) monkeypatch.setattr(decrypters_module.subprocess, "Popen", FakePackager)
monkeypatch.setattr(binaries, "ShakaPackager", Path("packager")) monkeypatch.setattr(binaries, "ShakaPackager", Path("packager"))
monkeypatch.setattr(config.directories, "temp", tmp_path) monkeypatch.setattr(config.directories, "temp", tmp_path)
monkeypatch.setattr(decrypters_module.console, "log", lambda text: printed.append(str(text)))
return printed
def shaka_run(tmp_path: Path, make: Callable[[], Any], raises: type[BaseException]) -> None: def shaka_run(tmp_path: Path, make: Callable[[], Any], raises: type[BaseException]) -> BaseException:
"""Decrypt a one-key track of ``make()`` through ``FakePackager`` and expect ``raises``.""" """Decrypt a one-key track of ``make()`` through ``FakePackager`` and return the ``raises`` it raised."""
path = tmp_path / "track.mp4" path = tmp_path / "track.mp4"
path.write_bytes(b"encrypted") path.write_bytes(b"encrypted")
drm = make() drm = make()
drm.content_keys[A] = KEY drm.content_keys[A] = KEY
with pytest.raises(raises): with pytest.raises(raises) as caught:
drm.decrypt_with_shaka_packager(path) drm.decrypt_with_shaka_packager(path)
assert path.read_bytes() == b"encrypted" assert path.read_bytes() == b"encrypted"
return caught.value
@pytest.mark.parametrize("make", DRMS) @pytest.mark.parametrize("make", DRMS)
def test_every_drm_passes_the_fake_clock(tmp_path: Path, fake_packager: list[str], make: Callable[[], Any]) -> None: @pytest.mark.usefixtures("fake_packager")
def test_every_drm_passes_the_fake_clock(tmp_path: Path, make: Callable[[], Any]) -> None:
shaka_run(tmp_path, make, FileNotFoundError) shaka_run(tmp_path, make, FileNotFoundError)
assert "--use_fake_clock_for_muxer" in FakePackager.argv assert "--use_fake_clock_for_muxer" in FakePackager.argv
def test_clearkey_gives_no_zero_kid_fallback(tmp_path: Path, fake_packager: list[str]) -> None: @pytest.mark.usefixtures("fake_packager")
def test_clearkey_gives_no_zero_kid_fallback(tmp_path: Path) -> None:
shaka_run(tmp_path, lambda: ClearKeyCENC(kids=[A]), FileNotFoundError) shaka_run(tmp_path, lambda: ClearKeyCENC(kids=[A]), FileNotFoundError)
assert FakePackager.argv[FakePackager.argv.index("--keys") + 1] == f"label=0:key_id={A.hex}:key={KEY}" assert FakePackager.argv[FakePackager.argv.index("--keys") + 1] == f"label=0:key_id={A.hex}:key={KEY}"
@pytest.mark.parametrize( @pytest.mark.usefixtures("fake_packager")
("make", "label"),
[
pytest.param(lambda: _widevine(A), "Widevine", id="widevine"),
pytest.param(lambda: _playready(A), "PlayReady", id="playready"),
pytest.param(lambda: ClearKeyCENC(kids=[A]), "ClearKey", id="clearkey"),
],
)
def test_a_shaka_failure_logs_under_the_drm_label(
tmp_path: Path, fake_packager: list[str], make: Callable[[], Any], label: str
) -> None:
FakePackager.code, FakePackager.log = 1, "[1103/153702:ERROR:main.cc(1)] Bad key\n"
shaka_run(tmp_path, make, subprocess.CalledProcessError)
assert len(fake_packager) == 1 and f"[{label}]: " in fake_packager[0] and "Bad key" in fake_packager[0]
@pytest.mark.parametrize("make", DRMS) @pytest.mark.parametrize("make", DRMS)
def test_a_skipped_shaka_stream_keeps_the_input( def test_a_shaka_failure_names_the_reason_and_keeps_the_key(tmp_path: Path, make: Callable[[], Any]) -> None:
tmp_path: Path, fake_packager: list[str], make: Callable[[], Any] FakePackager.code = 2
) -> None: FakePackager.log = (
"I1103 15:37:02 demuxer.cc(89)] Demuxer::Run()\n[1103/153702:ERROR:main.cc(1)] Packaging Error: 5\n"
)
error = shaka_run(tmp_path, make, subprocess.CalledProcessError)
assert str(error).startswith("shaka-packager failed (exit 2): Packaging Error: 5; command: ")
assert KEY in str(error) and "Demuxer" not in str(error)
assert categorize_exception(error).error_code == APIErrorCode.DRM_ERROR
@pytest.mark.usefixtures("fake_packager")
@pytest.mark.parametrize("make", DRMS)
def test_a_skipped_shaka_stream_keeps_the_input(tmp_path: Path, make: Callable[[], Any]) -> None:
FakePackager.log = ( FakePackager.log = (
"[1128/120000:INFO:mp4_muxer.cc(1)] Skip stream 'track_decrypted.mp4' which does not contain any sample.\n" "[1128/120000:INFO:mp4_muxer.cc(1)] Skip stream 'track_decrypted.mp4' which does not contain any sample.\n"
) )
@@ -320,7 +318,8 @@ def test_a_skipped_shaka_stream_keeps_the_input(
assert not stray.exists() assert not stray.exists()
def test_a_shaka_ctrl_c_exit_is_a_keyboard_interrupt(tmp_path: Path, fake_packager: list[str]) -> None: @pytest.mark.usefixtures("fake_packager")
def test_a_shaka_ctrl_c_exit_is_a_keyboard_interrupt(tmp_path: Path) -> None:
FakePackager.code = 0xC000013A FakePackager.code = 0xC000013A
shaka_run(tmp_path, lambda: _widevine(A), KeyboardInterrupt) shaka_run(tmp_path, lambda: _widevine(A), KeyboardInterrupt)
+158
View File
@@ -0,0 +1,158 @@
import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
import pytest
from unshackle.core import binaries
from unshackle.core.api.errors import categorize_exception
from unshackle.core.drm import decrypters
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks import Audio, Subtitle
from unshackle.core.tracks.subtitle_convert import SubtitleEditBackend
from unshackle.core.utils import subprocess as subprocess_module
from unshackle.core.utils.subprocess import ToolFailed, run_tool, tool_reason
KEY = "b5df2ae3f63b8dda9049d6e41422e075"
POSIX_STUBS = pytest.mark.skipif(sys.platform == "win32", reason="the tool stubs are shell scripts")
def exits(code: int, stderr: str = "", stdout: str = "") -> list[str]:
"""A Python command that writes ``stdout`` and ``stderr`` and exits with ``code``."""
script = f"import sys; sys.stdout.write({stdout!r}); sys.stderr.write({stderr!r}); sys.exit({code})"
return [sys.executable, "-c", script]
def test_the_reason_is_the_last_lines_without_blank_lines_or_glog_prefixes() -> None:
stderr = b"first\n\nsecond\n[1128/120001:ERROR:packager_main.cc(612)] Packaging Error: 5\n\rlast\n\n"
assert tool_reason(stderr) == "second; Packaging Error: 5; last"
def test_the_short_glog_prefix_is_removed() -> None:
assert tool_reason("E1128 12:00:01.123456 1 packager_main.cc:612] Packaging Error: 5\n") == "Packaging Error: 5"
def test_a_long_reason_line_keeps_its_start_and_its_end() -> None:
line = "Cannot close file " + "x" * 300 + ", possibly running out of disk space."
reason = tool_reason(line)
assert reason.startswith("Cannot close file ") and reason.endswith("running out of disk space.")
assert len(reason) == 205
@pytest.mark.parametrize("empty", [None, "", b"", "\n \n"])
def test_no_output_gives_no_reason(empty: str | bytes | None) -> None:
assert tool_reason(empty) == ""
def test_the_message_names_tool_exit_reason_and_command() -> None:
error = ToolFailed("FFmpeg", 1, ["ffmpeg", Path("in.mp4")], stderr=b"No space left on device\n")
assert str(error) == "FFmpeg failed (exit 1): No space left on device; command: ffmpeg in.mp4"
def test_stdout_is_the_reason_when_stderr_is_empty() -> None:
error = ToolFailed("SubtitleEdit", 1, ["se"], output="Errors:\nAccess denied\n", stderr="")
assert str(error) == "SubtitleEdit failed (exit 1): Errors:; Access denied; command: se"
@pytest.mark.parametrize(
("code", "text"),
[(5, "exit 5"), (-9, "signal 9"), (0xC0000005, "exit 0xc0000005")],
)
def test_a_failure_with_no_output_names_only_the_exit(code: int, text: str) -> None:
assert str(ToolFailed("ccextractor", code, ["cc"])) == f"ccextractor failed ({text}); command: cc"
def test_run_tool_raises_a_called_process_error_with_the_reason() -> None:
with pytest.raises(subprocess.CalledProcessError) as caught:
run_tool("tool", exits(2, stderr="Failed to write file out.mp4"), "tool step")
assert isinstance(caught.value, ToolFailed)
assert caught.value.returncode == 2 and caught.value.stderr == b"Failed to write file out.mp4"
assert str(caught.value).startswith("tool failed (exit 2): Failed to write file out.mp4; command: ")
def test_run_tool_returns_the_completed_process_on_exit_0() -> None:
p = run_tool("tool", exits(0, stdout="done"), "tool step")
assert p.returncode == 0 and p.stdout == b"done"
def test_a_failed_run_logs_the_reason_without_the_command(monkeypatch: pytest.MonkeyPatch) -> None:
logged: list[dict] = []
monkeypatch.setattr(
subprocess_module, "get_debug_logger", lambda: SimpleNamespace(log=lambda **kw: logged.append(kw))
)
with pytest.raises(ToolFailed):
run_tool("tool", [*exits(3, stderr="disk full\n"), KEY], "tool step")
assert len(logged) == 1 and logged[0]["level"] == "ERROR"
assert logged[0]["context"]["returncode"] == 3 and logged[0]["context"]["reason"] == "disk full"
assert KEY not in str(logged[0])
def stub(tmp_path: Path, name: str, script: str) -> Path:
"""A shell script ``name`` in ``tmp_path`` that runs ``script``."""
path = tmp_path / name
path.write_text(f"#!/bin/sh\n{script}\n")
path.chmod(0o755)
return path
@POSIX_STUBS
def test_a_repackage_failure_names_the_ffmpeg_reason(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(binaries, "FFMPEG", stub(tmp_path, "ffmpeg", "echo 'No space left on device' >&2; exit 1"))
track = Audio("http://example.test/a.mp4", "en", codec=Audio.Codec.AAC)
track.path = tmp_path / "a.mp4"
track.path.write_bytes(b"audio")
with pytest.raises(subprocess.CalledProcessError, match=r"^FFmpeg failed \(exit 1\): No space left on device; "):
track.repackage()
@POSIX_STUBS
def test_a_malformed_aac_repackage_retries_with_the_adts_filter(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
script = (
'case "$*" in *aac_adtstoasc*) for last; do :; done; echo ok > "$last"; exit 0;; esac\n'
"echo 'Malformed AAC bitstream detected' >&2; exit 1"
)
monkeypatch.setattr(binaries, "FFMPEG", stub(tmp_path, "ffmpeg", script))
track = Audio("http://example.test/a.mp4", "en", codec=Audio.Codec.AAC)
track.path = tmp_path / "a.mp4"
track.path.write_bytes(b"audio")
track.repackage()
assert track.path == tmp_path / "a_repack.mp4" and track.path.read_text() == "ok\n"
@POSIX_STUBS
def test_a_subtitleedit_failure_names_the_reason_it_wrote_to_stdout(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(binaries, "SubtitleEdit", stub(tmp_path, "SubtitleEdit", "echo 'Access is denied'; exit 1"))
src = tmp_path / "s.srt"
src.write_text("1\n00:00:01,000 --> 00:00:02,000\nhi\n")
with pytest.raises(subprocess.CalledProcessError, match=r"^SubtitleEdit failed \(exit 1\): Access is denied; "):
SubtitleEditBackend().convert(Subtitle.Codec.SubRip, src, Subtitle.Codec.WebVTT, tmp_path / "s.vtt")
@POSIX_STUBS
def test_an_mp4decrypt_failure_names_the_reason_and_keeps_the_key(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(
binaries,
"Mp4decrypt",
stub(tmp_path, "mp4decrypt", "echo 'ERROR: cannot open output file (out.mp4) -5' >&2; exit 1"),
)
path = tmp_path / "track.mp4"
path.write_bytes(b"encrypted")
with pytest.raises(subprocess.CalledProcessError) as caught:
decrypters.mp4decrypt(path, lambda kids: ["--key", f"1:{KEY}"])
message = str(caught.value)
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
+1 -1
View File
@@ -266,4 +266,4 @@ class CencDrm:
def decrypt_with_shaka_packager(self, path: Path) -> None: def decrypt_with_shaka_packager(self, path: Path) -> None:
"""Decrypt with shaka-packager.""" """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()))
+1 -1
View File
@@ -188,7 +188,7 @@ class ClearKeyCENC:
keys = ",".join( keys = ",".join(
f"label={i}:key_id={kid.hex}:key={key.lower()}" for i, (kid, key) in enumerate(self.content_keys.items()) 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 Exceptions:
class KIDNotFound(Exception): class KIDNotFound(Exception):
+37 -54
View File
@@ -3,7 +3,6 @@
import logging import logging
import shutil import shutil
import subprocess import subprocess
import textwrap
from collections.abc import Callable from collections.abc import Callable
from pathlib import Path from pathlib import Path
from time import monotonic from time import monotonic
@@ -11,11 +10,9 @@ from typing import Any
from uuid import UUID from uuid import UUID
import click import click
from rich.text import Text
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.config import config 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.key_args import shaka_noise
from unshackle.core.drm.verify import ( from unshackle.core.drm.verify import (
decrypter_for, decrypter_for,
@@ -25,6 +22,7 @@ from unshackle.core.drm.verify import (
) )
from unshackle.core.remote_protocol import APIErrorCode, coded from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.utilities import log_event from unshackle.core.utilities import log_event
from unshackle.core.utils.subprocess import ToolFailed, run_tool
log = logging.getLogger(__name__) 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)] cmd = [str(binaries.Mp4decrypt), "--show-progress", *key_args, str(path), str(output_path)]
try: try:
subprocess.run( run_tool("mp4decrypt", cmd, "mp4decrypt")
cmd, except ToolFailed as e:
check=True, raise coded(e, APIErrorCode.DRM_ERROR) from None
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
if not output_path.exists(): if not output_path.exists():
raise RuntimeError(f"mp4decrypt failed: output file {output_path} was not created") 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) 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``. """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. A track that shaka-packager skips because it has no samples leaves ``path`` as it is.
""" """
if not binaries.ShakaPackager: if not binaries.ShakaPackager:
@@ -132,45 +122,38 @@ def shaka_decrypt(path: Path, keys: str, label: str) -> None:
config.directories.temp, config.directories.temp,
] ]
try: cmd = [binaries.ShakaPackager, *arguments]
p = subprocess.Popen( p = subprocess.Popen(
[binaries.ShakaPackager, *arguments], cmd,
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, text=True,
encoding="utf-8", encoding="utf-8",
errors="replace", errors="replace",
) )
stream_skipped = False stream_skipped = False
shaka_log_buffer = "" shaka_log_buffer = ""
assert p.stderr is not None assert p.stderr is not None
for line in iter(p.stderr.readline, ""): for line in iter(p.stderr.readline, ""):
line = line.strip() line = line.strip()
if not line: if not line:
continue continue
if "Skip stream" in line: if "Skip stream" in line:
stream_skipped = True stream_skipped = True
if shaka_noise(line): if shaka_noise(line):
continue continue
shaka_log_buffer += f"{line}\n" shaka_log_buffer += f"{line}\n"
p.wait() p.wait()
if p.returncode != 0: if p.returncode == 0xC000013A: # STATUS_CONTROL_C_EXIT
if shaka_log_buffer: raise KeyboardInterrupt()
shaka_log_buffer = "\n ".join( if p.returncode != 0:
textwrap.wrap(shaka_log_buffer.rstrip(), width=console.width - 22, initial_indent="") raise coded(ToolFailed("shaka-packager", p.returncode, cmd, stderr=shaka_log_buffer), APIErrorCode.DRM_ERROR)
)
console.log(Text.from_ansi(f"\n[{label}]: " + shaka_log_buffer))
raise subprocess.CalledProcessError(p.returncode, [binaries.ShakaPackager, *arguments])
if stream_skipped: if stream_skipped:
log.warning(f"shaka-packager found no samples in {path.name}, kept the file as it is") log.warning(f"shaka-packager found no samples in {path.name}, kept the file as it is")
output_path.unlink(missing_ok=True) output_path.unlink(missing_ok=True)
else: else:
output_path.replace(path) output_path.replace(path)
except subprocess.CalledProcessError as e:
if e.returncode == 0xC000013A: # STATUS_CONTROL_C_EXIT
raise KeyboardInterrupt() from None
raise
+5 -23
View File
@@ -2,8 +2,6 @@ from __future__ import annotations
import logging import logging
import re import re
import subprocess
import time
from collections import defaultdict from collections import defaultdict
from collections.abc import Callable, Iterable, Sequence from collections.abc import Callable, Iterable, Sequence
from enum import Enum from enum import Enum
@@ -27,7 +25,7 @@ from unshackle.core.config import config
from unshackle.core.session import AnySession from unshackle.core.session import AnySession
from unshackle.core.tracks.track import Track from unshackle.core.tracks.track import Track
from unshackle.core.utilities import PYMP4_LOCK, try_ensure_utf8, with_script 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 from unshackle.core.utils.webvtt import merge_segmented_webvtt, rebase_webvtt
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -1202,20 +1200,12 @@ class Subtitle(Track):
assert self.codec is not None assert self.codec is not None
output_format = SUBTITLE_EDIT_FORMATS.get(self.codec, self.codec.name.lower()) output_format = SUBTITLE_EDIT_FORMATS.get(self.codec, self.codec.name.lower())
se_start = time.monotonic() run_tool(
subprocess.run( "SubtitleEdit",
subtitleedit_args( subtitleedit_args(
binaries.SubtitleEdit, self.path, output_format, output_folder=self.path.parent, remove_hi=True 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 strip SDH",
"SubtitleEdit",
0,
duration_ms=round((time.monotonic() - se_start) * 1000, 1),
format=output_format, format=output_format,
) )
else: else:
@@ -1267,20 +1257,12 @@ class Subtitle(Track):
assert self.codec is not None assert self.codec is not None
output_format = SUBTITLE_EDIT_FORMATS.get(self.codec, self.codec.name.lower()) output_format = SUBTITLE_EDIT_FORMATS.get(self.codec, self.codec.name.lower())
se_start = time.monotonic() run_tool(
subprocess.run( "SubtitleEdit",
subtitleedit_args( subtitleedit_args(
binaries.SubtitleEdit, self.path, output_format, output_folder=self.path.parent, reverse_rtl=True 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 reverse RTL",
"SubtitleEdit",
0,
duration_ms=round((time.monotonic() - se_start) * 1000, 1),
format=output_format, format=output_format,
) )
+3 -14
View File
@@ -18,8 +18,6 @@ import html
import logging import logging
import math import math
import re import re
import subprocess
import time
from collections.abc import Mapping from collections.abc import Mapping
from itertools import pairwise from itertools import pairwise
from pathlib import Path from pathlib import Path
@@ -31,7 +29,7 @@ from subby import CommonIssuesFixer, SAMIConverter, WebVTTConverter, WVTTConvert
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.tracks.subtitle import Subtitle 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") log = logging.getLogger("subtitle")
@@ -172,16 +170,7 @@ class SubtitleEditBackend:
output_folder=out.parent, output_folder=out.parent,
convert_colors=(target == Codec.SubRip), convert_colors=(target == Codec.SubRip),
) )
se_start = time.monotonic() run_tool("SubtitleEdit", args, "SubtitleEdit convert", source=str(source), target=str(target))
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),
)
# SE5 names the output <input-stem>.<format-ext>, which may differ from our 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`. # suffix (e.g. timedtext1.0 -> .ttml). Normalise it onto `out`.
if not out.exists(): if not out.exists():
@@ -503,4 +492,4 @@ def run_conversion(sub: Subtitle, target: Codec, *, pin: str | None = None, forc
if sorted_src: if sorted_src:
sorted_src.unlink(missing_ok=True) 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
+2 -5
View File
@@ -44,6 +44,7 @@ from unshackle.core.temp import restore_segments, stash_segments
from unshackle.core.tracks import resume from unshackle.core.tracks import resume
from unshackle.core.utilities import language_name, log_event, try_ensure_utf8 from unshackle.core.utilities import language_name, log_event, try_ensure_utf8
from unshackle.core.utils import run_proxy from unshackle.core.utils import run_proxy
from unshackle.core.utils.subprocess import run_tool
DRM_PREFERENCE_TYPES: dict[str, type[Widevine] | type[PlayReady]] = { DRM_PREFERENCE_TYPES: dict[str, type[Widevine] | type[PlayReady]] = {
"wv": Widevine, "wv": Widevine,
@@ -1289,11 +1290,7 @@ class Track:
args.extend(["-bsf:v", bsf, "-xerror"]) args.extend(["-bsf:v", bsf, "-xerror"])
args.append(str(output_path)) args.append(str(output_path))
subprocess.run( run_tool("FFmpeg", args, "ffmpeg repackage")
args,
check=True,
capture_output=True,
)
log_event( log_event(
"repackage", "repackage",
+10 -35
View File
@@ -19,7 +19,7 @@ from unshackle.core.drm.verify import has_second_view
from unshackle.core.tracks.subtitle import Subtitle from unshackle.core.tracks.subtitle import Subtitle
from unshackle.core.tracks.track import Track from unshackle.core.tracks.track import Track
from unshackle.core.utilities import FPS, get_boxes, log_event 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): class Video(Track):
@@ -409,14 +409,14 @@ class Video(Track):
original_path = self.path original_path = self.path
output_path = original_path.with_stem(f"{original_path.stem}_{['limited', 'full'][range_]}_range") output_path = original_path.with_stem(f"{original_path.stem}_{['limited', 'full'][range_]}_range")
range_start = time.monotonic() run_tool(
subprocess.run( "FFmpeg",
[ [
binaries.FFMPEG, binaries.FFMPEG,
"-nostdin", "-nostdin",
"-hide_banner", "-hide_banner",
"-loglevel", "-loglevel",
"panic", "error",
"-i", "-i",
original_path, original_path,
"-codec", "-codec",
@@ -427,13 +427,7 @@ class Video(Track):
f"{filter_key}=video_full_range_flag={range_}", f"{filter_key}=video_full_range_flag={range_}",
str(output_path), str(output_path),
], ],
check=True,
)
log_tool_run(
"ffmpeg change range", "ffmpeg change range",
"ffmpeg",
0,
duration_ms=round((time.monotonic() - range_start) * 1000, 1),
codec=str(self.codec), codec=str(self.codec),
full_range=bool(range_), full_range=bool(range_),
) )
@@ -662,21 +656,14 @@ class Video(Track):
ccextractor = binaries.CCExtractor ccextractor = binaries.CCExtractor
def run_ccextractor(video_path: Path, fallback: str) -> bool: def run_ccextractor(video_path: Path, fallback: str) -> bool:
cc_start = time.monotonic()
try: try:
subprocess.run( run_tool(
"ccextractor",
[ccextractor, "-trim", "-nobom", "-noru", "-ru1", "-o", out_path, video_path], [ccextractor, "-trim", "-nobom", "-noru", "-ru1", "-o", out_path, video_path],
check=True, "ccextractor",
capture_output=True,
) )
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
out_path.unlink(missing_ok=True) 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: if e.returncode < 0:
logging.getLogger("Video").warning( logging.getLogger("Video").warning(
f"ccextractor crashed (signal {-e.returncode}) on {video_path.name}; {fallback}" 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 if e.returncode != 10: # 10 = No captions found
raise raise
return out_path.exists() return out_path.exists()
log_tool_run(
"ccextractor",
"ccextractor",
0,
duration_ms=round((time.monotonic() - cc_start) * 1000, 1),
)
return out_path.exists() return out_path.exists()
# Try on the original file first (preserves container-level CC data like c608 boxes), # 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 original_path = self.path
cleaned_path = original_path.with_suffix(f".cleaned{original_path.suffix}") cleaned_path = original_path.with_suffix(f".cleaned{original_path.suffix}")
eia_start = time.monotonic() run_tool(
subprocess.run( "FFmpeg",
[ [
binaries.FFMPEG, binaries.FFMPEG,
"-nostdin", "-nostdin",
"-hide_banner", "-hide_banner",
"-loglevel", "-loglevel",
"panic", "error",
"-i", "-i",
original_path, original_path,
"-map_metadata", "-map_metadata",
@@ -806,13 +787,7 @@ class Video(Track):
"copy", "copy",
str(cleaned_path), str(cleaned_path),
], ],
check=True,
)
log_tool_run(
"ffmpeg remove EIA-CC", "ffmpeg remove EIA-CC",
"ffmpeg",
0,
duration_ms=round((time.monotonic() - eia_start) * 1000, 1),
) )
log.info(" + Removed") log.info(" + Removed")
+57
View File
@@ -1,8 +1,10 @@
import json import json
import re
import subprocess import subprocess
import time import time
from collections.abc import Sequence from collections.abc import Sequence
from pathlib import Path from pathlib import Path
from typing import Any
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.console import console 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 = ( FFMPEG_INCONCLUSIVE = (
"not found for", "not found for",
"no decoder found", "no decoder found",