mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-24 18:05:07 +00:00
Compare commits
7
Commits
83514d12fe
...
cd9785d406
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd9785d406 | ||
|
|
866420ed67 | ||
|
|
0de069f35a | ||
|
|
bcef9ff87a | ||
|
|
1036528fa3 | ||
|
|
ecf17baffe | ||
|
|
1175035317 |
@@ -333,7 +333,7 @@ When you give both `season` and `episode`, the server combines them into a `"{se
|
||||
"resolution": "2160p", "fps": "24", "range": "HDR10",
|
||||
"range_display": "HDR10", "scan_type": null, "closed_captions": [],
|
||||
"dv_compatible_bitstream": false, "hdr10plus": false, "language": "en", "is_original_lang": true,
|
||||
"name": null, "needs_repack": false, "edition": [], "data": null,
|
||||
"name": null, "track_name": "English", "needs_repack": false, "edition": [], "data": null,
|
||||
"drm": [], "descriptor": "DASH"
|
||||
}
|
||||
],
|
||||
@@ -342,14 +342,14 @@ When you give both `season` and `episode`, the server combines them into a `"{se
|
||||
"id": "a-1", "codec": "EC3", "codec_display": "DD+",
|
||||
"bitrate": 640, "bitrate_bps": 640000, "channels": "5.1", "language": "en",
|
||||
"is_original": true, "is_original_lang": true, "atmos": false, "joc": 0,
|
||||
"descriptive": false, "name": null, "needs_repack": false, "edition": [],
|
||||
"descriptive": false, "name": null, "track_name": "English", "needs_repack": false, "edition": [],
|
||||
"data": null, "drm": [], "descriptor": "DASH"
|
||||
}
|
||||
],
|
||||
"subtitles": [
|
||||
{ "id": "s-1", "codec": "vtt", "language": "en",
|
||||
"forced": false, "sdh": false, "cc": false, "is_original_lang": false,
|
||||
"name": null, "needs_repack": false, "edition": [], "data": null,
|
||||
"name": null, "track_name": "English", "needs_repack": false, "edition": [], "data": null,
|
||||
"drm": [], "descriptor": "DASH" }
|
||||
]
|
||||
}
|
||||
@@ -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`. `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`), 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.
|
||||
|
||||
| Status | Error code | Meaning |
|
||||
| --- | --- | --- |
|
||||
|
||||
@@ -284,6 +284,50 @@ warning and continues.
|
||||
!!! note "Height channels"
|
||||
A track with height channels is named bed.LFE.heights, such as `5.1.4`.
|
||||
|
||||
### Track names and language tags
|
||||
|
||||
When the service gives a track no name, unshackle names it with the English name of its language,
|
||||
such as `English`, `Portuguese (Portugal)` or `Spanish (Latin America)`. The name leaves out the
|
||||
region that is the default for the language, so `en-US` is `English` and `pt-BR` is `Portuguese`,
|
||||
but `en-GB` is `English (United Kingdom)`. A name from the service is kept as is. unshackle adds the SDH, CC, Forced or Descriptive label after either name.
|
||||
|
||||
A subtitle in a language with more than one script gets the script from its region:
|
||||
|
||||
| Service tag | Tag in the file | Track name |
|
||||
|-------------|-----------------|------------|
|
||||
| `zh-TW` | `zh-Hant-TW` | Chinese (Traditional) |
|
||||
| `zh-HK` | `zh-Hant-HK` | Chinese (Traditional, Hong Kong) |
|
||||
| `zh-CN` | `zh-Hans-CN` | Chinese (Simplified) |
|
||||
| `sr-ME` | `sr-Latn-ME` | Serbian (Latin, Montenegro) |
|
||||
| `zh` | `zh` | Chinese |
|
||||
|
||||
A tag without a region, such as `zh`, gets no script because the region is what tells the script.
|
||||
unshackle writes audio tags as the service gives them, because a script applies only to written text.
|
||||
Track selection, `--list` tags and file names use the service tag.
|
||||
|
||||
Set `muxing.track_names` to `native` to name each track in its own language. The same rules apply
|
||||
to the script and the region:
|
||||
|
||||
```yaml title="unshackle.yaml"
|
||||
muxing:
|
||||
track_names: native
|
||||
```
|
||||
|
||||
| Service tag | Track name |
|
||||
|-------------|------------|
|
||||
| `zh-TW` subtitle | 中文(繁體) |
|
||||
| `zh-HK` subtitle | 中文(繁體,香港) |
|
||||
| `pt-PT` | Português (Portugal) |
|
||||
| `es-419` | Español (Latinoamérica) |
|
||||
| `ja-JP` | 日本語 |
|
||||
|
||||
The option also changes the names in `--list` and in the `track_name` field of the REST API.
|
||||
|
||||
!!! 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
|
||||
such as `日本語` shows next to `Japanese` in an English interface.
|
||||
|
||||
### DTS:X Profile 2 output
|
||||
|
||||
A title whose audio holds a `dtsx` or `dtsy` sample entry (DTS:X Profile 2, DTS-UHD) muxes
|
||||
|
||||
@@ -288,6 +288,7 @@ 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). |
|
||||
| `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
|
||||
|
||||
+34
-1
@@ -4,10 +4,13 @@ from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import socketserver
|
||||
from typing import Any
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.update_checker import UpdateChecker
|
||||
|
||||
# shutdown() blocks until the serve loop polls again, and the 0.5s default is paid by every
|
||||
@@ -38,3 +41,33 @@ def no_update_check(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(UpdateChecker, "check_for_updates", no_release)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def default_muxing(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Mux with the default options, whatever the muxing block of the local unshackle.yaml sets."""
|
||||
monkeypatch.setattr(config, "muxing", {})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mux_args(monkeypatch: pytest.MonkeyPatch) -> Callable[..., list[str]]:
|
||||
"""Run Tracks.mux up to mkvmerge and return its arguments; ``ids`` is what the track ID probe reports."""
|
||||
|
||||
class Stop(Exception):
|
||||
pass
|
||||
|
||||
def run(tracks: Any, ids: Optional[dict[str, int]] = None, **kwargs: Any) -> list[str]:
|
||||
captured: list[list[str]] = []
|
||||
|
||||
def fake_popen(args: list[str], **_: object) -> None:
|
||||
captured.append(args)
|
||||
raise Stop
|
||||
|
||||
monkeypatch.setattr("unshackle.core.tracks.tracks.subprocess.Popen", fake_popen)
|
||||
monkeypatch.setattr("unshackle.core.tracks.tracks.file_track_ids", lambda path: ids or {"video": 0})
|
||||
monkeypatch.setattr(binaries, "MKVToolNix", Path("mkvmerge"))
|
||||
with pytest.raises(Stop):
|
||||
tracks.mux("Title", delete=False, **kwargs)
|
||||
return captured[0]
|
||||
|
||||
return run
|
||||
|
||||
@@ -22,3 +22,8 @@ def test_panel_pads_an_indic_label_to_the_border() -> None:
|
||||
Console(file=out, width=20, color_system=None).print(Panel("हिंदी"))
|
||||
|
||||
assert out.getvalue().splitlines()[1] == "│ हिंदी" + " " * 12 + " │"
|
||||
|
||||
|
||||
def test_a_virama_conjunct_shares_one_cell() -> None:
|
||||
assert cell_len("हिन्दी") == 4 # न्द is one conjunct
|
||||
assert cell_len("ಕನ್ನಡ") == 4 # a Kannada virama does not join, so ನ್ನ keeps two cells
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from unshackle.core.manifests.dash import DASH
|
||||
|
||||
CAPTION = '<Role schemeIdUri="urn:mpeg:dash:role:2011" value="caption"/>'
|
||||
SDH = '<Accessibility schemeIdUri="urn:tva:metadata:cs:AudioPurposeCS:2007" value="2"/>'
|
||||
|
||||
|
||||
def test_caption_role_is_closed_caption() -> None:
|
||||
element = ET.fromstring(f"<AdaptationSet>{CAPTION}</AdaptationSet>")
|
||||
assert DASH.is_closed_caption(element) is True
|
||||
assert DASH.is_sdh(element) is False
|
||||
|
||||
|
||||
def test_caption_role_with_sdh_value_is_sdh_only() -> None:
|
||||
# a Subtitle cannot be both CC and SDH, so a set marked both used to fail the whole title
|
||||
element = ET.fromstring(f"<AdaptationSet>{CAPTION}{SDH}</AdaptationSet>")
|
||||
assert DASH.is_closed_caption(element) is False
|
||||
assert DASH.is_sdh(element) is True
|
||||
@@ -150,6 +150,30 @@ def test_substation_alpha_subtitles_are_left_out(tmp_path: Path, monkeypatch: py
|
||||
assert "s.vtt:lang=es" in command
|
||||
|
||||
|
||||
def test_mp4_subtitles_get_the_script_their_region_implies(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
captured: list[FakePopen] = []
|
||||
|
||||
def fake_popen(args: list[str], **kwargs: object) -> FakePopen:
|
||||
p = FakePopen(args, **kwargs)
|
||||
captured.append(p)
|
||||
Path(args[-1]).write_bytes(b"muxed")
|
||||
return p
|
||||
|
||||
monkeypatch.setattr(binaries, "MP4Box", Path("MP4Box"), raising=False)
|
||||
monkeypatch.setattr(subprocess, "Popen", fake_popen)
|
||||
|
||||
tracks = build_tracks(tmp_path, b"dtsx")
|
||||
vtt = Subtitle(id_="s1", url="https://x/s", codec=Subtitle.Codec.WebVTT, language="zh-TW")
|
||||
vtt.path = tmp_path / "s.vtt"
|
||||
vtt.path.write_text("WEBVTT\n")
|
||||
tracks.add(vtt)
|
||||
|
||||
tracks.mux("Title", delete=False, output_path=tmp_path / "out.muxed.mkv")
|
||||
command = captured[0].args
|
||||
assert f"{tmp_path / 's.vtt'}:lang=zh-Hant-TW" in command
|
||||
assert any(arg.endswith("=Chinese (Traditional)") for arg in command)
|
||||
|
||||
|
||||
def test_mp4box_errors_come_back_to_the_caller(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""A failed mux does not raise; the caller inspects the return code and lines."""
|
||||
|
||||
|
||||
+20
-25
@@ -8,7 +8,7 @@ import struct
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Optional
|
||||
from typing import Callable, Optional
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import click
|
||||
@@ -16,7 +16,6 @@ import pytest
|
||||
from requests import Session
|
||||
|
||||
from unshackle.commands.dl import sample_name
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.manifests.dash import DASH
|
||||
@@ -231,19 +230,7 @@ def test_subtitle_trim_leaves_an_unreadable_file_whole(tmp_path: Path) -> None:
|
||||
assert subtitle.path.read_bytes() == b"\x00\x01not a subtitle"
|
||||
|
||||
|
||||
def mux_command(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> list[str]:
|
||||
class Stop(Exception):
|
||||
pass
|
||||
|
||||
captured: list[list[str]] = []
|
||||
|
||||
def fake_popen(args: list[str], **kwargs: object) -> None:
|
||||
captured.append(args)
|
||||
raise Stop
|
||||
|
||||
monkeypatch.setattr("unshackle.core.tracks.tracks.subprocess.Popen", fake_popen)
|
||||
monkeypatch.setattr(binaries, "MKVToolNix", Path("mkvmerge"))
|
||||
|
||||
def mux_command(tmp_path: Path, mux_args: Callable[..., list[str]]) -> list[str]:
|
||||
video, audio = make_video(), make_audio()
|
||||
trimmed = Subtitle(id_="s1", url="https://x/s1", codec=Subtitle.Codec.SubRip, language="en")
|
||||
whole = Subtitle(id_="s2", url="https://x/s2", codec=Subtitle.Codec.SubRip, language="fr")
|
||||
@@ -254,14 +241,14 @@ def mux_command(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> list[str]:
|
||||
tracks = Tracks([video, audio, trimmed, whole])
|
||||
tracks.chapters.add(Chapter("00:02:05.000", "Scene"))
|
||||
|
||||
with pytest.raises(Stop):
|
||||
tracks.mux("Title", delete=False, progress=lambda **k: None, output_path=tmp_path / "out.mkv")
|
||||
return captured[0]
|
||||
return mux_args(tracks, progress=lambda **k: None, output_path=tmp_path / "out.mkv")
|
||||
|
||||
|
||||
def test_the_mux_shifts_each_track_and_cuts_to_the_window(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def test_the_mux_shifts_each_track_and_cuts_to_the_window(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mux_args: Callable[..., list[str]]
|
||||
) -> None:
|
||||
monkeypatch.setattr(config, "sample", (121, 181))
|
||||
command = mux_command(tmp_path, monkeypatch)
|
||||
command = mux_command(tmp_path, mux_args)
|
||||
|
||||
def sync_before(name: str) -> str:
|
||||
file_at = command.index(str(tmp_path / name))
|
||||
@@ -273,17 +260,19 @@ def test_the_mux_shifts_each_track_and_cuts_to_the_window(tmp_path: Path, monkey
|
||||
return command[sync_at + 1]
|
||||
|
||||
assert command[command.index("--split") + 1] == "parts:1.500s-61.500s"
|
||||
assert sync_before("v.mp4") == "0:500"
|
||||
assert sync_before("v.mp4") == "-1:500"
|
||||
assert "--sync" not in command[: command.index(str(tmp_path / "a.mp4"))][-12:], "the earliest track is not moved"
|
||||
assert sync_before("s1.srt") == "0:1500"
|
||||
assert sync_before("s2.srt") == "0:-119500"
|
||||
assert sync_before("s1.srt") == "-1:1500"
|
||||
assert sync_before("s2.srt") == "-1:-119500"
|
||||
assert command[command.index("--chapter-sync") + 1] == "-119500"
|
||||
assert command.index("--chapter-sync") < command.index("--chapters")
|
||||
|
||||
|
||||
def test_a_full_download_adds_no_sample_options(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def test_a_full_download_adds_no_sample_options(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mux_args: Callable[..., list[str]]
|
||||
) -> None:
|
||||
monkeypatch.setattr(config, "sample", None)
|
||||
command = mux_command(tmp_path, monkeypatch)
|
||||
command = mux_command(tmp_path, mux_args)
|
||||
assert not {"--split", "--sync", "--chapter-sync"} & set(command)
|
||||
|
||||
|
||||
@@ -356,6 +345,12 @@ def test_parse_sidx_refuses_what_it_cannot_cut() -> None:
|
||||
assert parse_sidx(sidx_box(count=3)[:-4], 0) == (0, [])
|
||||
|
||||
|
||||
def test_parse_sidx_refuses_a_box_that_counts_more_references_than_it_holds() -> None:
|
||||
box = bytearray(sidx_box(count=3))
|
||||
box[30:32] = (5).to_bytes(2, "big")
|
||||
assert parse_sidx(bytes(box) + bytes(100), 0) == (0, [])
|
||||
|
||||
|
||||
def test_a_single_file_dash_track_is_cut_by_its_segment_index(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
box = sidx_box()
|
||||
requested: list[str] = []
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.tracks import Tracks, Video
|
||||
from unshackle.core.tracks.tracks import file_track_ids
|
||||
|
||||
|
||||
def make_video(track_id: str, **data) -> Video:
|
||||
@@ -19,6 +23,12 @@ def make_video(track_id: str, **data) -> Video:
|
||||
return video
|
||||
|
||||
|
||||
def downloaded(video: Video, tmp_path) -> Video:
|
||||
video.path = tmp_path / "v.ts"
|
||||
video.path.write_bytes(b"\x00" * 16)
|
||||
return video
|
||||
|
||||
|
||||
def mux_until_mkvmerge_check(tracks: Tracks) -> None:
|
||||
# the embedded-audio metadata pass runs before the mkvmerge lookup, so a missing
|
||||
# binary stops the mux right after the state under test has been written
|
||||
@@ -35,7 +45,7 @@ def test_names_undeclared_video(monkeypatch):
|
||||
|
||||
assert video.needs_repack
|
||||
assert video.data["audio_language"] == "zh"
|
||||
assert video.data["audio_language_name"] == "Chinese"
|
||||
assert video.embedded_audio_name() == "Chinese"
|
||||
|
||||
|
||||
def test_service_declaration_is_preserved(monkeypatch):
|
||||
@@ -50,3 +60,36 @@ def test_service_declaration_is_preserved(monkeypatch):
|
||||
assert declared.data["audio_language_name"] == "Thai [Original]"
|
||||
assert not declared.needs_repack
|
||||
assert undeclared.data["audio_language"] == "zh"
|
||||
|
||||
|
||||
def test_embedded_audio_without_a_name_gets_the_language_name(tmp_path, mux_args):
|
||||
args = mux_args(Tracks(downloaded(make_video("v1", audio_language="pt-BR"), tmp_path)), {"video": 0, "audio": 1})
|
||||
assert args[args.index("--track-name") + 1] == "1:Portuguese"
|
||||
|
||||
|
||||
def test_embedded_audio_options_use_the_file_track_ids(tmp_path, mux_args):
|
||||
video = make_video("v1", audio_language="ko", audio_language_name="Korean")
|
||||
args = mux_args(Tracks(downloaded(video, tmp_path)), {"audio": 0, "video": 1})
|
||||
assert args[args.index("--track-name") + 1] == "0:Korean"
|
||||
original = f"{video.is_original_lang}"
|
||||
assert [args[i + 1] for i, arg in enumerate(args) if arg == "--original-flag"] == [f"1:{original}", f"0:{original}"]
|
||||
assert "0:ko" in args and "1:zh" in args
|
||||
|
||||
|
||||
def test_embedded_audio_options_are_left_out_when_the_file_has_no_audio(tmp_path, mux_args):
|
||||
args = mux_args(Tracks(downloaded(make_video("v1", audio_language="ko"), tmp_path)), {"video": 0})
|
||||
assert "--track-name" not in args
|
||||
|
||||
|
||||
def test_repack_and_mux_share_the_embedded_audio_name():
|
||||
assert make_video("v1", audio_language="zh").embedded_audio_name() == "Chinese"
|
||||
assert make_video("v1", audio_language="zh", audio_language_name="Mandarin").embedded_audio_name() == "Mandarin"
|
||||
|
||||
|
||||
def test_file_track_ids_reads_the_first_id_of_each_type(monkeypatch, tmp_path):
|
||||
tracks = [{"id": 0, "type": "audio"}, {"id": 1, "type": "video"}, {"id": 2, "type": "audio"}]
|
||||
reply = SimpleNamespace(stdout=json.dumps({"tracks": tracks}))
|
||||
monkeypatch.setattr("unshackle.core.tracks.tracks.subprocess.run", lambda *a, **k: reply)
|
||||
assert file_track_ids(tmp_path / "v.ts") == {"audio": 0, "video": 1}
|
||||
monkeypatch.setattr("unshackle.core.tracks.tracks.subprocess.run", lambda *a, **k: SimpleNamespace(stdout=""))
|
||||
assert file_track_ids(tmp_path / "v.ts") == {"video": 0, "audio": 1}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable, Optional
|
||||
|
||||
import pytest
|
||||
from langcodes import Language
|
||||
|
||||
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 test_multi_script_languages_come_from_cldr() -> None:
|
||||
assert {"zh", "yue", "sr"} <= multi_script_languages()
|
||||
assert not {"en", "pt", "ja"} & multi_script_languages()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("tag", "expected"),
|
||||
[
|
||||
("zh", "zh"),
|
||||
("zh-TW", "zh-Hant-TW"),
|
||||
("zh-CN", "zh-Hans-CN"),
|
||||
("zh-HK", "zh-Hant-HK"),
|
||||
("zh-SG", "zh-Hans-SG"),
|
||||
("zh-Hant", "zh-Hant"),
|
||||
("yue-HK", "yue-Hant-HK"),
|
||||
("sr-ME", "sr-Latn-ME"),
|
||||
("sr-RS", "sr-Cyrl-RS"),
|
||||
("pa-PK", "pa-Arab-PK"),
|
||||
("ms-MY", "ms-MY"),
|
||||
("en-US", "en-US"),
|
||||
("und-TW", "und-TW"),
|
||||
("und", "und"),
|
||||
],
|
||||
)
|
||||
def test_with_script(tag: str, expected: str) -> None:
|
||||
assert str(with_script(Language.get(tag))) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("tag", "expected"),
|
||||
[
|
||||
("zh-Hant-TW", "Chinese (Traditional)"),
|
||||
("zh-Hans-CN", "Chinese (Simplified)"),
|
||||
("zh-Hant-HK", "Chinese (Traditional, Hong Kong)"),
|
||||
("zh-TW", "Chinese (Taiwan)"),
|
||||
("pt-BR", "Portuguese"),
|
||||
("pt-PT", "Portuguese (Portugal)"),
|
||||
("en-US", "English"),
|
||||
("en-GB", "English (United Kingdom)"),
|
||||
("ja-JP", "Japanese"),
|
||||
("fr-CA", "French (Canada)"),
|
||||
("ar-001", "Arabic"),
|
||||
("es-419", "Spanish (Latin America)"),
|
||||
("en", "English"),
|
||||
("de-DE", "German"),
|
||||
("en-ZZ", "English"),
|
||||
("en-XA", "English"),
|
||||
("en-Zzzz", "English"),
|
||||
("sq-XK", "Albanian (Kosovo)"),
|
||||
("mn-Mong-CN", "Mongolian (China)"),
|
||||
("und", None),
|
||||
("qaa", None),
|
||||
("x-foo", None),
|
||||
],
|
||||
)
|
||||
def test_language_name(tag: str, expected: Optional[str]) -> None:
|
||||
assert language_name(Language.get(tag)) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("tag", "expected"),
|
||||
[
|
||||
("zh-Hant-TW", "中文(繁體)"),
|
||||
("zh-Hans-CN", "中文(简体)"),
|
||||
("zh-Hant-HK", "中文(繁體,香港)"),
|
||||
("zh-Hans-MO", "中文(简体,澳门)"),
|
||||
("zh-TW", "中文(台灣)"),
|
||||
("zh-HK", "中文(香港)"),
|
||||
("cmn-Hant", "中文(繁體)"),
|
||||
("yue-Hant", "粵語(繁體)"),
|
||||
("sr-ME", "Srpski (Crna Gora)"),
|
||||
("ka", "ქართული"),
|
||||
("hy", "Հայերեն"),
|
||||
("pt-BR", "Português"),
|
||||
("pt-PT", "Português (Portugal)"),
|
||||
("es-419", "Español (Latinoamérica)"),
|
||||
("sr-Latn-ME", "Srpski (latinica, Crna Gora)"),
|
||||
("ja-JP", "日本語"),
|
||||
("en-GB", "English (United Kingdom)"),
|
||||
("en-HK", "English (Hong Kong)"),
|
||||
("qaa", None),
|
||||
],
|
||||
)
|
||||
def test_native_language_name(tag: str, expected: Optional[str], monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(config, "muxing", {"track_names": "native"})
|
||||
assert language_name(Language.get(tag)) == expected
|
||||
|
||||
|
||||
def test_native_subtitle_name_keeps_the_flag(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(config, "muxing", {"track_names": "native"})
|
||||
assert sub("zh-TW", sdh=True).get_track_name() == "中文(繁體) (SDH)"
|
||||
assert sub("zh", name="Mandarin").get_track_name() == "Mandarin"
|
||||
|
||||
|
||||
def test_subtitle_names_and_tags_the_script_but_keeps_its_language() -> None:
|
||||
track = sub("zh-TW")
|
||||
assert track.name is None
|
||||
assert track.get_track_name() == "Chinese (Traditional)"
|
||||
assert str(track.mux_language) == "zh-Hant-TW"
|
||||
assert str(track.language) == "zh-TW"
|
||||
|
||||
|
||||
def test_subtitle_flag_follows_the_default_name() -> None:
|
||||
assert sub("zh-CN", sdh=True).get_track_name() == "Chinese (Simplified) (SDH)"
|
||||
|
||||
|
||||
def test_audio_gets_no_script() -> None:
|
||||
track = Audio(id_="a", url="https://x/a", codec=Audio.Codec.AAC, language="zh-TW", bitrate=1)
|
||||
assert track.get_track_name() == "Chinese (Taiwan)"
|
||||
assert str(track.mux_language) == "zh-TW"
|
||||
|
||||
|
||||
def test_a_service_name_wins() -> None:
|
||||
assert sub("zh", name="简体中文").get_track_name() == "简体中文"
|
||||
|
||||
|
||||
def test_mkvmerge_gets_the_subtitle_script_and_name(tmp_path: Path, mux_args: Callable[..., list[str]]) -> None:
|
||||
video = Video(id_="v", url="https://x/v", codec=Video.Codec.AVC, language="zh-TW", width=1920, height=1080)
|
||||
audio = Audio(id_="a", url="https://x/a", codec=Audio.Codec.AAC, language="zh-TW", bitrate=1)
|
||||
subtitle = sub("zh-TW")
|
||||
for track, file in ((video, "v.mp4"), (audio, "a.mp4"), (subtitle, "s.vtt")):
|
||||
track.path = tmp_path / file
|
||||
track.path.write_bytes(b"\x00" * 16)
|
||||
|
||||
args = mux_args(Tracks([video, audio, subtitle]), output_path=tmp_path / "o.mkv")
|
||||
|
||||
def last_option(file: str, flag: str) -> str:
|
||||
"""Return the value of the last flag given before the file, which is the one mkvmerge applies to it."""
|
||||
before = args[: args.index(str(tmp_path / file))]
|
||||
return before[len(before) - before[::-1].index(flag)]
|
||||
|
||||
assert last_option("s.vtt", "--language") == "0:zh-Hant-TW"
|
||||
assert last_option("s.vtt", "--track-name") == "0:Chinese (Traditional)"
|
||||
assert last_option("a.mp4", "--language") == "0:zh-TW"
|
||||
|
||||
|
||||
def test_the_default_name_follows_a_later_language_change() -> None:
|
||||
track = sub("yue")
|
||||
track.language = Language.get("zh-Hant")
|
||||
assert track.get_track_name() == "Chinese (Traditional)"
|
||||
|
||||
|
||||
def test_a_language_assigned_as_text_later_is_parsed() -> None:
|
||||
track = sub("pt")
|
||||
track.language = "pt-PT"
|
||||
assert track.language == Language.get("pt-PT")
|
||||
assert track.get_track_name() == "Portuguese (Portugal)"
|
||||
assert str(track) == "SUB | [VTT] | pt-PT | Portuguese (Portugal)"
|
||||
track.language = None
|
||||
assert str(track.language) == "und"
|
||||
assert track.get_track_name() is None
|
||||
@@ -1718,6 +1718,7 @@ def serialize_track_common(track: Any) -> Dict[str, Any]:
|
||||
"language": str(track.language) if track.language else None,
|
||||
"is_original_lang": bool(getattr(track, "is_original_lang", False)),
|
||||
"name": getattr(track, "name", None),
|
||||
"track_name": track.get_track_name(),
|
||||
"needs_repack": bool(getattr(track, "needs_repack", False)),
|
||||
"edition": list(getattr(track, "edition", None) or []),
|
||||
"descriptor": descriptor_name(track),
|
||||
|
||||
@@ -426,7 +426,23 @@ def _cell_size(character: str, *args: str) -> int:
|
||||
return 1 if unicodedata.category(character) == "Mc" else _rich_cell_size(character, *args)
|
||||
|
||||
|
||||
# the viramas that join the next consonant into one cluster (Unicode InCB=Linker); Tamil and Kannada do not
|
||||
_JOINING_VIRAMAS = frozenset("्্્୍్്")
|
||||
_rich_cell_len = rich.cells._cell_len
|
||||
|
||||
|
||||
def _cell_len(text: str, *args: str) -> int:
|
||||
"""Count a consonant joined by a virama (the न्द in हिन्दी) as no cell: terminals draw the conjunct in one."""
|
||||
width = _rich_cell_len(text, *args)
|
||||
if _JOINING_VIRAMAS.isdisjoint(text):
|
||||
return width
|
||||
return width - sum(
|
||||
prev in _JOINING_VIRAMAS and unicodedata.category(char) == "Lo" for prev, char in zip(text, text[1:])
|
||||
)
|
||||
|
||||
|
||||
rich.cells.get_character_cell_size = _cell_size
|
||||
rich.cells._cell_len = _cell_len
|
||||
rich.cells.cached_cell_len.cache_clear()
|
||||
|
||||
console = ComfyConsole(
|
||||
|
||||
@@ -6,7 +6,6 @@ import logging
|
||||
import math
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from concurrent.futures import Future
|
||||
from contextlib import ExitStack, closing
|
||||
from copy import deepcopy
|
||||
@@ -17,6 +16,7 @@ from urllib.parse import urljoin, urlparse
|
||||
from uuid import UUID
|
||||
from zlib import crc32
|
||||
|
||||
import click
|
||||
import requests
|
||||
from langcodes import Language, tag_is_valid
|
||||
from lxml.etree import Element, ElementTree, XMLSyntaxError
|
||||
@@ -497,14 +497,13 @@ class DASH:
|
||||
if config.sample and segments:
|
||||
break
|
||||
|
||||
# raise, never sys.exit: this runs in a download thread, where SystemExit escapes the failure handler
|
||||
if not segments:
|
||||
log.error("Could not find a way to get segments from this MPD manifest.")
|
||||
log.debug(track.url)
|
||||
sys.exit(1)
|
||||
raise click.ClickException("Could not find a way to get segments from this MPD manifest.")
|
||||
|
||||
if config.sample and not segment_durations and not isinstance(track, Subtitle):
|
||||
log.error("--sample cannot cut this track: the manifest gives it as one file with no segment index.")
|
||||
sys.exit(1)
|
||||
raise click.ClickException("--sample cannot cut this track: the server sent no segment index for it.")
|
||||
|
||||
# TODO: Should we floor/ceil/round, or is int() ok?
|
||||
track.data["dash"]["timescale"] = int(segment_timescale)
|
||||
@@ -1294,8 +1293,8 @@ class DASH:
|
||||
|
||||
@staticmethod
|
||||
def is_closed_caption(adaptation_set: Element) -> bool:
|
||||
"""Whether the Adaptation Set is a Closed Caption Subtitle."""
|
||||
return any(
|
||||
"""Whether the Adaptation Set is a Closed Caption Subtitle. A caption that is also marked SDH counts as SDH."""
|
||||
return not DASH.is_sdh(adaptation_set) and any(
|
||||
(x.get("schemeIdUri"), x.get("value")) == ("urn:mpeg:dash:role:2011", "caption")
|
||||
for x in adaptation_set.findall("Role")
|
||||
)
|
||||
|
||||
@@ -8,7 +8,6 @@ import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from contextlib import ExitStack, closing
|
||||
from itertools import accumulate
|
||||
@@ -18,6 +17,7 @@ from urllib.parse import urljoin, urlparse
|
||||
from uuid import UUID
|
||||
from zlib import crc32
|
||||
|
||||
import click
|
||||
import m3u8
|
||||
import requests
|
||||
from langcodes import Language, tag_is_valid
|
||||
@@ -644,14 +644,12 @@ class HLS:
|
||||
if not isinstance(response, (requests.Response, RnetResponse)):
|
||||
raise TypeError(f"Expected response to be a requests.Response or rnet.Response, not {type(response)}")
|
||||
if not response.ok:
|
||||
log.error(f"Failed to request the invariant M3U8 playlist: {response.status_code}")
|
||||
sys.exit(1)
|
||||
raise click.ClickException(f"Failed to request the invariant M3U8 playlist: {response.status_code}")
|
||||
|
||||
master = m3u8.loads(utf8_text(response), uri=track.url)
|
||||
|
||||
if not master.segments:
|
||||
log.error("Track's HLS playlist has no segments, expecting an invariant M3U8 playlist.")
|
||||
sys.exit(1)
|
||||
raise click.ClickException("Track's HLS playlist has no segments, expecting an invariant M3U8 playlist.")
|
||||
|
||||
unwanted_segments = [
|
||||
segment for segment in master.segments if callable(track.OnSegmentFilter) and track.OnSegmentFilter(segment)
|
||||
|
||||
@@ -32,6 +32,58 @@ 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
|
||||
|
||||
|
||||
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
|
||||
git = str(binaries.Git)
|
||||
status = subprocess.run(
|
||||
[git, "-C", str(dest), "status", "--porcelain", "--untracked-files=no"], 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:
|
||||
"""True if value is a git repo spec (URL or owner/repo shorthand), not a local path."""
|
||||
@@ -121,6 +173,9 @@ 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):
|
||||
raise DirtyServiceRepo(dest)
|
||||
@@ -163,7 +218,13 @@ def local_dirty_services(dest: Path) -> list[str]:
|
||||
r = subprocess.run([str(binaries.Git), "-C", str(dest), "diff", "--name-only", "HEAD"], 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})
|
||||
return sorted(
|
||||
{
|
||||
line.split("/")[0]
|
||||
for line in r.stdout.decode(errors="ignore").splitlines()
|
||||
if line and not is_junk_path(line)
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def changed_services(dest: Path, old: Optional[str], new: Optional[str]) -> list[str]:
|
||||
@@ -205,17 +266,20 @@ 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.
|
||||
|
||||
This function intentionally ignores untracked files: a `git pull --ff-only` only touches tracked
|
||||
files, so untracked files (including `__pycache__` that importing the services creates) are never
|
||||
at risk and must not falsely flag the clone as dirty.
|
||||
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.
|
||||
"""
|
||||
git = str(binaries.Git)
|
||||
# modifications to tracked files only (--untracked-files=no skips __pycache__ etc.)
|
||||
# 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
|
||||
) # nosec B603
|
||||
if status.returncode == 0 and status.stdout.strip():
|
||||
return True
|
||||
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
|
||||
# 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:
|
||||
|
||||
@@ -28,6 +28,10 @@ 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``.
|
||||
|
||||
@@ -15,6 +15,7 @@ import click
|
||||
import pycaption
|
||||
import requests
|
||||
from construct import Container
|
||||
from langcodes import Language
|
||||
from pycaption import Caption, CaptionList, CaptionNode, WebVTTReader
|
||||
from pycaption.geometry import Layout
|
||||
from pymp4.parser import MP4
|
||||
@@ -24,7 +25,7 @@ from subtitle_filter import Subtitles
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.tracks.track import Track
|
||||
from unshackle.core.utilities import try_ensure_utf8
|
||||
from unshackle.core.utilities import try_ensure_utf8, with_script
|
||||
from unshackle.core.utils.subprocess import log_tool_run
|
||||
from unshackle.core.utils.webvtt import merge_segmented_webvtt
|
||||
|
||||
@@ -221,6 +222,11 @@ class Subtitle(Track):
|
||||
forced=data.get("forced", False),
|
||||
)
|
||||
|
||||
@property
|
||||
def mux_language(self) -> Language:
|
||||
"""The language tag written to the output file, with the script its region implies."""
|
||||
return with_script(self.language)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return " | ".join(
|
||||
filter(
|
||||
|
||||
@@ -35,7 +35,7 @@ from unshackle.core.events import events
|
||||
from unshackle.core.session import MAX_BACKOFF, RnetSession, utf8_text
|
||||
from unshackle.core.temp import restore_segments, stash_segments
|
||||
from unshackle.core.tracks import resume
|
||||
from unshackle.core.utilities import get_boxes, log_event, try_ensure_utf8
|
||||
from unshackle.core.utilities import get_boxes, language_name, log_event, try_ensure_utf8
|
||||
from unshackle.core.utils import run_proxy
|
||||
from unshackle.core.utils.subprocess import ffprobe
|
||||
|
||||
@@ -360,11 +360,15 @@ def parse_sidx(data: bytes, offset: int) -> tuple[int, list[tuple[int, int, int]
|
||||
Returns the timescale and one (start time, first byte, last byte) for each subsegment. The list
|
||||
is empty when the box is not a ``sidx`` or when it points at more indexes and not at media.
|
||||
"""
|
||||
size, header = int.from_bytes(data[:4], "big"), 32 if data[8:9] == b"\x00" else 40
|
||||
# pymp4 loops forever on a box that counts more references than its size holds
|
||||
if data[4:8] != b"sidx" or size < header + 12 * int.from_bytes(data[header - 2 : header], "big"):
|
||||
return 0, []
|
||||
try:
|
||||
box = Box.parse(data)
|
||||
except ConstructError:
|
||||
return 0, []
|
||||
if box.type != b"sidx" or any(reference.reference_type != "MEDIA" for reference in box.references):
|
||||
if any(reference.reference_type != "MEDIA" for reference in box.references):
|
||||
return 0, []
|
||||
start, byte = box.earliest_presentation_time, offset + box.end + box.first_offset
|
||||
subsegments: list[tuple[int, int, int]] = []
|
||||
@@ -467,7 +471,7 @@ class Track:
|
||||
|
||||
self.path: Optional[Path] = None
|
||||
self.url = url
|
||||
self.language = Language.get(language)
|
||||
self.language = language
|
||||
self.is_original_lang = is_original_lang
|
||||
self.descriptor = descriptor
|
||||
self.needs_repack = needs_repack
|
||||
@@ -483,23 +487,6 @@ class Track:
|
||||
self.data = data or {}
|
||||
self.extra: Any = extra or {} # allow anything for extra, but default to a dict
|
||||
|
||||
if self.name is None:
|
||||
lang = self.language
|
||||
if (lang.language or "").lower() == (lang.territory or "").lower():
|
||||
lang = lang.update_dict({"territory": None})
|
||||
reduced = lang.simplify_script()
|
||||
extra_parts = []
|
||||
if reduced.script is not None:
|
||||
script = reduced.script_name(max_distance=25)
|
||||
if script and script != "Zzzz":
|
||||
extra_parts.append(script)
|
||||
if reduced.territory is not None:
|
||||
territory = reduced.territory_name(max_distance=25)
|
||||
if territory and territory != "ZZ":
|
||||
territory = territory.removesuffix(" SAR China")
|
||||
extra_parts.append(territory)
|
||||
self.name = ", ".join(extra_parts) or None
|
||||
|
||||
if not id_:
|
||||
this = copy(self)
|
||||
this.url = self.url.rsplit("?", maxsplit=1)[0]
|
||||
@@ -588,6 +575,15 @@ class Track:
|
||||
def __eq__(self, other: Any) -> bool:
|
||||
return isinstance(other, Track) and self.id == other.id
|
||||
|
||||
@property
|
||||
def language(self) -> Language:
|
||||
"""The language the service tagged, parsed even when a service assigns a string or None later."""
|
||||
return self._language
|
||||
|
||||
@language.setter
|
||||
def language(self, value: Union[Language, str, None]) -> None:
|
||||
self._language = Language.get(value or "und")
|
||||
|
||||
@property
|
||||
def data(self) -> defaultdict[Any, Any]:
|
||||
"""
|
||||
@@ -1015,9 +1011,19 @@ class Track:
|
||||
raise ValueError(f"Cannot reconstruct unsupported track type: {track_type!r}")
|
||||
return builder.from_dict(data)
|
||||
|
||||
@property
|
||||
def mux_language(self) -> Language:
|
||||
"""The language tag written to the output file."""
|
||||
return self.language
|
||||
|
||||
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
|
||||
|
||||
def get_track_name(self) -> Optional[str]:
|
||||
"""Get the Track Name."""
|
||||
return self.name
|
||||
"""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)
|
||||
|
||||
def get_drm_for_cdm(self, cdm: Optional[object]) -> Optional[DRM_T]:
|
||||
"""Return the DRM matching the provided CDM, if available."""
|
||||
@@ -1279,7 +1285,7 @@ class Track:
|
||||
|
||||
if hasattr(self, "data") and self.data.get("audio_language"):
|
||||
audio_lang = self.data["audio_language"]
|
||||
audio_name = self.data.get("audio_language_name", audio_lang)
|
||||
audio_name = self.embedded_audio_name()
|
||||
args.extend(
|
||||
[
|
||||
"-metadata:s:a:0",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
@@ -46,6 +47,21 @@ def at_resolution(video: Video, res: int) -> bool:
|
||||
return video.height == res or bool(video.width and int(video.width * 9 / 16) == res)
|
||||
|
||||
|
||||
def file_track_ids(path: Path) -> dict[str, int]:
|
||||
"""Return the mkvmerge ID of the first track of each type in a file. A TS file can hold its audio first."""
|
||||
res = subprocess.run(
|
||||
[str(binaries.MKVToolNix), "-J", str(path)], capture_output=True, text=True, encoding="utf-8", errors="replace"
|
||||
)
|
||||
ids: dict[str, int] = {}
|
||||
for track in json.loads(res.stdout or "{}").get("tracks") or []:
|
||||
ids.setdefault(track["type"], track["id"])
|
||||
if not ids:
|
||||
logging.getLogger("Tracks").debug(
|
||||
f"mkvmerge found no tracks in {path.name}, so it is addressed as video 0, audio 1"
|
||||
)
|
||||
return ids or {"video": 0, "audio": 1}
|
||||
|
||||
|
||||
class Tracks:
|
||||
"""
|
||||
Video, Audio, Subtitle, Chapter, and Attachment Track Store.
|
||||
@@ -606,7 +622,7 @@ class Tracks:
|
||||
candidate.unlink()
|
||||
|
||||
delay = round((track.sample_start - sample_base) * 1000) if config.sample else 0
|
||||
cl.extend(["-add", f"{source}:lang={track.language}" + (f":delay={delay}" if delay else "")])
|
||||
cl.extend(["-add", f"{source}:lang={track.mux_language}" + (f":delay={delay}" if delay else "")])
|
||||
name = "" if isinstance(track, Video) else (track.get_track_name() or "")
|
||||
if name:
|
||||
names.extend(["-name", f"{track_id}={name}"])
|
||||
@@ -765,14 +781,11 @@ class Tracks:
|
||||
video_track = video_track or self.videos[0]
|
||||
if video_track.language.is_valid():
|
||||
lang_code = str(video_track.language)
|
||||
lang_name = video_track.language.display_name()
|
||||
|
||||
for video in self.videos:
|
||||
if video.data.get("audio_language"):
|
||||
continue
|
||||
video.needs_repack = True
|
||||
video.data["audio_language"] = lang_code
|
||||
video.data["audio_language_name"] = lang_name
|
||||
|
||||
if any(at.path and at.path.exists() and has_dts_uhd_sample_entry(at.path) for at in self.audio):
|
||||
return self._mux_mp4(
|
||||
@@ -795,7 +808,7 @@ class Tracks:
|
||||
|
||||
def sample_sync(start: float) -> list[str]:
|
||||
shift = round((start - sample_base) * 1000)
|
||||
return ["--sync", f"0:{shift}"] if config.sample and shift else []
|
||||
return ["--sync", f"-1:{shift}"] if config.sample and shift else []
|
||||
|
||||
if config.sample:
|
||||
start, end = (seconds - sample_base for seconds in config.sample)
|
||||
@@ -830,15 +843,17 @@ class Tracks:
|
||||
else:
|
||||
is_default = i == 0
|
||||
|
||||
ids = file_track_ids(vt.path)
|
||||
v = ids.get("video", 0)
|
||||
video_args = [
|
||||
"--language",
|
||||
f"0:{vt.language}",
|
||||
f"{v}:{vt.mux_language}",
|
||||
"--default-track",
|
||||
f"0:{is_default}",
|
||||
f"{v}:{is_default}",
|
||||
"--original-flag",
|
||||
f"0:{vt.is_original_lang}",
|
||||
f"{v}:{vt.is_original_lang}",
|
||||
"--compression",
|
||||
"0:none",
|
||||
f"{v}:none",
|
||||
*sample_sync(vt.sample_start),
|
||||
]
|
||||
|
||||
@@ -847,9 +862,9 @@ class Tracks:
|
||||
video_args.extend(
|
||||
[
|
||||
"--default-duration",
|
||||
f"0:{vt.fps}fps" if isinstance(vt.fps, str) else f"0:{vt.fps:.3f}fps",
|
||||
f"{v}:{vt.fps}fps" if isinstance(vt.fps, str) else f"{v}:{vt.fps:.3f}fps",
|
||||
"--fix-bitstream-timing-information",
|
||||
"0:1",
|
||||
f"{v}:1",
|
||||
]
|
||||
)
|
||||
|
||||
@@ -857,19 +872,20 @@ class Tracks:
|
||||
video_args.extend(
|
||||
[
|
||||
"--color-transfer-characteristics",
|
||||
"0:18", # ARIB STD-B67 (HLG)
|
||||
f"{v}:18", # ARIB STD-B67 (HLG)
|
||||
]
|
||||
)
|
||||
|
||||
if hasattr(vt, "data") and vt.data.get("audio_language"):
|
||||
audio_lang = vt.data["audio_language"]
|
||||
audio_name = vt.data.get("audio_language_name", audio_lang)
|
||||
a = ids.get("audio")
|
||||
if vt.data.get("audio_language") and a is not None:
|
||||
video_args.extend(
|
||||
[
|
||||
"--language",
|
||||
f"1:{audio_lang}",
|
||||
f"{a}:{vt.data['audio_language']}",
|
||||
"--track-name",
|
||||
f"1:{audio_name}",
|
||||
f"{a}:{vt.embedded_audio_name()}",
|
||||
"--original-flag",
|
||||
f"{a}:{vt.is_original_lang}",
|
||||
]
|
||||
)
|
||||
|
||||
@@ -888,7 +904,7 @@ class Tracks:
|
||||
"--track-name",
|
||||
f"0:{at.get_track_name() or ''}",
|
||||
"--language",
|
||||
f"0:{at.language}",
|
||||
f"0:{at.mux_language}",
|
||||
"--default-track",
|
||||
f"0:{audio_default}",
|
||||
"--visual-impaired-flag",
|
||||
@@ -918,7 +934,7 @@ class Tracks:
|
||||
"--track-name",
|
||||
f"0:{st.get_track_name() or ''}",
|
||||
"--language",
|
||||
f"0:{st.language}",
|
||||
f"0:{st.mux_language}",
|
||||
"--sub-charset",
|
||||
"0:UTF-8",
|
||||
"--forced-track",
|
||||
|
||||
@@ -15,6 +15,7 @@ import unicodedata
|
||||
import zlib
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timezone
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from typing import Any, Callable, Mapping, Optional, Sequence, Union
|
||||
@@ -26,6 +27,7 @@ import pycountry
|
||||
from construct import ValidationError
|
||||
from fontTools import ttLib
|
||||
from langcodes import Language, closest_match
|
||||
from langcodes.data_dicts import LIKELY_SUBTAGS
|
||||
from langcodes.tag_parser import LanguageTagError
|
||||
from pymp4.parser import Box
|
||||
from unidecode import unidecode
|
||||
@@ -169,6 +171,67 @@ def valid_language(language: Any) -> Optional[str]:
|
||||
return str(language)
|
||||
|
||||
|
||||
@cache
|
||||
def multi_script_languages() -> frozenset[str]:
|
||||
"""Return the languages whose likely script changes with the region in CLDR (zh, yue, sr, ...)."""
|
||||
found = set()
|
||||
for tag, likely in LIKELY_SUBTAGS.items():
|
||||
match = re.fullmatch(r"([a-z]{2,3})-(?:[A-Z]{2}|\d{3})", tag)
|
||||
if match and match[1] != "und" and Language.get(likely).script != Language.get(match[1]).maximize().script:
|
||||
found.add(match[1])
|
||||
return frozenset(found)
|
||||
|
||||
|
||||
def with_script(language: Language) -> Language:
|
||||
"""
|
||||
Add the script a region implies to a subtitle tag, e.g. zh-TW to zh-Hant-TW.
|
||||
|
||||
Only a language written in several scripts gets one, and only when the tag has a region:
|
||||
a bare zh says nothing about the script, so it stays zh.
|
||||
"""
|
||||
if language.script or not language.territory or language.language not in multi_script_languages():
|
||||
return language
|
||||
return language.update_dict({"script": language.maximize().script}).simplify_script()
|
||||
|
||||
|
||||
def language_name(language: Language) -> Optional[str]:
|
||||
"""
|
||||
Return the name of a track language, or None for an unknown or private-use language.
|
||||
|
||||
The name is English, or in the language itself when `muxing.track_names` is `native`. It leaves out a
|
||||
script or region that adds nothing: private use (but XK, Kosovo), 001, the CLDR default region of the
|
||||
language and script (pt-BR, zh-Hant-TW, but not pt-PT), a script named like the language.
|
||||
"""
|
||||
code = language.language
|
||||
if not code or not Language.make(language=code).has_name_data():
|
||||
return None
|
||||
script, region = language.script, language.territory
|
||||
if script and (
|
||||
re.fullmatch(r"Qaa[a-z]|Qab[a-x]|Zzzz", script) or language.script_name() == language.language_name()
|
||||
):
|
||||
script = None
|
||||
if region and (
|
||||
region == "001"
|
||||
or re.fullmatch(r"AA|Q[M-Z]|X[A-JL-Z]|ZZ", region)
|
||||
or Language.make(language=code, script=script).maximize().territory == region
|
||||
):
|
||||
region = None
|
||||
shown = language.update_dict({"script": script, "territory": region})
|
||||
native = config.muxing.get("track_names") == "native"
|
||||
# names are filed under the full macrolanguage tag (zh-Hant): zh-TW or cmn-Hant named in itself falls back to English
|
||||
full = language.maximize()
|
||||
name = shown.prefer_macrolanguage().display_name(full.prefer_macrolanguage()) if native else shown.display_name()
|
||||
name = name.replace(" SAR China", "")
|
||||
if not native:
|
||||
return name
|
||||
name = re.sub(r"中[国國](香港|澳[门門])特[别別]行政[区區]", r"\1", name)
|
||||
if "(" in name:
|
||||
# the Traditional Chinese data separates with an ASCII comma, the Simplified with a full-width one
|
||||
name = name.replace(", ", ",")
|
||||
# Georgian has capitals (Mtavruli) but never starts a name with one
|
||||
return name[:1].upper() + name[1:] if full.script in ("Latn", "Cyrl", "Grek", "Armn") else name
|
||||
|
||||
|
||||
def is_exact_match(language: Union[str, Language], languages: Sequence[Union[str, Language, None]]) -> bool:
|
||||
"""Examine whether a language exactly matches any of the given languages."""
|
||||
languages = [x for x in languages if x]
|
||||
|
||||
@@ -399,10 +399,11 @@ class EXAMPLE(Service):
|
||||
# tells us explicitly we can set it eagerly.
|
||||
if audio.data.get("isAtmos"):
|
||||
audio.joc = 16
|
||||
# is_original_lang was set by to_tracks (via the language= arg). Use it to
|
||||
# label the original audio so it reads "Original" in selection/output.
|
||||
if audio.is_original_lang:
|
||||
audio.name = "Original"
|
||||
# Leave audio.name unset: core names the track from its language and writes
|
||||
# is_original_lang (set by to_tracks) as the original flag. Set a name only
|
||||
# for what the language tag cannot say, such as a commentary track.
|
||||
if "commentary" in label.lower():
|
||||
audio.name = "Commentary"
|
||||
|
||||
# Subtitles built by hand (not via to_tracks) skip the parser's is_original_lang
|
||||
# pass, so determine it ourselves with the same helper the parser uses.
|
||||
|
||||
Reference in New Issue
Block a user