mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-24 09:55:12 +00:00
chore(release): promote 661be3ee to main
This commit is contained in:
@@ -0,0 +1,248 @@
|
||||
"""subtitle.ass_style and --sub-font: the look given to subtitles converted into ASS."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pysubs2
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import dl, set_subtitle_look, subtitle_look
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from unshackle.core.tracks import subtitle_convert as sc
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.tracks.video import Video
|
||||
|
||||
Codec = Subtitle.Codec
|
||||
|
||||
VTT = """WEBVTT
|
||||
|
||||
00:00:01.000 --> 00:00:02.000
|
||||
[door creaks]
|
||||
|
||||
00:00:03.000 --> 00:00:04.000
|
||||
Hello there.
|
||||
"""
|
||||
|
||||
NATIVE_ASS = """[Script Info]
|
||||
ScriptType: v4.00+
|
||||
PlayResX: 640
|
||||
PlayResY: 360
|
||||
|
||||
[V4+ Styles]
|
||||
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
||||
Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,1,2,10,10,18,1
|
||||
Style: Top,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,-1,0,0,100,100,0,0,1,2,1,8,10,10,18,1
|
||||
|
||||
[Events]
|
||||
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\\pos(320,50)}Sign
|
||||
Dialogue: 0,0:00:03.00,0:00:04.00,Top,,0,0,0,,Hello
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_subtitleedit(monkeypatch):
|
||||
monkeypatch.setattr(binaries, "SubtitleEdit", None)
|
||||
|
||||
|
||||
def make_sub(tmp_path, name: str, text: str, codec: Codec, style: pysubs2.SSAStyle | None = None) -> Subtitle:
|
||||
path = tmp_path / name
|
||||
path.write_text(text, encoding="utf8")
|
||||
sub = Subtitle(url="https://example.test/x", language="en", codec=codec)
|
||||
sub.path = path
|
||||
sub.ass_style = style
|
||||
sub.ass_video_size = (1440, 1080)
|
||||
return sub
|
||||
|
||||
|
||||
def test_style_fields_override_the_defaults():
|
||||
style = sc.build_ass_style({"fontname": "My Font", "marginv": 40, "primarycolor": "&H0000FFFF"})
|
||||
assert (style.fontname, style.fontsize, style.bold, style.marginv) == ("My Font", 72, True, 40)
|
||||
assert style.primarycolor == pysubs2.Color(255, 255, 0, 0)
|
||||
assert style.backcolor == pysubs2.Color(0, 0, 0, 0xA0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fields",
|
||||
[
|
||||
{"fontsize_px": 50},
|
||||
{"primarycolor": "white"},
|
||||
{"bold": "false"},
|
||||
{"fontname": "A,B"},
|
||||
{"fontname": " "},
|
||||
{"marginv": "low"},
|
||||
{"fontsize": None},
|
||||
{"fontsize": {}},
|
||||
{"fontsize": -5},
|
||||
{"fontsize": float("nan")},
|
||||
{"outline": float("inf")},
|
||||
{"marginv": True},
|
||||
{"marginv": 3.6},
|
||||
{"primarycolor": 16777215},
|
||||
{"fontname": "A\u2028B"},
|
||||
{"fontname": "A\x00B"},
|
||||
{"alignment": 10},
|
||||
],
|
||||
)
|
||||
def test_bad_style_fields_raise(fields):
|
||||
with pytest.raises(ValueError):
|
||||
sc.build_ass_style(fields)
|
||||
|
||||
|
||||
def test_ass_field_names_are_accepted():
|
||||
style = sc.build_ass_style({"Fontname": "My Font", "PrimaryColour": "&H0000FFFF", "MarginV": 40.0})
|
||||
assert (style.fontname, style.primarycolor, style.marginv) == ("My Font", pysubs2.Color(255, 255, 0, 0), 40)
|
||||
|
||||
|
||||
def test_the_look_goes_only_to_subtitles_that_are_not_already_ass(tmp_path):
|
||||
style = sc.build_ass_style({})
|
||||
vtt = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT)
|
||||
ass = make_sub(tmp_path, "x.ass", NATIVE_ASS, Codec.SubStationAlphav4)
|
||||
videos = [
|
||||
Video(url="https://example.test/v", language="en"),
|
||||
Video(url="https://example.test/v", language="en", width=3840, height=1600),
|
||||
]
|
||||
set_subtitle_look([vtt, ass], style, videos)
|
||||
assert (vtt.ass_style, ass.ass_style) == (style, None)
|
||||
assert vtt.ass_video_size == ass.ass_video_size == (3840, 1600)
|
||||
|
||||
|
||||
def test_a_stripped_styled_track_with_no_cues_left_stays_srt(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "auto"}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.vtt", VTT.split("00:00:03")[0], Codec.WebVTT, sc.build_ass_style({}))
|
||||
sub.convert(Codec.SubStationAlphav4)
|
||||
sub.strip_hearing_impaired()
|
||||
assert sub.codec == Codec.SubRip
|
||||
|
||||
|
||||
def test_a_stripped_native_ass_track_is_not_restyled(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "auto"}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.ass", NATIVE_ASS, Codec.SubStationAlphav4)
|
||||
set_subtitle_look([sub], sc.build_ass_style({"fontname": "My Font"}), [])
|
||||
sub.strip_hearing_impaired()
|
||||
assert sub.codec == Codec.SubRip
|
||||
|
||||
|
||||
def test_vtt_to_ass_gets_the_style_on_a_canvas_shaped_like_the_video(tmp_path):
|
||||
sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT, sc.build_ass_style({"fontname": "My Font"}))
|
||||
sub.convert(Codec.SubStationAlphav4)
|
||||
|
||||
subs = pysubs2.load(str(sub.path))
|
||||
assert (subs.info["PlayResX"], subs.info["PlayResY"]) == ("1440", "1080")
|
||||
assert (subs.info["LayoutResX"], subs.info["LayoutResY"]) == ("1440", "1080")
|
||||
assert subs.styles["Default"].fontname == "My Font"
|
||||
assert subs.styles["Default"].fontsize == 72
|
||||
|
||||
|
||||
def test_vtt_to_ass_without_a_style_is_left_as_converted(tmp_path):
|
||||
sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT)
|
||||
sub.convert(Codec.SubStationAlphav4)
|
||||
|
||||
subs = pysubs2.load(str(sub.path))
|
||||
assert "PlayResY" not in subs.info
|
||||
assert subs.styles["Default"].fontname == "Arial"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("target", [Codec.SubStationAlphav4, Codec.SubStationAlpha])
|
||||
def test_a_native_ass_track_is_never_restyled(tmp_path, target):
|
||||
sub = make_sub(tmp_path, "x.ass", NATIVE_ASS, Codec.SubStationAlphav4, sc.build_ass_style({}))
|
||||
sub.convert(target)
|
||||
|
||||
subs = pysubs2.load(str(sub.path))
|
||||
assert subs.info["PlayResY"] == "360"
|
||||
assert subs.styles["Default"].fontsize == 20
|
||||
assert "\\pos(320,50)" in subs.events[0].text
|
||||
|
||||
|
||||
def test_a_converter_canvas_is_kept_and_the_style_scales_to_it(tmp_path):
|
||||
path = tmp_path / "x.ass"
|
||||
path.write_text(NATIVE_ASS, encoding="utf8")
|
||||
sc.style_substation(path, sc.build_ass_style({"fontname": "My Font"}), (1920, 1080))
|
||||
|
||||
subs = pysubs2.load(str(path))
|
||||
assert (subs.info["PlayResX"], subs.info["PlayResY"]) == ("640", "360")
|
||||
assert subs.styles["Default"].fontsize == pytest.approx(24)
|
||||
assert subs.styles["Default"].marginv == 20
|
||||
top = subs.styles["Top"]
|
||||
assert (top.fontname, top.alignment, top.italic) == ("My Font", pysubs2.Alignment.TOP_CENTER, True)
|
||||
|
||||
|
||||
def test_restyling_twice_gives_the_same_file(tmp_path):
|
||||
sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT, sc.build_ass_style({}))
|
||||
sub.convert(Codec.SubStationAlphav4)
|
||||
first = sub.path.read_text("utf8")
|
||||
sc.style_substation(sub.path, sub.ass_style, sub.ass_video_size)
|
||||
assert sub.path.read_text("utf8") == first
|
||||
|
||||
|
||||
def test_a_stripped_styled_track_stays_styled_ass(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "auto"}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT, sc.build_ass_style({"fontname": "My Font"}))
|
||||
sub.convert(Codec.SubStationAlphav4)
|
||||
sub.strip_hearing_impaired()
|
||||
|
||||
assert sub.codec == Codec.SubStationAlphav4
|
||||
subs = pysubs2.load(str(sub.path))
|
||||
assert subs.styles["Default"].fontname == "My Font"
|
||||
assert [e.plaintext for e in subs.events] == ["Hello there."]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("sub_format", "sub_font", "fields", "expected"),
|
||||
[
|
||||
(None, None, None, (None, None)),
|
||||
(None, None, {"fontsize": 60}, (Codec.SubStationAlphav4, "Arial")),
|
||||
(None, "My Font", None, (Codec.SubStationAlphav4, "My Font")),
|
||||
(Codec.SubStationAlpha, "My Font", {"fontname": "Other"}, (Codec.SubStationAlpha, "My Font")),
|
||||
(Codec.SubRip, None, {"fontsize": 60}, (Codec.SubRip, None)),
|
||||
("original", None, {"fontsize": 60}, ("original", None)),
|
||||
],
|
||||
)
|
||||
def test_subtitle_look_picks_the_format_and_style(sub_format, sub_font, fields, expected):
|
||||
out_format, style = subtitle_look(sub_format, sub_font, fields)
|
||||
assert (out_format, style.fontname if style else None) == expected
|
||||
|
||||
|
||||
def test_a_typed_font_overrides_a_format_from_config():
|
||||
out_format, style = subtitle_look(Codec.SubRip, "My Font", None, typed_format=False)
|
||||
assert (out_format, style.fontname if style else None) == (Codec.SubStationAlphav4, "My Font")
|
||||
|
||||
|
||||
def test_a_font_from_config_is_ignored_with_another_format():
|
||||
assert subtitle_look(Codec.SubRip, "My Font", None, typed_font=False) == (Codec.SubRip, None)
|
||||
assert subtitle_look("original", "My Font", {"fontsize": 60}, typed_font=False) == ("original", None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("data", "error"),
|
||||
[
|
||||
({"sub_font": "My Font", "sub_format": "SRT"}, "Invalid sub_font: --sub-font needs ASS subtitles"),
|
||||
({"sub_font": "A,B"}, "Invalid sub_font: ass_style fontname"),
|
||||
],
|
||||
)
|
||||
def test_the_api_refuses_a_sub_font_it_cannot_use(data, error):
|
||||
assert (validate_download_parameters(data) or "").startswith(error)
|
||||
|
||||
|
||||
def test_the_api_takes_a_sub_font_with_ass():
|
||||
assert validate_download_parameters({"sub_font": "My Font", "sub_format": "ASS"}) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("sub_format", "fields"),
|
||||
[(Codec.SubRip, None), ("original", None), (None, "Arial,72"), (None, {"bold": "yes"})],
|
||||
)
|
||||
def test_subtitle_look_refuses_a_style_it_cannot_use(sub_format, fields):
|
||||
with pytest.raises(ValueError):
|
||||
subtitle_look(sub_format, "My Font" if fields is None else None, fields)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["..", "../other"])
|
||||
def test_a_font_name_that_is_a_path_finds_no_custom_font(tmp_path, monkeypatch, name):
|
||||
monkeypatch.setattr("unshackle.core.config.config.directories.fonts", tmp_path / "fonts", raising=False)
|
||||
for folder in ("fonts/My Font", "other"):
|
||||
(tmp_path / folder).mkdir(parents=True)
|
||||
(tmp_path / folder / "x.ttf").write_bytes(b"")
|
||||
(tmp_path / "x.ttf").write_bytes(b"")
|
||||
assert dl.find_custom_font(None, "My Font") == tmp_path / "fonts/My Font/x.ttf" # type: ignore[arg-type]
|
||||
assert dl.find_custom_font(None, name) is None # type: ignore[arg-type]
|
||||
@@ -2,24 +2,73 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
import unshackle.core.tracks.track as track_module
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.tracks.attachment import Attachment
|
||||
|
||||
URL = "https://cdn.example.com/images/thumb.jpg"
|
||||
downloader = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
BODY = bytes(range(256)) * 64
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
def raise_for_status(self) -> None:
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
"""Serves BODY (honoring a Range start), or the next scripted status or "cut" first."""
|
||||
|
||||
def do_GET(self) -> None:
|
||||
self.server.hits += 1 # type: ignore[attr-defined]
|
||||
script = self.server.script # type: ignore[attr-defined]
|
||||
action = script.pop(0) if script else "ok"
|
||||
if isinstance(action, int):
|
||||
self.send_response(action)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
rng = self.headers.get("Range")
|
||||
start = int(rng.removeprefix("bytes=").split("-")[0]) if rng else 0
|
||||
body = BODY[start:]
|
||||
self.send_response(206 if rng else 200)
|
||||
if rng:
|
||||
self.send_header("Content-Range", f"bytes {start}-{len(BODY) - 1}/{len(BODY)}")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body[: len(body) // 2] if action == "cut" else body)
|
||||
|
||||
def log_message(self, *args: object) -> None:
|
||||
pass
|
||||
|
||||
def iter_content(self, chunk_size: int):
|
||||
yield b"jpegdata"
|
||||
|
||||
@pytest.fixture
|
||||
def server():
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
srv.hits = 0 # type: ignore[attr-defined]
|
||||
srv.script = [] # type: ignore[attr-defined]
|
||||
thread = threading.Thread(target=srv.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
yield srv
|
||||
srv.shutdown()
|
||||
thread.join(timeout=5)
|
||||
|
||||
|
||||
class FakeSession(requests.Session):
|
||||
@pytest.fixture(autouse=True)
|
||||
def temp_and_no_wait(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
monkeypatch.setattr(downloader, "retry_sleep", lambda exc, attempts: 0)
|
||||
|
||||
|
||||
def url(srv, path: str = "/images/thumb.jpg") -> str:
|
||||
return f"http://127.0.0.1:{srv.server_address[1]}{path}"
|
||||
|
||||
|
||||
class Recorder(requests.Session):
|
||||
__attrs__ = [*requests.Session.__attrs__, "got"]
|
||||
|
||||
def __init__(self, proxies: dict | None = None) -> None:
|
||||
super().__init__()
|
||||
self.proxies = proxies or {}
|
||||
@@ -27,66 +76,89 @@ class FakeSession(requests.Session):
|
||||
|
||||
def get(self, url, **kwargs): # type: ignore[override]
|
||||
self.got.append(url)
|
||||
return FakeResponse()
|
||||
return super().get(url, **kwargs)
|
||||
|
||||
|
||||
def test_url_attachment_defers_download() -> None:
|
||||
session = FakeSession()
|
||||
attachment = Attachment.from_url(URL, name="thumbnail", session=session)
|
||||
session = Recorder()
|
||||
attachment = Attachment.from_url("https://cdn.example.com/images/thumb.jpg", name="thumbnail", session=session)
|
||||
assert attachment.path is None
|
||||
assert not session.got
|
||||
assert attachment.mime_type == "image/jpeg"
|
||||
|
||||
|
||||
def test_download_without_flag_uses_proxied_session(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
session = FakeSession(proxies={"https": "http://proxy:8080"})
|
||||
attachment = Attachment.from_url(URL, name="thumbnail", session=session)
|
||||
def test_download_without_flag_uses_proxied_session(server) -> None:
|
||||
session = Recorder(proxies={"https": "http://proxy:8080"})
|
||||
attachment = Attachment.from_url(url(server), name="thumbnail", session=session)
|
||||
attachment.download(session)
|
||||
assert session.got == [URL]
|
||||
assert attachment.path is not None and attachment.path.read_bytes() == b"jpegdata"
|
||||
assert session.got == [url(server)]
|
||||
assert attachment.path is not None and attachment.path.read_bytes() == BODY
|
||||
|
||||
|
||||
def test_download_with_flag_bypasses_proxy(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
direct = FakeSession()
|
||||
def test_download_with_flag_bypasses_proxy(server, monkeypatch) -> None:
|
||||
direct = Recorder()
|
||||
monkeypatch.setattr(track_module, "direct_session", lambda session: direct)
|
||||
proxied = FakeSession(proxies={"https": "http://proxy:8080"})
|
||||
attachment = Attachment.from_url(URL, name="thumbnail", session=proxied)
|
||||
proxied = Recorder(proxies={"https": "http://proxy:8080"})
|
||||
attachment = Attachment.from_url(url(server), name="thumbnail", session=proxied)
|
||||
attachment.download(proxied, no_proxy_download=True)
|
||||
assert not proxied.got
|
||||
assert direct.got == [URL]
|
||||
assert attachment.path is not None and attachment.path.read_bytes() == b"jpegdata"
|
||||
assert direct.got == [url(server)]
|
||||
assert attachment.path is not None and attachment.path.read_bytes() == BODY
|
||||
|
||||
|
||||
def test_download_with_proxy_download_uses_only_that_proxy(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
def test_download_with_proxy_download_uses_only_that_proxy(server, monkeypatch) -> None:
|
||||
seen: dict = {}
|
||||
|
||||
def fake_direct(session, proxy=None):
|
||||
seen["proxy"] = proxy
|
||||
return FakeSession(proxies={"all": proxy})
|
||||
return Recorder()
|
||||
|
||||
monkeypatch.setattr(track_module, "direct_session", fake_direct)
|
||||
proxied = FakeSession(proxies={"https": "http://manifest-proxy:1"})
|
||||
attachment = Attachment.from_url(URL, name="thumbnail", session=proxied)
|
||||
proxied = Recorder(proxies={"https": "http://manifest-proxy:1"})
|
||||
attachment = Attachment.from_url(url(server), name="thumbnail", session=proxied)
|
||||
attachment.download(proxied, proxy_download="http://dl-proxy:2")
|
||||
assert not proxied.got
|
||||
assert seen["proxy"] == "http://dl-proxy:2"
|
||||
assert proxied.proxies == {"https": "http://manifest-proxy:1"}
|
||||
|
||||
|
||||
def test_no_proxy_download_wins_over_proxy_download(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
def test_no_proxy_download_wins_over_proxy_download(server, monkeypatch) -> None:
|
||||
seen: dict = {}
|
||||
monkeypatch.setattr(
|
||||
track_module, "direct_session", lambda s, proxy=None: seen.setdefault("p", proxy) or FakeSession()
|
||||
)
|
||||
plain = FakeSession()
|
||||
Attachment.from_url(URL, name="t", session=plain).download(
|
||||
monkeypatch.setattr(track_module, "direct_session", lambda s, proxy=None: seen.setdefault("p", proxy) or Recorder())
|
||||
plain = Recorder()
|
||||
Attachment.from_url(url(server), name="t", session=plain).download(
|
||||
plain, no_proxy_download=True, proxy_download="http://dl-proxy:2"
|
||||
)
|
||||
assert "p" not in seen and plain.got == [URL]
|
||||
assert "p" not in seen and plain.got == [url(server)]
|
||||
|
||||
|
||||
def test_body_cut_is_resumed(server) -> None:
|
||||
server.script = ["cut"]
|
||||
attachment = Attachment.from_url(url(server), name="thumbnail")
|
||||
attachment.download(requests.Session())
|
||||
assert server.hits == 2
|
||||
assert attachment.path is not None and attachment.path.read_bytes() == BODY
|
||||
|
||||
|
||||
def test_spent_retries_fail_the_run_with_one_line(server) -> None:
|
||||
server.script = [503] * downloader.MAX_ATTEMPTS
|
||||
attachment = Attachment.from_url(url(server), name="thumbnail")
|
||||
with pytest.raises(requests.HTTPError) as raised:
|
||||
attachment.download(requests.Session())
|
||||
assert server.hits == downloader.MAX_ATTEMPTS
|
||||
assert attachment.path is None
|
||||
_, line = dl.failure_lines(raised.value)
|
||||
assert f"gave up after {downloader.MAX_ATTEMPTS} failed attempts" in line
|
||||
assert "attachment thumbnail" in line
|
||||
|
||||
|
||||
def test_same_named_attachments_get_separate_files(server) -> None:
|
||||
first = Attachment.from_url(url(server, "/a/image.jpg"))
|
||||
second = Attachment.from_url(url(server, "/b/image.jpg"))
|
||||
first.download(requests.Session())
|
||||
second.download(requests.Session())
|
||||
assert first.path is not None and second.path is not None
|
||||
assert first.path != second.path
|
||||
|
||||
|
||||
def test_direct_session_routes_through_the_given_proxy() -> None:
|
||||
|
||||
@@ -25,6 +25,20 @@ def test_existing_channel_forms_are_unchanged(value: object, expected: float) ->
|
||||
assert Audio.parse_channels(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("value", "expected"), [("FA01", 7.1), ("f801", 5.1), ("F805", "5.1.2"), ("A000", 2.0)])
|
||||
def test_a_dolby_channel_mask_counts_its_channels(value: str, expected: object) -> None:
|
||||
assert Audio.parse_channels(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("count", "expected"),
|
||||
[("2", 2.0), ("6", 5.1), ("7", 6.1), ("8", 7.1), (6, 5.1), ("1", 1.0), (None, None), ("2ch", "2ch")],
|
||||
)
|
||||
def test_a_bare_channel_count_takes_its_usual_layout(count: object, expected: object) -> None:
|
||||
"""HLS CHANNELS and Smooth Streaming Channels give a count, which names no LFE."""
|
||||
assert Audio.channels_from_count(count) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["stereo", "5.1.4.2", "", "..", "5.x.4"])
|
||||
def test_a_value_that_is_no_layout_still_raises(value: str) -> None:
|
||||
with pytest.raises(NotImplementedError):
|
||||
|
||||
@@ -25,6 +25,15 @@ def test_dts_uhd_sample_entries_map_to_dtsx(mime: str) -> None:
|
||||
assert Audio.Codec.DTSX.value == "DTS-X", "':' is not a legal path character on Windows"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mime", "codec"),
|
||||
[("dtsh", Audio.Codec.DTSHD), ("dtsl", Audio.Codec.DTSHD), ("dtse", Audio.Codec.DTSHD)]
|
||||
+ [(m, Audio.Codec.MPEGH) for m in ("mha1", "mha2", "mhm1", "mhm2.0x0C")],
|
||||
)
|
||||
def test_dts_hd_and_mpeg_h_sample_entries_map(mime: str, codec: Audio.Codec) -> None:
|
||||
assert Audio.Codec.from_mime(mime) == codec
|
||||
|
||||
|
||||
def test_unknown_mime_still_raises() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
Audio.Codec.from_mime("dtsz")
|
||||
@@ -108,3 +117,15 @@ def test_the_group_fallback_does_not_depend_on_variant_order() -> None:
|
||||
manifest = header + "\n".join(order) + "\n"
|
||||
tracks = HLS.from_text(manifest, "https://example.test/master.m3u8").to_tracks("en")
|
||||
assert [t.codec for t in tracks.audio] == [Audio.Codec.DTSX], f"variant order decided the codec: {order[0]!r}"
|
||||
|
||||
|
||||
def test_channels_keep_only_the_count_before_the_identifiers() -> None:
|
||||
manifest = textwrap.dedent("""\
|
||||
#EXTM3U
|
||||
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="A",NAME="Main",LANGUAGE="en",CHANNELS="2/BED-2",URI="a.m3u8"
|
||||
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="A",NAME="Atmos",LANGUAGE="en",CHANNELS="16/JOC",URI="b.m3u8"
|
||||
#EXT-X-STREAM-INF:BANDWIDTH=1,CODECS="avc1.640028,ec-3",AUDIO="A"
|
||||
v.m3u8
|
||||
""")
|
||||
audio = HLS.from_text(manifest, "https://example.test/master.m3u8").to_tracks("en").audio
|
||||
assert sorted((a.channels, a.joc) for a in audio) == [(2.0, 0), (5.1, 16)]
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Tests for the repackaged-copy retry in ``Video.ccextractor``."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.core.tracks import Video
|
||||
from unshackle.core.tracks import video as video_module
|
||||
|
||||
|
||||
def test_retry_runs_on_the_repackaged_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
original = tmp_path / "v.mp4"
|
||||
original.write_bytes(b"x")
|
||||
repacked = tmp_path / "v_repack.mp4"
|
||||
track = Video(id_="v", url="https://example.test/v.m3u8", language="en", codec=Video.Codec.AVC)
|
||||
track.path = original
|
||||
|
||||
def fake_repackage() -> None:
|
||||
original.unlink()
|
||||
repacked.write_bytes(b"x")
|
||||
track.path = repacked
|
||||
|
||||
inputs: list[Path] = []
|
||||
|
||||
def fake_run(args: list[Any], **_: Any) -> None:
|
||||
inputs.append(Path(args[-1]))
|
||||
if not Path(args[-1]).exists():
|
||||
raise subprocess.CalledProcessError(2, args)
|
||||
raise subprocess.CalledProcessError(10, args)
|
||||
|
||||
monkeypatch.setattr(video_module.binaries, "CCExtractor", Path("/usr/bin/ccextractor"))
|
||||
monkeypatch.setattr(video_module.subprocess, "run", fake_run)
|
||||
monkeypatch.setattr(track, "repackage", fake_repackage)
|
||||
|
||||
assert track.ccextractor("cc", tmp_path / "cc.srt", Language.get("en")) is None
|
||||
assert inputs == [original, repacked]
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Self-check for ``has_encrypted_sample_entry``: a finalized MP4 whose moov still carries
|
||||
an encv/enca sample entry means the decrypt tool skipped/failed the track (frma was never
|
||||
an encrypted (enc*/drm*) sample entry means the decrypt tool skipped/failed the track (frma was never
|
||||
applied), so the detector must flag it before the file reaches the muxer. Detection is
|
||||
scoped to moov, so stray 4CC byte runs in mdat must never trip (or mask) it.
|
||||
|
||||
@@ -11,6 +11,8 @@ from __future__ import annotations
|
||||
import struct
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.tracks.track import has_encrypted_sample_entry
|
||||
|
||||
|
||||
@@ -76,6 +78,12 @@ def test_text_containing_enca_in_moov_not_detected(tmp_path: Path) -> None:
|
||||
assert has_encrypted_sample_entry(f) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", [b"encs", b"enct", b"drmi"])
|
||||
def test_other_encrypted_entry_kinds_detected(tmp_path: Path, kind: bytes) -> None:
|
||||
f = write(tmp_path, "enc.mp4", FTYP, moov(stsd([sample_entry(kind, box(b"sinf", box(b"frma", b"stpp")))])))
|
||||
assert has_encrypted_sample_entry(f) is True
|
||||
|
||||
|
||||
def test_missing_or_bogus_file(tmp_path: Path) -> None:
|
||||
assert has_encrypted_sample_entry(tmp_path / "nope.mp4") is False
|
||||
bogus = write(tmp_path, "bogus.bin", b"\x00\x01\x02\x03not-an-mp4")
|
||||
|
||||
@@ -93,6 +93,19 @@ def test_select_hybrid_base_picks_highest_bitrate_then_worst_flips() -> None:
|
||||
assert ids(worst) == {"hdr10p-2160-lo", "dv-360"}
|
||||
|
||||
|
||||
def test_select_hybrid_skips_a_base_that_is_not_hevc() -> None:
|
||||
"""dovi_tool injects into HEVC, so a higher-bitrate AV1 base is not a hybrid ingredient."""
|
||||
tracks = [
|
||||
make_video(
|
||||
"hdr10p-2160-av1", range_=Video.Range.HDR10P, height=2160, bitrate=30_000_000, codec=Video.Codec.AV1
|
||||
),
|
||||
make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=20_000_000, codec=Video.Codec.HEVC),
|
||||
make_video("dv-360", range_=Video.Range.DV, height=360, bitrate=1_000_000, codec=Video.Codec.HEVC),
|
||||
]
|
||||
chosen = list(filter(Tracks().select_hybrid(tracks, [2160]), tracks))
|
||||
assert ids(chosen) == {"hdr10p-2160", "dv-360"}
|
||||
|
||||
|
||||
def test_select_hybrid_no_dv_selects_only_base() -> None:
|
||||
H = Video.Codec.HEVC
|
||||
tracks = [make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=20_000_000, codec=H)]
|
||||
@@ -100,6 +113,87 @@ def test_select_hybrid_no_dv_selects_only_base() -> None:
|
||||
assert ids(chosen) == {"hdr10p-2160"}
|
||||
|
||||
|
||||
def dv_hdr10p(track_id: str, height: int, bitrate: int) -> Video:
|
||||
video = make_video(track_id, range_=Video.Range.DV, height=height, bitrate=bitrate, codec=Video.Codec.HEVC)
|
||||
video.hdr10plus = True
|
||||
return video
|
||||
|
||||
|
||||
def test_select_hybrid_takes_the_highest_dv_hdr10p_track_over_a_base_and_the_lowest_dv() -> None:
|
||||
H = Video.Codec.HEVC
|
||||
tracks = [
|
||||
dv_hdr10p("dvp-2160-hi", 2160, 26_000_000),
|
||||
dv_hdr10p("dvp-2160-lo", 2160, 21_000_000),
|
||||
make_video("hdr10-2160", range_=Video.Range.HDR10, height=2160, bitrate=24_000_000, codec=H),
|
||||
dv_hdr10p("dvp-360", 360, 700_000),
|
||||
]
|
||||
assert ids(list(filter(Tracks().select_hybrid(tracks, [2160]), tracks))) == {"dvp-2160-hi"}
|
||||
assert ids(list(filter(Tracks().select_hybrid(tracks, [2160], worst=True), tracks))) == {"dvp-2160-lo"}
|
||||
|
||||
|
||||
def test_select_hybrid_builds_a_hybrid_only_where_no_dv_track_carries_hdr10p() -> None:
|
||||
H = Video.Codec.HEVC
|
||||
tracks = [
|
||||
dv_hdr10p("dvp-2160", 2160, 26_000_000),
|
||||
make_video("hdr10-1080", range_=Video.Range.HDR10, height=1080, bitrate=8_000_000, codec=H),
|
||||
make_video("dv-360", range_=Video.Range.DV, height=360, bitrate=1_000_000, codec=H),
|
||||
]
|
||||
chosen = list(filter(Tracks().select_hybrid(tracks, [2160, 1080]), tracks))
|
||||
assert ids(chosen) == {"dvp-2160", "hdr10-1080", "dv-360"}
|
||||
|
||||
Tracks.flag_hybrid_ingredients(chosen, [])
|
||||
assert {t.id for t in chosen if t.hybrid_base_only} == {"hdr10-1080", "dv-360"}
|
||||
|
||||
|
||||
def test_a_dv_hdr10p_track_used_only_for_its_rpu_stays_an_ingredient() -> None:
|
||||
H = Video.Codec.HEVC
|
||||
tracks = [
|
||||
make_video("hdr10-1080", range_=Video.Range.HDR10, height=1080, bitrate=8_000_000, codec=H),
|
||||
dv_hdr10p("dvp-360", 360, 700_000),
|
||||
]
|
||||
chosen = list(filter(Tracks().select_hybrid(tracks, [1080]), tracks))
|
||||
Tracks.flag_hybrid_ingredients(chosen, [])
|
||||
assert all(t.hybrid_base_only for t in chosen) and ids(chosen) == {"hdr10-1080", "dvp-360"}
|
||||
|
||||
|
||||
def dv_hdr10(track_id: str, height: int, bitrate: int, range_: Video.Range = Video.Range.HDR10) -> Video:
|
||||
video = make_video(track_id, range_=range_, height=height, bitrate=bitrate, codec=Video.Codec.HEVC)
|
||||
video.dv_compatible_bitstream = True
|
||||
return video
|
||||
|
||||
|
||||
def test_select_hybrid_takes_a_dv_hdr10_track_and_no_profile_5_donor() -> None:
|
||||
H = Video.Codec.HEVC
|
||||
tracks = [
|
||||
dv_hdr10("dvhdr-2160", 2160, 7_000_000),
|
||||
make_video("dv5-2160", range_=Video.Range.DV, height=2160, bitrate=6_800_000, codec=H),
|
||||
make_video("dv5-512", range_=Video.Range.DV, height=512, bitrate=400_000, codec=H),
|
||||
]
|
||||
chosen = list(filter(Tracks().select_hybrid(tracks, [2160]), tracks))
|
||||
assert ids(chosen) == {"dvhdr-2160"} and chosen[0].native_hybrid
|
||||
|
||||
|
||||
def test_select_hybrid_prefers_a_finished_hybrid_that_carries_hdr10p() -> None:
|
||||
tracks = [
|
||||
dv_hdr10("dvhdr-2160", 2160, 9_000_000),
|
||||
dv_hdr10("dvhdrp-2160", 2160, 7_000_000, Video.Range.HDR10P),
|
||||
dv_hdr10p("dvp-2160", 2160, 6_000_000),
|
||||
]
|
||||
assert ids(list(filter(Tracks().select_hybrid(tracks, [2160]), tracks))) == {"dvhdrp-2160"}
|
||||
assert ids(list(filter(Tracks().select_hybrid(tracks, [2160], worst=True), tracks))) == {"dvp-2160"}
|
||||
|
||||
|
||||
def test_select_hybrid_picks_no_base_that_has_no_dv_track_to_take_an_rpu_from() -> None:
|
||||
H = Video.Codec.HEVC
|
||||
tracks = [
|
||||
dv_hdr10("dvhdr-2160", 2160, 7_000_000),
|
||||
make_video("hdr10p-1080", range_=Video.Range.HDR10P, height=1080, bitrate=4_000_000, codec=H),
|
||||
]
|
||||
assert ids(list(filter(Tracks().select_hybrid(tracks, [2160, 1080]), tracks))) == {"dvhdr-2160"}
|
||||
with_generate = Tracks().select_hybrid(tracks, [2160, 1080], generate_dv=True)
|
||||
assert ids(list(filter(with_generate, tracks))) == {"dvhdr-2160", "hdr10p-1080"}
|
||||
|
||||
|
||||
def test_merge_dedups_shared_ingredient_and_deliverable() -> None:
|
||||
H = Video.Codec.HEVC
|
||||
dv = make_video("dv-1080", range_=Video.Range.DV, height=1080, bitrate=9_000_000, codec=H)
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
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
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("languages", "preferred", "expected"),
|
||||
[
|
||||
(["en-GB", "en-US"], "en-US", 1),
|
||||
(["en", "en-US"], "en-US", 1),
|
||||
(["en-GB", "fr"], "en-US", None),
|
||||
(["fr", "en-GB"], "en", 1),
|
||||
(["en-US"], None, None),
|
||||
],
|
||||
)
|
||||
def test_first_match_index(languages: list[str], preferred: Optional[str], expected: Optional[int]) -> None:
|
||||
tracks = [
|
||||
Audio(id_=f"a{i}", url=f"https://x/{i}", language=lang, codec=Audio.Codec.AAC, bitrate=1)
|
||||
for i, lang in enumerate(languages)
|
||||
]
|
||||
assert Tracks.first_match_index(tracks, preferred) == expected
|
||||
|
||||
|
||||
def subtitle(index: int, language: str, kind: str) -> Subtitle:
|
||||
return Subtitle(
|
||||
id_=f"s{index}",
|
||||
url=f"https://x.example/{index}",
|
||||
language=language,
|
||||
codec=Subtitle.Codec.WebVTT,
|
||||
forced=kind == "forced",
|
||||
sdh=kind == "sdh",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("language", "types", "expected"),
|
||||
[
|
||||
("pl", [], 0),
|
||||
("pl", ["normal", "sdh", "forced"], 1),
|
||||
("pl", ["forced"], 0),
|
||||
("en", ["sdh", "normal"], 3),
|
||||
("pl", ["sdh"], 0),
|
||||
("fr", ["normal"], None),
|
||||
(None, ["normal"], 1),
|
||||
(None, ["sdh", "normal"], 3),
|
||||
(None, [], None),
|
||||
],
|
||||
)
|
||||
def test_default_subtitle_index(language: Optional[str], types: list[str], expected: Optional[int]) -> None:
|
||||
kinds = [("pl", "forced"), ("pl", "normal"), ("en", "normal"), ("en", "sdh")]
|
||||
subtitles = [subtitle(i, lang, kind) for i, (lang, kind) in enumerate(kinds)]
|
||||
assert Tracks.default_subtitle_index(subtitles, language, types) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("audio", "expected"),
|
||||
[("en", 1), ("ar", 0), ("fr", 2), (None, 2)],
|
||||
)
|
||||
def test_a_forced_default_with_no_language_follows_the_audio(audio: Optional[str], expected: int) -> None:
|
||||
kinds = [("ar", "forced"), ("en", "forced"), ("en", "normal")]
|
||||
subtitles = [subtitle(i, lang, kind) for i, (lang, kind) in enumerate(kinds)]
|
||||
audio_language = Language.get(audio) if audio else None
|
||||
assert Tracks.default_subtitle_index(subtitles, None, ["forced", "normal"], audio_language) == expected
|
||||
|
||||
|
||||
def downloaded_tracks(tmp_path: Path, audio: list[tuple[str, bool]], subtitles: list[tuple[str, str]]) -> Tracks:
|
||||
tracks = Tracks()
|
||||
for i, (lang, original) in enumerate(audio):
|
||||
track = Audio(id_=f"a{i}", url=f"https://x.example/a{i}", language=lang, is_original_lang=original)
|
||||
tracks.add(track)
|
||||
for i, (lang, kind) in enumerate(subtitles):
|
||||
tracks.add(subtitle(i, lang, kind))
|
||||
for track in tracks:
|
||||
track.path = tmp_path / f"{track.id}.bin"
|
||||
track.path.write_bytes(b"\x00")
|
||||
return tracks
|
||||
|
||||
|
||||
def subtitle_defaults(args: list[str], count: int) -> list[str]:
|
||||
return [args[i + 1] for i, arg in enumerate(args) if arg == "--default-track"][-count:]
|
||||
|
||||
|
||||
def test_mux_reads_default_subtitle_type(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
mux_args: Callable[..., list[str]],
|
||||
) -> None:
|
||||
monkeypatch.setattr(config, "muxing", {"default_subtitle_type": ["full", "CC", "Normal"]})
|
||||
tracks = downloaded_tracks(tmp_path, [("en", True)], [("pl", "forced"), ("pl", "normal"), ("en", "sdh")])
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
args = mux_args(tracks)
|
||||
|
||||
assert subtitle_defaults(args, 3) == ["0:False", "0:False", "0:True"]
|
||||
assert "'full' is not a subtitle type" in caplog.text
|
||||
|
||||
|
||||
def test_the_forced_default_follows_the_default_audio(tmp_path: Path, mux_args: Callable[..., list[str]]) -> None:
|
||||
tracks = downloaded_tracks(tmp_path, [("en", False), ("pl", True)], [("en", "forced"), ("pl", "forced")])
|
||||
|
||||
assert subtitle_defaults(mux_args(tracks), 2) == ["0:False", "0:True"]
|
||||
@@ -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:
|
||||
with pytest.raises(RuntimeError, match="MKVToolNix"):
|
||||
tracks.mux("Test Title")
|
||||
@@ -33,7 +43,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):
|
||||
@@ -48,3 +58,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}
|
||||
|
||||
@@ -16,11 +16,13 @@ import pathlib
|
||||
import re
|
||||
import struct
|
||||
|
||||
import pycaption
|
||||
import pytest
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.tracks import subtitle_convert as sc
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.tracks.track import Track
|
||||
|
||||
Codec = Subtitle.Codec
|
||||
|
||||
@@ -49,6 +51,13 @@ Dialogue: 0,0:00:03.00,0:00:04.00,Default,,0,0,0,,World
|
||||
"""
|
||||
|
||||
|
||||
LAYERED_ASS_SAMPLE = ASS_SAMPLE.replace(
|
||||
"Dialogue: 0,0:00:01.00", "Dialogue: 1,0:00:05.00,0:00:06.00,Default,,0,0,0,,Sign\nDialogue: 0,0:00:01.00"
|
||||
)
|
||||
|
||||
INSTALLED_SUBTITLEEDIT = binaries.SubtitleEdit
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_subtitleedit(monkeypatch):
|
||||
"""Default every test to a SubtitleEdit-less environment; tests opt in when needed."""
|
||||
@@ -142,6 +151,30 @@ def test_ass_to_srt_converts_when_forced(tmp_path, monkeypatch):
|
||||
assert "{\\" not in out.read_text("utf8")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("target", [Codec.SubRip, Codec.WebVTT])
|
||||
@pytest.mark.parametrize("backend", ["pysubs2", "subtitleedit"])
|
||||
def test_layered_ass_converts_in_start_time_order(tmp_path, monkeypatch, backend, target):
|
||||
if backend == "subtitleedit":
|
||||
if not INSTALLED_SUBTITLEEDIT:
|
||||
pytest.skip("SubtitleEdit is not installed")
|
||||
monkeypatch.setattr(binaries, "SubtitleEdit", INSTALLED_SUBTITLEEDIT)
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"conversion_method": backend}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.ass", LAYERED_ASS_SAMPLE, Codec.SubStationAlphav4)
|
||||
out = sub.convert(target, forced=True)
|
||||
starts = re.findall(r"(\d+:\d\d:\d\d[.,]\d{3}) -->", out.read_text("utf-8-sig"))
|
||||
assert len(starts) == 3
|
||||
assert starts == sorted(starts)
|
||||
assert [p.name for p in tmp_path.iterdir()] == [out.name]
|
||||
|
||||
|
||||
def test_ass_to_ssa_keeps_file_order(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.ass", LAYERED_ASS_SAMPLE, Codec.SubStationAlphav4)
|
||||
out = sub.convert(Codec.SubStationAlpha, forced=True)
|
||||
text = out.read_text("utf8")
|
||||
assert text.index("Sign") < text.index("Hello")
|
||||
|
||||
|
||||
def test_webvtt_to_srt_conversion(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.vtt", VTT_SAMPLE, Codec.WebVTT)
|
||||
@@ -150,6 +183,78 @@ def test_webvtt_to_srt_conversion(tmp_path, monkeypatch):
|
||||
assert cue_count(out) == 2
|
||||
|
||||
|
||||
SCC_SAMPLE = """Scenarist_SCC V1.0
|
||||
|
||||
00:00:00;00 9420 9152 9723 5bc2 4f43 49ce c120 c445 20c2 c152 434f 5d80 9420 942c 942f
|
||||
|
||||
00:00:04;15 942c
|
||||
|
||||
00:01:48;06 9420 9152 91b3 54e5 2067 7573 f461 2c20 c2ec 616e e361 2046 ecef f2bf
|
||||
|
||||
00:01:51;20 9420 942c 942f
|
||||
|
||||
00:01:55;20 942c
|
||||
"""
|
||||
|
||||
|
||||
def test_scc_mime_maps_to_the_scc_codec():
|
||||
assert Codec.from_mime("x-scc") is Codec.SCC
|
||||
assert Codec.from_mime("scc") is Codec.SCC
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"sub_format, expected",
|
||||
[
|
||||
(None, Codec.SubRip),
|
||||
("original", Codec.SubRip),
|
||||
(Codec.SubRip, Codec.SubRip),
|
||||
(Codec.WebVTT, Codec.WebVTT),
|
||||
(Codec.SubStationAlphav4, Codec.SubRip),
|
||||
],
|
||||
)
|
||||
def test_scc_converts_to_the_requested_format_or_srt(tmp_path, monkeypatch, sub_format, expected):
|
||||
from unshackle.commands.dl import convert_scc
|
||||
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.scc", SCC_SAMPLE, Codec.SCC)
|
||||
assert convert_scc(sub, sub_format) == expected
|
||||
assert sub.codec == expected
|
||||
assert cue_count(sub.path) == 2
|
||||
assert "¿Te gusta, Blanca Flor?" in sub.path.read_text("utf8")
|
||||
|
||||
|
||||
def test_scc_to_webvtt_keeps_the_caption_row(tmp_path, monkeypatch):
|
||||
from unshackle.commands.dl import convert_scc
|
||||
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.scc", SCC_SAMPLE, Codec.SCC)
|
||||
convert_scc(sub, Codec.WebVTT)
|
||||
assert "line:" in sub.path.read_text("utf8")
|
||||
|
||||
|
||||
def test_scc_as_srt_converts_on_to_ass(tmp_path, monkeypatch):
|
||||
from unshackle.commands.dl import convert_scc
|
||||
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.scc", SCC_SAMPLE, Codec.SCC)
|
||||
convert_scc(sub, Codec.SubStationAlphav4)
|
||||
assert sub.convert(Codec.SubStationAlphav4, forced=True).read_text("utf8").count("Dialogue:") == 2
|
||||
|
||||
|
||||
def test_scc_without_cc1_captions_warns(tmp_path, monkeypatch, caplog):
|
||||
from unshackle.commands.dl import convert_scc
|
||||
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
|
||||
cc3 = "Scenarist_SCC V1.0\n\n00:00:01:00\t1520 1520 1552 1552 c8e5 ecec ef80 152f 152f\n\n00:00:03:00\t152c 152c\n"
|
||||
convert_scc(make_sub(tmp_path, "x.scc", cc3, Codec.SCC), None)
|
||||
assert "has no CC1 captions" in caplog.text
|
||||
|
||||
|
||||
def test_scc_with_a_bad_timecode_is_a_syntax_error():
|
||||
with pytest.raises(SyntaxError):
|
||||
Subtitle.parse(b"Scenarist_SCC V1.0\n\n00:00:xx;00\t9420 942f\n", Codec.SCC)
|
||||
|
||||
|
||||
def test_same_codec_is_noop(tmp_path):
|
||||
sub = make_sub(tmp_path, "x.srt", "1\n00:00:01,000 --> 00:00:02,000\nHi\n", Codec.SubRip)
|
||||
assert sub.convert(Codec.SubRip) == sub.path
|
||||
@@ -298,6 +403,37 @@ def test_segmented_fvtt_parses_and_converts(tmp_path, monkeypatch):
|
||||
assert cue_count(out) == 2
|
||||
|
||||
|
||||
def with_mdhd_timescale(data: bytes, timescale: int) -> bytes:
|
||||
"""The fixture with its version-0 mdhd timescale replaced; sample times stay in the same units."""
|
||||
at = data.index(b"mdhd") + 16
|
||||
return data[:at] + struct.pack(">I", timescale) + data[at + 4 :]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("timescale", [1000, 2000, 90000])
|
||||
def test_segmented_fvtt_cue_times_follow_the_media_timescale(timescale):
|
||||
data = (FIXTURES / "segmented.wvtt.mp4").read_bytes()
|
||||
assert with_mdhd_timescale(data, 1000) == data
|
||||
|
||||
captions, _ = Subtitle.merge_segmented_wvtt(with_mdhd_timescale(data, timescale))
|
||||
|
||||
times = [t for c in captions for t in (c.start, c.end)]
|
||||
assert times == pytest.approx([t * 1_000_000 / timescale for t in (1000, 2000, 3000, 4000)])
|
||||
|
||||
|
||||
def test_segmented_fttml_joins_a_cue_split_at_a_segment_boundary():
|
||||
data = build_stpp_mp4(
|
||||
ttml_fragment(("00:00:01.000", "00:00:02.000", "Carried")),
|
||||
ttml_fragment(("00:00:02.000", "00:00:03.500", "Carried"), ("00:00:03.500", "00:00:04.000", "Next")),
|
||||
)
|
||||
|
||||
captions = Subtitle.parse(data, Codec.fTTML).get_captions("en")
|
||||
|
||||
assert [(c.start / 1e6, c.end / 1e6, c.get_text()) for c in captions] == [
|
||||
(1.0, 3.5, "Carried"),
|
||||
(3.5, 4.0, "Next"),
|
||||
]
|
||||
|
||||
|
||||
def test_segmented_fttml_parses_and_converts(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
|
||||
frag = (
|
||||
@@ -319,3 +455,176 @@ def test_segmented_fttml_parses_and_converts(tmp_path, monkeypatch):
|
||||
assert sub.codec == Codec.TimedTextMarkupLang
|
||||
out = sub.convert(Codec.SubRip, forced=True)
|
||||
assert cue_count(out) == 2
|
||||
|
||||
|
||||
def downloaded_subtitle(tmp_path, monkeypatch, codec, data: bytes, descriptor: Track.Descriptor, track_data: dict):
|
||||
"""A Subtitle whose base download is a no-op, so download() runs only the post-processing on data."""
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
|
||||
monkeypatch.setattr(Track, "download", lambda *args, **kwargs: None)
|
||||
sub = Subtitle(url="https://example.test/x", language="en", codec=codec, descriptor=descriptor, data=track_data)
|
||||
sub.path = tmp_path / f"seg.{codec.extension}"
|
||||
sub.path.write_bytes(data)
|
||||
return sub
|
||||
|
||||
|
||||
def dash_subtitle(tmp_path, monkeypatch, codec, data: bytes, template: str):
|
||||
from lxml import etree
|
||||
|
||||
track_data = {
|
||||
"dash": {
|
||||
"adaptation_set": etree.fromstring(f"<AdaptationSet>{template}</AdaptationSet>"),
|
||||
"representation": etree.fromstring("<Representation/>"),
|
||||
"segment_durations": [],
|
||||
}
|
||||
}
|
||||
return downloaded_subtitle(tmp_path, monkeypatch, codec, data, Track.Descriptor.DASH, track_data)
|
||||
|
||||
|
||||
STPP_CUE = (
|
||||
'<?xml version="1.0" encoding="utf-8"?>'
|
||||
'<tt xmlns="http://www.w3.org/ns/ttml" xmlns:ttp="http://www.w3.org/ns/ttml#parameter"'
|
||||
' ttp:timeBase="media" xml:lang="en"><body><div>'
|
||||
'<p begin="00:06:02.000" end="00:06:02.839">Line</p>'
|
||||
"</div></body></tt>"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"template, offset, times",
|
||||
[
|
||||
(
|
||||
'<SegmentTemplate timescale="90000" presentationTimeOffset="180000">'
|
||||
'<SegmentTimeline><S t="180000" d="540000" r="10"/></SegmentTimeline></SegmentTemplate>',
|
||||
(2000, 6000),
|
||||
(360_000_000, 360_839_000),
|
||||
),
|
||||
(
|
||||
'<SegmentTemplate timescale="1000" presentationTimeOffset="3600000" duration="6000"/>',
|
||||
(3_600_000, 6000),
|
||||
(362_000_000, 362_839_000),
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_dash_fttml_cues_lose_the_presentation_time_offset(tmp_path, monkeypatch, template, offset, times):
|
||||
sub = dash_subtitle(tmp_path, monkeypatch, Codec.fTTML, build_stpp_mp4(STPP_CUE), template)
|
||||
assert sub.dash_offset_ms() == offset
|
||||
|
||||
sub.download(None, None) # type: ignore[arg-type]
|
||||
|
||||
assert sub.codec == Codec.TimedTextMarkupLang
|
||||
(caption,) = Subtitle.parse(sub.path.read_bytes(), Codec.TimedTextMarkupLang).get_captions("en")
|
||||
assert (caption.start, caption.end) == times
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["subby", "pycaption"])
|
||||
@pytest.mark.parametrize(
|
||||
"mdhd_timescale, pto, cues",
|
||||
[
|
||||
(1000, 1000, ("00:00:00.000 --> 00:00:01.000", "00:00:02.000 --> 00:00:03.000")),
|
||||
(2000, 500, ("00:00:00.000 --> 00:00:00.500", "00:00:01.000 --> 00:00:01.500")),
|
||||
],
|
||||
)
|
||||
def test_dash_fvtt_cues_lose_the_presentation_time_offset(tmp_path, monkeypatch, method, mdhd_timescale, pto, cues):
|
||||
template = f'<SegmentTemplate timescale="1000" presentationTimeOffset="{pto}" duration="2000"/>'
|
||||
data = with_mdhd_timescale((FIXTURES / "segmented.wvtt.mp4").read_bytes(), mdhd_timescale)
|
||||
sub = dash_subtitle(tmp_path, monkeypatch, Codec.fVTT, data, template)
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"conversion_method": method}, raising=False)
|
||||
|
||||
sub.download(None, None) # type: ignore[arg-type]
|
||||
|
||||
assert sub.codec == Codec.WebVTT
|
||||
text = sub.path.read_text("utf8")
|
||||
assert all(cue in text for cue in cues)
|
||||
|
||||
|
||||
def ttml_fragment(*cues: tuple[str, ...]) -> str:
|
||||
body = "".join(f'<p begin="{cue[0]}" end="{cue[1]}">{cue[2] if len(cue) > 2 else "Line"}</p>' for cue in cues)
|
||||
return f'<tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en"><body><div>{body}</div></body></tt>'
|
||||
|
||||
|
||||
def test_dash_fttml_with_no_cues_converts(tmp_path, monkeypatch):
|
||||
template = '<SegmentTemplate timescale="1000" presentationTimeOffset="2000" duration="6000"/>'
|
||||
sub = dash_subtitle(tmp_path, monkeypatch, Codec.fTTML, build_stpp_mp4(ttml_fragment()), template)
|
||||
|
||||
sub.download(None, None) # type: ignore[arg-type]
|
||||
|
||||
assert sub.codec == Codec.TimedTextMarkupLang
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fragments, expected",
|
||||
[
|
||||
(
|
||||
[
|
||||
ttml_fragment(),
|
||||
ttml_fragment(("00:00:06.000", "00:00:07.000")),
|
||||
ttml_fragment(("00:00:00.500", "00:00:01.000")),
|
||||
],
|
||||
[(14.0, 15.0), (16.5, 17.0)],
|
||||
),
|
||||
(
|
||||
[
|
||||
ttml_fragment(),
|
||||
ttml_fragment(("00:00:14.000", "00:00:15.000")),
|
||||
ttml_fragment(("00:00:16.500", "00:00:17.000")),
|
||||
],
|
||||
[(14.0, 15.0), (16.5, 17.0)],
|
||||
),
|
||||
(
|
||||
[
|
||||
ttml_fragment(),
|
||||
ttml_fragment(("00:00:07.000", "00:00:08.000")),
|
||||
ttml_fragment(("00:00:00.000", "00:00:01.000")),
|
||||
],
|
||||
[(15.0, 17.0)],
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_ism_fttml_cues_land_on_the_stream_timeline(tmp_path, monkeypatch, fragments, expected):
|
||||
times = [0, 80_000_000, 160_000_000]
|
||||
track_data = {"ism": {"segment_times": times, "fragment_times": times, "timescale": 10_000_000}}
|
||||
sub = downloaded_subtitle(
|
||||
tmp_path, monkeypatch, Codec.fTTML, build_stpp_mp4(*fragments), Track.Descriptor.ISM, track_data
|
||||
)
|
||||
|
||||
sub.download(None, None) # type: ignore[arg-type]
|
||||
|
||||
assert sub.codec == Codec.TimedTextMarkupLang
|
||||
captions = Subtitle.parse(sub.path.read_bytes(), Codec.TimedTextMarkupLang).get_captions("en")
|
||||
assert [(c.start / 1e6, c.end / 1e6) for c in captions] == expected
|
||||
|
||||
|
||||
def test_fttml_with_viewport_units_converts(tmp_path, monkeypatch):
|
||||
"""TTML2 ``vw``/``vh`` and ``rw``/``rh`` sizes, which pycaption rejects, still parse and convert.
|
||||
|
||||
Only the size attributes pycaption parses are rewritten: a negative one becomes 0, while an ``rh``
|
||||
font size and the same units in cue text stay as they are.
|
||||
"""
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
|
||||
frag = (
|
||||
'<?xml version="1.0" encoding="utf-8"?>'
|
||||
'<tt xmlns="http://www.w3.org/ns/ttml" xmlns:tts="http://www.w3.org/ns/ttml#styling"'
|
||||
' xmlns:ttp="http://www.w3.org/ns/ttml#parameter" xml:lang="ja" ttp:version="2">'
|
||||
'<head><styling><style xml:id="s1" tts:fontSize="5.33rh"/></styling><layout>'
|
||||
'<region xml:id="bottom" tts:extent="80vw 15vh" tts:position="center bottom 10vh"/>'
|
||||
'<region xml:id="side" tts:extent="15rw 80rh" tts:position="right 10vw center" tts:writingMode="tbrl"/>'
|
||||
"<region xml:id='edge' tts:origin='-5vw 80vh' tts:extent='90vw 10vh' tts:padding='1vh 2vw'/>"
|
||||
"</layout></head>"
|
||||
'<body region="bottom"><div>'
|
||||
'<p begin="00:00:01.000" end="00:00:02.000" style="s1">Speed 10vw</p>'
|
||||
'<p begin="00:00:03.000" end="00:00:04.000" region="side">Line 2</p>'
|
||||
'<p begin="00:00:05.000" end="00:00:06.000" region="edge">Line 3</p>'
|
||||
"</div></body></tt>"
|
||||
)
|
||||
styled = pycaption.DFXPWriter().write(Subtitle.parse(frag.encode(), Codec.TimedTextMarkupLang))
|
||||
assert 'tts:fontSize="5.33rh"' in styled
|
||||
|
||||
seg = tmp_path / "seg.stpp"
|
||||
seg.write_bytes(build_stpp_mp4(frag))
|
||||
sub = Subtitle(url="https://example.test/x", language="ja", codec=Codec.fTTML)
|
||||
sub.path = seg
|
||||
|
||||
sub.convert(Codec.TimedTextMarkupLang)
|
||||
out = sub.convert(Codec.SubRip, forced=True)
|
||||
assert cue_count(out) == 3
|
||||
assert "Speed 10vw" in out.read_text("utf8")
|
||||
|
||||
@@ -3,11 +3,19 @@ import pytest
|
||||
from unshackle.core.tracks import Subtitle, Tracks
|
||||
|
||||
|
||||
def sub(lang: str, forced: bool = False, sdh: bool = False, cc: bool = False, orig: bool = False) -> Subtitle:
|
||||
def sub(
|
||||
lang: str,
|
||||
forced: bool = False,
|
||||
sdh: bool = False,
|
||||
cc: bool = False,
|
||||
orig: bool = False,
|
||||
codec: Subtitle.Codec = Subtitle.Codec.SubRip,
|
||||
tag: str = "",
|
||||
) -> Subtitle:
|
||||
track = Subtitle(
|
||||
url=f"https://example.test/{lang}-{forced}-{sdh}-{cc}",
|
||||
url=f"https://example.test/{lang}-{forced}-{sdh}-{cc}-{codec.value}{tag}",
|
||||
language=lang,
|
||||
codec=Subtitle.Codec.SubRip,
|
||||
codec=codec,
|
||||
forced=forced,
|
||||
sdh=sdh,
|
||||
cc=cc,
|
||||
@@ -126,11 +134,11 @@ def test_language_grouping_keeps_regional_variants_adjacent_through_sections() -
|
||||
)
|
||||
t.sort_subtitles(by_language=["en"], group_by="language")
|
||||
assert shape(t) == [
|
||||
("en-US", "normal"),
|
||||
("en-US", "sdh"),
|
||||
("en-GB", "forced"),
|
||||
("en-GB", "normal"),
|
||||
("en-GB", "sdh"),
|
||||
("en-US", "normal"),
|
||||
("en-US", "sdh"),
|
||||
("fi", "normal"),
|
||||
("fi", "sdh"),
|
||||
]
|
||||
@@ -168,7 +176,15 @@ def test_priority_overlapping_entries_are_harmless() -> None:
|
||||
t = Tracks()
|
||||
t.add([sub("ar"), sub("en-GB"), sub("en-US"), sub("es"), sub("ja")])
|
||||
t.sort_subtitles(by_language=["en", "en-US", "es"], group_by="language")
|
||||
assert langs(t) == ["en-GB", "en-US", "es", "ar", "ja"]
|
||||
assert langs(t) == ["en-US", "en-GB", "es", "ar", "ja"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("group_by", ["language", "type"])
|
||||
def test_a_regional_priority_outranks_its_sibling(group_by: str) -> None:
|
||||
t = Tracks()
|
||||
t.add([sub("en-GB"), sub("en-US"), sub("fr")])
|
||||
t.sort_subtitles(by_language=["en-US"], group_by=group_by)
|
||||
assert langs(t) == ["en-US", "en-GB", "fr"]
|
||||
|
||||
|
||||
def test_no_priority_leaves_order_unchanged(many: Tracks) -> None:
|
||||
@@ -216,3 +232,55 @@ def test_exact_priority_still_falls_back_when_no_tag_is_string_equal() -> None:
|
||||
def test_unparseable_priority_entry_is_ignored(many: Tracks, exact: bool) -> None:
|
||||
many.sort_subtitles(by_language=["en", "engrish", "f", ""], group_by="language", exact_match=exact)
|
||||
assert langs(many) == ["en", "ar", "bg", "es", "fr", "ja"]
|
||||
|
||||
|
||||
def test_a_bare_audio_priority_sorts_the_meant_variant_then_its_other_forms() -> None:
|
||||
from unshackle.core.tracks import Audio
|
||||
|
||||
t = Tracks()
|
||||
t.add(
|
||||
[
|
||||
Audio(id_=lang, url=f"https://x/{lang}", language=lang, codec=Audio.Codec.AAC, bitrate=bitrate)
|
||||
for lang, bitrate in (("en", 3), ("es-419", 2), ("es-ES", 1))
|
||||
]
|
||||
)
|
||||
t.sort_audio(by_language=["es"])
|
||||
assert [str(a.language) for a in t.audio] == ["es-ES", "es-419", "en"]
|
||||
|
||||
|
||||
def test_all_sorts_the_original_track_then_its_other_regional_forms() -> None:
|
||||
from unshackle.core.tracks import Audio
|
||||
|
||||
t = Tracks()
|
||||
t.add(
|
||||
[
|
||||
Audio(
|
||||
id_=lang,
|
||||
url=f"https://x/{lang}",
|
||||
language=lang,
|
||||
codec=Audio.Codec.AAC,
|
||||
bitrate=bitrate,
|
||||
is_original_lang=orig,
|
||||
)
|
||||
for lang, bitrate, orig in (("en", 3, False), ("fr-FR", 2, False), ("fr-CA", 1, True))
|
||||
]
|
||||
)
|
||||
t.sort_audio(by_language=["all"])
|
||||
assert [str(a.language) for a in t.audio] == ["fr-CA", "fr-FR", "en"]
|
||||
|
||||
|
||||
def test_dedupe_subtitle_codecs_keeps_the_first_listed_codec_of_each_variant() -> None:
|
||||
codec = Subtitle.Codec
|
||||
vtt = sub("en", codec=codec.WebVTT)
|
||||
wvtt = sub("en", codec=codec.fVTT)
|
||||
stpp = sub("en", codec=codec.fTTML)
|
||||
stpp_cc = sub("en", cc=True, codec=codec.fTTML)
|
||||
srt = sub("en")
|
||||
de_wvtt = sub("de", codec=codec.fVTT)
|
||||
vtt_second = sub("en", codec=codec.WebVTT, tag="-second")
|
||||
tracks = Tracks()
|
||||
tracks.subtitles = [wvtt, stpp, vtt, stpp_cc, srt, de_wvtt, vtt_second]
|
||||
|
||||
tracks.dedupe_subtitle_codecs([codec.WebVTT, codec.fTTML, codec.fVTT])
|
||||
|
||||
assert tracks.subtitles == [vtt, stpp_cc, srt, de_wvtt, vtt_second]
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
from pathlib import Path
|
||||
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, 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:
|
||||
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_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
|
||||
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
|
||||
@@ -0,0 +1,19 @@
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.core.tracks import Audio, Tracks
|
||||
|
||||
|
||||
def audio(lang: str, bitrate: int, id_: str) -> Audio:
|
||||
return Audio(url=f"http://x/{id_}", id_=id_, language=lang, codec=Audio.Codec.AAC, bitrate=bitrate, channels=2.0)
|
||||
|
||||
|
||||
def test_naming_a_track_keeps_its_region() -> None:
|
||||
track = audio("fr-FR", 128000, "a1")
|
||||
assert track.name is None
|
||||
assert track.language.territory == "FR"
|
||||
assert Language.get("fr-FR").territory == "FR"
|
||||
|
||||
|
||||
def test_a_regional_request_picks_its_own_variant_over_a_higher_bitrate_sibling() -> None:
|
||||
tracks = [audio("fr-FR", 128000, "a1"), audio("fr-CA", 192000, "a2")]
|
||||
assert [str(t.language) for t in Tracks.by_language(tracks, ["fr-FR"])] == ["fr-FR"]
|
||||
@@ -97,6 +97,20 @@ def test_sort_videos_resolution_outranks_bitrate() -> None:
|
||||
assert [t.id for t in tracks.videos] == ["lo-bitrate-2160", "hi-bitrate-720"]
|
||||
|
||||
|
||||
def test_sort_videos_orders_crops_of_one_resolution_by_bitrate() -> None:
|
||||
tracks = Tracks()
|
||||
tracks.videos = [
|
||||
make_video("1610-lo", height=1610, bitrate=4_000_000, width=3840),
|
||||
make_video("1606-hi", height=1606, bitrate=15_000_000, width=3840),
|
||||
make_video("1610-hi", height=1610, bitrate=16_000_000, width=3840),
|
||||
make_video("804", height=804, bitrate=20_000_000, width=1920),
|
||||
]
|
||||
|
||||
tracks.sort_videos()
|
||||
|
||||
assert [t.id for t in tracks.videos] == ["1610-hi", "1606-hi", "1610-lo", "804"]
|
||||
|
||||
|
||||
def test_sort_videos_unknown_bitrate_still_wins_on_resolution() -> None:
|
||||
tracks = Tracks()
|
||||
tracks.videos = [
|
||||
@@ -136,3 +150,25 @@ def test_sort_audio_codec_priority_beats_bitrate() -> None:
|
||||
|
||||
best = Tracks.by_language(tracks.audio, ["en"])[0]
|
||||
assert best.id == "ec3-320"
|
||||
|
||||
|
||||
def test_dedupe_keeps_the_first_copy_and_every_track_that_differs() -> None:
|
||||
tracks = Tracks()
|
||||
tracks.audio = [
|
||||
make_audio("ec3-a", codec=Audio.Codec.EC3, bitrate=128_000),
|
||||
make_audio("ec3-b", codec=Audio.Codec.EC3, bitrate=128_000),
|
||||
make_audio("aac", codec=Audio.Codec.AAC, bitrate=128_000),
|
||||
make_audio("ec3-desc", codec=Audio.Codec.EC3, bitrate=128_000, descriptive=True),
|
||||
make_audio("ec3-atmos", codec=Audio.Codec.EC3, bitrate=128_000, joc=16),
|
||||
make_audio("ec3-de", codec=Audio.Codec.EC3, bitrate=128_000, language="de"),
|
||||
]
|
||||
tracks.videos = [
|
||||
make_video("hevc-a", height=1080, bitrate=5_000_000, width=1920),
|
||||
make_video("hevc-b", height=1080, bitrate=5_000_000, width=1920),
|
||||
make_video("hevc-hi", height=1080, bitrate=8_000_000, width=1920),
|
||||
]
|
||||
|
||||
tracks.dedupe()
|
||||
|
||||
assert [a.id for a in tracks.audio] == ["ec3-a", "aac", "ec3-desc", "ec3-atmos", "ec3-de"]
|
||||
assert [v.id for v in tracks.videos] == ["hevc-a", "hevc-hi"]
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.tracks import Tracks, Video
|
||||
|
||||
MASTERING = {
|
||||
"side_data_type": "Mastering display metadata",
|
||||
"red_x": "46400/65536",
|
||||
"red_y": "19137/65536",
|
||||
"green_x": "11142/65536",
|
||||
"green_y": "52233/65536",
|
||||
"blue_x": "8586/65536",
|
||||
"blue_y": "3015/65536",
|
||||
"white_point_x": "20494/65536",
|
||||
"white_point_y": "21562/65536",
|
||||
"min_luminance": "2/16384",
|
||||
"max_luminance": "256001/256",
|
||||
}
|
||||
NO_LIGHT_LEVEL = {"side_data_type": "Content light level metadata", "max_content": 0, "max_average": 0}
|
||||
|
||||
|
||||
def make_video(tmp_path: Path, codec: Video.Codec, range_: Video.Range) -> Video:
|
||||
video = Video(url="https://example.test/v.m3u8", language="en", codec=codec, range_=range_)
|
||||
video.path = tmp_path / "v.mp4"
|
||||
video.path.write_bytes(b"\x00" * 16)
|
||||
return video
|
||||
|
||||
|
||||
def probe_returns(monkeypatch: pytest.MonkeyPatch, stream: dict[str, Any]) -> None:
|
||||
monkeypatch.setattr(binaries, "FFProbe", Path("ffprobe"))
|
||||
stdout = json.dumps({"streams": [stream]})
|
||||
monkeypatch.setattr(subprocess, "run", lambda *a, **k: SimpleNamespace(stdout=stdout, returncode=0))
|
||||
|
||||
|
||||
def pairs(args: list[str]) -> dict[str, str]:
|
||||
return dict(zip(args[::2], args[1::2]))
|
||||
|
||||
|
||||
def test_hdr10_vp9_gets_cicp_and_mastering_display(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
probe_returns(monkeypatch, {"color_transfer": "smpte2084", "side_data_list": [MASTERING, NO_LIGHT_LEVEL]})
|
||||
|
||||
args = pairs(make_video(tmp_path, Video.Codec.VP9, Video.Range.HDR10).vp9_colour_args(0))
|
||||
|
||||
assert args["--colour-primaries"] == "0:9"
|
||||
assert args["--colour-transfer-characteristics"] == "0:16"
|
||||
assert args["--colour-matrix-coefficients"] == "0:9"
|
||||
assert args["--chromaticity-coordinates"] == "0:0.70801,0.29201,0.17001,0.79701,0.13101,0.04601"
|
||||
assert args["--white-colour-coordinates"] == "0:0.31271,0.32901"
|
||||
assert args["--max-luminance"] == "0:1000.003906"
|
||||
assert args["--min-luminance"] == "0:0.000122"
|
||||
assert "--max-content-light" not in args
|
||||
|
||||
|
||||
def test_partial_mastering_display_keeps_the_cicp_args(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
partial = {"side_data_type": "Mastering display metadata", "min_luminance": "1/10000", "max_luminance": "1000/1"}
|
||||
probe_returns(monkeypatch, {"color_transfer": "smpte2084", "side_data_list": [partial]})
|
||||
|
||||
args = pairs(make_video(tmp_path, Video.Codec.VP9, Video.Range.HDR10).vp9_colour_args(1))
|
||||
|
||||
assert args["--colour-transfer-characteristics"] == "1:16"
|
||||
assert "--max-luminance" not in args
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("transfer", "range_", "expected"),
|
||||
[
|
||||
("smpte2084", Video.Range.SDR, "0:16"),
|
||||
("arib-std-b67", Video.Range.SDR, "0:18"),
|
||||
("bt709", Video.Range.HDR10, None),
|
||||
("unknown", Video.Range.HLG, "0:18"),
|
||||
("unknown", Video.Range.SDR, None),
|
||||
],
|
||||
)
|
||||
def test_the_file_transfer_wins_over_the_range(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, transfer: str, range_: Video.Range, expected: Optional[str]
|
||||
) -> None:
|
||||
probe_returns(monkeypatch, {"color_transfer": transfer})
|
||||
|
||||
args = pairs(make_video(tmp_path, Video.Codec.VP9, range_).vp9_colour_args(0))
|
||||
|
||||
assert args.get("--colour-transfer-characteristics") == expected
|
||||
|
||||
|
||||
def test_no_ffprobe_falls_back_to_the_range(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(binaries, "FFProbe", None)
|
||||
|
||||
args = pairs(make_video(tmp_path, Video.Codec.VP9, Video.Range.HDR10).vp9_colour_args(0))
|
||||
|
||||
assert args == {
|
||||
"--colour-primaries": "0:9",
|
||||
"--colour-transfer-characteristics": "0:16",
|
||||
"--colour-matrix-coefficients": "0:9",
|
||||
}
|
||||
|
||||
|
||||
def test_mux_passes_the_vp9_args_and_keeps_the_hevc_hlg_flag(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mux_args: Callable[..., list[str]]
|
||||
) -> None:
|
||||
monkeypatch.setattr(binaries, "FFProbe", None)
|
||||
|
||||
vp9 = mux_args(Tracks(make_video(tmp_path, Video.Codec.VP9, Video.Range.HDR10)), {"video": 0})
|
||||
hevc = mux_args(Tracks(make_video(tmp_path, Video.Codec.HEVC, Video.Range.HLG)), {"video": 0})
|
||||
|
||||
assert vp9[vp9.index("--colour-transfer-characteristics") + 1] == "0:16"
|
||||
assert hevc[hevc.index("--color-transfer-characteristics") + 1] == "0:18"
|
||||
@@ -0,0 +1,73 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from pymediainfo import MediaInfo
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.drm.verify import read_top_level_box
|
||||
from unshackle.core.titles import Movie
|
||||
from unshackle.core.tracks import Tracks, Video
|
||||
from unshackle.core.tracks import tracks as tracks_module
|
||||
|
||||
|
||||
def vvc_mp4(path: Path) -> None:
|
||||
"""Encode a few frames of H.266 into an MP4, or skip when FFmpeg has no VVC encoder."""
|
||||
if not binaries.FFMPEG:
|
||||
pytest.skip("needs ffmpeg")
|
||||
encode = subprocess.run(
|
||||
[binaries.FFMPEG, "-v", "error", "-f", "lavfi", "-i", "testsrc=s=128x72:r=24:d=0.25"]
|
||||
+ ["-c:v", "libvvenc", "-preset", "faster", str(path)],
|
||||
capture_output=True,
|
||||
)
|
||||
if encode.returncode:
|
||||
pytest.skip("ffmpeg has no libvvenc")
|
||||
|
||||
|
||||
def vvc_tracks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Tracks:
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path / "temp", raising=False)
|
||||
(tmp_path / "temp").mkdir()
|
||||
video = Video(url="https://x.example/v.m3u8", language="en", codec=Video.Codec.VVC, id_="v")
|
||||
video.path = tmp_path / "v.mp4"
|
||||
vvc_mp4(video.path)
|
||||
tracks = Tracks()
|
||||
tracks.videos = [video]
|
||||
return tracks
|
||||
|
||||
|
||||
def video_codecs(path: Path) -> list[str]:
|
||||
return [t["properties"]["codec_id"] for t in tracks_module.mkvmerge_tracks(path) if t["type"] == "video"]
|
||||
|
||||
|
||||
def test_an_h266_track_is_muxed_as_vvc(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
if not binaries.MKVToolNix:
|
||||
pytest.skip("needs mkvmerge")
|
||||
tracks = vvc_tracks(tmp_path, monkeypatch)
|
||||
out, code, _ = tracks.mux("t", delete=False, audio_expected=False, output_path=tmp_path / "out.mkv")
|
||||
assert code == 0 and video_codecs(out) == ["V_MPEGI/ISO/VVC"]
|
||||
assert tracks.videos[0].path == tmp_path / "v.mp4" and tracks.videos[0].path.exists()
|
||||
assert not list((tmp_path / "temp").iterdir())
|
||||
movie = Movie(id_="movie-0001", service=type("EXAMPLE", (), {}), name="Some Movie", year=2024)
|
||||
assert ".H.266" in movie.get_filename(MediaInfo.parse(out))
|
||||
|
||||
|
||||
def test_the_mp4box_route_gets_the_original_h266_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
if not getattr(binaries, "MP4Box", None):
|
||||
pytest.skip("needs MP4Box")
|
||||
tracks = vvc_tracks(tmp_path, monkeypatch)
|
||||
tracks.videos[0].stereo = True
|
||||
out, code, _ = tracks.mux("t", delete=False, audio_expected=False, output_path=tmp_path / "out.mkv")
|
||||
moov = read_top_level_box(out, b"moov") or b""
|
||||
assert code == 0 and out.suffix == ".mp4" and b"vvc1" in moov and b"FFID" not in moov
|
||||
|
||||
|
||||
def test_a_remux_with_the_wrong_codec_id_stops_the_mux(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
tracks = vvc_tracks(tmp_path, monkeypatch)
|
||||
old_ffmpeg = [{"type": "video", "properties": {"codec_id": "V_MS/VFW/FOURCC"}}]
|
||||
monkeypatch.setattr(tracks_module, "mkvmerge_tracks", lambda path: old_ffmpeg)
|
||||
with pytest.raises(RuntimeError, match="FFmpeg wrote H.266 as V_MS/VFW/FOURCC"):
|
||||
tracks_module.remux_vvc(tracks.videos[0].path)
|
||||
assert not list((tmp_path / "temp").iterdir())
|
||||
@@ -10,7 +10,7 @@ survive, while duplicate headers collapse and boundary-duplicate cues dedupe.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unshackle.core.utils.webvtt import merge_segmented_webvtt
|
||||
from unshackle.core.utils.webvtt import merge_segmented_webvtt, rebase_webvtt, timestamp_ms
|
||||
|
||||
SEGMENTED_VTT = (
|
||||
"WEBVTT\n"
|
||||
@@ -105,3 +105,27 @@ def test_merge_skips_malformed_timing_line():
|
||||
out = merge_segmented_webvtt(vtt)
|
||||
assert "Good" in out
|
||||
assert "Broken" not in out
|
||||
|
||||
|
||||
def test_rebase_moves_live_clock_cues_to_zero():
|
||||
vtt = "WEBVTT\n\n498024:05:44.300 --> 498024:05:44.829 line:0.01%\nText\n"
|
||||
out = rebase_webvtt(vtt, timestamp_ms("498024:00:14.700"))
|
||||
assert "00:05:29.600 --> 00:05:30.129 line:0.01%\nText" in out
|
||||
|
||||
|
||||
def test_rebase_moves_cues_when_the_first_is_carried_over_from_before_the_offset():
|
||||
vtt = "WEBVTT\n\n03:59:43.500 --> 03:59:45.000\nCarried\n\n04:03:32.598 --> 04:03:32.698\nNext\n"
|
||||
out = rebase_webvtt(vtt, timestamp_ms("03:59:44.000"), 2002)
|
||||
assert "00:00:00.000 --> 00:00:01.000\nCarried" in out
|
||||
assert "00:03:48.598 --> 00:03:48.698\nNext" in out
|
||||
|
||||
|
||||
def test_rebase_leaves_a_later_period_with_a_small_offset_alone():
|
||||
vtt = "WEBVTT\n\n00:00:05.000 --> 00:00:12.000\nText\n"
|
||||
assert rebase_webvtt(vtt, 10_000, 2000) == vtt
|
||||
|
||||
|
||||
def test_rebase_leaves_presentation_time_cues_alone():
|
||||
vtt = "WEBVTT\n\n00:05:29.600 --> 00:05:30.129\nText\n"
|
||||
assert rebase_webvtt(vtt, 1_792_886_414_700) == vtt
|
||||
assert rebase_webvtt(vtt, 0) == vtt
|
||||
|
||||
Reference in New Issue
Block a user