mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-25 18:35:07 +00:00
chore(release): promote 6.0.0 to main
This commit is contained in:
@@ -57,3 +57,78 @@ def test_download_with_flag_bypasses_proxy(tmp_path, monkeypatch) -> None:
|
||||
assert not proxied.got
|
||||
assert direct.got == [URL]
|
||||
assert attachment.path is not None and attachment.path.read_bytes() == b"jpegdata"
|
||||
|
||||
|
||||
def test_download_with_proxy_download_uses_only_that_proxy(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
seen: dict = {}
|
||||
|
||||
def fake_direct(session, proxy=None):
|
||||
seen["proxy"] = proxy
|
||||
return FakeSession(proxies={"all": proxy})
|
||||
|
||||
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)
|
||||
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)
|
||||
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(
|
||||
plain, no_proxy_download=True, proxy_download="http://dl-proxy:2"
|
||||
)
|
||||
assert "p" not in seen and plain.got == [URL]
|
||||
|
||||
|
||||
def test_direct_session_routes_through_the_given_proxy() -> None:
|
||||
base = requests.Session()
|
||||
base.headers["X-Test"] = "1"
|
||||
new = track_module.direct_session(base, "http://dl-proxy:2")
|
||||
assert new.headers["X-Test"] == "1"
|
||||
assert new.proxies == {"http": "http://dl-proxy:2", "https": "http://dl-proxy:2"}
|
||||
assert requests.utils.select_proxy("https://cdn.example.com/a", new.proxies) == "http://dl-proxy:2"
|
||||
|
||||
|
||||
def test_direct_session_proxy_beats_environment(monkeypatch) -> None:
|
||||
monkeypatch.setenv("HTTPS_PROXY", "http://env-proxy:9")
|
||||
new = track_module.direct_session(requests.Session(), "http://dl-proxy:2")
|
||||
settings = new.merge_environment_settings("https://cdn.example.com/a", {}, None, None, None)
|
||||
assert settings["proxies"]["https"] == "http://dl-proxy:2"
|
||||
|
||||
|
||||
def test_direct_session_copies_rnet_cookies_set_by_name() -> None:
|
||||
from unshackle.core.session import RnetSession
|
||||
|
||||
rs = RnetSession()
|
||||
rs.cookies.set("via_set", "1", domain="cdn.example.com")
|
||||
rs.cookies["via_item"] = "3"
|
||||
new = track_module.direct_session(rs, "http://dl-proxy:2")
|
||||
assert new.cookies.get("via_set") == "1"
|
||||
assert new.cookies.get("via_item") == "3"
|
||||
|
||||
|
||||
def test_delete_removes_only_files_in_the_temp_directory(tmp_path, monkeypatch) -> None:
|
||||
temp = tmp_path / "temp"
|
||||
temp.mkdir()
|
||||
monkeypatch.setattr(config.directories, "temp", temp)
|
||||
temp_font = temp / "font.ttf"
|
||||
user_font = tmp_path / "font.ttf"
|
||||
temp_font.write_bytes(b"font")
|
||||
user_font.write_bytes(b"font")
|
||||
|
||||
for path in (temp_font, user_font):
|
||||
attachment = Attachment(path=path)
|
||||
attachment.delete()
|
||||
assert attachment.path is None
|
||||
|
||||
assert not temp_font.exists()
|
||||
assert user_font.exists()
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Channel values that no float can hold.
|
||||
|
||||
An immersive layout names its height channels in a third figure, e.g. 5.1.4. A service
|
||||
assigning that straight onto a track keeps it out of validation, but a remote download
|
||||
sends the track as JSON and rebuilds it through Audio(), which parses the value.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.tracks import Audio
|
||||
|
||||
|
||||
@pytest.mark.parametrize("layout", ["5.1.4", "7.1.2", "9.1.6"])
|
||||
def test_an_immersive_layout_survives_construction(layout: str) -> None:
|
||||
assert Audio(id_="a1", url="https://example.test/a", language="en", channels=layout).channels == layout
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "expected"),
|
||||
[("5.1", 5.1), ("2ch", 2.0), ("2", 2.0), ("2.0", 2.0), ("A000", 2.0), ("F801", 5.1), (6, 6.0)],
|
||||
)
|
||||
def test_existing_channel_forms_are_unchanged(value: object, expected: float) -> None:
|
||||
assert Audio.parse_channels(value) == 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):
|
||||
Audio.parse_channels(value)
|
||||
|
||||
|
||||
def test_an_immersive_layout_round_trips_as_a_dict() -> None:
|
||||
"""A remote download rebuilds every track from the dict the server sent."""
|
||||
track = Audio(id_="a1", url="https://example.test/a", language="en", channels="5.1.4", bitrate=448000)
|
||||
assert Audio.from_dict(track.to_dict()).channels == "5.1.4"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("channels", "total"),
|
||||
[("5.1.4", 10.0), ("7.1.2", 10.0), (5.1, 5.1), (6.0, 6.0), ("2.0", 2.0)],
|
||||
)
|
||||
def test_channel_total_compares_both_forms(channels: object, total: float) -> None:
|
||||
"""--channels rounds the sub channel up, so both forms have to reach that arithmetic."""
|
||||
assert Audio.channel_total(channels) == total
|
||||
@@ -0,0 +1,110 @@
|
||||
import textwrap
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.constants import SPACED_AUDIO_CODECS
|
||||
from unshackle.core.manifests.hls import HLS
|
||||
from unshackle.core.tracks.audio import Audio
|
||||
|
||||
DTS_X_GROUP = [
|
||||
("dtsx", Audio.Codec.DTSX),
|
||||
("ec-3", Audio.Codec.EC3),
|
||||
("mp4a", Audio.Codec.AAC),
|
||||
]
|
||||
|
||||
|
||||
def test_dtsc_maps_to_dts() -> None:
|
||||
assert Audio.Codec.from_mime("dtsc") == Audio.Codec.DTS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mime", ["dtsx", "dtsy"])
|
||||
def test_dts_uhd_sample_entries_map_to_dtsx(mime: str) -> None:
|
||||
"""DTS-UHD is a separate bitstream, so it must not share the DTS name."""
|
||||
assert Audio.Codec.from_mime(mime) == Audio.Codec.DTSX
|
||||
assert Audio.Codec.from_codecs(f"avc1.64001f,{mime},ec-3,mp4a.40.2") == Audio.Codec.DTSX
|
||||
assert Audio.Codec.DTSX.value == "DTS-X", "':' is not a legal path character on Windows"
|
||||
|
||||
|
||||
def test_unknown_mime_still_raises() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
Audio.Codec.from_mime("dtsz")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("uri", "expected"),
|
||||
[
|
||||
("r/composite_448k_dtsx_en_PRIMARY_de37f606-8b62-4116-bdec-0de711f2b7d0_x.m3u8", Audio.Codec.DTSX),
|
||||
("r/composite_256k_ec-3_cs_PRIMARY_b4556be9-7eb3-47a9-b103-d97263a99ec1_x.m3u8", Audio.Codec.EC3),
|
||||
("r/composite_128k_mp4a.40.2_en_NARRATION_3891a283-94c0-4b89-9dc8-a70fcec25661_x.m3u8", Audio.Codec.AAC),
|
||||
("r/composite_128k_mp4a.40.2_en_PRIMARY_b4556be9-7eb3-47a9-b103-d97263a9ec-3_x.m3u8", Audio.Codec.AAC),
|
||||
("https://cdn/x/dtsx-448k/index.m3u8", Audio.Codec.DTSX),
|
||||
("https://cdn/x/dtsx/index.m3u8", Audio.Codec.DTSX),
|
||||
("r/audio-en.m3u8", Audio.Codec.DTSX),
|
||||
],
|
||||
)
|
||||
def test_select_audio_codec_matches_delimited_codecs(uri: str, expected: Audio.Codec) -> None:
|
||||
assert HLS.select_audio_codec(DTS_X_GROUP, uri) == expected
|
||||
|
||||
|
||||
def test_select_audio_codec_will_not_read_one_codec_out_of_another() -> None:
|
||||
""" "ac-3" sits inside the "eac-3" that names an E-AC-3 rendition."""
|
||||
candidates = [("ec-3", Audio.Codec.EC3), ("ac-3", Audio.Codec.AC3)]
|
||||
assert HLS.select_audio_codec(candidates, "https://cdn/x/audio_ac-3_192k.m3u8") == Audio.Codec.AC3
|
||||
assert HLS.select_audio_codec(candidates, "https://cdn/x/audio_eac-3_768k.m3u8") == Audio.Codec.EC3
|
||||
|
||||
|
||||
def test_select_audio_codec_ignores_the_query_string() -> None:
|
||||
assert HLS.select_audio_codec(DTS_X_GROUP, "r/composite_448k_dtsx_en.m3u8?fallback=mp4a") == Audio.Codec.DTSX
|
||||
|
||||
|
||||
def test_select_audio_codec_holds_a_single_declaration() -> None:
|
||||
"""One declared codec needs no URI, so a group of one is never guessed at."""
|
||||
assert HLS.select_audio_codec([("mp4a", Audio.Codec.AAC)], "r/anything_dtsx.m3u8") == Audio.Codec.AAC
|
||||
assert HLS.select_audio_codec([], "r/x.m3u8") is None
|
||||
assert HLS.select_audio_codec(None, None) is None
|
||||
|
||||
|
||||
def test_spaced_codec_constants_name_real_codecs() -> None:
|
||||
"""The constant holds bare strings, so a rename must not silently stop matching."""
|
||||
for value in SPACED_AUDIO_CODECS:
|
||||
assert value in {c.value for c in Audio.Codec}, f"{value} is not an Audio.Codec value"
|
||||
|
||||
|
||||
def test_a_short_ladder_rung_cannot_hide_a_group_codec() -> None:
|
||||
"""
|
||||
One GROUP-ID is reached from every variant that references it, and a low rung may
|
||||
declare fewer codecs than the group holds. The union has to survive the short rung.
|
||||
"""
|
||||
manifest = textwrap.dedent("""\
|
||||
#EXTM3U
|
||||
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="A",NAME="English",LANGUAGE="en",CHANNELS="10",URI="composite_448k_dtsx_en.m3u8"
|
||||
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="A",NAME="Czech",LANGUAGE="cs",CHANNELS="6",URI="composite_256k_ec-3_cs.m3u8"
|
||||
#EXT-X-STREAM-INF:BANDWIDTH=9000000,CODECS="hvc1.2.4.L150.90,dtsx,ec-3",AUDIO="A"
|
||||
v_high.m3u8
|
||||
#EXT-X-STREAM-INF:BANDWIDTH=400000,CODECS="avc1.64001f,ec-3",AUDIO="A"
|
||||
v_low.m3u8
|
||||
""")
|
||||
tracks = HLS.from_text(manifest, "https://example.test/master.m3u8").to_tracks("en")
|
||||
by_lang = {str(t.language): t.codec for t in tracks.audio}
|
||||
assert by_lang["en"] == Audio.Codec.DTSX, "the low rung dropped dtsx from the group"
|
||||
assert by_lang["cs"] == Audio.Codec.EC3
|
||||
|
||||
|
||||
def test_the_group_fallback_does_not_depend_on_variant_order() -> None:
|
||||
"""
|
||||
A rendition URI that names no codec falls back to a codec the group declares. Which
|
||||
one must not depend on where the packager put its variants: ascending by BANDWIDTH is
|
||||
as common as descending, and picking the lossy label makes the premium rendition
|
||||
unreachable through --acodec.
|
||||
"""
|
||||
variants = [
|
||||
'#EXT-X-STREAM-INF:BANDWIDTH=9000000,CODECS="hvc1.2.4.L150.90,dtsx,ec-3",AUDIO="A"\nv_high.m3u8',
|
||||
'#EXT-X-STREAM-INF:BANDWIDTH=400000,CODECS="avc1.64001f,ec-3",AUDIO="A"\nv_low.m3u8',
|
||||
]
|
||||
header = (
|
||||
'#EXTM3U\n#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="A",NAME="English",LANGUAGE="en",CHANNELS="10",URI="audio_en.m3u8"\n'
|
||||
)
|
||||
for order in (variants, list(reversed(variants))):
|
||||
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}"
|
||||
@@ -14,73 +14,69 @@ from pathlib import Path
|
||||
from unshackle.core.tracks.track import has_encrypted_sample_entry
|
||||
|
||||
|
||||
def _box(fmt: bytes, payload: bytes = b"") -> bytes:
|
||||
def box(fmt: bytes, payload: bytes = b"") -> bytes:
|
||||
return struct.pack(">I", 8 + len(payload)) + fmt + payload
|
||||
|
||||
|
||||
def _sample_entry(fmt: bytes, payload: bytes = b"") -> bytes:
|
||||
body = b"\x00" * 6 + struct.pack(">H", 1) + payload # reserved + data_reference_index
|
||||
def sample_entry(fmt: bytes, payload: bytes = b"") -> bytes:
|
||||
body = b"\x00" * 6 + struct.pack(">H", 1) + payload
|
||||
return struct.pack(">I", 8 + len(body)) + fmt + body
|
||||
|
||||
|
||||
def _stsd(entries: list[bytes]) -> bytes:
|
||||
body = b"\x00" * 4 + struct.pack(">I", len(entries)) + b"".join(entries) # version/flags + count
|
||||
return _box(b"stsd", body)
|
||||
def stsd(entries: list[bytes]) -> bytes:
|
||||
body = b"\x00" * 4 + struct.pack(">I", len(entries)) + b"".join(entries)
|
||||
return box(b"stsd", body)
|
||||
|
||||
|
||||
def _moov(*children: bytes) -> bytes:
|
||||
stbl = _box(b"stbl", b"".join(children))
|
||||
return _box(b"moov", _box(b"trak", _box(b"mdia", _box(b"minf", stbl))))
|
||||
def moov(*children: bytes) -> bytes:
|
||||
stbl = box(b"stbl", b"".join(children))
|
||||
return box(b"moov", box(b"trak", box(b"mdia", box(b"minf", stbl))))
|
||||
|
||||
|
||||
FTYP = _box(b"ftyp", b"isom\x00\x00\x02\x00isomiso2")
|
||||
# stray [size][encv] byte run as compressed A/V payload could randomly contain
|
||||
FTYP = box(b"ftyp", b"isom\x00\x00\x02\x00isomiso2")
|
||||
STRAY_ENCV = b"\xde\xad" * 4 + struct.pack(">I", 100) + b"encv" + b"\xbe\xef" * 8
|
||||
|
||||
|
||||
def _write(tmp_path: Path, name: str, *boxes: bytes) -> Path:
|
||||
def write(tmp_path: Path, name: str, *boxes: bytes) -> Path:
|
||||
f = tmp_path / name
|
||||
f.write_bytes(b"".join(boxes))
|
||||
return f
|
||||
|
||||
|
||||
def test_dual_stsd_encv_and_avc1_detected(tmp_path: Path) -> None:
|
||||
sinf = _box(b"sinf", _box(b"frma", b"avc1"))
|
||||
avc1 = _sample_entry(b"avc1", b"\x00" * 70)
|
||||
encv = _sample_entry(b"encv", b"\x00" * 70 + sinf)
|
||||
f = _write(tmp_path, "dual.mp4", FTYP, _moov(_stsd([avc1, encv])), _box(b"mdat", b"\x00" * 32))
|
||||
sinf = box(b"sinf", box(b"frma", b"avc1"))
|
||||
avc1 = sample_entry(b"avc1", b"\x00" * 70)
|
||||
encv = sample_entry(b"encv", b"\x00" * 70 + sinf)
|
||||
f = write(tmp_path, "dual.mp4", FTYP, moov(stsd([avc1, encv])), box(b"mdat", b"\x00" * 32))
|
||||
assert has_encrypted_sample_entry(f) is True
|
||||
|
||||
|
||||
def test_single_avc1_not_detected(tmp_path: Path) -> None:
|
||||
avc1 = _sample_entry(b"avc1", b"\x00" * 70)
|
||||
f = _write(tmp_path, "clear.mp4", FTYP, _moov(_stsd([avc1])), _box(b"mdat", b"\x00" * 32))
|
||||
avc1 = sample_entry(b"avc1", b"\x00" * 70)
|
||||
f = write(tmp_path, "clear.mp4", FTYP, moov(stsd([avc1])), box(b"mdat", b"\x00" * 32))
|
||||
assert has_encrypted_sample_entry(f) is False
|
||||
|
||||
|
||||
def test_stray_encv_in_mdat_not_detected(tmp_path: Path) -> None:
|
||||
# clean moov, mdat happens to contain a plausible [size][encv] run -> must NOT flag
|
||||
avc1 = _sample_entry(b"avc1", b"\x00" * 70)
|
||||
f = _write(tmp_path, "stray.mp4", FTYP, _moov(_stsd([avc1])), _box(b"mdat", STRAY_ENCV))
|
||||
avc1 = sample_entry(b"avc1", b"\x00" * 70)
|
||||
f = write(tmp_path, "stray.mp4", FTYP, moov(stsd([avc1])), box(b"mdat", STRAY_ENCV))
|
||||
assert has_encrypted_sample_entry(f) is False
|
||||
|
||||
|
||||
def test_leading_mdat_does_not_mask_real_encv(tmp_path: Path) -> None:
|
||||
# progressive layout (mdat before moov) with a stray run must not hide a genuine encv
|
||||
enca = _sample_entry(b"enca", b"\x00" * 20 + _box(b"sinf", _box(b"frma", b"mp4a")))
|
||||
f = _write(tmp_path, "masked.mp4", FTYP, _box(b"mdat", STRAY_ENCV), _moov(_stsd([enca])))
|
||||
enca = sample_entry(b"enca", b"\x00" * 20 + box(b"sinf", box(b"frma", b"mp4a")))
|
||||
f = write(tmp_path, "masked.mp4", FTYP, box(b"mdat", STRAY_ENCV), moov(stsd([enca])))
|
||||
assert has_encrypted_sample_entry(f) is True
|
||||
|
||||
|
||||
def test_text_containing_enca_in_moov_not_detected(tmp_path: Path) -> None:
|
||||
# "enca" inside a metadata string has no plausible box size before it -> must NOT flag
|
||||
avc1 = _sample_entry(b"avc1", b"\x00" * 70)
|
||||
udta = _box(b"udta", b"data is encapsulated here")
|
||||
f = _write(tmp_path, "text.mp4", FTYP, _box(b"moov", _stsd([avc1]) + udta))
|
||||
avc1 = sample_entry(b"avc1", b"\x00" * 70)
|
||||
udta = box(b"udta", b"data is encapsulated here")
|
||||
f = write(tmp_path, "text.mp4", FTYP, box(b"moov", stsd([avc1]) + udta))
|
||||
assert has_encrypted_sample_entry(f) is False
|
||||
|
||||
|
||||
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")
|
||||
bogus = write(tmp_path, "bogus.bin", b"\x00\x01\x02\x03not-an-mp4")
|
||||
assert has_encrypted_sample_entry(bogus) is False
|
||||
|
||||
@@ -19,142 +19,129 @@ from unshackle.core.manifests.ism_init import PIFF_SENC_UUID
|
||||
from unshackle.core.tracks.track import assert_fragments_decrypted
|
||||
|
||||
|
||||
def _box(fmt: bytes, payload: bytes = b"") -> bytes:
|
||||
def box(fmt: bytes, payload: bytes = b"") -> bytes:
|
||||
return struct.pack(">I", 8 + len(payload)) + fmt + payload
|
||||
|
||||
|
||||
def _senc(sample_count: int = 4) -> bytes:
|
||||
return _box(b"senc", b"\x00" * 4 + struct.pack(">I", sample_count) + b"\x00" * (8 * sample_count))
|
||||
def senc(sample_count: int = 4) -> bytes:
|
||||
return box(b"senc", b"\x00" * 4 + struct.pack(">I", sample_count) + b"\x00" * (8 * sample_count))
|
||||
|
||||
|
||||
def _piff_senc(sample_count: int = 4) -> bytes:
|
||||
def piff_senc(sample_count: int = 4) -> bytes:
|
||||
body = PIFF_SENC_UUID + b"\x00" * 4 + struct.pack(">I", sample_count) + b"\x00" * (8 * sample_count)
|
||||
return _box(b"uuid", body)
|
||||
return box(b"uuid", body)
|
||||
|
||||
|
||||
def _moof(*children: bytes, sdi: int = 1) -> bytes:
|
||||
tfhd = _box(b"tfhd", b"\x00\x00\x00\x02" + struct.pack(">II", 1, sdi)) # sample-description-index-present
|
||||
return _box(b"moof", _box(b"mfhd", b"\x00" * 8) + _box(b"traf", tfhd + b"".join(children)))
|
||||
def moof(*children: bytes, sdi: int = 1) -> bytes:
|
||||
tfhd = box(b"tfhd", b"\x00\x00\x00\x02" + struct.pack(">II", 1, sdi))
|
||||
return box(b"moof", box(b"mfhd", b"\x00" * 8) + box(b"traf", tfhd + b"".join(children)))
|
||||
|
||||
|
||||
FTYP = _box(b"ftyp", b"isom\x00\x00\x02\x00isomiso2")
|
||||
MOOV = _box(b"moov", _box(b"mvex", _box(b"trex", b"\x00" * 24)))
|
||||
MDAT = _box(b"mdat", b"\x00" * 64)
|
||||
# a compressed payload can contain anything, including plausible-looking box runs
|
||||
STRAY = _box(b"mdat", struct.pack(">I", 64) + b"senc" + b"\xbe\xef" * 8 + PIFF_SENC_UUID)
|
||||
FTYP = box(b"ftyp", b"isom\x00\x00\x02\x00isomiso2")
|
||||
MOOV = box(b"moov", box(b"mvex", box(b"trex", b"\x00" * 24)))
|
||||
MDAT = box(b"mdat", b"\x00" * 64)
|
||||
STRAY = box(b"mdat", struct.pack(">I", 64) + b"senc" + b"\xbe\xef" * 8 + PIFF_SENC_UUID)
|
||||
|
||||
|
||||
def _write(tmp_path: Path, name: str, *boxes: bytes) -> Path:
|
||||
def write(tmp_path: Path, name: str, *boxes: bytes) -> Path:
|
||||
f = tmp_path / name
|
||||
f.write_bytes(b"".join(boxes))
|
||||
return f
|
||||
|
||||
|
||||
def test_all_fragments_decrypted_passes(tmp_path: Path) -> None:
|
||||
f = _write(tmp_path, "clean.mp4", FTYP, MOOV, _moof(), MDAT, _moof(sdi=2), MDAT)
|
||||
f = write(tmp_path, "clean.mp4", FTYP, MOOV, moof(), MDAT, moof(sdi=2), MDAT)
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def test_surviving_senc_raises(tmp_path: Path) -> None:
|
||||
# the real bug: fragment 1 (index 1) decrypted, the rest (index 2) silently skipped
|
||||
boxes = [FTYP, MOOV, _moof(), MDAT]
|
||||
boxes = [FTYP, MOOV, moof(), MDAT]
|
||||
for _ in range(3):
|
||||
boxes += [_moof(_senc(), sdi=2), MDAT]
|
||||
f = _write(tmp_path, "skipped.mp4", *boxes)
|
||||
boxes += [moof(senc(), sdi=2), MDAT]
|
||||
f = write(tmp_path, "skipped.mp4", *boxes)
|
||||
with pytest.raises(ValueError, match=r"3/4 fragment"):
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def test_surviving_cenc_senc_raises(tmp_path: Path) -> None:
|
||||
f = _write(tmp_path, "cenc.mp4", FTYP, MOOV, _moof(_senc()), MDAT)
|
||||
f = write(tmp_path, "cenc.mp4", FTYP, MOOV, moof(senc()), MDAT)
|
||||
with pytest.raises(ValueError, match=r"1/1 fragment"):
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def test_leftover_piff_uuid_after_senc_removed_does_not_raise(tmp_path: Path) -> None:
|
||||
# live DASH shape: the traf shipped senc+saiz+saio plus a duplicate PIFF uuid. mp4decrypt
|
||||
# consumed senc, detached senc/saiz/saio, and left the uuid on a fully decrypted fragment.
|
||||
boxes = [FTYP, MOOV]
|
||||
for _ in range(3):
|
||||
boxes += [_moof(_piff_senc()), MDAT]
|
||||
f = _write(tmp_path, "piff_leftover.mp4", *boxes)
|
||||
boxes += [moof(piff_senc()), MDAT]
|
||||
f = write(tmp_path, "piff_leftover.mp4", *boxes)
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def test_stray_senc_bytes_in_mdat_ignored(tmp_path: Path) -> None:
|
||||
f = _write(tmp_path, "stray.mp4", FTYP, MOOV, _moof(), STRAY, _moof(sdi=2), STRAY)
|
||||
f = write(tmp_path, "stray.mp4", FTYP, MOOV, moof(), STRAY, moof(sdi=2), STRAY)
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def test_senc_text_without_plausible_size_ignored(tmp_path: Path) -> None:
|
||||
# "senc" inside a free-box string has no valid box size before it
|
||||
f = _write(tmp_path, "text.mp4", FTYP, MOOV, _moof(_box(b"free", b"presence sencoded here")), MDAT)
|
||||
f = write(tmp_path, "text.mp4", FTYP, MOOV, moof(box(b"free", b"presence sencoded here")), MDAT)
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def test_senc_bytes_inside_trun_payload_ignored(tmp_path: Path) -> None:
|
||||
# a trun sample entry spelling "senc" after a size-looking duration; only a byte scan bites
|
||||
trun = _box(b"trun", b"\x00\x00\x03\x01" + struct.pack(">I", 2) + struct.pack(">I", 512) + b"senc")
|
||||
f = _write(tmp_path, "trun.mp4", FTYP, MOOV, _moof(trun), MDAT)
|
||||
trun = box(b"trun", b"\x00\x00\x03\x01" + struct.pack(">I", 2) + struct.pack(">I", 512) + b"senc")
|
||||
f = write(tmp_path, "trun.mp4", FTYP, MOOV, moof(trun), MDAT)
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def test_empty_senc_on_clear_fragment_ignored(tmp_path: Path) -> None:
|
||||
# sample_count 0 marks a fragment with no protected samples, so the guard ignores it
|
||||
f = _write(tmp_path, "empty.mp4", FTYP, MOOV, _moof(_senc(sample_count=0)), MDAT)
|
||||
f = write(tmp_path, "empty.mp4", FTYP, MOOV, moof(senc(sample_count=0)), MDAT)
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def _senc_override(sample_count: int) -> bytes:
|
||||
# flags&1 => AlgorithmID(3) + IV_size(1) + KID(16) precede sample_count
|
||||
def senc_override(sample_count: int) -> bytes:
|
||||
head = b"\x00\x00\x00\x01" + b"\x00\x00\x08" + b"\x08" + b"\xaa" * 16
|
||||
return _box(b"senc", head + struct.pack(">I", sample_count) + b"\x00" * (8 * sample_count))
|
||||
return box(b"senc", head + struct.pack(">I", sample_count) + b"\x00" * (8 * sample_count))
|
||||
|
||||
|
||||
def test_override_flag_shifts_sample_count_offset(tmp_path: Path) -> None:
|
||||
clear = _write(tmp_path, "ovr_clear.mp4", FTYP, MOOV, _moof(_senc_override(0)), MDAT)
|
||||
clear = write(tmp_path, "ovr_clear.mp4", FTYP, MOOV, moof(senc_override(0)), MDAT)
|
||||
assert_fragments_decrypted(clear)
|
||||
f = _write(tmp_path, "ovr.mp4", FTYP, MOOV, _moof(_senc_override(5)), MDAT)
|
||||
f = write(tmp_path, "ovr.mp4", FTYP, MOOV, moof(senc_override(5)), MDAT)
|
||||
with pytest.raises(ValueError, match=r"1/1 fragment"):
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def test_senc_outside_traf_ignored(tmp_path: Path) -> None:
|
||||
# a decrypted moof whose only "senc" sits in a sibling box outside any traf
|
||||
f = _write(tmp_path, "sibling.mp4", FTYP, MOOV, _box(b"moof", _box(b"mfhd", b"\x00" * 8) + _senc()), MDAT)
|
||||
f = write(tmp_path, "sibling.mp4", FTYP, MOOV, box(b"moof", box(b"mfhd", b"\x00" * 8) + senc()), MDAT)
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def test_senc_nested_under_non_traf_ignored(tmp_path: Path) -> None:
|
||||
# senc two levels down under a non-traf container: only traf children count
|
||||
meta = _box(b"meta", _senc())
|
||||
f = _write(tmp_path, "nested.mp4", FTYP, MOOV, _box(b"moof", _box(b"mfhd", b"\x00" * 8) + meta), MDAT)
|
||||
meta = box(b"meta", senc())
|
||||
f = write(tmp_path, "nested.mp4", FTYP, MOOV, box(b"moof", box(b"mfhd", b"\x00" * 8) + meta), MDAT)
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def test_undersized_largesize_box_does_not_desync_walk(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
# size==1 reads a 16-byte header, so a largesize of 12 clears the 8-byte floor but
|
||||
# still stalls the cursor onto payload; only a header-aware floor catches it
|
||||
runt = struct.pack(">I", 1) + b"free" + struct.pack(">Q", 12)
|
||||
f = _write(tmp_path, "runt.mp4", FTYP, MOOV, runt, _moof(_senc()), MDAT, _moof(_senc()), MDAT)
|
||||
f = write(tmp_path, "runt.mp4", FTYP, MOOV, runt, moof(senc()), MDAT, moof(senc()), MDAT)
|
||||
with caplog.at_level("WARNING"):
|
||||
assert_fragments_decrypted(f)
|
||||
assert "malformed box size" in caplog.text
|
||||
|
||||
|
||||
def test_largesize_and_zero_size_boxes_walked(tmp_path: Path) -> None:
|
||||
frag = _moof(_senc())
|
||||
frag = moof(senc())
|
||||
large = struct.pack(">I", 1) + b"mdat" + struct.pack(">Q", 16 + 64) + b"\x00" * 64
|
||||
trailing = struct.pack(">I", 0) + b"mdat" + b"\x00" * 64 # size 0 => runs to EOF
|
||||
f = _write(tmp_path, "large.mp4", FTYP, MOOV, frag, large, trailing)
|
||||
trailing = struct.pack(">I", 0) + b"mdat" + b"\x00" * 64
|
||||
f = write(tmp_path, "large.mp4", FTYP, MOOV, frag, large, trailing)
|
||||
with pytest.raises(ValueError, match=r"1/1 fragment"):
|
||||
assert_fragments_decrypted(f)
|
||||
|
||||
|
||||
def test_malformed_box_size_warns_and_does_not_raise(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
# failing open is deliberate, but the abort must be logged so it cannot pass as clean
|
||||
overrun = struct.pack(">I", 1 << 30) + b"free" + b"\x00" * 8
|
||||
f = _write(tmp_path, "overrun.mp4", FTYP, MOOV, overrun, _moof(_senc()), MDAT)
|
||||
f = write(tmp_path, "overrun.mp4", FTYP, MOOV, overrun, moof(senc()), MDAT)
|
||||
with caplog.at_level("WARNING"):
|
||||
assert_fragments_decrypted(f)
|
||||
assert "malformed box size" in caplog.text
|
||||
@@ -162,6 +149,6 @@ def test_malformed_box_size_warns_and_does_not_raise(tmp_path: Path, caplog: pyt
|
||||
|
||||
def test_missing_or_bogus_file_is_noop(tmp_path: Path) -> None:
|
||||
assert_fragments_decrypted(tmp_path / "nope.mp4")
|
||||
assert_fragments_decrypted(_write(tmp_path, "bogus.bin", b"\x00\x01\x02\x03not-an-mp4"))
|
||||
truncated = _write(tmp_path, "cut.mp4", FTYP, MOOV, _moof(_senc())[:20])
|
||||
assert_fragments_decrypted(write(tmp_path, "bogus.bin", b"\x00\x01\x02\x03not-an-mp4"))
|
||||
truncated = write(tmp_path, "cut.mp4", FTYP, MOOV, moof(senc())[:20])
|
||||
assert_fragments_decrypted(truncated)
|
||||
|
||||
@@ -2,19 +2,19 @@
|
||||
|
||||
Covers the selection primitives that back `-r ...,DV,HYBRID` downloads:
|
||||
|
||||
- ``Tracks.select_hybrid`` — picks the HDR base layer per resolution and the
|
||||
- ``Tracks.select_hybrid``: picks the HDR base layer per resolution and the
|
||||
single lowest DV track used as a hybrid ingredient.
|
||||
- ``Tracks.merge_video_selections`` — de-duplicates the ingredient/deliverable
|
||||
- ``Tracks.merge_video_selections``: de-duplicates the ingredient/deliverable
|
||||
overlap so a DV track that is chosen as both is not muxed/downloaded twice.
|
||||
- ``Tracks.partition_hybrid_videos`` — splits the ladder into hybrid-ingredient
|
||||
- ``Tracks.partition_hybrid_videos``: splits the ladder into hybrid-ingredient
|
||||
candidates and the standalone-deliverable pool; HDR10/HDR10+/DV only enter
|
||||
the pool when their range was explicitly requested alongside HYBRID.
|
||||
- ``Tracks.flag_hybrid_ingredients`` — marks ingredient-only tracks with
|
||||
- ``Tracks.flag_hybrid_ingredients``: marks ingredient-only tracks with
|
||||
``hybrid_base_only`` so the standalone mux loop skips them.
|
||||
|
||||
The remaining ``dl`` glue (the Cartesian deliverable product and the mux loop)
|
||||
is orchestration inside the Click command; these tests lock down the pure
|
||||
units it relies on plus the documented end-state of a realistic ATV-style ladder.
|
||||
units it relies on plus the documented end-state of a realistic streaming ladder.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -39,7 +39,7 @@ def make_video(track_id: str, *, range_: Video.Range, height: int, bitrate: int,
|
||||
|
||||
@pytest.fixture
|
||||
def ladder() -> list[Video]:
|
||||
"""Mirrors the reported ATV ladder: HDR10+, DV and SDR at multiple resolutions."""
|
||||
"""Mirrors the ladder from the reported fault: HDR10+, DV and SDR at multiple resolutions."""
|
||||
H = Video.Codec.HEVC
|
||||
A = Video.Codec.AVC
|
||||
return [
|
||||
@@ -58,19 +58,12 @@ def ids(tracks: list[Video]) -> set[str]:
|
||||
return {t.id for t in tracks}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# select_hybrid
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_select_hybrid_picks_base_per_resolution_and_lowest_dv(ladder: list[Video]) -> None:
|
||||
chosen = list(filter(Tracks().select_hybrid(ladder, [2160, 1080]), ladder))
|
||||
# HDR10+ base at each requested resolution, plus the single lowest DV ingredient.
|
||||
assert ids(chosen) == {"hdr10p-2160", "hdr10p-1080", "dv-360"}
|
||||
|
||||
|
||||
def test_select_hybrid_ingredient_is_lowest_dv_regardless_of_quality(ladder: list[Video]) -> None:
|
||||
# Even when only 2160 is requested, the ingredient is the globally lowest DV.
|
||||
chosen = list(filter(Tracks().select_hybrid(ladder, [2160]), ladder))
|
||||
assert ids(chosen) == {"hdr10p-2160", "dv-360"}
|
||||
|
||||
@@ -107,18 +100,12 @@ def test_select_hybrid_no_dv_selects_only_base() -> None:
|
||||
assert ids(chosen) == {"hdr10p-2160"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# merge_video_selections (the dedup fix)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
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)
|
||||
hdr = make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=20_000_000, codec=H)
|
||||
sdr = make_video("sdr-2160", range_=Video.Range.SDR, height=2160, bitrate=21_000_000, codec=H)
|
||||
|
||||
# dv is both the hybrid ingredient and an explicit DV deliverable (same object).
|
||||
merged = Tracks.merge_video_selections([hdr, dv], [sdr, dv])
|
||||
assert [t.id for t in merged] == ["hdr10p-2160", "dv-1080", "sdr-2160"]
|
||||
|
||||
@@ -133,7 +120,6 @@ def test_merge_preserves_order_and_keeps_distinct_dv() -> None:
|
||||
|
||||
|
||||
def test_merge_dedup_uses_track_identity_by_id() -> None:
|
||||
# Tracks compare equal by id; merge must treat same-id tracks as one.
|
||||
H = Video.Codec.HEVC
|
||||
a = make_video("same", range_=Video.Range.DV, height=1080, bitrate=9_000_000, codec=H)
|
||||
b = make_video("same", range_=Video.Range.DV, height=1080, bitrate=9_000_000, codec=H)
|
||||
@@ -141,11 +127,6 @@ def test_merge_dedup_uses_track_identity_by_id() -> None:
|
||||
assert len(Tracks.merge_video_selections([a], [b])) == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# partition_hybrid_videos
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_partition_hybrid_only_keeps_ingredients_out_of_pool(ladder: list[Video]) -> None:
|
||||
"""`-r HYBRID`: HDR10+/DV are ingredients only; pool holds just SDR."""
|
||||
candidates, pool = Tracks.partition_hybrid_videos(ladder, [])
|
||||
@@ -158,7 +139,6 @@ def test_partition_admits_hdr10p_to_pool_when_requested(ladder: list[Video]) ->
|
||||
candidates, pool = Tracks.partition_hybrid_videos(ladder, [Video.Range.HDR10P])
|
||||
assert {"hdr10p-2160", "hdr10p-1080"} <= ids(pool)
|
||||
assert not any(t.range == Video.Range.DV for t in pool)
|
||||
# Candidates are unaffected by the requested ranges.
|
||||
assert ids(candidates) == {"hdr10p-2160", "hdr10p-1080", "dv-2160", "dv-1080", "dv-360"}
|
||||
|
||||
|
||||
@@ -178,18 +158,13 @@ def test_partition_hdr10_requested_does_not_admit_hdr10p() -> None:
|
||||
assert ids(pool) == {"hdr10-2160"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# flag_hybrid_ingredients
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def flagged(tracks: list[Video]) -> set[str]:
|
||||
return {t.id for t in tracks if t.hybrid_base_only}
|
||||
|
||||
|
||||
def test_flag_hybrid_only_flags_base_and_ingredient_dv(ladder: list[Video]) -> None:
|
||||
"""`-r HYBRID`: no deliverables, so the base and the ingredient DV are both
|
||||
skipped by the standalone mux loop — only the hybrid output remains."""
|
||||
skipped by the standalone mux loop; only the hybrid output remains."""
|
||||
hybrid_selected = list(filter(Tracks().select_hybrid(ladder, [1080]), ladder))
|
||||
Tracks.flag_hybrid_ingredients(hybrid_selected, [])
|
||||
assert flagged(ladder) == {"hdr10p-1080", "dv-360"}
|
||||
@@ -197,7 +172,7 @@ def test_flag_hybrid_only_flags_base_and_ingredient_dv(ladder: list[Video]) -> N
|
||||
|
||||
def test_flag_hybrid_plus_hdr10p_keeps_base_deliverable(ladder: list[Video]) -> None:
|
||||
"""`-r HYBRID,HDR10P`: the base is also an explicit deliverable, only the
|
||||
ingredient DV is skipped — hybrid + standalone HDR10+ are muxed."""
|
||||
ingredient DV is skipped; hybrid + standalone HDR10+ are muxed."""
|
||||
hybrid_selected = list(filter(Tracks().select_hybrid(ladder, [1080]), ladder))
|
||||
base = next(t for t in ladder if t.id == "hdr10p-1080")
|
||||
Tracks.flag_hybrid_ingredients(hybrid_selected, [base])
|
||||
@@ -206,7 +181,7 @@ def test_flag_hybrid_plus_hdr10p_keeps_base_deliverable(ladder: list[Video]) ->
|
||||
|
||||
def test_flag_hybrid_plus_hdr10p_and_dv_keeps_both_deliverables(ladder: list[Video]) -> None:
|
||||
"""`-r HYBRID,HDR10P,DV`: best DV is a deliverable, lowest DV stays
|
||||
ingredient-only — hybrid + HDR10+ + DV are muxed."""
|
||||
ingredient-only; hybrid + HDR10+ + DV are muxed."""
|
||||
hybrid_selected = list(filter(Tracks().select_hybrid(ladder, [1080]), ladder))
|
||||
base = next(t for t in ladder if t.id == "hdr10p-1080")
|
||||
best_dv = next(t for t in ladder if t.id == "dv-1080")
|
||||
@@ -228,11 +203,6 @@ def test_flag_single_dv_rendition_as_deliverable_stays_unflagged() -> None:
|
||||
assert flagged(tracks) == {"hdr10p-1080"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# documented end-state for the reported command
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_hybrid_plus_dv_deliverable_end_state(ladder: list[Video]) -> None:
|
||||
"""`-r SDR,HDR10P,DV,HYBRID -q 2160,1080`: hybrid base + lowest DV ingredient,
|
||||
de-duplicated against the best-DV-per-resolution deliverables and SDR."""
|
||||
@@ -240,7 +210,6 @@ def test_hybrid_plus_dv_deliverable_end_state(ladder: list[Video]) -> None:
|
||||
|
||||
hybrid_selected = list(filter(Tracks().select_hybrid(ladder, quality), ladder))
|
||||
|
||||
# Deliverables: best DV and SDR per requested resolution (what the dl Cartesian picks).
|
||||
def best_per_res(range_: Video.Range, codec: Video.Codec | None = None) -> list[Video]:
|
||||
out = []
|
||||
for res in quality:
|
||||
@@ -254,9 +223,8 @@ def test_hybrid_plus_dv_deliverable_end_state(ladder: list[Video]) -> None:
|
||||
|
||||
final = Tracks.merge_video_selections(hybrid_selected, dv_deliverable + sdr_deliverable)
|
||||
|
||||
# No duplicates, and the lowest DV ingredient coexists with the DV deliverables.
|
||||
assert len(final) == len({t.id for t in final})
|
||||
assert "dv-360" in ids(final) # ingredient retained for hybrid build
|
||||
assert {"dv-2160", "dv-1080"} <= ids(final) # standalone DV deliverables
|
||||
assert "dv-360" in ids(final)
|
||||
assert {"dv-2160", "dv-1080"} <= ids(final)
|
||||
assert {"hdr10p-2160", "hdr10p-1080"} <= ids(final)
|
||||
assert {"sdr-2160", "sdr-1080-avc", "sdr-1080-hevc"} <= ids(final)
|
||||
|
||||
@@ -20,8 +20,6 @@ def make_video(track_id: str, **data) -> 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
|
||||
with pytest.raises(RuntimeError, match="MKVToolNix"):
|
||||
tracks.mux("Test Title")
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ Dialogue: 0,0:00:03.00,0:00:04.00,Default,,0,0,0,,World
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_subtitleedit(monkeypatch):
|
||||
def no_subtitleedit(monkeypatch):
|
||||
"""Default every test to a SubtitleEdit-less environment; tests opt in when needed."""
|
||||
monkeypatch.setattr(binaries, "SubtitleEdit", None)
|
||||
|
||||
@@ -67,16 +67,12 @@ def cue_count(path) -> int:
|
||||
return len(re.findall(r"-->", path.read_text("utf8")))
|
||||
|
||||
|
||||
# --- capability matrix / resolver -------------------------------------------------------
|
||||
|
||||
|
||||
def test_resolve_webvtt_to_srt_order():
|
||||
chain = [b.name for b in sc.resolve_backends(Codec.WebVTT, Codec.SubRip)]
|
||||
assert chain == ["subby", "pysubs2", "pycaption"]
|
||||
|
||||
|
||||
def test_resolve_ass_to_srt_only_pysubs2_without_subtitleedit():
|
||||
# subby and pycaption cannot read ASS, so only pysubs2 remains.
|
||||
chain = [b.name for b in sc.resolve_backends(Codec.SubStationAlphav4, Codec.SubRip)]
|
||||
assert chain == ["pysubs2"]
|
||||
|
||||
@@ -88,13 +84,11 @@ def test_subtitleedit_ranks_first_when_available(monkeypatch):
|
||||
|
||||
|
||||
def test_styled_ass_to_ttml_vtt_prefers_pysubs2_over_subtitleedit(monkeypatch):
|
||||
# Measured: SE flattens ASS inline styling to TTML/VTT; pysubs2 keeps i/b/u.
|
||||
monkeypatch.setattr(binaries, "SubtitleEdit", "/usr/bin/seconv")
|
||||
for target in (Codec.TimedTextMarkupLang, Codec.WebVTT):
|
||||
chain = [b.name for b in sc.resolve_backends(Codec.SubStationAlphav4, target)]
|
||||
assert chain[0] == "pysubs2", f"expected pysubs2 first for ASS->{target.name}, got {chain}"
|
||||
assert "subtitleedit" in chain # still a fallback
|
||||
# ASS->SRT keeps SE first (only backend that keeps colour there).
|
||||
assert "subtitleedit" in chain
|
||||
chain = [b.name for b in sc.resolve_backends(Codec.SubStationAlphav4, Codec.SubRip)]
|
||||
assert chain[0] == "subtitleedit"
|
||||
|
||||
@@ -102,11 +96,10 @@ def test_styled_ass_to_ttml_vtt_prefers_pysubs2_over_subtitleedit(monkeypatch):
|
||||
def test_pin_then_fallback_orders_pin_first():
|
||||
chain = [b.name for b in sc.resolve_backends(Codec.WebVTT, Codec.SubRip, pin="pysubs2")]
|
||||
assert chain[0] == "pysubs2"
|
||||
assert "subby" in chain # fallbacks remain after the pin
|
||||
assert "subby" in chain
|
||||
|
||||
|
||||
def test_pin_unavailable_falls_back_to_ranked_chain():
|
||||
# subtitleedit pinned but not installed -> just the ranked available backends.
|
||||
chain = [b.name for b in sc.resolve_backends(Codec.WebVTT, Codec.SubRip, pin="subtitleedit")]
|
||||
assert chain == ["subby", "pysubs2", "pycaption"]
|
||||
|
||||
@@ -117,7 +110,6 @@ def test_fallback_runs_when_first_backend_fails(tmp_path, monkeypatch):
|
||||
def boom(self, source, src, target, out):
|
||||
raise RuntimeError("backend exploded")
|
||||
|
||||
# WebVTT->SRT chain is [subby, pysubs2, pycaption]; kill subby, expect pysubs2 to finish.
|
||||
monkeypatch.setattr(sc.SubbyBackend, "convert", boom)
|
||||
sub = make_sub(tmp_path, "x.vtt", VTT_SAMPLE, Codec.WebVTT)
|
||||
out = sub.convert(Codec.SubRip, forced=True)
|
||||
@@ -128,17 +120,14 @@ def test_fallback_runs_when_first_backend_fails(tmp_path, monkeypatch):
|
||||
def test_no_backend_for_unsupported_target_raises(tmp_path):
|
||||
sub = make_sub(tmp_path, "x.ass", ASS_SAMPLE, Codec.SubStationAlphav4)
|
||||
with pytest.raises(NotImplementedError):
|
||||
sub.convert(Codec.fVTT, forced=True) # no backend writes segmented fVTT
|
||||
|
||||
|
||||
# --- styled-ASS protection --------------------------------------------------------------
|
||||
sub.convert(Codec.fVTT, forced=True)
|
||||
|
||||
|
||||
def test_ass_to_srt_kept_as_is_when_not_forced(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.ass", ASS_SAMPLE, Codec.SubStationAlphav4)
|
||||
out = sub.convert(Codec.SubRip, forced=False)
|
||||
assert sub.codec == Codec.SubStationAlphav4 # unchanged
|
||||
assert sub.codec == Codec.SubStationAlphav4
|
||||
assert out == sub.path
|
||||
assert out.suffix == ".ass"
|
||||
|
||||
@@ -150,10 +139,7 @@ def test_ass_to_srt_converts_when_forced(tmp_path, monkeypatch):
|
||||
assert sub.codec == Codec.SubRip
|
||||
assert out.suffix == ".srt"
|
||||
assert cue_count(out) == 2
|
||||
assert "{\\" not in out.read_text("utf8") # override tags stripped
|
||||
|
||||
|
||||
# --- conversion paths -------------------------------------------------------------------
|
||||
assert "{\\" not in out.read_text("utf8")
|
||||
|
||||
|
||||
def test_webvtt_to_srt_conversion(tmp_path, monkeypatch):
|
||||
@@ -170,8 +156,6 @@ def test_same_codec_is_noop(tmp_path):
|
||||
assert sub.codec == Codec.SubRip
|
||||
|
||||
|
||||
# --- ASS/SSA font detection ------------------------------------------------------------
|
||||
|
||||
FONT_ASS = """[Script Info]
|
||||
ScriptType: v4.00+
|
||||
|
||||
@@ -190,23 +174,15 @@ Dialogue: 0,0:00:05.00,0:00:06.00,Default,,0,0,0,,{\\fnGeorgia\\b1}bold note
|
||||
|
||||
def test_extract_fonts_styles_and_inline_overrides():
|
||||
fonts = Subtitle.extract_fonts(FONT_ASS)
|
||||
# Style fontnames (column located via Format line, @-prefix stripped) + inline \fn overrides
|
||||
assert fonts == {"Trebuchet MS", "Arial Unicode MS", "Times New Roman", "Georgia"}
|
||||
# case-insensitive de-dup keeps the mixed-case spelling, not "times new roman"
|
||||
assert "times new roman" not in fonts
|
||||
|
||||
|
||||
def test_extract_fonts_handles_non_default_column_order():
|
||||
ass = (
|
||||
"[V4+ Styles]\n"
|
||||
"Format: Name, Fontsize, Fontname, Bold\n" # Fontname not in the usual position
|
||||
"Style: Main,28,Verdana,0\n"
|
||||
)
|
||||
ass = "[V4+ Styles]\nFormat: Name, Fontsize, Fontname, Bold\nStyle: Main,28,Verdana,0\n"
|
||||
assert Subtitle.extract_fonts(ass) == {"Verdana"}
|
||||
|
||||
|
||||
# --- non-Latin scripts (RTL / CJK) preserved through conversion ------------------------
|
||||
|
||||
CJK_RTL_VTT = """WEBVTT
|
||||
|
||||
1
|
||||
@@ -225,7 +201,7 @@ CJK_RTL_VTT = """WEBVTT
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"pattern",
|
||||
[r"[-ۿ]", r"[가-힣]", r"[一-鿿]"], # Arabic, Hangul, CJK
|
||||
[r"[-ۿ]", r"[가-힣]", r"[一-鿿]"],
|
||||
)
|
||||
def test_non_latin_scripts_survive_vtt_to_srt(tmp_path, monkeypatch, pattern):
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
|
||||
@@ -233,11 +209,9 @@ def test_non_latin_scripts_survive_vtt_to_srt(tmp_path, monkeypatch, pattern):
|
||||
out = sub.convert(Codec.SubRip, forced=True)
|
||||
text = out.read_text("utf8")
|
||||
assert cue_count(out) == 3
|
||||
assert re.search(pattern, text) # script survived the round-trip, no mojibake
|
||||
assert re.search(pattern, text)
|
||||
|
||||
|
||||
# --- SDH stripping ----------------------------------------------------------------------
|
||||
|
||||
SDH_SRT = """1
|
||||
00:00:01,000 --> 00:00:02,000
|
||||
[door creaks]
|
||||
@@ -253,18 +227,41 @@ Hello there.
|
||||
|
||||
|
||||
def test_sdh_stripping_removes_effects_keeps_dialogue(tmp_path, monkeypatch):
|
||||
# subby's SDHStripper runs on SRT without SubtitleEdit installed.
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "subby"}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.srt", SDH_SRT, Codec.SubRip)
|
||||
sub.strip_hearing_impaired()
|
||||
out = sub.path.read_text("utf8")
|
||||
assert "Hello there." in out # real dialogue kept
|
||||
assert "door creaks" not in out # bracketed effect removed (subby SDHStripper)
|
||||
assert "Hello there." in out
|
||||
assert "door creaks" not in out
|
||||
|
||||
|
||||
# --- segmented (box-encapsulated) formats: fVTT (wvtt) / fTTML (stpp) --------------------
|
||||
# These ship from DASH/HLS as fragmented MP4 (e.g. HBO Max). The downloader concatenates
|
||||
# init + media segments into one file; parse() reads the MP4 boxes directly.
|
||||
SDH_ASS = """[Script Info]
|
||||
ScriptType: v4.00+
|
||||
|
||||
[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
|
||||
|
||||
[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,,[door creaks]
|
||||
Dialogue: 0,0:00:03.00,0:00:04.00,Default,,0,0,0,,Hello there.
|
||||
"""
|
||||
|
||||
|
||||
def test_sdh_stripping_ass_without_subtitleedit_content_matches_codec(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "auto"}, raising=False)
|
||||
sub = make_sub(tmp_path, "x.ass", SDH_ASS, Codec.SubStationAlphav4)
|
||||
sub.strip_hearing_impaired()
|
||||
|
||||
assert sub.codec == Codec.SubRip
|
||||
assert sub.path.suffix == ".srt"
|
||||
text = sub.path.read_text("utf8")
|
||||
assert "[Script Info]" not in text and "Dialogue:" not in text
|
||||
assert "-->" in text
|
||||
assert "Hello there." in text
|
||||
assert "door creaks" not in text
|
||||
|
||||
|
||||
FIXTURES = pathlib.Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -296,7 +293,6 @@ def test_segmented_fvtt_parses_and_converts(tmp_path, monkeypatch):
|
||||
seg.write_bytes(data)
|
||||
sub = Subtitle(url="https://example.test/x", language="en", codec=Codec.fVTT)
|
||||
sub.path = seg
|
||||
# download() converts fVTT -> WebVTT (not "forced"); chain is subby then pycaption.
|
||||
out = sub.convert(Codec.WebVTT)
|
||||
assert sub.codec == Codec.WebVTT
|
||||
assert cue_count(out) == 2
|
||||
@@ -319,7 +315,6 @@ def test_segmented_fttml_parses_and_converts(tmp_path, monkeypatch):
|
||||
seg.write_bytes(data)
|
||||
sub = Subtitle(url="https://example.test/x", language="en", codec=Codec.fTTML)
|
||||
sub.path = seg
|
||||
# download() converts fTTML -> TTML (only pycaption can read fTTML); then -> SRT.
|
||||
sub.convert(Codec.TimedTextMarkupLang)
|
||||
assert sub.codec == Codec.TimedTextMarkupLang
|
||||
out = sub.convert(Codec.SubRip, forced=True)
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""``strip_hearing_impaired`` fallback path (``tracks/subtitle.py``).
|
||||
|
||||
Pins the filter-subs fallback's warn-and-continue branch: an invalid subtitle file must
|
||||
log a warning and return, not crash (it previously raised AttributeError via a
|
||||
nonexistent ``self.log``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
|
||||
SRT_SAMPLE = """1
|
||||
00:00:01,000 --> 00:00:02,000
|
||||
Hello
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def srt_track(tmp_path):
|
||||
path = tmp_path / "sub.srt"
|
||||
path.write_text(SRT_SAMPLE, encoding="utf-8")
|
||||
sub = Subtitle(url="https://example.test/x", language="en", codec=Subtitle.Codec.SubRip)
|
||||
sub.path = path
|
||||
return sub
|
||||
|
||||
|
||||
def test_invalid_subtitle_warns_and_continues(srt_track, monkeypatch, caplog):
|
||||
import unshackle.core.tracks.subtitle as subtitle_mod
|
||||
|
||||
monkeypatch.setattr(binaries, "SubtitleEdit", None)
|
||||
monkeypatch.setattr(config, "subtitle", {"sdh_method": "auto"}, raising=False)
|
||||
|
||||
def broken(*args, **kwargs):
|
||||
raise RuntimeError("subby unavailable")
|
||||
|
||||
monkeypatch.setattr(subtitle_mod, "CommonIssuesFixer", broken)
|
||||
|
||||
def invalid(path):
|
||||
raise OSError(f"{path} is not valid subtitle file")
|
||||
|
||||
monkeypatch.setattr(subtitle_mod, "Subtitles", invalid)
|
||||
|
||||
with caplog.at_level("WARNING", logger="Subtitle"):
|
||||
srt_track.strip_hearing_impaired()
|
||||
|
||||
assert any("Failed to strip SDH" in r.message for r in caplog.records)
|
||||
|
||||
|
||||
def test_other_oserror_still_raises(srt_track, monkeypatch):
|
||||
import unshackle.core.tracks.subtitle as subtitle_mod
|
||||
|
||||
monkeypatch.setattr(binaries, "SubtitleEdit", None)
|
||||
monkeypatch.setattr(config, "subtitle", {"sdh_method": "auto"}, raising=False)
|
||||
|
||||
def broken(*args, **kwargs):
|
||||
raise RuntimeError("subby unavailable")
|
||||
|
||||
monkeypatch.setattr(subtitle_mod, "CommonIssuesFixer", broken)
|
||||
|
||||
def denied(path):
|
||||
raise PermissionError("permission denied")
|
||||
|
||||
monkeypatch.setattr(subtitle_mod, "Subtitles", denied)
|
||||
|
||||
with pytest.raises(PermissionError):
|
||||
srt_track.strip_hearing_impaired()
|
||||
@@ -77,7 +77,7 @@ class Harness:
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_event():
|
||||
def clear_event():
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
yield
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
@@ -97,9 +97,9 @@ def test_failed_subtitle_does_not_truncate_video_or_audio():
|
||||
on_subtitle_skipped=h.on_subtitle_skipped,
|
||||
)
|
||||
|
||||
assert set(h.completed) == {"v", "a"} # both fatal tracks fully downloaded
|
||||
assert h.early_returned == [] # nothing early-returned because of the subtitle
|
||||
assert h.skipped == [sub] # the subtitle was recorded as skipped
|
||||
assert set(h.completed) == {"v", "a"}
|
||||
assert h.early_returned == []
|
||||
assert h.skipped == [sub]
|
||||
|
||||
|
||||
def test_good_subtitle_kept_bad_subtitle_skipped():
|
||||
@@ -115,8 +115,8 @@ def test_good_subtitle_kept_bad_subtitle_skipped():
|
||||
on_subtitle_skipped=h.on_subtitle_skipped,
|
||||
)
|
||||
|
||||
assert "s-en" in h.completed # the available subtitle still downloaded
|
||||
assert h.skipped == [bad] # only the failing one was skipped
|
||||
assert "s-en" in h.completed
|
||||
assert h.skipped == [bad]
|
||||
|
||||
|
||||
def test_subtitle_failure_stays_fatal_without_flag():
|
||||
@@ -134,7 +134,7 @@ def test_subtitle_failure_stays_fatal_without_flag():
|
||||
on_subtitle_skipped=h.on_subtitle_skipped,
|
||||
)
|
||||
|
||||
assert not DOWNLOAD_CANCELLED.is_set() # the finally clears the event even on the fatal path
|
||||
assert not DOWNLOAD_CANCELLED.is_set()
|
||||
|
||||
|
||||
def test_cancel_event_is_reset_between_titles():
|
||||
@@ -169,7 +169,7 @@ def test_cancel_event_cleared_after_failed_final_subtitle():
|
||||
on_subtitle_skipped=h.on_subtitle_skipped,
|
||||
)
|
||||
|
||||
assert not DOWNLOAD_CANCELLED.is_set() # the helper clears it on exit for any later code
|
||||
assert not DOWNLOAD_CANCELLED.is_set()
|
||||
|
||||
|
||||
def test_all_subtitles_skipped_video_audio_kept():
|
||||
@@ -186,8 +186,8 @@ def test_all_subtitles_skipped_video_audio_kept():
|
||||
on_subtitle_skipped=h.on_subtitle_skipped,
|
||||
)
|
||||
|
||||
assert set(h.completed) == {"v", "a"} # both fatal tracks survived
|
||||
assert {t.id for t in h.skipped} == {"s-en", "s-he"} # every failing subtitle recorded
|
||||
assert set(h.completed) == {"v", "a"}
|
||||
assert {t.id for t in h.skipped} == {"s-en", "s-he"}
|
||||
|
||||
|
||||
def test_duplicate_language_subtitles_distinguished_by_id():
|
||||
@@ -204,7 +204,7 @@ def test_duplicate_language_subtitles_distinguished_by_id():
|
||||
on_subtitle_skipped=h.on_subtitle_skipped,
|
||||
)
|
||||
|
||||
assert [t.id for t in h.skipped] == ["en-forced", "en-sdh"] # same language, distinct ids
|
||||
assert [t.id for t in h.skipped] == ["en-forced", "en-sdh"]
|
||||
|
||||
|
||||
def test_skipped_subtitle_contract():
|
||||
|
||||
@@ -53,7 +53,6 @@ def test_type_priority_overrides_group_order(tracks: Tracks) -> None:
|
||||
|
||||
def test_type_priority_unlisted_types_fall_to_end(tracks: Tracks) -> None:
|
||||
tracks.sort_subtitles(by_language=["en"], type_priority=["normal"])
|
||||
# unlisted types keep their pre-sort relative order (stable sort)
|
||||
assert shape(tracks) == [
|
||||
("en", "normal"),
|
||||
("en", "sdh"),
|
||||
@@ -99,7 +98,6 @@ def test_language_grouping_keeps_a_language_with_its_sdh(unprioritised: Tracks)
|
||||
|
||||
|
||||
def test_language_grouping_still_honours_type_priority_and_sections(tracks: Tracks) -> None:
|
||||
# de sits outside by_language, where type-major sorting would interleave it with en
|
||||
tracks.add([sub("de"), sub("de", sdh=True)])
|
||||
tracks.sort_subtitles(by_language=["it"], type_priority=["normal", "sdh", "forced"], group_by="language")
|
||||
assert shape(tracks) == [
|
||||
@@ -114,7 +112,6 @@ def test_language_grouping_still_honours_type_priority_and_sections(tracks: Trac
|
||||
|
||||
|
||||
def test_language_grouping_keeps_regional_variants_adjacent_through_sections() -> None:
|
||||
# "en" floats en-GB and en-US as one block, so each exact tag keeps its variants
|
||||
t = Tracks()
|
||||
t.add(
|
||||
[
|
||||
@@ -156,7 +153,6 @@ def test_priority_orders_listed_then_rest_alphabetically(many: Tracks) -> None:
|
||||
|
||||
|
||||
def test_priority_outranks_the_original_language(many: Tracks) -> None:
|
||||
# "all" resolves to the original language (ja), which must stay below the named ones
|
||||
many.sort_subtitles(by_language=["en", "es", "all"], group_by="language")
|
||||
assert langs(many) == ["en", "es", "ja", "ar", "bg", "fr"]
|
||||
|
||||
@@ -205,8 +201,6 @@ def test_fuzzy_priority_floats_regional_variants(regionals: Tracks) -> None:
|
||||
|
||||
|
||||
def test_exact_priority_floats_only_the_named_tag(regionals: Tracks) -> None:
|
||||
# CLDR rates en/en-US at distance 0, so exact mode needs the RFC 4647 string preference
|
||||
# to hold en-US back; without it en-US floats and en-GB does not.
|
||||
regionals.sort_subtitles(by_language=["en"], group_by="language", exact_match=True)
|
||||
assert langs(regionals) == ["en", "ar", "en-GB", "en-US", "ja"]
|
||||
|
||||
@@ -220,6 +214,5 @@ def test_exact_priority_still_falls_back_when_no_tag_is_string_equal() -> None:
|
||||
|
||||
@pytest.mark.parametrize("exact", [False, True])
|
||||
def test_unparseable_priority_entry_is_ignored(many: Tracks, exact: bool) -> None:
|
||||
# a config typo in language_priority must not crash the sort
|
||||
many.sort_subtitles(by_language=["en", "engrish", "f", ""], group_by="language", exact_match=exact)
|
||||
assert langs(many) == ["en", "ar", "bg", "es", "fr", "ja"]
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
Cover the pure ``Tracks`` helpers behind the ``dl`` selection layer:
|
||||
|
||||
- ``Tracks.by_resolutions``: the 16:9 canvas fallback must tolerate tracks with
|
||||
no known width instead of crashing on ``int(None * 9 / 16)``.
|
||||
no known width instead of crashing on ``int(None * 9 / 16)``, and it applies to
|
||||
each range and codec on its own.
|
||||
- ``Tracks.sort_videos``: resolution outranks bitrate, and an unknown-bitrate
|
||||
track can still win on resolution.
|
||||
- ``Tracks.sort_audio``: descriptive-last, Atmos, codec_priority then bitrate;
|
||||
@@ -22,13 +23,14 @@ def make_video(
|
||||
bitrate: int | None,
|
||||
width: int | None = None,
|
||||
codec: Video.Codec = Video.Codec.HEVC,
|
||||
range_: Video.Range = Video.Range.SDR,
|
||||
) -> Video:
|
||||
return Video(
|
||||
id_=track_id,
|
||||
url=f"https://example.test/{track_id}.m3u8",
|
||||
language="en",
|
||||
codec=codec,
|
||||
range_=Video.Range.SDR,
|
||||
range_=range_,
|
||||
width=width,
|
||||
height=height,
|
||||
bitrate=bitrate,
|
||||
@@ -55,17 +57,12 @@ def make_audio(
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# by_resolutions: width=None must not crash the canvas fallback
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_by_resolutions_tolerates_width_none_track() -> None:
|
||||
tracks = Tracks()
|
||||
tracks.videos = [
|
||||
make_video("h1080", height=1080, width=1920, bitrate=8_000_000), # no exact/canvas 720 match
|
||||
make_video("no-width", height=480, width=None, bitrate=1_000_000), # width-less, must be skipped
|
||||
make_video("canvas-720", height=406, width=1280, bitrate=3_000_000), # 1280*9/16 == 720
|
||||
make_video("h1080", height=1080, width=1920, bitrate=8_000_000),
|
||||
make_video("no-width", height=480, width=None, bitrate=1_000_000),
|
||||
make_video("canvas-720", height=406, width=1280, bitrate=3_000_000),
|
||||
]
|
||||
|
||||
tracks.by_resolutions([720])
|
||||
@@ -73,9 +70,19 @@ def test_by_resolutions_tolerates_width_none_track() -> None:
|
||||
assert [t.id for t in tracks.videos] == ["canvas-720"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# sort_videos: resolution before bitrate
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_by_resolutions_keeps_cropped_variants_of_other_ranges() -> None:
|
||||
"""A DV track with an exact height must not remove the cropped HDR10 and SDR tracks."""
|
||||
tracks = Tracks()
|
||||
tracks.videos = [
|
||||
make_video("dv-2160", height=2160, width=3840, bitrate=20_000_000, range_=Video.Range.DV),
|
||||
make_video("hdr10-2160", height=1920, width=3840, bitrate=20_000_000, range_=Video.Range.HDR10),
|
||||
make_video("sdr-2160", height=1920, width=3840, bitrate=15_000_000, range_=Video.Range.SDR),
|
||||
make_video("dv-1080", height=1080, width=1920, bitrate=5_000_000, range_=Video.Range.DV),
|
||||
]
|
||||
|
||||
tracks.by_resolutions([2160])
|
||||
|
||||
assert [t.id for t in tracks.videos] == ["dv-2160", "hdr10-2160", "sdr-2160"]
|
||||
|
||||
|
||||
def test_sort_videos_resolution_outranks_bitrate() -> None:
|
||||
@@ -102,11 +109,6 @@ def test_sort_videos_unknown_bitrate_still_wins_on_resolution() -> None:
|
||||
assert [t.id for t in tracks.videos] == ["unknown-1080", "known-720"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# sort_audio: first track after sort is the "best" the dl layer picks
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_sort_audio_atmos_ranks_first() -> None:
|
||||
tracks = Tracks()
|
||||
tracks.audio = [
|
||||
@@ -120,7 +122,6 @@ def test_sort_audio_atmos_ranks_first() -> None:
|
||||
|
||||
best = Tracks.by_language(tracks.audio, ["en"])[0]
|
||||
assert best.id == "ec3-atmos"
|
||||
# descriptive always sorts last
|
||||
assert tracks.audio[-1].id == "ec3-desc"
|
||||
|
||||
|
||||
@@ -134,5 +135,4 @@ def test_sort_audio_codec_priority_beats_bitrate() -> None:
|
||||
tracks.sort_audio(codec_priority=["EC3", "AC3"])
|
||||
|
||||
best = Tracks.by_language(tracks.audio, ["en"])[0]
|
||||
# EC3 is prioritized even though the AC3 track has the higher bitrate
|
||||
assert best.id == "ec3-320"
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
|
||||
|
||||
def test_strip_webvtt_cue_classes():
|
||||
text = (
|
||||
"WEBVTT\n\n"
|
||||
"00:00:01.000 --> 00:00:04.000\n"
|
||||
"<c.bg_transparent>Mor, da vi blev gift,</c>\n"
|
||||
"<c>kom Ben</c> <c.a.b>og jeg</c.a.b> til dig.\n"
|
||||
"<i>Keep</i> <b>these</b> and <code>this</code>\n"
|
||||
"<i.loud>class</i> <b.x>on</b> <u.y>styling</u>\n"
|
||||
"<v.z Bob>voice</v> <lang ja>jp</lang> <ruby>\u6f22<rt>\u304b\u3093</rt></ruby>\n"
|
||||
"kara <00:00:01.500>timing <00:01.500>short\n"
|
||||
)
|
||||
out = Subtitle.strip_webvtt_cue_classes(text)
|
||||
assert "bg_transparent" not in out and "</c>" not in out and "<c>" not in out
|
||||
assert "Mor, da vi blev gift," in out
|
||||
assert "<i>Keep</i> <b>these</b> and <code>this</code>" in out
|
||||
assert "<i>class</i> <b>on</b> <u>styling</u>" in out
|
||||
assert "voice jp \u6f22\u304b\u3093" in out
|
||||
assert "kara timing short" in out
|
||||
|
||||
|
||||
def test_decode_entities(tmp_path):
|
||||
from unshackle.core.tracks.subtitle_convert import decode_entities
|
||||
|
||||
out = tmp_path / "a.srt"
|
||||
out.write_text(
|
||||
"1\n00:00:01,000 --> 00:00:04,000\nROBERT & RA'ED x 'q'\nTom ¬ sure, AT&T\n",
|
||||
encoding="utf8",
|
||||
)
|
||||
decode_entities(out)
|
||||
text = out.read_text(encoding="utf8")
|
||||
assert "ROBERT & RA'ED \xa0x 'q'" in text
|
||||
assert "Tom ¬ sure, AT&T" in text
|
||||
|
||||
|
||||
def test_filter_subs_converts_before_stripping(tmp_path, monkeypatch):
|
||||
"""``sdh_method: filter-subs`` used to hand subtitle-filter a .vtt and raise OSError."""
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
|
||||
monkeypatch.setattr(binaries, "SubtitleEdit", None)
|
||||
monkeypatch.setattr(config, "subtitle", {"sdh_method": "filter-subs"}, raising=False)
|
||||
|
||||
path = tmp_path / "sub.vtt"
|
||||
path.write_text(
|
||||
"WEBVTT\n\n00:00:01.000 --> 00:00:03.000\n[MUSIC PLAYING]\n\n"
|
||||
"00:00:04.000 --> 00:00:06.000\nPlain dialogue stays.\n",
|
||||
encoding="utf8",
|
||||
)
|
||||
sub = Subtitle(url="https://example.test/x", language="en", codec=Subtitle.Codec.WebVTT)
|
||||
sub.path = path
|
||||
sub.strip_hearing_impaired()
|
||||
|
||||
assert sub.codec == Subtitle.Codec.SubRip
|
||||
text = sub.path.read_text(encoding="utf8")
|
||||
assert "MUSIC PLAYING" not in text
|
||||
assert "Plain dialogue stays." in text
|
||||
@@ -12,9 +12,6 @@ from __future__ import annotations
|
||||
|
||||
from unshackle.core.utils.webvtt import merge_segmented_webvtt
|
||||
|
||||
# Two segments, each a full WebVTT document with its own X-TIMESTAMP-MAP header,
|
||||
# as they arrive concatenated from a DASH/HLS subtitle stream. The first cue carries
|
||||
# span tags, an {\an8} override, a cue setting, and a literal < entity.
|
||||
SEGMENTED_VTT = (
|
||||
"WEBVTT\n"
|
||||
"X-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:00:00:00.000\n\n"
|
||||
@@ -35,8 +32,8 @@ def test_merge_preserves_inline_formatting():
|
||||
|
||||
def test_merge_preserves_cue_settings_and_entities():
|
||||
out = merge_segmented_webvtt(SEGMENTED_VTT, segment_durations=[900000, 900000], timescale=1)
|
||||
assert "line:10% align:center" in out # cue positioning survives
|
||||
assert "<" in out # a literal entity is not turned into a stray tag
|
||||
assert "line:10% align:center" in out
|
||||
assert "<" in out
|
||||
|
||||
|
||||
def test_merge_collapses_headers_into_single_document():
|
||||
@@ -46,8 +43,6 @@ def test_merge_collapses_headers_into_single_document():
|
||||
|
||||
|
||||
def test_merge_dedupes_boundary_duplicate_cues():
|
||||
# A cue that spans a segment boundary is emitted in both segments; the merge
|
||||
# should collapse the adjacent identical pair into one.
|
||||
dup = SEGMENTED_VTT + (
|
||||
"\nWEBVTT\n"
|
||||
"X-TIMESTAMP-MAP=MPEGTS:2700000,LOCAL:00:00:00.000\n\n"
|
||||
@@ -59,16 +54,12 @@ def test_merge_dedupes_boundary_duplicate_cues():
|
||||
|
||||
|
||||
def test_merge_keeps_timing_lines_verbatim():
|
||||
# String-level merge must not re-render timestamps (pycaption shortened
|
||||
# 00:00:01.000 -> 00:01.000) and must keep the settings tail untouched.
|
||||
out = merge_segmented_webvtt(SEGMENTED_VTT, segment_durations=[900000, 900000], timescale=1)
|
||||
assert "00:00:01.000 --> 00:00:03.000 line:10% align:center" in out
|
||||
assert "00:00:04.000 --> 00:00:06.000" in out
|
||||
|
||||
|
||||
def test_merge_splices_triple_duplicate_into_one():
|
||||
# A cue spanning two boundaries appears in three consecutive segments; the
|
||||
# kept cue must be extended each time (latent bug: extending the dropped one).
|
||||
vtt = (
|
||||
"WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nSame cue\n\n"
|
||||
"WEBVTT\n\n00:00:02.000 --> 00:00:03.000\nSame cue\n\n"
|
||||
@@ -79,6 +70,14 @@ def test_merge_splices_triple_duplicate_into_one():
|
||||
assert "00:00:01.000 --> 00:00:04.000" in out
|
||||
|
||||
|
||||
def test_merge_duplicate_ending_earlier_keeps_later_end():
|
||||
vtt = "WEBVTT\n\n00:00:01.000 --> 00:00:05.000\n[music]\n\nWEBVTT\n\n00:00:04.900 --> 00:00:04.950\n[music]\n"
|
||||
out = merge_segmented_webvtt(vtt)
|
||||
assert out.count("[music]") == 1
|
||||
assert "00:00:01.000 --> 00:00:05.000" in out, f"kept cue was truncated:\n{out}"
|
||||
assert "00:00:04.950" not in out
|
||||
|
||||
|
||||
def test_merge_drops_cue_ids_and_notes_keeps_style():
|
||||
vtt = (
|
||||
"WEBVTT\n\n"
|
||||
@@ -90,11 +89,10 @@ def test_merge_drops_cue_ids_and_notes_keeps_style():
|
||||
assert "Hello" in out
|
||||
assert "some-cue-id-42" not in out
|
||||
assert "NOTE" not in out
|
||||
assert "STYLE\n::cue { color: red }" in out # kept; players without STYLE support ignore it
|
||||
assert "STYLE\n::cue { color: red }" in out
|
||||
|
||||
|
||||
def test_merge_dedupes_repeated_style_blocks_before_cues():
|
||||
# Every segment repeats the same STYLE block; keep exactly one, before the first cue.
|
||||
style = "WEBVTT\n\nSTYLE\n::cue { color: red }\n\n"
|
||||
vtt = style + "00:00:01.000 --> 00:00:02.000\nOne\n\n" + style + "00:00:03.000 --> 00:00:04.000\nTwo\n"
|
||||
out = merge_segmented_webvtt(vtt)
|
||||
|
||||
@@ -10,7 +10,6 @@ def test_strips_timestamp_map_keeps_cues():
|
||||
|
||||
|
||||
def test_strips_lowercase_timestamp_map():
|
||||
# SubtitleEdit honours the header case-insensitively, so the strip must too
|
||||
text = "WEBVTT\nx-timestamp-map=MPEGTS:900000,LOCAL:00:00:00.000\n\n00:00:22.690 --> 00:00:24.710\nHi\n"
|
||||
out = Subtitle.strip_webvtt_timestamp_map(text)
|
||||
assert "x-timestamp-map" not in out.lower()
|
||||
|
||||
Reference in New Issue
Block a user