"""The key plan of an HLS track, built from the playlist text and the init segment bytes, without a download.""" from __future__ import annotations from pathlib import Path from typing import Any from uuid import UUID import m3u8 import pytest from tests.core.test_hls_kid_from_init import keyed_segment, no_kid_pssh, playlist from tests.core.test_hls_service_drm_keys import KID, OTHER_KID, SKD_KEY, encrypted_init from unshackle.core.cdm.detect import cdm_type_stub from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.drm import PlayReady, Widevine, cenc from unshackle.core.manifests.hls import HLS from unshackle.core.manifests.hls_key_plan import HlsKeyPlan from unshackle.core.tracks import Video from unshackle.core.tracks.track import DownloadContext, Track FIRST = keyed_segment(no_kid_pssh(b"first"), init="a.mp4") LATER = keyed_segment(no_kid_pssh(b"later"), init="b.mp4") CLEAR = "#EXT-X-KEY:METHOD=NONE\n#EXTINF:6.0,\nclear.m4s\n" INITS = {"a.mp4": encrypted_init(KID), "b.mp4": encrypted_init(OTHER_KID)} @pytest.fixture(autouse=True) def no_ffprobe(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(cenc, "ffprobe", lambda data: {}) def plan_of(text: str, cdm: Any = None, bridge: bool = False, skip: int = 0) -> tuple[HlsKeyPlan, list[str]]: """The plan of `text` without its first `skip` segments, and the init segments it reads, in order of the first read.""" manifest = m3u8.loads(text, uri="https://example.test/media.m3u8") track = Video( url="https://example.test/media.m3u8", language="en", descriptor=Track.Descriptor.HLS, codec=Video.Codec.AVC ) reads: list[str] = [] def read_init(init_section: m3u8.model.InitializationSection) -> bytes | None: if init_section.uri not in reads: reads.append(init_section.uri) return INITS.get(init_section.uri) return HlsKeyPlan.build(manifest, manifest.segments[skip:], track, cdm, bridge, read_init, None), reads def licences(tmp_path: Path, licensed: list[UUID | None]) -> DownloadContext: return DownloadContext( save_path=tmp_path / "video.mp4", save_dir=tmp_path / "segments", progress=lambda **_: None, license_widevine=lambda drm, track_kid=None: licensed.append(track_kid), cdm=None, ) def test_each_key_tag_takes_the_key_id_of_the_init_segment_of_its_first_span(tmp_path: Path) -> None: plan, reads = plan_of(playlist(FIRST, LATER)) licensed: list[UUID | None] = [] plan.license(licences(tmp_path, licensed)) assert list(plan.keys) == [0, 1] assert licensed == [KID] and reads == ["a.mp4"] assert isinstance(plan.drm, Widevine) and plan.drm.kids == [KID] and plan.track.drm == [plan.drm] plan.license_later(licences(tmp_path, licensed)) assert licensed == [KID, OTHER_KID] and reads == ["a.mp4", "b.mp4"] def test_the_first_licence_skips_the_key_tag_of_a_dropped_segment(tmp_path: Path) -> None: plan, reads = plan_of(playlist(FIRST, LATER), skip=1) licensed: list[UUID | None] = [] plan.license(licences(tmp_path, licensed)) assert list(plan.keys) == [0] and licensed == [OTHER_KID] and reads == ["b.mp4"] def merged(plan: HlsKeyPlan, start: int) -> tuple[m3u8.model.InitializationSection, bytes]: """The init segment and its bytes that the merge loop holds at the span that starts at `start`.""" init_section = next(span.init_section for span in plan.spans if span.start == start) return init_section, INITS[init_section.uri] def test_a_key_tag_that_comes_back_is_licensed_once_and_holds_the_keys_before_it(tmp_path: Path) -> None: plan, _ = plan_of(playlist(FIRST, LATER, FIRST)) licensed: list[UUID | None] = [] ctx = licences(tmp_path, licensed) plan.license(ctx) first = plan.drm assert isinstance(first, Widevine) first.content_keys[KID] = "a" * 32 later = plan.switch(ctx, plan.keys[1], first, merged(plan, 1)) assert isinstance(later, Widevine) later.content_keys[OTHER_KID] = "b" * 32 again = plan.switch(ctx, plan.keys[2], later, merged(plan, 2)) assert plan.keys[2] == plan.keys[0] and again is first assert licensed == [KID, OTHER_KID] assert later.content_keys == {KID: "a" * 32, OTHER_KID: "b" * 32} == again.content_keys def test_a_key_tag_that_comes_back_over_another_key_id_is_licensed_again(tmp_path: Path) -> None: plan, reads = plan_of(playlist(FIRST, LATER, FIRST.replace("a.mp4", "b.mp4"))) licensed: list[UUID | None] = [] ctx = licences(tmp_path, licensed) plan.license(ctx) plan.switch(ctx, plan.keys[1], plan.drm, merged(plan, 1)) again = plan.switch(ctx, plan.keys[2], plan.drm, merged(plan, 2)) assert plan.keys[2] == plan.keys[0] and again is not plan.drm assert isinstance(again, Widevine) and again.kids == [OTHER_KID] assert licensed == [KID, OTHER_KID, OTHER_KID] and reads == ["a.mp4"] def test_a_failed_key_fetch_in_the_merge_cancels_the_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: plan, _ = plan_of(playlist(FIRST, LATER)) ctx = licences(tmp_path, []) plan.license(ctx) def refused(key: Any, session: Any = None, kid: Any = None) -> Any: raise ConnectionError("EXAMPLE key server refused") monkeypatch.setattr(HLS, "get_drm", refused) try: with pytest.raises(ConnectionError): plan.switch(ctx, plan.keys[1], plan.drm, merged(plan, 1)) assert DOWNLOAD_CANCELLED.is_set() finally: DOWNLOAD_CANCELLED.clear() def test_the_first_licence_takes_the_first_tag_after_a_clear_lead_with_no_cdm(tmp_path: Path) -> None: plan, _ = plan_of(playlist(f'#EXT-X-MAP:URI="a.mp4"\n{CLEAR}', FIRST)) licensed: list[UUID | None] = [] plan.license(licences(tmp_path, licensed)) assert list(plan.keys.values()) == [None, plan.first] and licensed == [KID] def test_a_clear_span_has_no_key_tag() -> None: plan, reads = plan_of(playlist(FIRST, f'#EXT-X-MAP:URI="a.mp4"\n{CLEAR}')) assert list(plan.keys.values()) == [plan.first, None] and plan.first is not None assert not reads @pytest.mark.parametrize( "text, single", [ pytest.param(playlist(FIRST), True, id="one-key-one-init"), pytest.param(playlist(FIRST + "#EXTINF:6.0,\nnext.m4s\n"), True, id="two-segments"), pytest.param(playlist(FIRST, LATER), False, id="rotation"), pytest.param(playlist(FIRST + CLEAR), False, id="clear-tail"), pytest.param(playlist(FIRST.split("\n", 1)[1]), False, id="no-init-segment"), pytest.param(playlist(FIRST, FIRST), False, id="discontinuity"), ], ) def test_one_init_segment_and_one_key_tag_make_a_single_init_track(text: str, single: bool) -> None: plan, _ = plan_of(text) manifest = m3u8.loads(text) assert plan.single_init(manifest.segments) is single @pytest.mark.parametrize("system, drm_class", [("playready", PlayReady), ("widevine", Widevine)]) def test_a_track_with_only_fairplay_tags_is_bridged_and_keeps_no_tag(system: str, drm_class: type) -> None: text = playlist(f'#EXT-X-MAP:URI="a.mp4"\n{SKD_KEY}\n#EXTINF:6.0,\nseg.m4s\n') plan, reads = plan_of(text, cdm_type_stub(system), bridge=True) assert isinstance(plan.drm, drm_class) and plan.bridged is plan.drm and plan.drm.kids == [KID] assert plan.keys == {} and plan.first is None and plan.track.drm == [plan.drm] assert reads == ["a.mp4"] def test_a_key_tag_unshackle_cannot_use_is_refused_when_the_plan_is_built() -> None: text = playlist(f'#EXT-X-MAP:URI="a.mp4"\n{SKD_KEY}\n#EXTINF:6.0,\nseg.m4s\n') with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"): plan_of(text, cdm_type_stub("playready"))