refactor(manifests): pick the licensable DRM and KID in one licence step

This commit is contained in:
imSp4rky
2026-11-25 16:28:55 -07:00
parent 4d3df8e74f
commit 1a63076df2
9 changed files with 260 additions and 87 deletions
+2 -2
View File
@@ -41,8 +41,8 @@ def playready_object(kid: UUID) -> str:
return base64.b64encode(pro).decode() return base64.b64encode(pro).decode()
def widevine() -> Widevine: def widevine(kid: UUID = KID) -> Widevine:
return Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID])) return Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[kid]))
def playready(kid: UUID = KID) -> PlayReady: def playready(kid: UUID = KID) -> PlayReady:
@@ -10,9 +10,10 @@ from pathlib import Path
from typing import Any from typing import Any
from uuid import UUID from uuid import UUID
import pytest
from pywidevine.pssh import PSSH from pywidevine.pssh import PSSH
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY
from unshackle.core.manifests.hls import HLS from unshackle.core.manifests.hls import HLS
from unshackle.core.remote_service import segment_uri_filter from unshackle.core.remote_service import segment_uri_filter
from unshackle.core.tracks import Video from unshackle.core.tracks import Video
@@ -76,6 +77,44 @@ def test_licence_only_licenses_a_key_that_starts_part_way(tmp_path: Path, monkey
assert track.data["hls"]["unwanted_segments"] == [] assert track.data["hls"]["unwanted_segments"] == []
def test_a_refused_later_key_fails_through_the_licence_step(tmp_path: Path, monkeypatch: Any) -> 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")
track = Video(
url="https://example.test/media.m3u8",
language="en",
descriptor=Track.Descriptor.HLS,
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:
raise PermissionError("EXAMPLE licence refused")
statuses: list[str] = []
ctx = DownloadContext(
save_path=tmp_path / "video.mp4",
save_dir=tmp_path / "video_segments",
progress=lambda **kw: statuses.append(kw["downloaded"]) if "downloaded" in kw else None,
license_widevine=licence,
cdm=None,
)
DOWNLOAD_LICENCE_ONLY.set()
try:
with pytest.raises(PermissionError, match="EXAMPLE licence refused"):
HLS.download_track(track=track, ctx=ctx)
assert DOWNLOAD_CANCELLED.is_set()
finally:
DOWNLOAD_LICENCE_ONLY.clear()
DOWNLOAD_CANCELLED.clear()
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, monkeypatch: Any) -> None:
"""The filtered segment URIs go to the track data, and an import filter built from them drops the same segment.""" """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 = tmp_path / "media.m3u8"
+44 -1
View File
@@ -18,20 +18,23 @@ from pathlib import Path
from uuid import UUID from uuid import UUID
import pytest import pytest
import requests
from Cryptodome.Cipher import AES from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad from Cryptodome.Util.Padding import pad
from pywidevine.pssh import PSSH from pywidevine.pssh import PSSH
from tests.core.test_hls_kid_from_init import KEY_LINE, no_kid_pssh from tests.core.test_hls_kid_from_init import KEY_LINE, no_kid_pssh
from tests.core.test_ism_init import piff_fragment from tests.core.test_ism_init import piff_fragment
from unshackle.core import constants
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import MonaLisa, Widevine from unshackle.core.drm import ClearKeyCENC, MonaLisa, Widevine
from unshackle.core.manifests import DASH, HLS, ISM from unshackle.core.manifests import DASH, HLS, ISM
from unshackle.core.manifests import dash as dash_module from unshackle.core.manifests import dash as dash_module
from unshackle.core.manifests import hls as hls_module from unshackle.core.manifests import hls as hls_module
from unshackle.core.manifests import segment_pipeline from unshackle.core.manifests import segment_pipeline
from unshackle.core.manifests.ism_init import PIFF_SENC_UUID 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 import track as track_module
from unshackle.core.tracks.track import DownloadContext from unshackle.core.tracks.track import DownloadContext
@@ -401,3 +404,43 @@ def test_hls_rekey_takes_the_kid_from_the_init_segment_of_the_new_key(server, tm
HLS.download_track(track, ctx) HLS.download_track(track, ctx)
assert licensed == [KID, later_kid] assert licensed == [KID, later_kid]
@pytest.mark.parametrize("system", ["Widevine", "ClearKeyCENC"])
@pytest.mark.parametrize("kind", ["dash", "hls", "ism", "url"])
def test_each_manifest_kind_licenses_through_the_licence_step(server, tmp_path, monkeypatch, kind, system):
"""A licence-only run of every download path: the step picks the systems and the KID for each kind.
The fake inits name no KID, so DASH and URL pass none, and HLS and ISM take the KID their DRM names.
"""
drm = widevine() if system == "Widevine" else ClearKeyCENC(kids=[KID])
licensed: list[tuple[object, object]] = []
def licence(drm, track_kid=None):
licensed.append((drm, track_kid))
if kind == "url":
track = Video(url=f"{base(server)}init.mp4", language="en", descriptor=Video.Descriptor.URL, drm=[drm])
else:
track = {"dash": dash_track, "hls": lambda srv: hls_track(srv, False), "ism": ism_track}[kind](server)
track.drm = [drm]
ctx = make_ctx(tmp_path, f"{kind}.mp4")
ctx.license_widevine = licence
monkeypatch.setattr(constants.DOWNLOAD_LICENCE_ONLY, "is_set", lambda: True)
if kind == "url":
track.download(requests.Session(), licence, progress=ctx.progress)
else:
{"dash": DASH, "hls": HLS, "ism": ISM}[kind].download_track(track, ctx)
expected = {
("dash", "Widevine"): [(drm, None)],
("dash", "ClearKeyCENC"): [(drm, None)],
("hls", "Widevine"): [(drm, KID)],
("hls", "ClearKeyCENC"): [],
("ism", "Widevine"): [(drm, KID)],
("ism", "ClearKeyCENC"): [],
("url", "Widevine"): [(drm, None)],
("url", "ClearKeyCENC"): [(drm, None)],
}
assert licensed == expected[(kind, system)]
+105 -19
View File
@@ -11,8 +11,9 @@ from uuid import UUID
import pytest import pytest
from tests.core.test_all_drm import playready, widevine
from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import verify from unshackle.core.drm import ClearKey, ClearKeyCENC, MonaLisa, verify
from unshackle.core.events import events from unshackle.core.events import events
from unshackle.core.manifests.segment_pipeline import ( from unshackle.core.manifests.segment_pipeline import (
RollingMerge, RollingMerge,
@@ -20,9 +21,9 @@ from unshackle.core.manifests.segment_pipeline import (
complete_track, complete_track,
fetch_segments, fetch_segments,
license_drm, license_drm,
licensing,
) )
from unshackle.core.tracks.track import DownloadContext from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks.track import DownloadContext, Track
INIT = b"init" * 8 INIT = b"init" * 8
DECRYPTED_INIT = b"clear-init" * 8 DECRYPTED_INIT = b"clear-init" * 8
@@ -197,17 +198,91 @@ def test_a_short_rolling_merge_raises_and_removes_the_output(tmp_path):
check_merged(merger, 0, SimpleNamespace(id="EXAMPLE"), ctx, "EXAMPLE") # type: ignore[arg-type] check_merged(merger, 0, SimpleNamespace(id="EXAMPLE"), ctx, "EXAMPLE") # type: ignore[arg-type]
def test_license_drm_wraps_the_callback_in_licensing_progress(tmp_path): WV, PR, CKC, ML, AES = "Widevine", "PlayReady", "ClearKeyCENC", "MonaLisa", "ClearKey"
received: list[tuple[Any, dict[str, Any]]] = [] PSSH_KID = UUID(hex="22222222222222222222222222222222")
ctx = make_ctx(tmp_path, license_widevine=lambda drm, **kw: received.append((drm, kw))) PROBED_KID = UUID(hex="33333333333333333333333333333333")
drm = object() URL, DASH_, HLS_, ISM_ = (Track.Descriptor.URL, Track.Descriptor.DASH, Track.Descriptor.HLS, Track.Descriptor.ISM)
with licensing(ctx):
license_drm(drm, ctx, track_kid=KID) # type: ignore[arg-type]
assert received == [(drm, {"track_kid": KID})] def make_drm(system: str, monkeypatch: pytest.MonkeyPatch) -> Any:
assert ctx.statuses == ["LICENSING", "[yellow]LICENSED"] """One DRM of each system; every one that names a KID names PSSH_KID."""
assert not DOWNLOAD_CANCELLED.is_set() if system == WV:
return widevine(PSSH_KID)
if system == PR:
return playready(PSSH_KID)
if system == CKC:
return ClearKeyCENC(kids=[PSSH_KID])
if system == ML:
monkeypatch.setattr(MonaLisa, "extract_keys", lambda self: None)
return MonaLisa("EXAMPLE", Path("unused.mld"))
return ClearKey(key=bytes(16))
def licence_calls(tmp_path: Path) -> tuple[DownloadContext, list[tuple[Any, Any]]]:
calls: list[tuple[Any, Any]] = []
return make_ctx(tmp_path, license_widevine=lambda drm, track_kid: calls.append((drm, track_kid))), calls
LICENSED = {URL: {WV, PR, CKC}, DASH_: {WV, PR, CKC}, HLS_: {WV, PR, ML}, ISM_: {WV, PR}}
@pytest.mark.parametrize("descriptor", list(LICENSED), ids=lambda d: d.name)
@pytest.mark.parametrize("system", [WV, PR, CKC, ML, AES])
def test_the_licence_step_licenses_the_systems_each_manifest_kind_licensed(tmp_path, monkeypatch, descriptor, system):
ctx, calls = licence_calls(tmp_path)
drm = make_drm(system, monkeypatch)
license_drm(SimpleNamespace(descriptor=descriptor, id="EXAMPLE"), drm, ctx) # type: ignore[arg-type]
licensed = system in LICENSED[descriptor]
assert [c[0] for c in calls] == ([drm] if licensed else [])
assert ctx.statuses == (["LICENSING", "[yellow]LICENSED"] if licensed else []) # type: ignore[attr-defined]
def test_the_licence_step_skips_a_track_with_no_drm(tmp_path):
ctx, calls = licence_calls(tmp_path)
license_drm(SimpleNamespace(descriptor=DASH_, id="EXAMPLE"), None, ctx) # type: ignore[arg-type]
assert calls == [] and ctx.statuses == [] # type: ignore[attr-defined]
@pytest.mark.parametrize(
"descriptor, system, kid, probed, expected",
[
(DASH_, WV, KID, None, KID),
(DASH_, WV, None, PROBED_KID, PROBED_KID),
(DASH_, WV, None, None, None),
(URL, CKC, None, "no probe", None),
(HLS_, WV, KID, "no probe", KID),
(HLS_, PR, None, "no probe", PSSH_KID),
(HLS_, WV, None, None, PSSH_KID),
(HLS_, ML, KID, PROBED_KID, None),
(ISM_, PR, None, "no probe", PSSH_KID),
],
ids=[
"dash-init-kid",
"dash-probed",
"dash-never-the-pssh-kid",
"url-never-the-drm-kid",
"hls-init-kid",
"hls-drm-kid",
"hls-probe-misses",
"monalisa-no-kid",
"ism-drm-kid",
],
)
def test_the_licence_step_finds_the_track_kid(tmp_path, monkeypatch, descriptor, system, kid, probed, expected):
ctx, calls = licence_calls(tmp_path)
probes: list[bool] = []
def probe() -> Any:
probes.append(True)
return probed
track = SimpleNamespace(descriptor=descriptor, id="EXAMPLE")
license_drm(track, make_drm(system, monkeypatch), ctx, kid, None if probed == "no probe" else probe) # type: ignore[arg-type]
assert [c[1] for c in calls] == [expected]
assert not (kid and probes), "a KID the caller holds needs no probe"
def test_a_licence_failure_cancels_the_other_tracks_and_shows_failed(tmp_path): def test_a_licence_failure_cancels_the_other_tracks_and_shows_failed(tmp_path):
@@ -216,18 +291,29 @@ def test_a_licence_failure_cancels_the_other_tracks_and_shows_failed(tmp_path):
ctx = make_ctx(tmp_path, license_widevine=refuse) ctx = make_ctx(tmp_path, license_widevine=refuse)
with pytest.raises(PermissionError, match="EXAMPLE licence refused"): with pytest.raises(PermissionError, match="EXAMPLE licence refused"):
with licensing(ctx): license_drm(SimpleNamespace(descriptor=DASH_, id="EXAMPLE"), widevine(KID), ctx) # type: ignore[arg-type]
license_drm(object(), ctx) # type: ignore[arg-type]
assert ctx.statuses == ["LICENSING", "[red]FAILED"] assert ctx.statuses == ["LICENSING", "[red]FAILED"] # type: ignore[attr-defined]
assert DOWNLOAD_CANCELLED.is_set() assert DOWNLOAD_CANCELLED.is_set()
def test_license_drm_without_a_callback_raises(tmp_path): def test_a_failed_kid_probe_fails_only_this_track(tmp_path):
def probe() -> Any:
raise ConnectionError("EXAMPLE init unreachable")
ctx, calls = licence_calls(tmp_path)
with pytest.raises(ConnectionError):
license_drm(SimpleNamespace(descriptor=DASH_, id="EXAMPLE"), widevine(KID), ctx, probe=probe) # type: ignore[arg-type]
assert calls == [] and ctx.statuses == [] # type: ignore[attr-defined]
assert not DOWNLOAD_CANCELLED.is_set()
def test_the_licence_step_without_a_callback_raises_a_drm_error(tmp_path):
ctx = make_ctx(tmp_path) ctx = make_ctx(tmp_path)
with pytest.raises(ValueError, match="license_widevine func must be supplied"): with pytest.raises(ValueError, match="No licence callback for the Widevine DRM of track EXAMPLE") as raised:
license_drm(object(), ctx) # type: ignore[arg-type] license_drm(SimpleNamespace(descriptor=DASH_, id="EXAMPLE"), widevine(KID), ctx) # type: ignore[arg-type]
assert ctx.statuses == [] assert raised.value.error_code == APIErrorCode.DRM_ERROR # type: ignore[attr-defined]
assert ctx.statuses == ["[red]FAILED"] # type: ignore[attr-defined]
@pytest.fixture @pytest.fixture
+2 -10
View File
@@ -38,7 +38,6 @@ from unshackle.core.manifests.segment_pipeline import (
complete_track, complete_track,
fetch_segments, fetch_segments,
license_drm, license_drm,
licensing,
) )
from unshackle.core.manifests.trim import trim_overlaps from unshackle.core.manifests.trim import trim_overlaps
from unshackle.core.session import RnetSession from unshackle.core.session import RnetSession
@@ -641,15 +640,8 @@ class DASH:
pssh_init = init_data pssh_init = init_data
track.drm_from_pssh(cdm, lambda system: system.from_init_data(pssh_init), log) track.drm_from_pssh(cdm, lambda system: system.from_init_data(pssh_init), log)
if track.drm: drm = track.get_drm_for_cdm(cdm)
track_kid = track_kid or track.get_key_id(url=segments[0][0], session=session) license_drm(track, drm, ctx, track_kid, probe=lambda: track.get_key_id(url=segments[0][0], session=session))
drm = track.get_drm_for_cdm(cdm)
if isinstance(drm, (Widevine, PlayReady, ClearKeyCENC)):
# license and grab content keys (ClearKeyCENC uses no CDM)
with licensing(ctx):
license_drm(drm, ctx, track_kid=track_kid)
else:
drm = None
if DOWNLOAD_LICENCE_ONLY.is_set(): if DOWNLOAD_LICENCE_ONLY.is_set():
progress(downloaded="[yellow]SKIPPED") progress(downloaded="[yellow]SKIPPED")
+6 -16
View File
@@ -32,7 +32,7 @@ from unshackle.core import binaries
from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm, is_widevine_cdm from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm, is_widevine_cdm
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, MonaLisa, PlayReady, Widevine from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, PlayReady, Widevine
from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
from unshackle.core.drm.verify import decrypt_track from unshackle.core.drm.verify import decrypt_track
from unshackle.core.events import events from unshackle.core.events import events
@@ -709,7 +709,6 @@ class HLS:
) )
media_drm = HLS.get_drm(media_playlist_key, session, **({"kid": init_kid} if init_kid else {})) media_drm = HLS.get_drm(media_playlist_key, session, **({"kid": init_kid} if init_kid else {}))
if isinstance(media_drm, (Widevine, PlayReady)): if isinstance(media_drm, (Widevine, PlayReady)):
track_kid = init_kid or media_drm.kid
# Preserve pre-existing keys (e.g. from server_cdm) # Preserve pre-existing keys (e.g. from server_cdm)
if track.drm: if track.drm:
for existing_drm in track.drm: for existing_drm in track.drm:
@@ -718,8 +717,7 @@ class HLS:
track.drm = [media_drm] track.drm = [media_drm]
if DOWNLOAD_ALL_DRM.is_set(): if DOWNLOAD_ALL_DRM.is_set():
track.drm += HLS.alternate_drm(media_keys, media_drm, session, init_kid) track.drm += HLS.alternate_drm(media_keys, media_drm, session, init_kid)
with licensing(ctx): license_drm(track, media_drm, ctx, init_kid)
license_drm(media_drm, ctx, track_kid=track_kid)
initial_drm_licensed = True initial_drm_licensed = True
initial_drm_key = media_playlist_key initial_drm_key = media_playlist_key
session_drm = media_drm session_drm = media_drm
@@ -730,14 +728,8 @@ class HLS:
initial_drm_key = media_playlist_key initial_drm_key = media_playlist_key
initial_drm_licensed = True initial_drm_licensed = True
if not initial_drm_licensed and session_drm and isinstance(session_drm, (Widevine, PlayReady)): if not initial_drm_licensed:
with licensing(ctx): license_drm(track, session_drm, ctx, probe=lambda: HLS.get_track_kid_from_init(master, track, session))
track_kid = HLS.get_track_kid_from_init(master, track, session) or session_drm.kid
license_drm(session_drm, ctx, track_kid=track_kid)
if not initial_drm_licensed and session_drm and isinstance(session_drm, MonaLisa):
with licensing(ctx):
license_drm(session_drm, ctx)
if DOWNLOAD_LICENCE_ONLY.is_set(): if DOWNLOAD_LICENCE_ONLY.is_set():
# a playlist can change its key part-way, and only the download loop licenses the later keys # a playlist can change its key part-way, and only the download loop licenses the later keys
@@ -750,8 +742,7 @@ class HLS:
continue continue
licensed_keys.append(key) licensed_keys.append(key)
later_drm = HLS.get_drm_or_probe(key, master, track, session, segment.init_section) later_drm = HLS.get_drm_or_probe(key, master, track, session, segment.init_section)
if isinstance(later_drm, (Widevine, PlayReady)) and license_widevine: license_drm(track, later_drm, ctx)
license_widevine(later_drm, track_kid=later_drm.kid)
progress(downloaded="[yellow]SKIPPED") progress(downloaded="[yellow]SKIPPED")
return return
@@ -1080,8 +1071,7 @@ class HLS:
with licensing(ctx): with licensing(ctx):
init_kid = track.get_key_id(map_data[1]) if map_data and key.method != "AES-128" else None init_kid = track.get_key_id(map_data[1]) if map_data and key.method != "AES-128" else None
drm = HLS.get_drm(key, session, **({"kid": init_kid} if init_kid else {})) drm = HLS.get_drm(key, session, **({"kid": init_kid} if init_kid else {}))
if isinstance(drm, (Widevine, PlayReady)): license_drm(track, drm, ctx, init_kid)
license_drm(drm, ctx, track_kid=init_kid or drm.kid)
if ( if (
encryption_data encryption_data
and isinstance(drm, (Widevine, PlayReady)) and isinstance(drm, (Widevine, PlayReady))
+2 -9
View File
@@ -35,7 +35,6 @@ from unshackle.core.manifests.segment_pipeline import (
complete_track, complete_track,
fetch_segments, fetch_segments,
license_drm, license_drm,
licensing,
) )
from unshackle.core.session import RnetSession from unshackle.core.session import RnetSession
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video, resume from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video, resume
@@ -419,14 +418,8 @@ class ISM:
segments = segments[kept] segments = segments[kept]
track.data["ism"]["fragment_times"] = segment_times[kept] track.data["ism"]["fragment_times"] = segment_times[kept]
session_drm = None session_drm = track.get_drm_for_cdm(ctx.cdm)
if track.drm: license_drm(track, session_drm, ctx)
# Mirror HLS.download_track: pick the DRM matching the provided CDM
# (or the first available) and license it if supported.
session_drm = track.get_drm_for_cdm(ctx.cdm)
if isinstance(session_drm, (Widevine, PlayReady)):
with licensing(ctx):
license_drm(session_drm, ctx)
if DOWNLOAD_LICENCE_ONLY.is_set(): if DOWNLOAD_LICENCE_ONLY.is_set():
progress(downloaded="[yellow]SKIPPED") progress(downloaded="[yellow]SKIPPED")
+44 -9
View File
@@ -12,14 +12,16 @@ from concurrent.futures import Future
from contextlib import ExitStack, closing, contextmanager from contextlib import ExitStack, closing, contextmanager
from pathlib import Path from pathlib import Path
from typing import Any, BinaryIO, Callable, Iterator, Optional from typing import Any, BinaryIO, Callable, Iterator, Optional
from uuid import UUID
from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack
from unshackle.core.drm import DRM_T from unshackle.core.drm import DRM_T, ClearKeyCENC, MonaLisa, PlayReady, Widevine
from unshackle.core.drm.segment_decrypt import SegmentDecrypter from unshackle.core.drm.segment_decrypt import SegmentDecrypter
from unshackle.core.drm.verify import decrypt_track from unshackle.core.drm.verify import decrypt_track
from unshackle.core.events import events from unshackle.core.events import events
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.session import AnySession from unshackle.core.session import AnySession
from unshackle.core.tracks import DownloadContext, resume from unshackle.core.tracks import DownloadContext, Track, resume
from unshackle.core.tracks.track import assert_fragments_decrypted from unshackle.core.tracks.track import assert_fragments_decrypted
from unshackle.core.utilities import log_event, try_ensure_utf8 from unshackle.core.utilities import log_event, try_ensure_utf8
@@ -92,13 +94,46 @@ def licensing(ctx: DownloadContext) -> Iterator[None]:
raise raise
def license_drm(drm: DRM_T, ctx: DownloadContext, **kwargs: Any) -> None: LICENSABLE: dict[Track.Descriptor, tuple[type, ...]] = {
"""Call ctx.license_widevine for one DRM, with the LICENSING and LICENSED progress around it.""" Track.Descriptor.URL: (Widevine, PlayReady, ClearKeyCENC),
if not ctx.license_widevine: Track.Descriptor.DASH: (Widevine, PlayReady, ClearKeyCENC),
raise ValueError("license_widevine func must be supplied to use DRM") Track.Descriptor.HLS: (Widevine, PlayReady, MonaLisa),
ctx.progress(downloaded="LICENSING") Track.Descriptor.ISM: (Widevine, PlayReady),
ctx.license_widevine(drm, **kwargs) }
ctx.progress(downloaded="[yellow]LICENSED") """The DRM systems the licence step licenses, by the kind of manifest the track comes from."""
def license_drm(
track: AnyTrack,
drm: Optional[DRM_T],
ctx: DownloadContext,
kid: Optional[UUID] = None,
probe: Optional[Callable[[], Optional[UUID]]] = None,
) -> None:
"""The licence step: get the content keys of `drm` for `track` through ctx.license_widevine, with progress.
A DRM system that LICENSABLE does not list for the track gets no licence. The track KID is `kid`, else
what `probe` reads from the init. An HLS or ISM DRM comes from the track's own key tag or protection
header, so its first KID stands in when the init names none. A MonaLisa DRM gets no KID: its ticket gives
the track's own key. A failed `probe` fails only this track; a failed licence cancels the run.
ctx.license_widevine licenses every DRM system; dl and services pass it by keyword.
"""
if not isinstance(drm, LICENSABLE[track.descriptor]):
return
track_kid = None
if not isinstance(drm, MonaLisa):
track_kid = kid or (probe() if probe else None)
if not track_kid and track.descriptor in (Track.Descriptor.HLS, Track.Descriptor.ISM):
track_kid = getattr(drm, "kid", None)
with licensing(ctx):
if not ctx.license_widevine:
raise coded(
ValueError(f"No licence callback for the {type(drm).__name__} DRM of track {track.id}"),
APIErrorCode.DRM_ERROR,
)
ctx.progress(downloaded="LICENSING")
ctx.license_widevine(drm, track_kid=track_kid)
ctx.progress(downloaded="[yellow]LICENSED")
def fetch_segments( def fetch_segments(
+15 -20
View File
@@ -27,7 +27,7 @@ from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled
from unshackle.core.downloaders.requests import requests from unshackle.core.downloaders.requests import requests
from unshackle.core.drm import DRM_T, BlowfishStripe, ClearKeyCENC, PlayReady, Widevine from unshackle.core.drm import DRM_T, BlowfishStripe, PlayReady, Widevine
from unshackle.core.drm.verify import ( from unshackle.core.drm.verify import (
children, children,
decrypt_track, decrypt_track,
@@ -723,6 +723,7 @@ class Track:
track's init data and stores it on the track, so a service need not declare `drm` itself. track's init data and stores it on the track, so a service need not declare `drm` itself.
""" """
from unshackle.core.manifests import DASH, HLS, ISM from unshackle.core.manifests import DASH, HLS, ISM
from unshackle.core.manifests.segment_pipeline import license_drm
from unshackle.core.tracks.audio import Audio from unshackle.core.tracks.audio import Audio
from unshackle.core.tracks.subtitle import Subtitle from unshackle.core.tracks.subtitle import Subtitle
from unshackle.core.tracks.video import Video from unshackle.core.tracks.video import Video
@@ -803,19 +804,19 @@ class Track:
self.Descriptor.DASH: DASH, self.Descriptor.DASH: DASH,
self.Descriptor.ISM: ISM, self.Descriptor.ISM: ISM,
} }
ctx = DownloadContext(
save_path=save_path,
save_dir=save_dir,
progress=progress,
session=dl_session,
proxy=proxy,
max_workers=max_workers,
adaptive_workers=adaptive_workers,
download_processes=download_processes,
license_widevine=prepare_drm,
cdm=cdm,
)
if self.descriptor in manifest_parsers: if self.descriptor in manifest_parsers:
ctx = DownloadContext(
save_path=save_path,
save_dir=save_dir,
progress=progress,
session=dl_session,
proxy=proxy,
max_workers=max_workers,
adaptive_workers=adaptive_workers,
download_processes=download_processes,
license_widevine=prepare_drm,
cdm=cdm,
)
manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx) manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx)
elif self.descriptor == self.Descriptor.URL: elif self.descriptor == self.Descriptor.URL:
try: try:
@@ -831,13 +832,7 @@ class Track:
if self.drm: if self.drm:
drm = self.get_drm_for_cdm(cdm) drm = self.get_drm_for_cdm(cdm)
track_kid = None if isinstance(drm, BlowfishStripe) else self.get_key_id(session=session) track_kid = None if isinstance(drm, BlowfishStripe) else self.get_key_id(session=session)
if isinstance(drm, (Widevine, PlayReady, ClearKeyCENC)): license_drm(self, drm, ctx, track_kid)
if not prepare_drm:
system = type(drm).__name__.removesuffix("CENC")
raise ValueError(f"prepare_drm func must be supplied to use {system} DRM")
progress(downloaded="LICENSING")
prepare_drm(drm, track_kid=track_kid)
progress(downloaded="[yellow]LICENSED")
else: else:
drm = None drm = None