fix(hls): read the key id from the init segment when the PSSH has none

An EXT-X-KEY whose Widevine PSSH holds a content id and no key id raised KIDNotFound. Covers download, licence-only, --all-drm, session keys, import and the server CDM path. Fixes #166.
This commit is contained in:
imSp4rky
2026-10-13 12:14:34 -06:00
parent b4136e1cf5
commit af4e6d5d47
6 changed files with 256 additions and 32 deletions
+65 -26
View File
@@ -706,9 +706,14 @@ class HLS:
media_playlist_key = HLS.get_supported_key(cdm_media_keys) if cdm_media_keys else None
if media_playlist_key:
media_drm = HLS.get_drm(media_playlist_key, session)
init_kid = (
None
if media_playlist_key.method == "AES-128"
else HLS.get_track_kid_from_init(master, track, session)
)
media_drm = HLS.get_drm(media_playlist_key, session, **({"kid": init_kid} if init_kid else {}))
if isinstance(media_drm, (Widevine, PlayReady)):
track_kid = HLS.get_track_kid_from_init(master, track, session) or media_drm.kid
track_kid = init_kid or media_drm.kid
# Preserve pre-existing keys (e.g. from server_cdm)
if track.drm:
for existing_drm in track.drm:
@@ -716,7 +721,7 @@ class HLS:
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)
track.drm += HLS.alternate_drm(media_keys, media_drm, session, init_kid)
try:
if not license_widevine:
raise ValueError("license_widevine func must be supplied to use DRM")
@@ -772,7 +777,7 @@ class HLS:
if key is None or key.method == "AES-128" or key in licensed_keys:
continue
licensed_keys.append(key)
later_drm = HLS.get_drm(key, session)
later_drm = HLS.get_drm_or_probe(key, master, track, session, segment.init_section)
if isinstance(later_drm, (Widevine, PlayReady)) and license_widevine:
license_widevine(later_drm, track_kid=later_drm.kid)
progress(downloaded="[yellow]SKIPPED")
@@ -1152,22 +1157,18 @@ class HLS:
if key is None:
encryption_data = None
elif not encryption_data or encryption_data[0] != key:
drm = HLS.get_drm(key, session)
if isinstance(drm, (Widevine, PlayReady)):
try:
if map_data:
track_kid = track.get_key_id(map_data[1])
else:
track_kid = None
if not track_kid:
track_kid = drm.kid
try:
init_kid = track.get_key_id(map_data[1]) if map_data and key.method != "AES-128" else None
drm = HLS.get_drm(key, session, **({"kid": init_kid} if init_kid else {}))
if isinstance(drm, (Widevine, PlayReady)):
track_kid = init_kid or drm.kid
progress(downloaded="LICENSING")
license_widevine(drm, track_kid=track_kid)
progress(downloaded="[yellow]LICENSED")
except Exception: # noqa
DOWNLOAD_CANCELLED.set() # skip pending track downloads
progress(downloaded="[red]FAILED")
raise
except Exception: # noqa
DOWNLOAD_CANCELLED.set() # skip pending track downloads
progress(downloaded="[red]FAILED")
raise
if (
encryption_data
and isinstance(drm, (Widevine, PlayReady))
@@ -1462,6 +1463,7 @@ class HLS:
keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]],
chosen: DRM_T,
session: Optional[Union[Session, RnetSession]] = None,
kid: Optional[UUID] = None,
) -> list[DRM_T]:
"""Build the Widevine or PlayReady DRM that the EXT-X-KEY entries offer next to ``chosen``.
@@ -1472,7 +1474,7 @@ class HLS:
if not other_keys:
return []
try:
return [HLS.get_drm(other_keys[0], session)]
return [HLS.get_drm(other_keys[0], session, **({"kid": kid} if kid else {}))]
except Exception as e:
logging.getLogger("HLS").warning(f"Could not read the {system} EXT-X-KEY entry: {e}")
return []
@@ -1482,14 +1484,15 @@ class HLS:
master: M3U8,
track: AnyTrack,
session: Union[Session, RnetSession],
init_section: Optional[m3u8.model.InitializationSection] = None,
) -> Optional[UUID]:
"""
Extract the track's Key ID from its init segment (EXT-X-MAP).
Extract the track's Key ID from an init segment (EXT-X-MAP), by default the first in the playlist.
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.
"""
map_section = next((seg.init_section for seg in master.segments if seg.init_section), None)
map_section = init_section or next((seg.init_section for seg in master.segments if seg.init_section), None)
if not map_section:
return None
@@ -1503,6 +1506,10 @@ class HLS:
map_res = session.get(url=map_uri, headers=headers)
if map_res.ok:
return track.get_key_id(map_res.content)
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}"
)
# best-effort key-id probe over network + init parse; caller falls back without it
except Exception as e:
logging.getLogger("HLS").debug(f"Init map key-id probe failed for {map_uri}: {e!r}")
@@ -1550,6 +1557,7 @@ class HLS:
def get_drm(
key: Union[m3u8.model.SessionKey, m3u8.model.Key],
session: Optional[Union[Session, RnetSession]] = None,
kid: Optional[UUID] = None,
) -> DRM_T:
"""
Convert HLS EXT-X-KEY data to an initialized DRM object.
@@ -1558,6 +1566,8 @@ class HLS:
key: The m3u8 `EXT-X-KEY` object.
session: Optional HTTP session used to request AES-128 URIs.
Useful to set headers, proxies, cookies, and so forth.
kid: The Key ID from the init segment. Widevine uses it only when the tag
and the PSSH both carry no real Key ID.
Raises a NotImplementedError when unshackle cannot use the DRM system.
"""
@@ -1573,13 +1583,16 @@ class HLS:
drm = Widevine(pssh=WV_PSSH.new(key_ids=[key.uri.split(",")[-1]], system_id=WV_PSSH.SystemId.Widevine))
elif key.keyformat and key.keyformat.lower() == WidevineCdm.urn:
extra_params = dict(key._extra_params) # noqa
# a v0 PSSH carries no KID, leaving the tag's own KEYID as the only source
kid = extra_params.pop("keyid", None) or extra_params.pop("kid", None)
if isinstance(kid, str):
kid = kid.removeprefix("0x").removeprefix("0X")
pssh = WV_PSSH(key.uri.split(",")[-1])
if kid in Widevine.PLACEHOLDER_KIDS or any(k not in Widevine.PLACEHOLDER_KIDS for k in pssh.key_ids):
kid = None
# a v0 PSSH can carry no KID: the tag's own KEYID is the first source, the init segment the last
tag_kid = extra_params.pop("keyid", None) or extra_params.pop("kid", None)
if isinstance(tag_kid, str):
tag_kid = tag_kid.removeprefix("0x").removeprefix("0X")
drm = Widevine(
pssh=WV_PSSH(key.uri.split(",")[-1]),
kid=kid,
pssh=pssh,
kid=tag_kid or kid,
**extra_params,
)
elif key.keyformat and key.keyformat.lower() in {f"urn:uuid:{PR_PSSH.SYSTEM_ID}", "com.microsoft.playready"}:
@@ -1592,6 +1605,28 @@ class HLS:
return drm
@staticmethod
def get_drm_or_probe(
key: Union[m3u8.model.SessionKey, m3u8.model.Key],
master: M3U8,
track: AnyTrack,
session: Optional[Union[Session, RnetSession]] = None,
init_section: Optional[m3u8.model.InitializationSection] = None,
probe_session: Any = None,
) -> DRM_T:
"""
Convert HLS EXT-X-KEY data to a DRM object, with the Key ID of the init segment when the key carries none.
The init segment request uses `probe_session` when the caller has no HTTP session that `get_drm` accepts.
"""
try:
return HLS.get_drm(key, session)
except Widevine.Exceptions.KIDNotFound:
kid = HLS.get_track_kid_from_init(master, track, probe_session or session or Session(), init_section)
if not kid:
raise
return HLS.get_drm(key, session, kid=kid)
@staticmethod
def get_all_drm(
keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]], proxy: Optional[str] = None
@@ -1617,6 +1652,10 @@ class HLS:
drm_objects.append(drm)
except NotImplementedError:
unsupported_keys.append(key)
except Widevine.Exceptions.KIDNotFound:
logging.getLogger("HLS").warning(
"Skipped an EXT-X-SESSION-KEY entry that carries no Key ID. The media playlist must supply the key."
)
if not drm_objects and unsupported_keys:
logging.debug(