refactor(drm): move track drm discovery into core and merge the drifted pssh and hls playlist readers

This commit is contained in:
imSp4rky
2026-11-26 13:40:06 -07:00
parent 136e9fc84d
commit 3c90346ae4
18 changed files with 260 additions and 206 deletions
+5 -133
View File
@@ -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")
+5
View File
@@ -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])
+115
View File
@@ -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}")
+1 -2
View File
@@ -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)}
+3 -5
View File
@@ -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 ""))
+1 -11
View File
@@ -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.
+28 -23
View File
@@ -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(