diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md index 899d1e64..3c73c430 100644 --- a/docs/dev/service-architecture.md +++ b/docs/dev/service-architecture.md @@ -593,8 +593,8 @@ init segment that gives no real key ID does not count. A service that must choose the DRM system itself, or one that knows the key ID, puts the DRM object on the track: -1. Read the key ID from the init segment of the track. `HLS.get_track_kid_from_init` returns it. It reads - the first init segment of the playlist, unless you give it the init segment of the encrypted segments. +1. Read the key ID from the init segment of the encrypted segments. `HLS.get_track_kid_from_init` returns it + for the track, a reader of init segments (`HLS.init_reader(playlist, session)`) and that init segment. 2. Put a DRM object that names the key ID on the track: `drm_stub` from `unshackle.core.drm.cenc` with `"playready"` or `"widevine"` and the key ID. When only one of the two systems issues the content key, also set `track.drm_preference` to it. diff --git a/tests/core/test_cenc.py b/tests/core/test_cenc.py index 14542e9e..3df99ba5 100644 --- a/tests/core/test_cenc.py +++ b/tests/core/test_cenc.py @@ -294,5 +294,8 @@ def test_the_hls_probe_reads_the_pssh_kid_only_when_asked() -> None: track.get_key_id = lambda data: cenc.init_kid(data) # type: ignore[method-assign] - assert HLS.get_track_kid_from_init(manifest, track, session) is None - assert HLS.get_track_kid_from_init(manifest, track, session, pssh=True) == TRACK_KID + read_init = HLS.init_reader(manifest, session) + init_section = manifest.segments[0].init_section + + assert HLS.get_track_kid_from_init(track, read_init, init_section) is None + assert HLS.get_track_kid_from_init(track, read_init, init_section, pssh=True) == TRACK_KID diff --git a/tests/core/test_fairplay_bridge_hook.py b/tests/core/test_fairplay_bridge_hook.py index 59b37cc9..63b4ff96 100644 --- a/tests/core/test_fairplay_bridge_hook.py +++ b/tests/core/test_fairplay_bridge_hook.py @@ -18,8 +18,8 @@ from tests.core.test_hls_service_drm_keys import ( SKD_KEY, InitServer, download, + encrypted_init, hls_video, - init_kid_probe, playlist, ) from tests.lang_selection import test_kind_only_selection as harness @@ -68,16 +68,14 @@ class Bridged(Example): return "" if drm_system == "playready" else b"LIC" -def test_a_fairplay_only_track_is_refused_without_the_hook(tmp_path: Path, monkeypatch: Any) -> None: +def test_a_fairplay_only_track_is_refused_without_the_hook(tmp_path: Path) -> None: track = hls_video(tmp_path, playlist(SKD_KEY)) - probe = init_kid_probe(monkeypatch, KID) - session = InitServer() + session = InitServer(init=encrypted_init(KID)) with pytest.raises(NotImplementedError, match="None of the key systems are supported"): download(track, cdm_type_stub("playready"), session=session, fairplay_bridge=False) assert not track.drm - assert not probe.called assert not session.requests @@ -102,23 +100,27 @@ def test_a_bridged_challenge_goes_to_the_hook_and_every_other_to_the_system_call assert keys.service.calls == [(route, expected)] -def test_drm_preference_picks_the_system_of_the_stub(tmp_path: Path, monkeypatch: Any) -> None: +def test_drm_preference_picks_the_system_of_the_stub(tmp_path: Path) -> None: track = hls_video(tmp_path, playlist(SKD_KEY)) track.drm_preference = "pr" - init_kid_probe(monkeypatch, KID) licensed: list[str] = [] - download(track, cdm_type_stub("widevine"), lambda drm, track_kid=None: licensed.append(type(drm).__name__), True) + download( + track, + cdm_type_stub("widevine"), + lambda drm, track_kid=None: licensed.append(type(drm).__name__), + True, + InitServer(init=encrypted_init(KID)), + ) assert licensed == ["PlayReady"] assert track.drm is not None and track.drm[0].bridged -def test_the_drm_of_the_service_needs_no_hook(tmp_path: Path, monkeypatch: Any) -> None: +def test_the_drm_of_the_service_needs_no_hook(tmp_path: Path) -> None: """A service that puts its own stub on a FairPlay-only track keeps its route, with no hook.""" track = hls_video(tmp_path, playlist(SKD_KEY)) track.drm = [drm_stub("playready", [KID.hex])] - init_kid_probe(monkeypatch, KID) licensed: list[tuple[str, UUID | None]] = [] download( @@ -126,6 +128,7 @@ def test_the_drm_of_the_service_needs_no_hook(tmp_path: Path, monkeypatch: Any) cdm_type_stub("widevine"), lambda drm, track_kid=None: licensed.append((type(drm).__name__, track_kid)), licence_only=True, + session=InitServer(init=encrypted_init(KID)), fairplay_bridge=False, ) diff --git a/tests/core/test_hls_key_plan.py b/tests/core/test_hls_key_plan.py new file mode 100644 index 00000000..d4548d4f --- /dev/null +++ b/tests/core/test_hls_key_plan.py @@ -0,0 +1,187 @@ +"""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")) diff --git a/tests/core/test_hls_kid_from_init.py b/tests/core/test_hls_kid_from_init.py index b13643fd..b9eca499 100644 --- a/tests/core/test_hls_kid_from_init.py +++ b/tests/core/test_hls_kid_from_init.py @@ -3,7 +3,6 @@ from __future__ import annotations from functools import partial -from pathlib import Path from types import SimpleNamespace from typing import Any from uuid import UUID @@ -12,12 +11,10 @@ import m3u8 from pywidevine.license_protocol_pb2 import WidevinePsshData from pywidevine.pssh import PSSH -from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY from unshackle.core.drm import PlayReady, Widevine from unshackle.core.import_service import hls_playlist_kids from unshackle.core.manifests.hls import HLS -from unshackle.core.tracks import Video -from unshackle.core.tracks.track import DownloadContext, Track +from unshackle.core.tracks.track import Track INIT_KID = UUID("11111111-1111-1111-1111-111111111111") PSSH_KID = UUID("22222222-2222-2222-2222-222222222222") @@ -53,48 +50,6 @@ def key_of(pssh: str, extra: str = "") -> m3u8.Key: return m3u8.loads(playlist(keyed_segment(pssh, extra))).keys[0] -def licence_only(text: str, tmp_path: Path) -> list[tuple[list[UUID], Any]]: - """Run a licence-only download of the playlist and return the Key IDs of each licence call.""" - media = tmp_path / "media.m3u8" - media.write_text(text, encoding="utf-8") - track = Video( - url="https://example.test/media.m3u8", - language="en", - descriptor=Track.Descriptor.HLS, - codec=Video.Codec.AVC, - ) - track.from_file = media - licensed: list[tuple[list[UUID], Any]] = [] - ctx = DownloadContext( - save_path=tmp_path / "video.mp4", - save_dir=tmp_path / "video_segments", - progress=lambda **_: None, - license_widevine=lambda drm, track_kid=None: licensed.append((drm.kids, track_kid)), - cdm=None, - ) - DOWNLOAD_LICENCE_ONLY.set() - try: - HLS.download_track(track=track, ctx=ctx) - finally: - DOWNLOAD_LICENCE_ONLY.clear() - return licensed - - -def test_download_track_licenses_with_the_init_segment_kid(tmp_path: Path, monkeypatch: Any) -> None: - # the probe itself needs the network and FFprobe; the order of the calls is under test - monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: INIT_KID)) - assert licence_only(playlist(keyed_segment(NO_KID_PSSH)), tmp_path) == [([INIT_KID], INIT_KID)] - - -def test_licence_only_reads_each_later_key_from_its_own_init_segment(tmp_path: Path, monkeypatch: Any) -> None: - def probe(master: Any, track: Any, session: Any, init_section: Any = None) -> UUID: - return PSSH_KID if init_section is not None and init_section.uri == "init2.mp4" else INIT_KID - - monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(probe)) - text = playlist(keyed_segment(no_kid_pssh(b"first")), keyed_segment(no_kid_pssh(b"later"), init="init2.mp4")) - assert licence_only(text, tmp_path) == [([INIT_KID], INIT_KID), ([PSSH_KID], PSSH_KID)] - - def test_get_drm_keeps_a_pssh_that_has_its_own_kid() -> None: pssh = PSSH.new(key_ids=[PSSH_KID], system_id=PSSH.SystemId.Widevine).dumps() drm = HLS.get_drm(key_of(pssh), kid=INIT_KID) diff --git a/tests/core/test_hls_licence_only_key_rotation.py b/tests/core/test_hls_licence_only_key_rotation.py index 3fda4134..c42e3c88 100644 --- a/tests/core/test_hls_licence_only_key_rotation.py +++ b/tests/core/test_hls_licence_only_key_rotation.py @@ -45,7 +45,7 @@ seg1.m4s """ -def test_licence_only_licenses_a_key_that_starts_part_way(tmp_path: Path, monkeypatch: Any) -> None: +def test_licence_only_licenses_a_key_that_starts_part_way(tmp_path: Path) -> None: playlist = tmp_path / "media.m3u8" playlist.write_text(PLAYLIST, encoding="utf-8") track = Video( @@ -55,8 +55,6 @@ def test_licence_only_licenses_a_key_that_starts_part_way(tmp_path: Path, monkey codec=Video.Codec.HEVC, ) track.from_file = playlist - # the KID normally comes from the init segment; this test is offline - monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: None)) licensed: list[UUID] = [] ctx = DownloadContext( @@ -77,7 +75,7 @@ def test_licence_only_licenses_a_key_that_starts_part_way(tmp_path: Path, monkey assert track.data["hls"]["unwanted_segments"] == [] -def test_a_refused_later_key_fails_through_the_licence_step(tmp_path: Path, monkeypatch: Any) -> None: +def test_a_refused_later_key_fails_through_the_licence_step(tmp_path: Path) -> None: """The rotation loop licenses each later key through the licence step, so a refusal shows FAILED and cancels.""" playlist = tmp_path / "media.m3u8" playlist.write_text(PLAYLIST, encoding="utf-8") @@ -88,7 +86,6 @@ def test_a_refused_later_key_fails_through_the_licence_step(tmp_path: Path, monk codec=Video.Codec.HEVC, ) track.from_file = playlist - monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: None)) def licence(drm: Any, track_kid: Any = None) -> None: if track_kid == LATER_KID: @@ -115,11 +112,10 @@ def test_a_refused_later_key_fails_through_the_licence_step(tmp_path: Path, monk assert statuses == ["LICENSING", "[yellow]LICENSED", "LICENSING", "[red]FAILED"] -def test_licence_only_skips_the_key_of_a_filtered_segment(tmp_path: Path, monkeypatch: Any) -> None: +def test_licence_only_skips_the_key_of_a_filtered_segment(tmp_path: Path) -> None: """The filtered segment URIs go to the track data, and an import filter built from them drops the same segment.""" playlist = tmp_path / "media.m3u8" playlist.write_text(PLAYLIST, encoding="utf-8") - monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: None)) def licence_only(segment_filter: Any) -> tuple[list[UUID], list[str]]: track = Video( @@ -152,13 +148,10 @@ def test_licence_only_skips_the_key_of_a_filtered_segment(tmp_path: Path, monkey assert licence_only(segment_uri_filter(unwanted)) == (licensed, unwanted) -def test_licence_only_warns_when_no_dropped_segment_is_in_the_playlist( - tmp_path: Path, monkeypatch: Any, caplog: Any -) -> None: +def test_licence_only_warns_when_no_dropped_segment_is_in_the_playlist(tmp_path: Path, caplog: Any) -> None: """A changed host or path makes an exported list match nothing, and the download then keeps every segment.""" playlist = tmp_path / "media.m3u8" playlist.write_text(PLAYLIST, encoding="utf-8") - monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: None)) track = Video( url="https://example.test/media.m3u8", language="en", diff --git a/tests/core/test_hls_service_drm_keys.py b/tests/core/test_hls_service_drm_keys.py index 3b26fa0f..d1f868d9 100644 --- a/tests/core/test_hls_service_drm_keys.py +++ b/tests/core/test_hls_service_drm_keys.py @@ -9,7 +9,6 @@ from __future__ import annotations from pathlib import Path from types import SimpleNamespace from typing import Any -from unittest.mock import Mock from uuid import UUID import m3u8 @@ -98,13 +97,6 @@ def download( DOWNLOAD_LICENCE_ONLY.clear() -def init_kid_probe(monkeypatch: Any, kid: UUID | None) -> Mock: - """The KID normally comes from the init segment; these tests are offline.""" - probe = Mock(return_value=kid) - monkeypatch.setattr(HLS, "get_track_kid_from_init", probe) - return probe - - def test_key_tags_no_licence_route_can_use_are_dropped() -> None: manifest = m3u8.loads(playlist(SKD_KEY)) @@ -112,7 +104,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, key_spans(manifest, manifest.segments), None, None) + assert all(not span.keys for span in key_spans(manifest, manifest.segments)) @pytest.mark.parametrize( @@ -171,21 +163,20 @@ def test_only_a_key_tag_of_a_drm_system_is_unsupported(text: str, unsupported: b def test_the_server_builds_no_stub_for_an_identity_sample_aes_track(tmp_path: Path, monkeypatch: Any) -> None: monkeypatch.setattr("unshackle.core.tracks.track.utf8_text", lambda response: playlist(IDENTITY_KEY)) track = hls_video(tmp_path, playlist(IDENTITY_KEY)) - probe = init_kid_probe(monkeypatch, KID) + session = InitServer(init=encrypted_init(KID)) - assert not track.load_drm_from_playlist(InitServer(), bridge=True) + assert not track.load_drm_from_playlist(session, bridge=True) assert not track.drm - assert not probe.called + assert "init.mp4" not in session.requests def test_a_playlist_with_no_key_tag_is_left_alone() -> None: assert not HLS.drop_unsupported_keys(m3u8.loads(playlist())) -def test_the_drm_of_the_service_licenses_the_track(tmp_path: Path, monkeypatch: Any) -> None: +def test_the_drm_of_the_service_licenses_the_track(tmp_path: Path) -> None: track = hls_video(tmp_path, playlist(SKD_KEY)) track.drm = [drm_stub("playready", [KID.hex])] - init_kid_probe(monkeypatch, KID) licensed: list[tuple[str, UUID | None]] = [] download( @@ -193,6 +184,7 @@ def test_the_drm_of_the_service_licenses_the_track(tmp_path: Path, monkeypatch: None, lambda drm, track_kid=None: licensed.append((type(drm).__name__, track_kid)), licence_only=True, + session=InitServer(init=encrypted_init(KID)), ) assert licensed == [("PlayReady", KID)] @@ -201,10 +193,10 @@ def test_the_drm_of_the_service_licenses_the_track(tmp_path: Path, monkeypatch: @pytest.mark.parametrize("method", ["SAMPLE-AES", "SAMPLE-AES-CTR"]) @pytest.mark.parametrize("system, drm_class", [("playready", "PlayReady"), ("widevine", "Widevine")]) def test_a_track_with_no_drm_licenses_through_the_cdm( - tmp_path: Path, monkeypatch: Any, caplog: pytest.LogCaptureFixture, system: str, drm_class: str, method: str + tmp_path: Path, caplog: pytest.LogCaptureFixture, system: str, drm_class: str, method: str ) -> None: track = hls_video(tmp_path, playlist(SKD_KEY.replace("SAMPLE-AES", method))) - probe = init_kid_probe(monkeypatch, KID) + session = InitServer(init=encrypted_init(KID)) licensed: list[tuple[str, list[UUID], UUID | None]] = [] with caplog.at_level("DEBUG", logger="HLS"): @@ -213,11 +205,12 @@ def test_a_track_with_no_drm_licenses_through_the_cdm( cdm_type_stub(system), lambda drm, track_kid=None: licensed.append((type(drm).__name__, drm.kids, track_kid)), licence_only=True, + session=session, ) assert licensed == [(drm_class, [KID], KID)] assert [type(drm).__name__ for drm in track.drm] == [drm_class] - assert probe.call_count == 1 + assert session.requests == ["init.mp4"] lines = [record.getMessage() for record in caplog.records if KID.hex in record.getMessage()] assert len(lines) == 1 and track.id in lines[0] and drm_class in lines[0] @@ -238,24 +231,24 @@ def two_inits(between: str, lead_key: str = "") -> str: ], ) def test_the_key_id_comes_from_the_init_segment_of_the_encrypted_segments( - tmp_path: Path, monkeypatch: Any, text: str, skip_lead: bool + tmp_path: Path, text: str, skip_lead: bool ) -> None: track = hls_video(tmp_path, text) if skip_lead: track.OnSegmentFilter = lambda segment: segment.uri.startswith("ad") licensed: list[UUID | None] = [] - init_kid_probe(monkeypatch, None).side_effect = lambda master, track, session, init_section=None, pssh=False: { - "init.mp4": KID - }.get(init_section.uri) + session = InitServer(ad=encrypted_init(OTHER_KID), init=encrypted_init(KID)) download( track, cdm_type_stub("playready"), lambda drm, track_kid=None: licensed.append(track_kid), licence_only=True, + session=session, ) assert licensed == [KID] + assert session.requests == ["init.mp4"] def filter_first_segment(track: Video) -> None: @@ -265,15 +258,20 @@ def filter_first_segment(track: Video) -> None: @pytest.mark.parametrize( "cdm", [pytest.param(cdm_type_stub("playready"), id="bridge"), pytest.param(None, id="refused")] ) -def test_a_key_tag_on_a_skipped_segment_stays_in_force(tmp_path: Path, monkeypatch: Any, cdm: Any) -> None: +def test_a_key_tag_on_a_skipped_segment_stays_in_force(tmp_path: Path, cdm: Any) -> None: """python-m3u8 puts a key tag on the next segment only, and ``--sample`` can skip that segment.""" track = hls_video(tmp_path, playlist(SKD_KEY)) filter_first_segment(track) - init_kid_probe(monkeypatch, KID) licensed: list[UUID | None] = [] def run() -> None: - download(track, cdm, lambda drm, track_kid=None: licensed.append(track_kid), licence_only=True) + download( + track, + cdm, + lambda drm, track_kid=None: licensed.append(track_kid), + licence_only=True, + session=InitServer(init=encrypted_init(KID)), + ) if cdm: run() @@ -296,17 +294,25 @@ TWO_KEYS = playlist(SKD_KEY).replace("seg0.m4s\n", f"seg0.m4s\n{SKD_KEY.replace( ], ) def test_one_keyed_init_segment_reads_its_pssh_only_in_a_one_key_playlist( - tmp_path: Path, monkeypatch: Any, text: str, skip_first: bool, pssh: bool + tmp_path: Path, text: str, skip_first: bool, pssh: bool ) -> None: """With an all-zero tenc, a decrypter gives the one content key to every segment, so a second key is garbage.""" track = hls_video(tmp_path, text) if skip_first: filter_first_segment(track) - probe = init_kid_probe(monkeypatch, KID) + licensed: list[UUID | None] = [] + session = InitServer() - download(track, cdm_type_stub("playready"), lambda drm, track_kid=None: None, licence_only=True) + if pssh: + download( + track, cdm_type_stub("playready"), lambda drm, track_kid=None: licensed.append(track_kid), True, session + ) + else: + with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"): + download(track, cdm_type_stub("playready"), session=session) - assert [call.kwargs["pssh"] for call in probe.call_args_list] == [pssh] + assert licensed == ([KID] if pssh else []) + assert session.requests == ["init.mp4"] OTHER_KID = UUID("44444444-4444-4444-4444-444444444444") @@ -335,6 +341,10 @@ def stitched(*inits: str, keyed_from: int = 1, clear_from: int | None = None) -> return f"#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-TARGETDURATION:6\n{body}#EXT-X-ENDLIST\n" +def read_init(manifest: m3u8.M3U8, session: Session) -> Any: + return HLS.init_reader(manifest, session) + + class InitServer(Session): """A session that serves a clear lead and a main init with an all-zero tenc by name, and the given ``files``. @@ -421,7 +431,9 @@ def test_the_key_id_of_two_keys_comes_from_the_init_after_a_method_none_lead(tmp manifest = m3u8.loads(text, "https://example.test/media.m3u8") session = InitServer(real=encrypted_init(KID)) - assert HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), session) == [KID] + assert HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), read_init(manifest, session)) == [ + KID + ] assert session.requests == ["real.mp4"] @@ -488,7 +500,7 @@ def test_a_first_encrypted_init_with_no_key_id_stops_the_reads(tmp_path: Path) - manifest = m3u8.loads(stitched("lead.mp4", "init.mp4", "tail.mp4"), "https://example.test/media.m3u8") session = InitServer(init=encrypted_init(ZERO_KID), tail=ZERO_INIT) - assert HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), session) == [] + assert HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), read_init(manifest, session)) == [] assert session.requests == ["init.mp4"] @@ -498,7 +510,9 @@ def test_an_all_zero_key_id_from_ffprobe_reads_the_pssh(tmp_path: Path, monkeypa manifest = m3u8.loads(stitched("lead.mp4", "init.mp4", "lead.mp4"), "https://example.test/media.m3u8") session = InitServer() - assert HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), session) == [KID] + assert HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), read_init(manifest, session)) == [ + KID + ] def test_a_stitched_playlist_with_two_keys_is_refused(tmp_path: Path) -> None: @@ -513,7 +527,7 @@ def test_a_first_init_segment_that_cannot_be_read_stops_the_reads(tmp_path: Path session = InitServer(init=None) manifest = m3u8.loads(stitched("lead.mp4", "init.mp4", "tail.mp4"), "https://example.test/media.m3u8") - assert HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), session) == [] + assert HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), read_init(manifest, session)) == [] assert session.requests == ["init.mp4"] @@ -713,33 +727,34 @@ def test_the_server_takes_the_same_key_id_of_a_stitched_playlist( ], ) def test_a_track_with_no_drm_that_cannot_be_bridged_is_refused_before_the_download( - tmp_path: Path, monkeypatch: Any, text: str, kid: UUID | None, cdm: Any + tmp_path: Path, text: str, kid: UUID | None, cdm: Any ) -> None: track = hls_video(tmp_path, text) - probe = init_kid_probe(monkeypatch, kid) - session = InitServer() + session = InitServer(init=encrypted_init(kid or ZERO_KID)) with pytest.raises(NotImplementedError, match="None of the key systems are supported: SAMPLE-AES"): download(track, cdm, session=session) assert not track.drm - assert probe.called == (kid != KID) - assert not session.requests + assert session.requests == ([] if kid == KID else ["init.mp4"]) -def test_a_licence_with_no_content_key_stops_the_bridge_before_a_segment(tmp_path: Path, monkeypatch: Any) -> None: +def test_a_licence_with_no_content_key_stops_the_bridge_before_a_segment(tmp_path: Path) -> None: track = hls_video(tmp_path, playlist(SKD_KEY)) - init_kid_probe(monkeypatch, KID) with pytest.raises(PlayReady.Exceptions.CEKNotFound, match=KID.hex): - download(track, cdm_type_stub("playready"), lambda drm, track_kid=None: None) + download( + track, + cdm_type_stub("playready"), + lambda drm, track_kid=None: None, + session=InitServer(init=encrypted_init(KID)), + ) -def test_a_track_whose_drm_cannot_stand_in_is_refused_before_the_download(tmp_path: Path, monkeypatch: Any) -> None: +def test_a_track_whose_drm_cannot_stand_in_is_refused_before_the_download(tmp_path: Path) -> None: """The refusal comes before a segment is requested: a ClearKey would otherwise write the ciphertext as the output.""" track = hls_video(tmp_path, playlist(SKD_KEY)) track.drm = [ClearKey(key=bytes(16))] - init_kid_probe(monkeypatch, KID) with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"): download(track, cdm_type_stub("playready")) diff --git a/tests/core/test_request_record.py b/tests/core/test_request_record.py index c73db6c8..25331e6b 100644 --- a/tests/core/test_request_record.py +++ b/tests/core/test_request_record.py @@ -499,7 +499,11 @@ def test_hls_media_probes_are_not_recorded_but_the_playlist_is(server, debug_log HLS.probe_ts_info(f"{server.url}/v.m3u8", session) playlist = m3u8.loads(server.docs["/v.m3u8"], uri=f"{server.url}/v.m3u8") HLS.fetch_init_section(session, playlist.segments[0].init_section, 0) - HLS.get_track_kid_from_init(playlist, SimpleNamespace(get_key_id=lambda _: None), session) # type: ignore[arg-type] + HLS.get_track_kid_from_init( + SimpleNamespace(get_key_id=lambda _: None), # type: ignore[arg-type] + HLS.init_reader(playlist, session), + playlist.segments[0].init_section, + ) assert (server.hits.count("/seg.ts"), server.hits.count("/init.mp4")) == (1, 2) assert paths(debug_log) == ["/v.m3u8"] diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py index 0b060f65..0536ba70 100644 --- a/unshackle/core/manifests/hls.py +++ b/unshackle/core/manifests/hls.py @@ -28,10 +28,9 @@ from pywidevine.pssh import PSSH as WV_PSSH from requests import Session from unshackle.core import binaries -from unshackle.core.cdm.choice import drm_system -from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_widevine_cdm +from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm, is_widevine_cdm from unshackle.core.config import config -from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack +from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY, AnyTrack from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, MonaLisa, PlayReady, Widevine from unshackle.core.drm.bbts import renumber_continuity from unshackle.core.drm.cenc import ( @@ -50,15 +49,13 @@ 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, keyformat +from unshackle.core.manifests.hls_keys import ReadInit, key_spans, keyformat from unshackle.core.manifests.segment_pipeline import ( append_segment, check_decrypted, check_merged, complete_track, fetch_segments, - license_drm, - licensing, ) from unshackle.core.session import RnetResponse, RnetSession, unrecorded, utf8_text from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video @@ -614,19 +611,6 @@ class HLS: return None - @staticmethod - def resolve_segment_key( - segment_keys: list[m3u8.model.SessionKey | m3u8.model.Key], - cdm: object, - drm_preference: str | None = None, - ) -> m3u8.Key | None: - """Pick the EXT-X-KEY for a segment, preferring one the CDM can handle.""" - if cdm: - cdm_segment_keys = HLS.filter_keys_for_cdm(segment_keys, cdm, drm_preference) - if cdm_segment_keys: - return HLS.get_supported_key(cdm_segment_keys) - return HLS.get_supported_key(segment_keys) - @staticmethod def fetch_init_section( session: Session | RnetSession, @@ -648,28 +632,6 @@ class HLS: res.raise_for_status() return res.content, range_offset - @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, - ) -> bool: - """Whether every wanted segment shares one init segment and one EXT-X-KEY, with no discontinuity. - - 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 len(spans) != 1 or not spans[0].init_section or any(s.discontinuity for s in wanted_segments[1:]): - return False - - if not spans[0].keys: - return True - # 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(spans[0].keys, cdm, drm_preference) == initial_key - @staticmethod def download_track(track: AnyTrack, ctx: DownloadContext) -> None: session = ctx.ensure_session() @@ -721,95 +683,26 @@ class HLS: if ctx.on_segments: ctx.on_segments(track, wanted_segments) - # 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 = None - if ( - session_drm is None - and ctx.fairplay_bridge - and (system := drm_system(track.drm_preference) or cdm_system(cdm)) - ): - 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 IDs {', '.join(kid.hex for kid in bridge_drm.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") + from unshackle.core.manifests.hls_key_plan import HlsKeyPlan # a module-level import would be circular - 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 = 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 - - if media_playlist_key: - init_kid = ( - None - if media_playlist_key.method == "AES-128" - 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)): - # Preserve pre-existing keys (e.g. from server_cdm) - if track.drm: - for existing_drm in track.drm: - if hasattr(existing_drm, "content_keys") and existing_drm.content_keys: - media_drm.content_keys.update(existing_drm.content_keys) - track.drm = [media_drm] - if DOWNLOAD_ALL_DRM.is_set(): - track.drm += HLS.alternate_drm(media_keys, media_drm, session, init_kid) - license_drm(track, media_drm, ctx, init_kid) - initial_drm_licensed = True - initial_drm_key = media_playlist_key - session_drm = media_drm - elif isinstance(media_drm, ClearKey): - # AES-128 (ClearKey) needs no license server - the key is already fetched. - track.drm = [media_drm] - session_drm = media_drm - initial_drm_key = media_playlist_key - initial_drm_licensed = True - - bridged_drm = session_drm if isinstance(session_drm, (Widevine, PlayReady)) and session_drm.bridged else None - if not initial_drm_licensed: - for kid in bridged_drm.kids if bridged_drm else (None,): - license_drm( - track, session_drm, ctx, kid, probe=lambda: HLS.get_track_kid_from_init(master, track, session) - ) + plan = HlsKeyPlan.build( + master, wanted_segments, track, cdm, bool(ctx.fairplay_bridge), HLS.init_reader(master, session), session + ) + plan.license(ctx) + session_drm = plan.drm 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 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, span.init_section) - license_drm(track, later_drm, ctx) + plan.license_later(ctx) progress(downloaded="[yellow]SKIPPED") return - if bridged_drm and (missing := [kid for kid in bridged_drm.kids if kid not in bridged_drm.content_keys]): + if (bridged_drm := plan.bridged) and ( + missing := [kid for kid in bridged_drm.kids if kid not in bridged_drm.content_keys] + ): raise bridged_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. - single_init = HLS.single_init_no_rotation(wanted_segments, spans, initial_drm_key, cdm, track.drm_preference) + single_init = plan.single_init(wanted_segments) use_segment_decrypt = ( isinstance(session_drm, (Widevine, PlayReady)) and can_use(session_drm, config.decryption) and single_init ) @@ -936,7 +829,7 @@ class HLS: media_sequence_start = getattr(master, "media_sequence", None) or 0 encryption_data: tuple[m3u8.Key | None, DRM_T] | None = None if session_drm: - encryption_data = (initial_drm_key, session_drm) + encryption_data = (plan.first, session_drm) def merge(to: Path, via: list[Path], delete: bool = False, include_map_data: bool = False) -> None: """ @@ -1074,16 +967,15 @@ 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 + new_span = False 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 + new_span = i in plan.keys + key = plan.keys.get(i) key_changed = bool(new_span and i and encryption_data and encryption_data[0] != key) if isinstance(track, Subtitle): @@ -1127,20 +1019,8 @@ class HLS: if key is None: encryption_data = (None, session_drm) if isinstance(session_drm, MonaLisa) else None elif not encryption_data or encryption_data[0] != key: - with licensing(ctx): - init_kid = track.get_key_id(map_data[1]) if map_data and key.method != "AES-128" else None - drm = HLS.get_drm(key, session, **({"kid": init_kid} if init_kid else {})) - license_drm(track, drm, ctx, init_kid) - if ( - encryption_data - and isinstance(drm, (Widevine, PlayReady)) - and isinstance(encryption_data[1], type(drm)) - and isinstance(encryption_data[1], (Widevine, PlayReady)) - and getattr(encryption_data[1], "content_keys", None) - ): - for prev_kid, prev_key in encryption_data[1].content_keys.items(): - drm.content_keys.setdefault(prev_kid, prev_key) - encryption_data = (key, drm) + previous = encryption_data[1] if encryption_data else None + encryption_data = (key, plan.switch(ctx, key, previous, map_data)) if is_last_segment: # required as it won't end with EXT-X-DISCONTINUITY nor a new key @@ -1457,24 +1337,16 @@ class HLS: @staticmethod def get_track_kid_from_init( - master: M3U8, - track: Track, - session: Session | RnetSession, - init_section: m3u8.model.InitializationSection | None = None, - pssh: bool = False, + track: Track, read_init: ReadInit, init_section: m3u8.model.InitializationSection, pssh: bool = False ) -> UUID | None: """ - Extract the track's Key ID from an init segment (EXT-X-MAP), by default the first in the playlist. + The track's Key ID from the init segment (EXT-X-MAP) that `read_init` reads. With `pssh`, an init segment with an all-zero tenc Key ID gives the one Key ID that its pssh boxes name. - Returns None if no init segment exists or KID extraction fails. + Returns None if the init segment cannot be read or KID extraction fails. The caller should fall back to drm.kid from the PSSH if this returns None. """ - map_section = init_section or next((seg.init_section for seg in master.segments if seg.init_section), None) - if not map_section: - return None - - init_data = HLS.probe_init_section(master, session, map_section) + init_data = read_init(init_section) if init_data is None: return None try: @@ -1483,9 +1355,25 @@ class HLS: return init_pssh_kid(init_data) return kid except Exception as e: - logging.getLogger("HLS").debug(f"Init map key-id probe failed for {map_section.uri}: {e!r}") + logging.getLogger("HLS").debug(f"Init map key-id probe failed for {init_section.uri}: {e!r}") return None + @staticmethod + def init_reader(master: M3U8, session: Session | RnetSession) -> ReadInit: + """A reader of the init segments (EXT-X-MAP) of `master` that requests each one once. + + It gives None when the request fails: the caller falls back without the init segment. + """ + read: dict[tuple[str | None, str | None, str | None], bytes | None] = {} + + def read_init(init_section: m3u8.model.InitializationSection) -> bytes | None: + at = (init_section.base_uri, init_section.uri, init_section.byterange) + if at not in read: + read[at] = HLS.probe_init_section(master, session, init_section) + return read[at] + + return read_init + @staticmethod def probe_init_section( master: M3U8, session: Session | RnetSession, init_section: m3u8.model.InitializationSection @@ -1542,9 +1430,7 @@ class HLS: raise NotImplementedError(f"None of the key systems are supported: {', '.join(unsupported_systems)}") @staticmethod - def get_bridge_kids( - manifest: M3U8, segments: list[Any], track: Track, session: Session | RnetSession - ) -> list[UUID]: + def get_bridge_kids(manifest: M3U8, segments: list[Any], track: Track, read_init: ReadInit) -> list[UUID]: """The real Key IDs of the init segments of the `segments` entries with an EXT-X-KEY unshackle cannot license. A real first Key ID adds each other real tenc Key ID once, in playlist order. Empty when `only_unsupported_keys` @@ -1563,20 +1449,17 @@ class HLS: if span.init_section not in init_sections: init_sections.append(span.init_section) if one_key and len(init_sections) > 1: - kids = HLS.get_stitched_kids(manifest, init_sections, track, session) + kids = HLS.get_stitched_kids(init_sections, track, read_init) else: - kid = HLS.get_track_kid_from_init(manifest, track, session, init_sections[0], pssh=one_key) + kid = HLS.get_track_kid_from_init(track, read_init, init_sections[0], pssh=one_key) if kid is None or kid in PLACEHOLDER_KIDS: return [] - kids = [kid, *HLS.get_later_kids(manifest, init_sections[1:], track, session)] + kids = [kid, *HLS.get_later_kids(init_sections[1:], track, read_init)] return [] if not kids or kids[0] in PLACEHOLDER_KIDS else list(dict.fromkeys(kids)) @staticmethod def get_stitched_kids( - manifest: M3U8, - init_sections: list[m3u8.model.InitializationSection], - track: Track, - session: Session | RnetSession, + init_sections: list[m3u8.model.InitializationSection], track: Track, read_init: ReadInit ) -> 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. @@ -1585,7 +1468,7 @@ class HLS: """ found: UUID | None = None for i, init_section in enumerate(init_sections): - init_data = HLS.probe_init_section(manifest, session, init_section) + init_data = read_init(init_section) if not init_data: return [] try: @@ -1595,7 +1478,7 @@ class HLS: if not (kid and kid.int): kid = init_pssh_kid(init_data) elif found is None: - return [kid, *HLS.get_later_kids(manifest, init_sections[i + 1 :], track, session)] + return [kid, *HLS.get_later_kids(init_sections[i + 1 :], track, read_init)] except Exception as e: logging.getLogger("HLS").debug(f"Init map key-id probe failed for {init_section.uri}: {e!r}") return [] @@ -1607,13 +1490,10 @@ class HLS: @staticmethod def get_later_kids( - manifest: M3U8, - init_sections: list[m3u8.model.InitializationSection], - track: Track, - session: Session | RnetSession, + init_sections: list[m3u8.model.InitializationSection], track: Track, read_init: ReadInit ) -> 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) + kids = (HLS.get_track_kid_from_init(track, read_init, init_section) for init_section in init_sections) return [kid for kid in kids if kid and kid not in PLACEHOLDER_KIDS] @staticmethod @@ -1722,9 +1602,9 @@ class HLS: try: return HLS.get_drm(key, session) except Widevine.Exceptions.KIDNotFound: - kid = HLS.get_track_kid_from_init( - master, track, probe_session or session or run_proxy.fallback_session(), init_section - ) + init_section = init_section or next((s.init_section for s in master.segments if s.init_section), None) + read_init = HLS.init_reader(master, probe_session or session or run_proxy.fallback_session()) + kid = init_section and HLS.get_track_kid_from_init(track, read_init, init_section) if not kid: raise return HLS.get_drm(key, session, kid=kid) diff --git a/unshackle/core/manifests/hls_key_plan.py b/unshackle/core/manifests/hls_key_plan.py new file mode 100644 index 00000000..c086b363 --- /dev/null +++ b/unshackle/core/manifests/hls_key_plan.py @@ -0,0 +1,205 @@ +"""The EXT-X-KEY plan of an HLS track: the tag, Key ID and DRM of each keyed span of its wanted segments.""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass, field +from typing import Any +from uuid import UUID + +import m3u8 +from m3u8 import M3U8 + +from unshackle.core.cdm.choice import drm_system +from unshackle.core.cdm.detect import cdm_system +from unshackle.core.constants import DOWNLOAD_ALL_DRM, AnyTrack +from unshackle.core.drm import DRM_T, PlayReady, Widevine +from unshackle.core.manifests.hls import HLS +from unshackle.core.manifests.hls_keys import KeySpan, ReadInit, key_spans +from unshackle.core.manifests.segment_pipeline import license_drm, licensing +from unshackle.core.tracks.track import DownloadContext + + +def segment_key(keys: list[m3u8.model.Key], cdm: object, drm_preference: str | None = None) -> m3u8.Key | None: + """The EXT-X-KEY of a span that unshackle uses, one the CDM can license first; None for METHOD=NONE.""" + if cdm and (cdm_keys := HLS.filter_keys_for_cdm(keys, cdm, drm_preference)): + return HLS.get_supported_key(cdm_keys) + return HLS.get_supported_key(keys) + + +@dataclass +class HlsKeyPlan: + """Which EXT-X-KEY tag, Key ID and DRM decrypt each keyed span of the wanted segments of an HLS track. + + `keys` maps the start of each keyed span to its EXT-X-KEY tag. `drm` is the DRM in force before the first + tag: the track's own DRM or a FairPlay bridge stub, until `license` puts the DRM of the first tag in its place. + Each pair of tag and init Key ID gets one DRM and one licence. + """ + + track: AnyTrack + session: Any + read_init: ReadInit + spans: list[KeySpan] + keys: dict[int, m3u8.model.Key | None] + drm: DRM_T | None + first_init: m3u8.model.InitializationSection | None = None + drms: dict[tuple[str, str | None, tuple[tuple[str, Any], ...], UUID | None], DRM_T] = field(default_factory=dict) + + @classmethod + def build( + cls, + manifest: M3U8, + wanted_segments: list[Any], + track: AnyTrack, + cdm: object, + bridge: bool, + read_init: ReadInit, + session: Any, + ) -> HlsKeyPlan: + """The plan of `wanted_segments`, which bridges a track with no DRM when `bridge` is true. + + A bridged track, or one whose own DRM stands in, loses the EXT-X-KEY tags of `manifest`, and the bridge stub + becomes its DRM. Raises NotImplementedError for a keyed span with no EXT-X-KEY tag that unshackle can use. + """ + log = logging.getLogger("HLS") + drm = track.get_drm_for_cdm(cdm) if track.drm else None + stub = None + if drm is None and bridge and (system := drm_system(track.drm_preference) or cdm_system(cdm)): + kids = HLS.get_bridge_kids(manifest, wanted_segments, track, read_init) + stub = HLS.bridge_stub(system, kids) if kids else None + if stub: + HLS.drop_unsupported_keys(manifest) + drm = stub + track.drm = [stub] + log.debug( + f"{track.id}: licensing key IDs {', '.join(kid.hex for kid in stub.kids)} " + f"of its init segments as {stub.NAME}" + ) + elif isinstance(drm, (Widevine, PlayReady)) and HLS.drop_unsupported_keys(manifest): + log.debug(f"{track.id}: its key tags name key systems unshackle cannot license, using the DRM of the track") + + spans = key_spans(manifest, wanted_segments) + keys = {span.start: segment_key(span.keys, cdm, track.drm_preference) for span in spans if span.keys} + first_init = next((segment.init_section for segment in manifest.segments if segment.init_section), None) + return cls(track, session, read_init, spans, keys, drm, first_init) + + @property + def first(self) -> m3u8.model.Key | None: + """The first EXT-X-KEY tag of the wanted segments that is not METHOD=NONE.""" + return next((key for key in self.keys.values() if key), None) + + @property + def bridged(self) -> Widevine | PlayReady | None: + """The DRM in force when it is a bridge stub, of this run or preset by the server.""" + return self.drm if isinstance(self.drm, (Widevine, PlayReady)) and self.drm.bridged else None + + def kid( + self, + key: m3u8.model.Key, + init_section: m3u8.model.InitializationSection | None, + read_init: ReadInit | None = None, + ) -> UUID | None: + """The Key ID of the init segment of a span under `key`; an AES-128 key, or a span with no init, has none.""" + if key.method == "AES-128" or init_section is None: + return None + return HLS.get_track_kid_from_init(self.track, read_init or self.read_init, init_section) + + def key_drm(self, key: m3u8.model.Key, kid: UUID | None) -> tuple[DRM_T, bool]: + """The DRM of `key` with the init Key ID `kid`, and whether this call built it. + + The cache reads the extra attributes of the tag too: `str(key)` leaves out KEYID, and an m3u8 tag object is not + hashable. + """ + at = (str(key), key.base_uri, tuple(sorted(key._extra_params.items())), kid) + if at in self.drms: + return self.drms[at], False + drm = self.drms[at] = HLS.get_drm(key, self.session, **({"kid": kid} if kid else {})) + return drm, True + + def license(self, ctx: DownloadContext) -> None: + """License the DRM in force at the first wanted segment. + + The DRM of the first EXT-X-KEY tag replaces the track's DRM and keeps its content keys; under --all-drm the + tag of the other system joins it. Without an EXT-X-KEY tag it licenses the track's own DRM, a bridge stub once + per Key ID. + """ + span = next((span for span in self.spans if self.keys.get(span.start)), None) + if span is None: + bridged = self.bridged + for kid in bridged.kids if bridged else (None,): + license_drm(self.track, self.drm, ctx, kid, probe=self.first_kid) + return + key = self.keys[span.start] + assert key is not None + kid = self.kid(key, span.init_section) + drm, _ = self.key_drm(key, kid) + if isinstance(drm, (Widevine, PlayReady)): + for held in self.track.drm or []: + drm.content_keys.update(getattr(held, "content_keys", None) or {}) + self.drm = drm + self.track.drm = [drm] + if not isinstance(drm, (Widevine, PlayReady)): + return + if DOWNLOAD_ALL_DRM.is_set(): + tags = {id(tag): tag for span in self.spans for tag in span.keys if tag} + self.track.drm += HLS.alternate_drm(list(tags.values()), drm, self.session, kid) + license_drm(self.track, drm, ctx, kid) + + def license_later(self, ctx: DownloadContext) -> None: + """License each later pair of EXT-X-KEY tag and init Key ID once. + + It fetches no AES-128 key: a licence-only run needs none. + """ + for span in self.spans: + key = self.keys.get(span.start) + if key is None or key.method == "AES-128": + continue + kid = self.kid(key, span.init_section) + drm, new = self.key_drm(key, kid) + if new: + license_drm(self.track, drm, ctx, kid) + + def switch( + self, + ctx: DownloadContext, + key: m3u8.model.Key, + previous: DRM_T | None, + map_data: tuple[m3u8.model.InitializationSection, bytes] | None, + ) -> DRM_T: + """The licensed DRM of `key` for the init segment in `map_data`, with the content keys of `previous` as well. + + The Key ID comes from the init bytes the merge holds. A pair of tag and Key ID gets one licence, and only + content keys of the same DRM system carry over. + """ + init_section, init_data = map_data or (None, b"") + with licensing(ctx): + kid = self.kid(key, init_section, lambda _: init_data) + drm, new = self.key_drm(key, kid) + if new: + license_drm(self.track, drm, ctx, kid) + if ( + isinstance(drm, (Widevine, PlayReady)) + and isinstance(previous, (Widevine, PlayReady)) + and isinstance(previous, type(drm)) + ): + for prev_kid, prev_key in previous.content_keys.items(): + drm.content_keys.setdefault(prev_kid, prev_key) + return drm + + def first_kid(self) -> UUID | None: + """The Key ID of the first init segment of the playlist.""" + if not self.first_init: + return None + return HLS.get_track_kid_from_init(self.track, self.read_init, self.first_init) + + def single_init(self, wanted_segments: list[Any]) -> bool: + """Whether every wanted segment shares one init segment and one EXT-X-KEY tag, with no discontinuity. + + 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 len(self.spans) != 1 or not self.spans[0].init_section: + return False + return not any(segment.discontinuity for segment in wanted_segments[1:]) and ( + not self.spans[0].keys or self.first is not None + ) diff --git a/unshackle/core/manifests/hls_keys.py b/unshackle/core/manifests/hls_keys.py index 77b79b6e..c292cd1c 100644 --- a/unshackle/core/manifests/hls_keys.py +++ b/unshackle/core/manifests/hls_keys.py @@ -2,12 +2,16 @@ from __future__ import annotations +from collections.abc import Callable from itertools import takewhile from typing import Any, NamedTuple import m3u8 from m3u8 import M3U8 +ReadInit = Callable[[m3u8.model.InitializationSection], bytes | None] +"""Reads the bytes of an init segment (EXT-X-MAP), or None when the request for it fails.""" + class KeySpan(NamedTuple): """A run of wanted segments under the same EXT-X-KEY tags and the same init segment. diff --git a/unshackle/core/tracks/track.py b/unshackle/core/tracks/track.py index 33d54df7..2f5030fc 100644 --- a/unshackle/core/tracks/track.py +++ b/unshackle/core/tracks/track.py @@ -1061,7 +1061,7 @@ class Track: segments = [ s for s in playlist.segments if not (callable(self.OnSegmentFilter) and self.OnSegmentFilter(s)) ] - if kids := HLS.get_bridge_kids(playlist, segments, self, session): + if kids := HLS.get_bridge_kids(playlist, segments, self, HLS.init_reader(playlist, session)): drm_list = [HLS.bridge_stub(system, kids) for system in SYSTEMS] if drm_list: self.drm = drm_list