forked from kenzuya/unshackle
feat(hls): license a FairPlay-only SAMPLE-AES playlist through a PlayReady or Widevine CDM
This commit is contained in:
@@ -101,6 +101,26 @@ def init_kid(init_data: bytes) -> UUID | None:
|
||||
return None
|
||||
|
||||
|
||||
def init_pssh_kid(init_data: bytes) -> UUID | None:
|
||||
"""The one real KID that every pssh box of an init segment with a tenc names, or None for none or several."""
|
||||
from unshackle.core.drm.playready import PlayReady
|
||||
from unshackle.core.drm.widevine import Widevine
|
||||
|
||||
if not any(get_boxes(init_data, b"tenc")):
|
||||
return None
|
||||
drm_classes: dict[UUID, type[CencDrm]] = {WIDEVINE_ID: Widevine, PLAYREADY_ID: PlayReady}
|
||||
kids: set[UUID] = set()
|
||||
for box in get_boxes(init_data, b"pssh"):
|
||||
kids.update(box.key_IDs or [])
|
||||
if drm_class := drm_classes.get(box.system_ID):
|
||||
try:
|
||||
kids.update(drm_class.from_pssh_box(box, None).kids)
|
||||
except drm_class.Exceptions.KIDNotFound:
|
||||
continue
|
||||
kids -= PLACEHOLDER_KIDS
|
||||
return kids.pop() if len(kids) == 1 else None
|
||||
|
||||
|
||||
def hls_key_drm(key: Any, kid: UUID | None = None) -> Widevine | PlayReady | None:
|
||||
"""The Widevine or PlayReady DRM of an EXT-X-KEY, or None for another KEYFORMAT.
|
||||
|
||||
|
||||
@@ -109,7 +109,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):
|
||||
if track.load_drm_from_playlist(session, bridge=True):
|
||||
return
|
||||
except Exception as e:
|
||||
log.debug(f"HLS DRM prefetch failed for {track.id}: {e!r}")
|
||||
|
||||
@@ -12,7 +12,7 @@ import time
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
from functools import partial
|
||||
from itertools import accumulate
|
||||
from itertools import accumulate, pairwise
|
||||
from pathlib import Path
|
||||
from typing import Any, BinaryIO, cast
|
||||
from urllib.parse import urljoin, urlparse
|
||||
@@ -28,11 +28,21 @@ from pywidevine.pssh import PSSH as WV_PSSH
|
||||
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.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
|
||||
from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, PlayReady, Widevine
|
||||
from unshackle.core.drm.cenc import PLAYREADY_ID, WIDEVINE_ID, cenc_key, hls_key_drm, key_data, key_system
|
||||
from unshackle.core.drm.cenc import (
|
||||
PLACEHOLDER_KIDS,
|
||||
PLAYREADY_ID,
|
||||
WIDEVINE_ID,
|
||||
cenc_key,
|
||||
drm_stub,
|
||||
hls_key_drm,
|
||||
init_pssh_kid,
|
||||
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
|
||||
@@ -711,10 +721,18 @@ class HLS:
|
||||
|
||||
# Get session DRM as fallback but prefer media playlist keys for accurate KID matching
|
||||
session_drm = track.get_drm_for_cdm(cdm) if track.drm else None
|
||||
if not isinstance(session_drm, (Widevine, PlayReady)):
|
||||
for segment in wanted_segments:
|
||||
if segment.keys:
|
||||
HLS.resolve_segment_key(segment.keys, cdm, track.drm_preference)
|
||||
bridge_drm = bridge_kid = None
|
||||
if session_drm is None and (system := cdm_system(cdm)):
|
||||
bridge_kid = HLS.get_bridge_kid(master, wanted_segments, track, session)
|
||||
bridge_drm = drm_stub(system, [bridge_kid.hex]) if bridge_kid else None
|
||||
if bridge_drm and bridge_kid:
|
||||
HLS.drop_unsupported_keys(master)
|
||||
session_drm = bridge_drm
|
||||
track.drm = [bridge_drm]
|
||||
log.debug(f"{track.id}: licensing key ID {bridge_kid.hex} of its init segment as {bridge_drm.NAME}")
|
||||
elif not isinstance(session_drm, (Widevine, PlayReady)):
|
||||
for keys in {id(keys): keys for _, keys in HLS.keys_in_force(master, wanted_segments)}.values():
|
||||
HLS.resolve_segment_key(keys, cdm, track.drm_preference)
|
||||
elif HLS.drop_unsupported_keys(master):
|
||||
log.debug(f"{track.id}: its key tags name key systems unshackle cannot license, using the DRM of the track")
|
||||
|
||||
@@ -753,7 +771,9 @@ class HLS:
|
||||
initial_drm_licensed = True
|
||||
|
||||
if not initial_drm_licensed:
|
||||
license_drm(track, session_drm, ctx, probe=lambda: HLS.get_track_kid_from_init(master, track, session))
|
||||
license_drm(
|
||||
track, session_drm, ctx, bridge_kid, probe=lambda: HLS.get_track_kid_from_init(master, track, session)
|
||||
)
|
||||
|
||||
if DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
# a playlist can change its key part-way, and only the download loop licenses the later keys
|
||||
@@ -770,6 +790,9 @@ class HLS:
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
return
|
||||
|
||||
if bridge_drm and bridge_kid and not bridge_drm.content_keys:
|
||||
raise bridge_drm.Exceptions.CEKNotFound(f"No content key for KID {bridge_kid.hex} of track {track.id}")
|
||||
|
||||
# Downloaded segment files are named by post-filter index; map that back to the wanted
|
||||
# segment so the IV uses the absolute media sequence number, not the download index.
|
||||
single_init = HLS.single_init_no_rotation(wanted_segments, initial_drm_key, cdm, track.drm_preference)
|
||||
@@ -1410,10 +1433,12 @@ class HLS:
|
||||
track: Track,
|
||||
session: Session | RnetSession,
|
||||
init_section: m3u8.model.InitializationSection | None = None,
|
||||
pssh: bool = False,
|
||||
) -> UUID | None:
|
||||
"""
|
||||
Extract the track's Key ID from an init segment (EXT-X-MAP), by default the first in the playlist.
|
||||
|
||||
With `pssh`, an init segment with an all-zero tenc Key ID gives the one Key ID that its pssh boxes name.
|
||||
Returns None if no init segment exists or KID extraction fails.
|
||||
The caller should fall back to drm.kid from the PSSH if this returns None.
|
||||
"""
|
||||
@@ -1430,7 +1455,10 @@ class HLS:
|
||||
headers = {}
|
||||
map_res = unrecorded(session, "get", map_uri, headers=headers)
|
||||
if map_res.ok:
|
||||
return track.get_key_id(map_res.content)
|
||||
kid = track.get_key_id(map_res.content)
|
||||
if pssh and (kid is None or kid.int == 0):
|
||||
return init_pssh_kid(map_res.content)
|
||||
return kid
|
||||
logging.getLogger("HLS").warning(
|
||||
f"Could not read the Key ID from the init segment {safe_display_url(map_uri)}: "
|
||||
f"HTTP {map_res.status_code}"
|
||||
@@ -1472,14 +1500,55 @@ class HLS:
|
||||
raise NotImplementedError(f"None of the key systems are supported: {', '.join(unsupported_systems)}")
|
||||
|
||||
@staticmethod
|
||||
def drop_unsupported_keys(manifest: M3U8) -> bool:
|
||||
"""Remove every EXT-X-KEY of `manifest` when each is sample encryption of a DRM system unshackle cannot license.
|
||||
def get_bridge_kid(
|
||||
manifest: M3U8, segments: list[Any], track: Track, session: Session | RnetSession
|
||||
) -> UUID | None:
|
||||
"""The real Key ID of the init segment of the first `segments` entry with an EXT-X-KEY unshackle cannot license.
|
||||
|
||||
Returns whether it did. The download then reads the playlist as one without an EXT-X-KEY and decrypts with the
|
||||
one Widevine or PlayReady DRM of the track. Any other METHOD, such as AES-128 or AES-256, keeps every tag.
|
||||
None when `only_unsupported_keys` is false of `manifest`, or when the init segment changes with no
|
||||
EXT-X-DISCONTINUITY: the merge splits there only on a changed EXT-X-KEY, and the tags go.
|
||||
The pssh boxes count only for one init segment in a one-key playlist: an all-zero tenc takes any content key.
|
||||
"""
|
||||
keyed = [(s, keys) for s, keys in HLS.keys_in_force(manifest, segments) if s.init_section and any(keys)]
|
||||
if not keyed or not HLS.only_unsupported_keys(manifest):
|
||||
return None
|
||||
init_section = keyed[0][0].init_section
|
||||
one_key = len({key.uri for key in manifest.keys if key}) == 1
|
||||
pssh = one_key and all(s.init_section == init_section for s, _ in keyed)
|
||||
if any(b.init_section != a.init_section and not b.discontinuity for a, b in pairwise(segments)):
|
||||
return None
|
||||
kid = HLS.get_track_kid_from_init(manifest, track, session, init_section, pssh=pssh)
|
||||
return None if kid in PLACEHOLDER_KIDS else kid
|
||||
|
||||
@staticmethod
|
||||
def keys_in_force(manifest: M3U8, segments: list[Any]) -> list[tuple[Any, list[Any]]]:
|
||||
"""Each of `segments` that has an EXT-X-KEY in force, with its tags: python-m3u8 puts them on the first one only."""
|
||||
wanted = {id(segment) for segment in segments}
|
||||
found: list[tuple[Any, list[Any]]] = []
|
||||
keys: list[Any] = []
|
||||
for segment in manifest.segments:
|
||||
keys = segment.keys or keys
|
||||
if keys and id(segment) in wanted:
|
||||
found.append((segment, keys))
|
||||
return found
|
||||
|
||||
@staticmethod
|
||||
def only_unsupported_keys(manifest: M3U8) -> bool:
|
||||
"""Whether each EXT-X-KEY of `manifest`, at least one, is sample encryption of a DRM system unshackle cannot license.
|
||||
|
||||
Any other METHOD, such as AES-128 or AES-256, makes it false.
|
||||
"""
|
||||
keys = [key for key in (manifest.keys or []) if key is not None]
|
||||
if not keys or any(key.method not in ("SAMPLE-AES", "SAMPLE-AES-CTR") or cenc_key(key) for key in keys):
|
||||
return bool(keys) and all(key.method in ("SAMPLE-AES", "SAMPLE-AES-CTR") and not cenc_key(key) for key in keys)
|
||||
|
||||
@staticmethod
|
||||
def drop_unsupported_keys(manifest: M3U8) -> bool:
|
||||
"""Remove every EXT-X-KEY of `manifest` when `only_unsupported_keys` is true of it.
|
||||
|
||||
Returns whether it did. The download then reads the playlist as one without an EXT-X-KEY and decrypts with the
|
||||
one Widevine or PlayReady DRM of the track.
|
||||
"""
|
||||
if not HLS.only_unsupported_keys(manifest):
|
||||
return False
|
||||
manifest.keys = []
|
||||
for segment in manifest.segments:
|
||||
|
||||
@@ -22,13 +22,14 @@ from requests import Session
|
||||
from requests.adapters import HTTPAdapter, Retry
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.cdm.choice import SYSTEMS
|
||||
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.downloaders.requests import requests
|
||||
from unshackle.core.drm import DRM_T, PlayReady, Widevine
|
||||
from unshackle.core.drm.cbcs import SampleDecrypter
|
||||
from unshackle.core.drm.cenc import cenc_key, init_kid
|
||||
from unshackle.core.drm.cenc import cenc_key, drm_stub, init_kid
|
||||
from unshackle.core.drm.verify import (
|
||||
children,
|
||||
find_child_box,
|
||||
@@ -993,10 +994,11 @@ class Track:
|
||||
|
||||
return self.load_drm_from_playlist()
|
||||
|
||||
def load_drm_from_playlist(self, session: Any = None) -> bool:
|
||||
def load_drm_from_playlist(self, session: Any = None, bridge: bool = False) -> 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.
|
||||
With ``bridge`` it builds both stubs for the key ID that ``HLS.get_bridge_kid`` finds when no tag gives a DRM.
|
||||
"""
|
||||
if self.drm:
|
||||
self.needs_drm_loading = False
|
||||
@@ -1024,12 +1026,18 @@ class Track:
|
||||
except Exception as e:
|
||||
logging.getLogger("track").debug(f"Skipping HLS key {key} of track {self.id}: {e!r}")
|
||||
error = e
|
||||
if error and not drm_list:
|
||||
raise ValueError(f"Failed to load DRM from playlist for track {self.id}: {error}")
|
||||
if bridge and not drm_list:
|
||||
segments = [
|
||||
s for s in playlist.segments if not (callable(self.OnSegmentFilter) and self.OnSegmentFilter(s))
|
||||
]
|
||||
if kid := HLS.get_bridge_kid(playlist, segments, self, session):
|
||||
drm_list = [drm_stub(system, [kid.hex]) for system in SYSTEMS]
|
||||
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(
|
||||
|
||||
Reference in New Issue
Block a user