feat(hls): license every content key of a FairPlay bridge playlist that rotates its key

This commit is contained in:
imSp4rky
2026-12-01 18:32:36 -07:00
parent e0880812d5
commit 41c2b3d86a
12 changed files with 478 additions and 76 deletions
+67 -33
View File
@@ -711,15 +711,19 @@ 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
bridge_drm = bridge_kid = None
bridge_drm = None
bridge_kids: list[UUID] = []
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:
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:
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}")
log.debug(
f"{track.id}: licensing key IDs {', '.join(kid.hex for kid in bridge_kids)} "
f"of its init segments as {bridge_drm.NAME}"
)
elif isinstance(session_drm, (Widevine, PlayReady)) and 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")
@@ -766,9 +770,10 @@ class HLS:
initial_drm_licensed = True
if not initial_drm_licensed:
license_drm(
track, session_drm, ctx, bridge_kid, probe=lambda: HLS.get_track_kid_from_init(master, track, session)
)
for kid in bridge_kids or (None,):
license_drm(
track, session_drm, ctx, 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
@@ -783,8 +788,11 @@ 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}")
if bridge_drm:
content_keys = bridge_drm.content_keys
missing = [k for k in bridge_kids[1:] if k not in content_keys] if content_keys else bridge_kids[:1]
if missing:
raise bridge_drm.Exceptions.CEKNotFound(f"No content key for KID {missing[0].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.
@@ -1518,65 +1526,91 @@ class HLS:
raise NotImplementedError(f"None of the key systems are supported: {', '.join(unsupported_systems)}")
@staticmethod
def get_bridge_kid(
def get_bridge_kids(
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.
) -> list[UUID]:
"""The real Key IDs of the init segments of the `segments` entries with an EXT-X-KEY unshackle cannot license.
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 in a one-key playlist, and with several init segments only as `get_stitched_kid` reads
them: an all-zero tenc takes any content key.
A real first Key ID adds each other real tenc Key ID once, in playlist order. Empty 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. The pssh boxes count only in a one-key playlist, as `get_stitched_kids` reads them:
an all-zero tenc takes any content key.
"""
keyed = [span for span in key_spans(manifest, segments) if span.init_section and HLS.encrypts(span.keys)]
if not keyed or not HLS.only_unsupported_keys(manifest):
return None
return []
one_key = len({key.uri for key in manifest.keys if key and key.method != "NONE"}) == 1
if any(b.init_section != a.init_section and not b.discontinuity for a, b in pairwise(segments)):
return None
return []
init_sections: list[m3u8.model.InitializationSection] = []
for span in keyed:
if span.init_section not in init_sections:
init_sections.append(span.init_section)
if one_key and len(init_sections) > 1:
kid = HLS.get_stitched_kid(manifest, init_sections, track, session)
kids = HLS.get_stitched_kids(manifest, init_sections, track, session)
else:
kid = HLS.get_track_kid_from_init(manifest, track, session, init_sections[0], pssh=one_key)
return None if kid in PLACEHOLDER_KIDS else kid
if kid is None or kid in PLACEHOLDER_KIDS:
return []
kids = [kid, *HLS.get_later_kids(manifest, init_sections[1:], track, session)]
return [] if not kids or kids[0] in PLACEHOLDER_KIDS else list(dict.fromkeys(kids))
@staticmethod
def get_stitched_kid(
def get_stitched_kids(
manifest: M3U8,
init_sections: list[m3u8.model.InitializationSection],
track: Track,
session: Session | RnetSession,
) -> UUID | None:
"""The tenc Key ID of the first init segment, or when that is all-zero, the one Key ID that all of them give.
) -> list[UUID]:
"""The real tenc Key ID of the first encrypted init segment and `get_later_kids` of the rest, else one Key ID of all.
Each gives its tenc Key ID, or else that of its pssh boxes. One that is clear does not count, and one that
unshackle cannot read makes it None.
For the one Key ID, each gives its tenc Key ID, or else that of its pssh boxes. One that is clear does not
count, and one that unshackle cannot read makes it empty.
"""
found: UUID | None = None
for init_section in init_sections:
for i, init_section in enumerate(init_sections):
init_data = HLS.probe_init_section(manifest, session, init_section)
if not init_data:
return None
return []
try:
if is_clear_init(init_data):
continue
kid = track.get_key_id(init_data)
if not (kid and kid.int):
kid = init_pssh_kid(init_data)
elif init_section is init_sections[0]:
return kid
elif found is None:
return [kid, *HLS.get_later_kids(manifest, init_sections[i + 1 :], track, session)]
except Exception as e:
logging.getLogger("HLS").debug(f"Init map key-id probe failed for {init_section.uri}: {e!r}")
return None
return []
if kid is None or found not in (None, kid):
logging.getLogger("HLS").debug(f"{track.id}: init segment {init_section.uri} gives key ID {kid}")
return None
return []
found = kid
return found
return [found] if found else []
@staticmethod
def get_later_kids(
manifest: M3U8,
init_sections: list[m3u8.model.InitializationSection],
track: Track,
session: Session | RnetSession,
) -> list[UUID]:
"""The real tenc Key IDs of the init segments of a playlist that changes its key, without one that gives none."""
kids = (HLS.get_track_kid_from_init(manifest, track, session, init_section) for init_section in init_sections)
return [kid for kid in kids if kid and kid not in PLACEHOLDER_KIDS]
@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.
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)
return drm
@staticmethod
def only_unsupported_keys(manifest: M3U8) -> bool: