fix(dl): stop a failed mux with one line that names the free space

This commit is contained in:
imSp4rky
2026-11-28 15:26:38 -07:00
parent 418d69b1ec
commit 74856d2ddb
7 changed files with 145 additions and 38 deletions
+27 -22
View File
@@ -2543,29 +2543,34 @@ class dl:
self.completed_files.append(final_path)
self.log.debug(f"Saved: {final_path.name}")
elif isinstance(title, (Movie, Episode)):
outputs, mux_sidecars = mux_title(
title,
placement,
log=self.log,
service_tag=self.service,
split_audio=split_audio,
merge_video=merge_video,
audio_expected=not video_only and not no_audio,
skip_subtitles=bool(skip_subtitle_mux),
quality=quality,
range_=range_,
vcodec=vcodec,
generate_dv=generate_dv,
progress_sink=progress_sink,
write_sidecars=partial(
self.output_subtitle_sidecars,
sidecar_subtitles,
sidecar_format=sidecar_format,
original_paths=sidecar_original_paths or None,
try:
outputs, mux_sidecars = mux_title(
title,
placement,
log=self.log,
service_tag=self.service,
split_audio=split_audio,
merge_video=merge_video,
audio_expected=not video_only and not no_audio,
skip_subtitles=bool(skip_subtitle_mux),
quality=quality,
range_=range_,
vcodec=vcodec,
generate_dv=generate_dv,
progress_sink=progress_sink,
write_sidecars=partial(
self.output_subtitle_sidecars,
sidecar_subtitles,
sidecar_format=sidecar_format,
original_paths=sidecar_original_paths or None,
)
if sidecar_subtitles
else None,
)
if sidecar_subtitles
else None,
)
except RunStopped as stopped:
stopped.reason += low_free_space(stopped)
self.log.error(stopped.reason)
raise
sidecar_files.update(mux_sidecars)
for temp_path in sidecar_original_paths.values():
temp_path.unlink(missing_ok=True)
+7 -2
View File
@@ -1361,8 +1361,8 @@ def mp_worker(queue: Any, kwargs: dict[str, Any]) -> None:
"""Child entry point (top-level so ``spawn`` can pickle it).
Rebuilds the HTTP session, iterates ``requests()`` for its url slice, and relays every event
over the shared queue. Errors travel as a ``__mp_error__`` sentinel. This child always sends a
``__mp_done__`` sentinel last, so the parent knows that this child is complete.
over the shared queue. Errors travel as a ``__mp_error__`` sentinel with the notes and API error code of the
error. This child always sends a ``__mp_done__`` sentinel last, so the parent knows that this child is complete.
"""
try:
# spawn re-imports this module, dropping any timing constants the bench patched in
@@ -1387,6 +1387,9 @@ def mp_worker(queue: Any, kwargs: dict[str, Any]) -> None:
"__mp_error__": " ".join(f"{type(exc).__name__}: {exc}".split()),
"__mp_traceback__": traceback.format_exc(),
"__mp_notes__": [str(note) for note in getattr(exc, "__notes__", ())],
"__mp_error_code__": code
if isinstance(code := getattr(exc, "error_code", None), APIErrorCode)
else None,
}
)
finally:
@@ -1508,6 +1511,8 @@ def download_multiprocess(
child_error = RuntimeError(f"segment download child failed: {event['__mp_error__']}")
for note in event.get("__mp_notes__", ()):
child_error.add_note(note)
if code := event.get("__mp_error_code__"):
coded(child_error, code)
raise child_error
if "total" in event:
continue
+17 -11
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import logging
import shutil
import sys
from collections.abc import Callable, Sequence
from concurrent import futures
from concurrent.futures import ThreadPoolExecutor
@@ -21,6 +20,7 @@ from rich.progress import Progress, SpinnerColumn, TaskID, TextColumn, TimeRemai
from unshackle.core.config import config
from unshackle.core.console import GradientPulseBarColumn, SyncLive, console
from unshackle.core.placement import Placement
from unshackle.core.run_plan import RunStopped
from unshackle.core.titles import Movie
from unshackle.core.titles.episode import Episode
from unshackle.core.tracks import Audio, Tracks, Video
@@ -28,6 +28,7 @@ from unshackle.core.tracks.dv_fixup import apply_dv_fixup
from unshackle.core.tracks.hybrid import Hybrid
from unshackle.core.tracks.selection import select_hybrid_bases
from unshackle.core.utilities import standard_resolution
from unshackle.core.utils.subprocess import tool_reason
MuxOutput = tuple[Path, Audio.Codec | None]
@@ -113,7 +114,7 @@ def mux_title(
"""Mux the tracks of a title, then delete them; the muxed files and the sidecar files of each.
Each output is a muxed file with the audio codec it holds when the audio is split by codec.
A failed mux exits the run.
A failed mux stops the run with RunStopped, whose reason names the muxer, its exit and its error.
"""
outputs: list[MuxOutput] = []
sidecars: dict[Path | None, list[Path]] = {}
@@ -232,7 +233,6 @@ def mux_title(
try:
with SyncLive(Padding(progress, (0, 5, 1, 5)), console=console, refresh_per_second=20):
mux_failed = False
mux_concurrency = max(1, int(config.muxing.get("concurrency", 4)))
with (
@@ -310,23 +310,29 @@ def mux_title(
mux_video_group(group)
mux_results = [f.result() for f in mux_futures]
failure: str | None = None
for (_, _, audio_codec), (muxed_path, return_code, errors) in zip(
multiplex_tasks, mux_results, strict=True
):
outputs.append((muxed_path, audio_codec))
if return_code >= 2:
log.error(f"Failed to Mux video to Matroska file ({return_code}):")
elif return_code == 1 or errors:
failed = return_code >= 2 or return_code < 0
error_lines = [e for e in errors if not e.startswith("#GUI#warning")]
if failed and not failure:
tool = "MP4Box" if muxed_path.suffix == ".mp4" else "mkvmerge"
exit_text = f"signal {-return_code}" if return_code < 0 else f"exit {return_code}"
reason = tool_reason("\n".join(e.removeprefix("#GUI#error") for e in error_lines))
failure = f"{tool} failed ({exit_text}){f': {reason}' if reason else ''}"
elif not failed and (return_code == 1 or errors):
log.warning("mkvmerge had at least one warning or error, continuing anyway...")
for line in errors:
if line.startswith("#GUI#error"):
if failed and line in error_lines:
log.debug(line)
elif line.startswith("#GUI#error"):
log.error(line)
else:
log.warning(line)
if return_code >= 2:
mux_failed = True
if mux_failed:
sys.exit(1)
if failure:
raise RunStopped(failure)
if write_sidecars:
sidecar_targets: list[tuple[Path | None, str, Path]] = []
+1 -1
View File
@@ -28,7 +28,7 @@ class PlanError(click.ClickException):
class RunStopped(SystemExit):
"""A run that a missing track or language stopped, with the reason dl logged."""
"""A run that a missing track or language or a failed mux stopped, with the reason dl logged."""
def __init__(self, reason: str) -> None:
super().__init__(1)