fix(hls): apply each key tag to the wanted segments that it governs

This commit is contained in:
imSp4rky
2026-11-30 20:49:35 -07:00
parent b907069eb5
commit 33645b8c96
5 changed files with 553 additions and 55 deletions
+36 -51
View File
@@ -47,6 +47,7 @@ from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
from unshackle.core.drm.verify import decrypt_track
from unshackle.core.events import events
from unshackle.core.manifests.dash import PeriodRebase, mdhd_timescale, missing_language, rebase_webvtt_files
from unshackle.core.manifests.hls_keys import KeySpan, key_spans
from unshackle.core.manifests.segment_pipeline import (
append_segment,
check_decrypted,
@@ -637,6 +638,7 @@ class HLS:
@staticmethod
def single_init_no_rotation(
wanted_segments: list[Any],
spans: list[KeySpan],
initial_key: m3u8.Key | None,
cdm: object,
drm_preference: str | None = None,
@@ -646,27 +648,14 @@ class HLS:
Only then does the track merge into a single file with one init segment and one set of
content keys, which segment-by-segment decryption needs.
"""
if not wanted_segments:
if len(spans) != 1 or not spans[0].init_section or any(s.discontinuity for s in wanted_segments[1:]):
return False
first = wanted_segments[0]
if not first.init_section:
return False
first_keys = list(getattr(first, "keys", None) or [])
for segment in wanted_segments[1:]:
if segment.discontinuity or segment.init_section != first.init_section:
return False
# the merge loop treats a segment without its own EXT-X-KEY as "key unchanged"
segment_keys = list(getattr(segment, "keys", None) or [])
if segment_keys and segment_keys != first_keys:
return False
if not first_keys:
if not spans[0].keys:
return True
# the merge loop re-resolves the content key per segment; a pick other than the one already
# the merge loop re-resolves the content key of the span; a pick other than the one already
# licensed would re-key mid-track, which one pass of segment decryption cannot follow
return initial_key is not None and HLS.resolve_segment_key(first_keys, cdm, drm_preference) == initial_key
return initial_key is not None and HLS.resolve_segment_key(spans[0].keys, cdm, drm_preference) == initial_key
@staticmethod
def download_track(track: AnyTrack, ctx: DownloadContext) -> None:
@@ -730,15 +719,18 @@ class HLS:
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):
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")
spans = key_spans(master, wanted_segments)
keyed_spans = [span for span in spans if span.keys]
if not isinstance(session_drm, (Widevine, PlayReady)):
for span in keyed_spans:
HLS.resolve_segment_key(span.keys, cdm, track.drm_preference)
initial_drm_licensed = False
initial_drm_key = None # Track the EXT-X-KEY used for initial licensing
media_keys = [k for k in (master.keys or []) if k is not None]
media_keys = list({id(key): key for span in keyed_spans for key in span.keys if key}.values())
if media_keys:
cdm_media_keys = HLS.filter_keys_for_cdm(media_keys, cdm, track.drm_preference)
media_playlist_key = HLS.get_supported_key(cdm_media_keys) if cdm_media_keys else None
@@ -747,7 +739,9 @@ class HLS:
init_kid = (
None
if media_playlist_key.method == "AES-128"
else HLS.get_track_kid_from_init(master, track, session)
else HLS.get_track_kid_from_init(
master, track, session, next(s.init_section for s in spans if media_playlist_key in s.keys)
)
)
media_drm = HLS.get_drm(media_playlist_key, session, **({"kid": init_kid} if init_kid else {}))
if isinstance(media_drm, (Widevine, PlayReady)):
@@ -778,14 +772,12 @@ class HLS:
if DOWNLOAD_LICENCE_ONLY.is_set():
# a playlist can change its key part-way, and only the download loop licenses the later keys
licensed_keys = [initial_drm_key]
for segment in master.segments:
if not segment.keys or segment in unwanted_segments:
continue
key = HLS.resolve_segment_key(segment.keys, cdm, track.drm_preference)
for span in keyed_spans:
key = HLS.resolve_segment_key(span.keys, cdm, track.drm_preference)
if key is None or key.method == "AES-128" or key in licensed_keys:
continue
licensed_keys.append(key)
later_drm = HLS.get_drm_or_probe(key, master, track, session, segment.init_section)
later_drm = HLS.get_drm_or_probe(key, master, track, session, span.init_section)
license_drm(track, later_drm, ctx)
progress(downloaded="[yellow]SKIPPED")
return
@@ -795,7 +787,7 @@ class HLS:
# 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)
single_init = HLS.single_init_no_rotation(wanted_segments, spans, initial_drm_key, cdm, track.drm_preference)
use_segment_decrypt = (
isinstance(session_drm, (Widevine, PlayReady)) and can_use(session_drm, config.decryption) and single_init
)
@@ -1056,14 +1048,18 @@ class HLS:
to_path = to_dir / f"{str(discon_i).zfill(name_len)}{files[-1].suffix}"
merge(to=to_path, via=files, delete=True, include_map_data=include_map_data)
span_starts = {span.start: span for span in keyed_spans}
i = -1
for real_i, segment in enumerate(master.segments):
is_last_segment = (real_i + 1) == len(master.segments)
new_span = None
if segment not in unwanted_segments:
i += 1
new_span = span_starts.get(i)
key = HLS.resolve_segment_key(new_span.keys, cdm, track.drm_preference) if new_span else None
key_changed = bool(new_span and i and encryption_data and encryption_data[0] != key)
is_last_segment = (real_i + 1) == len(master.segments)
if segment not in unwanted_segments:
if isinstance(track, Subtitle):
segment_file_ext = get_extension(segment.uri) or ""
segment_file_path = segment_save_dir / f"{str(i).zfill(name_len)}{segment_file_ext}"
@@ -1091,14 +1087,15 @@ class HLS:
range_offset = 0 # TODO: Should this be reset or not?
map_data = None
if key_changed and master.segments[real_i - 1] in unwanted_segments:
decrypt(include_this_segment=False)
if segment.init_section and (not map_data or segment.init_section != map_data[0]):
init_content, range_offset = HLS.fetch_init_section(session, segment.init_section, range_offset)
map_data = (segment.init_section, init_content)
segment_keys = getattr(segment, "keys", None)
if segment_keys and segment not in unwanted_segments:
key = HLS.resolve_segment_key(segment_keys, cdm, track.drm_preference)
if encryption_data and encryption_data[0] != key and i != 0 and segment not in unwanted_segments:
if new_span:
if key_changed:
decrypt(include_this_segment=False)
if key is None:
@@ -1509,29 +1506,17 @@ class HLS:
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)]
keyed = [span for span in key_spans(manifest, segments) if span.init_section and span.keys]
if not keyed or not HLS.only_unsupported_keys(manifest):
return None
init_section = keyed[0][0].init_section
init_section = keyed[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)
pssh = one_key and all(span.init_section == init_section for span 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.
+42
View File
@@ -0,0 +1,42 @@
"""Which EXT-X-KEY tags and which EXT-X-MAP apply to each wanted segment of an HLS media playlist."""
from __future__ import annotations
from itertools import takewhile
from typing import Any, NamedTuple
import m3u8
from m3u8 import M3U8
class KeySpan(NamedTuple):
"""A run of wanted segments under the same EXT-X-KEY tags and the same init segment.
`start` is the index of its first segment in the wanted segments. `keys` is empty when no tag is in force.
"""
start: int
keys: list[m3u8.model.Key]
init_section: m3u8.model.InitializationSection | None
def key_spans(manifest: M3U8, wanted_segments: list[Any]) -> list[KeySpan]:
"""The spans of `wanted_segments`, which are segments of `manifest` in playlist order.
The EXT-X-KEY tags before a segment govern it and each later segment up to the next such tags, whatever their
KEYFORMAT, also when the segment is not wanted. python-m3u8 puts them on that segment only, and on no segment when
EXT-X-DISCONTINUITY-SEQUENCE follows. RFC 8216 4.3.3.3 allows that tag only before the first segment, so a lost
EXT-X-KEY heads `manifest.keys`.
"""
wanted = {id(segment) for segment in wanted_segments}
spans: list[KeySpan] = []
keys: list[Any] = list(takewhile(bool, manifest.keys or []))
start = 0
for segment in manifest.segments:
keys = segment.keys or keys
if id(segment) not in wanted:
continue
if not spans or keys != spans[-1].keys or segment.init_section != spans[-1].init_section:
spans.append(KeySpan(start, keys, segment.init_section))
start += 1
return spans