From ba2911056d28057b9186e68f72d76f2eb3a11b93 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Sun, 29 Nov 2026 20:33:13 -0700 Subject: [PATCH] feat(hls): use the DRM of the track when no key tag can be licensed --- docs/dev/service-architecture.md | 18 ++++ tests/core/test_hls_service_drm_keys.py | 133 ++++++++++++++++++++++++ unshackle/core/drm/cenc.py | 5 +- unshackle/core/manifests/hls.py | 20 ++++ 4 files changed, 174 insertions(+), 2 deletions(-) create mode 100644 tests/core/test_hls_service_drm_keys.py diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md index 4bed253ac..411e16cfc 100644 --- a/docs/dev/service-architecture.md +++ b/docs/dev/service-architecture.md @@ -455,6 +455,24 @@ to `None`, and after it your `on_track_downloaded` runs and gets the clear file. runs on the server: the client sends the samples through the `samples` route, so a decrypter that needs a process on the server also works for a remote client. +### A playlist whose key tag unshackle cannot license + +A media playlist can name only a key system that unshackle does not read, such as an `skd://` key +over cbcs media, while the licence server of the platform also issues the same content key over +PlayReady or Widevine. To license such a track through one of those systems: + +1. Read the key ID from the init segment of the track. `HLS.get_track_kid_from_init` returns it. +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. +3. Let your licence callback send the challenge to the server that issues that key. + +`drm_stub` builds the header from the key ID alone, so this works with a licence server that goes +by the key ID, not with one that checks a header a packager signed. When a track carries a DRM +object and every `EXT-X-KEY` of its playlist names a key system unshackle cannot license, +`HLS.drop_unsupported_keys` removes the tags from the parsed playlist. The download then licenses +and decrypts the track with the DRM object of the track. A track with no DRM object still stops +with `None of the key systems are supported`. + ### How unshackle chooses a CDM and finds keys CDM selection is config-driven: the `cdm` map resolves a service tag (and optionally the diff --git a/tests/core/test_hls_service_drm_keys.py b/tests/core/test_hls_service_drm_keys.py new file mode 100644 index 000000000..9ccec4fe4 --- /dev/null +++ b/tests/core/test_hls_service_drm_keys.py @@ -0,0 +1,133 @@ +"""A service can license a playlist whose key tags name key systems unshackle cannot license itself. + +Such a playlist carries no Widevine, PlayReady or AES-128 tag. The service puts its own DRM on the track, and +``HLS.download_track`` then reads the playlist as one with no key tag. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any +from uuid import UUID + +import m3u8 +import pytest +from pywidevine.pssh import PSSH + +from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY +from unshackle.core.drm.cenc import drm_stub +from unshackle.core.manifests.hls import HLS +from unshackle.core.tracks import Video +from unshackle.core.tracks.track import DownloadContext, Track + +KID = UUID("33333333-3333-3333-3333-333333333333") +SKD_KEY = ( + '#EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://keys.example/asset",' + 'KEYFORMAT="com.apple.streamingkeydelivery",KEYFORMATVERSIONS="1"' +) +WIDEVINE_KEY = ( + '#EXT-X-KEY:METHOD=SAMPLE-AES,URI="data:text/plain;base64,' + f'{PSSH.new(key_ids=[KID], system_id=PSSH.SystemId.Widevine).dumps()}",' + 'KEYFORMAT="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",KEYFORMATVERSIONS="1"' +) + + +def playlist(*key_tags: str) -> str: + return ( + "#EXTM3U\n#EXT-X-VERSION:6\n#EXT-X-TARGETDURATION:6\n" + '#EXT-X-MAP:URI="init.mp4",BYTERANGE="994@0"\n' + + "".join(f"{tag}\n" for tag in key_tags) + + "#EXTINF:6.0,\nseg0.m4s\n#EXTINF:6.0,\nseg1.m4s\n#EXT-X-ENDLIST\n" + ) + + +def test_key_tags_no_licence_route_can_use_are_dropped() -> None: + manifest = m3u8.loads(playlist(SKD_KEY)) + + assert HLS.drop_unsupported_keys(manifest) + + assert manifest.keys == [] + assert all(segment.keys == [] for segment in manifest.segments) + assert HLS.single_init_no_rotation(manifest.segments, None, None) + + +@pytest.mark.parametrize( + "key_tag", + [ + pytest.param(WIDEVINE_KEY, id="widevine"), + pytest.param('#EXT-X-KEY:METHOD=AES-128,URI="key"', id="aes-128"), + pytest.param("#EXT-X-KEY:METHOD=NONE", id="none"), + ], +) +def test_a_key_tag_unshackle_can_read_keeps_every_tag(key_tag: str) -> None: + manifest = m3u8.loads(playlist(SKD_KEY, key_tag)) + before = list(manifest.keys) + segment_keys = [list(segment.keys) for segment in manifest.segments] + + assert not HLS.drop_unsupported_keys(manifest) + + assert manifest.keys == before + assert [segment.keys for segment in manifest.segments] == segment_keys + + +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: + playlist_file = tmp_path / "media.m3u8" + playlist_file.write_text(playlist(SKD_KEY), encoding="utf-8") + track = Video( + url="https://example.test/media.m3u8", + language="en", + descriptor=Track.Descriptor.HLS, + codec=Video.Codec.HEVC, + ) + track.from_file = playlist_file + drm = drm_stub("playready", [KID.hex]) + track.drm = [drm] + # the KID normally comes from the init segment; this test is offline + monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: KID)) + licensed: list[tuple[str, UUID | None]] = [] + 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((type(drm).__name__, track_kid)), + cdm=None, + ) + + DOWNLOAD_LICENCE_ONLY.set() + try: + HLS.download_track(track=track, ctx=ctx) + finally: + DOWNLOAD_LICENCE_ONLY.clear() + + assert licensed == [("PlayReady", KID)] + + +def test_a_track_without_drm_still_refuses_the_key_tag(tmp_path: Path, monkeypatch: Any) -> None: + playlist_file = tmp_path / "media.m3u8" + playlist_file.write_text(playlist(SKD_KEY), encoding="utf-8") + track = Video( + url="https://example.test/media.m3u8", + language="en", + descriptor=Track.Descriptor.HLS, + codec=Video.Codec.HEVC, + ) + track.from_file = playlist_file + monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: None)) + ctx = DownloadContext( + save_path=tmp_path / "video.mp4", + save_dir=tmp_path / "video_segments", + progress=lambda **_: None, + license_widevine=lambda drm, track_kid=None: None, + cdm=None, + ) + + DOWNLOAD_LICENCE_ONLY.set() + try: + with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"): + HLS.download_track(track=track, ctx=ctx) + finally: + DOWNLOAD_LICENCE_ONLY.clear() diff --git a/unshackle/core/drm/cenc.py b/unshackle/core/drm/cenc.py index 113cc8505..5047a1e69 100644 --- a/unshackle/core/drm/cenc.py +++ b/unshackle/core/drm/cenc.py @@ -126,9 +126,10 @@ def hls_key_drm(key: Any, kid: UUID | None = None) -> Widevine | PlayReady | Non def drm_stub(drm_type: str, kid_hexes: list[str]) -> Widevine | PlayReady: - """A PlayReady (``drm_type`` ``playready``) or else Widevine DRM that names ``kid_hexes``, to hold content keys got without its PSSH. + """A PlayReady (``drm_type`` ``playready``) or else Widevine DRM that names ``kid_hexes``, for content keys got without a PSSH. - The PSSH is built here, so it is for display only: the caller already has the content keys. + The header is built here and holds the key ids and nothing a packager signed. A licence server that goes by + the key ids answers its challenge, so a service can also license through it; one that checks the header does not. """ from unshackle.core.drm.playready import PlayReady from unshackle.core.drm.widevine import Widevine diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py index 778febaea..b18a92712 100644 --- a/unshackle/core/manifests/hls.py +++ b/unshackle/core/manifests/hls.py @@ -706,6 +706,11 @@ class HLS: if ctx.on_segments: ctx.on_segments(track, wanted_segments) + if track.drm 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 service" + ) + # Get session DRM as fallback but prefer media playlist keys for accurate KID matching if track.drm: session_drm = track.get_drm_for_cdm(cdm) @@ -1465,6 +1470,21 @@ class HLS: else: raise NotImplementedError(f"None of the key systems are supported: {', '.join(unsupported_systems)}") + @staticmethod + def drop_unsupported_keys(manifest: M3U8) -> bool: + """Remove every EXT-X-KEY of `manifest` when each one names a DRM system unshackle cannot license; True when it did. + + A service can license such a playlist another way, with the DRM it puts on the track. The download then + reads the playlist as one without an EXT-X-KEY, and the track keeps that DRM. + """ + keys = [key for key in (manifest.keys or []) if key is not None] + if not keys or any(key.method in ("NONE", "AES-128") or cenc_key(key) for key in keys): + return False + manifest.keys = [] + for segment in manifest.segments: + segment.keys = [] + return True + @staticmethod def get_drm( key: m3u8.model.SessionKey | m3u8.model.Key,