forked from kenzuya/unshackle
feat(drm): bridge a FairPlay-only HLS track only for a service with get_fairplay_bridge_license
This commit is contained in:
@@ -2339,6 +2339,7 @@ class dl:
|
||||
progress=progress_callables[i],
|
||||
on_segments=disk_check.add_segments if disk_check else None,
|
||||
sample_decrypter=service.sample_decrypter(track),
|
||||
fairplay_bridge=service.fairplay_bridge() is not None,
|
||||
)
|
||||
# DRM-free and HLS-ClearKey tracks never reach prepare_drm, so export here.
|
||||
# drm=None on purpose: licensed tracks already recorded their DRM/keys
|
||||
|
||||
@@ -86,6 +86,7 @@ from unshackle.core.remote_protocol import (
|
||||
from unshackle.core.run_plan import SESSION_DL_KEYS, PlanError, served_plan
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.session import RnetSession, utf8_text
|
||||
from unshackle.core.title_source import service_licence
|
||||
from unshackle.core.titles import Episode, Song
|
||||
from unshackle.core.tunnel import (
|
||||
HEARTBEAT,
|
||||
@@ -3187,6 +3188,7 @@ async def session_tracks_handler(
|
||||
sample_decrypt_tracks=[
|
||||
str(t.id) for t in [*tracks.videos, *tracks.audio] if service_instance.decrypts_samples(t)
|
||||
],
|
||||
fairplay_bridge=service_instance.fairplay_bridge() is not None,
|
||||
)
|
||||
|
||||
reply = await asyncio.to_thread(
|
||||
@@ -3600,16 +3602,13 @@ def handle_proxy_license(
|
||||
if drm_type == "widevine":
|
||||
from pywidevine.pssh import PSSH
|
||||
|
||||
licence, challenge = service.get_widevine_license, challenge_bytes
|
||||
challenge = challenge_bytes
|
||||
relayed = {"pssh": PSSH(pssh_b64)} if pssh_b64 else {}
|
||||
else:
|
||||
licence, challenge = service.get_playready_license, challenge_bytes.decode("utf-8", errors="replace")
|
||||
challenge = challenge_bytes.decode("utf-8", errors="replace")
|
||||
relayed = {"pssh_b64": pssh_b64} if pssh_b64 else {}
|
||||
license_blob = call_licence(
|
||||
lambda **kw: licence(**declared_kwargs(licence, {"title": title, "track": track, **kw})),
|
||||
challenge,
|
||||
**relayed,
|
||||
)
|
||||
licence = partial(service_licence, service, drm_type, title=title, track=track)
|
||||
license_blob = call_licence(licence, challenge, **relayed)
|
||||
except APIError:
|
||||
raise
|
||||
except (Exception, SystemExit) as exc:
|
||||
@@ -3811,7 +3810,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
|
||||
pssh_b64 = data.get("pssh")
|
||||
if pssh_b64 or mode == "server_cdm":
|
||||
ensure_track_drm(track, getattr(service, "session", None))
|
||||
ensure_track_drm(track, getattr(service, "session", None), bridge=service.fairplay_bridge() is not None)
|
||||
|
||||
if mode == "server_cdm":
|
||||
# The server's config.cdm mapping decides the DRM system, as in the batch path.
|
||||
@@ -3853,6 +3852,11 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
server_keys.note_served_keys(session, keys, key_sources)
|
||||
return web.json_response(LicenseReply(keys=keys, vault_keys=list(key_sources), drm_type=server_drm_type))
|
||||
|
||||
if pssh_b64 and not track.drm and service.fairplay_bridge():
|
||||
raise APIError(
|
||||
APIErrorCode.DRM_ERROR,
|
||||
f"The server read no key ID of track {track_log_label(track)} for the FairPlay bridge",
|
||||
)
|
||||
if pssh_b64:
|
||||
try:
|
||||
server_keys.require_track_pssh(track, pssh_b64, drm_type)
|
||||
@@ -3951,7 +3955,7 @@ async def session_keys_handler(data: TrackKeys, session_id: str, request: web.Re
|
||||
def named_kids() -> set[str]:
|
||||
track = session.tracks.get(track_id) if isinstance(track_id, str) else None
|
||||
if track is not None:
|
||||
ensure_track_drm(track, getattr(service, "session", None))
|
||||
ensure_track_drm(track, getattr(service, "session", None), bridge=service.fairplay_bridge() is not None)
|
||||
return {kid.hex for t in list(session.tracks.values()) for drm in t.drm or [] for kid in real_kids(drm)}
|
||||
|
||||
def store(named: set[str]) -> tuple[Any, dict[Any, str]]:
|
||||
|
||||
@@ -438,6 +438,7 @@ def service_details(tag: str) -> dict[str, Any]:
|
||||
service_data["has_drm"] = (
|
||||
getattr(service_module, "get_widevine_license", None) is not _BaseService.get_widevine_license
|
||||
or getattr(service_module, "get_playready_license", None) is not _BaseService.get_playready_license
|
||||
or hasattr(service_module, "get_fairplay_bridge_license")
|
||||
)
|
||||
|
||||
# Prefer the service's explicit AUTH_METHODS; otherwise infer from authenticate().
|
||||
|
||||
@@ -6,6 +6,7 @@ import logging
|
||||
import uuid
|
||||
from collections.abc import Callable, Iterable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from functools import partial
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple
|
||||
|
||||
from unshackle.core.api import licence_cap
|
||||
@@ -19,7 +20,7 @@ from unshackle.core.cdm.loader import device_system
|
||||
from unshackle.core.drm import WHOLE_FILE_DRM, is_null_key, whole_file_cipher
|
||||
from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.utilities import declared_kwargs
|
||||
from unshackle.core.title_source import service_licence
|
||||
from unshackle.core.utils.redact import redact_all
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -399,6 +400,7 @@ def handle_single_server_cdm(
|
||||
return vault_keys
|
||||
raise refusal or APIError(APIErrorCode.NO_CONTENT, "The server vault holds no content key for this track")
|
||||
|
||||
licence = partial(service_licence, service, drm_type, title=title, track=track)
|
||||
if drm_type == "playready":
|
||||
from unshackle.core.drm import PlayReady
|
||||
|
||||
@@ -424,9 +426,7 @@ def handle_single_server_cdm(
|
||||
track,
|
||||
cdm=cdm,
|
||||
certificate=lambda challenge, **_: None,
|
||||
licence=lambda **kw: service.get_playready_license(
|
||||
**declared_kwargs(service.get_playready_license, {**kw, "title": title, "track": track})
|
||||
),
|
||||
licence=licence,
|
||||
)
|
||||
elif drm_type == "widevine":
|
||||
from pywidevine.pssh import PSSH as WvPSSH
|
||||
@@ -455,9 +455,7 @@ def handle_single_server_cdm(
|
||||
certificate=lambda challenge, **_: service.get_widevine_service_certificate(
|
||||
challenge=challenge, title=title, track=track
|
||||
),
|
||||
licence=lambda **kw: service.get_widevine_license(
|
||||
**declared_kwargs(service.get_widevine_license, {**kw, "title": title, "track": track})
|
||||
),
|
||||
licence=licence,
|
||||
)
|
||||
else:
|
||||
raise APIError(
|
||||
@@ -641,7 +639,7 @@ def resolve_batch(session: Any, track_ids: Iterable[str], drm_type: str, policy:
|
||||
|
||||
svc_session = getattr(service, "session", None)
|
||||
init_data = fetch_init_segment(track, svc_session)
|
||||
ensure_track_drm(track, svc_session, init_data)
|
||||
ensure_track_drm(track, svc_session, init_data, bridge=service.fairplay_bridge() is not None)
|
||||
cipher = whole_file_cipher(track)
|
||||
if cipher is not None:
|
||||
if not session.licensing.vault_only:
|
||||
|
||||
@@ -210,6 +210,8 @@ class CencDrm:
|
||||
Exceptions: Any
|
||||
content_keys: dict[UUID, str]
|
||||
_kid: UUID | None
|
||||
bridged = False
|
||||
"""A stub ``HLS.bridge_stub`` built for a FairPlay-only track: its challenge goes to the FairPlay bridge hook."""
|
||||
|
||||
@classmethod
|
||||
def from_pssh_box(cls, box: Container, kid: UUID | None) -> Self:
|
||||
|
||||
@@ -87,10 +87,11 @@ def drm_from_init_segment(track: Any, session: Any = None, init_data: bytes | No
|
||||
return drms
|
||||
|
||||
|
||||
def ensure_track_drm(track: Any, session: Any = None, init_data: bytes | None = None) -> None:
|
||||
def ensure_track_drm(track: Any, session: Any = None, init_data: bytes | None = None, bridge: bool = False) -> 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.
|
||||
With ``bridge`` (the service has a FairPlay bridge hook) a FairPlay-only HLS track gets the bridged stubs.
|
||||
"""
|
||||
if track.drm:
|
||||
return
|
||||
@@ -109,7 +110,7 @@ def ensure_track_drm(track: Any, session: Any = None, init_data: bytes | None =
|
||||
|
||||
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, bridge=True):
|
||||
if track.load_drm_from_playlist(session, bridge=bridge):
|
||||
return
|
||||
except Exception as e:
|
||||
log.debug(f"HLS DRM prefetch failed for {track.id}: {e!r}")
|
||||
|
||||
@@ -37,10 +37,10 @@ from unshackle.core.drm import (
|
||||
real_kids,
|
||||
verify,
|
||||
)
|
||||
from unshackle.core.title_source import TitleSource
|
||||
from unshackle.core.title_source import TitleSource, service_licence
|
||||
from unshackle.core.titles import Title_T
|
||||
from unshackle.core.tracks import Video
|
||||
from unshackle.core.utilities import declared_kwargs, log_event
|
||||
from unshackle.core.utilities import log_event
|
||||
from unshackle.core.utils.redact import redact_secrets
|
||||
from unshackle.core.utils.subprocess import ffmpeg_decodes
|
||||
from unshackle.core.vaults import KeySource, Vaults
|
||||
@@ -708,18 +708,14 @@ class ContentKeyResolver:
|
||||
tree.add(label)
|
||||
|
||||
def _service_licence(self, drm_system: str | None = None, **kwargs: Any) -> Any:
|
||||
"""Call the service's licence function for the track's DRM system.
|
||||
|
||||
Arguments go through declared_kwargs, so a service receives only the ones its own
|
||||
licence function declares.
|
||||
"""Call the service's licence function, or its FairPlay bridge hook, for the track's DRM system (``service_licence``).
|
||||
|
||||
_prepare_drm passes drm_system so the choice follows the track, not the loaded CDM:
|
||||
a track downloading at the same time can swap self.cdms.cdm.
|
||||
"""
|
||||
if drm_system is None:
|
||||
drm_system = cdm_system(self.cdms.cdm) or "widevine"
|
||||
fn = self.service.get_playready_license if drm_system == "playready" else self.service.get_widevine_license
|
||||
return fn(**declared_kwargs(fn, kwargs))
|
||||
return service_licence(self.service, drm_system, **kwargs)
|
||||
|
||||
def _licence_one_drm(self, prepare: Callable, drm: Widevine | PlayReady, track_kid: UUID | None) -> None:
|
||||
"""Send one challenge for the KIDs of this DRM, also when the DRM or a vault has the content keys.
|
||||
|
||||
@@ -28,6 +28,7 @@ from pywidevine.pssh import PSSH as WV_PSSH
|
||||
from requests import Session
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.cdm.choice import drm_system
|
||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_widevine_cdm
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
@@ -713,7 +714,11 @@ class HLS:
|
||||
session_drm = track.get_drm_for_cdm(cdm) if track.drm else None
|
||||
bridge_drm = None
|
||||
bridge_kids: list[UUID] = []
|
||||
if session_drm is None and (system := cdm_system(cdm)):
|
||||
if (
|
||||
session_drm is None
|
||||
and ctx.fairplay_bridge
|
||||
and (system := drm_system(track.drm_preference) or cdm_system(cdm))
|
||||
):
|
||||
bridge_kids = HLS.get_bridge_kids(master, wanted_segments, track, session)
|
||||
bridge_drm = HLS.bridge_stub(system, bridge_kids) if bridge_kids else None
|
||||
if bridge_drm:
|
||||
@@ -1602,14 +1607,16 @@ class HLS:
|
||||
|
||||
@staticmethod
|
||||
def bridge_stub(system: str, kids: list[UUID]) -> Widevine | PlayReady:
|
||||
"""The `drm_stub` of `system` for `kids`: one Widevine header that names each, or a PlayReady header for each.
|
||||
"""The `drm_stub` of `system` for `kids`, marked bridged: one Widevine header for all, or a PlayReady header each.
|
||||
|
||||
A PlayReady stub header holds one KID, so one that named several would license only the first content key.
|
||||
"""
|
||||
if system != "playready":
|
||||
return drm_stub(system, [kid.hex for kid in kids])
|
||||
drm, *others = (cast(PlayReady, drm_stub(system, [kid.hex])) for kid in kids)
|
||||
drm.absorb(*others)
|
||||
drm = drm_stub(system, [kid.hex for kid in kids])
|
||||
else:
|
||||
drm, *others = (cast(PlayReady, drm_stub(system, [kid.hex])) for kid in kids)
|
||||
drm.absorb(*others)
|
||||
drm.bridged = True
|
||||
return drm
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -278,6 +278,7 @@ class TracksReply(TypedDict, total=False):
|
||||
server_cdm: bool | None
|
||||
server_cdm_type: str
|
||||
sample_decrypt_tracks: list[str]
|
||||
fairplay_bridge: bool
|
||||
|
||||
|
||||
class SegmentsRequest(TypedDict):
|
||||
|
||||
@@ -835,6 +835,8 @@ class RemoteService(TitleSource):
|
||||
"""The server's answer to who licenses this remote session; an older server gives it in the tracks reply."""
|
||||
_server_cdm_request: bool | None = None
|
||||
"""This client's own server CDM choice; None leaves it to the server."""
|
||||
_fairplay_bridge = False
|
||||
"""The last tracks reply said the service on the server has the FairPlay bridge hook."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -1451,6 +1453,7 @@ class RemoteService(TitleSource):
|
||||
self.report_local_fallback()
|
||||
self.server_cdm_type = session_fields.get("server_cdm_type", "widevine")
|
||||
self._sample_decrypt_tracks.update(session_fields.get("sample_decrypt_tracks") or [])
|
||||
self._fairplay_bridge = bool(session_fields.get("fairplay_bridge"))
|
||||
|
||||
for track in [*tracks.videos, *tracks.audio, *tracks.subtitles]:
|
||||
if track.descriptor == Track.Descriptor.HLS:
|
||||
@@ -1743,6 +1746,22 @@ class RemoteService(TitleSource):
|
||||
) -> bytes | str | None:
|
||||
return self.proxy_license(challenge, track, "playready", pssh_b64)
|
||||
|
||||
def fairplay_bridge(self) -> Callable[..., Any] | None:
|
||||
"""The relay of the FairPlay bridge, when the tracks reply says the service on the server has the hook."""
|
||||
return self.relay_fairplay_bridge if self._fairplay_bridge else None
|
||||
|
||||
def relay_fairplay_bridge(
|
||||
self,
|
||||
*,
|
||||
challenge: bytes,
|
||||
track: AnyTrack,
|
||||
drm_system: str,
|
||||
pssh: PSSH | None = None,
|
||||
pssh_b64: str | None = None,
|
||||
) -> bytes | str | None:
|
||||
"""Relay a bridged challenge with the PSSH of its header; the server sends it to the hook of its service."""
|
||||
return self.proxy_license(challenge, track, drm_system, pssh.dumps() if pssh else pssh_b64)
|
||||
|
||||
def get_widevine_service_certificate(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -223,6 +223,14 @@ class TitleSource(metaclass=ABCMeta):
|
||||
"""
|
||||
return None
|
||||
|
||||
def fairplay_bridge(self) -> Callable[..., Any] | None:
|
||||
"""The service's ``get_fairplay_bridge_license``, or None: only a service with it gets FairPlay-only tracks bridged.
|
||||
|
||||
The hook gets a PlayReady or Widevine challenge for the key IDs of the init segments, with ``challenge``,
|
||||
``title``, ``track``, ``drm_system`` and the extras of that system's licence callback.
|
||||
"""
|
||||
return getattr(self, "get_fairplay_bridge_license", None)
|
||||
|
||||
@abstractmethod
|
||||
def get_titles(self) -> Titles_T:
|
||||
"""The titles of the title ID."""
|
||||
@@ -312,4 +320,16 @@ class TitleSource(metaclass=ABCMeta):
|
||||
"""
|
||||
|
||||
|
||||
__all__ = ("CacheIdentity", "KeyArrival", "ServerKeySource", "TitleSource")
|
||||
def service_licence(source: TitleSource, drm_system: str, **kwargs: Any) -> Any:
|
||||
"""Call the licence callback of ``source`` for a ``drm_system`` challenge, with the ``kwargs`` it declares.
|
||||
|
||||
A track with a bridged stub goes to ``source.fairplay_bridge()`` with ``drm_system``; any other track goes to
|
||||
``get_playready_license`` or ``get_widevine_license``.
|
||||
"""
|
||||
bridged = any(getattr(drm, "bridged", False) for drm in getattr(kwargs.get("track"), "drm", None) or [])
|
||||
hook = source.fairplay_bridge() if bridged else None
|
||||
fn = hook or (source.get_playready_license if drm_system == "playready" else source.get_widevine_license)
|
||||
return fn(**declared_kwargs(fn, {**kwargs, "drm_system": drm_system} if hook else kwargs))
|
||||
|
||||
|
||||
__all__ = ("CacheIdentity", "KeyArrival", "ServerKeySource", "TitleSource", "service_licence")
|
||||
|
||||
@@ -247,6 +247,7 @@ class Subtitle(Track):
|
||||
download_processes: int = 1,
|
||||
on_segments: Callable[[Track, list[Any]], None] | None = None,
|
||||
sample_decrypter: Callable[[int], bytes | SampleDecrypter] | None = None,
|
||||
fairplay_bridge: bool = False,
|
||||
) -> None:
|
||||
super().download(
|
||||
session,
|
||||
@@ -260,6 +261,7 @@ class Subtitle(Track):
|
||||
download_processes=download_processes,
|
||||
on_segments=on_segments,
|
||||
sample_decrypter=sample_decrypter,
|
||||
fairplay_bridge=fairplay_bridge,
|
||||
)
|
||||
if not self.path:
|
||||
return
|
||||
|
||||
@@ -403,6 +403,8 @@ class DownloadContext:
|
||||
"""Called by the HLS step with a track and its wanted media segments, before they download."""
|
||||
sample_decrypter: Callable[[int], bytes | SampleDecrypter] | None = None
|
||||
"""The service's key or `cbcs.SampleDecrypter` for a 1-based `stsd` entry, for a track it decrypts itself."""
|
||||
fairplay_bridge: bool = False
|
||||
"""The service has a FairPlay bridge hook, so the HLS step may license a FairPlay-only track as PlayReady or Widevine."""
|
||||
|
||||
def ensure_session(self) -> AnySession:
|
||||
"""Return the HTTP session, or a new ``Session`` if none was set."""
|
||||
@@ -732,12 +734,13 @@ class Track:
|
||||
download_processes: int = 1,
|
||||
on_segments: Callable[["Track", list[Any]], None] | None = None,
|
||||
sample_decrypter: Callable[[int], bytes | SampleDecrypter] | None = None,
|
||||
fairplay_bridge: bool = False,
|
||||
) -> None:
|
||||
"""Download and optionally Decrypt this Track, then emit TRACK_DOWNLOADED.
|
||||
|
||||
For a URL-descriptor Video or Audio track with no `drm` set, unshackle probes the DRM from the
|
||||
track's init data and stores it on the track, so a service need not declare `drm` itself.
|
||||
`sample_decrypter` decrypts a track the service decrypts itself (see DownloadContext).
|
||||
`sample_decrypter` and `fairplay_bridge` go on the DownloadContext.
|
||||
"""
|
||||
from unshackle.core.manifests import DASH, HLS, ISM, url
|
||||
from unshackle.core.manifests.segment_pipeline import licensing
|
||||
@@ -814,6 +817,7 @@ class Track:
|
||||
cdm=cdm,
|
||||
on_segments=on_segments,
|
||||
sample_decrypter=sample_decrypter,
|
||||
fairplay_bridge=fairplay_bridge,
|
||||
)
|
||||
if self.descriptor in manifest_parsers:
|
||||
manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx)
|
||||
|
||||
@@ -65,6 +65,7 @@ class EXAMPLE(Service):
|
||||
get_widevine_* service certificate + license (per-segment PSSH through `track`)
|
||||
get_playready_license PlayReady challenge POST
|
||||
get_clearkey_license DASH org.w3.clearkey JWK Set POST (Laurl fallback)
|
||||
get_fairplay_bridge_license commented out: FairPlay-only HLS tracks, opt-in only
|
||||
"""
|
||||
|
||||
# ALIASES: extra CLI tags that resolve to this service (e.g. `dl EX ...`).
|
||||
@@ -523,6 +524,18 @@ class EXAMPLE(Service):
|
||||
response.raise_for_status()
|
||||
return response.content
|
||||
|
||||
# unshackle has no FairPlay CDM and never sends a FairPlay challenge. For a FairPlay-only track it can send a
|
||||
# PlayReady or Widevine challenge for the KIDs of the init segments to the licence server of the platform, which
|
||||
# works only when that server issues the same content key to PlayReady or Widevine. Defining this method opts the
|
||||
# service in; a server that does not issue the content key refuses the challenge and can flag the device, so
|
||||
# enable it only after a licence-only run (`--cdm-only --skip-dl`) proves the route.
|
||||
#
|
||||
# def get_fairplay_bridge_license(
|
||||
# self, *, challenge: bytes, title: Title_T, track: AnyTrack, drm_system: str
|
||||
# ) -> bytes | str | None:
|
||||
# licence = self.get_playready_license if drm_system == "playready" else self.get_widevine_license
|
||||
# return licence(challenge=challenge, title=title, track=track)
|
||||
|
||||
def get_clearkey_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | dict | None:
|
||||
# DASH org.w3.clearkey: `challenge` is the W3C JSON license request; return the
|
||||
# JWK Set response. Omit this method entirely when the manifest carries a Laurl:
|
||||
|
||||
Reference in New Issue
Block a user