From 33645b8c96d8d72c1962e2722737c25357b5a07b Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Mon, 30 Nov 2026 20:49:34 -0700 Subject: [PATCH] fix(hls): apply each key tag to the wanted segments that it governs --- docs/dev/service-architecture.md | 10 +- tests/core/test_hls_keys.py | 466 ++++++++++++++++++++++++ tests/core/test_hls_service_drm_keys.py | 3 +- unshackle/core/manifests/hls.py | 87 ++--- unshackle/core/manifests/hls_keys.py | 42 +++ 5 files changed, 553 insertions(+), 55 deletions(-) create mode 100644 tests/core/test_hls_keys.py create mode 100644 unshackle/core/manifests/hls_keys.py diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md index 908bd012..9b12fd4b 100644 --- a/docs/dev/service-architecture.md +++ b/docs/dev/service-architecture.md @@ -387,9 +387,13 @@ least one and no track is left. ### Segment-filtering hooks - **HLS**: set `track.OnSegmentFilter(segment)` to drop unwanted segments (ads/bumpers). - A dropped segment is invisible to the whole download: unshackle ignores its `EXT-X-KEY` - and its `EXT-X-DISCONTINUITY`, so a clear ad break inside an encrypted track does - not disturb decryption. + An `EXT-X-KEY` applies to each later segment until the next `EXT-X-KEY`, also when the + filter or `--sample` drops the segment that carries it. unshackle ignores an `EXT-X-KEY` that + 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 + disturb decryption when the playlist repeats the `EXT-X-KEY` of the title after the break. + Without the repeat, the segments after the break take the `EXT-X-KEY` of the ads, and + `METHOD=NONE` there makes them clear. - **DASH**: pass a `period_filter` callable to `to_tracks` to drop whole periods. unshackle automatically drops the caching-breadth periods that some services send, and the non-`content` segment types. diff --git a/tests/core/test_hls_keys.py b/tests/core/test_hls_keys.py new file mode 100644 index 00000000..c8a3d990 --- /dev/null +++ b/tests/core/test_hls_keys.py @@ -0,0 +1,466 @@ +"""The key tags and the init segment that apply to each wanted segment, at ``key_spans`` and in ``HLS.download_track``. + +python-m3u8 puts an EXT-X-KEY on the next segment only. A ``--sample`` or an OnSegmentFilter that skipped that segment +made a track with a Widevine or PlayReady CDM write AES-128 ciphertext with no error. The downloads here run on real +AES-128 segments from a localhost server and compare the output with the plaintext. +""" + +from __future__ import annotations + +from collections.abc import Iterator, Sequence +from pathlib import Path +from typing import Any +from uuid import UUID + +import m3u8 +import pytest +import requests + +from tests.core.test_clearkey import encrypt as aes_cbc +from tests.core.test_hls_licence_only_key_rotation import key_tag +from tests.core.test_resume_hls_integration import server as server # noqa: F401 +from unshackle.core.cdm.detect import cdm_type_stub +from unshackle.core.config import config +from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY +from unshackle.core.drm import Widevine +from unshackle.core.manifests import hls as hls_module +from unshackle.core.manifests.hls import HLS +from unshackle.core.manifests.hls_keys import key_spans +from unshackle.core.tracks import Audio +from unshackle.core.tracks.track import DownloadContext, Track + +PLAIN = [bytes([0x41 + i]) * 752 for i in range(6)] +INIT = b"INIT" * 20 +SEQUENCE = 7 +KEYS = {"k1": bytes(range(16)), "k2": bytes(range(16, 32))} +K1, K2 = (f'#EXT-X-KEY:METHOD=AES-128,URI="{name}"' for name in KEYS) +NONE = "#EXT-X-KEY:METHOD=NONE" +MAP = '#EXT-X-MAP:URI="init.mp4"' +DISCONTINUITY_SEQUENCE = "#EXT-X-DISCONTINUITY-SEQUENCE:0" +SKD = '#EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://keys.example/a",KEYFORMAT="com.apple.streamingkeydelivery"' +KID_A, KID_B = UUID(int=0xA1), UUID(int=0xB2) +WV_A, WV_B = key_tag(KID_A), key_tag(KID_B) + + +def playlist(tags: dict[int, list[str]]) -> str: + """A media playlist of 6 second segments, with `tags` before the segment of each index.""" + lines = ["#EXTM3U", "#EXT-X-VERSION:6", "#EXT-X-TARGETDURATION:6", f"#EXT-X-MEDIA-SEQUENCE:{SEQUENCE}"] + for i in range(len(PLAIN)): + lines += [*tags.get(i, []), "#EXTINF:6.0,", f"s{i}.ts"] + return "\n".join([*lines, "#EXT-X-ENDLIST", ""]) + + +@pytest.mark.parametrize( + "tags, wanted, expected", + [ + pytest.param({}, range(6), [(0, [], None)], id="no-tag"), + pytest.param({0: [K1]}, range(6), [(0, ["k1"], None)], id="one-key"), + pytest.param({0: [K1]}, [2, 3], [(0, ["k1"], None)], id="tag-before-the-window"), + pytest.param({2: [K1]}, range(6), [(0, [], None), (2, ["k1"], None)], id="clear-lead"), + pytest.param({2: [K1]}, [0, 1], [(0, [], None)], id="tag-after-the-window"), + pytest.param( + {0: [K1], 3: [K2]}, [0, 1, 4, 5], [(0, ["k1"], None), (2, ["k2"], None)], id="second-tag-on-a-skipped" + ), + pytest.param({0: [K1], 3: [K2]}, [0, 1, 2], [(0, ["k1"], None)], id="second-key-covers-none"), + pytest.param({0: [K1], 3: [K2]}, [4], [(0, ["k2"], None)], id="first-key-covers-none"), + pytest.param({0: [K1], 2: [NONE], 4: [K1]}, [0, 1, 4, 5], [(0, ["k1"], None)], id="clear-ad-tagged-again"), + pytest.param({0: [K1], 2: [K2], 4: [K1]}, [0, 1, 4, 5], [(0, ["k1"], None)], id="keyed-ad-tagged-again"), + 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: [SKD, WV_A]}, [3], [(0, ["skd", "data"], None)], id="two-systems"), + pytest.param( + {0: [MAP, K1], 3: [MAP.replace("init", "next")]}, + [1, 4], + [(0, ["k1"], "init.mp4"), (1, ["k1"], "next.mp4")], + id="second-init", + ), + pytest.param({0: [K1, DISCONTINUITY_SEQUENCE]}, range(6), [(0, ["k1"], None)], id="lost-tag"), + pytest.param({0: [SKD, K1, DISCONTINUITY_SEQUENCE]}, range(6), [(0, ["skd", "k1"], None)], id="lost-tags"), + pytest.param({0: [K1, DISCONTINUITY_SEQUENCE]}, [2], [(0, ["k1"], None)], id="lost-tag-before-the-window"), + pytest.param( + {0: [K1, DISCONTINUITY_SEQUENCE], 3: [K2]}, + range(6), + [(0, ["k1"], None), (3, ["k2"], None)], + id="lost-tag-then-a-key", + ), + pytest.param({0: [K1, DISCONTINUITY_SEQUENCE, K2]}, range(6), [(0, ["k2"], None)], id="lost-tag-replaced"), + pytest.param({0: [K1]}, [], [], id="nothing-wanted"), + ], +) +def test_key_spans(tags: dict[int, list[str]], wanted: Any, expected: list[Any]) -> None: + manifest = m3u8.loads(playlist(tags), uri="https://example.test/media.m3u8") + + spans = key_spans(manifest, [manifest.segments[i] for i in wanted]) + + found = [ + (s.start, [k.uri and k.uri.split(":")[0] for k in s.keys], s.init_section and s.init_section.uri) for s in spans + ] + assert found == expected + + +def test_dropped_tags_leave_no_span_with_a_key() -> None: + manifest = m3u8.loads(playlist({0: [SKD, DISCONTINUITY_SEQUENCE]})) + + assert HLS.drop_unsupported_keys(manifest) + + assert [span.keys for span in key_spans(manifest, manifest.segments)] == [[]] + + +def keys_requested(server: Any) -> list[str]: + return [path[1:] for path in server.requests if path[1:] in KEYS] + + +@pytest.fixture(autouse=True) +def clean_run(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + """No state of an earlier download, and no check of CENC output: those segments are plaintext.""" + monkeypatch.setattr(hls_module, "check_decrypted", lambda *args: None) + DOWNLOAD_CANCELLED.clear() + yield + DOWNLOAD_CANCELLED.clear() + DOWNLOAD_LICENCE_ONLY.clear() + + +def encrypt(i: int, key: str | None) -> bytes: + """Segment `i` under `key`, with the media sequence number as its IV.""" + if key is None: + return PLAIN[i] + return aes_cbc(PLAIN[i], KEYS[key], (SEQUENCE + i).to_bytes(16, "big")) + + +def download( + server: Any, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + tags: dict[int, list[str]], + keys: Sequence[str | None] = (None,) * len(PLAIN), + *, + cdm: Any, + sample: tuple[int, int] | None = None, + drop: tuple[int, ...] = (), + licence: Any = None, +) -> bytes: + """Run HLS.download_track on segments encrypted with `keys` and return the output.""" + server.routes |= {"/init.mp4": INIT, **{f"/{name}": key for name, key in KEYS.items()}} + server.routes["/media.m3u8"] = playlist(tags).encode() + for i, key in enumerate(keys): + server.routes[f"/s{i}.ts"] = encrypt(i, key) + track = Audio( + url=f"http://127.0.0.1:{server.server_address[1]}/media.m3u8", + language="en", + descriptor=Track.Descriptor.HLS, + codec=Audio.Codec.AAC, + ) + track.OnSegmentFilter = lambda segment: segment.uri in {f"s{i}.ts" for i in drop} + monkeypatch.setattr(config, "sample", sample) + ctx = DownloadContext( + save_path=tmp_path / "audio.ts", + save_dir=tmp_path / "audio_segments", + progress=lambda **_: None, + session=requests.Session(), + license_widevine=licence or (lambda drm, track_kid=None: pytest.fail("a licence was requested")), + cdm=cdm, + max_workers=2, + ) + HLS.download_track(track, ctx) + return ctx.save_path.read_bytes() if ctx.save_path.exists() else b"" + + +ONE_KEY: list[str | None] = ["k1"] * 6 +TWO_KEYS: list[str | None] = ["k1"] * 3 + ["k2"] * 3 + + +@pytest.mark.parametrize("cdm", ["widevine", "playready", None]) +@pytest.mark.parametrize( + "tags, keys, sample, drop, wanted, requested", + [ + pytest.param({0: [K1]}, ONE_KEY, None, (), range(6), ["k1"], id="whole-track"), + pytest.param({0: [K1]}, ONE_KEY, (12, 24), (), [2, 3], ["k1"], id="sample-past-the-tag"), + pytest.param({0: [K1]}, ONE_KEY, None, (0,), range(1, 6), ["k1"], id="filter-drops-the-tagged-segment"), + pytest.param({0: [K1]}, ONE_KEY, (6, 12), (0,), [2], ["k1"], id="filter-and-sample"), + pytest.param({0: [K1], 3: [K2]}, TWO_KEYS, (24, 30), (), [4], ["k2"], id="sample-in-the-second-key"), + pytest.param({0: [K1], 3: [K2]}, TWO_KEYS, (0, 18), (), [0, 1, 2], ["k1"], id="sample-in-the-first-key"), + pytest.param( + {0: [K1], 3: [K2]}, TWO_KEYS, None, (3,), [0, 1, 2, 4, 5], ["k1", "k2"], id="filter-drops-the-second-tag" + ), + pytest.param({0: [K1], 3: [K2]}, TWO_KEYS, None, (0, 1, 2), [3, 4, 5], ["k2"], id="filter-drops-the-first-key"), + pytest.param( + {0: [K1], 2: [NONE], 4: [K1]}, + ["k1", "k1", None, None, "k1", "k1"], + None, + (2, 3), + [0, 1, 4, 5], + ["k1"], + id="clear-ad-dropped", + ), + pytest.param( + {0: [K1], 2: [K2], 4: [K1]}, + ["k1", "k1", "k2", "k2", "k1", "k1"], + None, + (2, 3), + [0, 1, 4, 5], + ["k1"], + id="keyed-ad-dropped", + ), + pytest.param( + {0: [K1], 3: [NONE]}, + ["k1", "k1", "k1", None, None, None], + None, + (3,), + [0, 1, 2, 4, 5], + ["k1"], + id="filter-drops-the-none-tag", + ), + pytest.param( + {0: [K1, DISCONTINUITY_SEQUENCE]}, + ONE_KEY, + None, + (), + range(6), + ["k1"], + id="tag-before-discontinuity-sequence", + ), + ], +) +def test_aes_128_output_is_the_plaintext( + server: Any, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + cdm: str | None, + tags: dict[int, list[str]], + keys: list[str | None], + sample: tuple[int, int] | None, + drop: tuple[int, ...], + wanted: Any, + requested: list[str], +) -> None: + stub = cdm_type_stub(cdm) if cdm else None + + output = download(server, tmp_path, monkeypatch, tags, keys, cdm=stub, sample=sample, drop=drop) + + assert output == b"".join(PLAIN[i] for i in wanted) + assert keys_requested(server) == requested + + +def test_aes_128_fmp4_is_decrypted_past_the_tag(server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """One init segment and no tag in the window is also the shape that a rolling merge takes.""" + monkeypatch.setattr(config, "merge_segments", True) + + output = download( + server, + tmp_path, + monkeypatch, + {0: [MAP, K1]}, + ONE_KEY, + cdm=cdm_type_stub("widevine"), + sample=(12, 24), + ) + + assert output == INIT + PLAIN[2] + PLAIN[3] + + +TWO_WV = {0: [WV_A], 3: [WV_B]} + + +@pytest.mark.parametrize( + "sample, drop, kids", + [ + pytest.param(None, (), [KID_A, KID_B], id="whole-track"), + pytest.param(None, (3,), [KID_A, KID_B], id="filter-drops-the-second-tag"), + pytest.param((24, 30), (), [KID_B], id="sample-in-the-second-key"), + pytest.param((0, 18), (), [KID_A], id="sample-in-the-first-key"), + pytest.param(None, (0, 1, 2), [KID_B], id="filter-drops-the-first-key"), + pytest.param(None, (3, 4, 5), [KID_A], id="filter-drops-the-second-key"), + ], +) +@pytest.mark.parametrize("licence_only", [True, False], ids=["licence-only", "download"]) +def test_only_the_keys_of_the_wanted_segments_are_licensed_and_applied( + server: Any, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + licence_only: bool, + sample: tuple[int, int] | None, + drop: tuple[int, ...], + kids: list[UUID], +) -> None: + licensed: list[UUID | None] = [] + decrypted: list[UUID] = [] + + def licence(drm: Widevine, track_kid: UUID | None = None) -> None: + licensed.append(track_kid) + drm.content_keys.update({kid: "01" * 16 for kid in drm.kids}) + + monkeypatch.setattr( + hls_module, "decrypt_track", lambda drm, path, *args, **kwargs: decrypted.append(next(iter(drm.content_keys))) + ) + if licence_only: + DOWNLOAD_LICENCE_ONLY.set() + + download( + server, + tmp_path, + monkeypatch, + TWO_WV, + cdm=cdm_type_stub("widevine"), + sample=sample, + drop=drop, + licence=licence, + ) + + assert licensed == kids + assert decrypted == ([] if licence_only else kids) + + +@pytest.mark.parametrize("drop", [(), (3,)], ids=["no-filter", "filter-drops-the-second-tag"]) +def test_each_key_decrypts_behind_its_own_init_segment( + server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, drop: tuple[int, ...] +) -> None: + """A dropped EXT-X-DISCONTINUITY starts no new block, so the key change alone separates the two init segments.""" + monkeypatch.setattr(Audio, "get_key_id", lambda self, data: None) + server.routes |= {"/first.mp4": b"first", "/later.mp4": b"later"} + first, later = (MAP.replace("init", name) for name in ("first", "later")) + heads: list[bytes] = [] + monkeypatch.setattr( + hls_module, "decrypt_track", lambda drm, path, *args, **kwargs: heads.append(path.read_bytes()[:5]) + ) + monkeypatch.setattr(HLS, "merge_segments", lambda segments, save_path, progress: save_path.touch()) + + download( + server, + tmp_path, + monkeypatch, + {0: [first, WV_A], 3: ["#EXT-X-DISCONTINUITY", later, WV_B]}, + cdm=cdm_type_stub("widevine"), + drop=drop, + licence=lambda drm, track_kid=None: None, + ) + + assert heads == [b"first", b"later"] + + +@pytest.mark.parametrize("mapped", [True, False], ids=["two-keys-one-init", "one-key-no-init"]) +def test_a_rotation_or_a_missing_init_segment_keeps_the_post_merge( + server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mapped: bool +) -> None: + """A rolling merge decrypts the whole file with the content keys of the first licence only.""" + monkeypatch.setattr(config, "merge_segments", True) + monkeypatch.setattr(Audio, "get_key_id", lambda self, data: None) + rolling: list[bool] = [] + fetch = hls_module.fetch_segments + monkeypatch.setattr( + hls_module, + "fetch_segments", + lambda *args, **kwargs: rolling.append(kwargs["rolling"]) or fetch(*args, **kwargs), + ) + monkeypatch.setattr(hls_module, "decrypt_track", lambda *args, **kwargs: None) + + download( + server, + tmp_path, + monkeypatch, + {0: [MAP, WV_A], 3: [WV_B]} if mapped else {0: [WV_A]}, + cdm=cdm_type_stub("widevine"), + licence=lambda drm, track_kid=None: None, + ) + + assert rolling == [False] + + +def test_the_first_key_of_the_wanted_segments_is_licensed_before_a_segment_request( + server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + hits: list[list[str]] = [] + monkeypatch.setattr(hls_module, "decrypt_track", lambda *args, **kwargs: None) + + download( + server, + tmp_path, + monkeypatch, + {0: [WV_A]}, + cdm=cdm_type_stub("widevine"), + sample=(12, 24), + licence=lambda drm, track_kid=None: hits.append(list(server.requests)), + ) + + assert hits == [["/media.m3u8"]] + + +@pytest.mark.parametrize( + "lead, sample, drop", + [ + pytest.param(WV_A, (24, 30), (), id="sample-in-the-second-key"), + pytest.param("", None, (), id="clear-lead"), + pytest.param("", None, (0,), id="filter-in-the-clear-lead"), + ], +) +def test_the_first_licence_reads_the_init_segment_of_its_own_key( + server: Any, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + lead: str, + sample: tuple[int, int] | None, + drop: tuple[int, ...], +) -> None: + """The Key ID comes from the init segment of the licensed key, not from the first one of the playlist.""" + DOWNLOAD_LICENCE_ONLY.set() + monkeypatch.setattr(Audio, "get_key_id", lambda self, data: {b"first": KID_A, b"later": KID_B}[data]) + server.routes |= {"/first.mp4": b"first", "/later.mp4": b"later"} + first, later = (MAP.replace("init", name) for name in ("first", "later")) + licensed: list[UUID | None] = [] + + download( + server, + tmp_path, + monkeypatch, + {0: [first, lead], 3: [later, WV_B]}, + cdm=cdm_type_stub("widevine"), + sample=sample, + drop=drop, + licence=lambda drm, track_kid=None: licensed.append(track_kid), + ) + + assert licensed == [KID_B] + assert "/first.mp4" not in server.requests + + +@pytest.mark.parametrize( + "tags", + [ + pytest.param({0: [MAP, SKD]}, id="first-segment"), + pytest.param({0: [MAP, SKD, DISCONTINUITY_SEQUENCE]}, id="lost"), + pytest.param({0: [MAP, WV_A], 3: [SKD]}, id="second-key"), + ], +) +@pytest.mark.parametrize("cdm", ["widevine", None]) +def test_a_tag_unshackle_cannot_license_is_refused_before_a_segment( + server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, cdm: str | None, tags: dict[int, list[str]] +) -> None: + with pytest.raises(NotImplementedError, match="None of the key systems are supported"): + download( + server, + tmp_path, + monkeypatch, + tags, + cdm=cdm_type_stub(cdm) if cdm else None, + ) + + assert not [path for path in server.requests if path.endswith(".ts")] + + +def test_a_lost_tag_is_bridged_with_the_first_init_segment( + server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(Audio, "get_key_id", lambda self, data: {INIT: KID_A, b"later": KID_B}[data]) + server.routes["/later.mp4"] = b"later" + DOWNLOAD_LICENCE_ONLY.set() + licensed: list[UUID | None] = [] + + download( + server, + tmp_path, + monkeypatch, + {0: [MAP, SKD, DISCONTINUITY_SEQUENCE], 3: ["#EXT-X-DISCONTINUITY", MAP.replace("init", "later")]}, + cdm=cdm_type_stub("widevine"), + licence=lambda drm, track_kid=None: licensed.append(track_kid), + ) + + assert licensed == [KID_A] diff --git a/tests/core/test_hls_service_drm_keys.py b/tests/core/test_hls_service_drm_keys.py index af0eab45..6ca99419 100644 --- a/tests/core/test_hls_service_drm_keys.py +++ b/tests/core/test_hls_service_drm_keys.py @@ -20,6 +20,7 @@ from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY from unshackle.core.drm import ClearKey, PlayReady from unshackle.core.drm.cenc import drm_stub from unshackle.core.manifests.hls import HLS +from unshackle.core.manifests.hls_keys import key_spans from unshackle.core.tracks import Video from unshackle.core.tracks.track import DownloadContext, Track @@ -88,7 +89,7 @@ def test_key_tags_no_licence_route_can_use_are_dropped() -> None: assert manifest.keys == [] assert all(segment.keys == [] for segment in manifest.segments) - assert HLS.single_init_no_rotation(manifest.segments, None, None) + assert HLS.single_init_no_rotation(manifest.segments, key_spans(manifest, manifest.segments), None, None) @pytest.mark.parametrize( diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py index 76200cef..fbcc4cca 100644 --- a/unshackle/core/manifests/hls.py +++ b/unshackle/core/manifests/hls.py @@ -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. diff --git a/unshackle/core/manifests/hls_keys.py b/unshackle/core/manifests/hls_keys.py new file mode 100644 index 00000000..8f4465ca --- /dev/null +++ b/unshackle/core/manifests/hls_keys.py @@ -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