refactor(manifests): share one segment pipeline across dash, hls, ism

This commit is contained in:
imSp4rky
2026-11-24 13:50:09 -07:00
parent b7018c9b27
commit e385234a92
10 changed files with 830 additions and 491 deletions
+52
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import base64
import logging
from collections import defaultdict
from functools import partial
from types import SimpleNamespace
@@ -282,12 +283,63 @@ def test_the_init_segment_adds_the_drm_system_the_track_does_not_have(monkeypatc
Widevine, "from_init_data", classmethod(lambda cls, data: pytest.fail("the track has Widevine already"))
)
track = SimpleNamespace(drm=[wv], prefers_playready=lambda cdm: True)
track.pssh_order = lambda cdm: Track.pssh_order(track, cdm)
Track.add_init_drm(track, b"init", None)
assert track.drm == [wv, pr]
@pytest.mark.parametrize(
("preference", "found", "read", "expected"),
[
("pr", {PlayReady, Widevine}, [PlayReady], PlayReady),
("pr", {Widevine}, [PlayReady, Widevine], Widevine),
("wv", {PlayReady, Widevine}, [Widevine], Widevine),
("wv", {PlayReady}, [Widevine, PlayReady], PlayReady),
],
)
def test_drm_from_pssh_reads_the_preferred_system_first(
preference: str, found: set, read: list, expected: type, caplog: pytest.LogCaptureFixture
) -> None:
from unshackle.core.tracks import Video
track = Video("https://cdn.example/v.mp4", language="en")
track.drm_preference = preference
tried: list[type] = []
def read_pssh(system: Any) -> Any:
tried.append(system)
if system not in found:
raise system.Exceptions.PSSHNotFound()
return system
with caplog.at_level(logging.DEBUG, logger="EXAMPLE"):
track.drm_from_pssh(None, read_pssh, logging.getLogger("EXAMPLE"))
assert tried == read
assert track.drm == [expected]
assert not caplog.records
def test_drm_from_pssh_without_a_pssh_logs_once_and_keeps_the_drm(caplog: pytest.LogCaptureFixture) -> None:
from unshackle.core.tracks import Video
track = Video("https://cdn.example/v.mp4", language="en")
track.drm_preference = "pr"
def read_pssh(system: Any) -> Any:
raise system.Exceptions.PSSHNotFound()
with caplog.at_level(logging.DEBUG, logger="EXAMPLE"):
track.drm_from_pssh(None, read_pssh, logging.getLogger("EXAMPLE"))
assert track.drm is None
assert [r.getMessage() for r in caplog.records] == [
"No PlayReady or Widevine PSSH was found for this track, is it DRM free?"
]
@pytest.mark.parametrize(
("entry", "expected"),
[
+116 -18
View File
@@ -4,8 +4,8 @@ Same localhost-server shape as the DASH collapse test. Each parser downloads one
track twice, with ``merge_segments`` off and on, and the two output files must be byte
identical with no segment directory left behind, and the rolling run must report no Merging
phase (the post-download run must). A second HLS case with a discontinuity checks that an
ineligible playlist keeps the post-download merge and still produces the same bytes. A stalled
drain must raise and leave no output file.
ineligible playlist keeps the post-download merge and still produces the same bytes. The shared
download, rolling merge and decrypt hand-off are tested on their own in test_segment_pipeline.
"""
from __future__ import annotations
@@ -14,6 +14,7 @@ import threading
from concurrent.futures import Future
from functools import partial
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from uuid import UUID
import pytest
@@ -25,11 +26,11 @@ from tests.core.test_hls_kid_from_init import KEY_LINE, no_kid_pssh
from tests.core.test_ism_init import piff_fragment
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import Widevine
from unshackle.core.manifests import HLS, ISM
from unshackle.core.drm import MonaLisa, Widevine
from unshackle.core.manifests import DASH, HLS, ISM
from unshackle.core.manifests import dash as dash_module
from unshackle.core.manifests import hls as hls_module
from unshackle.core.manifests import ism as ism_module
from unshackle.core.manifests.dash import RollingMerge
from unshackle.core.manifests import segment_pipeline
from unshackle.core.manifests.ism_init import PIFF_SENC_UUID
from unshackle.core.tracks.track import DownloadContext
@@ -126,6 +127,29 @@ def ism_track(srv):
return ISM.from_text(manifest, f"{base(srv)}x.ism/manifest").to_tracks().audio[0]
def dash_track(srv):
segment_urls = "\n".join(f' <SegmentURL media="part{i}.m4s"/>' for i in range(len(PARTS)))
mpd = f"""<?xml version="1.0"?>
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011">
<BaseURL>{base(srv)}</BaseURL>
<Period id="0">
<AdaptationSet contentType="video" mimeType="video/mp4" lang="en">
<Representation id="v0" codecs="avc1.640028" bandwidth="1000000" width="1920" height="1080">
<SegmentList timescale="1">
<Initialization sourceURL="init.mp4"/>
{segment_urls}
</SegmentList>
</Representation>
</AdaptationSet>
</Period>
</MPD>"""
return DASH.from_text(mpd, url=f"{base(srv)}manifest.mpd").to_tracks(language="en").videos[0]
def widevine() -> Widevine:
return Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID]))
def download_both_ways(parser, make, tmp_path, monkeypatch, expect_rolling: bool) -> tuple[bytes, bytes]:
monkeypatch.setattr(config, "merge_segments", False)
plain = make_ctx(tmp_path, "plain.mp4")
@@ -159,14 +183,18 @@ def test_ism_rolling_matches_post_merge(server, tmp_path, monkeypatch):
assert len(rolling) > len(b"".join(PARTS))
@pytest.mark.parametrize("parser, make", [(HLS, hls_track), (ISM, lambda srv, _d=None: ism_track(srv))])
@pytest.mark.parametrize(
"parser, make",
[(HLS, lambda srv: hls_track(srv, False)), (ISM, ism_track), (DASH, dash_track)],
ids=["hls", "ism", "dash"],
)
def test_incomplete_rolling_merge_raises_and_leaves_no_output(server, tmp_path, monkeypatch, parser, make):
monkeypatch.setattr(config, "merge_segments", True)
# a drain that never reaches the end must not ship a short file as a finished track
monkeypatch.setattr(RollingMerge, "add", lambda self, *a, **kw: None)
monkeypatch.setattr(segment_pipeline.RollingMerge, "add", lambda self, *a, **kw: None)
ctx = make_ctx(tmp_path, "short.mp4")
with pytest.raises(FileNotFoundError, match="Rolling merge appended 0 of"):
parser.download_track(make(server, False), ctx)
parser.download_track(make(server), ctx)
assert not ctx.save_path.exists()
@@ -198,23 +226,38 @@ class FakeSegmentDecrypter:
pass
def no_decrypt(monkeypatch, module):
# the merged file is compared byte for byte, so the decrypt step and its check are stubbed
monkeypatch.setattr(module, "decrypt_track", lambda *a, **kw: None)
monkeypatch.setattr(module, "assert_fragments_decrypted", lambda *a, **kw: None)
def no_decrypt(monkeypatch) -> list[tuple[object, bool]]:
"""Stub the decrypt step and its check, and return the (drm, decrypt) of each decrypt call.
The merged file is compared byte for byte. The pipeline decrypts a merged track; HLS itself
decrypts each key range of a post-download merge.
"""
calls: list[tuple[object, bool]] = []
def decrypt_track(drm, path, licence=None, track_kid=None, decrypt=True):
calls.append((drm, decrypt))
for module in (segment_pipeline, hls_module):
monkeypatch.setattr(module, "decrypt_track", decrypt_track)
monkeypatch.setattr(module, "assert_fragments_decrypted", lambda *a, **kw: None)
return calls
def test_ism_encrypted_rolling_matches_post_merge(server, tmp_path, monkeypatch):
for i, part in enumerate(PIFF_PARTS):
server.routes[f"/x.ism/part{i}.m4s"] = part
no_decrypt(monkeypatch, ism_module)
decrypted = no_decrypt(monkeypatch)
drms: list[FakeDRM] = []
def make():
track = ism_track(server)
track.drm = [FakeDRM()]
drms.append(FakeDRM())
track.drm = [drms[-1]]
return track
plain, rolling = download_both_ways(ISM, make, tmp_path, monkeypatch, True)
# each run hands its licensed DRM to the decrypt step
assert decrypted == [(drms[0], True), (drms[1], True)]
assert rolling == plain
# every fragment went through the PIFF to CENC rewrite, and the head carries the KID
assert PIFF_SENC_UUID not in rolling
@@ -228,11 +271,11 @@ def test_ism_encrypted_rolling_matches_post_merge(server, tmp_path, monkeypatch)
def test_hls_segment_decrypt_rolling_writes_decrypted_init(server, tmp_path, monkeypatch):
monkeypatch.setattr(hls_module, "can_use", lambda *a, **kw: True)
monkeypatch.setattr(hls_module, "SegmentDecrypter", FakeSegmentDecrypter)
no_decrypt(monkeypatch, hls_module)
decrypted = no_decrypt(monkeypatch)
def make():
track = hls_track(server, False)
track.drm = [Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID]))]
track.drm = [widevine()]
return track
def download(name, merge_segments):
@@ -248,6 +291,61 @@ def test_hls_segment_decrypt_rolling_writes_decrypted_init(server, tmp_path, mon
assert "Decrypting" in rolling.statuses
assert rolling.save_path.read_bytes() == plain.save_path.read_bytes() == DECRYPTED_INIT + b"".join(PARTS)
assert not rolling.save_dir.exists() or not list(rolling.save_dir.glob("*"))
# the segments are already clear, so the decrypt step only checks them
assert [decrypt for _, decrypt in decrypted] == [False, False]
def test_dash_hands_the_drm_to_the_decrypt_step(server, tmp_path, monkeypatch):
decrypted = no_decrypt(monkeypatch)
drm = FakeDRM()
track = dash_track(server)
track.drm = [drm]
monkeypatch.setattr(config, "merge_segments", False)
ctx = make_ctx(tmp_path, "dash.mp4")
DASH.download_track(track, ctx)
assert decrypted == [(drm, True)]
assert ctx.save_path.read_bytes() == INIT + b"".join(PARTS)
assert track.drm is None
@pytest.mark.parametrize("merge_segments", [False, True], ids=["post-merge", "rolling"])
def test_dash_segment_decrypt_writes_decrypted_init_and_only_checks(server, tmp_path, monkeypatch, merge_segments):
monkeypatch.setattr(dash_module, "can_use", lambda *a, **kw: True)
monkeypatch.setattr(dash_module, "SegmentDecrypter", FakeSegmentDecrypter)
monkeypatch.setattr(config, "merge_segments", merge_segments)
decrypted = no_decrypt(monkeypatch)
track = dash_track(server)
track.drm = [widevine()]
ctx = make_ctx(tmp_path, "dash.mp4")
ctx.license_widevine = lambda *a, **kw: None
DASH.download_track(track, ctx)
assert ctx.save_path.read_bytes() == DECRYPTED_INIT + b"".join(PARTS)
assert [decrypt for _, decrypt in decrypted] == [False]
@pytest.mark.parametrize("site", ["session-drm", "monalisa"])
def test_hls_licence_failure_cancels_the_other_tracks(server, tmp_path, monkeypatch, site):
if site == "monalisa":
# extract_keys needs a real device file
monkeypatch.setattr(MonaLisa, "extract_keys", lambda self: None)
drm = MonaLisa("ticket", Path("unused.mld"))
else:
drm = widevine()
track = hls_track(server, False)
track.drm = [drm]
licensed: list[object] = []
def refuse(drm, **kw):
licensed.append(drm)
raise PermissionError("EXAMPLE licence refused")
ctx = make_ctx(tmp_path, "refused.mp4")
ctx.license_widevine = refuse
with pytest.raises(PermissionError, match="EXAMPLE licence refused"):
HLS.download_track(track, ctx)
assert licensed == [drm]
assert DOWNLOAD_CANCELLED.is_set()
assert ctx.statuses[-2:] == ["LICENSING", "[red]FAILED"]
def test_hls_aes128_keeps_post_merge(server, tmp_path, monkeypatch):
@@ -272,7 +370,7 @@ def test_hls_rekey_takes_the_kid_from_the_init_segment_of_the_new_key(server, tm
later_kid = UUID(hex="22222222222222222222222222222222")
later_init = bytes(range(100, 200))
server.routes["/init2.mp4"] = later_init
no_decrypt(monkeypatch, hls_module)
no_decrypt(monkeypatch)
monkeypatch.setattr(config, "merge_segments", False)
def key_line(content_id: bytes) -> str:
+273
View File
@@ -0,0 +1,273 @@
"""The segment pipeline on its own: no manifest, no HTTP server, a fake downloader that writes the segment files."""
from __future__ import annotations
from concurrent.futures import Future
from functools import partial
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Iterator
from uuid import UUID
import pytest
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import verify
from unshackle.core.events import events
from unshackle.core.manifests.segment_pipeline import (
RollingMerge,
check_merged,
complete_track,
fetch_segments,
license_drm,
licensing,
)
from unshackle.core.tracks.track import DownloadContext
INIT = b"init" * 8
DECRYPTED_INIT = b"clear-init" * 8
PARTS = [bytes([0xA0 + i]) * (40 + 7 * i) for i in range(4)]
ARRIVAL = [2, 0, 3, 1]
KID = UUID(hex="11111111111111111111111111111111")
SESSION = SimpleNamespace(headers={"User-Agent": "EXAMPLE"}, cookies={})
@pytest.fixture(autouse=True)
def no_cancel() -> Iterator[None]:
DOWNLOAD_CANCELLED.clear()
yield
DOWNLOAD_CANCELLED.clear()
@pytest.fixture
def seen() -> Iterator[list[tuple[str, Any]]]:
"""Every pipeline event as (name, detail); a segment event records whether its file still existed."""
log: list[tuple[str, Any]] = []
handlers = {
events.Types.SEGMENT_DOWNLOADED: lambda track, segment: log.append(("segment", segment.exists())),
events.Types.TRACK_DOWNLOADED: lambda track: log.append(("downloaded", track.path)),
events.Types.TRACK_DECRYPTED: lambda track, drm, segment: log.append(("decrypted", drm)),
}
for kind, handler in handlers.items():
events.subscribe(kind, handler)
yield log
for kind, handler in handlers.items():
events.unsubscribe(kind, handler)
def make_ctx(tmp_path: Path, **kw: Any) -> DownloadContext:
statuses: list[str] = []
def progress(**update: Any) -> None:
if update.get("downloaded"):
statuses.append(update["downloaded"])
ctx = DownloadContext(
save_path=tmp_path / "track.mp4",
save_dir=tmp_path / "track.mp4_segments",
progress=partial(progress),
proxy="http://proxy.example:8080",
max_workers=3,
**kw,
)
ctx.statuses = statuses # type: ignore[attr-defined]
return ctx
class FakeDownloader:
"""Writes PARTS in ARRIVAL order and reports each file, with one speed update; can fail after some segments."""
def __init__(self, fail_after: int | None = None) -> None:
self.fail_after = fail_after
self.kwargs: dict[str, Any] = {}
self.closed = False
def __call__(self, **kwargs: Any) -> Iterator[dict[str, Any]]:
self.kwargs = kwargs
try:
yield {"downloaded": "1.0 MB/s"}
for n, index in enumerate(ARRIVAL):
if n == self.fail_after:
raise ConnectionError("EXAMPLE segment failed")
path = kwargs["output_dir"] / f"{index}.mp4"
path.write_bytes(PARTS[index])
yield {"file_downloaded": path}
finally:
self.closed = True
class FakeDecrypter:
"""Hands each segment back as it is, and records the order of its calls."""
def __init__(self, calls: list[tuple[str, Any]]) -> None:
self.calls = calls
def init_bytes(self) -> bytes:
return DECRYPTED_INIT
def submit(self, segment: Path) -> Future:
self.calls.append(("submit", segment.exists()))
future: Future = Future()
future.set_result(None)
return future
def finish(self) -> bytes:
self.calls.append(("finish", None))
return DECRYPTED_INIT
def close(self) -> None:
self.calls.append(("close", None))
class FakeDRM:
"""decrypt_track calls decrypt() when no hook is installed; it marks the file and records the events seen so far."""
def __init__(self, seen: list[tuple[str, Any]]) -> None:
self.seen = seen
self.events_before: list[str] = []
def decrypt(self, path: Path) -> None:
self.events_before = [name for name, _ in self.seen]
path.write_bytes(b"clear:" + path.read_bytes())
def fetch(ctx: DownloadContext, downloader: FakeDownloader, **kw: Any) -> tuple[RollingMerge | None, bytes | None]:
ctx.save_dir.mkdir(parents=True, exist_ok=True)
track = SimpleNamespace(id="EXAMPLE", downloader=downloader)
urls = [{"url": f"https://cdn.example/{i}.m4s"} for i in range(len(PARTS))]
return fetch_segments(track, ctx, SESSION, "EXAMPLE", urls, ctx.save_dir, "{i}.mp4", **kw) # type: ignore[arg-type]
def test_rolling_merge_writes_the_init_then_the_segments_in_order(tmp_path, seen):
ctx = make_ctx(tmp_path)
downloader = FakeDownloader()
merger, head_init = fetch(ctx, downloader, rolling=True, init=INIT)
assert merger is not None and merger.merged == len(PARTS) and head_init == INIT
assert ctx.save_path.read_bytes() == INIT + b"".join(PARTS)
assert not list(ctx.save_dir.iterdir())
# listeners get each segment while it still exists; the merge unlinks it afterwards
assert seen == [("segment", True)] * len(PARTS)
assert ctx.statuses == ["EXAMPLE 1.0 MB/s"]
assert downloader.closed
assert downloader.kwargs["proxy"] == ctx.proxy and downloader.kwargs["max_workers"] == ctx.max_workers
assert downloader.kwargs["headers"] is SESSION.headers and downloader.kwargs["filename"] == "{i}.mp4"
def test_without_rolling_merge_the_segments_stay_for_the_manifest_merge(tmp_path, seen):
ctx = make_ctx(tmp_path)
merger, _ = fetch(ctx, FakeDownloader())
assert merger is None
assert not ctx.save_path.exists()
assert sorted(p.name for p in ctx.save_dir.iterdir()) == [f"{i}.mp4" for i in range(len(PARTS))]
assert len(seen) == len(PARTS)
def test_a_decrypter_gets_each_segment_before_its_event_and_heads_the_output(tmp_path, seen):
ctx = make_ctx(tmp_path)
merger, decrypted_init = fetch(ctx, FakeDownloader(), rolling=True, init=INIT, decrypter=FakeDecrypter(seen))
assert decrypted_init == DECRYPTED_INIT
assert ctx.save_path.read_bytes() == DECRYPTED_INIT + b"".join(PARTS)
assert seen == [("submit", True), ("segment", True)] * len(PARTS) + [("finish", None)]
def test_a_failure_closes_the_decrypter_and_removes_the_output(tmp_path, seen):
ctx = make_ctx(tmp_path)
calls: list[tuple[str, Any]] = []
downloader = FakeDownloader(fail_after=2)
with pytest.raises(ConnectionError, match="EXAMPLE segment failed"):
fetch(ctx, downloader, rolling=True, init=INIT, decrypter=FakeDecrypter(calls))
assert downloader.closed
assert calls[-1] == ("close", None) and ("finish", None) not in calls
assert not ctx.save_path.exists()
def test_a_short_rolling_merge_raises_and_removes_the_output(tmp_path):
ctx = make_ctx(tmp_path)
ctx.save_path.write_bytes(INIT)
merger = RollingMerge(open(ctx.save_path, "ab"))
merger.dst.close()
with pytest.raises(FileNotFoundError, match=f"Rolling merge appended 0 of {len(PARTS)} segments"):
check_merged(merger, len(PARTS), SimpleNamespace(id="EXAMPLE"), ctx, "EXAMPLE") # type: ignore[arg-type]
assert not ctx.save_path.exists()
check_merged(merger, 0, SimpleNamespace(id="EXAMPLE"), ctx, "EXAMPLE") # type: ignore[arg-type]
def test_license_drm_wraps_the_callback_in_licensing_progress(tmp_path):
received: list[tuple[Any, dict[str, Any]]] = []
ctx = make_ctx(tmp_path, license_widevine=lambda drm, **kw: received.append((drm, kw)))
drm = object()
with licensing(ctx):
license_drm(drm, ctx, track_kid=KID) # type: ignore[arg-type]
assert received == [(drm, {"track_kid": KID})]
assert ctx.statuses == ["LICENSING", "[yellow]LICENSED"]
assert not DOWNLOAD_CANCELLED.is_set()
def test_a_licence_failure_cancels_the_other_tracks_and_shows_failed(tmp_path):
def refuse(drm: Any, **kw: Any) -> None:
raise PermissionError("EXAMPLE licence refused")
ctx = make_ctx(tmp_path, license_widevine=refuse)
with pytest.raises(PermissionError, match="EXAMPLE licence refused"):
with licensing(ctx):
license_drm(object(), ctx) # type: ignore[arg-type]
assert ctx.statuses == ["LICENSING", "[red]FAILED"]
assert DOWNLOAD_CANCELLED.is_set()
def test_license_drm_without_a_callback_raises(tmp_path):
ctx = make_ctx(tmp_path)
with pytest.raises(ValueError, match="license_widevine func must be supplied"):
license_drm(object(), ctx) # type: ignore[arg-type]
assert ctx.statuses == []
@pytest.fixture
def no_hook(monkeypatch):
monkeypatch.setattr(verify, "DECRYPT_HOOK", None)
def test_complete_track_emits_downloaded_then_decrypts_then_cleans_up(tmp_path, seen, no_hook):
ctx = make_ctx(tmp_path)
ctx.save_dir.mkdir()
ctx.save_path.write_bytes(b"merged")
drm = FakeDRM(seen)
track = SimpleNamespace(path=None, drm=[drm])
complete_track(track, ctx, drm) # type: ignore[arg-type]
assert drm.events_before == ["downloaded"]
assert seen == [("downloaded", ctx.save_path), ("decrypted", drm)]
assert ctx.save_path.read_bytes() == b"clear:merged"
assert track.path == ctx.save_path and track.drm is None
assert ctx.statuses == ["Decrypting", "Decrypted", "Downloaded"]
assert not ctx.save_dir.exists()
def test_complete_track_after_segment_decryption_only_checks(tmp_path, seen, no_hook):
ctx = make_ctx(tmp_path)
ctx.save_path.write_bytes(b"merged")
drm = FakeDRM(seen)
complete_track(SimpleNamespace(path=None, drm=[drm]), ctx, drm, decrypt=False) # type: ignore[arg-type]
assert ctx.save_path.read_bytes() == b"merged"
assert [name for name, _ in seen] == ["downloaded", "decrypted"]
def test_complete_track_without_drm_skips_the_decryption(tmp_path, seen):
ctx = make_ctx(tmp_path)
ctx.save_path.write_bytes(b"merged")
complete_track(SimpleNamespace(path=None, drm=None), ctx, None) # type: ignore[arg-type]
assert seen == [("downloaded", ctx.save_path)]
assert ctx.statuses == ["Downloaded"]
+7 -3
View File
@@ -177,12 +177,16 @@ def test_downloaders_route_through_the_hook(monkeypatch: pytest.MonkeyPatch) ->
"""Every real decrypt site calls decrypt_track, so the dl hook sees it."""
import inspect
from unshackle.core.manifests import dash, hls, ism
from unshackle.core.manifests import dash, hls, ism, segment_pipeline
from unshackle.core.tracks import track
for module in (dash, hls, ism, track):
for module in (segment_pipeline, hls, track):
assert "decrypt_track(" in inspect.getsource(module), module.__name__
# DASH and ISM decrypt through the pipeline's complete_track, which calls decrypt_track
for module in (dash, ism):
assert "complete_track(" in inspect.getsource(module), module.__name__
for module in (dash, hls, ism, segment_pipeline, track):
src = inspect.getsource(module)
assert "decrypt_track(" in src, module.__name__
assert "drm.decrypt(save_path)" not in src and "drm.decrypt(merged_path)" not in src, module.__name__