refactor(manifests): build the HLS key plan once and read it in every HLS licence pass

This commit is contained in:
imSp4rky
2026-12-02 21:02:06 -07:00
parent d2418414a0
commit 340a4b368f
12 changed files with 537 additions and 288 deletions
+5 -2
View File
@@ -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
+13 -10
View File
@@ -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 "<License/>" 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,
)
+187
View File
@@ -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"))
+1 -46
View File
@@ -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)
@@ -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",
+57 -42
View File
@@ -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"))
+5 -1
View File
@@ -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"]