diff --git a/tests/core/test_cenc.py b/tests/core/test_cenc.py index 655747b2..6e75afc1 100644 --- a/tests/core/test_cenc.py +++ b/tests/core/test_cenc.py @@ -184,6 +184,50 @@ def test_load_drm_from_playlist_takes_the_init_kid_when_the_tag_and_pssh_have_no assert [drm.kids for drm in track.drm] == [[TRACK_KID]] +def kid_pssh(kid: UUID) -> str: + return str(PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[kid]).dumps()) + + +def test_load_drm_from_playlist_reads_the_session_keys_and_skips_a_bad_key() -> None: + bad = KEY_LINE.format(pssh="AAAA") + session = KEY_LINE.format(pssh=kid_pssh(TRACK_KID)).replace("#EXT-X-KEY", "#EXT-X-SESSION-KEY") + track = playlist_track(f"#EXTM3U\n{session}\n{bad}\n#EXTINF:6.0,\na.m4s\n#EXT-X-ENDLIST\n") + + assert track.load_drm_from_playlist() is True + assert track.drm is not None + assert [drm.kids for drm in track.drm] == [[TRACK_KID]] + assert track.needs_drm_loading is False + + +def test_load_drm_from_playlist_keeps_every_key_once() -> None: + line = KEY_LINE.format(pssh=kid_pssh(TRACK_KID)) + other = KEY_LINE.format(pssh=kid_pssh(OTHER_KID)) + iso = f'#EXT-X-KEY:METHOD=ISO-23001-7,URI="data:text/plain;base64,{base64.b64encode(OTHER_KID.bytes).decode()}"' + session = line.replace("#EXT-X-KEY", "#EXT-X-SESSION-KEY") + track = playlist_track( + f"#EXTM3U\n{session}\n{line}\n#EXTINF:6.0,\na.m4s\n{other}\n#EXTINF:6.0,\nb.m4s\n{iso}\n#EXTINF:6.0,\nc.m4s\n" + ) + + assert track.load_drm_from_playlist() is True + assert track.drm is not None + assert [drm.kids for drm in track.drm] == [[TRACK_KID], [OTHER_KID], [OTHER_KID]] + + +def test_load_drm_from_playlist_raises_when_every_key_fails() -> None: + track = playlist_track(f"#EXTM3U\n{KEY_LINE.format(pssh='AAAA')}\n#EXTINF:6.0,\na.m4s\n#EXT-X-ENDLIST\n") + + with pytest.raises(ValueError, match="Failed to load DRM from playlist"): + track.load_drm_from_playlist() + + +def test_load_drm_from_playlist_uses_the_given_session_when_the_track_has_none() -> None: + track = playlist_track(f"#EXTM3U\n{KEY_LINE.format(pssh=kid_pssh(TRACK_KID))}\n#EXTINF:6.0,\na.m4s\n") + given, track.session = track.session, None + + assert track.load_drm_from_playlist(given) is True + assert track.drm is not None + + def test_from_track_reads_the_playlist_pssh_and_the_init_kid() -> None: pssh_b64 = base64.b64encode(playready_box(OTHER_KID)).decode() line = ( diff --git a/tests/remote/unit/test_ensure_track_drm_hls_descriptor.py b/tests/remote/unit/test_ensure_track_drm_hls_descriptor.py index 927c111a..b4dc3ee5 100644 --- a/tests/remote/unit/test_ensure_track_drm_hls_descriptor.py +++ b/tests/remote/unit/test_ensure_track_drm_hls_descriptor.py @@ -14,9 +14,9 @@ import pytest from pywidevine.pssh import PSSH as WvPSSH from tests.core.test_hls_kid_from_init import NO_KID_PSSH -from unshackle.core.api import handlers from unshackle.core.drm import Widevine -from unshackle.core.tracks import Track +from unshackle.core.drm.discovery import ensure_track_drm, track_pssh +from unshackle.core.tracks import Track, Video pytestmark = pytest.mark.unit @@ -40,32 +40,45 @@ def _media_playlist(pssh: str | None = None) -> str: ) +def hls_track() -> Video: + track = Video.__new__(Video) + track.id = "vid" + track.url = "https://cdn.example.invalid/media.m3u8" + track.descriptor = Track.Descriptor.HLS + track.data = {} + track.drm = None + track.session = None + return track + + def test_hls_descriptor_alone_reaches_the_media_playlist_keys(): session = SimpleNamespace(get=lambda url: SimpleNamespace(text=_media_playlist())) - track = SimpleNamespace( - id="vid", url="https://cdn.example.invalid/media.m3u8", descriptor=Track.Descriptor.HLS, data={}, drm=None - ) + track = hls_track() - handlers.ensure_track_drm(track, session) + ensure_track_drm(track, session) assert track.drm and isinstance(track.drm[0], Widevine), "media playlist DRM not read" assert track.drm[0].kids == [KID] - assert base64.b64decode(handlers.extract_pssh_from_track(track, "widevine")) + assert base64.b64decode(track_pssh(track, "widevine")) def test_key_without_a_kid_takes_it_from_the_init_segment(): """A PSSH that holds a content id and no Key ID is DRM, and the server must not call the track clear.""" response = SimpleNamespace(text=_media_playlist(NO_KID_PSSH), ok=True, content=b"init") session = SimpleNamespace(get=lambda url, headers=None: response) - track = SimpleNamespace( - id="vid", - url="https://cdn.example.invalid/media.m3u8", - descriptor=Track.Descriptor.HLS, - data={}, - drm=None, - get_key_id=lambda init: KID, - ) + track = hls_track() + track.get_key_id = lambda init: KID # type: ignore[method-assign] - handlers.ensure_track_drm(track, session) + ensure_track_drm(track, session) assert track.drm and track.drm[0].kids == [KID] + + +def test_a_playlist_whose_keys_all_fail_leaves_the_track_without_drm(): + """The server logs and goes on where dl raises.""" + session = SimpleNamespace(get=lambda url: SimpleNamespace(text=_media_playlist("AAAA"))) + track = hls_track() + + ensure_track_drm(track, session) + + assert not track.drm diff --git a/tests/remote/unit/test_extract_pssh_strict.py b/tests/remote/unit/test_extract_pssh_strict.py index 46862685..feee28e5 100644 --- a/tests/remote/unit/test_extract_pssh_strict.py +++ b/tests/remote/unit/test_extract_pssh_strict.py @@ -1,4 +1,4 @@ -"""extract_pssh_from_track must answer for the requested DRM system only. +"""track_pssh must answer for the requested DRM system only. A loose match made the batch candidate loop a no-op: the first candidate always won, so the loop licensed a PlayReady-only track as Widevine by accident. A Widevine device can still @@ -12,13 +12,14 @@ import pytest from tests.remote.sessions import session_entry from unshackle.core.api import handlers +from unshackle.core.drm.discovery import track_pssh pytestmark = pytest.mark.unit class _WV: def __init__(self, b64): - self._pssh = SimpleNamespace(dumps=lambda: b64) + self.pssh = SimpleNamespace(dumps=lambda: b64) _WV.__name__ = "Widevine" @@ -26,7 +27,7 @@ _WV.__name__ = "Widevine" class _PR: def __init__(self, b64): - self.data = {"pssh_b64": b64} + self.pssh_b64 = b64 _PR.__name__ = "PlayReady" @@ -34,13 +35,25 @@ _PR.__name__ = "PlayReady" def test_extractor_is_type_strict(): track = SimpleNamespace(drm=[_PR("pr")]) - assert handlers.extract_pssh_from_track(track, "playready") == "pr" - assert handlers.extract_pssh_from_track(track, "widevine") is None + assert track_pssh(track, "playready") == "pr" + assert track_pssh(track, "widevine") is None track = SimpleNamespace(drm=[_WV("wv"), _PR("pr")]) - assert handlers.extract_pssh_from_track(track, "widevine") == "wv" - assert handlers.extract_pssh_from_track(track, "playready") == "pr" - assert handlers.extract_pssh_from_track(SimpleNamespace(drm=None), "widevine") is None + assert track_pssh(track, "widevine") == "wv" + assert track_pssh(track, "playready") == "pr" + assert track_pssh(SimpleNamespace(drm=None), "widevine") is None + + +def test_a_playready_header_without_a_pssh_is_skipped(): + track = SimpleNamespace(drm=[_PR(None), _PR("pr")]) + assert track_pssh(track, "playready") == "pr" + assert track_pssh(SimpleNamespace(drm=[_PR(None)]), "playready") is None + + +def test_the_given_drm_goes_before_the_track_drm(): + track = SimpleNamespace(drm=[_WV("track")]) + assert track_pssh(track, "widevine", _WV("given")) == "given" + assert track_pssh(track, "widevine", _PR("pr")) == "track" async def _run_batch(monkeypatch, tracks, cdm_type, calls): diff --git a/tests/remote/unit/test_remote_service_server_cdm_license.py b/tests/remote/unit/test_remote_service_server_cdm_license.py index 679476ec..5cb62968 100644 --- a/tests/remote/unit/test_remote_service_server_cdm_license.py +++ b/tests/remote/unit/test_remote_service_server_cdm_license.py @@ -20,7 +20,7 @@ KID = UUID("161219ec3df64e0eadbb3827c0ccc46d") class _PlayReady: def __init__(self): - self.data = {"pssh_b64": "PR"} + self.pssh_b64 = "PR" self.content_keys: dict = {} diff --git a/tests/remote/unit/test_server_cdm_absorb_routes.py b/tests/remote/unit/test_server_cdm_absorb_routes.py index 7493ec05..4b441b13 100644 --- a/tests/remote/unit/test_server_cdm_absorb_routes.py +++ b/tests/remote/unit/test_server_cdm_absorb_routes.py @@ -138,7 +138,7 @@ async def test_no_pssh_tells_the_client_why(env, monkeypatch): monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "playready") monkeypatch.setattr(handlers, "drm_preference_name", lambda track: None) monkeypatch.setattr(handlers, "fetch_init_segment", lambda track, sess: None) - monkeypatch.setattr(handlers, "extract_pssh_from_track", lambda track, drm: None) + monkeypatch.setattr(handlers, "track_pssh", lambda track, drm: None) await handlers.session_license_handler( {"mode": "server_cdm", "track_ids": ["vid"], "drm_type": "playready"}, "sess", None diff --git a/tests/remote/unit/test_server_cdm_absorbs_headers.py b/tests/remote/unit/test_server_cdm_absorbs_headers.py index 1e71f15b..33f95719 100644 --- a/tests/remote/unit/test_server_cdm_absorbs_headers.py +++ b/tests/remote/unit/test_server_cdm_absorbs_headers.py @@ -1,7 +1,7 @@ """The server CDM must license every WRM header a track carries, not only the first. A track can hold one `PlayReady` object per header: `ISM` shares a Protection list, `HLS` -emits one per `EXT-X-KEY`. `extract_pssh_from_track` returns the first PSSH only, so the +emits one per `EXT-X-KEY`. `track_pssh` returns the first PSSH only, so the server folds in the siblings. Without that it returns fewer content keys than a local CDM. """ diff --git a/tests/remote/unit/test_server_cdm_key_verification.py b/tests/remote/unit/test_server_cdm_key_verification.py index 4fc99725..1343d217 100644 --- a/tests/remote/unit/test_server_cdm_key_verification.py +++ b/tests/remote/unit/test_server_cdm_key_verification.py @@ -103,7 +103,7 @@ async def test_server_does_not_flag_a_pair_its_cdm_licensed(session): class _WV: def __init__(self, b64, kids): - self._pssh = SimpleNamespace(dumps=lambda: b64) + self.pssh = SimpleNamespace(dumps=lambda: b64) self.kids = kids diff --git a/tests/remote/unit/test_server_cdm_max_height.py b/tests/remote/unit/test_server_cdm_max_height.py index d89a027f..d979ae27 100644 --- a/tests/remote/unit/test_server_cdm_max_height.py +++ b/tests/remote/unit/test_server_cdm_max_height.py @@ -354,7 +354,7 @@ CAP_DETAILS = {"reason": "server_cdm_max_height", "max_height": 1080} class _PSSHDrm: def __init__(self, b64, kids): - self._pssh = SimpleNamespace(dumps=lambda: b64) + self.pssh = SimpleNamespace(dumps=lambda: b64) self.kids = kids diff --git a/tests/remote/unit/test_server_cdm_multikey.py b/tests/remote/unit/test_server_cdm_multikey.py index 63e5f4ea..6a74bbe3 100644 --- a/tests/remote/unit/test_server_cdm_multikey.py +++ b/tests/remote/unit/test_server_cdm_multikey.py @@ -147,7 +147,7 @@ async def test_batch_shares_full_bundle_per_pssh(monkeypatch): monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "playready") monkeypatch.setattr(handlers, "resolve_device_name", lambda *a, **k: "dev") monkeypatch.setattr(handlers, "drm_preference_name", lambda track: None) - monkeypatch.setattr(handlers, "extract_pssh_from_track", lambda track, drm: track_pssh[track.id]) + monkeypatch.setattr(handlers, "track_pssh", lambda track, drm: track_pssh[track.id]) monkeypatch.setattr(handlers, "handle_single_server_cdm", fake_single) monkeypatch.setattr(handlers.config, "serve", {"users": {}}, raising=False) diff --git a/tests/remote/unit/test_server_cdm_type_override.py b/tests/remote/unit/test_server_cdm_type_override.py index 231bf7af..a1e76c0b 100644 --- a/tests/remote/unit/test_server_cdm_type_override.py +++ b/tests/remote/unit/test_server_cdm_type_override.py @@ -57,7 +57,7 @@ class _FakePlayReady: self.content_keys = {KID: "key_pr"} -# extract_pssh_from_track matches on class name, so name the fakes after the DRM classes +# track_pssh matches on class name, so name the fakes after the DRM classes _FakePlayReady.__name__ = "PlayReady" _FakeWidevine.__name__ = "Widevine" diff --git a/tests/test_client_session_auth.py b/tests/test_client_session_auth.py index c8e0ad3b..d707382a 100644 --- a/tests/test_client_session_auth.py +++ b/tests/test_client_session_auth.py @@ -246,7 +246,7 @@ def test_server_login_strips_nested_and_unlisted_secrets(): def test_track_own_pssh_passes_without_kids(monkeypatch): from unshackle.core.api import handlers - monkeypatch.setattr(handlers, "extract_pssh_from_track", lambda track, drm_type: "OWN") + monkeypatch.setattr(handlers, "track_pssh", lambda track, drm_type: "OWN") monkeypatch.setattr(handlers, "pssh_kids", lambda pssh, drm_type: set()) handlers.require_track_pssh(SimpleNamespace(id="t", drm=[]), "OWN", "widevine") with pytest.raises(APIError): diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index 579159ca..fd6a7047 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -50,6 +50,7 @@ from unshackle.core.dl_options import ( forwarded_dl_params, ) from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids +from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh from unshackle.core.launch import served_context from unshackle.core.manifests.snapshot import capture from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy @@ -94,7 +95,6 @@ from unshackle.core.utils.hdr10plus import probed_tracks from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text from unshackle.core.utils.service_params import FLAT_DL_KEYS, cast_service_options, service_options from unshackle.core.wire import ( - descriptor_name, serialize_attachment, serialize_drm, serialize_title, @@ -3626,134 +3626,6 @@ def find_title_for_track(track_id: str, session: Any) -> Any: return None -def extract_pssh_from_track(track: Any, drm_type: str) -> str | None: - """The base64 PSSH of the track's DRM object for `drm_type`; None when the track has none of that system.""" - for drm_obj in track.drm or []: - drm_class = drm_obj.__class__.__name__ - if drm_type == "widevine" and drm_class == "Widevine": - pssh = getattr(drm_obj, "_pssh", None) - if pssh and hasattr(pssh, "dumps"): - return pssh.dumps() - elif drm_type == "playready" and drm_class == "PlayReady": - pssh_b64 = getattr(drm_obj, "data", {}).get("pssh_b64") - if pssh_b64: - return pssh_b64 - return None - - -def fetch_init_segment(track: Any, session: Any = None) -> bytes | None: - """The init segment of a DASH track, or the head of a one-file track with DRM; None otherwise, or when the fetch fails.""" - from unshackle.core.manifests import DASH as DASHManifest - - session = getattr(track, "session", None) or session - if session is None: - return None - - dash = (getattr(track, "data", None) or {}).get("dash") or {} - if not all(dash.get(k) is not None for k in ("period", "adaptation_set", "representation", "manifest")): - if getattr(track, "descriptor", None) is not Video.Descriptor.URL or not getattr(track, "drm", None): - return None - try: - return track.get_init_segment(session=session) - except Exception as e: - log.debug(f"Init segment fetch failed for {track.id}: {e!r}") - return None - - try: - return DASHManifest.get_period_segments( - period=dash["period"], - adaptation_set=dash["adaptation_set"], - representation=dash["representation"], - manifest=dash["manifest"], - track=track, - track_url=track.url, - session=session, - )[0] - except Exception as e: - log.warning(f"Init segment fetch failed for {track.id}: {e!r}") - return None - - -def drm_from_init_segment(track: Any, session: Any = None, init_data: bytes | None = None) -> list: - """Read the DRM headers out of a DASH track's init segment. - - Some manifests carry no ContentProtection PSSH; the real header reaches the player only - in the init segment, so the server must read it there too. - """ - from unshackle.core.drm import PlayReady, Widevine - - if init_data is None: - init_data = fetch_init_segment(track, session) - if not init_data: - return [] - - drms = [] - for drm_cls in (Widevine, PlayReady): - try: - drms.append(drm_cls.from_init_data(init_data)) - except Exception as e: - log.debug(f"No usable {drm_cls.__name__} PSSH in the init segment of {track.id}: {e!r}") - return drms - - -def ensure_track_drm(track: Any, session: Any = None, init_data: bytes | None = None) -> None: - """Extract DRM from manifest data if track has none. - - Supports DASH (ContentProtection elements, then the init segment), HLS - (EXT-X-KEY from playlist fetch), and ISM (ProtectionHeader elements). - """ - if track.drm: - return - - if track.data.get("dash"): - from unshackle.core.manifests import DASH as DASHManifest - - rep = track.data["dash"].get("representation") - ada = track.data["dash"].get("adaptation_set") - if rep is not None and ada is not None: - track.drm = DASHManifest.get_drm(rep.findall("ContentProtection") + ada.findall("ContentProtection")) - if track.drm: - return - - track.drm = drm_from_init_segment(track, session, init_data) or None - if track.drm: - return - - if (track.data.get("hls") or descriptor_name(track) == "HLS") and track.url: - try: - import m3u8 - - from unshackle.core.drm import PlayReady, Widevine - from unshackle.core.manifests import HLS - - http = getattr(track, "session", None) or session - playlist = m3u8.loads(utf8_text(http.get(track.url)), uri=track.url) if http else m3u8.load(track.url) - keys = [k for k in (playlist.keys or []) + (playlist.session_keys or []) if k is not None] - for key in keys: - try: - drm = HLS.get_drm_or_probe(key, playlist, track, probe_session=http) - if isinstance(drm, (Widevine, PlayReady)): - track.drm = [drm] - return - # EXT-X-KEY data is third-party input; skip keys we cannot turn into a DRM object - except Exception as e: - log.debug(f"Skipping HLS key {key}: {e!r}") - continue - except Exception as e: - log.debug(f"HLS DRM prefetch failed for {track.id}: {e!r}") - - if track.data.get("ism"): - try: - from unshackle.core.manifests import ISM as ISMManifest - - manifest = track.data["ism"].get("manifest") - if manifest is not None: - track.drm = ISMManifest.get_drm(manifest.xpath(".//ProtectionHeader")) - # a swallowed error here means the track silently gets no DRM, so it must be loud - except Exception as e: - log.warning(f"ISM DRM extraction failed for {track.id}: {e!r}") - - def resolve_device_name(policy: KeyPolicy, drm_type: str, service_tag: str = "") -> str: """Get the CDM device name, checking the service's cdm mapping first. @@ -3828,9 +3700,9 @@ def pick_server_pssh(track: Any, candidates: list[str]) -> tuple[str, str] | Non Widevine DRM class converts the PlayReady PSSH on construction. """ for candidate in candidates: - pssh_str = extract_pssh_from_track(track, candidate) + pssh_str = track_pssh(track, candidate) if not pssh_str and candidate == "widevine": - pssh_str = extract_pssh_from_track(track, "playready") + pssh_str = track_pssh(track, "playready") if pssh_str: log.info( f"Track {track_log_label(track)} has only a PlayReady PSSH, licensing it with the Widevine device" @@ -3986,7 +3858,7 @@ def require_track_pssh(track: Any, pssh_b64: str, drm_type: str) -> None: unchecked PSSH would make the key vault answer with content keys for any title. The track's own PSSH passes as it is, so a header without KIDs still licenses. """ - if pssh_b64 == extract_pssh_from_track(track, drm_type): + if pssh_b64 == track_pssh(track, drm_type): return try: client_kids = pssh_kids(pssh_b64, drm_type) @@ -4034,7 +3906,7 @@ def handle_single_server_cdm( service_name = service.__class__.__name__ if not pssh_b64: - pssh_b64 = extract_pssh_from_track(track, drm_type) + pssh_b64 = track_pssh(track, drm_type) if not pssh_b64: raise APIError(APIErrorCode.INVALID_INPUT, "No PSSH available for server_cdm licensing") diff --git a/unshackle/core/drm/cenc.py b/unshackle/core/drm/cenc.py index 6c57e055..5e56a17a 100644 --- a/unshackle/core/drm/cenc.py +++ b/unshackle/core/drm/cenc.py @@ -51,6 +51,11 @@ def key_system(key: Any) -> UUID | None: return KEYFORMATS.get((getattr(key, "keyformat", None) or "").lower()) +def cenc_key(key: Any) -> bool: + """True when an EXT-X-KEY gives a CENC DRM: METHOD ISO-23001-7, or a Widevine or PlayReady KEYFORMAT.""" + return bool(key) and (key.method == "ISO-23001-7" or key_system(key) is not None) + + def key_data(key: Any) -> str: """The base64 PSSH at the end of an EXT-X-KEY data URI.""" return str(key.uri.split(",")[-1]) diff --git a/unshackle/core/drm/discovery.py b/unshackle/core/drm/discovery.py new file mode 100644 index 00000000..e97ad995 --- /dev/null +++ b/unshackle/core/drm/discovery.py @@ -0,0 +1,115 @@ +"""Find a track's DRM headers without a licence: from its manifest data, its playlist or its init segment.""" + +from __future__ import annotations + +import logging +from typing import Any + +from unshackle.core.drm.playready import PlayReady +from unshackle.core.drm.widevine import Widevine +from unshackle.core.manifests import DASH, ISM +from unshackle.core.tracks import Track + +log = logging.getLogger(__name__) + + +def track_pssh(track: Any, drm_type: str, drm: Any = None) -> str | None: + """The base64 PSSH of one DRM system's header: ``drm``'s own when it is of that system, else the track's first. + + None when no header of that system has a PSSH. + """ + for drm_obj in [drm, *(getattr(track, "drm", None) or [])]: + drm_class = drm_obj.__class__.__name__ + if drm_type == "widevine" and drm_class == "Widevine": + return str(drm_obj.pssh.dumps()) + if drm_type == "playready" and drm_class == "PlayReady" and drm_obj.pssh_b64: + return str(drm_obj.pssh_b64) + return None + + +def fetch_init_segment(track: Any, session: Any = None) -> bytes | None: + """The init segment of a DASH track, or the head of a one-file track with DRM; None otherwise, or when the fetch fails.""" + session = getattr(track, "session", None) or session + if session is None: + return None + + dash = (getattr(track, "data", None) or {}).get("dash") or {} + if not all(dash.get(k) is not None for k in ("period", "adaptation_set", "representation", "manifest")): + if getattr(track, "descriptor", None) is not Track.Descriptor.URL or not getattr(track, "drm", None): + return None + try: + return track.get_init_segment(session=session) + except Exception as e: + log.debug(f"Init segment fetch failed for {track.id}: {e!r}") + return None + + try: + return DASH.get_period_segments( + period=dash["period"], + adaptation_set=dash["adaptation_set"], + representation=dash["representation"], + manifest=dash["manifest"], + track=track, + track_url=track.url, + session=session, + )[0] + except Exception as e: + log.warning(f"Init segment fetch failed for {track.id}: {e!r}") + return None + + +def drm_from_init_segment(track: Any, session: Any = None, init_data: bytes | None = None) -> list: + """Read the DRM headers out of a DASH track's init segment. + + Some manifests carry no ContentProtection PSSH; the real header reaches the player only + in the init segment. + """ + if init_data is None: + init_data = fetch_init_segment(track, session) + if not init_data: + return [] + + drms = [] + for drm_cls in (Widevine, PlayReady): + try: + drms.append(drm_cls.from_init_data(init_data)) + except Exception as e: + log.debug(f"No usable {drm_cls.__name__} PSSH in the init segment of {track.id}: {e!r}") + return drms + + +def ensure_track_drm(track: Any, session: Any = None, init_data: bytes | None = None) -> None: + """Fill ``track.drm`` from the manifest when the track has none; a failure leaves it empty and never raises. + + Reads DASH ContentProtection and then the init segment, the HLS playlist keys, or the ISM ProtectionHeader. + """ + if track.drm: + return + + if track.data.get("dash"): + rep = track.data["dash"].get("representation") + ada = track.data["dash"].get("adaptation_set") + if rep is not None and ada is not None: + track.drm = DASH.get_drm(rep.findall("ContentProtection") + ada.findall("ContentProtection")) + if track.drm: + return + + track.drm = drm_from_init_segment(track, session, init_data) or None + if track.drm: + return + + if (track.data.get("hls") or getattr(track, "descriptor", None) is Track.Descriptor.HLS) and track.url: + try: + if track.load_drm_from_playlist(session): + return + except Exception as e: + log.debug(f"HLS DRM prefetch failed for {track.id}: {e!r}") + + if track.data.get("ism"): + try: + manifest = track.data["ism"].get("manifest") + if manifest is not None: + track.drm = ISM.get_drm(manifest.xpath(".//ProtectionHeader")) + # a swallowed error here means the track silently gets no DRM, so it must be loud + except Exception as e: + log.warning(f"ISM DRM extraction failed for {track.id}: {e!r}") diff --git a/unshackle/core/import_service.py b/unshackle/core/import_service.py index 60f89681..f465d4cc 100644 --- a/unshackle/core/import_service.py +++ b/unshackle/core/import_service.py @@ -19,6 +19,7 @@ from unshackle.core.constants import AnyTrack from unshackle.core.credential import Credential from unshackle.core.drm import ClearKey, MonaLisa, real_kids from unshackle.core.drm.cenc import drm_stub +from unshackle.core.drm.discovery import drm_from_init_segment from unshackle.core.manifests import DASH, HLS, ISM, MissingLanguageError, snapshot from unshackle.core.remote_protocol import APIErrorCode, coded from unshackle.core.remote_service import resolve_proxy_arg, segment_uri_filter @@ -795,8 +796,6 @@ class ImportService(TitleSource): if kid and kid.int: kids.add(kid) return kids - from unshackle.core.api.handlers import drm_from_init_segment - init_drm = drm_from_init_segment(track, session) if init_drm: return {kid for drm in init_drm for kid in real_kids(drm)} diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py index 34d75153..87a066eb 100644 --- a/unshackle/core/manifests/hls.py +++ b/unshackle/core/manifests/hls.py @@ -32,7 +32,7 @@ from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm, is_widevi from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, PlayReady, Widevine -from unshackle.core.drm.cenc import PLAYREADY_ID, WIDEVINE_ID, hls_key_drm, key_data, key_system +from unshackle.core.drm.cenc import PLAYREADY_ID, WIDEVINE_ID, cenc_key, hls_key_drm, key_data, key_system from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use from unshackle.core.drm.verify import decrypt_track from unshackle.core.events import events @@ -1336,7 +1336,7 @@ class HLS: keyformat=item.get("keyformat"), keyformatversions=",".join(item.get("keyformatversion") or item.get("keyformatversions") or []), ) - if key.method in {"AES-128", "ISO-23001-7"} or key_system(key): + if key.method == "AES-128" or cenc_key(key): keys.append(key) return keys @@ -1454,9 +1454,7 @@ class HLS: # TODO: Add support for 'SAMPLE-AES', 'AES-CTR', 'AES-CBC', 'ClearKey' elif key.method == "AES-128": return key - elif key.method == "ISO-23001-7": - return key - elif key_system(key): + elif cenc_key(key): return key else: unsupported_systems.append(key.method + (f" ({key.keyformat})" if key.keyformat else "")) diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index 6c90d19b..d37d8301 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -46,6 +46,7 @@ from unshackle.core.credential import Credential from unshackle.core.dl_options import remote_dl_params from unshackle.core.drm import cbcs, real_kids from unshackle.core.drm.cenc import drm_stub +from unshackle.core.drm.discovery import track_pssh from unshackle.core.launch import launch_keys from unshackle.core.manifests.snapshot import match_track, restore from unshackle.core.proxies.resolve import is_loopback @@ -412,17 +413,6 @@ def sample_batches(samples: list[bytes]) -> Iterator[list[bytes]]: yield batch -def track_pssh(track: Any, drm_type: str, drm: Any = None) -> str | None: - """The base64 PSSH of one DRM system's header: ``drm``'s own when it is of that system, else the track's first.""" - for drm_obj in [drm, *(track.drm or [])]: - drm_class = drm_obj.__class__.__name__ - if drm_type == "playready" and drm_class == "PlayReady": - return drm_obj.data["pssh_b64"] - if drm_type == "widevine" and drm_class == "Widevine": - return drm_obj.pssh.dumps() - return None - - def apply_service_track_data(tracks: Tracks, data: dict[str, Any]) -> None: """Overlay the service-set ``track.data`` the server sent. diff --git a/unshackle/core/tracks/track.py b/unshackle/core/tracks/track.py index af9a5d1f..593efd49 100644 --- a/unshackle/core/tracks/track.py +++ b/unshackle/core/tracks/track.py @@ -28,7 +28,7 @@ from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled from unshackle.core.downloaders.requests import requests from unshackle.core.drm import DRM_T, BlowfishStripe, PlayReady, Widevine -from unshackle.core.drm.cenc import init_kid, key_system +from unshackle.core.drm.cenc import cenc_key, init_kid from unshackle.core.drm.verify import ( children, decrypt_track, @@ -1087,38 +1087,43 @@ class Track: return self.load_drm_from_playlist() - def load_drm_from_playlist(self) -> bool: - """ - Fallback method to load DRM by fetching this track's individual playlist. + def load_drm_from_playlist(self, session: Any = None) -> bool: + """Load the Widevine and PlayReady DRM of the EXT-X-KEY and EXT-X-SESSION-KEY tags of this track's playlist. + + It skips a tag that gives no DRM, and raises ValueError when the fetch fails or when every such tag fails. """ if self.drm: self.needs_drm_loading = False return True + import m3u8 + + from unshackle.core.manifests.hls import HLS + + session = self.session or session or run_proxy.fallback_session() try: - import m3u8 - - from unshackle.core.manifests.hls import HLS - - session = getattr(self, "session", None) or run_proxy.fallback_session() assert isinstance(self.url, str) - - response = session.get(self.url) - playlist = m3u8.loads(utf8_text(response), self.url) - - drm_list: list[DRM_T] = [ - HLS.get_drm_or_probe(key, playlist, self, probe_session=session) - for key in playlist.keys or [] - if key_system(key) - ] - if drm_list: - self.drm = drm_list - self.needs_drm_loading = False - return True - + playlist = m3u8.loads(utf8_text(session.get(self.url)), self.url) except Exception as e: raise ValueError(f"Failed to load DRM from playlist for track {self.id}: {e}") # noqa: B904 + drm_list: list[DRM_T] = [] + error: Exception | None = None + keys = playlist.keys or [] + for key in [*keys, *(k for k in playlist.session_keys or [] if k not in keys)]: + if not cenc_key(key): + continue + try: + drm_list.append(HLS.get_drm_or_probe(key, playlist, self, probe_session=session)) + except Exception as e: + logging.getLogger("track").debug(f"Skipping HLS key {key} of track {self.id}: {e!r}") + error = e + if drm_list: + self.drm = drm_list + self.needs_drm_loading = False + return True + if error: + raise ValueError(f"Failed to load DRM from playlist for track {self.id}: {error}") return False def get_init_segment(