feat(dl): add --all-drm to license Widevine and PlayReady per track

Each DRM system sends one challenge per KID set in a run, also when a vault has the content keys. Needs a CDM for each system in the cdm config.
This commit is contained in:
imSp4rky
2026-10-05 15:22:01 -06:00
parent b530d96e9f
commit ee38477b11
15 changed files with 563 additions and 18 deletions
+2
View File
@@ -464,6 +464,7 @@ def perform_download(
"proxy_download": params.get("proxy_download"),
"profile": params.get("profile"),
"cdm_name": params.get("cdm"),
"all_drm": params.get("all_drm", False),
"repack": params.get("repack", False),
"tag": params.get("tag"),
"tmdb_id": params.get("tmdb_id"),
@@ -618,6 +619,7 @@ def perform_download(
list_=False,
list_titles=False,
skip_dl=params.get("skip_dl", False),
all_drm=params.get("all_drm", False),
export=params.get("export"),
cdm_only=params.get("cdm_only"),
no_proxy=params.get("no_proxy", False),
+6
View File
@@ -80,6 +80,7 @@ DEFAULT_DOWNLOAD_PARAMS = {
"slow": None,
"split_audio": None,
"skip_dl": False,
"all_drm": False,
"export": False,
"cdm_only": None,
"proxy": None,
@@ -1834,6 +1835,11 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
return "output_dir must be a path under the server's downloads directory."
data["output_dir"] = str(target)
if data.get("all_drm") and data.get("cdm_only") is False:
return "all_drm sends licence requests, so it cannot be used with cdm_only set to false."
if data.get("all_drm") and data.get("cdm"):
return "all_drm needs a CDM for each DRM system, so it cannot be used with cdm, which selects one device."
if "vcodec" in data and data["vcodec"]:
err = check_codec(data["vcodec"], VALID_VCODECS, "vcodec")
if err:
+3
View File
@@ -947,6 +947,9 @@ async def download(request: web.Request) -> web.Response:
skip_dl:
type: boolean
description: Skip downloading, only retrieve decryption keys (default - false)
all_drm:
type: boolean
description: License each track with both Widevine and PlayReady. Needs a CDM for each DRM system and cannot be used with `cdm` or with `cdm_only` set to false (default - false)
export:
type: boolean
description: Export manifest, DRM init data, keys, and track info to a JSON file in the exports directory (default - false)
+1
View File
@@ -3,6 +3,7 @@ from typing import TypeVar, Union
DOWNLOAD_CANCELLED = Event()
DOWNLOAD_LICENCE_ONLY = Event()
DOWNLOAD_ALL_DRM = Event()
class DownloadCancelled(Exception):
+9 -2
View File
@@ -27,7 +27,7 @@ from requests import Session
from unshackle.core import binaries
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
from unshackle.core.drm.verify import decrypt_track
@@ -395,8 +395,13 @@ class DASH:
track.drm = manifest_drm
else:
track.drm = existing_drm
if DOWNLOAD_ALL_DRM.is_set():
track.drm = [
*existing_drm,
*(d for d in manifest_drm if not any(type(d) is type(e) for e in existing_drm)),
]
if track.drm and track.drm_preference:
if track.drm and track.drm_preference and not DOWNLOAD_ALL_DRM.is_set():
wanted = DRM_PREFERENCE_TYPES[track.drm_preference]
preferred = [drm_obj for drm_obj in track.drm if isinstance(drm_obj, wanted)]
if preferred:
@@ -478,6 +483,8 @@ class DASH:
if not track.drm and init_data and isinstance(track, (Video, Audio)) and not binaries.FFProbe:
log.warning("FFprobe was not found, so the init segment was not probed for a PSSH.")
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:
+24 -2
View File
@@ -28,9 +28,9 @@ from pywidevine.pssh import PSSH as WV_PSSH
from requests import Session
from unshackle.core import binaries
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
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_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.drm import DRM_T, ClearKey, MonaLisa, PlayReady, Widevine
from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
from unshackle.core.drm.verify import decrypt_track
@@ -697,6 +697,8 @@ class HLS:
if hasattr(existing_drm, "content_keys") and existing_drm.content_keys:
media_drm.content_keys.update(existing_drm.content_keys)
track.drm = [media_drm]
if DOWNLOAD_ALL_DRM.is_set():
track.drm += HLS.alternate_drm(media_keys, media_drm, session)
try:
if not license_widevine:
raise ValueError("license_widevine func must be supplied to use DRM")
@@ -1435,6 +1437,26 @@ class HLS:
return [k for k in keys if k.keyformat and k.keyformat.lower() in playready_keyformats]
return keys
@staticmethod
def alternate_drm(
keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]],
chosen: DRM_T,
session: Optional[Union[Session, RnetSession]] = None,
) -> list[DRM_T]:
"""Build the Widevine or PlayReady DRM that the EXT-X-KEY entries offer next to ``chosen``.
Only an entry with the KEYFORMAT of the other DRM system counts, so unshackle requests no URI.
"""
system = "widevine" if isinstance(chosen, PlayReady) else "playready"
other_keys = [k for k in HLS.filter_keys_for_cdm(keys, cdm_type_stub(system)) if k.method != "NONE"]
if not other_keys:
return []
try:
return [HLS.get_drm(other_keys[0], session)]
except Exception as e:
logging.getLogger("HLS").warning(f"Could not read the {system} EXT-X-KEY entry: {e}")
return []
@staticmethod
def get_track_kid_from_init(
master: M3U8,
+33 -2
View File
@@ -21,7 +21,7 @@ from requests.adapters import HTTPAdapter, Retry
from unshackle.core import binaries
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled
from unshackle.core.downloaders import requests
from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
from unshackle.core.drm.verify import decrypt_track
@@ -563,6 +563,31 @@ class Track:
)
self._drm_preference = value.lower()
def add_init_drm(self, init_data: Optional[bytes], cdm: Optional[object]) -> None:
"""Add the Widevine and PlayReady DRM that the init segment carries and the track does not have.
A track with a different DRM type stays as it is. The DRM system that agrees with the CDM comes first.
"""
log = logging.getLogger("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):
if any(type(d) is system for d in held):
continue
try:
held.append(system.from_init_data(init_data))
except (PlayReady.Exceptions.PSSHNotFound, Widevine.Exceptions.PSSHNotFound):
continue
except Exception as e:
if not held:
raise
log.debug(f"Could not read the {system.__name__} PSSH of the init segment: {e}")
if held:
self.drm = held
else:
log.debug("No PlayReady or Widevine PSSH was found for this track, is it DRM free?")
def prefers_playready(self, cdm: Optional[object]) -> bool:
"""Whether to try PlayReady before Widevine. The track's preference wins over the loaded CDM."""
if self._drm_preference:
@@ -665,7 +690,13 @@ class Track:
manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx)
elif self.descriptor == self.Descriptor.URL:
try:
if not self.drm and track_type in ("Video", "Audio"):
if (
DOWNLOAD_ALL_DRM.is_set()
and track_type in ("Video", "Audio")
and not {Widevine, PlayReady} <= {type(d) for d in self.drm or []}
):
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)]