feat(hls): license a FairPlay-only SAMPLE-AES playlist through a PlayReady or Widevine CDM

This commit is contained in:
imSp4rky
2026-11-30 19:36:01 -07:00
parent c41d8ec3cf
commit b826eccb86
9 changed files with 449 additions and 98 deletions
+83 -14
View File
@@ -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: