refactor(dl): move track selection into core/tracks/selection.py

This commit is contained in:
imSp4rky
2026-11-24 13:48:50 -07:00
parent e7c95f03e9
commit b7018c9b27
9 changed files with 1014 additions and 744 deletions
+2 -1
View File
@@ -9,10 +9,11 @@ from typing import Any
import pytest
from unshackle.commands.dl import hybrid_source_tracks, select_hybrid_bases
from unshackle.commands.dl 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
from unshackle.core.tracks.selection import select_hybrid_bases
pytestmark = pytest.mark.unit
+1 -3
View File
@@ -20,13 +20,10 @@ 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_gate_failure,
hybrid_plan,
hybrid_source_tracks,
hybrid_step_error,
keep_generated_dv_bases,
missing_hybrid_error,
select_hybrid_bases,
)
from unshackle.core.api import download_manager, handlers
from unshackle.core.api.handlers import validate_download_parameters
@@ -44,6 +41,7 @@ from unshackle.core.tracks.hybrid import (
nits_to_pq,
pq_to_nits,
)
from unshackle.core.tracks.selection import hybrid_gate_failure, keep_generated_dv_bases, select_hybrid_bases
pytestmark = pytest.mark.unit
+14 -23
View File
@@ -1,15 +1,16 @@
"""The kind-only flags: --audio-description-only and --forced-subs-only.
The filters in dl.result are not extractable without executing the whole download loop, so
their wiring is pinned against the source, the same way test_required_langs_gate does it.
Their filters are tested through TrackSelection in test_track_selection.
"""
from __future__ import annotations
import inspect
from types import SimpleNamespace
from typing import Any
import pytest
from tests.lang_selection import test_kind_only_selection as harness
from unshackle.commands.dl import dl
from unshackle.core.api.handlers import validate_download_parameters
from unshackle.core.utilities import kind_only_conflict
@@ -68,23 +69,13 @@ def test_api_rejects_a_non_boolean_flag(key):
assert validate_download_parameters({**BASE, key: None}) is None
class TestFilterWiring:
source = inspect.getsource(dl.result)
def test_ado_runs_when_the_title_has_no_separate_audio(self):
# embedded audio is standard audio: the filter must sit before the `len(...) > 0` guard
ado = self.source.index("if keep_audio and audio_description_only:")
guard = self.source.index("if keep_audio and len(title.tracks.audio) > 0:")
assert ado < guard
def test_ado_does_not_count_embedded_audio(self):
# both the --require-audio gate and the missing-language check
assert self.source.count("keep_videos and not audio_description_only") == 2
def test_only_filters_keep_one_kind(self):
assert "title.tracks.select_audio(lambda x: x.descriptive)" in self.source
assert "title.tracks.select_subtitles(lambda x: x.forced)" in self.source
def test_fso_implies_forced_subs(self):
# services read forced_subs from the ctx params to fetch forced tracks at all
assert "if forced_s_lang or fsl_excl or forced_subs_only:" in self.source
@pytest.mark.parametrize("flags", [{"forced_subs_only": True}, {"forced_s_lang": ["en"]}, {"forced_s_lang": ["-en"]}])
def test_a_forced_flag_turns_forced_subs_on_for_the_service(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, flags: dict[str, Any]
) -> None:
# services read forced_subs from the ctx params to fetch forced tracks at all
service = harness.FakeService({1: {"forced": True}})
params = {"forced_subs": False}
service.ctx = SimpleNamespace(parent=SimpleNamespace(params=params)) # type: ignore[attr-defined]
harness.run(monkeypatch, caplog, {}, service=service, **flags)
assert params["forced_subs"] is True
@@ -1,8 +1,9 @@
"""Run the kind-only filters through the real dl.result() selection loop.
"""Run track selection through the real dl.result() loop, for what the run does with a skip.
A fake service hands in-memory tracks to the loop, and the run stops at the first
title that reaches ``Tracks.tree``, the step right after selection. A title with no
track of the kind never gets there, so what the hook records is what the run kept.
title that reaches ``Tracks.tree``, the step right after selection. What a selection keeps
is tested through TrackSelection in test_track_selection; these tests cover the run:
when a skip stops it, what it reports, and how it settles the post-script groups.
"""
from __future__ import annotations
@@ -136,29 +137,6 @@ def run(
return None
def test_ado_keeps_the_descriptive_track_and_the_other_types(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, audio_description_only=True)
assert ids == {"video": ["v"], "audio": ["ad"], "subs": ["s"]}
def test_fso_keeps_the_forced_track_and_the_other_types(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, forced_subs_only=True)
assert ids == {"video": ["v"], "audio": ["a"], "subs": ["sf"]}
def test_only_flags_with_their_type_flags_give_a_single_kind(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, audio_description_only=True, audio_only=True)
assert ids == {"video": [], "audio": ["ad"], "subs": []}
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, forced_subs_only=True, subs_only=True)
assert ids == {"video": [], "audio": [], "subs": ["sf"]}
@pytest.mark.parametrize("flag", ["audio_description_only", "forced_subs_only"])
def test_a_single_title_with_no_such_track_exits(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, flag: str
@@ -218,20 +196,6 @@ def test_skip_missing_skips_the_title_and_reports_it(
assert {"skipped_titles": [{"title": "Show S01E01", "reason": "Required audio language(s) not found: ko"}]} in sink
def test_require_audio_video_and_subs_work_together(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {}}, require_audio=["en"], require_video=["en"], require_subs=["en"])
assert ids == {"video": ["v"], "audio": ["a"], "subs": ["s"]}
assert run(monkeypatch, caplog, {1: {}}, require_audio=["ko"], require_video=["ko"], require_subs=["ko"]) == 1
assert (
"Required audio language(s) not found: ko; Required video language(s) not found: ko; "
"Required subtitle language(s) not found: ko"
) in caplog.text
assert run(monkeypatch, caplog, {1: {}}, require_audio=["en"], require_video=["ko"], require_subs=["en"]) == 1
assert "Show S01E01: Required video language(s) not found: ko" in caplog.text
def test_skip_missing_skips_a_filter_miss_and_continues(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
@@ -336,19 +300,42 @@ def test_a_skipped_title_settles_its_post_script_group(
assert seen.count("Show S01E01") == settled
class LcevcService(FakeService):
"""A 540p base video and the 1080p LCEVC enhancement layer that decodes on top of it."""
class CaptionlessService(FakeService):
"""A service that finds out in get_tracks that the title has no subtitles, and turns them off."""
def get_tracks(self, title: Episode) -> Tracks:
tracks = super().get_tracks(title)
tracks.videos[0].height = 540
tracks.add(Video(id_="lcevc", url="https://x/l", language="en", codec=Video.Codec.LCEVC, height=1080))
tracks.subtitles = []
self.NO_SUBTITLES = True
return tracks
def test_an_lcevc_layer_is_left_out_unless_asked_for(
def test_no_subtitles_set_in_get_tracks_turns_the_subtitle_requirement_off(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
assert run(monkeypatch, caplog, {1: {}}, service=LcevcService({1: {}}))["video"] == ["v"]
asked = run(monkeypatch, caplog, {1: {}}, service=LcevcService({1: {}}), vcodec=[Video.Codec.LCEVC])
assert asked["video"] == ["lcevc"]
ids = run(monkeypatch, caplog, {1: {}}, service=CaptionlessService({1: {}}), require_subs=["en"])
assert ids == {"video": ["v"], "audio": ["a"], "subs": []}
class Muxed(BaseException):
"""Stops the run at the first mux."""
def test_a_failed_hybrid_muxes_the_ranges_it_falls_back_to(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
"""The mux step must see the fallback ranges, or it runs the hybrid step on an SDR title."""
def hybrid_step(*args: Any, **kwargs: Any) -> None:
raise AssertionError("the hybrid step ran for a title that fell back to SDR")
def mux(*args: Any, **kwargs: Any) -> None:
raise Muxed()
stub_hybrid(monkeypatch)
monkeypatch.setattr("unshackle.commands.dl.hybrid_plan", hybrid_step)
monkeypatch.setattr(Tracks, "mux", mux)
ranges = [Video.Range.HYBRID, Video.Range.SDR]
with pytest.raises(Muxed):
run(monkeypatch, caplog, {1: {}}, to_end=True, video_only=True, range_=ranges, best_available=True)
assert "continuing with SDR" in caplog.text
@@ -139,19 +139,6 @@ def test_require_subs_no_longer_conflicts_with_s_lang():
)
def test_all_three_require_flags_share_one_gate():
import inspect as _inspect
from unshackle.commands import dl as dl_module
source = _inspect.getsource(dl_module.dl.result)
# the sub gate must not short-circuit the s_lang branch any more
assert "downloading all available subtitles" not in source
for kind in ("audio", "video", "subtitle"):
assert f'"{kind}",' in source
assert "missing_required_langs(required, available, title.language, exact=exact_lang)" in source
def test_exact_lang_turns_off_the_bare_tag_fallback():
assert missing_required_langs(["en"], ["en-GB"]) == []
assert missing_required_langs(["en"], ["en-GB"], exact=True) == ["en"]
@@ -1,18 +1,20 @@
"""The dl.result call site of missing_required_langs, and inputs the unit tests skip.
"""The required-language gate of the track selection, and inputs the unit tests skip.
The gate in dl.result is not extractable without executing the whole download loop, so
its wiring is pinned the same way test_required_langs pins download_manager: against the
source. The value inputs cover what the helper's own tests leave out — real tracks carry
The gate runs in TrackSelection.select, so its tests cross that interface with real tracks.
The value inputs cover what the helper's own tests leave out: real tracks carry
langcodes.Language objects, not strings.
"""
from __future__ import annotations
import inspect
from typing import Any
import pytest
from langcodes import Language
from unshackle.commands.dl import dl
from tests.lang_selection import test_kind_only_selection as harness
from tests.lang_selection.test_track_selection import audio, episode, selection, standard, video
from unshackle.core.tracks.selection import Kept, Skip
from unshackle.core.utilities import missing_required_langs
@@ -37,37 +39,76 @@ def test_requirement_checks_the_catalogue_not_the_selection():
assert missing_required_langs(["fr"], ["en", "ko", "ja", "fr"]) == []
class TestGateWiring:
"""Pin the dl.result gate's shape; a silent rewire is otherwise invisible to tests."""
def test_the_gate_is_disabled_with_the_track_kind() -> None:
# --no-audio / -V must not fail on a requirement the download cannot honour
assert isinstance(selection(require_audio=["ko"], no_audio=True).select(standard(), False), Kept)
assert isinstance(selection(require_video=["ko"], audio_only=True).select(standard(), False), Kept)
source = inspect.getsource(dl.result)
def test_gate_is_disabled_with_the_track_kind(self):
# --no-audio / -V must not fail on a require_audio the download cannot honour
assert "require_audio if keep_audio else []" in self.source
assert "require_video if keep_videos else []" in self.source
def test_the_gate_counts_audio_embedded_in_a_kept_video() -> None:
def title() -> Any:
return episode(video(data={"audio_language": "ko"}), audio())
def test_gate_counts_audio_embedded_in_kept_video(self):
assert "embedded_audio_langs(title.tracks.videos, keep_videos and not audio_description_only)" in self.source
assert isinstance(selection(require_audio=["ko"]).select(title(), False), Kept)
missing = Skip("Required audio language(s) not found: ko")
assert selection(require_audio=["ko"], audio_only=True).select(title(), False) == missing
def test_gate_honours_exact_lang(self):
assert "missing_required_langs(required, available, title.language, exact=exact_lang)" in self.source
def test_gate_reads_tracks_before_the_keep_flags_empty_them(self):
# the availability lists must be built before `if not keep_videos:` clears
# title.tracks.videos, or embedded audio could never satisfy a requirement
gate = self.source.index("missing_required_langs(required")
reset = self.source.index("if not keep_videos:")
assert gate < reset
def test_ado_does_not_count_audio_embedded_in_the_video_at_the_gate() -> None:
title = episode(video(data={"audio_language": "ko"}), audio("ad", bitrate=1, descriptive=True))
sel = selection(require_audio=["ko"], audio_description=True, audio_description_only=True)
assert sel.select(title, False) == Skip("Required audio language(s) not found: ko")
def test_require_and_exclude_clash_is_rejected_per_flag(self):
# --require-audio en with -l all,-en can never be satisfied as the user
# meant it, so it must die at parse time, against each flag's own
# exclusion list (-vl/-al cascade from -l only when unset)
assert "cannot be required and excluded at the same time" in self.source
for pair in (
'("--require-audio", require_audio, audio_excl)',
'("--require-video", require_video, video_excl)',
'("--require-subs", require_subs, s_lang_excl)',
):
assert pair in self.source
def test_a_run_with_every_required_language_present_keeps_the_title() -> None:
sel = selection(require_audio=["en"], require_video=["en"], require_subs=["en"])
assert isinstance(sel.select(standard(), False), Kept)
def test_the_gate_honours_exact_lang() -> None:
def title() -> Any:
return episode(video(), audio(language="en-GB"))
assert isinstance(selection(require_audio=["en"]).select(title(), False), Kept)
missing = Skip("Required audio language(s) not found: en")
assert selection(require_audio=["en"], exact_lang=True).select(title(), False) == missing
def test_the_gate_reads_the_tracks_before_any_filter() -> None:
title = episode(video(), audio("en", "en", bitrate=1), audio("ko", "ko", bitrate=1))
outcome = selection(a_lang=["en"], require_audio=["ko"]).select(title, False)
assert isinstance(outcome, Kept)
assert [a.id for a in outcome.tracks.audio] == ["en"]
def test_every_kind_misses_in_one_reason() -> None:
sel = selection(require_audio=["ko"], require_video=["ko"], require_subs=["ko"])
assert sel.select(standard(), False) == Skip(
"Required audio language(s) not found: ko; Required video language(s) not found: ko; "
"Required subtitle language(s) not found: ko"
)
@pytest.mark.parametrize(
("flags", "clash"),
[
({"require_audio": ["en"], "lang": ["all", "-en"]}, "--require-audio: en"),
({"require_video": ["en"], "v_lang": ["all", "-en"]}, "--require-video: en"),
({"require_subs": ["en"], "s_lang": ["all", "-en"]}, "--require-subs: en"),
({"require_audio": ["-en"]}, "--require-audio: en"),
],
)
def test_a_required_and_excluded_language_stops_the_run(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, flags: dict[str, Any], clash: str
) -> None:
assert harness.run(monkeypatch, caplog, {1: {}}, **flags) == 1
assert f"{clash} cannot be required and excluded at the same time." in caplog.text
def test_a_language_override_does_not_inherit_the_lang_exclusions(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
# -al and -vl name languages, so they replace -l and its -en
flags: dict[str, Any] = {"require_audio": ["en"], "a_lang": ["en"], "v_lang": ["all"], "lang": ["all", "-en"]}
ids = harness.run(monkeypatch, caplog, {1: {}}, **flags)
assert ids["audio"] == ["a"]
@@ -0,0 +1,159 @@
"""Track selection through its interface: real tracks in, the kept tracks or the skip reason out."""
from __future__ import annotations
import logging
from dataclasses import fields
from typing import Any
import pytest
from unshackle.core.titles import Episode
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.tracks.selection import Kept, Skip, TrackSelection
def selection(**flags: Any) -> TrackSelection:
"""A TrackSelection with every filter off but the given flags."""
off: dict[str, Any] = {}
for flag in fields(TrackSelection):
off[flag.name] = [] if str(flag.type).startswith("list") else None if "Optional" in str(flag.type) else False
return TrackSelection(**{**off, **flags})
class EXAMPLE:
"""The service class an Episode names."""
def video(id_: str = "v", language: str = "en", **kwargs: Any) -> Video:
kwargs.setdefault("codec", Video.Codec.AVC)
kwargs.setdefault("range_", Video.Range.SDR)
return Video(id_=id_, url=f"https://cdn.example/{id_}", language=language, **kwargs)
def audio(id_: str = "a", language: str = "en", **kwargs: Any) -> Audio:
return Audio(id_=id_, url=f"https://cdn.example/{id_}", language=language, codec=Audio.Codec.AAC, **kwargs)
def subtitle(id_: str = "s", language: str = "en", **kwargs: Any) -> Subtitle:
return Subtitle(id_=id_, url=f"https://cdn.example/{id_}", language=language, codec=Subtitle.Codec.WebVTT, **kwargs)
def episode(*tracks: Any, language: str = "en") -> Episode:
title = Episode(id_="show-s01-e001", service=EXAMPLE, title="Show", season=1, number=1, language=language)
title.tracks = Tracks(list(tracks))
return title
def standard(**extra: bool) -> Episode:
"""One video, one audio and one subtitle in English; ad adds a descriptive track, forced a forced subtitle."""
tracks: list[Any] = [video(), audio(bitrate=128_000)]
if extra.get("ad"):
tracks.append(audio("ad", bitrate=1, descriptive=True))
tracks.append(subtitle())
if extra.get("forced"):
tracks.append(subtitle("sf", forced=True))
return episode(*tracks)
def kept(outcome: Kept | Skip) -> dict[str, list[str]]:
assert isinstance(outcome, Kept), outcome
return {
"video": [t.id for t in outcome.tracks.videos],
"audio": [t.id for t in outcome.tracks.audio],
"subs": [t.id for t in outcome.tracks.subtitles],
}
def test_the_defaults_keep_every_track() -> None:
assert kept(selection().select(standard(), False)) == {"video": ["v"], "audio": ["a"], "subs": ["s"]}
def test_ado_keeps_the_descriptive_track_and_the_other_types() -> None:
sel = selection(audio_description=True, audio_description_only=True)
assert kept(sel.select(standard(ad=True, forced=True), False)) == {"video": ["v"], "audio": ["ad"], "subs": ["s"]}
def test_fso_keeps_the_forced_track_and_the_other_types() -> None:
sel = selection(forced_subs=True, forced_subs_only=True)
assert kept(sel.select(standard(ad=True, forced=True), False)) == {"video": ["v"], "audio": ["a"], "subs": ["sf"]}
def test_only_flags_with_their_type_flags_give_a_single_kind() -> None:
sel = selection(audio_description=True, audio_description_only=True, audio_only=True)
assert kept(sel.select(standard(ad=True, forced=True), False)) == {"video": [], "audio": ["ad"], "subs": []}
sel = selection(forced_subs=True, forced_subs_only=True, subs_only=True)
assert kept(sel.select(standard(ad=True, forced=True), False)) == {"video": [], "audio": [], "subs": ["sf"]}
@pytest.mark.parametrize(
("flags", "reason"),
[
({"audio_description": True, "audio_description_only": True}, "There's no audio description track."),
(
{"forced_subs": True, "forced_subs_only": True},
"There's no forced subtitle track for the selected languages.",
),
({"subs_only": True, "s_lang": ["fr"]}, "There's no track left for the selected options."),
],
)
def test_a_kind_only_miss_is_a_kind_only_skip(flags: dict[str, Any], reason: str) -> None:
assert selection(**flags).select(standard(), False) == Skip(reason, kind_only=True)
def test_ado_runs_when_the_title_has_no_separate_audio() -> None:
title = episode(video(data={"audio_language": "en"}))
sel = selection(audio_description=True, audio_description_only=True)
assert sel.select(title, False) == Skip("There's no audio description track.", kind_only=True)
def test_ado_does_not_count_audio_embedded_in_the_video() -> None:
def title() -> Episode:
return episode(video(data={"audio_language": "ko"}), audio("ad", bitrate=1, descriptive=True))
assert kept(selection(audio_description=True, a_lang=["ko"]).select(title(), False))["video"] == ["v"]
sel = selection(audio_description=True, audio_description_only=True, a_lang=["ko"])
assert sel.select(title(), False) == Skip("ko not found in audio description tracks")
def test_a_missing_audio_language_skips_unless_best_available(caplog: pytest.LogCaptureFixture) -> None:
def title() -> Episode:
return episode(video(), audio("ja", "ja", bitrate=1), audio("en", "en", bitrate=1), language="ja")
assert selection(a_lang=["orig", "ko", "en"]).select(title(), False) == Skip("ko not found in audio tracks")
with caplog.at_level(logging.WARNING):
outcome = selection(a_lang=["orig", "ko", "en"], best_available=True).select(title(), False)
assert kept(outcome)["audio"] == ["ja", "en"]
assert "ko not found in audio tracks, continuing with: orig, en" in caplog.text
def test_an_lcevc_layer_is_left_out_unless_asked_for() -> None:
def title() -> Episode:
return episode(video(height=540), video("lcevc", codec=Video.Codec.LCEVC, height=1080), audio())
assert kept(selection().select(title(), False))["video"] == ["v"]
assert kept(selection(vcodec=[Video.Codec.LCEVC]).select(title(), False))["video"] == ["lcevc"]
def test_a_failed_hybrid_falls_back_to_the_other_ranges_only_with_best_available() -> None:
ranges = [Video.Range.HYBRID, Video.Range.SDR]
failure = "HYBRID needs HDR10/HDR10+ and DV tracks, available ranges: SDR"
assert selection(range_=ranges).select(standard(), False) == Skip(failure)
outcome = selection(range_=ranges, best_available=True).select(standard(), False)
assert isinstance(outcome, Kept)
assert outcome.ranges == [Video.Range.SDR]
assert kept(outcome)["video"] == ["v"]
def test_the_selection_can_run_on_every_title_of_a_run() -> None:
sel = selection(no_subs=True, range_=[Video.Range.HYBRID, Video.Range.SDR], best_available=True)
for _ in range(2):
outcome = sel.select(standard(), False)
assert isinstance(outcome, Kept)
assert outcome.ranges == [Video.Range.SDR]
assert kept(outcome)["subs"] == []
assert sel.range_ == [Video.Range.HYBRID, Video.Range.SDR]
def test_a_service_without_subtitles_drops_them_and_their_requirement() -> None:
assert kept(selection(require_subs=["ko"]).select(standard(), True)) == {"video": ["v"], "audio": ["a"], "subs": []}
+49 -622
View File
@@ -2,7 +2,6 @@ from __future__ import annotations
import html
import logging
import math
import os
import random
import re
@@ -103,6 +102,7 @@ from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.tracks.attachment import Attachment
from unshackle.core.tracks.dv_fixup import apply_dv_fixup
from unshackle.core.tracks.hybrid import Hybrid
from unshackle.core.tracks.selection import HYBRID_BASE_RANGES, Skip, TrackSelection, select_hybrid_bases
from unshackle.core.tracks.subtitle_convert import PYCAPTION_WRITERS, SUBSTATION, build_ass_style
from unshackle.core.tracks.track import (
Track,
@@ -110,25 +110,17 @@ from unshackle.core.tracks.track import (
fix_data_reference_indexes,
has_encrypted_sample_entry,
)
from unshackle.core.tracks.tracks import at_resolution, select_videos
from unshackle.core.utilities import (
apply_original_language,
as_requested,
declared_kwargs,
embedded_audio_langs,
find_font_with_fallbacks,
find_missing_langs,
get_debug_logger,
get_system_fonts,
init_debug_logger,
kind_only_conflict,
log_event,
matched_language_tags,
matching_languages,
missing_required_langs,
orig_token,
partition_exclusions,
plain_subtitle_tags,
resolve_sort_langs,
standard_resolution,
suggest_font_packages,
@@ -253,9 +245,6 @@ def group_videos_by_variant(videos: list[Video], *, merge: bool) -> list[list[Vi
return list(groups.values())
HYBRID_BASE_RANGES = (Video.Range.HDR10P, Video.Range.HDR10)
def convert_scc(subtitle: Subtitle, sub_format: Optional[Union[Subtitle.Codec, str]]) -> Subtitle.Codec:
"""
Convert an SCC subtitle to sub_format when pycaption can write it, else to SRT, and return the new codec.
@@ -270,22 +259,6 @@ def convert_scc(subtitle: Subtitle, sub_format: Optional[Union[Subtitle.Codec, s
return target
def select_hybrid_bases(videos: Sequence[Video]) -> list[Video]:
"""The HDR10 or HDR10+ track that is the hybrid base for each height, tallest first.
Only HEVC tracks qualify, because dovi_tool injects the RPU into an HEVC stream. HDR10+ comes before
HDR10 at one height.
"""
bases: dict[int, Video] = {}
for video in sorted(
(v for v in videos if v.range in HYBRID_BASE_RANGES and v.codec in (Video.Codec.HEVC, None)),
key=lambda v: (v.height or 0, v.range == Video.Range.HDR10P),
reverse=True,
):
bases.setdefault(video.height or 0, video)
return list(bases.values())
def generated_dv_ranges(
range_: Sequence[Video.Range], generate_dv: bool
) -> tuple[list[Video.Range], list[Video.Range]]:
@@ -301,11 +274,6 @@ def generated_dv_ranges(
return [Video.Range.HYBRID, *(r for r in range_ if r not in bases)], bases
def keep_generated_dv_bases(videos: Sequence[Video], bases: Sequence[Video.Range]) -> list[Video]:
"""The videos without the DV tracks and without a hybrid base range the user did not name."""
return [v for v in videos if v.range != Video.Range.DV and (v.range not in HYBRID_BASE_RANGES or v.range in bases)]
def subtitle_look(
sub_format: Optional[Union[Subtitle.Codec, str]],
sub_font: Optional[str],
@@ -341,26 +309,6 @@ def set_subtitle_look(
subtitle.ass_video_size = size
def hybrid_gate_failure(videos: Sequence[Video], generate_dv: bool) -> Optional[str]:
"""The message that stops HYBRID for these selected videos, or None when it can go on."""
if any(v.native_hybrid for v in videos):
return None
hdr_tracks = [v for v in videos if v.range in HYBRID_BASE_RANGES]
base_tracks = [v for v in hdr_tracks if v.codec in (Video.Codec.HEVC, None)]
dv_tracks = [v for v in videos if v.range == Video.Range.DV]
ranges = ", ".join(sorted(set(v.range.name for v in videos))) or "none"
missing = f"HYBRID needs HDR10/HDR10+ and DV tracks, available ranges: {ranges}"
if not hdr_tracks:
return missing
if not base_tracks:
codecs = sorted(set(v.codec.name for v in hdr_tracks if v.codec))
return f"HYBRID needs an HEVC HDR10/HDR10+ base, available codecs: {', '.join(codecs)}"
if not dv_tracks and not generate_dv:
return f"{missing}; add --generate-dv to make DV"
return None
def hybrid_plan(videos: Sequence[Video], generate_dv: bool) -> tuple[list[Video], Optional[Video]]:
"""The hybrid bases and the 2D DV track to pair with them.
@@ -2283,59 +2231,50 @@ class dl:
# replaces -w; a base SxE key selects every part of a split episode
wanted = [f"{season}x{number}" for season, number in latest_keys]
def select_best_audio(
audio: list[Audio],
languages: list[str],
acodec: list[Audio.Codec],
audio_description: bool,
exact_lang: bool,
) -> list[Audio]:
"""Pick the best audio per (language, codec) group from a sort_audio-ordered list.
"Best" is the first track of each order-preserving candidate filter, so the
sort_audio ranking (descriptive-last, Atmos, codec_priority, bitrate) decides the
winner. With audio_description both the best standard and best descriptive track per
group are kept. "best"/"all" tokens select every language present in sorted order.
"""
select_all = any(tok in ("best", "all") for tok in languages)
if select_all:
target_langs: list[Any] = list(dict.fromkeys(t.language for t in audio))
else:
target_langs = languages
codecs: list[Optional[Audio.Codec]] = list(acodec) if len(acodec) > 1 else [None]
selected: list[Audio] = []
for language in target_langs:
for codec in codecs:
if select_all:
candidates = [
t for t in audio if t.language == language and (codec is None or t.codec == codec)
]
else:
# match against every codec at once, so the variant a tag means does not depend on codec
tags = matching_languages(language, [t.language for t in audio], exact_lang)
candidates = [
t for t in audio if str(t.language) in tags and (codec is None or t.codec == codec)
]
if not candidates:
continue
if audio_description:
standards = [t for t in candidates if not t.descriptive]
if standards:
selected.append(standards[0])
descs = [t for t in candidates if t.descriptive]
if descs:
selected.append(descs[0])
else:
selected.append(candidates[0])
# Built via per-tag by_language calls, so overlapping tags can append
# the same track across iterations; dedupe by id.
unique: dict[str, Audio] = {}
for t in selected:
unique.setdefault(t.id, t)
return list(unique.values())
base_selection = (v_lang, a_lang, s_lang, range_)
selection = TrackSelection(
quality=quality,
vcodec=vcodec,
acodec=acodec,
vbitrate=vbitrate,
abitrate=abitrate,
vbitrate_min=vbitrate_min,
vbitrate_max=vbitrate_max,
abitrate_min=abitrate_min,
abitrate_max=abitrate_max,
range_=range_,
generated_dv_bases=generated_dv_bases,
channels=channels,
no_atmos=no_atmos,
lang=lang,
v_lang=v_lang,
a_lang=a_lang,
s_lang=s_lang,
video_excl=video_excl,
audio_excl=audio_excl,
s_lang_excl=s_lang_excl,
fsl_excl=fsl_excl,
forced_s_lang=forced_s_lang,
require_audio=require_audio,
require_video=require_video,
require_subs=require_subs,
forced_subs=forced_subs,
forced_subs_only=forced_subs_only,
exact_lang=exact_lang,
video_only=video_only,
audio_only=audio_only,
subs_only=subs_only,
chapters_only=chapters_only,
no_subs=no_subs,
no_audio=no_audio,
no_chapters=no_chapters,
no_video=no_video,
no_attachments=no_attachments,
audio_description=audio_description,
audio_description_only=audio_description_only,
worst=worst,
best_available=best_available,
generate_dv=generate_dv,
)
post_script_pending: dict[Any, int] = {}
for candidate in titles:
@@ -2373,7 +2312,6 @@ class dl:
settle_post_script_group(title)
for i, title in enumerate(titles):
v_lang, a_lang, s_lang, range_ = base_selection
if not title_wanted(title, wanted):
continue
@@ -2611,527 +2549,16 @@ class dl:
print_listing(listing_panel(available_tracks, "Available Tracks"))
continue
keep_videos = True
keep_audio = True
keep_subtitles = True
keep_chapters = True
if video_only or audio_only or subs_only or chapters_only:
keep_videos = video_only
keep_audio = audio_only
keep_subtitles = subs_only
keep_chapters = chapters_only
if hasattr(service, "NO_SUBTITLES") and service.NO_SUBTITLES:
console.log("Skipping subtitles - service does not support subtitle downloads")
keep_subtitles = False
s_lang = None
elif no_subs:
console.log("Skipped subtitles as --no-subs was used...")
keep_subtitles = False
s_lang = None
if no_video:
console.log("Skipped video as --no-video was used...")
keep_videos = False
v_lang = None
if no_audio:
console.log("Skipped audio as --no-audio was used...")
keep_audio = False
a_lang = None
if no_chapters:
console.log("Skipped chapters as --no-chapters was used...")
keep_chapters = False
if no_attachments:
console.log("Skipped attachments as --no-attachments was used...")
if no_proxy_download and any(service.session.proxies.values()):
console.log("Bypassing proxy for downloads as --no-proxy-download was used...")
elif proxy_download:
console.log(f"Using a separate proxy for downloads: {mask_proxy(proxy_download)}")
missing_required: list[str] = []
for kind, required, available in (
(
"audio",
require_audio if keep_audio else [],
[a.language for a in title.tracks.audio if a.descriptive or not audio_description_only]
+ embedded_audio_langs(title.tracks.videos, keep_videos and not audio_description_only),
),
("video", require_video if keep_videos else [], [v.language for v in title.tracks.videos]),
(
"subtitle",
require_subs if keep_subtitles else [],
[
t.language
for t in title.tracks.subtitles
if (t.forced if forced_subs_only else forced_subs or not t.forced)
],
),
):
if missing := missing_required_langs(required, available, title.language, exact=exact_lang):
missing_required.append(f"Required {kind} language(s) not found: {', '.join(missing)}")
if missing_required:
skip_title(title, "; ".join(missing_required))
outcome = selection.select(title, bool(getattr(service, "NO_SUBTITLES", False)))
if isinstance(outcome, Skip):
skip_title(title, outcome.reason, outcome.kind_only)
continue
if not keep_videos:
title.tracks.videos = []
if not keep_audio:
title.tracks.audio = []
if not keep_subtitles:
title.tracks.subtitles = []
if not keep_chapters:
title.tracks.chapters = []
with console.status("Selecting tracks...", spinner="dots"):
video_excl_r = resolve_sort_langs(video_excl, title.language, exact=exact_lang)
audio_excl_r = resolve_sort_langs(audio_excl, title.language, exact=exact_lang)
s_excl_r = resolve_sort_langs(s_lang_excl, title.language, exact=exact_lang)
fsl_excl_r = resolve_sort_langs(fsl_excl, title.language, exact=exact_lang)
if isinstance(title, (Movie, Episode)):
resolution: Optional[int]
color_range: Optional[Video.Range]
codec: Optional[Video.Codec]
if keep_videos and vcodec:
title.tracks.select_video(lambda x: x.codec in vcodec)
missing_codecs = [c for c in vcodec if not any(x.codec == c for x in title.tracks.videos)]
for codec in missing_codecs:
self.log.warning(f"Skipping {codec.name} video tracks as none are available.")
if not title.tracks.videos:
skip_title(title, f"There's no {', '.join(c.name for c in vcodec)} Video Track...")
continue
elif keep_videos:
title.tracks.select_video(lambda x: x.codec != Video.Codec.LCEVC)
if keep_videos and generated_dv_bases:
title.tracks.videos = keep_generated_dv_bases(title.tracks.videos, generated_dv_bases)
if not any(v.range in generated_dv_bases for v in title.tracks.videos):
skip_title(
title, f"There's no {', '.join(r.name for r in generated_dv_bases)} Video Track..."
)
continue
if keep_videos and range_:
# Special handling for HYBRID - don't filter, keep all HDR10 and DV tracks
if Video.Range.HYBRID not in range_:
dv_has_hdr10p = any(x.hdr10plus for x in title.tracks.videos)
title.tracks.select_video(lambda x: x.range in range_)
missing_ranges = [r for r in range_ if not any(x.range == r for x in title.tracks.videos)]
for color_range in missing_ranges:
self.log.warning(f"Skipping {color_range.name} video tracks as none are available.")
if Video.Range.HDR10P in missing_ranges and dv_has_hdr10p:
self.log.warning("A DV track carries HDR10+: use -r DV or -r HYBRID.")
if not title.tracks.videos:
skip_title(title, f"There's no {', '.join(r.name for r in range_)} Video Track...")
continue
if keep_videos and vbitrate:
if any(r == Video.Range.HYBRID for r in range_):
# In HYBRID mode, only apply bitrate filter to non-DV tracks
# DV tracks are kept regardless since they're only used for RPU metadata
title.tracks.select_video(
lambda x: x.range == Video.Range.DV or bool(x.bitrate and x.bitrate // 1000 == vbitrate)
)
if not any(x.range != Video.Range.DV for x in title.tracks.videos):
skip_title(title, f"There's no {vbitrate}kbps Video Track...")
continue
else:
title.tracks.select_video(lambda x: bool(x.bitrate and x.bitrate // 1000 == vbitrate))
if not title.tracks.videos:
skip_title(title, f"There's no {vbitrate}kbps Video Track...")
continue
if keep_videos and vbitrate_min is not None and vbitrate_max is not None:
title.tracks.select_video(
lambda x: bool(x.bitrate and vbitrate_min <= x.bitrate // 1000 <= vbitrate_max)
)
if not title.tracks.videos:
skip_title(title, f"No Video Track in {vbitrate_min}-{vbitrate_max}kbps range...")
continue
if keep_videos and video_excl_r:
drop = matched_language_tags(
video_excl_r, [t.language for t in title.tracks.videos], exact_lang, every_variant=True
)
title.tracks.select_video(lambda x: str(x.language) not in drop)
if not title.tracks.videos:
skip_title(title, f"Every Video Track was excluded by -{', -'.join(video_excl_r)}...")
continue
effective_video_lang = v_lang or lang
video_languages = [lang for lang in effective_video_lang if lang != "best"]
processed_video_lang = video_languages
if keep_videos and video_languages and "all" not in video_languages:
processed_video_lang = resolve_sort_langs(video_languages, title.language, exact=exact_lang)
v_orig_token = orig_token(video_languages, title.language, exact_lang)
if "orig" in video_languages and not title.language:
self.log.warning(
"Original language not available for title, skipping 'orig' selection for video"
)
missing_v_langs = find_missing_langs(
processed_video_lang,
[v.language for v in title.tracks.videos],
exact=exact_lang,
)
if missing_v_langs:
missing_str = as_requested(missing_v_langs, v_orig_token)
if best_available:
remaining_v_langs = [tok for tok in processed_video_lang if tok not in missing_v_langs]
if remaining_v_langs:
self.log.warning(
f"{missing_str} not found in video tracks, "
f"continuing with: {as_requested(remaining_v_langs, v_orig_token)}"
)
processed_video_lang = remaining_v_langs
else:
skip_title(
title, f"{missing_str} not found in video tracks and no fallback available"
)
continue
else:
skip_title(title, missing_str + " not found in video tracks")
continue
title.tracks.videos = title.tracks.by_language(
title.tracks.videos, processed_video_lang, exact_match=exact_lang
)
if not title.tracks.videos:
# empty only when 'orig' was the sole request and did not resolve
skip_title(
title,
f"There's no {as_requested(processed_video_lang, v_orig_token) or 'orig'} Video Track...",
)
continue
video_requests = None if {"best", "all"} & set(effective_video_lang) else processed_video_lang
has_hybrid = any(r == Video.Range.HYBRID for r in range_)
non_hybrid_ranges: list[Video.Range] = [r for r in range_ if r != Video.Range.HYBRID]
effective_quality = quality
if keep_videos and quality:
missing_resolutions = []
if has_hybrid:
hybrid_candidate_tracks, non_hybrid_tracks = Tracks.partition_hybrid_videos(
title.tracks.videos, non_hybrid_ranges
)
# only ranges that can actually be delivered count towards "present"
deliverable_pool = hybrid_candidate_tracks + [
v for v in non_hybrid_tracks if v.range in non_hybrid_ranges
]
for resolution in quality:
if any(at_resolution(v, resolution) for v in deliverable_pool):
continue
missing_resolutions.append(resolution)
if len(missing_resolutions) == len(quality) and best_available:
# every requested resolution missing: leave the pool untouched so the
# best-available hybrid pass below selects the top resolution instead
effective_quality = []
else:
hybrid_filter = title.tracks.select_hybrid(
hybrid_candidate_tracks, quality, worst=worst, generate_dv=generate_dv
)
hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks))
if non_hybrid_ranges and non_hybrid_tracks:
non_hybrid_selected = [
v for v in non_hybrid_tracks if any(at_resolution(v, res) for res in quality)
]
title.tracks.videos = Tracks.merge_video_selections(
hybrid_selected, non_hybrid_selected
)
else:
title.tracks.videos = hybrid_selected
else:
pre_quality_videos = list(title.tracks.videos)
title.tracks.by_resolutions(quality)
for resolution in quality:
if any(at_resolution(v, resolution) for v in title.tracks.videos):
continue
missing_resolutions.append(resolution)
if len(missing_resolutions) == len(quality) and best_available:
# every requested resolution missing: fall back to the best available
title.tracks.videos = pre_quality_videos
effective_quality = []
if missing_resolutions:
res_list = ""
if len(missing_resolutions) > 1:
res_list = ", ".join([f"{x}p" for x in missing_resolutions[:-1]]) + " or "
res_list = f"{res_list}{missing_resolutions[-1]}p"
plural = "s" if len(missing_resolutions) > 1 else ""
if best_available:
self.log.warning(
f"There's no {res_list} Video Track{plural}, continuing with available qualities..."
)
else:
skip_title(title, f"There's no {res_list} Video Track{plural}...")
continue
pre_hybrid_videos: list[Video] = list(title.tracks.videos) if has_hybrid else []
if keep_videos and has_hybrid:
hybrid_candidate_tracks, non_hybrid_tracks = Tracks.partition_hybrid_videos(
title.tracks.videos, non_hybrid_ranges
)
hybrid_quality = effective_quality
if not hybrid_quality:
height_pool = (
[
*select_hybrid_bases(hybrid_candidate_tracks),
*(v for v in hybrid_candidate_tracks if v.finished_hybrid),
]
if worst
else hybrid_candidate_tracks
)
base_heights = [v.height for v in height_pool if v.height]
hybrid_quality = [(min if worst else max)(base_heights)] if base_heights else []
hybrid_selected = []
if hybrid_quality:
hybrid_filter = title.tracks.select_hybrid(
hybrid_candidate_tracks, hybrid_quality, worst=worst, generate_dv=generate_dv
)
hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks))
for res in hybrid_quality:
if not any(at_resolution(v, res) for v in hybrid_selected):
self.log.warning(f"Skipping {res}p: nothing at that resolution can make a hybrid")
non_hybrid_selected = []
if non_hybrid_ranges and non_hybrid_tracks:
non_hybrid_selected = select_videos(
non_hybrid_tracks,
effective_quality,
non_hybrid_ranges,
vcodec,
video_requests,
exact_lang,
worst,
)
title.tracks.videos = Tracks.merge_video_selections(hybrid_selected, non_hybrid_selected)
Tracks.flag_hybrid_ingredients(hybrid_selected, non_hybrid_selected)
elif keep_videos:
title.tracks.videos = select_videos(
title.tracks.videos, effective_quality, range_, vcodec, video_requests, exact_lang, worst
)
if keep_videos and any(r == Video.Range.HYBRID for r in range_):
gate_failure = hybrid_gate_failure(title.tracks.videos, generate_dv)
if not gate_failure and not any(
v.range == Video.Range.DV or v.native_hybrid for v in title.tracks.videos
):
self.log.info("No Dolby Vision track: Dolby Vision will be generated")
if gate_failure:
other_ranges: list[Video.Range] = [r for r in range_ if r != Video.Range.HYBRID]
if best_available and other_ranges:
self.log.warning(
f"{gate_failure}; continuing with {', '.join(r.name for r in other_ranges)}"
)
range_ = other_ranges
title.tracks.videos = select_videos(
pre_hybrid_videos,
effective_quality,
other_ranges,
vcodec,
video_requests,
exact_lang,
worst,
)
else:
skip_title(title, gate_failure)
continue
fsl = resolve_sort_langs(forced_s_lang, title.language, exact=exact_lang)
if keep_subtitles and s_excl_r:
# applies to forced subs too: an excluded language is unwanted in any form
drop = matched_language_tags(
s_excl_r, [t.language for t in title.tracks.subtitles], exact_lang, every_variant=True
)
title.tracks.select_subtitles(lambda x: str(x.language) not in drop)
if keep_subtitles and s_lang and "all" not in s_lang:
s_orig_token = orig_token(s_lang, title.language, exact_lang)
s_lang = resolve_sort_langs(s_lang, title.language, exact=exact_lang)
# the pool selection draws from: forced tracks count only when -fs keeps them
missing_langs = find_missing_langs(
s_lang,
[sub.language for sub in title.tracks.subtitles if forced_subs or not sub.forced],
exact=exact_lang,
)
if missing_langs:
remaining = [tok for tok in s_lang if tok not in missing_langs]
tail = (
f"continuing with: {as_requested(remaining, s_orig_token)}"
if remaining
else "continuing without subtitles"
)
self.log.warning(
f"{as_requested(missing_langs, s_orig_token)} not found in subtitle tracks, {tail}"
)
if s_lang and title.tracks.subtitles:
plain_tags = plain_subtitle_tags(s_lang, title.tracks.subtitles, exact_lang)
forced_tags = matched_language_tags(
[*s_lang, *fsl], [x.language for x in title.tracks.subtitles if x.forced], exact_lang
)
title.tracks.select_subtitles(
lambda x: str(x.language) in (forced_tags if x.forced else plain_tags)
)
if keep_subtitles:
# fsl, not forced_s_lang: unresolvable orig must keep all forced, not drop them
if fsl:
fsl_tags = matched_language_tags(
fsl, [x.language for x in title.tracks.subtitles if x.forced], exact_lang
)
title.tracks.select_subtitles(lambda x: not x.forced or str(x.language) in fsl_tags)
if not any(x.forced for x in title.tracks.subtitles):
self.log.warning(
f"No forced subtitle tracks matched --forced-s-lang ({', '.join(forced_s_lang)})"
)
elif not forced_subs:
title.tracks.select_subtitles(lambda x: not x.forced)
if fsl_excl_r:
drop = matched_language_tags(
fsl_excl_r,
[t.language for t in title.tracks.subtitles if t.forced],
exact_lang,
every_variant=True,
)
title.tracks.select_subtitles(lambda x: not (x.forced and str(x.language) in drop))
if forced_subs_only:
title.tracks.select_subtitles(lambda x: x.forced)
if not title.tracks.subtitles:
skip_title(
title,
"There's no forced subtitle track for the selected languages.",
kind_only=True,
)
continue
if keep_audio and audio_description_only:
title.tracks.select_audio(lambda x: x.descriptive)
if not title.tracks.audio:
skip_title(title, "There's no audio description track.", kind_only=True)
continue
# might have no audio tracks if part of the video, e.g. transport stream hls
if keep_audio and len(title.tracks.audio) > 0:
if not audio_description:
title.tracks.select_audio(lambda x: not x.descriptive)
if not title.tracks.audio:
skip_title(title, "Audio description only, use --audio-description...")
continue
if acodec:
title.tracks.select_audio(lambda x: x.codec in acodec)
if not title.tracks.audio:
codec_names = ", ".join(c.name for c in acodec)
skip_title(title, f"No audio tracks matching codecs: {codec_names}")
continue
if channels:
title.tracks.select_audio(
lambda x: bool(
x.channels and math.ceil(Audio.channel_total(x.channels)) == math.ceil(channels)
)
)
if not title.tracks.audio:
skip_title(title, f"There's no {channels} Audio Track...")
continue
if no_atmos:
title.tracks.audio = [x for x in title.tracks.audio if not x.atmos]
if not title.tracks.audio:
skip_title(title, "No non-Atmos audio tracks available...")
continue
if abitrate:
title.tracks.select_audio(lambda x: x.bitrate and x.bitrate // 1000 == abitrate)
if not title.tracks.audio:
skip_title(title, f"There's no {abitrate}kbps Audio Track...")
continue
if abitrate_min is not None and abitrate_max is not None:
title.tracks.select_audio(
lambda x: x.bitrate and abitrate_min <= x.bitrate // 1000 <= abitrate_max
)
if not title.tracks.audio:
skip_title(title, f"No Audio Track in {abitrate_min}-{abitrate_max}kbps range...")
continue
if audio_excl_r:
drop = matched_language_tags(
audio_excl_r, [t.language for t in title.tracks.audio], exact_lang, every_variant=True
)
title.tracks.select_audio(lambda x: str(x.language) not in drop)
if not title.tracks.audio:
skip_title(title, f"Every Audio Track was excluded by -{', -'.join(audio_excl_r)}...")
continue
audio_languages = a_lang or lang
if audio_languages:
processed_lang = resolve_sort_langs(audio_languages, title.language, exact=exact_lang)
a_orig_token = orig_token(audio_languages, title.language, exact_lang)
if "orig" in audio_languages and not title.language:
self.log.warning("Original language not available for title, skipping 'orig' selection")
embedded_langs = embedded_audio_langs(
title.tracks.videos, keep_videos and not audio_description_only
)
audio_noun = "audio description tracks" if audio_description_only else "audio tracks"
if not any(tok in processed_lang for tok in ("best", "all")):
missing_a_langs = find_missing_langs(
processed_lang,
[a.language for a in title.tracks.audio] + embedded_langs,
exact=exact_lang,
)
if missing_a_langs:
missing_str = as_requested(missing_a_langs, a_orig_token)
if best_available:
remaining = [tok for tok in processed_lang if tok not in missing_a_langs]
if remaining:
self.log.warning(
f"{missing_str} not found in {audio_noun}, "
f"continuing with: {as_requested(remaining, a_orig_token)}"
)
processed_lang = remaining
else:
skip_title(
title, f"{missing_str} not found in {audio_noun} and no fallback available"
)
continue
else:
skip_title(title, f"{missing_str} not found in {audio_noun}")
continue
title.tracks.audio = select_best_audio(
title.tracks.audio, processed_lang, acodec, audio_description, exact_lang
)
if not title.tracks.audio and not embedded_langs:
# empty when 'orig' was the sole request, did not resolve, and the
# video carries no audio of its own to fall back on
skip_title(
title,
f"There's no {as_requested(processed_lang, a_orig_token) or 'orig'} Audio Track...",
)
continue
kept_tracks = []
if keep_videos:
kept_tracks.extend(title.tracks.videos)
if keep_audio:
kept_tracks.extend(title.tracks.audio)
if keep_subtitles:
kept_tracks.extend(title.tracks.subtitles)
if keep_chapters:
kept_tracks.extend(title.tracks.chapters)
if not no_attachments:
kept_tracks.extend(title.tracks.attachments)
title.tracks = Tracks(kept_tracks, manifest_url=title.tracks.manifest_url)
if not (title.tracks.videos or title.tracks.audio or title.tracks.subtitles or title.tracks.chapters):
skip_title(title, "There's no track left for the selected options.", kind_only=True)
continue
range_ = outcome.ranges
selected_tracks, tracks_progress_callables = title.tracks.tree(add_progress=True)
+679
View File
@@ -0,0 +1,679 @@
"""Track selection: which tracks of a title a dl run keeps, or why it skips the title."""
from __future__ import annotations
import logging
import math
from dataclasses import dataclass
from typing import Any, Optional, Sequence, Union
from unshackle.core.console import console
from unshackle.core.constants import AnyTrack
from unshackle.core.titles import Episode, Movie, Title_T
from unshackle.core.tracks.attachment import Attachment
from unshackle.core.tracks.audio import Audio
from unshackle.core.tracks.chapter import Chapter
from unshackle.core.tracks.chapters import Chapters
from unshackle.core.tracks.tracks import Tracks, at_resolution, select_videos
from unshackle.core.tracks.video import Video
from unshackle.core.utilities import (
as_requested,
embedded_audio_langs,
find_missing_langs,
matched_language_tags,
matching_languages,
missing_required_langs,
orig_token,
plain_subtitle_tags,
resolve_sort_langs,
)
log = logging.getLogger("download")
HYBRID_BASE_RANGES = (Video.Range.HDR10P, Video.Range.HDR10)
@dataclass(frozen=True)
class Skip:
"""The title has no track the selection asks for.
A kind-only miss (-ado, -fso, no track left) skips without --skip-missing; the caller decides the rest.
"""
reason: str
kind_only: bool = False
@dataclass(frozen=True)
class Kept:
"""The tracks the title keeps, and the ranges it downloads: a failed HYBRID falls back to the other ranges."""
tracks: Tracks
ranges: list[Video.Range]
@dataclass(frozen=True, kw_only=True)
class TrackSelection:
"""The selection flags of one dl run, as result() normalizes them, applied to each title in a fixed order."""
quality: list[int]
vcodec: list[Video.Codec]
acodec: list[Audio.Codec]
vbitrate: Optional[int]
abitrate: Optional[int]
vbitrate_min: Optional[int]
vbitrate_max: Optional[int]
abitrate_min: Optional[int]
abitrate_max: Optional[int]
range_: list[Video.Range]
generated_dv_bases: list[Video.Range]
channels: Optional[float]
no_atmos: bool
lang: list[str]
v_lang: Optional[list[str]]
a_lang: Optional[list[str]]
s_lang: Optional[list[str]]
video_excl: list[str]
audio_excl: list[str]
s_lang_excl: list[str]
fsl_excl: list[str]
forced_s_lang: list[str]
require_audio: list[str]
require_video: list[str]
require_subs: list[str]
forced_subs: bool
forced_subs_only: bool
exact_lang: bool
video_only: bool
audio_only: bool
subs_only: bool
chapters_only: bool
no_subs: bool
no_audio: bool
no_chapters: bool
no_video: bool
no_attachments: bool
audio_description: bool
audio_description_only: bool
worst: bool
best_available: bool
generate_dv: bool
def select(self, title: Title_T, subtitles_unsupported: bool) -> Union[Kept, Skip]:
"""Narrow title.tracks to the tracks the flags ask for, or return the reason to skip the title.
subtitles_unsupported is the service's NO_SUBTITLES read after get_tracks, which can set it. The
required-language gate runs first, on the tracks before any filter, so a miss there is never kind-only.
"""
v_lang, a_lang, s_lang, range_ = self.v_lang, self.a_lang, self.s_lang, self.range_
vbitrate_min, vbitrate_max, abitrate_min, abitrate_max = (
self.vbitrate_min,
self.vbitrate_max,
self.abitrate_min,
self.abitrate_max,
)
channels = self.channels
keep_videos = True
keep_audio = True
keep_subtitles = True
keep_chapters = True
if self.video_only or self.audio_only or self.subs_only or self.chapters_only:
keep_videos = self.video_only
keep_audio = self.audio_only
keep_subtitles = self.subs_only
keep_chapters = self.chapters_only
if subtitles_unsupported:
console.log("Skipping subtitles - service does not support subtitle downloads")
keep_subtitles = False
s_lang = None
elif self.no_subs:
console.log("Skipped subtitles as --no-subs was used...")
keep_subtitles = False
s_lang = None
if self.no_video:
console.log("Skipped video as --no-video was used...")
keep_videos = False
v_lang = None
if self.no_audio:
console.log("Skipped audio as --no-audio was used...")
keep_audio = False
a_lang = None
if self.no_chapters:
console.log("Skipped chapters as --no-chapters was used...")
keep_chapters = False
if self.no_attachments:
console.log("Skipped attachments as --no-attachments was used...")
missing_required: list[str] = []
for kind, required, available in (
(
"audio",
self.require_audio if keep_audio else [],
[a.language for a in title.tracks.audio if a.descriptive or not self.audio_description_only]
+ embedded_audio_langs(title.tracks.videos, keep_videos and not self.audio_description_only),
),
("video", self.require_video if keep_videos else [], [v.language for v in title.tracks.videos]),
(
"subtitle",
self.require_subs if keep_subtitles else [],
[
t.language
for t in title.tracks.subtitles
if (t.forced if self.forced_subs_only else self.forced_subs or not t.forced)
],
),
):
if missing := missing_required_langs(required, available, title.language, exact=self.exact_lang):
missing_required.append(f"Required {kind} language(s) not found: {', '.join(missing)}")
if missing_required:
return Skip("; ".join(missing_required))
if not keep_videos:
title.tracks.videos = []
if not keep_audio:
title.tracks.audio = []
if not keep_subtitles:
title.tracks.subtitles = []
if not keep_chapters:
title.tracks.chapters = Chapters()
with console.status("Selecting tracks...", spinner="dots"):
video_excl_r = resolve_sort_langs(self.video_excl, title.language, exact=self.exact_lang)
audio_excl_r = resolve_sort_langs(self.audio_excl, title.language, exact=self.exact_lang)
s_excl_r = resolve_sort_langs(self.s_lang_excl, title.language, exact=self.exact_lang)
fsl_excl_r = resolve_sort_langs(self.fsl_excl, title.language, exact=self.exact_lang)
if isinstance(title, (Movie, Episode)):
if keep_videos and self.vcodec:
title.tracks.select_video(lambda x: x.codec in self.vcodec)
missing_codecs = [c for c in self.vcodec if not any(x.codec == c for x in title.tracks.videos)]
for codec in missing_codecs:
log.warning(f"Skipping {codec.name} video tracks as none are available.")
if not title.tracks.videos:
return Skip(f"There's no {', '.join(c.name for c in self.vcodec)} Video Track...")
elif keep_videos:
title.tracks.select_video(lambda x: x.codec != Video.Codec.LCEVC)
if keep_videos and self.generated_dv_bases:
title.tracks.videos = keep_generated_dv_bases(title.tracks.videos, self.generated_dv_bases)
if not any(v.range in self.generated_dv_bases for v in title.tracks.videos):
return Skip(f"There's no {', '.join(r.name for r in self.generated_dv_bases)} Video Track...")
if keep_videos and range_:
# Special handling for HYBRID - don't filter, keep all HDR10 and DV tracks
if Video.Range.HYBRID not in range_:
dv_has_hdr10p = any(x.hdr10plus for x in title.tracks.videos)
title.tracks.select_video(lambda x: x.range in range_)
missing_ranges = [r for r in range_ if not any(x.range == r for x in title.tracks.videos)]
for color_range in missing_ranges:
log.warning(f"Skipping {color_range.name} video tracks as none are available.")
if Video.Range.HDR10P in missing_ranges and dv_has_hdr10p:
log.warning("A DV track carries HDR10+: use -r DV or -r HYBRID.")
if not title.tracks.videos:
return Skip(f"There's no {', '.join(r.name for r in range_)} Video Track...")
if keep_videos and self.vbitrate:
if any(r == Video.Range.HYBRID for r in range_):
# In HYBRID mode, only apply bitrate filter to non-DV tracks
# DV tracks are kept regardless since they're only used for RPU metadata
title.tracks.select_video(
lambda x: (
x.range == Video.Range.DV or bool(x.bitrate and x.bitrate // 1000 == self.vbitrate)
)
)
if not any(x.range != Video.Range.DV for x in title.tracks.videos):
return Skip(f"There's no {self.vbitrate}kbps Video Track...")
else:
title.tracks.select_video(lambda x: bool(x.bitrate and x.bitrate // 1000 == self.vbitrate))
if not title.tracks.videos:
return Skip(f"There's no {self.vbitrate}kbps Video Track...")
if keep_videos and vbitrate_min is not None and vbitrate_max is not None:
title.tracks.select_video(
lambda x: bool(x.bitrate and vbitrate_min <= x.bitrate // 1000 <= vbitrate_max)
)
if not title.tracks.videos:
return Skip(f"No Video Track in {vbitrate_min}-{vbitrate_max}kbps range...")
if keep_videos and video_excl_r:
drop = matched_language_tags(
video_excl_r, [t.language for t in title.tracks.videos], self.exact_lang, every_variant=True
)
title.tracks.select_video(lambda x: str(x.language) not in drop)
if not title.tracks.videos:
return Skip(f"Every Video Track was excluded by -{', -'.join(video_excl_r)}...")
effective_video_lang = v_lang or self.lang
video_languages = [tok for tok in effective_video_lang if tok != "best"]
processed_video_lang = video_languages
if keep_videos and video_languages and "all" not in video_languages:
processed_video_lang = resolve_sort_langs(video_languages, title.language, exact=self.exact_lang)
v_orig_token = orig_token(video_languages, title.language, self.exact_lang)
if "orig" in video_languages and not title.language:
log.warning("Original language not available for title, skipping 'orig' selection for video")
missing_v_langs = find_missing_langs(
processed_video_lang,
[v.language for v in title.tracks.videos],
exact=self.exact_lang,
)
if missing_v_langs:
missing_str = as_requested(missing_v_langs, v_orig_token)
if self.best_available:
remaining_v_langs = [tok for tok in processed_video_lang if tok not in missing_v_langs]
if remaining_v_langs:
log.warning(
f"{missing_str} not found in video tracks, "
f"continuing with: {as_requested(remaining_v_langs, v_orig_token)}"
)
processed_video_lang = remaining_v_langs
else:
return Skip(f"{missing_str} not found in video tracks and no fallback available")
else:
return Skip(missing_str + " not found in video tracks")
title.tracks.videos = title.tracks.by_language(
title.tracks.videos, processed_video_lang, exact_match=self.exact_lang
)
if not title.tracks.videos:
# empty only when 'orig' was the sole request and did not resolve
return Skip(
f"There's no {as_requested(processed_video_lang, v_orig_token) or 'orig'} Video Track..."
)
video_requests = None if {"best", "all"} & set(effective_video_lang) else processed_video_lang
has_hybrid = any(r == Video.Range.HYBRID for r in range_)
non_hybrid_ranges: list[Video.Range] = [r for r in range_ if r != Video.Range.HYBRID]
effective_quality = self.quality
if keep_videos and self.quality:
missing_resolutions = []
if has_hybrid:
hybrid_candidate_tracks, non_hybrid_tracks = Tracks.partition_hybrid_videos(
title.tracks.videos, non_hybrid_ranges
)
# only ranges that can actually be delivered count towards "present"
deliverable_pool = hybrid_candidate_tracks + [
v for v in non_hybrid_tracks if v.range in non_hybrid_ranges
]
for resolution in self.quality:
if any(at_resolution(v, resolution) for v in deliverable_pool):
continue
missing_resolutions.append(resolution)
if len(missing_resolutions) == len(self.quality) and self.best_available:
# every requested resolution missing: leave the pool untouched so the
# best-available hybrid pass below selects the top resolution instead
effective_quality = []
else:
hybrid_filter = title.tracks.select_hybrid(
hybrid_candidate_tracks, self.quality, worst=self.worst, generate_dv=self.generate_dv
)
hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks))
if non_hybrid_ranges and non_hybrid_tracks:
non_hybrid_selected = [
v for v in non_hybrid_tracks if any(at_resolution(v, res) for res in self.quality)
]
title.tracks.videos = Tracks.merge_video_selections(
hybrid_selected, non_hybrid_selected
)
else:
title.tracks.videos = hybrid_selected
else:
pre_quality_videos = list(title.tracks.videos)
title.tracks.by_resolutions(self.quality)
for resolution in self.quality:
if any(at_resolution(v, resolution) for v in title.tracks.videos):
continue
missing_resolutions.append(resolution)
if len(missing_resolutions) == len(self.quality) and self.best_available:
# every requested resolution missing: fall back to the best available
title.tracks.videos = pre_quality_videos
effective_quality = []
if missing_resolutions:
res_list = ""
if len(missing_resolutions) > 1:
res_list = ", ".join([f"{x}p" for x in missing_resolutions[:-1]]) + " or "
res_list = f"{res_list}{missing_resolutions[-1]}p"
plural = "s" if len(missing_resolutions) > 1 else ""
if self.best_available:
log.warning(
f"There's no {res_list} Video Track{plural}, continuing with available qualities..."
)
else:
return Skip(f"There's no {res_list} Video Track{plural}...")
pre_hybrid_videos: list[Video] = list(title.tracks.videos) if has_hybrid else []
if keep_videos and has_hybrid:
hybrid_candidate_tracks, non_hybrid_tracks = Tracks.partition_hybrid_videos(
title.tracks.videos, non_hybrid_ranges
)
hybrid_quality = effective_quality
if not hybrid_quality:
height_pool = (
[
*select_hybrid_bases(hybrid_candidate_tracks),
*(v for v in hybrid_candidate_tracks if v.finished_hybrid),
]
if self.worst
else hybrid_candidate_tracks
)
base_heights = [v.height for v in height_pool if v.height]
hybrid_quality = [(min if self.worst else max)(base_heights)] if base_heights else []
hybrid_selected = []
if hybrid_quality:
hybrid_filter = title.tracks.select_hybrid(
hybrid_candidate_tracks, hybrid_quality, worst=self.worst, generate_dv=self.generate_dv
)
hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks))
for res in hybrid_quality:
if not any(at_resolution(v, res) for v in hybrid_selected):
log.warning(f"Skipping {res}p: nothing at that resolution can make a hybrid")
non_hybrid_selected = []
if non_hybrid_ranges and non_hybrid_tracks:
non_hybrid_selected = select_videos(
non_hybrid_tracks,
effective_quality,
non_hybrid_ranges,
self.vcodec,
video_requests,
self.exact_lang,
self.worst,
)
title.tracks.videos = Tracks.merge_video_selections(hybrid_selected, non_hybrid_selected)
Tracks.flag_hybrid_ingredients(hybrid_selected, non_hybrid_selected)
elif keep_videos:
title.tracks.videos = select_videos(
title.tracks.videos,
effective_quality,
range_,
self.vcodec,
video_requests,
self.exact_lang,
self.worst,
)
if keep_videos and any(r == Video.Range.HYBRID for r in range_):
gate_failure = hybrid_gate_failure(title.tracks.videos, self.generate_dv)
if not gate_failure and not any(
v.range == Video.Range.DV or v.native_hybrid for v in title.tracks.videos
):
log.info("No Dolby Vision track: Dolby Vision will be generated")
if gate_failure:
other_ranges: list[Video.Range] = [r for r in range_ if r != Video.Range.HYBRID]
if self.best_available and other_ranges:
log.warning(f"{gate_failure}; continuing with {', '.join(r.name for r in other_ranges)}")
range_ = other_ranges
title.tracks.videos = select_videos(
pre_hybrid_videos,
effective_quality,
other_ranges,
self.vcodec,
video_requests,
self.exact_lang,
self.worst,
)
else:
return Skip(gate_failure)
fsl = resolve_sort_langs(self.forced_s_lang, title.language, exact=self.exact_lang)
if keep_subtitles and s_excl_r:
# applies to forced subs too: an excluded language is unwanted in any form
drop = matched_language_tags(
s_excl_r, [t.language for t in title.tracks.subtitles], self.exact_lang, every_variant=True
)
title.tracks.select_subtitles(lambda x: str(x.language) not in drop)
if keep_subtitles and s_lang and "all" not in s_lang:
s_orig_token = orig_token(s_lang, title.language, self.exact_lang)
s_lang = resolve_sort_langs(s_lang, title.language, exact=self.exact_lang)
# the pool selection draws from: forced tracks count only when -fs keeps them
missing_langs = find_missing_langs(
s_lang,
[sub.language for sub in title.tracks.subtitles if self.forced_subs or not sub.forced],
exact=self.exact_lang,
)
if missing_langs:
remaining = [tok for tok in s_lang if tok not in missing_langs]
tail = (
f"continuing with: {as_requested(remaining, s_orig_token)}"
if remaining
else "continuing without subtitles"
)
log.warning(f"{as_requested(missing_langs, s_orig_token)} not found in subtitle tracks, {tail}")
if s_lang and title.tracks.subtitles:
plain_tags = plain_subtitle_tags(s_lang, title.tracks.subtitles, self.exact_lang)
forced_tags = matched_language_tags(
[*s_lang, *fsl], [x.language for x in title.tracks.subtitles if x.forced], self.exact_lang
)
title.tracks.select_subtitles(
lambda x: str(x.language) in (forced_tags if x.forced else plain_tags)
)
if keep_subtitles:
# fsl, not self.forced_s_lang: unresolvable orig must keep all forced, not drop them
if fsl:
fsl_tags = matched_language_tags(
fsl, [x.language for x in title.tracks.subtitles if x.forced], self.exact_lang
)
title.tracks.select_subtitles(lambda x: not x.forced or str(x.language) in fsl_tags)
if not any(x.forced for x in title.tracks.subtitles):
log.warning(
f"No forced subtitle tracks matched --forced-s-lang ({', '.join(self.forced_s_lang)})"
)
elif not self.forced_subs:
title.tracks.select_subtitles(lambda x: not x.forced)
if fsl_excl_r:
drop = matched_language_tags(
fsl_excl_r,
[t.language for t in title.tracks.subtitles if t.forced],
self.exact_lang,
every_variant=True,
)
title.tracks.select_subtitles(lambda x: not (x.forced and str(x.language) in drop))
if self.forced_subs_only:
title.tracks.select_subtitles(lambda x: x.forced)
if not title.tracks.subtitles:
return Skip("There's no forced subtitle track for the selected languages.", kind_only=True)
if keep_audio and self.audio_description_only:
title.tracks.select_audio(lambda x: x.descriptive)
if not title.tracks.audio:
return Skip("There's no audio description track.", kind_only=True)
# might have no audio tracks if part of the video, e.g. transport stream hls
if keep_audio and len(title.tracks.audio) > 0:
if not self.audio_description:
title.tracks.select_audio(lambda x: not x.descriptive)
if not title.tracks.audio:
return Skip("Audio description only, use --audio-description...")
if self.acodec:
title.tracks.select_audio(lambda x: x.codec in self.acodec)
if not title.tracks.audio:
codec_names = ", ".join(c.name for c in self.acodec)
return Skip(f"No audio tracks matching codecs: {codec_names}")
if channels:
title.tracks.select_audio(
lambda x: bool(x.channels and math.ceil(Audio.channel_total(x.channels)) == math.ceil(channels))
)
if not title.tracks.audio:
return Skip(f"There's no {channels} Audio Track...")
if self.no_atmos:
title.tracks.audio = [x for x in title.tracks.audio if not x.atmos]
if not title.tracks.audio:
return Skip("No non-Atmos audio tracks available...")
if self.abitrate:
title.tracks.select_audio(lambda x: bool(x.bitrate and x.bitrate // 1000 == self.abitrate))
if not title.tracks.audio:
return Skip(f"There's no {self.abitrate}kbps Audio Track...")
if abitrate_min is not None and abitrate_max is not None:
title.tracks.select_audio(
lambda x: bool(x.bitrate and abitrate_min <= x.bitrate // 1000 <= abitrate_max)
)
if not title.tracks.audio:
return Skip(f"No Audio Track in {abitrate_min}-{abitrate_max}kbps range...")
if audio_excl_r:
drop = matched_language_tags(
audio_excl_r, [t.language for t in title.tracks.audio], self.exact_lang, every_variant=True
)
title.tracks.select_audio(lambda x: str(x.language) not in drop)
if not title.tracks.audio:
return Skip(f"Every Audio Track was excluded by -{', -'.join(audio_excl_r)}...")
audio_languages = a_lang or self.lang
if audio_languages:
processed_lang = resolve_sort_langs(audio_languages, title.language, exact=self.exact_lang)
a_orig_token = orig_token(audio_languages, title.language, self.exact_lang)
if "orig" in audio_languages and not title.language:
log.warning("Original language not available for title, skipping 'orig' selection")
embedded_langs = embedded_audio_langs(
title.tracks.videos, keep_videos and not self.audio_description_only
)
audio_noun = "audio description tracks" if self.audio_description_only else "audio tracks"
if not any(tok in processed_lang for tok in ("best", "all")):
missing_a_langs = find_missing_langs(
processed_lang,
[*(a.language for a in title.tracks.audio), *embedded_langs],
exact=self.exact_lang,
)
if missing_a_langs:
missing_str = as_requested(missing_a_langs, a_orig_token)
if self.best_available:
remaining = [tok for tok in processed_lang if tok not in missing_a_langs]
if remaining:
log.warning(
f"{missing_str} not found in {audio_noun}, "
f"continuing with: {as_requested(remaining, a_orig_token)}"
)
processed_lang = remaining
else:
return Skip(f"{missing_str} not found in {audio_noun} and no fallback available")
else:
return Skip(f"{missing_str} not found in {audio_noun}")
title.tracks.audio = select_best_audio(
title.tracks.audio, processed_lang, self.acodec, self.audio_description, self.exact_lang
)
if not title.tracks.audio and not embedded_langs:
# empty when 'orig' was the sole request, did not resolve, and the
# video carries no audio of its own to fall back on
return Skip(f"There's no {as_requested(processed_lang, a_orig_token) or 'orig'} Audio Track...")
kept_tracks: list[Union[AnyTrack, Chapter, Attachment]] = []
if keep_videos:
kept_tracks.extend(title.tracks.videos)
if keep_audio:
kept_tracks.extend(title.tracks.audio)
if keep_subtitles:
kept_tracks.extend(title.tracks.subtitles)
if keep_chapters:
kept_tracks.extend(title.tracks.chapters)
if not self.no_attachments:
kept_tracks.extend(title.tracks.attachments)
title.tracks = Tracks(kept_tracks, manifest_url=title.tracks.manifest_url)
if not (title.tracks.videos or title.tracks.audio or title.tracks.subtitles or title.tracks.chapters):
return Skip("There's no track left for the selected options.", kind_only=True)
return Kept(title.tracks, range_)
def select_best_audio(
audio: list[Audio],
languages: list[str],
acodec: list[Audio.Codec],
audio_description: bool,
exact_lang: bool,
) -> list[Audio]:
"""Pick the best audio per (language, codec) group from a sort_audio-ordered list.
"Best" is the first track of each order-preserving candidate filter, so the
sort_audio ranking (descriptive-last, Atmos, codec_priority, bitrate) decides the
winner. With audio_description both the best standard and best descriptive track per
group are kept. "best"/"all" tokens select every language present in sorted order.
"""
select_all = any(tok in ("best", "all") for tok in languages)
if select_all:
target_langs: list[Any] = list(dict.fromkeys(t.language for t in audio))
else:
target_langs = languages
codecs: list[Optional[Audio.Codec]] = list(acodec) if len(acodec) > 1 else [None]
selected: list[Audio] = []
for language in target_langs:
for codec in codecs:
if select_all:
candidates = [t for t in audio if t.language == language and (codec is None or t.codec == codec)]
else:
# match against every codec at once, so the variant a tag means does not depend on codec
tags = matching_languages(language, [t.language for t in audio], exact_lang)
candidates = [t for t in audio if str(t.language) in tags and (codec is None or t.codec == codec)]
if not candidates:
continue
if audio_description:
standards = [t for t in candidates if not t.descriptive]
if standards:
selected.append(standards[0])
descs = [t for t in candidates if t.descriptive]
if descs:
selected.append(descs[0])
else:
selected.append(candidates[0])
# Built via per-tag by_language calls, so overlapping tags can append
# the same track across iterations; dedupe by id.
unique: dict[str, Audio] = {}
for t in selected:
unique.setdefault(t.id, t)
return list(unique.values())
def select_hybrid_bases(videos: Sequence[Video]) -> list[Video]:
"""The HDR10 or HDR10+ track that is the hybrid base for each height, tallest first.
Only HEVC tracks qualify, because dovi_tool injects the RPU into an HEVC stream. HDR10+ comes before
HDR10 at one height.
"""
bases: dict[int, Video] = {}
for video in sorted(
(v for v in videos if v.range in HYBRID_BASE_RANGES and v.codec in (Video.Codec.HEVC, None)),
key=lambda v: (v.height or 0, v.range == Video.Range.HDR10P),
reverse=True,
):
bases.setdefault(video.height or 0, video)
return list(bases.values())
def keep_generated_dv_bases(videos: Sequence[Video], bases: Sequence[Video.Range]) -> list[Video]:
"""The videos without the DV tracks and without a hybrid base range the user did not name."""
return [v for v in videos if v.range != Video.Range.DV and (v.range not in HYBRID_BASE_RANGES or v.range in bases)]
def hybrid_gate_failure(videos: Sequence[Video], generate_dv: bool) -> Optional[str]:
"""The message that stops HYBRID for these selected videos, or None when it can go on."""
if any(v.native_hybrid for v in videos):
return None
hdr_tracks = [v for v in videos if v.range in HYBRID_BASE_RANGES]
base_tracks = [v for v in hdr_tracks if v.codec in (Video.Codec.HEVC, None)]
dv_tracks = [v for v in videos if v.range == Video.Range.DV]
ranges = ", ".join(sorted(set(v.range.name for v in videos))) or "none"
missing = f"HYBRID needs HDR10/HDR10+ and DV tracks, available ranges: {ranges}"
if not hdr_tracks:
return missing
if not base_tracks:
codecs = sorted(set(v.codec.name for v in hdr_tracks if v.codec))
return f"HYBRID needs an HEVC HDR10/HDR10+ base, available codecs: {', '.join(codecs)}"
if not dv_tracks and not generate_dv:
return f"{missing}; add --generate-dv to make DV"
return None