fix(dl): keep a second file with the same name by moving output placement and the mux step into their own modules

This commit is contained in:
imSp4rky
2026-11-25 15:42:06 -07:00
parent fba28198d0
commit e4ba7c2908
14 changed files with 720 additions and 534 deletions
+2 -1
View File
@@ -6,7 +6,8 @@ from typing import Any
from pymediainfo import MediaInfo
from tests.core.test_hdr10plus_probe import ts
from unshackle.commands.dl import no_mux_extension, take_unmuxable_audio, track_file_suffix
from unshackle.commands.dl import take_unmuxable_audio
from unshackle.core.placement import no_mux_extension, track_file_suffix
from unshackle.core.tracks import Audio, Tracks, Video
+1 -1
View File
@@ -9,7 +9,7 @@ from typing import Any
import pytest
from unshackle.commands.dl import hybrid_source_tracks
from unshackle.core.mux_step import hybrid_source_tracks
from unshackle.core.tracks import Video
from unshackle.core.tracks import dv_fixup as dv_fixup_mod
from unshackle.core.tracks.dv_fixup import apply_dv_fixup
+6 -10
View File
@@ -18,16 +18,12 @@ import pytest
import unshackle.commands.dl as dl_module
from tests.remote.unit.test_remote_service_helpers import _sent_create_data
from unshackle.commands.dl import (
generated_dv_ranges,
hybrid_plan,
hybrid_source_tracks,
hybrid_step_error,
missing_hybrid_error,
)
from unshackle.commands.dl import generated_dv_ranges
from unshackle.core import mux_step
from unshackle.core.api import download_manager, handlers
from unshackle.core.api.handlers import validate_download_parameters
from unshackle.core.config import config
from unshackle.core.mux_step import hybrid_plan, hybrid_source_tracks, hybrid_step_error, missing_hybrid_error
from unshackle.core.service import Service, TrackRequest
from unshackle.core.services import Services
from unshackle.core.tracks import Audio, Chapter, Subtitle, Tracks, Video
@@ -702,20 +698,20 @@ def test_a_hybrid_failure_is_reported_so_the_title_goes_on(monkeypatch: pytest.M
def failed_hybrid(*args: Any, **kwargs: Any) -> None:
raise error
monkeypatch.setattr(dl_module, "Hybrid", failed_hybrid)
monkeypatch.setattr(mux_step, "Hybrid", failed_hybrid)
assert hybrid_step_error([], "TEST", "HDR10-DV-2160p.hevc") == str(error)
def test_a_working_hybrid_reports_no_error_and_an_exit_passes_through(monkeypatch: pytest.MonkeyPatch) -> None:
seen: dict[str, Any] = {}
monkeypatch.setattr(dl_module, "Hybrid", lambda tracks, source, output_name: seen.update(name=output_name))
monkeypatch.setattr(mux_step, "Hybrid", lambda tracks, source, output_name: seen.update(name=output_name))
assert hybrid_step_error([], "TEST", "HDR10-DV-2160p.hevc") is None and seen == {"name": "HDR10-DV-2160p.hevc"}
def exiting(*args: Any, **kwargs: Any) -> None:
raise SystemExit(1)
monkeypatch.setattr(dl_module, "Hybrid", exiting)
monkeypatch.setattr(mux_step, "Hybrid", exiting)
with pytest.raises(SystemExit):
hybrid_step_error([], "TEST", "HDR10-DV-2160p.hevc")
+139
View File
@@ -0,0 +1,139 @@
"""The placement of a title's output files: folder, name, and one rule for a name taken twice."""
from __future__ import annotations
from pathlib import Path
from typing import Any, Iterator
import pytest
from pymediainfo import MediaInfo
from tests.lang_selection.test_kind_only_selection import FakeService, run, stub_hybrid
from unshackle.core.config import config
from unshackle.core.placement import Placement
from unshackle.core.titles import Movie
from unshackle.core.titles.episode import Episode
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
AAC_MP4 = """<?xml version="1.0" encoding="UTF-8"?>
<Mediainfo><File>
<track type="General"><Format>MPEG-4</Format></track>
<track type="Audio"><Format>AAC</Format><Channel_s_>2</Channel_s_></track>
</File></Mediainfo>"""
@pytest.fixture(autouse=True)
def templates() -> Iterator[None]:
"""Pin the naming templates, because the suite shares the live global config."""
saved = (config.output_template, config.folder_templates, config.folder_template)
config.output_template = {"movies": "{title}.{year}", "series": "{title}.{season_episode}"}
config.folder_templates = {}
config.folder_template = ""
yield
config.output_template, config.folder_templates, config.folder_template = saved
def movie() -> Movie:
return Movie(id_="movie1", service=type("EXAMPLE", (), {}), name="Some Movie", year=2026)
def placement(root: Path, title: object = None, *, sample: bool = False, no_folder: bool = False) -> Placement:
return Placement(title or movie(), root=root, no_folder=no_folder, no_source=False, sample=sample)
def audio(path: Path, track_id: str, *, descriptive: bool = False) -> Audio:
track = Audio(
id_=track_id,
url=f"https://x.example/{track_id}.mp4",
language="en",
codec=Audio.Codec.AAC,
descriptive=descriptive,
)
track.path = path
return track
def test_two_same_language_aac_tracks_get_two_paths_without_mux(tmp_path: Path) -> None:
place = placement(tmp_path / "out")
folder = place.folder(MediaInfo(AAC_MP4))
main = audio(tmp_path / "Audio_a1.mp4", "a1")
described = audio(tmp_path / "Audio_a2.mp4", "a2", descriptive=True)
paths = [place.track_file(folder, t, MediaInfo(AAC_MP4)) for t in (main, described)]
assert [p.name for p in paths] == ["Some.Movie.2026.en.AAC.m4a", "Some.Movie.2026.en.AAC.2.m4a"]
def test_two_kept_tracks_beside_one_output_get_two_paths(tmp_path: Path) -> None:
place = placement(tmp_path)
output = place.claim(tmp_path, "Some.Movie.2026", ".mkv")
kept = [audio(tmp_path / f"Audio_{n}.mp4", n) for n in ("a1", "a2")]
names = [place.track_file(tmp_path, t, MediaInfo(AAC_MP4), stem=output.stem).name for t in kept]
assert names == ["Some.Movie.2026.en.AAC.m4a", "Some.Movie.2026.en.AAC.2.m4a"]
def test_names_that_do_not_collide_keep_their_form(tmp_path: Path) -> None:
place = placement(tmp_path)
video = Video(id_="v", url="https://x.example/v", codec=Video.Codec.HEVC, language="en")
video.path = tmp_path / "v.mp4"
subtitle = Subtitle(id_="s", url="https://x.example/s", codec=Subtitle.Codec.WebVTT, language="en", sdh=True)
subtitle.path = tmp_path / "s.vtt"
tracks = [video, audio(tmp_path / "a.mp4", "a"), subtitle]
names = [place.track_file(tmp_path, t, MediaInfo(AAC_MP4)).name for t in tracks]
assert names == ["Some.Movie.2026.HEVC.mp4", "Some.Movie.2026.en.AAC.m4a", "Some.Movie.2026.en.sdh.vtt"]
def test_a_split_audio_mux_adds_the_codec_to_a_name_on_disk(tmp_path: Path) -> None:
place = placement(tmp_path)
first = place.claim(tmp_path, "Some.Movie.2026", ".mkv", Audio.Codec.AAC)
first.touch()
second = place.claim(tmp_path, "Some.Movie.2026", ".mkv", Audio.Codec.EC3)
assert [first.name, second.name] == ["Some.Movie.2026.mkv", "Some.Movie.2026.EC3.mkv"]
def test_a_path_taken_twice_gets_a_counter(tmp_path: Path) -> None:
place = placement(tmp_path)
names = [place.claim(tmp_path, "Some.Movie.2026", ".mkv").name for _ in range(3)]
assert names == ["Some.Movie.2026.mkv", "Some.Movie.2026.2.mkv", "Some.Movie.2026.3.mkv"]
def test_a_file_from_an_earlier_run_is_replaced_when_no_codec_tells_them_apart(tmp_path: Path) -> None:
(tmp_path / "Some.Movie.2026.mkv").touch()
assert placement(tmp_path).claim(tmp_path, "Some.Movie.2026", ".mkv").name == "Some.Movie.2026.mkv"
def test_folder_and_sample(tmp_path: Path) -> None:
episode = Episode(
id_="episode1", service=type("EXAMPLE", (), {}), title="Some Show", season=1, number=2, name="Pilot", year=2026
)
info = MediaInfo(AAC_MP4)
assert placement(tmp_path).folder(info) == tmp_path
assert placement(tmp_path, sample=True).folder(info) == tmp_path / "Sample"
assert placement(tmp_path, episode, no_folder=True).folder(info) == tmp_path
assert placement(tmp_path, episode).folder(None) == tmp_path
assert placement(tmp_path, episode).folder(info).parent == tmp_path
assert placement(tmp_path, sample=True).name(info) == "Some.Movie.2026.SAMPLE"
class DownloadedAudio(FakeService):
"""Each audio track comes with a file, as if the download had run."""
def __init__(self, folder: Path) -> None:
super().__init__({1: {"ad": True}})
self.folder = folder
def get_tracks(self, title: Episode) -> Tracks:
tracks = super().get_tracks(title)
for track in tracks.audio:
track.path = self.folder / f"Audio_{track.id}.mp4"
track.path.write_bytes(track.id.encode())
return tracks
def test_a_no_mux_run_keeps_both_same_language_aac_tracks(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
out = tmp_path / "out"
monkeypatch.setattr(config.directories, "downloads", out)
stub_hybrid(monkeypatch)
flags: dict[str, Any] = {"no_mux": True, "audio_description": True, "no_folder": True}
assert run(monkeypatch, caplog, {}, service=DownloadedAudio(tmp_path), to_end=True, **flags) is None
assert sorted(p.read_bytes() for p in out.iterdir()) == [b"a", b"ad"]
+2 -1
View File
@@ -11,11 +11,12 @@ from typing import Any
import pytest
from langcodes import Language
from unshackle.commands.dl import dl, hybrid_plan
from unshackle.commands.dl import dl
from unshackle.core import binaries
from unshackle.core.config import config
from unshackle.core.drm.verify import decrypter_for
from unshackle.core.manifests import DASH, HLS
from unshackle.core.mux_step import hybrid_plan
from unshackle.core.titles.movie import Movie
from unshackle.core.tracks import Audio, Chapter, Chapters, Track, Tracks, Video
from unshackle.core.tracks import tracks as tracks_module
@@ -333,7 +333,7 @@ def test_a_failed_hybrid_muxes_the_ranges_it_falls_back_to(
raise Muxed()
stub_hybrid(monkeypatch)
monkeypatch.setattr("unshackle.commands.dl.hybrid_plan", hybrid_step)
monkeypatch.setattr("unshackle.core.mux_step.hybrid_plan", hybrid_step)
monkeypatch.setattr(Tracks, "mux", mux)
ranges = [Video.Range.HYBRID, Video.Range.SDR]
with pytest.raises(Muxed):
@@ -8,7 +8,7 @@ import pytest
from langcodes import Language
from tests.lang_selection import test_kind_only_selection as harness
from unshackle.commands.dl import hybrid_plan
from unshackle.core.mux_step import hybrid_plan
from unshackle.core.titles import Episode
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
@@ -368,7 +368,7 @@ def test_a_standalone_range_beside_hybrid_does_not_add_a_hybrid_base(
def stop_at_plan(videos: list[Video], generate_dv: bool) -> None:
raise Planned(videos, generate_dv)
monkeypatch.setattr("unshackle.commands.dl.hybrid_plan", stop_at_plan)
monkeypatch.setattr("unshackle.core.mux_step.hybrid_plan", stop_at_plan)
monkeypatch.setattr(Video, "normalize_vui", lambda self: None)
with pytest.raises(Planned) as planned:
run_hdr(monkeypatch, caplog, videos, ["HYBRID", "HDR10"], to_end=True, video_only=True)
+2 -2
View File
@@ -1,6 +1,6 @@
"""Tests for ``--merge-video`` track grouping.
``group_videos_by_variant`` (``unshackle/commands/dl.py``) decides which selected video
``group_videos_by_variant`` (``unshackle/core/mux_step.py``) decides which selected video
tracks share one MKV when merge mode is on. The rule: group by ``(resolution, range,
codec)`` so only language varies within a file; resolutions, ranges and codecs stay
separate. With ``merge=False`` every track is its own group (one file per track).
@@ -10,7 +10,7 @@ These lock the pure grouping unit; the surrounding mux loop is Click-command orc
from __future__ import annotations
from unshackle.commands.dl import group_videos_by_variant
from unshackle.core.mux_step import group_videos_by_variant
from unshackle.core.tracks import Video
+2 -1
View File
@@ -20,8 +20,9 @@ from pymediainfo import MediaInfo
from tests.core.test_music_container import fragmented_mp4, header_length
from tests.core.test_music_tagger_roundtrip import make_song
from unshackle.commands.dl import mux_skipped, no_mux_extension, remux_music_tracks
from unshackle.commands.dl import mux_skipped, remux_music_tracks
from unshackle.core.config import config
from unshackle.core.placement import no_mux_extension
from unshackle.core.titles.movie import Movie
from unshackle.core.tracks import Audio, Tracks, Video
from unshackle.core.utils import tags
+1 -1
View File
@@ -15,10 +15,10 @@ import click
import pytest
from requests import Session
from unshackle.commands.dl import sample_name
from unshackle.core.api.handlers import validate_download_parameters
from unshackle.core.config import config
from unshackle.core.manifests.dash import DASH
from unshackle.core.placement import sample_name
from unshackle.core.services import Services
from unshackle.core.titles import Episode, Movie
from unshackle.core.tracks import Audio, Chapter, Subtitle, Tracks, Video