Compare commits

...
6 Commits
Author SHA1 Message Date
imSp4rky cc33600cc7 feat(tracks): add muxing.original_label to mark original-language tracks
Adds the label to audio, subtitle and embedded audio names unless the name already says it, and escapes track lines in the --list tree.
2026-10-24 22:51:35 -06:00
imSp4rky 80bda08f36 feat(tracks): add muxing.track_names none to leave unnamed tracks unnamed
A track the service gives no name keeps none (--list shows [VTT] | en); SDH, CC, Forced and Descriptive labels still apply.
2026-10-24 21:24:31 -06:00
imSp4rky 7832c4dbe4 fix(cacher): treat an expiry within 1 µs of now as expired
datetime rounds the expiry to the microsecond, which can land past a coarse time.time() tick (15.6 ms on Windows) and flake test_zero_seconds_expires_now.
2026-10-24 21:22:35 -06:00
imSp4rky d0f9307506 perf(proxy): test the remote CDM hosts only after the walk finds service code 2026-10-24 17:57:48 -06:00
imSp4rky fdb5369534 fix(proxy): match a reloaded service class by name and dedup warnings per run
A hot service reload made instance_of miss the new class, so a run with no proxy got a false bypass warning.
2026-10-24 17:29:02 -06:00
imSp4rky 34e8e37fdc fix(services): clear service-repo bytecode with git pathspecs before a pull
Delete untracked __pycache__ before each pull and drop the global dont_write_bytecode, so service bytecode is cached again
2026-10-24 15:57:08 -06:00
13 changed files with 279 additions and 91 deletions
+1 -1
View File
@@ -377,7 +377,7 @@ The server sorts tracks by bitrate, descending. Episodes the server cannot get g
The `drm` array on a track is a list of `{type, pssh?, kids?, content_keys?, license_url?}` objects.
Every track carries the same fields as a local track: `is_original_lang`, `name`, `needs_repack`, `edition`, and `data`. `name` is the name the service set, or null. `track_name` is the name `--list` shows and the mux writes to an audio or subtitle track: `name` when the service set one, else the name of the language (English, or in the language itself when the server sets `muxing.track_names: native`), with the SDH, CC, Forced or Descriptive label. `bitrate` is in kb/s, and `bitrate_bps` gives the exact bits/s. `data` holds the part of the service-set `track.data` that fits in JSON, without the `hls`, `dash`, and `ism` parser keys. Audio keeps `is_original` and `atmos` for clients that read them, and adds the exact `joc` object count.
Every track carries the same fields as a local track: `is_original_lang`, `name`, `needs_repack`, `edition`, and `data`. `name` is the name the service set, or null. `track_name` is the name `--list` shows and the mux writes to an audio or subtitle track: `name` when the service set one, else the name of the language (English, or in the language itself when the server sets `muxing.track_names: native`, or no name when it sets `none`), then the server's `muxing.original_label` on an original-language track, then the SDH, CC, Forced or Descriptive label. `bitrate` is in kb/s, and `bitrate_bps` gives the exact bits/s. `data` holds the part of the service-set `track.data` that fits in JSON, without the `hls`, `dash`, and `ism` parser keys. Audio keeps `is_original` and `atmos` for clients that read them, and adds the exact `joc` object count.
| Status | Error code | Meaning |
| --- | --- | --- |
+31
View File
@@ -321,8 +321,39 @@ muxing:
| `es-419` | Español (Latinoamérica) |
| `ja-JP` | 日本語 |
Set `muxing.track_names` to `none` to leave a track unnamed when the service gives it no name. An
SDH, CC, Forced or Descriptive track then has only that label as its name.
The option also changes the names in `--list` and in the `track_name` field of the REST API.
Set `muxing.original_label` to add a label after the name of each audio and subtitle track in the
title's original language. unshackle also sets the Matroska original flag on these tracks, but some
players show only the name. MP4 output has no original flag, so there the label is the only marker:
```yaml title="unshackle.yaml"
muxing:
original_label: "[Original]"
```
| Track | Track name |
|-------|------------|
| Japanese audio, original language | Japanese [Original] |
| Japanese SDH subtitle, original language | Japanese [Original] (SDH) |
| Korean subtitle | Korean |
The label can be any text, for example `"| Original"` or a label in another language. Put it in
quotes: YAML reads an unquoted `[Original]` as a list, and an unquoted `| Original` stops the config
from loading. unshackle ignores a value that is not text.
The label also applies to a name that the service sets, and to audio that a service keeps inside the
video file. unshackle does not add the label when the name already contains its words, so a service
name `Original` or `Japanese (original)` stays as it is.
!!! tip "Use an English label with Jellyfin 12"
Jellyfin 12 adds its own "Original" to an original-language audio track from the flag, unless the
name already contains the word. It adds none to a subtitle. A label in another language, such as `[원어]`, then shows next to Jellyfin's
"Original".
!!! note "Players that show the language next to the name"
Some players, such as Jellyfin, show the track name and the language name together. They leave
out the language when the name already contains it, so an English name shows once. A native name
+2 -1
View File
@@ -63,7 +63,8 @@ directories:
The **automatic** 24 h-TTL refresh that happens during a normal `dl`/`search` run
**refuses to refresh and exits** (naming the offending clone) if that clone has
uncommitted changes to tracked files or unpushed local commits. Untracked files (new
service folders, `__pycache__`) never block it. The **manual**
service folders, `__pycache__`), Python bytecode (`.pyc`, `.pyo`, also when the repo
commits it) and `.DS_Store` never block it. The **manual**
`unshackle util refresh-services` command instead **hard-resets** the clone to upstream,
discarding any local edits.
+2 -1
View File
@@ -288,7 +288,8 @@ Matroska (MKV) muxing options.
| `default_language` | dict | `{}` | Force which language is flagged *default* per track type, e.g. `{audio: en, subtitle: en}`. A tag with a region, such as `en-US`, matches only that variant. |
| `merge_audio` | bool | `true` | Merge all audio into one file. `--split-audio` on the CLI flips this off. |
| `merge_video` | bool | `false` | Merge video tracks that share height, range, and codec into one file, so only language varies inside a file. `--merge-video` on the CLI flips this on. |
| `track_names` | str | `english` | The language of the name unshackle gives a track that the service left unnamed: `english` (`Chinese (Traditional)`) or `native`, the name in the language itself (`中文(繁體)`). Read [Track names and language tags](../../guide/output-and-naming.md#track-names-and-language-tags). |
| `track_names` | str | `english` | The language of the name unshackle gives a track that the service left unnamed: `english` (`Chinese (Traditional)`), `native`, the name in the language itself (`中文(繁體)`), or `none`, which leaves the track unnamed. Read [Track names and language tags](../../guide/output-and-naming.md#track-names-and-language-tags). |
| `original_label` | str | unset | Text that unshackle adds after the name of an audio or subtitle track in the title's original language, such as `[Original]`. Read [Track names and language tags](../../guide/output-and-naming.md#track-names-and-language-tags). |
| `concurrency` | int | `4` | How many mkvmerge processes run at the same time when a title muxes more than one output file (one per video variant or audio codec). Each process uses one CPU core, so this shortens the mux step on an SSD. Set it to `1` on a hard disk, where parallel writes are slower. |
```yaml
+57 -2
View File
@@ -3,6 +3,7 @@
import logging
import os
import sys
import weakref
import pytest
import requests
@@ -26,12 +27,31 @@ class Svc:
def fallback(self) -> requests.Session:
return run_proxy.fallback_session()
def helper_lookup(self, host: str) -> None:
Helper().lookup(host)
def helper_fallback(self) -> requests.Session:
return Helper().fallback()
class Helper:
"""A helper class of the service with its own HTTP session, which has no proxy."""
def __init__(self):
self.session = requests.Session()
def lookup(self, host: str) -> None:
lookup(host)
def fallback(self) -> requests.Session:
return run_proxy.fallback_session()
@pytest.fixture(autouse=True)
def watching(monkeypatch):
monkeypatch.setattr(run_proxy, "watched", {})
monkeypatch.setattr(run_proxy, "proxy_hosts", set())
monkeypatch.setattr(run_proxy, "warned", set())
monkeypatch.setattr(run_proxy, "warned", weakref.WeakKeyDictionary())
run_proxy.watch(Svc, PROXY)
@@ -109,7 +129,9 @@ def test_raw_socket_connect_to_a_host_name_warns(caplog, address, warns):
assert bool(leaks(caplog)) is warns
def test_core_frame_ends_the_walk(caplog):
def test_core_frame_ends_the_walk(caplog, monkeypatch):
"""A core lookup returns before the CDM host set is built, which a server does for every request it sends."""
monkeypatch.setattr(run_proxy, "cdm_hosts", lambda: pytest.fail("cdm_hosts() ran for a core lookup"))
with caplog.at_level(logging.WARNING):
source = "sys.audit('socket.getaddrinfo', 'vault.example', 443, 0, 0, 0)"
run_as(os.path.join(run_proxy.CORE_DIR, "core", "vaults.py"), source)
@@ -149,6 +171,39 @@ def test_service_instance_uses_the_proxy_of_its_own_run(caplog):
assert {r.name for r in caplog.records if r.getMessage() in leaks(caplog)} == {"Svc"}
def test_a_reloaded_service_class_uses_the_proxy_of_its_own_run(caplog):
"""A service reload makes a new class from the same directory; the watch still holds the old one."""
reloaded = type("Svc", (), {"__init__": Svc.__init__, "lookup": Svc.lookup})
with caplog.at_level(logging.WARNING):
reloaded().lookup("direct.example") # a run with no proxy
reloaded(PROXY).lookup("leak.example")
assert len(leaks(caplog)) == 1
assert "leak.example" in leaks(caplog)[0]
def test_a_subclass_of_the_service_uses_the_proxy_of_its_own_run(caplog):
sub = type("Sub", (Svc,), {})
with caplog.at_level(logging.WARNING):
sub().lookup("direct.example")
assert leaks(caplog) == []
def test_a_helper_session_without_proxy_does_not_hide_a_leak(caplog):
"""A helper class of the service is not the service instance, so the proxy of the run still decides."""
with caplog.at_level(logging.WARNING):
Svc(PROXY).helper_lookup("leak.example")
assert len(leaks(caplog)) == 1
assert Svc(PROXY).helper_fallback().proxies == {"all": PROXY}
def test_each_run_warns_even_when_a_finished_run_had_the_same_id(caplog):
"""CPython reuses the id of a freed instance, so the warned hosts belong to the instance itself."""
with caplog.at_level(logging.WARNING):
for _ in range(2):
Svc(PROXY).lookup("leak.example")
assert len(leaks(caplog)) == 2
def test_fallback_session_takes_the_proxy_of_the_calling_run():
session = Svc("http://own.example:1").fallback()
assert session.proxies == {"all": "http://own.example:1"}
+61 -1
View File
@@ -1,4 +1,4 @@
"""Unit tests for remote git service-repo resolution. No network, no real git."""
"""Unit tests for remote git service-repo resolution. No network; only the bytecode tests run a real git."""
from __future__ import annotations
@@ -245,6 +245,66 @@ def test_changed_services_up_to_date(monkeypatch):
assert service_repo.changed_services(Path("/x"), "same", "same") == []
@pytest.fixture
def bytecode_clone(tmp_path):
"""A clone of a repo that commits a ``.pyc``, with that ``.pyc`` rewritten as an import does."""
git = service_repo.binaries.Git
if not git:
pytest.skip("git not found")
upstream, dest = tmp_path / "upstream", tmp_path / "clone"
(upstream / "EXAMPLE" / "__pycache__").mkdir(parents=True)
(upstream / "EXAMPLE" / "__init__.py").write_text("X = 1\n")
(upstream / "EXAMPLE" / "__pycache__" / "__init__.cpython-312.pyc").write_bytes(b"old")
def run(*args: str, cwd: Path = upstream) -> None:
subprocess.run(
[git, "-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", *args],
cwd=cwd,
check=True,
capture_output=True,
)
run("init", "-q", "-b", "main")
run("add", "-A")
run("commit", "-qm", "init")
run("clone", "-q", str(upstream), str(dest), cwd=tmp_path)
(dest / "EXAMPLE" / "__pycache__" / "__init__.cpython-312.pyc").write_bytes(b"rewritten")
return upstream, dest, run
def test_rewritten_bytecode_does_not_block_pull(bytecode_clone, tmp_path):
upstream, dest, run = bytecode_clone
assert service_repo.is_dirty(dest) is False
assert service_repo.local_dirty_services(dest) == []
(upstream / "EXAMPLE" / "__init__.py").write_text("X = 2\n")
(upstream / "EXAMPLE" / "__pycache__" / "__init__.cpython-312.pyc").write_bytes(b"new")
run("commit", "-qam", "update")
service_repo.pull(dest, tmp_path / "stamp")
assert (dest / "EXAMPLE" / "__init__.py").read_text() == "X = 2\n"
def test_source_edit_still_dirty_beside_bytecode(bytecode_clone):
_, dest, _ = bytecode_clone
(dest / "EXAMPLE" / "__init__.py").write_text("X = 3\n")
assert service_repo.is_dirty(dest) is True
assert service_repo.local_dirty_services(dest) == ["EXAMPLE"]
def test_untracked_bytecode_does_not_block_pull(bytecode_clone, tmp_path):
upstream, dest, run = bytecode_clone
(dest / "EXAMPLE" / "__pycache__" / "__init__.cpython-314.pyc").write_bytes(b"local")
(dest / "OTHER").mkdir()
(dest / "OTHER" / "__init__.py").write_text("")
(dest / "OTHER" / "__init__.cpython-314-x86_64-linux-gnu.so").write_bytes(b"compiled")
(upstream / "EXAMPLE" / "__init__.py").write_text("X = 2\n")
(upstream / "EXAMPLE" / "__pycache__" / "__init__.cpython-314.pyc").write_bytes(b"upstream")
run("add", "-A")
run("commit", "-qm", "update")
service_repo.pull(dest, tmp_path / "stamp")
assert (dest / "EXAMPLE" / "__init__.py").read_text() == "X = 2\n"
assert (dest / "OTHER" / "__init__.cpython-314-x86_64-linux-gnu.so").read_bytes() == b"compiled"
@pytest.mark.parametrize("order", [["a", "b"], ["b", "a"]])
def test_collision_first_source_wins(tmp_path, order):
"""Discovery dedupes by tag honoring list order: the FIRST source to define a tag wins,
+62 -2
View File
@@ -3,14 +3,23 @@ from typing import Callable, Optional
import pytest
from langcodes import Language
from rich.text import Text
from unshackle.core.config import config
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.utilities import language_name, multi_script_languages, with_script
def sub(lang: str, name: Optional[str] = None, sdh: bool = False) -> Subtitle:
return Subtitle(id_="s", url="https://x/s", codec=Subtitle.Codec.WebVTT, language=lang, name=name, sdh=sdh)
def sub(lang: str, name: Optional[str] = None, sdh: bool = False, original: bool = False) -> Subtitle:
return Subtitle(
id_="s",
url="https://x/s",
codec=Subtitle.Codec.WebVTT,
language=lang,
name=name,
sdh=sdh,
is_original_lang=original,
)
def test_multi_script_languages_come_from_cldr() -> None:
@@ -107,6 +116,57 @@ def test_native_subtitle_name_keeps_the_flag(monkeypatch: pytest.MonkeyPatch) ->
assert sub("zh", name="Mandarin").get_track_name() == "Mandarin"
def test_no_language_name_when_track_names_is_none(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"track_names": "none"})
assert sub("en").get_track_name() is None
assert sub("en", sdh=True).get_track_name() == "SDH"
assert sub("en", name="English [Full]").get_track_name() == "English [Full]"
video = Video(id_="v", url="https://x/v", codec=Video.Codec.AVC, language="en")
video.data["audio_language"] = "en"
assert video.embedded_audio_name() == ""
@pytest.mark.parametrize(
("muxing", "track", "expected"),
[
({"original_label": "[Original]"}, sub("ja", sdh=True, original=True), "Japanese [Original] (SDH)"),
({"original_label": "[Original]"}, sub("ko"), "Korean"),
({"original_label": "| Original", "track_names": "none"}, sub("ja", original=True), "| Original"),
],
)
def test_original_label_follows_the_name_of_an_original_language_track(
muxing: dict, track: Subtitle, expected: str, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(config, "muxing", muxing)
assert track.get_track_name() == expected
@pytest.mark.parametrize("name", ["Original", "Japanese [Original]", "Japanese (original)"])
def test_original_label_is_not_added_twice(name: str, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"original_label": "[Original]"})
assert sub("ja", name=name, original=True).get_track_name() == name
@pytest.mark.parametrize("label", [True, 1, ["Original"], " "])
def test_original_label_that_is_not_text_is_ignored(label: object, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"original_label": label, "track_names": "none"})
assert sub("ja", sdh=True, original=True).get_track_name() == "SDH"
def test_embedded_audio_takes_the_original_label(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"original_label": "[Original]"})
video = Video(id_="v", url="https://x/v", codec=Video.Codec.AVC, language="ja", is_original_lang=True)
video.data["audio_language"] = "ja"
assert video.embedded_audio_name() == "Japanese [Original]"
def test_track_list_shows_a_bracketed_label_as_text(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"original_label": "[/]"})
tree = Tracks([sub("ja", original=True)]).tree()[0]
labels = [Text.from_markup(node.label).plain for node in tree.children[0].children]
assert labels == ["[VTT] | ja | Japanese [/]"]
def test_subtitle_names_and_tags_the_script_but_keeps_its_language() -> None:
track = sub("zh-TW")
assert track.name is None
+5 -2
View File
@@ -49,8 +49,11 @@ class Cacher:
@property
def expired(self) -> bool:
"""Compare as unix time: wall-clock comparison is wrong for an hour at each DST change."""
return bool(self.expiration and self.expiration.timestamp() < time.time())
"""
Compare as unix time: wall-clock comparison is wrong for an hour at each DST change.
The 1 µs allowance covers datetime rounding the expiry up past a coarse clock (15.6 ms on Windows).
"""
return bool(self.expiration and self.expiration.timestamp() < time.time() + 1e-6)
def get(self, key: str, version: int = 1) -> Cacher:
"""
+22 -66
View File
@@ -32,57 +32,24 @@ def stamp_for(dest: Path) -> Path:
SHORTHAND_RE = re.compile(r"^[\w.-]+/[\w.-]+$")
# Importing services rewrites tracked bytecode when upstream mistakenly commits
# ``__pycache__`` (e.g. playtv). That must not block refresh / look like source edits.
_JUNK_NAME_SUFFIXES = (".pyc", ".pyo")
_JUNK_BASENAMES = frozenset({".DS_Store"})
def is_junk_path(path: str) -> bool:
"""True for import/OS noise that is never a meaningful service-source edit."""
normalized = path.replace("\\", "/").strip()
if not normalized:
return False
parts = normalized.split("/")
if "__pycache__" in parts:
return True
name = parts[-1]
if name in _JUNK_BASENAMES:
return True
return name.endswith(_JUNK_NAME_SUFFIXES)
def porcelain_paths(porcelain: str) -> list[str]:
"""Paths from ``git status --porcelain`` lines (handles rename ``old -> new``)."""
paths: list[str] = []
for raw in porcelain.splitlines():
if len(raw) < 4:
continue
# XY<space>path or XY<space>old -> new
entry = raw[3:]
if " -> " in entry:
entry = entry.split(" -> ", 1)[1]
# quoted paths are rare here; strip optional quotes
if len(entry) >= 2 and entry[0] == entry[-1] == '"':
entry = entry[1:-1]
paths.append(entry)
return paths
JUNK_GLOBS = ("**/__pycache__/**", "**/*.pyc", "**/*.pyo", "**/.DS_Store")
JUNK = tuple(f":(glob){g}" for g in JUNK_GLOBS)
NOT_JUNK = (".", *(f":(exclude,glob){g}" for g in JUNK_GLOBS))
def discard_junk_workdir(dest: Path) -> None:
"""Restore tracked junk paths so ``git pull`` is not blocked by rewritten ``.pyc`` files."""
if not binaries.Git:
return
"""Restore tracked bytecode the import rewrote and delete untracked ``__pycache__`` files, so
neither can block ``git pull --ff-only``. It never touches compiled ``.so``/``.pyd`` modules."""
git = str(binaries.Git)
status = subprocess.run(
[git, "-C", str(dest), "status", "--porcelain", "--untracked-files=no"], capture_output=True
subprocess.run([git, "-C", str(dest), "clean", "-fdqx", "--", JUNK[0]], capture_output=True) # nosec B603
changed = subprocess.run([git, "-C", str(dest), "diff", "--name-only", "-z", "--", *JUNK], capture_output=True) # nosec B603
if not changed.stdout:
return
subprocess.run(
[git, "--literal-pathspecs", "-C", str(dest), "checkout", "--pathspec-from-file=-", "--pathspec-file-nul"],
input=changed.stdout,
capture_output=True,
) # nosec B603
if status.returncode != 0 or not status.stdout.strip():
return
junk = [p for p in porcelain_paths(status.stdout.decode(errors="ignore")) if is_junk_path(p)]
if not junk:
return
subprocess.run([git, "-C", str(dest), "checkout", "--", *junk], capture_output=True) # nosec B603
def is_repo_spec(value: object) -> bool:
@@ -173,8 +140,6 @@ def pull(dest: Path, stamp: Path) -> None:
if not binaries.Git:
write_stamp(stamp)
return
# Drop rewritten bytecode before the dirty check / pull so a tracked ``.pyc`` cannot
# false-trigger DirtyServiceRepo or block ``git pull --ff-only``.
discard_junk_workdir(dest)
# never clobber local edits: refuse to refresh a dirty clone and let the caller exit cleanly
if is_dirty(dest):
@@ -215,16 +180,12 @@ def head(dest: Path) -> Optional[str]:
def local_dirty_services(dest: Path) -> list[str]:
"""Top-level service dirs with uncommitted edits to tracked files (lost on a force reset)."""
r = subprocess.run([str(binaries.Git), "-C", str(dest), "diff", "--name-only", "HEAD"], capture_output=True) # nosec B603
r = subprocess.run(
[str(binaries.Git), "-C", str(dest), "diff", "--name-only", "HEAD", "--", *NOT_JUNK], capture_output=True
) # nosec B603
if r.returncode != 0:
return []
return sorted(
{
line.split("/")[0]
for line in r.stdout.decode(errors="ignore").splitlines()
if line and not is_junk_path(line)
}
)
return sorted({line.split("/")[0] for line in r.stdout.decode(errors="ignore").splitlines() if line})
def changed_services(dest: Path, old: Optional[str], new: Optional[str]) -> list[str]:
@@ -266,20 +227,15 @@ def force_sync(dest: Path, stamp: Path) -> None:
def is_dirty(dest: Path) -> bool:
"""True if the clone has uncommitted edits to tracked files or local commits not on its upstream.
Ignores untracked files (``git pull`` does not remove them) and tracked import/OS noise
(``__pycache__/``, ``*.pyc`` / ``*.pyo``, ``.DS_Store``). Upstream sometimes commits a
``.pyc``; importing under another interpreter rewrites it and must not look like a
service-source edit.
This function ignores untracked files, tracked bytecode and ``.DS_Store``: importing a service
rewrites a committed ``.pyc`` whose source modification time changed on checkout.
"""
git = str(binaries.Git)
# modifications to tracked files only (--untracked-files=no skips untracked __pycache__ etc.)
status = subprocess.run(
[git, "-C", str(dest), "status", "--porcelain", "--untracked-files=no"], capture_output=True
[git, "-C", str(dest), "status", "--porcelain", "--untracked-files=no", "--", *NOT_JUNK], capture_output=True
) # nosec B603
if status.returncode == 0:
meaningful = [p for p in porcelain_paths(status.stdout.decode(errors="ignore")) if not is_junk_path(p)]
if meaningful:
return True
if status.returncode == 0 and status.stdout.strip():
return True
# local commits ahead of upstream (committed but not pushed); no upstream → treat as clean
ahead = subprocess.run([git, "-C", str(dest), "rev-list", "--count", "@{u}..HEAD"], capture_output=True) # nosec B603
if ahead.returncode == 0:
-4
View File
@@ -28,10 +28,6 @@ log = logging.getLogger("services")
DIRTY_REPOS: list[str] = []
SHADOWED: list[str] = []
# Service clones live inside the tree; writing bytecode there rewrites tracked ``.pyc``
# files (when upstream committed them) and floods untracked ``__pycache__`` dirs.
sys.dont_write_bytecode = True
def discover_services() -> tuple[list[Path], list[str]]:
"""Resolve the configured service dirs and glob every ``TAG/__init__.py``.
+20 -2
View File
@@ -1019,11 +1019,29 @@ class Track:
def embedded_audio_name(self) -> str:
"""Name the audio a service keeps inside this track's file, by its language when the service set none."""
lang = self.data["audio_language"]
return self.data.get("audio_language_name") or language_name(Language.get(lang)) or lang
name = self.data.get("audio_language_name")
if not name and config.muxing.get("track_names") != "none":
name = language_name(Language.get(lang)) or lang
return self.with_original_label(name) or ""
def get_track_name(self) -> Optional[str]:
"""Get the Track Name, or the name of its language when the service set none."""
return self.name if self.name is not None else language_name(self.mux_language)
name = self.name
if name is None and config.muxing.get("track_names") != "none":
name = language_name(self.mux_language)
return self.with_original_label(name)
def with_original_label(self, name: Optional[str]) -> Optional[str]:
"""Add `muxing.original_label` to the name of a track in the title's original language,
unless the name already contains the label's words."""
label = config.muxing.get("original_label")
label = label.strip() if isinstance(label, str) else ""
if not label or not self.is_original_lang:
return name
words = re.sub(r"[\W_]+", " ", label).strip() or label
if name and words.casefold() in name.casefold():
return name
return f"{name} {label}" if name else label
def get_drm_for_cdm(self, cdm: Optional[object]) -> Optional[DRM_T]:
"""Return the DRM matching the provided CDM, if available."""
+3 -2
View File
@@ -12,6 +12,7 @@ from pathlib import Path
from typing import Any, Callable, Iterator, Optional, Sequence, Union
from langcodes import Language
from rich.markup import escape
from rich.progress import Progress, SpinnerColumn, TaskID, TextColumn, TimeRemainingColumn
from rich.table import Table
from rich.tree import Tree
@@ -190,11 +191,11 @@ class Tracks:
progress_callables.append(update_track_progress)
track_table = Table.grid()
track_table.add_row(str(track)[6:], style="text2")
track_table.add_row(escape(str(track)[6:]), style="text2")
track_table.add_row(progress)
tracks_tree.add(track_table)
else:
tracks_tree.add(str(track)[6:], style="text2")
tracks_tree.add(escape(str(track)[6:]), style="text2")
# Show Closed Captions right after Subtitles (even if no subtitle tracks exist)
if track_type is Subtitle:
+13 -7
View File
@@ -10,6 +10,7 @@ import ipaddress
import logging
import os
import sys
import weakref
from dataclasses import dataclass, field
from types import FrameType
from typing import Any, Optional
@@ -30,7 +31,7 @@ class Watch:
watched: dict[str, Watch] = {} # service directory -> Watch
proxy_hosts: set[str] = set()
warned: set[tuple[str, str, int]] = set()
warned: weakref.WeakKeyDictionary[Any, set[str]] = weakref.WeakKeyDictionary()
hook_installed = False
@@ -99,10 +100,15 @@ def instance_of(frame: Optional[FrameType], entry: Watch) -> Any:
"""The service instance nearest to ``frame``, which knows the proxy of its own run.
The walk goes on past helper functions of the service, which have no ``self``.
It matches the class by module and qualified name, because a service reload makes a new class
that ``entry.cls`` is not.
"""
name = (entry.cls.__module__, entry.cls.__qualname__)
while frame is not None:
inst = frame.f_locals.get("self")
if isinstance(inst, entry.cls) and getattr(inst, "session", None) is not None:
if getattr(inst, "session", None) is not None and any(
(c.__module__, c.__qualname__) == name for c in type(inst).__mro__
):
return inst
frame = frame.f_back
return None
@@ -184,10 +190,10 @@ def check(host: Any, frame: Optional[FrameType]) -> None:
if isinstance(host, bytes):
host = host.decode(errors="replace")
host = str(host or "").lower().strip("[]")
if not host or is_local(host) or host in proxy_hosts or host in cdm_hosts():
if not host or is_local(host) or host in proxy_hosts:
return
found = find_service(frame, through_core=False)
if not found:
if not found or host in cdm_hosts():
return
service_frame, entry = found
while frame is not None and frame is not service_frame:
@@ -198,10 +204,10 @@ def check(host: Any, frame: Optional[FrameType]) -> None:
inst = instance_of(service_frame, entry)
if inst is not None and not proxy_of(getattr(inst, "session", None)):
return
key = (entry.cls.__name__, host, id(inst))
if key in warned:
hosts = warned.setdefault(entry.cls if inst is None else inst, set())
if host in hosts:
return
warned.add(key)
hosts.add(host)
# a service instance logs through self.log, which a remote session mirrors to its client
log = getattr(inst, "log", None) or logging.getLogger(entry.cls.__name__)
where = os.path.relpath(service_frame.f_code.co_filename, os.path.dirname(entry.directory[:-1]))