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__
+1 -1
View File
@@ -3,7 +3,7 @@ import random
from concurrent.futures import Future
from pathlib import Path
from unshackle.core.manifests.dash import RollingMerge, append_segment
from unshackle.core.manifests.segment_pipeline import RollingMerge, append_segment
def write_segments(save_dir: Path, payloads: list[bytes]) -> int:
+41 -205
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
import base64
import html
import logging
import math
import mmap
@@ -9,8 +8,7 @@ import os
import re
import shutil
from bisect import bisect_right
from concurrent.futures import Future
from contextlib import ExitStack, closing, suppress
from contextlib import suppress
from copy import deepcopy
from functools import lru_cache, partial
from pathlib import Path
@@ -29,21 +27,23 @@ from requests import Session
from unshackle.core import binaries
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.downloaders.requests import parse_content_range
from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
from unshackle.core.drm.segment_decrypt import SEGMENT_DRM_T, SegmentDecrypter, can_use
from unshackle.core.drm.verify import decrypt_track, walk
from unshackle.core.events import events
from unshackle.core.drm.verify import walk
from unshackle.core.manifests.segment_pipeline import (
append_segment,
check_merged,
complete_track,
fetch_segments,
license_drm,
licensing,
)
from unshackle.core.manifests.trim import trim_overlaps
from unshackle.core.session import RnetSession
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
from unshackle.core.tracks.track import (
DRM_PREFERENCE_TYPES,
Track,
assert_fragments_decrypted,
parse_sidx,
)
from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track, parse_sidx
from unshackle.core.utilities import is_close_match, log_event, try_ensure_utf8
from unshackle.core.utils import run_proxy
from unshackle.core.utils.bitrate import ranged_get
@@ -105,63 +105,6 @@ def rebase_webvtt_files(groups: list[list[Path]], bounds_ms: list[int]) -> None:
path.write_bytes(shift_webvtt(text, offset).encode("utf8"))
def append_segment(dst: BinaryIO, segment_file: Path, is_text_subtitle: bool) -> None:
"""Append one segment file to the output, with the text subtitle fixups when they apply."""
if is_text_subtitle:
segment_data = try_ensure_utf8(segment_file.read_bytes())
segment_data = (
segment_data.decode("utf8")
.replace("&lrm;", html.unescape("&lrm;"))
.replace("&rlm;", html.unescape("&rlm;"))
.encode("utf8")
)
dst.write(segment_data)
else:
with open(segment_file, "rb") as src:
shutil.copyfileobj(src, dst, 1024 * 1024)
class RollingMerge:
"""Appends segments to the output in index order as they arrive, out of order, and unlinks them.
A cursor holds the next expected index; every `add` records one ready segment and then drains
every contiguous ready segment from the cursor onward. A segment that carries a future (per-segment
decryption) waits for that future before the append, so the output never holds raw bytes.
`append(dst, segment_file)` writes one segment; the default is a plain byte copy. A parser
whose merge needs a per-segment transform, or a head that only exists once segment 0 has
landed (ISM), passes its own.
"""
def __init__(self, dst: BinaryIO, append: Optional[Callable[[BinaryIO, Path], None]] = None) -> None:
self.dst = dst
self.append = append or (lambda dst, path: append_segment(dst, path, is_text_subtitle=False))
self.cursor = 0
self.ready: dict[int, tuple[Path, Optional[Future]]] = {}
def add(self, index: int, segment_file: Path, future: Optional[Future] = None) -> None:
# runs on the downloader's own loop, so a decrypt wait or a catch-up burst
# delays new submissions; move the drain to a writer thread if throughput measurably drops
self.ready[index] = (segment_file, future)
while self.cursor in self.ready:
path, pending = self.ready.pop(self.cursor)
if pending is not None:
pending.result()
self.append(self.dst, path)
self.cursor += 1
# the bytes are already in the output; a handle another process still holds on
# the just-replaced file (Windows) must not fail the track, the segment dir sweep
# after the download removes any leftover
try:
path.unlink()
except OSError:
pass
@property
def merged(self) -> int:
return self.cursor
def mdhd_timescale(init_data: bytes) -> Optional[int]:
"""The media timescale of the first track in an init segment, or None when it has no mdhd."""
for kind, body, box_end in walk(init_data):
@@ -534,15 +477,10 @@ class DASH:
save_path = ctx.save_path
save_dir = ctx.save_dir
progress = ctx.progress
proxy = ctx.proxy
max_workers = ctx.max_workers
adaptive = ctx.adaptive_workers
processes = ctx.download_processes
license_widevine = ctx.license_widevine
cdm = ctx.cdm
if proxy:
session.proxies.update({"all": proxy})
if ctx.proxy:
session.proxies.update({"all": ctx.proxy})
log = logging.getLogger("DASH")
assert isinstance(track.url, str)
@@ -700,39 +638,16 @@ class DASH:
elif DOWNLOAD_ALL_DRM.is_set() and init_data and binaries.FFProbe and isinstance(track, (Video, Audio)):
track.add_init_drm(init_data, cdm)
elif not track.drm and init_data and isinstance(track, (Video, Audio)):
prefers_playready = track.prefers_playready(cdm)
if prefers_playready:
try:
track.drm = [PlayReady.from_init_data(init_data)]
except PlayReady.Exceptions.PSSHNotFound:
try:
track.drm = [Widevine.from_init_data(init_data)]
except Widevine.Exceptions.PSSHNotFound:
log.debug("No PlayReady or Widevine PSSH was found for this track, is it DRM free?")
else:
try:
track.drm = [Widevine.from_init_data(init_data)]
except Widevine.Exceptions.PSSHNotFound:
try:
track.drm = [PlayReady.from_init_data(init_data)]
except PlayReady.Exceptions.PSSHNotFound:
log.debug("No Widevine or PlayReady PSSH was found for this track, is it DRM free?")
pssh_init = init_data
track.drm_from_pssh(cdm, lambda system: system.from_init_data(pssh_init), log)
if track.drm:
track_kid = track_kid or track.get_key_id(url=segments[0][0], session=session)
drm = track.get_drm_for_cdm(cdm)
if isinstance(drm, (Widevine, PlayReady, ClearKeyCENC)):
# license and grab content keys (ClearKeyCENC uses no CDM)
try:
if not license_widevine:
raise ValueError("license_widevine func must be supplied to use DRM")
progress(downloaded="LICENSING")
license_widevine(drm, track_kid=track_kid)
progress(downloaded="[yellow]LICENSED")
except Exception: # noqa
DOWNLOAD_CANCELLED.set() # skip pending track downloads
progress(downloaded="[red]FAILED")
raise
with licensing(ctx):
license_drm(drm, ctx, track_kid=track_kid)
else:
drm = None
@@ -742,8 +657,6 @@ class DASH:
progress(total=len(segments))
downloader = track.downloader
# A parent resource that is itself a valid MP4 downloads in one pass to save_path,
# replacing the per-segment files, init write and merge pass.
collapse_span = (
@@ -773,37 +686,16 @@ class DASH:
if can_resume:
resume.write_sidecar(save_dir, digest)
downloader_args: dict[str, Any]
urls: list[dict[str, Any]]
if collapse_single_url:
# must carry no Range header, or the downloader would skip its ranged-parallel path
downloader_args = dict(
urls=[{"url": segments[0][0]}],
output_dir=save_path.parent,
filename=save_path.name,
headers=session.headers,
cookies=session.cookies,
proxy=proxy,
max_workers=max_workers,
session=session,
adaptive=adaptive,
processes=processes,
)
urls, output_dir, filename = [{"url": segments[0][0]}], save_path.parent, save_path.name
else:
downloader_args = dict(
urls=[
{"url": url, "headers": {"Range": f"bytes={bytes_range}"} if bytes_range else {}}
for url, bytes_range in segments
],
output_dir=save_dir,
filename="{i:0%d}.mp4" % (len(str(len(segments)))),
headers=session.headers,
cookies=session.cookies,
proxy=proxy,
max_workers=max_workers,
session=session,
adaptive=adaptive,
processes=processes,
)
urls = [
{"url": url, "headers": {"Range": f"bytes={bytes_range}"} if bytes_range else {}}
for url, bytes_range in segments
]
output_dir, filename = save_dir, "{i:0%d}.mp4" % (len(str(len(segments))))
log_event(
"manifest_dash_download_start",
@@ -826,7 +718,7 @@ class DASH:
decrypter: Optional[SegmentDecrypter] = None
if use_segment_decrypt and init_data:
decrypter = SegmentDecrypter(cast(SEGMENT_DRM_T, drm), init_data, save_dir.parent, max_workers)
decrypter = SegmentDecrypter(cast(SEGMENT_DRM_T, drm), init_data, save_dir.parent, ctx.max_workers)
rebase: Optional[PeriodRebase] = None
known = timed and len(period_starts) > 1
@@ -835,41 +727,19 @@ class DASH:
rebase = PeriodRebase(period_starts, timescale)
append = rebase.append if rebase else partial(append_segment, is_text_subtitle=is_text_subtitle)
merger: Optional[RollingMerge] = None
try:
with ExitStack() as stack:
if use_rolling_merge:
output = stack.enter_context(open(save_path, "wb"))
head = decrypter.init_bytes() if decrypter else init_data
if head:
output.write(head)
merger = RollingMerge(output, append)
# an exception raised in this body (a decrypt failure re-raised by the merge)
# must close the generator now, so its finally aborts the workers
stream = stack.enter_context(closing(downloader(**downloader_args)))
for status_update in stream:
file_downloaded = status_update.get("file_downloaded")
if file_downloaded:
future = decrypter.submit(file_downloaded) if decrypter else None
# listeners get the segment while it still exists; the merge unlinks it
events.emit(events.Types.SEGMENT_DOWNLOADED, track=track, segment=file_downloaded)
if merger:
merger.add(int(file_downloaded.stem), file_downloaded, future)
else:
downloaded = status_update.get("downloaded")
if downloaded and downloaded.endswith("/s"):
status_update["downloaded"] = f"DASH {downloaded}"
progress(**status_update)
if decrypter:
init_data = decrypter.finish()
except BaseException:
if decrypter:
decrypter.close()
if merger:
save_path.unlink(missing_ok=True)
raise
merger, init_data = fetch_segments(
track,
ctx,
session,
"DASH",
urls,
output_dir,
filename,
rolling=use_rolling_merge,
init=init_data,
append=append,
decrypter=decrypter,
)
if collapse_span:
with open(save_path, "r+b") as collapsed:
@@ -877,22 +747,7 @@ class DASH:
elif merger:
for control_file in save_dir.glob("*.!dev"):
control_file.unlink(missing_ok=True)
if merger.merged != len(segments):
error_msg = f"Rolling merge appended {merger.merged} of {len(segments)} segments: {save_dir}"
log_event(
"manifest_dash_rolling_merge_incomplete",
level="ERROR",
message=error_msg,
context={
"track_id": getattr(track, "id", None),
"track_type": track.__class__.__name__,
"save_dir": str(save_dir),
"merged": merger.merged,
"total_segments": len(segments),
"downloader": "requests",
},
)
raise FileNotFoundError(error_msg)
check_merged(merger, len(segments), track, ctx, "DASH")
else:
if not save_dir.exists():
error_msg = f"Output directory does not exist: {save_dir}"
@@ -974,26 +829,7 @@ class DASH:
except Exception as e:
log.warning(f"Could not trim the audio overlaps of {save_path.name}: {e}")
track.path = save_path
events.emit(events.Types.TRACK_DOWNLOADED, track=track)
if drm:
progress(downloaded="Decrypting", completed=0, total=None)
decrypt_track(drm, save_path, license_widevine, decrypt=not decrypter)
assert_fragments_decrypted(save_path)
track.drm = None
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=None)
progress(downloaded="Decrypted", completed=100, total=100)
if save_dir.exists() and save_dir.name.endswith("_segments"):
try:
save_dir.rmdir()
except OSError:
# Directory might not be empty, try removing recursively
shutil.rmtree(save_dir, ignore_errors=True)
resume.clear_sidecar(save_dir)
progress(downloaded="Downloaded")
complete_track(track, ctx, drm, decrypt=not decrypter)
@staticmethod
def find_segment_element(name: str, adaptation_set: Element, representation: Element) -> Optional[Element]:
+42 -136
View File
@@ -9,7 +9,7 @@ import re
import shutil
import subprocess
import time
from contextlib import ExitStack, closing, suppress
from contextlib import suppress
from functools import partial
from itertools import accumulate
from pathlib import Path
@@ -31,18 +31,20 @@ from requests import Session
from unshackle.core import binaries
from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm, is_widevine_cdm
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, MonaLisa, PlayReady, Widevine
from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
from unshackle.core.drm.verify import decrypt_track
from unshackle.core.events import events
from unshackle.core.manifests.dash import (
PeriodRebase,
RollingMerge,
from unshackle.core.manifests.dash import PeriodRebase, mdhd_timescale, missing_language, rebase_webvtt_files
from unshackle.core.manifests.segment_pipeline import (
append_segment,
mdhd_timescale,
missing_language,
rebase_webvtt_files,
check_merged,
decrypt_output,
fetch_segments,
license_drm,
licensing,
remove_segment_dir,
)
from unshackle.core.session import RnetResponse, RnetSession, utf8_text
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
@@ -645,16 +647,12 @@ class HLS:
save_path = ctx.save_path
save_dir = ctx.save_dir
progress = ctx.progress
proxy = ctx.proxy
max_workers = ctx.max_workers
adaptive = ctx.adaptive_workers
processes = ctx.download_processes
license_widevine = ctx.license_widevine
cdm = ctx.cdm
if proxy:
if ctx.proxy:
if isinstance(session, Session):
session.proxies.update({"all": proxy})
session.proxies.update({"all": ctx.proxy})
log = logging.getLogger("HLS")
assert isinstance(track.url, str)
@@ -720,19 +718,11 @@ class HLS:
track.drm = [media_drm]
if DOWNLOAD_ALL_DRM.is_set():
track.drm += HLS.alternate_drm(media_keys, media_drm, session, init_kid)
try:
if not license_widevine:
raise ValueError("license_widevine func must be supplied to use DRM")
progress(downloaded="LICENSING")
license_widevine(media_drm, track_kid=track_kid)
progress(downloaded="[yellow]LICENSED")
initial_drm_licensed = True
initial_drm_key = media_playlist_key
session_drm = media_drm
except Exception: # noqa
DOWNLOAD_CANCELLED.set() # skip pending track downloads
progress(downloaded="[red]FAILED")
raise
with licensing(ctx):
license_drm(media_drm, ctx, track_kid=track_kid)
initial_drm_licensed = True
initial_drm_key = media_playlist_key
session_drm = media_drm
elif isinstance(media_drm, ClearKey):
# AES-128 (ClearKey) needs no license server - the key is already fetched.
track.drm = [media_drm]
@@ -741,29 +731,13 @@ class HLS:
initial_drm_licensed = True
if not initial_drm_licensed and session_drm and isinstance(session_drm, (Widevine, PlayReady)):
try:
if not license_widevine:
raise ValueError("license_widevine func must be supplied to use DRM")
with licensing(ctx):
track_kid = HLS.get_track_kid_from_init(master, track, session) or session_drm.kid
progress(downloaded="LICENSING")
license_widevine(session_drm, track_kid=track_kid)
progress(downloaded="[yellow]LICENSED")
except Exception: # noqa
DOWNLOAD_CANCELLED.set() # skip pending track downloads
progress(downloaded="[red]FAILED")
raise
license_drm(session_drm, ctx, track_kid=track_kid)
if not initial_drm_licensed and session_drm and isinstance(session_drm, MonaLisa):
try:
if not license_widevine:
raise ValueError("license_widevine func must be supplied to use DRM")
progress(downloaded="LICENSING")
license_widevine(session_drm)
progress(downloaded="[yellow]LICENSED")
except Exception: # noqa
DOWNLOAD_CANCELLED.set() # skip pending track downloads
progress(downloaded="[red]FAILED")
raise
with licensing(ctx):
license_drm(session_drm, ctx)
if DOWNLOAD_LICENCE_ONLY.is_set():
# a playlist can change its key part-way, and only the download loop licenses the later keys
@@ -799,8 +773,6 @@ class HLS:
total_segments = len(master.segments) - len(unwanted_segments)
progress(total=total_segments)
downloader = track.downloader
urls: list[dict[str, Any]] = []
segment_durations: list[int] = []
@@ -849,19 +821,6 @@ class HLS:
if config.continue_downloads and resumable_drm:
resume.write_sidecar(save_dir, digest)
downloader_args: dict[str, Any] = dict(
urls=urls,
output_dir=segment_save_dir,
filename="{i:0%d}{ext}" % len(str(len(urls))),
headers=session.headers,
cookies=session.cookies,
proxy=proxy,
max_workers=max_workers,
session=session,
adaptive=adaptive,
processes=processes,
)
log_event(
"manifest_hls_download_start",
level="DEBUG",
@@ -885,35 +844,20 @@ class HLS:
use_segment_decrypt = use_segment_decrypt and can_use(session_drm, config.decryption, init_content)
if use_segment_decrypt:
assert isinstance(session_drm, (Widevine, PlayReady, ClearKeyCENC))
segment_decrypter = SegmentDecrypter(session_drm, init_content, save_dir.parent, max_workers)
segment_decrypter = SegmentDecrypter(session_drm, init_content, save_dir.parent, ctx.max_workers)
merger: Optional[RollingMerge] = None
try:
with ExitStack() as stack:
if use_rolling_merge:
output = stack.enter_context(open(save_path, "wb"))
output.write(segment_decrypter.init_bytes() if segment_decrypter else init_content)
merger = RollingMerge(output)
stream = stack.enter_context(closing(downloader(**downloader_args)))
for status_update in stream:
file_downloaded = status_update.get("file_downloaded")
if file_downloaded:
future = segment_decrypter.submit(file_downloaded) if segment_decrypter else None
events.emit(events.Types.SEGMENT_DOWNLOADED, track=track, segment=file_downloaded)
if merger:
merger.add(int(file_downloaded.stem), file_downloaded, future)
else:
downloaded = status_update.get("downloaded")
if downloaded and downloaded.endswith("/s"):
status_update["downloaded"] = f"HLS {downloaded}"
progress(**status_update)
except BaseException:
if segment_decrypter:
segment_decrypter.close()
if merger:
save_path.unlink(missing_ok=True)
raise
merger, decrypted_init = fetch_segments(
track,
ctx,
session,
"HLS",
urls,
segment_save_dir,
"{i:0%d}{ext}" % len(str(len(urls))),
rolling=use_rolling_merge,
init=map_data[1] if map_data else None,
decrypter=segment_decrypter,
)
for control_file in segment_save_dir.glob("*.!dev"):
control_file.unlink(missing_ok=True)
@@ -922,27 +866,8 @@ class HLS:
resume.clear_sidecar(save_dir)
if merger:
if segment_decrypter:
segment_decrypter.finish()
if merger.merged != total_segments:
error_msg = f"Rolling merge appended {merger.merged} of {total_segments} segments: {save_dir}"
log_event(
"manifest_hls_rolling_merge_incomplete",
level="ERROR",
message=error_msg,
context={
"track_id": getattr(track, "id", None),
"track_type": track.__class__.__name__,
"save_dir": str(save_dir),
"merged": merger.merged,
"total_segments": total_segments,
"downloader": "requests",
},
)
save_path.unlink(missing_ok=True)
raise FileNotFoundError(error_msg)
if save_dir.name.endswith("_segments"):
shutil.rmtree(save_dir, ignore_errors=True)
check_merged(merger, total_segments, track, ctx, "HLS")
remove_segment_dir(save_dir)
log_event(
"manifest_hls_download_complete",
level="DEBUG",
@@ -957,11 +882,7 @@ class HLS:
},
)
if session_drm:
progress(downloaded="Decrypting", completed=0, total=None)
decrypt_track(session_drm, save_path, license_widevine, decrypt=not segment_decrypter)
assert_fragments_decrypted(save_path)
track.drm = None
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=session_drm, segment=None)
decrypt_output(track, ctx, session_drm, decrypt=not segment_decrypter)
progress(downloaded="Downloaded", completed=100, total=100)
track.path = save_path
events.emit(events.Types.TRACK_DOWNLOADED, track=track)
@@ -975,7 +896,6 @@ class HLS:
# First segment's Media Sequence Number - used as the AES-128 IV when EXT-X-KEY has
# no explicit IV (RFC 8216 §5.2), where each segment's IV is its sequence number.
media_sequence_start = getattr(master, "media_sequence", None) or 0
decrypted_init: Optional[bytes] = None
encryption_data: Optional[tuple[Optional[m3u8.Key], DRM_T]] = None
if session_drm:
encryption_data = (initial_drm_key, session_drm)
@@ -1032,7 +952,7 @@ class HLS:
Returns the decrypted path.
"""
nonlocal map_data, decrypted_init
nonlocal map_data
assert encryption_data is not None
drm = encryption_data[1]
first_segment_i = next(
@@ -1062,8 +982,7 @@ class HLS:
if segment_decrypter:
if not map_data:
raise ValueError("Segment decryption needs an EXT-X-MAP init segment.")
if decrypted_init is None:
decrypted_init = segment_decrypter.finish()
assert decrypted_init is not None
map_data = (map_data[0], decrypted_init)
merge(to=merged_path, via=files, delete=True, include_map_data=True)
decrypt_track(drm, merged_path, license_widevine, decrypt=not segment_decrypter)
@@ -1158,20 +1077,11 @@ class HLS:
if key is None:
encryption_data = None
elif not encryption_data or encryption_data[0] != key:
try:
with licensing(ctx):
init_kid = track.get_key_id(map_data[1]) if map_data and key.method != "AES-128" else None
drm = HLS.get_drm(key, session, **({"kid": init_kid} if init_kid else {}))
if isinstance(drm, (Widevine, PlayReady)):
if not license_widevine:
raise ValueError("license_widevine func must be supplied to use DRM")
track_kid = init_kid or drm.kid
progress(downloaded="LICENSING")
license_widevine(drm, track_kid=track_kid)
progress(downloaded="[yellow]LICENSED")
except Exception: # noqa
DOWNLOAD_CANCELLED.set() # skip pending track downloads
progress(downloaded="[red]FAILED")
raise
license_drm(drm, ctx, track_kid=init_kid or drm.kid)
if (
encryption_data
and isinstance(drm, (Widevine, PlayReady))
@@ -1258,11 +1168,7 @@ class HLS:
with suppress(OSError):
discontinuity_file.unlink()
if save_dir.exists() and save_dir.name.endswith("_segments"):
try:
save_dir.rmdir()
except OSError:
shutil.rmtree(save_dir, ignore_errors=True)
remove_segment_dir(save_dir)
progress(downloaded="Downloaded", completed=100, total=100)
+30 -97
View File
@@ -8,7 +8,7 @@ import re
import shutil
import struct
import urllib.parse
from contextlib import ExitStack, closing, suppress
from contextlib import suppress
from pathlib import Path
from typing import Any, BinaryIO, Optional, Union
@@ -19,11 +19,9 @@ from pywidevine.pssh import PSSH
from requests import Session
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.drm import DRM_T, PlayReady, Widevine
from unshackle.core.drm.verify import decrypt_track
from unshackle.core.events import events
from unshackle.core.manifests.dash import RollingMerge, append_segment, missing_language
from unshackle.core.manifests.dash import missing_language
from unshackle.core.manifests.ism_init import (
build_init_segment,
parse_codec_private_data_vui,
@@ -31,9 +29,16 @@ from unshackle.core.manifests.ism_init import (
read_per_sample_iv_size,
read_track_id,
)
from unshackle.core.manifests.segment_pipeline import (
append_segment,
check_merged,
complete_track,
fetch_segments,
license_drm,
licensing,
)
from unshackle.core.session import RnetSession
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video, resume
from unshackle.core.tracks.track import assert_fragments_decrypted
from unshackle.core.utilities import log_event, try_ensure_utf8
from unshackle.core.utils import run_proxy
from unshackle.core.utils.redact import safe_display_url
@@ -403,15 +408,9 @@ class ISM:
save_path = ctx.save_path
save_dir = ctx.save_dir
progress = ctx.progress
proxy = ctx.proxy
max_workers = ctx.max_workers
adaptive = ctx.adaptive_workers
processes = ctx.download_processes
license_widevine = ctx.license_widevine
cdm = ctx.cdm
if proxy:
session.proxies.update({"all": proxy})
if ctx.proxy:
session.proxies.update({"all": ctx.proxy})
segments: list[str] = track.data["ism"]["segments"]
segment_times: list[int] = track.data["ism"].get("segment_times") or []
@@ -424,18 +423,10 @@ class ISM:
if track.drm:
# Mirror HLS.download_track: pick the DRM matching the provided CDM
# (or the first available) and license it if supported.
session_drm = track.get_drm_for_cdm(cdm)
session_drm = track.get_drm_for_cdm(ctx.cdm)
if isinstance(session_drm, (Widevine, PlayReady)):
try:
if not license_widevine:
raise ValueError("license_widevine func must be supplied to use DRM")
progress(downloaded="LICENSING")
license_widevine(session_drm)
progress(downloaded="[yellow]LICENSED")
except Exception:
DOWNLOAD_CANCELLED.set()
progress(downloaded="[red]FAILED")
raise
with licensing(ctx):
license_drm(session_drm, ctx)
if DOWNLOAD_LICENCE_ONLY.is_set():
progress(downloaded="[yellow]SKIPPED")
@@ -443,8 +434,6 @@ class ISM:
progress(total=len(segments))
downloader = track.downloader
use_rolling_merge = config.merge_segments and not isinstance(track, Subtitle)
can_resume = config.continue_downloads and not use_rolling_merge
@@ -456,19 +445,6 @@ class ISM:
if can_resume:
resume.write_sidecar(save_dir, digest)
downloader_args: dict[str, Any] = dict(
urls=[{"url": url} for url in segments],
output_dir=save_dir,
filename="{i:0%d}.mp4" % len(str(len(segments))),
headers=session.headers,
cookies=session.cookies,
proxy=proxy,
max_workers=max_workers,
session=session,
adaptive=adaptive,
processes=processes,
)
log_event(
"manifest_ism_download_start",
level="DEBUG",
@@ -501,28 +477,17 @@ class ISM:
else:
append_segment(dst, segment_file, is_text_subtitle=False)
merger: Optional[RollingMerge] = None
try:
with ExitStack() as stack:
if use_rolling_merge:
output = stack.enter_context(open(save_path, "wb"))
merger = RollingMerge(output, append_ism)
stream = stack.enter_context(closing(downloader(**downloader_args)))
for status_update in stream:
file_downloaded = status_update.get("file_downloaded")
if file_downloaded:
events.emit(events.Types.SEGMENT_DOWNLOADED, track=track, segment=file_downloaded)
if merger:
merger.add(int(file_downloaded.stem), file_downloaded)
else:
downloaded = status_update.get("downloaded")
if downloaded and downloaded.endswith("/s"):
status_update["downloaded"] = f"ISM {downloaded}"
progress(**status_update)
except BaseException:
if merger:
save_path.unlink(missing_ok=True)
raise
merger, _ = fetch_segments(
track,
ctx,
session,
"ISM",
[{"url": url} for url in segments],
save_dir,
"{i:0%d}.mp4" % len(str(len(segments))),
rolling=use_rolling_merge,
append=append_ism,
)
if not save_dir.exists():
error_msg = f"Output directory does not exist: {save_dir}"
@@ -543,23 +508,8 @@ class ISM:
for control_file in save_dir.glob("*.!dev"):
control_file.unlink(missing_ok=True)
if merger and merger.merged != len(segments):
error_msg = f"Rolling merge appended {merger.merged} of {len(segments)} segments: {save_dir}"
log_event(
"manifest_ism_rolling_merge_incomplete",
level="ERROR",
message=error_msg,
context={
"track_id": getattr(track, "id", None),
"track_type": track.__class__.__name__,
"save_dir": str(save_dir),
"merged": merger.merged,
"total_segments": len(segments),
"downloader": "requests",
},
)
save_path.unlink(missing_ok=True)
raise FileNotFoundError(error_msg)
if merger:
check_merged(merger, len(segments), track, ctx, "ISM")
segments_to_merge = [] if merger else [x for x in sorted(save_dir.iterdir()) if x.is_file()]
@@ -633,24 +583,7 @@ class ISM:
segment_file.unlink()
progress(advance=1)
track.path = save_path
events.emit(events.Types.TRACK_DOWNLOADED, track=track)
if session_drm:
progress(downloaded="Decrypting", completed=0, total=None)
decrypt_track(session_drm, save_path, license_widevine)
assert_fragments_decrypted(save_path)
track.drm = None
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=session_drm, segment=None)
progress(downloaded="Decrypted", completed=100, total=100)
try:
save_dir.rmdir()
except OSError:
# a superseded hedge download may still drop a .!dev file here
shutil.rmtree(save_dir, ignore_errors=True)
resume.clear_sidecar(save_dir)
progress(downloaded="Downloaded")
complete_track(track, ctx, session_drm)
__all__ = ("ISM",)
@@ -0,0 +1,243 @@
"""The segment pipeline: the steps DASH, HLS and ISM share to download a segmented track.
Each manifest finds its own segments and supplies its own quirks; the pipeline runs the
licence step, the download with its rolling merge, the decrypt hand-off and the cleanup.
"""
from __future__ import annotations
import html
import shutil
from concurrent.futures import Future
from contextlib import ExitStack, closing, contextmanager
from pathlib import Path
from typing import Any, BinaryIO, Callable, Iterator, Optional
from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack
from unshackle.core.drm import DRM_T
from unshackle.core.drm.segment_decrypt import SegmentDecrypter
from unshackle.core.drm.verify import decrypt_track
from unshackle.core.events import events
from unshackle.core.session import AnySession
from unshackle.core.tracks import DownloadContext, resume
from unshackle.core.tracks.track import assert_fragments_decrypted
from unshackle.core.utilities import log_event, try_ensure_utf8
def append_segment(dst: BinaryIO, segment_file: Path, is_text_subtitle: bool) -> None:
"""Append one segment file to the output, with the text subtitle fixups when they apply."""
if is_text_subtitle:
segment_data = try_ensure_utf8(segment_file.read_bytes())
segment_data = (
segment_data.decode("utf8")
.replace("&lrm;", html.unescape("&lrm;"))
.replace("&rlm;", html.unescape("&rlm;"))
.encode("utf8")
)
dst.write(segment_data)
else:
with open(segment_file, "rb") as src:
shutil.copyfileobj(src, dst, 1024 * 1024)
class RollingMerge:
"""Appends segments to the output in index order as they arrive, out of order, and unlinks them.
A cursor holds the next expected index; every `add` records one ready segment and then drains
every contiguous ready segment from the cursor onward. A segment that carries a future (per-segment
decryption) waits for that future before the append, so the output never holds raw bytes.
`append(dst, segment_file)` writes one segment; the default is a plain byte copy. A parser
whose merge needs a per-segment transform, or a head that only exists once segment 0 has
landed (ISM), passes its own.
"""
def __init__(self, dst: BinaryIO, append: Optional[Callable[[BinaryIO, Path], None]] = None) -> None:
self.dst = dst
self.append = append or (lambda dst, path: append_segment(dst, path, is_text_subtitle=False))
self.cursor = 0
self.ready: dict[int, tuple[Path, Optional[Future]]] = {}
def add(self, index: int, segment_file: Path, future: Optional[Future] = None) -> None:
# runs on the downloader's own loop, so a decrypt wait or a catch-up burst
# delays new submissions; move the drain to a writer thread if throughput measurably drops
self.ready[index] = (segment_file, future)
while self.cursor in self.ready:
path, pending = self.ready.pop(self.cursor)
if pending is not None:
pending.result()
self.append(self.dst, path)
self.cursor += 1
# the bytes are already in the output; a handle another process still holds on
# the just-replaced file (Windows) must not fail the track, the segment dir sweep
# after the download removes any leftover
try:
path.unlink()
except OSError:
pass
@property
def merged(self) -> int:
return self.cursor
@contextmanager
def licensing(ctx: DownloadContext) -> Iterator[None]:
"""Show FAILED and cancel the pending track downloads when the body raises."""
try:
yield
except Exception:
DOWNLOAD_CANCELLED.set()
ctx.progress(downloaded="[red]FAILED")
raise
def license_drm(drm: DRM_T, ctx: DownloadContext, **kwargs: Any) -> None:
"""Call ctx.license_widevine for one DRM, with the LICENSING and LICENSED progress around it."""
if not ctx.license_widevine:
raise ValueError("license_widevine func must be supplied to use DRM")
ctx.progress(downloaded="LICENSING")
ctx.license_widevine(drm, **kwargs)
ctx.progress(downloaded="[yellow]LICENSED")
def fetch_segments(
track: AnyTrack,
ctx: DownloadContext,
session: AnySession,
label: str,
urls: list[dict[str, Any]],
output_dir: Path,
filename: str,
*,
rolling: bool = False,
init: Optional[bytes] = None,
append: Optional[Callable[[BinaryIO, Path], None]] = None,
decrypter: Optional[SegmentDecrypter] = None,
) -> tuple[Optional[RollingMerge], Optional[bytes]]:
"""Download the segment requests and return the rolling merge, if any, and the init that heads the output.
With `rolling`, the init (or the decrypter's decrypted init) and each segment go into ctx.save_path
as they land. A decrypter gets every segment before its SEGMENT_DOWNLOADED event. Any failure closes
the decrypter and removes a rolling output. The returned init is the decrypter's decrypted init, else `init`.
"""
merger: Optional[RollingMerge] = None
try:
with ExitStack() as stack:
if rolling:
output = stack.enter_context(open(ctx.save_path, "wb"))
head = decrypter.init_bytes() if decrypter else init
if head:
output.write(head)
merger = RollingMerge(output, append)
# an exception raised in this body (a decrypt failure re-raised by the merge)
# must close the generator now, so its finally aborts the workers
stream = stack.enter_context(
closing(
track.downloader(
urls=urls,
output_dir=output_dir,
filename=filename,
headers=session.headers,
cookies=session.cookies,
proxy=ctx.proxy,
max_workers=ctx.max_workers,
session=session,
adaptive=ctx.adaptive_workers,
processes=ctx.download_processes,
)
)
)
for status_update in stream:
file_downloaded = status_update.get("file_downloaded")
if file_downloaded:
future = decrypter.submit(file_downloaded) if decrypter else None
# listeners get the segment while it still exists; the merge unlinks it
events.emit(events.Types.SEGMENT_DOWNLOADED, track=track, segment=file_downloaded)
if merger:
merger.add(int(file_downloaded.stem), file_downloaded, future)
else:
downloaded = status_update.get("downloaded")
if downloaded and downloaded.endswith("/s"):
status_update["downloaded"] = f"{label} {downloaded}"
ctx.progress(**status_update)
head_init = decrypter.finish() if decrypter else init
except BaseException:
if decrypter:
decrypter.close()
if merger:
ctx.save_path.unlink(missing_ok=True)
raise
return merger, head_init
def check_merged(merger: RollingMerge, total: int, track: AnyTrack, ctx: DownloadContext, label: str) -> None:
"""Remove the output and raise FileNotFoundError when the rolling merge appended fewer than total segments."""
if merger.merged == total:
return
error_msg = f"Rolling merge appended {merger.merged} of {total} segments: {ctx.save_dir}"
log_event(
f"manifest_{label.lower()}_rolling_merge_incomplete",
level="ERROR",
message=error_msg,
context={
"track_id": getattr(track, "id", None),
"track_type": track.__class__.__name__,
"save_dir": str(ctx.save_dir),
"merged": merger.merged,
"total_segments": total,
"downloader": "requests",
},
)
ctx.save_path.unlink(missing_ok=True)
raise FileNotFoundError(error_msg)
def decrypt_output(track: AnyTrack, ctx: DownloadContext, drm: DRM_T, decrypt: bool = True) -> None:
"""Decrypt ctx.save_path through decrypt_track, check every fragment, and emit TRACK_DECRYPTED.
`decrypt=False` means a SegmentDecrypter already decrypted the segments, so only the check runs.
"""
ctx.progress(downloaded="Decrypting", completed=0, total=None)
decrypt_track(drm, ctx.save_path, ctx.license_widevine, decrypt=decrypt)
assert_fragments_decrypted(ctx.save_path)
track.drm = None
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=None)
def remove_segment_dir(save_dir: Path) -> None:
"""Remove the segment directory, also when a superseded hedge download still dropped a .!dev file in it."""
if save_dir.exists() and save_dir.name.endswith("_segments"):
try:
save_dir.rmdir()
except OSError:
shutil.rmtree(save_dir, ignore_errors=True)
def complete_track(track: AnyTrack, ctx: DownloadContext, drm: Optional[DRM_T], decrypt: bool = True) -> None:
"""Hand the merged file to the track: TRACK_DOWNLOADED, then the decryption, then the segment directory cleanup."""
track.path = ctx.save_path
events.emit(events.Types.TRACK_DOWNLOADED, track=track)
if drm:
decrypt_output(track, ctx, drm, decrypt)
ctx.progress(downloaded="Decrypted", completed=100, total=100)
remove_segment_dir(ctx.save_dir)
resume.clear_sidecar(ctx.save_dir)
ctx.progress(downloaded="Downloaded")
__all__ = (
"RollingMerge",
"append_segment",
"check_merged",
"complete_track",
"decrypt_output",
"fetch_segments",
"license_drm",
"licensing",
"remove_segment_dir",
)
+25 -31
View File
@@ -662,7 +662,7 @@ class Track:
held: list[DRM_T] = list(self.drm or [])
if not init_data or any(type(d) not in (Widevine, PlayReady) for d in held):
return
for system in (PlayReady, Widevine) if self.prefers_playready(cdm) else (Widevine, PlayReady):
for system in self.pssh_order(cdm):
if any(type(d) is system for d in held):
continue
try:
@@ -684,6 +684,26 @@ class Track:
return DRM_PREFERENCE_TYPES[self._drm_preference] is PlayReady
return is_playready_cdm(cdm)
def pssh_order(self, cdm: Optional[object]) -> tuple[Union[type[Widevine], type[PlayReady]], ...]:
"""Widevine and PlayReady, in the order to look for their PSSH."""
return (PlayReady, Widevine) if self.prefers_playready(cdm) else (Widevine, PlayReady)
def drm_from_pssh(
self,
cdm: Optional[object],
read: Callable[[Union[type[Widevine], type[PlayReady]]], DRM_T],
log: logging.Logger,
) -> None:
"""Set drm to the first DRM that `read` finds a PSSH for, in pssh_order."""
systems = self.pssh_order(cdm)
for system in systems:
try:
self.drm = [read(system)]
return
except system.Exceptions.PSSHNotFound:
continue
log.debug(f"No {systems[0].__name__} or {systems[1].__name__} PSSH was found for this track, is it DRM free?")
def download(
self,
session: AnySession,
@@ -806,41 +826,15 @@ class Track:
):
self.add_init_drm(self.get_init_segment(session=session), cdm)
elif not self.drm and track_type in ("Video", "Audio"):
if self.prefers_playready(cdm):
try:
self.drm = [PlayReady.from_track(self, session)]
except PlayReady.Exceptions.PSSHNotFound:
try:
self.drm = [Widevine.from_track(self, session)]
except Widevine.Exceptions.PSSHNotFound:
log.debug("No PlayReady or Widevine PSSH was found for this track, is it DRM free?")
else:
try:
self.drm = [Widevine.from_track(self, session)]
except Widevine.Exceptions.PSSHNotFound:
try:
self.drm = [PlayReady.from_track(self, session)]
except PlayReady.Exceptions.PSSHNotFound:
log.debug("No Widevine or PlayReady PSSH was found for this track, is it DRM free?")
self.drm_from_pssh(cdm, lambda system: system.from_track(self, session), log)
if self.drm:
drm = self.get_drm_for_cdm(cdm)
track_kid = None if isinstance(drm, BlowfishStripe) else self.get_key_id(session=session)
if isinstance(drm, Widevine):
if isinstance(drm, (Widevine, PlayReady, ClearKeyCENC)):
if not prepare_drm:
raise ValueError("prepare_drm func must be supplied to use Widevine DRM")
progress(downloaded="LICENSING")
prepare_drm(drm, track_kid=track_kid)
progress(downloaded="[yellow]LICENSED")
elif isinstance(drm, PlayReady):
if not prepare_drm:
raise ValueError("prepare_drm func must be supplied to use PlayReady DRM")
progress(downloaded="LICENSING")
prepare_drm(drm, track_kid=track_kid)
progress(downloaded="[yellow]LICENSED")
elif isinstance(drm, ClearKeyCENC):
if not prepare_drm:
raise ValueError("prepare_drm func must be supplied to use ClearKey DRM")
system = type(drm).__name__.removesuffix("CENC")
raise ValueError(f"prepare_drm func must be supplied to use {system} DRM")
progress(downloaded="LICENSING")
prepare_drm(drm, track_kid=track_kid)
progress(downloaded="[yellow]LICENSED")