From 2da0043d17267c6d45d3b2c2aa20b07c8a421086 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Wed, 25 Nov 2026 21:07:21 -0700 Subject: [PATCH] refactor(drm): read CENC systems and track KIDs in one cenc module --- tests/core/test_cenc.py | 199 ++++++++++++++++++++ tests/core/test_rolling_merge_hls_ism.py | 4 +- unshackle/core/drm/__init__.py | 5 +- unshackle/core/drm/cenc.py | 230 +++++++++++++++++++++++ unshackle/core/drm/playready.py | 140 ++------------ unshackle/core/drm/widevine.py | 174 ++--------------- unshackle/core/manifests/hls.py | 56 ++---- unshackle/core/tracks/track.py | 49 +---- 8 files changed, 483 insertions(+), 374 deletions(-) create mode 100644 tests/core/test_cenc.py create mode 100644 unshackle/core/drm/cenc.py diff --git a/tests/core/test_cenc.py b/tests/core/test_cenc.py new file mode 100644 index 00000000..655747b2 --- /dev/null +++ b/tests/core/test_cenc.py @@ -0,0 +1,199 @@ +"""The CENC reader finds the systems and the track's own KID in init data and in HLS keys.""" + +from __future__ import annotations + +import base64 +from types import SimpleNamespace +from typing import Any +from uuid import UUID + +import pytest +import requests +from pymp4.parser import Box +from pyplayready.system.wrmheader import WRMHeader +from pywidevine.pssh import PSSH + +from tests.core.test_hls_kid_from_init import KEY_LINE, key_of, no_kid_pssh +from tests.core.test_kid_windows import box, encv +from unshackle.core.drm import PlayReady, Widevine, cenc +from unshackle.core.drm.verify import PIFF_TENC +from unshackle.core.tracks import Video + +TRACK_KID = UUID(int=0xA) +OTHER_KID = UUID(int=0xB) +PR_KEYFORMAT = "urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95" + + +@pytest.fixture(autouse=True) +def no_ffprobe(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(cenc, "ffprobe", lambda data: {}) + + +def playready_box(kid: UUID) -> bytes: + kid_b64 = base64.b64encode(kid.bytes_le).decode() + header = WRMHeader( + ( + '' + f'' + ).encode("utf-16-le") + ) + pro = base64.b64decode(PlayReady.pro_b64_for(header)) + return Box.build({"type": b"pssh", "version": 0, "flags": 0, "system_ID": cenc.PLAYREADY_ID, "init_data": pro}) + + +def init(*boxes: bytes) -> bytes: + return box(b"moov", box(b"trak", *boxes)) + + +def test_init_kid_reads_the_first_real_tenc() -> None: + assert cenc.init_kid(init(encv(UUID(int=0)), encv(TRACK_KID))) == TRACK_KID + + +def test_init_kid_reads_a_piff_tenc() -> None: + assert cenc.init_kid(init(encv(TRACK_KID, piff=True))) == TRACK_KID + + +def test_init_kid_prefers_the_ffprobe_kid(monkeypatch: pytest.MonkeyPatch) -> None: + enc_key_id = base64.b64encode(OTHER_KID.bytes).decode() + monkeypatch.setattr(cenc, "ffprobe", lambda data: {"streams": [{"tags": {"enc_key_id": enc_key_id}}]}) + assert cenc.init_kid(init(encv(TRACK_KID))) == OTHER_KID + + +def test_init_kid_skips_a_clear_piff_tenc() -> None: + clear = box(b"uuid", PIFF_TENC, bytes(8) + TRACK_KID.bytes) + assert cenc.init_kid(init(clear, encv(OTHER_KID, piff=True))) == OTHER_KID + + +def test_init_kid_is_none_without_a_real_kid() -> None: + assert cenc.init_kid(init(encv(UUID(int=0)))) is None + + +def test_widevine_from_init_data_takes_the_piff_kid_when_the_pssh_names_none() -> None: + pssh = PSSH(no_kid_pssh()).dump() + drm = Widevine.from_init_data(init(pssh, encv(TRACK_KID, piff=True))) + assert drm.kids == [TRACK_KID] + + +def test_playready_from_init_data_keeps_the_piff_kid_as_the_track_kid() -> None: + drm = PlayReady.from_init_data(init(playready_box(OTHER_KID), encv(TRACK_KID, piff=True))) + drm.content_keys = {TRACK_KID: "00" * 16, OTHER_KID: "11" * 16} + assert drm.kids == [OTHER_KID, TRACK_KID] + assert drm.own_kids() == [TRACK_KID] + + +def test_from_init_data_without_a_pssh_of_the_system_raises() -> None: + with pytest.raises(Widevine.Exceptions.PSSHNotFound): + Widevine.from_init_data(init(playready_box(OTHER_KID), encv(TRACK_KID))) + + +@pytest.mark.parametrize( + ("keyformat", "system"), + [ + ("urn:uuid:EDEF8BA9-79D6-4ACE-A3C8-27DCD51D21ED", cenc.WIDEVINE_ID), + (PR_KEYFORMAT, cenc.PLAYREADY_ID), + ("com.microsoft.playready", cenc.PLAYREADY_ID), + ("identity", None), + (None, None), + ], +) +def test_key_system(keyformat: str | None, system: UUID | None) -> None: + assert cenc.key_system(SimpleNamespace(keyformat=keyformat)) == system + + +def test_hls_key_drm_takes_the_tag_kid_before_the_init_kid() -> None: + drm = cenc.hls_key_drm(key_of(no_kid_pssh(), f",KEYID=0x{TRACK_KID.hex}"), kid=OTHER_KID) + assert isinstance(drm, Widevine) + assert drm.kids == [TRACK_KID] + + +def test_hls_key_drm_replaces_placeholder_kids_with_the_init_kid() -> None: + placeholder = PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[UUID(int=0)]).dumps() + drm = cenc.hls_key_drm(key_of(placeholder), kid=TRACK_KID) + assert isinstance(drm, Widevine) + assert drm.kids == [TRACK_KID] + + +def test_hls_key_drm_ignores_the_init_kid_when_the_pssh_names_a_real_kid() -> None: + real = PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[OTHER_KID]).dumps() + drm = cenc.hls_key_drm(key_of(real), kid=TRACK_KID) + assert isinstance(drm, Widevine) + assert drm.kids == [OTHER_KID] + + +def test_hls_key_drm_is_none_for_another_keyformat() -> None: + assert cenc.hls_key_drm(SimpleNamespace(keyformat="identity", uri="x")) is None + + +@pytest.mark.parametrize( + "extra", + [ + pytest.param(",KEYID=0xZZZ", id="bad-hex"), + pytest.param(f",KEYID=0x{UUID(int=0).hex}", id="zero"), + pytest.param(f",KEYID=0x{TRACK_KID.hex},KID=0x{OTHER_KID.hex}", id="keyid-and-kid"), + pytest.param(',PSSH="x"', id="pssh-attribute"), + ], +) +def test_hls_key_drm_falls_back_on_an_unusable_tag_kid(extra: str) -> None: + real = PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[OTHER_KID]).dumps() + drm = cenc.hls_key_drm(key_of(real, extra)) + assert isinstance(drm, Widevine) + assert drm.kids[0] == OTHER_KID + assert UUID(int=0) not in drm.kids + + +class RouteSession(requests.Session): + def __init__(self, routes: dict[str, bytes]) -> None: + super().__init__() + self.routes = routes + + def get(self, url: str | bytes, **kwargs: Any) -> requests.Response: # type: ignore[override] + res = requests.Response() + res.status_code = 200 + res._content = self.routes[str(url).rsplit("/", 1)[-1]] + res.encoding = "utf-8" + return res + + +def playlist_track(text: str, init_data: bytes = b"") -> Video: + track = Video.__new__(Video) + track.id = "test" + track.url = "https://example.test/video.m3u8" + track.descriptor = Video.Descriptor.HLS + track.drm = None + track.needs_drm_loading = True + track.session = RouteSession({"video.m3u8": text.encode(), "init.mp4": init_data}) + return track + + +def test_load_drm_from_playlist_takes_the_tag_kid() -> None: + line = KEY_LINE.format(pssh=no_kid_pssh()) + f",KEYID=0x{TRACK_KID.hex}" + track = playlist_track(f"#EXTM3U\n{line}\n#EXTINF:6.0,\na.m4s\n#EXT-X-ENDLIST\n") + + assert track.load_drm_from_playlist() is True + assert track.drm is not None + assert [drm.kids for drm in track.drm] == [[TRACK_KID]] + + +def test_load_drm_from_playlist_takes_the_init_kid_when_the_tag_and_pssh_have_none() -> None: + line = KEY_LINE.format(pssh=no_kid_pssh()) + text = f'#EXTM3U\n#EXT-X-MAP:URI="init.mp4"\n{line}\n#EXTINF:6.0,\na.m4s\n#EXT-X-ENDLIST\n' + track = playlist_track(text, init(encv(TRACK_KID, piff=True))) + + assert track.load_drm_from_playlist() is True + assert track.drm is not None + assert [drm.kids for drm in track.drm] == [[TRACK_KID]] + + +def test_from_track_reads_the_playlist_pssh_and_the_init_kid() -> None: + pssh_b64 = base64.b64encode(playready_box(OTHER_KID)).decode() + line = ( + f'#EXT-X-KEY:METHOD=SAMPLE-AES-CTR,URI="data:text/plain;charset=UTF-16;base64,{pssh_b64}",' + f'KEYFORMAT="{PR_KEYFORMAT}",KEYFORMATVERSIONS="1"' + ) + track = playlist_track(f"#EXTM3U\n{line}\n#EXTINF:6.0,\na.m4s\n#EXT-X-ENDLIST\n") + track.get_init_segment = lambda **kwargs: init(encv(TRACK_KID, piff=True)) # type: ignore[method-assign] + + drm = PlayReady.from_track(track, track.session) + assert drm.kids == [OTHER_KID, TRACK_KID] + with pytest.raises(Widevine.Exceptions.PSSHNotFound): + Widevine.from_track(track, track.session) diff --git a/tests/core/test_rolling_merge_hls_ism.py b/tests/core/test_rolling_merge_hls_ism.py index 88c56829..368af883 100644 --- a/tests/core/test_rolling_merge_hls_ism.py +++ b/tests/core/test_rolling_merge_hls_ism.py @@ -29,13 +29,13 @@ from unshackle.core import constants from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.drm import ClearKeyCENC, MonaLisa, Widevine +from unshackle.core.drm import cenc as cenc_module from unshackle.core.manifests import DASH, HLS, ISM from unshackle.core.manifests import dash as dash_module from unshackle.core.manifests import hls as hls_module from unshackle.core.manifests import segment_pipeline from unshackle.core.manifests.ism_init import PIFF_SENC_UUID from unshackle.core.tracks import Video -from unshackle.core.tracks import track as track_module from unshackle.core.tracks.track import DownloadContext INIT = bytes(range(100)) @@ -67,7 +67,7 @@ class _Handler(BaseHTTPRequestHandler): @pytest.fixture(autouse=True) def no_ffprobe(monkeypatch): """The fake init segments hold no stream for FFprobe to read, so the KID probe goes on to the boxes.""" - monkeypatch.setattr(track_module, "ffprobe", lambda data: {}) + monkeypatch.setattr(cenc_module, "ffprobe", lambda data: {}) @pytest.fixture diff --git a/unshackle/core/drm/__init__.py b/unshackle/core/drm/__init__.py index 7860257f..8b222083 100644 --- a/unshackle/core/drm/__init__.py +++ b/unshackle/core/drm/__init__.py @@ -2,6 +2,7 @@ from typing import Any from uuid import UUID from unshackle.core.drm.blowfish_stripe import BlowfishStripe +from unshackle.core.drm.cenc import PLACEHOLDER_KIDS from unshackle.core.drm.clearkey import ClearKey from unshackle.core.drm.clearkey_cenc import ClearKeyCENC from unshackle.core.drm.monalisa import MonaLisa @@ -23,14 +24,14 @@ def drop_null_keys(drm: Any) -> None: def real_kids(drm: Any) -> list[UUID]: """Return the KIDs a DRM object names, without the all-zero and test-pattern placeholders.""" - return [kid for kid in getattr(drm, "kids", None) or [] if kid.int and kid not in Widevine.PLACEHOLDER_KIDS] + return [kid for kid in getattr(drm, "kids", None) or [] if kid not in PLACEHOLDER_KIDS] def own_kids(drm: Any) -> list[UUID]: """Return the real KIDs that identify the track's own content key, as the DRM object knows them.""" own = getattr(drm, "own_kids", None) kids = own() if callable(own) else getattr(drm, "kids", None) or [] - return [kid for kid in kids if kid.int and kid not in Widevine.PLACEHOLDER_KIDS] + return [kid for kid in kids if kid not in PLACEHOLDER_KIDS] __all__ = ( diff --git a/unshackle/core/drm/cenc.py b/unshackle/core/drm/cenc.py new file mode 100644 index 00000000..014c1b9c --- /dev/null +++ b/unshackle/core/drm/cenc.py @@ -0,0 +1,230 @@ +"""Which CENC systems an init segment or an HLS key list carries, and which KID belongs to the track.""" + +from __future__ import annotations + +import base64 +import logging +from collections.abc import Iterable +from pathlib import Path +from typing import TYPE_CHECKING, Any, Self +from uuid import UUID + +import m3u8 +from construct import Container +from pymp4.parser import Box +from pyplayready.system.pssh import PSSH as PR_PSSH +from pywidevine.cdm import Cdm as WidevineCdm +from pywidevine.pssh import PSSH as WV_PSSH + +from unshackle.core.config import config +from unshackle.core.constants import AnyTrack +from unshackle.core.drm import key_args as drm_key_args +from unshackle.core.drm.decrypters import decrypt_cenc, mp4decrypt, shaka_decrypt +from unshackle.core.drm.verify import PIFF_TENC +from unshackle.core.session import AnySession, utf8_text +from unshackle.core.utilities import get_boxes +from unshackle.core.utils import run_proxy +from unshackle.core.utils.subprocess import ffprobe + +log = logging.getLogger(__name__) + +if TYPE_CHECKING: + from unshackle.core.drm.playready import PlayReady + from unshackle.core.drm.widevine import Widevine + +WIDEVINE_ID: UUID = WV_PSSH.SystemId.Widevine +PLAYREADY_ID: UUID = PR_PSSH.SYSTEM_ID +KEYFORMATS = { + WidevineCdm.urn: WIDEVINE_ID, + f"urn:uuid:{PLAYREADY_ID}": PLAYREADY_ID, + "com.microsoft.playready": PLAYREADY_ID, +} +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 +} + + +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()) + + +def key_data(key: Any) -> str: + """The base64 PSSH at the end of an EXT-X-KEY data URI.""" + return str(key.uri.split(",")[-1]) + + +def init_kid(init_data: bytes) -> UUID | None: + """The track's own KID: FFprobe's enc_key_id, then the first real tenc KID, then the first real PIFF tenc KID. + + A pssh box is no source, because it can name the KIDs of other renditions too. The PIFF box is read by + offset, and only when its AlgorithmID is not 0 (clear): pymp4 parses it but cannot build it again, so + ``get_boxes`` raises on it. + """ + probe = ffprobe(init_data) + for stream in (probe or {}).get("streams") or []: + enc_key_id = stream.get("tags", {}).get("enc_key_id") + if enc_key_id: + return UUID(bytes=base64.b64decode(enc_key_id)) + for tenc in get_boxes(init_data, b"tenc"): + if tenc.key_ID.int != 0: + return tenc.key_ID + marker = b"uuid" + PIFF_TENC + at = init_data.find(marker) + while at != -1: + kid = init_data[at + 28 : at + 44] + if len(kid) == 16 and any(kid) and init_data[at + 26]: + return UUID(bytes=kid) + at = init_data.find(marker, at + 1) + return None + + +def hls_key_drm(key: Any, kid: UUID | None = None) -> Widevine | PlayReady | None: + """The Widevine or PlayReady DRM of an EXT-X-KEY, or None for another KEYFORMAT. + + Widevine takes the tag's own KEYID first. It takes ``kid`` (from the init segment) only when the + tag and the PSSH carry no real KID, because a v0 PSSH can carry none. + """ + from unshackle.core.drm.playready import PlayReady + from unshackle.core.drm.widevine import Widevine + + system = key_system(key) + if system == PLAYREADY_ID: + return PlayReady.from_pssh_b64(key_data(key)) + if system != WIDEVINE_ID: + return None + extra_params = dict(key._extra_params) + extra_params.pop("pssh", None) + pssh = WV_PSSH(key_data(key)) + if kid in PLACEHOLDER_KIDS or any(k not in PLACEHOLDER_KIDS for k in pssh.key_ids): + kid = None + keyid, kid_attr = extra_params.pop("keyid", None), extra_params.pop("kid", None) + tag_kid = tag_key_id(keyid) or tag_key_id(kid_attr) + return Widevine(pssh=pssh, kid=tag_kid or kid, **extra_params) + + +def tag_key_id(value: Any) -> UUID | None: + """The KID of an EXT-X-KEY KEYID or KID attribute, or None when it is absent, a placeholder or not a KID.""" + try: + kid = as_kid(value.removeprefix("0x").removeprefix("0X") if value else None) + except ValueError: + log.debug(f"Ignoring the EXT-X-KEY KEYID {value!r}: it is not a Key ID") + return None + return None if kid in PLACEHOLDER_KIDS else kid + + +def as_kid(kid: UUID | str | bytes | None) -> UUID | None: + """A KID given as a UUID, a hex string or 16 bytes, as a UUID.""" + if not kid: + return None + if isinstance(kid, str): + kid = UUID(hex=kid) + elif isinstance(kid, bytes): + kid = UUID(bytes=kid) + if not isinstance(kid, UUID): + raise ValueError(f"Expected kid to be a {UUID}, str, or bytes, not {kid!r}") + return kid + + +class CencDrm: + """What Widevine and PlayReady share: reading their PSSH and KID from track data, and the CENC decrypt. + + A subclass gives its ``SYSTEM_ID``, its display ``NAME``, ``from_pssh_box`` and its licence step. + ``from_track`` and ``from_init_data`` are for when the caller has no PSSH to give. They raise + PSSHNotFound when the data has no pssh of this system, and the constructor raises KIDNotFound. + """ + + SYSTEM_ID: UUID + NAME: str + Exceptions: Any + content_keys: dict[UUID, str] + _kid: UUID | None + + @classmethod + def from_pssh_box(cls, box: Container, kid: UUID | None) -> Self: + """Make the DRM from a parsed pssh box of this system and the track's own KID.""" + raise NotImplementedError + + @classmethod + def from_boxes(cls, boxes: Iterable[Container], init_data: bytes | None) -> Self: + """Make the DRM from the first pssh box of this system, with the KID of ``init_data``.""" + box = next((box for box in boxes if box.system_ID == cls.SYSTEM_ID), None) + if box is None: + raise cls.Exceptions.PSSHNotFound("PSSH was not found in track data.") + return cls.from_pssh_box(box, init_kid(init_data) if init_data else None) + + @classmethod + def from_track(cls, track: AnyTrack, session: AnySession | None = None) -> Self: + """Make the DRM from a track's HLS playlist keys and its init segment.""" + if not session: + session = run_proxy.fallback_session() + session.headers.update(config.headers) + + boxes: list[Container] = [] + if track.descriptor == track.Descriptor.HLS: + m3u_url = track.url + assert isinstance(m3u_url, str) + master = m3u8.loads(utf8_text(session.get(m3u_url)), uri=m3u_url) + boxes.extend( + Box.parse(base64.b64decode(key_data(key))) + for key in (master.session_keys or master.keys) + if key_system(key) == cls.SYSTEM_ID + ) + + init_data = track.get_init_segment(session=session) + if init_data: + boxes.extend(get_boxes(init_data, b"pssh")) + return cls.from_boxes(boxes, init_data) + + @classmethod + def from_init_data(cls, init_data: bytes) -> Self: + """Make the DRM from the pssh and KID of an init segment.""" + if not init_data: + raise ValueError("Init data should be provided.") + if not isinstance(init_data, bytes): + raise TypeError(f"Expected init data to be bytes, not {init_data!r}") + return cls.from_boxes(get_boxes(init_data, b"pssh"), init_data) + + @property + def kids(self) -> list[UUID]: + """All the KIDs this DRM names.""" + raise NotImplementedError + + @property + def kid(self) -> UUID | None: + """The first KID, if any.""" + return next(iter(self.kids), None) + + def to_dict(self) -> dict[str, Any]: + """This DRM in the export form; see ``wire.drm_to_dict``.""" + from unshackle.core.wire import drm_to_dict + + return drm_to_dict(self) # type: ignore[arg-type] + + def own_kids(self) -> list[UUID]: + """Return the KIDs that identify this track's own content key. + + The KID given to the constructor (from the manifest or the init segment) names the + track exactly. A PSSH can name the KIDs of other renditions too. + """ + if self._kid and self._kid in self.content_keys: + return [self._kid] + return self.kids + + def decrypt(self, path: Path) -> None: + """Decrypt the file at ``path`` in place with this track's content keys.""" + decrypt_cenc(self, path, self.NAME) + + def mp4decrypt_key_args(self, track_kids: dict[int, UUID] | None = None) -> list[str]: + """Build the mp4decrypt --key arguments for every content key, the zero-KID and the track ID fallbacks.""" + return drm_key_args.mp4decrypt_key_args(self.content_keys, self.own_kids(), track_kids) + + def decrypt_with_mp4decrypt(self, path: Path) -> None: + """Decrypt with mp4decrypt.""" + mp4decrypt(path, self.mp4decrypt_key_args) + + def decrypt_with_shaka_packager(self, path: Path) -> None: + """Decrypt with shaka-packager.""" + shaka_decrypt(path, drm_key_args.shaka_keys(self.content_keys, self.own_kids()), self.NAME) diff --git a/unshackle/core/drm/playready.py b/unshackle/core/drm/playready.py index f5201a85..59fa3f8c 100644 --- a/unshackle/core/drm/playready.py +++ b/unshackle/core/drm/playready.py @@ -3,13 +3,11 @@ from __future__ import annotations import base64 import re from collections.abc import Callable -from pathlib import Path from threading import Lock from typing import Any from uuid import UUID import click -import m3u8 from construct import Container from pymp4.parser import Box from pyplayready.cdm import Cdm as PlayReadyCdm @@ -18,20 +16,17 @@ from pyplayready.system.pssh import PSSH from pyplayready.system.wrmheader import WRMHeader from unshackle.core.cdm.http_cdm import HttpCdm -from unshackle.core.config import config -from unshackle.core.constants import AnyTrack -from unshackle.core.drm import key_args as drm_key_args -from unshackle.core.drm.decrypters import decrypt_cenc, mp4decrypt, shaka_decrypt +from unshackle.core.drm.cenc import PLAYREADY_ID, CencDrm, as_kid from unshackle.core.remote_protocol import APIErrorCode -from unshackle.core.session import AnySession, utf8_text -from unshackle.core.utilities import call_licence, get_boxes, log_event -from unshackle.core.utils import run_proxy -from unshackle.core.utils.subprocess import ffprobe +from unshackle.core.utilities import call_licence, log_event -class PlayReady: +class PlayReady(CencDrm): """PlayReady DRM System.""" + SYSTEM_ID = PLAYREADY_ID + NAME = "PlayReady" + _ABSORB_LOCK = Lock() def __init__( @@ -56,17 +51,9 @@ class PlayReady: if extra_kid not in kids: kids.append(extra_kid) - self._kid: UUID | None = None - if kid: - if isinstance(kid, str): - kid = UUID(hex=kid) - elif isinstance(kid, bytes): - kid = UUID(bytes=kid) - if not isinstance(kid, UUID): - raise ValueError(f"Expected kid to be a {UUID}, str, or bytes, not {kid!r}") - self._kid = kid - if kid not in kids: - kids.append(kid) + self._kid = as_kid(kid) + if self._kid and self._kid not in kids: + kids.append(self._kid) self._pssh = pssh self._kids = kids @@ -189,76 +176,9 @@ class PlayReady: return cls(pssh=pssh, kid=kid, pssh_b64=pssh_b64) @classmethod - def from_track(cls, track: AnyTrack, session: AnySession | None = None) -> PlayReady: - if not session: - session = run_proxy.fallback_session() - session.headers.update(config.headers) - - kid: UUID | None = None - pssh_boxes: list[Container] = [] - tenc_boxes: list[Container] = [] - - if track.descriptor == track.Descriptor.HLS: - m3u_url = track.url - assert isinstance(m3u_url, str) - master = m3u8.loads(utf8_text(session.get(m3u_url)), uri=m3u_url) - pssh_boxes.extend( - Box.parse(base64.b64decode(x.uri.split(",")[-1])) - for x in (master.session_keys or master.keys) - if x - and x.keyformat - and x.keyformat.lower() in {f"urn:uuid:{PSSH.SYSTEM_ID}", "com.microsoft.playready"} - ) - - init_data = track.get_init_segment(session=session) - if init_data: - probe = ffprobe(init_data) - if probe: - for stream in probe.get("streams") or []: - enc_key_id = stream.get("tags", {}).get("enc_key_id") - if enc_key_id: - kid = UUID(bytes=base64.b64decode(enc_key_id)) - pssh_boxes.extend(list(get_boxes(init_data, b"pssh"))) - tenc_boxes.extend(list(get_boxes(init_data, b"tenc"))) - - pssh = next((b for b in pssh_boxes if b.system_ID == PSSH.SYSTEM_ID), None) - if not pssh: - raise PlayReady.Exceptions.PSSHNotFound("PSSH was not found in track data.") - - tenc = next(iter(tenc_boxes), None) - if not kid and tenc and tenc.key_ID.int != 0: - kid = tenc.key_ID - - pssh_bytes = Box.build(pssh) - return cls(pssh=PSSH(pssh_bytes), kid=kid, pssh_b64=base64.b64encode(pssh_bytes).decode()) - - @classmethod - def from_init_data(cls, init_data: bytes) -> PlayReady: - if not init_data: - raise ValueError("Init data should be provided.") - if not isinstance(init_data, bytes): - raise TypeError(f"Expected init data to be bytes, not {init_data!r}") - - kid: UUID | None = None - pssh_boxes: list[Container] = list(get_boxes(init_data, b"pssh")) - tenc_boxes: list[Container] = list(get_boxes(init_data, b"tenc")) - - probe = ffprobe(init_data) - if probe: - for stream in probe.get("streams") or []: - enc_key_id = stream.get("tags", {}).get("enc_key_id") - if enc_key_id: - kid = UUID(bytes=base64.b64decode(enc_key_id)) - - pssh = next((b for b in pssh_boxes if b.system_ID == PSSH.SYSTEM_ID), None) - if not pssh: - raise PlayReady.Exceptions.PSSHNotFound("PSSH was not found in track data.") - - tenc = next(iter(tenc_boxes), None) - if not kid and tenc and tenc.key_ID.int != 0: - kid = tenc.key_ID - - pssh_bytes = Box.build(pssh) + def from_pssh_box(cls, box: Container, kid: UUID | None) -> PlayReady: + """Make the DRM from a parsed PlayReady pssh box and the track's own KID.""" + pssh_bytes = Box.build(box) return cls(pssh=PSSH(pssh_bytes), kid=kid, pssh_b64=base64.b64encode(pssh_bytes).decode()) @property @@ -269,16 +189,6 @@ class PlayReady: def pssh_b64(self) -> str | None: return self.data.get("pssh_b64") - @property - def kid(self) -> UUID | None: - return next(iter(self.kids), None) - - def to_dict(self) -> dict[str, Any]: - """This DRM in the export form; see ``wire.drm_to_dict``.""" - from unshackle.core.wire import drm_to_dict - - return drm_to_dict(self) - @property def kids(self) -> list[UUID]: return self._kids @@ -533,32 +443,6 @@ class PlayReady: return describe(code) or f"0x{code & 0xFFFFFFFF:08X}" return None - def decrypt(self, path: Path) -> None: - """Decrypt the file at ``path`` in place with this track's PlayReady content keys.""" - decrypt_cenc(self, path, "PlayReady") - - def own_kids(self) -> list[UUID]: - """Return the KIDs that identify this track's own content key. - - The KID given to the constructor (from the manifest or the init segment) names the - track exactly. A PSSH can name the KIDs of other renditions too. - """ - if self._kid and self._kid in self.content_keys: - return [self._kid] - return self.kids - - def mp4decrypt_key_args(self, track_kids: dict[int, UUID] | None = None) -> list[str]: - """Build the mp4decrypt --key arguments for every content key, the zero-KID and the track ID fallbacks.""" - return drm_key_args.mp4decrypt_key_args(self.content_keys, self.own_kids(), track_kids) - - def decrypt_with_mp4decrypt(self, path: Path) -> None: - """Decrypt with mp4decrypt.""" - mp4decrypt(path, self.mp4decrypt_key_args) - - def decrypt_with_shaka_packager(self, path: Path) -> None: - """Decrypt with shaka-packager.""" - shaka_decrypt(path, drm_key_args.shaka_keys(self.content_keys, self.own_kids()), "PlayReady") - class Exceptions: class PSSHNotFound(Exception): error_code = APIErrorCode.DRM_ERROR diff --git a/unshackle/core/drm/widevine.py b/unshackle/core/drm/widevine.py index 979a9368..09877f2d 100644 --- a/unshackle/core/drm/widevine.py +++ b/unshackle/core/drm/widevine.py @@ -2,37 +2,27 @@ from __future__ import annotations import base64 from collections.abc import Callable -from pathlib import Path from typing import Any from uuid import UUID import click -import m3u8 from construct import Container from pymp4.parser import Box from pywidevine.cdm import Cdm as WidevineCdm from pywidevine.pssh import PSSH from unshackle.core.cdm.http_cdm import HttpCdm -from unshackle.core.config import config -from unshackle.core.constants import AnyTrack -from unshackle.core.drm import key_args as drm_key_args -from unshackle.core.drm.decrypters import decrypt_cenc, mp4decrypt, shaka_decrypt +from unshackle.core.drm.cenc import PLACEHOLDER_KIDS, WIDEVINE_ID, CencDrm, as_kid from unshackle.core.remote_protocol import APIErrorCode -from unshackle.core.session import AnySession, utf8_text -from unshackle.core.utilities import call_licence, get_boxes, log_event -from unshackle.core.utils import run_proxy -from unshackle.core.utils.subprocess import ffprobe +from unshackle.core.utilities import call_licence, log_event -class Widevine: +class Widevine(CencDrm): """Widevine DRM System.""" - 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 - } + SYSTEM_ID = WIDEVINE_ID + NAME = "Widevine" + PLACEHOLDER_KIDS = PLACEHOLDER_KIDS def __init__(self, pssh: PSSH, kid: UUID | str | bytes | None = None, **kwargs: Any) -> None: if not pssh: @@ -43,19 +33,12 @@ class Widevine: if pssh.system_id == PSSH.SystemId.PlayReady: pssh = self.from_playready(pssh) - self._kid: UUID | None = None - if kid: - if isinstance(kid, str): - kid = UUID(hex=kid) - elif isinstance(kid, bytes): - kid = UUID(bytes=kid) - if not isinstance(kid, UUID): - raise ValueError(f"Expected kid to be a {UUID}, str, or bytes, not {kid!r}") - self._kid = kid + self._kid = as_kid(kid) + if self._kid: if pssh.key_ids and all(k in self.PLACEHOLDER_KIDS for k in pssh.key_ids): - pssh.set_key_ids([kid]) - elif kid not in (pssh.key_ids or []): - pssh.set_key_ids([*(pssh.key_ids or []), kid]) + pssh.set_key_ids([self._kid]) + elif self._kid not in (pssh.key_ids or []): + pssh.set_key_ids([*(pssh.key_ids or []), self._kid]) self._pssh = pssh @@ -87,112 +70,15 @@ class Widevine: return PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=list(dict.fromkeys(kids))) @classmethod - def from_track(cls, track: AnyTrack, session: AnySession | None = None) -> Widevine: - """ - Get PSSH and KID from within the Initiation Segment of the Track Data. - It also tries to get PSSH and KID from other track data like M3U8 data - as well as through FFprobe. - - Make a Widevine DRM System object from a track's information. - Use this method only when a PSSH cannot be given directly. - It is *rare* to need to use this. - - You can give your own `requests.Session` to use custom headers - and more. - - Raises: - PSSHNotFound: If the PSSH was not found within the data. - KIDNotFound: If the KID was not found within the data or PSSH. - """ - if not session: - session = run_proxy.fallback_session() - session.headers.update(config.headers) - - kid: UUID | None = None - pssh_boxes: list[Container] = [] - tenc_boxes: list[Container] = [] - - if track.descriptor == track.Descriptor.HLS: - m3u_url = track.url - assert isinstance(m3u_url, str) - master = m3u8.loads(utf8_text(session.get(m3u_url)), uri=m3u_url) - pssh_boxes.extend( - Box.parse(base64.b64decode(x.uri.split(",")[-1])) - for x in (master.session_keys or master.keys) - if x and x.keyformat and x.keyformat.lower() == WidevineCdm.urn - ) - - init_data = track.get_init_segment(session=session) - if init_data: - # try get via ffprobe, needed for non mp4 data e.g. WEBM from Google Play - probe = ffprobe(init_data) - if probe: - for stream in probe.get("streams") or []: - enc_key_id = stream.get("tags", {}).get("enc_key_id") - if enc_key_id: - kid = UUID(bytes=base64.b64decode(enc_key_id)) - pssh_boxes.extend(list(get_boxes(init_data, b"pssh"))) - tenc_boxes.extend(list(get_boxes(init_data, b"tenc"))) - - pssh = next((b for b in pssh_boxes if b.system_ID == PSSH.SystemId.Widevine), None) - if not pssh: - raise Widevine.Exceptions.PSSHNotFound("PSSH was not found in track data.") - - tenc = next(iter(tenc_boxes), None) - if not kid and tenc and tenc.key_ID.int != 0: - kid = tenc.key_ID - - return cls(pssh=PSSH(pssh), kid=kid) - - @classmethod - def from_init_data(cls, init_data: bytes) -> Widevine: - """ - Get PSSH and KID from within Initialization Segment Data. - - Use this method only when a PSSH cannot be given directly. - It is *rare* to need to use this. - - Raises: - PSSHNotFound: If the PSSH was not found within the data. - KIDNotFound: If the KID was not found within the data or PSSH. - """ - if not init_data: - raise ValueError("Init data should be provided.") - if not isinstance(init_data, bytes): - raise TypeError(f"Expected init data to be bytes, not {init_data!r}") - - kid: UUID | None = None - pssh_boxes: list[Container] = list(get_boxes(init_data, b"pssh")) - tenc_boxes: list[Container] = list(get_boxes(init_data, b"tenc")) - - # try get via ffprobe, needed for non mp4 data e.g. WEBM from Google Play - probe = ffprobe(init_data) - if probe: - for stream in probe.get("streams") or []: - enc_key_id = stream.get("tags", {}).get("enc_key_id") - if enc_key_id: - kid = UUID(bytes=base64.b64decode(enc_key_id)) - - pssh = next((b for b in pssh_boxes if b.system_ID == PSSH.SystemId.Widevine), None) - if not pssh: - raise Widevine.Exceptions.PSSHNotFound("PSSH was not found in track data.") - - tenc = next(iter(tenc_boxes), None) - if not kid and tenc and tenc.key_ID.int != 0: - kid = tenc.key_ID - - return cls(pssh=PSSH(pssh), kid=kid) + def from_pssh_box(cls, box: Container, kid: UUID | None) -> Widevine: + """Make the DRM from a parsed Widevine pssh box and the track's own KID.""" + return cls(pssh=PSSH(box), kid=kid) @property def pssh(self) -> PSSH: """Get Protection System Specific Header Box.""" return self._pssh - @property - def kid(self) -> UUID | None: - """Get first Key ID, if any.""" - return next(iter(self.kids), None) - @property def kids(self) -> list[UUID]: """Get all Key IDs from PSSH, falling back to the externally provided KID.""" @@ -203,12 +89,6 @@ class Widevine: return [self._kid] return [] - def to_dict(self) -> dict[str, Any]: - """This DRM in the export form; see ``wire.drm_to_dict``.""" - from unshackle.core.wire import drm_to_dict - - return drm_to_dict(self) - def get_content_keys(self, cdm: WidevineCdm, certificate: Callable, licence: Callable) -> None: """ Make a CDM Session and get Content Keys for this DRM Instance. @@ -284,32 +164,6 @@ class Widevine: finally: cdm.close(session_id) - def decrypt(self, path: Path) -> None: - """Decrypt the file at ``path`` in place with this track's Widevine content keys.""" - decrypt_cenc(self, path, "Widevine") - - def own_kids(self) -> list[UUID]: - """Return the KIDs that identify this track's own content key. - - The KID given to the constructor (from the manifest or the init segment) names the - track exactly. A PSSH can name the KIDs of other renditions too. - """ - if self._kid and self._kid in self.content_keys: - return [self._kid] - return self.kids - - def mp4decrypt_key_args(self, track_kids: dict[int, UUID] | None = None) -> list[str]: - """Build the mp4decrypt --key arguments for every content key, the zero-KID and the track ID fallbacks.""" - return drm_key_args.mp4decrypt_key_args(self.content_keys, self.own_kids(), track_kids) - - def decrypt_with_mp4decrypt(self, path: Path) -> None: - """Decrypt with mp4decrypt.""" - mp4decrypt(path, self.mp4decrypt_key_args) - - def decrypt_with_shaka_packager(self, path: Path) -> None: - """Decrypt with shaka-packager.""" - shaka_decrypt(path, drm_key_args.shaka_keys(self.content_keys, self.own_kids()), "Widevine") - class Exceptions: class PSSHNotFound(Exception): """PSSH (Protection System Specific Header) was not found.""" diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py index 8e0f9933..34d75153 100644 --- a/unshackle/core/manifests/hls.py +++ b/unshackle/core/manifests/hls.py @@ -24,8 +24,6 @@ import m3u8 import requests from langcodes import Language, tag_is_valid from m3u8 import M3U8 -from pyplayready.system.pssh import PSSH as PR_PSSH -from pywidevine.cdm import Cdm as WidevineCdm from pywidevine.pssh import PSSH as WV_PSSH from requests import Session @@ -34,6 +32,7 @@ from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm, is_widevi from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, PlayReady, Widevine +from unshackle.core.drm.cenc import PLAYREADY_ID, WIDEVINE_ID, hls_key_drm, key_data, key_system from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use from unshackle.core.drm.verify import decrypt_track from unshackle.core.events import events @@ -49,7 +48,7 @@ from unshackle.core.manifests.segment_pipeline import ( ) from unshackle.core.session import RnetResponse, RnetSession, utf8_text from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume -from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, assert_fragments_decrypted +from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track, assert_fragments_decrypted from unshackle.core.utilities import get_extension, is_close_match, log_event, try_ensure_utf8 from unshackle.core.utils import run_proxy from unshackle.core.utils.redact import safe_display_url @@ -1337,15 +1336,7 @@ class HLS: keyformat=item.get("keyformat"), keyformatversions=",".join(item.get("keyformatversion") or item.get("keyformatversions") or []), ) - if key.method in {"AES-128", "ISO-23001-7"} or ( - key.keyformat - and key.keyformat.lower() - in { - WidevineCdm.urn, - f"urn:uuid:{PR_PSSH.SYSTEM_ID}", - "com.microsoft.playready", - } - ): + if key.method in {"AES-128", "ISO-23001-7"} or key_system(key): keys.append(key) return keys @@ -1365,13 +1356,11 @@ class HLS: A track's drm_preference wins over the CDM. If the playlist has no EXT-X-KEY entry for it, the CDM decides as usual. """ - playready_urn = f"urn:uuid:{PR_PSSH.SYSTEM_ID}" - playready_keyformats = {playready_urn, "com.microsoft.playready"} if drm_preference: if DRM_PREFERENCE_TYPES[drm_preference] is PlayReady: - preferred = [k for k in keys if k.keyformat and k.keyformat.lower() in playready_keyformats] + preferred = [k for k in keys if key_system(k) == PLAYREADY_ID] else: - preferred = [k for k in keys if k.keyformat and k.keyformat.lower() == WidevineCdm.urn] + preferred = [k for k in keys if key_system(k) == WIDEVINE_ID] if preferred: return preferred logging.getLogger("HLS").warning( @@ -1379,9 +1368,9 @@ class HLS: "using the CDM's DRM instead" ) if is_widevine_cdm(cdm): - return [k for k in keys if k.keyformat and k.keyformat.lower() == WidevineCdm.urn] + return [k for k in keys if key_system(k) == WIDEVINE_ID] elif is_playready_cdm(cdm): - return [k for k in keys if k.keyformat and k.keyformat.lower() in playready_keyformats] + return [k for k in keys if key_system(k) == PLAYREADY_ID] return keys @staticmethod @@ -1408,7 +1397,7 @@ class HLS: @staticmethod def get_track_kid_from_init( master: M3U8, - track: AnyTrack, + track: Track, session: Session | RnetSession, init_section: m3u8.model.InitializationSection | None = None, ) -> UUID | None: @@ -1467,12 +1456,7 @@ class HLS: return key elif key.method == "ISO-23001-7": return key - elif key.keyformat and key.keyformat.lower() == WidevineCdm.urn: - return key - elif key.keyformat and key.keyformat.lower() in { - f"urn:uuid:{PR_PSSH.SYSTEM_ID}", - "com.microsoft.playready", - }: + elif key_system(key): return key else: unsupported_systems.append(key.method + (f" ({key.keyformat})" if key.keyformat else "")) @@ -1507,23 +1491,9 @@ class HLS: if key.method == "AES-128": drm = ClearKey.from_m3u_key(key, session) elif key.method == "ISO-23001-7": - drm = Widevine(pssh=WV_PSSH.new(key_ids=[key.uri.split(",")[-1]], system_id=WV_PSSH.SystemId.Widevine)) - elif key.keyformat and key.keyformat.lower() == WidevineCdm.urn: - extra_params = dict(key._extra_params) # noqa - pssh = WV_PSSH(key.uri.split(",")[-1]) - if kid in Widevine.PLACEHOLDER_KIDS or any(k not in Widevine.PLACEHOLDER_KIDS for k in pssh.key_ids): - kid = None - # a v0 PSSH can carry no KID: the tag's own KEYID is the first source, the init segment the last - tag_kid = extra_params.pop("keyid", None) or extra_params.pop("kid", None) - if isinstance(tag_kid, str): - tag_kid = tag_kid.removeprefix("0x").removeprefix("0X") - drm = Widevine( - pssh=pssh, - kid=tag_kid or kid, - **extra_params, - ) - elif key.keyformat and key.keyformat.lower() in {f"urn:uuid:{PR_PSSH.SYSTEM_ID}", "com.microsoft.playready"}: - drm = PlayReady.from_pssh_b64(key.uri.split(",")[-1]) + drm = Widevine(pssh=WV_PSSH.new(key_ids=[key_data(key)], system_id=WV_PSSH.SystemId.Widevine)) + elif cenc_drm := hls_key_drm(key, kid): + drm = cenc_drm else: raise NotImplementedError(f"The key system is not supported: {key}") @@ -1533,7 +1503,7 @@ class HLS: def get_drm_or_probe( key: m3u8.model.SessionKey | m3u8.model.Key, master: M3U8, - track: AnyTrack, + track: Track, session: Session | RnetSession | None = None, init_section: m3u8.model.InitializationSection | None = None, probe_session: Any = None, diff --git a/unshackle/core/tracks/track.py b/unshackle/core/tracks/track.py index a8e0f315..af9a5d1f 100644 --- a/unshackle/core/tracks/track.py +++ b/unshackle/core/tracks/track.py @@ -1,4 +1,3 @@ -import base64 import contextlib import html import logging @@ -29,6 +28,7 @@ from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled from unshackle.core.downloaders.requests import requests from unshackle.core.drm import DRM_T, BlowfishStripe, PlayReady, Widevine +from unshackle.core.drm.cenc import init_kid, key_system from unshackle.core.drm.verify import ( children, decrypt_track, @@ -42,9 +42,8 @@ from unshackle.core.events import events from unshackle.core.session import MAX_BACKOFF, AnySession, RnetSession, utf8_text from unshackle.core.temp import restore_segments, stash_segments from unshackle.core.tracks import resume -from unshackle.core.utilities import get_boxes, language_name, log_event, try_ensure_utf8 +from unshackle.core.utilities import language_name, log_event, try_ensure_utf8 from unshackle.core.utils import run_proxy -from unshackle.core.utils.subprocess import ffprobe DRM_PREFERENCE_TYPES: dict[str, type[Widevine] | type[PlayReady]] = { "wv": Widevine, @@ -1055,23 +1054,7 @@ class Track: if not isinstance(init_data, bytes): raise TypeError(f"Expected init_data to be bytes, not {init_data!r}") - probe = ffprobe(init_data) - if probe: - for stream in probe.get("streams") or []: - enc_key_id = stream.get("tags", {}).get("enc_key_id") - if enc_key_id: - return UUID(bytes=base64.b64decode(enc_key_id)) - - for tenc in get_boxes(init_data, b"tenc"): - if tenc.key_ID.int != 0: - return tenc.key_ID - - for uuid_box in get_boxes(init_data, b"uuid"): - if uuid_box.extended_type == UUID("8974dbce-7be7-4c51-84f9-7148f9882554"): - tenc = uuid_box.data - if tenc.key_ID.int != 0: - return tenc.key_ID - return None + return init_kid(init_data) def load_drm_if_needed(self, service: Any | None = None) -> bool: """ @@ -1114,9 +1097,8 @@ class Track: try: import m3u8 - from pyplayready.system.pssh import PSSH as PR_PSSH - from pywidevine.cdm import Cdm as WidevineCdm - from pywidevine.pssh import PSSH as WV_PSSH + + from unshackle.core.manifests.hls import HLS session = getattr(self, "session", None) or run_proxy.fallback_session() assert isinstance(self.url, str) @@ -1124,22 +1106,11 @@ class Track: response = session.get(self.url) playlist = m3u8.loads(utf8_text(response), self.url) - drm_list = [] - - for key in playlist.keys or []: - if not key or not key.keyformat: - continue - - fmt = key.keyformat.lower() - if fmt == WidevineCdm.urn: - pssh_b64 = key.uri.split(",")[-1] - drm: DRM_T = Widevine(pssh=WV_PSSH(pssh_b64)) - drm_list.append(drm) - elif fmt in {f"urn:uuid:{PR_PSSH.SYSTEM_ID}", "com.microsoft.playready"}: - pssh_b64 = key.uri.split(",")[-1] - drm = PlayReady.from_pssh_b64(pssh_b64) - drm_list.append(drm) - + drm_list: list[DRM_T] = [ + HLS.get_drm_or_probe(key, playlist, self, probe_session=session) + for key in playlist.keys or [] + if key_system(key) + ] if drm_list: self.drm = drm_list self.needs_drm_loading = False