fix(hls): keep the EXT-X-KEY of another KEYFORMAT in force when a playlist renews one key tag

This commit is contained in:
imSp4rky
2026-12-01 18:58:20 -07:00
parent 3963e80ec3
commit 7a5bac7878
5 changed files with 94 additions and 13 deletions
+3 -2
View File
@@ -387,8 +387,9 @@ least one and no track is left.
### Segment-filtering hooks ### Segment-filtering hooks
- **HLS**: set `track.OnSegmentFilter(segment)` to drop unwanted segments (ads/bumpers). - **HLS**: set `track.OnSegmentFilter(segment)` to drop unwanted segments (ads/bumpers).
An `EXT-X-KEY` applies to each later segment until the next `EXT-X-KEY`, also when the An `EXT-X-KEY` applies to each later segment until the next `EXT-X-KEY` with the same
filter or `--sample` drops the segment that carries it. unshackle ignores an `EXT-X-KEY` that `KEYFORMAT`, or with another `METHOD`, also when the filter or `--sample` drops the segment
that carries it. `METHOD=NONE` ends every `EXT-X-KEY`. unshackle ignores an `EXT-X-KEY` that
applies to dropped segments only: no licence, no request and no new decryption. It also applies to dropped segments only: no licence, no request and no new decryption. It also
ignores the `EXT-X-DISCONTINUITY` of a dropped segment. A dropped ad break thus does not ignores the `EXT-X-DISCONTINUITY` of a dropped segment. A dropped ad break thus does not
disturb decryption when the playlist repeats the `EXT-X-KEY` of the title after the break. disturb decryption when the playlist repeats the `EXT-X-KEY` of the title after the break.
+57 -1
View File
@@ -38,6 +38,9 @@ NONE = "#EXT-X-KEY:METHOD=NONE"
MAP = '#EXT-X-MAP:URI="init.mp4"' MAP = '#EXT-X-MAP:URI="init.mp4"'
DISCONTINUITY_SEQUENCE = "#EXT-X-DISCONTINUITY-SEQUENCE:0" DISCONTINUITY_SEQUENCE = "#EXT-X-DISCONTINUITY-SEQUENCE:0"
SKD = '#EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://keys.example/a",KEYFORMAT="com.apple.streamingkeydelivery"' SKD = '#EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://keys.example/a",KEYFORMAT="com.apple.streamingkeydelivery"'
SKD_B = SKD.replace("/a", "/b")
ID_A = '#EXT-X-KEY:METHOD=SAMPLE-AES,URI="id-a"'
ID_B = '#EXT-X-KEY:METHOD=SAMPLE-AES,URI="id-b",KEYFORMAT="Identity"'
KID_A, KID_B = UUID(int=0xA1), UUID(int=0xB2) KID_A, KID_B = UUID(int=0xA1), UUID(int=0xB2)
WV_A, WV_B = key_tag(KID_A), key_tag(KID_B) WV_A, WV_B = key_tag(KID_A), key_tag(KID_B)
@@ -68,6 +71,40 @@ def playlist(tags: dict[int, list[str]]) -> str:
pytest.param({0: [K1], 2: [NONE]}, [0, 1, 4], [(0, ["k1"], None), (2, [None], None)], id="clear-ad-not-tagged"), pytest.param({0: [K1], 2: [NONE]}, [0, 1, 4], [(0, ["k1"], None), (2, [None], None)], id="clear-ad-not-tagged"),
pytest.param({0: [K1], 2: [K1]}, range(6), [(0, ["k1"], None)], id="same-tag-again"), pytest.param({0: [K1], 2: [K1]}, range(6), [(0, ["k1"], None)], id="same-tag-again"),
pytest.param({0: [SKD, WV_A]}, [3], [(0, ["skd", "data"], None)], id="two-systems"), pytest.param({0: [SKD, WV_A]}, [3], [(0, ["skd", "data"], None)], id="two-systems"),
pytest.param(
{0: [WV_A, SKD], 3: [SKD_B]},
range(6),
[(0, ["data", "skd"], None), (3, ["data", "skd"], None)],
id="other-system-stays-in-force",
),
pytest.param(
{0: [ID_A, SKD], 3: [ID_B]},
range(6),
[(0, ["id-a", "skd"], None), (3, ["id-b", "skd"], None)],
id="identity-renewed",
),
pytest.param({0: [WV_A, SKD], 3: [WV_A]}, range(6), [(0, ["data", "skd"], None)], id="first-tag-again"),
pytest.param(
{0: [ID_A], 1: [SKD]}, range(6), [(0, ["id-a"], None), (1, ["id-a", "skd"], None)], id="tag-on-each"
),
pytest.param(
{0: [SKD, DISCONTINUITY_SEQUENCE, ID_A], 1: [SKD_B]},
range(6),
[(0, ["skd", "id-a"], None), (1, ["skd", "id-a"], None)],
id="lost-tag-beside-a-tag",
),
pytest.param(
{0: [SKD], 2: [K1], 4: [SKD_B]},
range(6),
[(0, ["skd"], None), (2, ["k1"], None), (4, ["skd"], None)],
id="other-method",
),
pytest.param(
{0: [WV_A, SKD], 2: [NONE], 4: [SKD]},
range(6),
[(0, ["data", "skd"], None), (2, [None], None), (4, ["skd"], None)],
id="none-ends-every-system",
),
pytest.param( pytest.param(
{0: [MAP, K1], 3: [MAP.replace("init", "next")]}, {0: [MAP, K1], 3: [MAP.replace("init", "next")]},
[1, 4], [1, 4],
@@ -427,7 +464,7 @@ def test_the_first_licence_reads_the_init_segment_of_its_own_key(
[ [
pytest.param({0: [MAP, SKD]}, id="first-segment"), pytest.param({0: [MAP, SKD]}, id="first-segment"),
pytest.param({0: [MAP, SKD, DISCONTINUITY_SEQUENCE]}, id="lost"), pytest.param({0: [MAP, SKD, DISCONTINUITY_SEQUENCE]}, id="lost"),
pytest.param({0: [MAP, WV_A], 3: [SKD]}, id="second-key"), pytest.param({0: [MAP, WV_A], 2: [NONE], 3: [SKD]}, id="second-key"),
], ],
) )
@pytest.mark.parametrize("cdm", ["widevine", None]) @pytest.mark.parametrize("cdm", ["widevine", None])
@@ -446,6 +483,25 @@ def test_a_tag_unshackle_cannot_license_is_refused_before_a_segment(
assert not [path for path in server.requests if path.endswith(".ts")] assert not [path for path in server.requests if path.endswith(".ts")]
def test_a_tag_of_another_keyformat_keeps_the_licensed_tag_in_force(
server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
DOWNLOAD_LICENCE_ONLY.set()
monkeypatch.setattr(Audio, "get_key_id", lambda self, data: KID_A)
licensed: list[UUID | None] = []
download(
server,
tmp_path,
monkeypatch,
{0: [MAP, WV_A, SKD], 3: [SKD_B]},
cdm=cdm_type_stub("widevine"),
licence=lambda drm, track_kid=None: licensed.append(track_kid),
)
assert licensed == [KID_A]
def test_a_lost_tag_is_bridged_with_the_first_init_segment( def test_a_lost_tag_is_bridged_with_the_first_init_segment(
server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None: ) -> None:
+7 -1
View File
@@ -144,8 +144,14 @@ IDENTITY_KEY = '#EXT-X-KEY:METHOD=SAMPLE-AES,URI="https://keys.example/key"'
pytest.param(playlist(f'{IDENTITY_KEY},KEYFORMAT="identity"'), False, id="identity"), pytest.param(playlist(f'{IDENTITY_KEY},KEYFORMAT="identity"'), False, id="identity"),
pytest.param(playlist(SKD_KEY), True, id="fairplay"), pytest.param(playlist(SKD_KEY), True, id="fairplay"),
pytest.param(playlist(IDENTITY_KEY, SKD_KEY), True, id="identity-beside-fairplay"), pytest.param(playlist(IDENTITY_KEY, SKD_KEY), True, id="identity-beside-fairplay"),
pytest.param(playlist(SKD_KEY).replace("seg0.m4s\n", f"seg0.m4s\n{IDENTITY_KEY}\n"), True, id="identity-later"),
pytest.param( pytest.param(
playlist(SKD_KEY).replace("seg0.m4s\n", f"seg0.m4s\n{IDENTITY_KEY}\n"), False, id="identity-later" playlist(SKD_KEY).replace("seg0.m4s\n", f"seg0.m4s\n{NONE_KEY}\n{IDENTITY_KEY}\n"),
False,
id="identity-after-a-clear-tag",
),
pytest.param(
playlist(IDENTITY_KEY).replace("seg0.m4s\n", f"seg0.m4s\n{SKD_KEY}\n"), False, id="fairplay-later"
), ),
], ],
) )
+2 -3
View File
@@ -48,7 +48,7 @@ from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
from unshackle.core.drm.verify import decrypt_track from unshackle.core.drm.verify import decrypt_track
from unshackle.core.events import events from unshackle.core.events import events
from unshackle.core.manifests.dash import PeriodRebase, mdhd_timescale, missing_language, rebase_webvtt_files 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.hls_keys import KeySpan, key_spans, keyformat
from unshackle.core.manifests.segment_pipeline import ( from unshackle.core.manifests.segment_pipeline import (
append_segment, append_segment,
check_decrypted, check_decrypted,
@@ -1627,8 +1627,7 @@ class HLS:
spans = key_spans(manifest, manifest.segments) spans = key_spans(manifest, manifest.segments)
clear_inits = [span.init_section for span in spans if any(key.method == "NONE" for key in span.keys if key)] clear_inits = [span.init_section for span in spans if any(key.method == "NONE" for key in span.keys if key)]
return all( return all(
span.init_section not in clear_inits span.init_section not in clear_inits and any(keyformat(key) != "identity" for key in span.keys if key)
and any((key.keyformat or "identity").lower() != "identity" for key in span.keys if key)
for span in spans for span in spans
if HLS.encrypts(span.keys) if HLS.encrypts(span.keys)
) )
+25 -6
View File
@@ -20,20 +20,39 @@ class KeySpan(NamedTuple):
init_section: m3u8.model.InitializationSection | None init_section: m3u8.model.InitializationSection | None
def keyformat(key: m3u8.model.Key) -> str:
"""The KEYFORMAT of an EXT-X-KEY in lower case, identity when it has none."""
return (key.keyformat or "identity").lower()
def by_keyformat(keys: list[m3u8.model.Key]) -> dict[str, list[m3u8.model.Key]]:
"""`keys` grouped by `keyformat`, in the order of the first tag of each group."""
groups: dict[str, list[m3u8.model.Key]] = {}
for key in keys:
groups.setdefault(keyformat(key), []).append(key)
return groups
def key_spans(manifest: M3U8, wanted_segments: list[Any]) -> list[KeySpan]: 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 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 An EXT-X-KEY tag governs its segment and each later segment up to the next tag with the same `keyformat` and
KEYFORMAT, also when the segment is not wanted. python-m3u8 puts them on that segment only, and on no segment when takes its place, also when the segment is not wanted (RFC 8216 4.3.2.4). A new tag ends each tag in force of
EXT-X-DISCONTINUITY-SEQUENCE follows. RFC 8216 4.3.3.3 allows that tag only before the first segment, so a lost another METHOD, METHOD=NONE included, because the tags of one segment give one content key. python-m3u8 puts the
EXT-X-KEY heads `manifest.keys`. tags 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`, before the tags of the first
segment.
""" """
wanted = {id(segment) for segment in wanted_segments} wanted = {id(segment) for segment in wanted_segments}
spans: list[KeySpan] = [] spans: list[KeySpan] = []
keys: list[Any] = list(takewhile(bool, manifest.keys or [])) first = manifest.segments[0].keys if manifest.segments else []
keys: list[Any] = list(takewhile(lambda key: key and key not in first, manifest.keys or []))
start = 0 start = 0
for segment in manifest.segments: for segment in manifest.segments:
keys = segment.keys or keys if segment.keys:
methods = {key.method for key in segment.keys}
kept = by_keyformat([key for key in keys if key.method in methods])
keys = [key for group in (kept | by_keyformat(segment.keys)).values() for key in group]
if id(segment) not in wanted: if id(segment) not in wanted:
continue continue
if not spans or keys != spans[-1].keys or segment.init_section != spans[-1].init_section: if not spans or keys != spans[-1].keys or segment.init_section != spans[-1].init_section: