diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md
index bb53f93a..aa8e83b3 100644
--- a/docs/dev/service-architecture.md
+++ b/docs/dev/service-architecture.md
@@ -403,7 +403,7 @@ service to talk to the platform's license server. unshackle recognizes seven DRM
|---|---|---|
| `Widevine` | Widevine | CDM challenge → license server → content keys (`.wvd` device) |
| `PlayReady` | PlayReady | CDM challenge (WRM header) → license server → content keys (`.prd` device) |
-| `ClearKeyCENC` | W3C `org.w3.clearkey` over CENC | JSON KID request → JWK set; no CDM |
+| `ClearKeyCENC` | W3C `org.w3.clearkey` or W3C common PSSH over CENC | JSON KID request → JWK set; no CDM |
| `ClearKey` | HLS AES-128 | content key fetched directly from a URI; no CDM, no challenge |
| `MonaLisa` | Proprietary WASM DRM | keys extracted locally; no license server |
| `BlowfishStripe` | Blowfish CBC stripe cipher | the service gives the per-track key; no CDM, no license server |
diff --git a/docs/guide/drm-and-cdm.md b/docs/guide/drm-and-cdm.md
index d73542a5..864d8f2e 100644
--- a/docs/guide/drm-and-cdm.md
+++ b/docs/guide/drm-and-cdm.md
@@ -48,7 +48,7 @@ license-server handshake. The rest are special cases.
|--------|-------------|--------------|------------|
| **Widevine** (Google) | `.wvd` | CDM challenge → license server → CDM parses → keys | shaka-packager / mp4decrypt |
| **PlayReady** (Microsoft) | `.prd` | CDM challenge (WRM header) → license server → CDM parses → keys | shaka-packager / mp4decrypt |
-| **ClearKey (CENC)**, W3C EME `org.w3.clearkey` | none | JSON `{"kids":[...],"type":"temporary"}` → license server returns a JWK Set. No CDM. | shaka-packager / mp4decrypt |
+| **ClearKey (CENC)**, W3C EME `org.w3.clearkey` or the W3C common PSSH | none | JSON `{"kids":[...],"type":"temporary"}` → license server returns a JWK Set. No CDM. | shaka-packager / mp4decrypt |
| **ClearKey (HLS)**, AES-128 `EXT-X-KEY` | none | Key fetched directly from a URI or `data:` URL. No CDM, no challenge. | in-process AES-CBC |
| **MonaLisa** (proprietary, WASM) | `.mld` | Ticket from the service API; keys extracted locally via WASM. No license server. | ML-Worker binary + AES-ECB, per segment |
| **Blowfish stripe** | none | The service gives the per-track key. No CDM, no license server. | in-process Blowfish-CBC on every third 2048-byte chunk |
@@ -474,6 +474,12 @@ license hook returns) and reads the JSON Web Key set back. You do not need a dev
file. The decrypted file still goes through shaka-packager or mp4decrypt like any
other CENC track, so the `decryption` setting applies.
+A DASH manifest can also give the KID of a ClearKey track with only the W3C common PSSH
+(`urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b`). The common PSSH can name KIDs for any DRM
+system, so unshackle reads it as ClearKey (CENC) only when the manifest and the init segment
+give no other DRM system. This scheme has no license URL in the manifest, so the content key
+must come from the service's ClearKey license hook or from a key vault.
+
### ClearKey over a whole file (AES-CTR)
Some services encrypt one whole audio file with AES-128-CTR and give the content key and
diff --git a/tests/core/test_clearkey_cenc.py b/tests/core/test_clearkey_cenc.py
index 4be366dd..62a75c4e 100644
--- a/tests/core/test_clearkey_cenc.py
+++ b/tests/core/test_clearkey_cenc.py
@@ -3,6 +3,7 @@
Covers the three seams of the native ClearKey flow:
- ``DASH.get_drm`` emitting a ``ClearKeyCENC`` from a clearkey ContentProtection
element (KID from own attrs or sibling mp4protection, Laurl namespace variants)
+- ``DASH.get_common_clearkey`` reading a W3C common PSSH ContentProtection
- ``ClearKeyCENC.get_content_keys`` building the W3C JSON license request and
parsing the JWK Set response (dict/str/bytes, unpadded base64url)
- ``to_dict`` / ``drm_from_dict`` round-trip for the --export/import path
@@ -19,16 +20,21 @@ import pytest
# lxml.etree: XML parser used to build ContentProtection fixtures for DASH.get_drm
from lxml import etree
+from pymp4.parser import Box
+from pywidevine.cdm import Cdm as WidevineCdm
+from unshackle.core.drm.cenc import COMMON_ID
from unshackle.core.drm.clearkey_cenc import ClearKeyCENC
from unshackle.core.manifests.dash import DASH
from unshackle.core.wire import drm_from_dict
KID = UUID("9eb4050d-e44b-4802-932e-27d75083e266")
+OTHER_KID = UUID("2c2d0a35-8f2a-4b1d-9c6e-5a7b8c9d0e1f")
KEY = bytes.fromhex("ccd0064c43f7e9fcbaa9b12af3fd1f40")
LAURL = "https://license.example.test/clearkey"
CLEARKEY_URN = "urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e"
+COMMON_URN = "urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b"
CENC_NS = "urn:mpeg:cenc:2013"
@@ -47,6 +53,13 @@ def protection(xml: str) -> etree._Element:
return etree.fromstring(xml.encode("utf8"))
+def mp4protection(kid: str) -> etree._Element:
+ return protection(
+ f''
+ )
+
+
class StubLicence:
"""Callable license stub that records the challenge it was given."""
@@ -122,12 +135,8 @@ def test_get_drm_clearkey_laurl_variants(laurl_xml: str) -> None:
def test_get_drm_clearkey_kid_from_sibling_mp4protection() -> None:
# Canonical DASH-IF shape: default_KID on the mp4protection element only.
clearkey = protection(f'')
- mp4protection = protection(
- f''
- )
- drm = DASH.get_drm([mp4protection, clearkey])
+ drm = DASH.get_drm([mp4protection(str(KID)), clearkey])
assert len(drm) == 1
assert isinstance(drm[0], ClearKeyCENC)
@@ -140,6 +149,62 @@ def test_get_drm_clearkey_without_any_kid_is_skipped() -> None:
assert DASH.get_drm([elem]) == []
+def common_pssh(*kids: UUID, system_id: UUID = COMMON_ID, version: int = 1) -> str:
+ box = Box.build(
+ dict(type=b"pssh", version=version, flags=0, system_ID=system_id, key_IDs=list(kids), init_data=b"")
+ )
+ return base64.b64encode(box).decode("ascii")
+
+
+def common_protection(pssh_b64: str, attrs: str = "") -> etree._Element:
+ return protection(
+ f''
+ f"{pssh_b64}"
+ )
+
+
+@pytest.mark.parametrize(
+ ("sibling_kid", "pssh_b64"),
+ [
+ (str(KID), common_pssh(OTHER_KID)),
+ (str(KID), common_pssh(version=0)),
+ (base64.b64encode(KID.bytes).decode("ascii"), common_pssh()),
+ ],
+ ids=["over-the-box-kid", "v0-box", "base64-kid"],
+)
+def test_common_clearkey_takes_the_sibling_default_kid(sibling_kid: str, pssh_b64: str) -> None:
+ clearkey = DASH.get_common_clearkey([mp4protection(sibling_kid), common_protection(pssh_b64)])
+
+ assert clearkey is not None
+ assert clearkey.kids == [KID]
+
+
+def test_common_clearkey_without_default_kid_takes_the_box_kids() -> None:
+ clearkey = DASH.get_common_clearkey([common_protection(common_pssh(KID, UUID(int=0), OTHER_KID))])
+
+ assert clearkey is not None
+ assert clearkey.kids == [KID, OTHER_KID]
+
+
+@pytest.mark.parametrize(
+ "pssh_b64",
+ [
+ common_pssh(version=0),
+ common_pssh(UUID(int=0)),
+ common_pssh(KID, system_id=WidevineCdm.uuid),
+ "not base64!",
+ "",
+ ],
+ ids=["v0-box", "placeholder-kid", "other-system", "garbage", "empty"],
+)
+def test_common_clearkey_with_no_kid_is_none(pssh_b64: str) -> None:
+ assert DASH.get_common_clearkey([common_protection(pssh_b64)]) is None
+
+
+def test_get_drm_leaves_a_common_pssh_to_the_caller() -> None:
+ assert DASH.get_drm([mp4protection(str(KID)), common_protection(common_pssh(KID))]) == []
+
+
@pytest.mark.parametrize(
"shape",
["dict", "str", "bytes"],
diff --git a/tests/core/test_dash_clearkey_licensing.py b/tests/core/test_dash_clearkey_licensing.py
index 6f85790b..1489740f 100644
--- a/tests/core/test_dash_clearkey_licensing.py
+++ b/tests/core/test_dash_clearkey_licensing.py
@@ -10,11 +10,15 @@ decrypt) and asserts the ClearKeyCENC drm is licensed.
from __future__ import annotations
+import base64
from functools import partial
from typing import Any
from uuid import UUID
+from pywidevine.pssh import PSSH
+
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY
+from unshackle.core.drm import Widevine
from unshackle.core.drm.clearkey_cenc import ClearKeyCENC
from unshackle.core.manifests.dash import DASH
from unshackle.core.tracks.track import DownloadContext
@@ -101,3 +105,45 @@ def test_download_track_keeps_service_drm_when_manifest_has_none(tmp_path, monke
assert track.drm == service_drm
assert len(licence.calls) == 1
+
+
+COMMON_MPD = MPD.replace(
+ MPD[MPD.index("") + len("")],
+ f''
+ '',
+)
+
+
+def with_init(monkeypatch: Any, init_data: bytes | None) -> None:
+ """Make the period give ``init_data`` as its init segment, offline."""
+ segments = DASH.get_period_segments
+
+ def fake(*args: Any, **kwargs: Any) -> Any:
+ _, *rest = segments(*args, **kwargs)
+ return (init_data, *rest)
+
+ monkeypatch.setattr(DASH, "get_period_segments", staticmethod(fake))
+
+
+def test_download_track_licenses_a_common_pssh_track_as_clearkey(tmp_path, monkeypatch) -> None:
+ track = DASH.from_text(COMMON_MPD, MANIFEST_URL).to_tracks().videos[0]
+ monkeypatch.setattr(track, "get_key_id", lambda *args, **kwargs: KID)
+ assert track.drm is None
+
+ licence = licence_only(track, tmp_path)
+
+ assert len(licence.calls) == 1
+ drm, _ = licence.calls[0]
+ assert isinstance(drm, ClearKeyCENC)
+ assert drm.kids == [KID]
+
+
+def test_download_track_prefers_the_init_segment_pssh_over_a_common_pssh(tmp_path, monkeypatch) -> None:
+ track = DASH.from_text(COMMON_MPD, MANIFEST_URL).to_tracks().videos[0]
+ monkeypatch.setattr(track, "get_key_id", lambda *args, **kwargs: KID)
+ with_init(monkeypatch, base64.b64decode(PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID]).dumps()))
+
+ licence = licence_only(track, tmp_path)
+
+ assert [type(d) for d in track.drm] == [Widevine]
+ assert isinstance(licence.calls[0][0], Widevine)
diff --git a/tests/core/test_manifest_corpus.py b/tests/core/test_manifest_corpus.py
index 793e02da..40212564 100644
--- a/tests/core/test_manifest_corpus.py
+++ b/tests/core/test_manifest_corpus.py
@@ -7,9 +7,11 @@ from collections import Counter
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock
+from uuid import UUID
import pytest
+from unshackle.core.drm import ClearKeyCENC
from unshackle.core.manifests import DASH, HLS, ISM
from unshackle.core.tracks import Audio, Tracks, Video
from unshackle.core.utils.xml import load_xml
@@ -104,3 +106,18 @@ def test_dash_segments_and_drm_resolve_offline(entry: dict[str, Any]) -> None:
continue
assert segments, track
assert all(url.startswith(("http://", "https://")) for url, _ in segments), track
+
+
+def test_common_pssh_manifest_gives_each_track_its_clearkey() -> None:
+ """A manifest whose only key system is the W3C common PSSH gives each audio and video track its ClearKey KID."""
+ entry = next(e for e in INDEX if e["file"].endswith("clearkey-server-1061a743.mpd"))
+ tracks = parse(entry)
+ for track in [*tracks.videos, *tracks.audio]:
+ dash = track.data["dash"]
+ protections = dash["representation"].findall("ContentProtection") + dash["adaptation_set"].findall(
+ "ContentProtection"
+ )
+ assert DASH.get_drm(protections) == []
+ clearkey = DASH.get_common_clearkey(protections)
+ assert isinstance(clearkey, ClearKeyCENC)
+ assert clearkey.kids == [UUID("feedf00d-eede-adbe-eff0-baadf00dd00d")]
diff --git a/unshackle/core/drm/cenc.py b/unshackle/core/drm/cenc.py
index 5e56a17a..1943d646 100644
--- a/unshackle/core/drm/cenc.py
+++ b/unshackle/core/drm/cenc.py
@@ -10,7 +10,7 @@ from typing import TYPE_CHECKING, Any, Self
from uuid import UUID
import m3u8
-from construct import Container
+from construct import ConstructError, Container
from pymp4.parser import Box
from pyplayready.system.pssh import PSSH as PR_PSSH
from pywidevine.cdm import Cdm as WidevineCdm
@@ -34,6 +34,7 @@ if TYPE_CHECKING:
WIDEVINE_ID: UUID = WV_PSSH.SystemId.Widevine
PLAYREADY_ID: UUID = PR_PSSH.SYSTEM_ID
+COMMON_ID = UUID("1077efec-c0b2-4d02-ace3-3c1e52e2fb4b")
KEYFORMATS = {
WidevineCdm.urn: WIDEVINE_ID,
f"urn:uuid:{PLAYREADY_ID}": PLAYREADY_ID,
@@ -46,6 +47,17 @@ PLACEHOLDER_KIDS = {
}
+def common_pssh_kids(pssh_b64: str | None) -> list[UUID]:
+ """The real KIDs of a base64 v1 PSSH box of the W3C common system ID, or an empty list for any other data."""
+ try:
+ box = Box.parse(base64.b64decode(pssh_b64 or ""))
+ except (ValueError, ConstructError):
+ return []
+ if box.type != b"pssh" or box.system_ID != COMMON_ID or box.version != 1:
+ return []
+ return [kid for kid in box.key_IDs if kid not in PLACEHOLDER_KIDS]
+
+
def key_system(key: Any) -> UUID | None:
"""The system ID that an EXT-X-KEY's KEYFORMAT names, or None when it names neither Widevine nor PlayReady."""
return KEYFORMATS.get((getattr(key, "keyformat", None) or "").lower())
diff --git a/unshackle/core/manifests/dash.py b/unshackle/core/manifests/dash.py
index 2f067812..52381896 100644
--- a/unshackle/core/manifests/dash.py
+++ b/unshackle/core/manifests/dash.py
@@ -31,6 +31,7 @@ from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.downloaders.requests import parse_content_range, range_answers, request_range
from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
+from unshackle.core.drm.cenc import COMMON_ID, PLACEHOLDER_KIDS, common_pssh_kids
from unshackle.core.drm.segment_decrypt import SEGMENT_DRM_T, SegmentDecrypter, can_use
from unshackle.core.drm.verify import walk
from unshackle.core.manifests.segment_pipeline import (
@@ -496,9 +497,8 @@ class DASH:
# Preserve existing DRM if it was set by the service, especially when service set Widevine
# but manifest only contains PlayReady protection (common scenario for some services)
existing_drm = track.drm
- manifest_drm = DASH.get_drm(
- representation.findall("ContentProtection") + adaptation_set.findall("ContentProtection")
- )
+ protections = representation.findall("ContentProtection") + adaptation_set.findall("ContentProtection")
+ manifest_drm = DASH.get_drm(protections)
# Only override existing DRM if:
# 1. No existing DRM was set, OR
@@ -642,6 +642,8 @@ class DASH:
elif not track.drm and init_data and isinstance(track, (Video, Audio)):
pssh_init = init_data
track.drm_from_pssh(cdm, lambda system: system.from_init_data(pssh_init), log)
+ if not track.drm and (clearkey := DASH.get_common_clearkey(protections)):
+ track.drm = [clearkey]
drm = track.get_drm_for_cdm(cdm)
license_drm(track, drm, ctx, track_kid, probe=lambda: track.get_key_id(url=segments[0][0], session=session))
@@ -1507,11 +1509,6 @@ class DASH:
@staticmethod
def get_drm(protections: list[Element]) -> list[DRM_T]:
drm: list[DRM_T] = []
- PLACEHOLDER_KIDS = {
- UUID("00000000-0000-0000-0000-000000000000"), # All zeros (key rotation default)
- UUID("00010203-0405-0607-0809-0a0b0c0d0e0f"), # Sequential 0x00-0x0f
- UUID("00010203-0405-0607-0809-101112131415"), # Shaka Packager test pattern
- }
for protection in protections:
urn = (protection.get("schemeIdUri") or "").lower()
@@ -1570,53 +1567,72 @@ class DASH:
elif urn == ClearKeyCENC.urn:
# W3C EME ClearKey (org.w3.clearkey): match the scheme UUID alone,
# value="ClearKey1.0" is spec'd (DASH-IF CCP) but not required in the wild
- kid_attr = protection.get("default_KID") or protection.get("{urn:mpeg:cenc:2013}default_KID")
- kid = None
- if kid_attr:
- try:
- kid = UUID(kid_attr)
- except ValueError:
- try:
- kid = UUID(bytes=base64.b64decode(kid_attr))
- except ValueError:
- kid = None
-
- if not kid:
- # DASH-IF puts default_KID on the sibling mp4protection element
- kid = next(
- (
- UUID(p.get("default_KID") or p.get("{urn:mpeg:cenc:2013}default_KID"))
- for p in protections
- if p.get("default_KID") or p.get("{urn:mpeg:cenc:2013}default_KID")
- ),
- None,
- )
-
- if not kid or kid in PLACEHOLDER_KIDS:
- continue
-
- # license URL appears under several namespaces/casings in the wild
- laurl = next(
- (
- text.strip()
- for name in (
- "{https://dashif.org/CPS}Laurl",
- "{https://dashif.org/CPS}laurl",
- "{http://dashif.org/guidelines/clearKey}Laurl",
- "{http://dashif.org/guidelines/clearKey}laurl",
- "Laurl",
- "laurl",
- )
- for text in [protection.findtext(name)]
- if text and text.strip()
- ),
- None,
- )
-
- drm.append(ClearKeyCENC(kids=[kid], laurl=laurl))
+ clearkey = DASH.get_clearkey(protection, protections)
+ if clearkey:
+ drm.append(clearkey)
return drm
+ @staticmethod
+ def default_kid(protection: Element) -> UUID | None:
+ """The default_KID of a ContentProtection, given as a UUID or base64, or None when it has none or it is no KID."""
+ kid_attr = protection.get("default_KID") or protection.get("{urn:mpeg:cenc:2013}default_KID")
+ if not kid_attr:
+ return None
+ try:
+ return UUID(kid_attr)
+ except ValueError:
+ try:
+ return UUID(bytes=base64.b64decode(kid_attr))
+ except ValueError:
+ return None
+
+ @staticmethod
+ def get_common_clearkey(protections: list[Element]) -> ClearKeyCENC | None:
+ """The ClearKeyCENC of the first W3C common PSSH ContentProtection that names a real KID, or None.
+
+ A common PSSH names KIDs for any DRM system, so the caller asks for it only after the manifest and the init
+ segment gave no other DRM system.
+ """
+ common = (p for p in protections if (p.get("schemeIdUri") or "").lower() == f"urn:uuid:{COMMON_ID}")
+ return next(filter(None, (DASH.get_clearkey(p, protections) for p in common)), None)
+
+ @staticmethod
+ def get_clearkey(protection: Element, protections: list[Element]) -> ClearKeyCENC | None:
+ """The ClearKeyCENC of a ClearKey or W3C common PSSH ContentProtection, or None when it names no real KID.
+
+ The KID is the default_KID of the element, else of a sibling (DASH-IF puts it on mp4protection), else each KID
+ of its common PSSH box.
+ """
+ kid = next(filter(None, map(DASH.default_kid, [protection, *protections])), None)
+ kids = (
+ [kid]
+ if kid and kid not in PLACEHOLDER_KIDS
+ else common_pssh_kids(protection.findtext("{urn:mpeg:cenc:2013}pssh") or protection.findtext("pssh"))
+ )
+ if not kids:
+ return None
+
+ # license URL appears under several namespaces/casings in the wild
+ laurl = next(
+ (
+ text.strip()
+ for name in (
+ "{https://dashif.org/CPS}Laurl",
+ "{https://dashif.org/CPS}laurl",
+ "{http://dashif.org/guidelines/clearKey}Laurl",
+ "{http://dashif.org/guidelines/clearKey}laurl",
+ "Laurl",
+ "laurl",
+ )
+ for text in [protection.findtext(name)]
+ if text and text.strip()
+ ),
+ None,
+ )
+
+ return ClearKeyCENC(kids=kids, laurl=laurl)
+
@staticmethod
def pt_to_sec(d: str | float) -> float:
if isinstance(d, float):