"""A MonaLisa track whose content key does not decode stops after the merge, through ``HLS.download_track``. The segments are a real HEVC clip in the synthetic BBTS format, and the built-in decrypter decrypts them. """ from __future__ import annotations import subprocess import threading from collections.abc import Iterator from http.server import ThreadingHTTPServer from pathlib import Path from uuid import UUID import click import pytest from tests.core import bbts_sample from tests.core.key_resolver import MemoryVault, resolver, vaults_of from tests.core.test_rolling_merge_hls_ism import _Handler, base, make_ctx from unshackle.core import binaries from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.drm import MonaLisa, monalisa, verify from unshackle.core.manifests import HLS from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.tracks import Audio, Video from unshackle.core.tracks.track import DownloadContext from unshackle.core.utils.subprocess import ffmpeg_decodes pytestmark = pytest.mark.skipif(binaries.FFMPEG is None, reason="requires ffmpeg") KID = UUID(hex="11111111111111111111111111111111") WRONG = "5a" * 16 FPS = 25 @pytest.fixture(scope="module") def segments(tmp_path_factory: pytest.TempPathFactory) -> list[bytes]: """Three 2 s BBTS segments of a 640x360 HEVC clip, encrypted with bbts_sample.KEY and a fixed IV.""" clip = tmp_path_factory.mktemp("bbts") / "clip.hevc" x265 = "keyint=50:min-keyint=50:scenecut=0:bframes=0:aud=1:info=0:repeat-headers=1:log-level=none" source = f"testsrc2=size=640x360:rate={FPS}:duration=6" subprocess.run( [str(binaries.FFMPEG), "-nostdin", "-v", "error", "-f", "lavfi", "-i", source, "-c:v", "libx265"] + ["-preset", "ultrafast", "-pix_fmt", "yuv420p", "-x265-params", x265, "-f", "hevc", str(clip)], check=True, ) return bbts_sample.bbts_segments(clip.read_bytes(), bbts_sample.IVS[0], 2 * FPS, FPS) @pytest.fixture def server(segments: list[bytes]) -> Iterator[ThreadingHTTPServer]: srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) lines = ["#EXTM3U", "#EXT-X-VERSION:3", "#EXT-X-TARGETDURATION:2"] srv.routes = {} # type: ignore[attr-defined] for i, segment in enumerate(segments): srv.routes[f"/{i}.ts"] = segment # type: ignore[attr-defined] lines += ["#EXTINF:2.0,", f"{i}.ts"] srv.routes["/v.m3u8"] = "\n".join([*lines, "#EXT-X-ENDLIST"]).encode() # type: ignore[attr-defined] thread = threading.Thread(target=srv.serve_forever, daemon=True) thread.start() yield srv srv.shutdown() thread.join(timeout=5) DOWNLOAD_CANCELLED.clear() def download( server: ThreadingHTTPServer, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, key: str, memory: MemoryVault, vault: bool, kind: type[Video] | type[Audio] = Video, ) -> tuple[Video | Audio, DownloadContext]: """Download the track with the built-in decrypter and the hook of dl; with ``vault``, ``memory`` is the key's source.""" monkeypatch.setattr(monalisa, "local_tool", lambda: None) keys = resolver(vaults_of(memory, MemoryVault(name="other"))) monkeypatch.setattr(verify, "DECRYPT_HOOK", keys.decrypt_verified) drm = MonaLisa(kid=KID) drm.content_keys[KID] = key if vault: keys.vaults.supplied(KID, key, memory) track = kind(url=f"{base(server)}v.m3u8", language="en", descriptor=kind.Descriptor.HLS) track.drm = [drm] ctx = make_ctx(tmp_path, "monalisa.ts") ctx.license_widevine = lambda *a, **kw: None try: HLS.download_track(track, ctx) finally: keys.wait_vault_writes() return track, ctx @pytest.mark.parametrize("vault", [False, True], ids=["licence", "vault"]) def test_a_wrong_monalisa_key_stops_the_track_and_leaves_no_output(server, tmp_path, monkeypatch, vault: bool) -> None: memory = MemoryVault({KID: WRONG} if vault else {}) refused = f"^The MonaLisa content key of KID {KID.hex} does not decrypt track " with pytest.raises(click.ClickException, match=refused) as e: download(server, tmp_path, monkeypatch, WRONG, memory, vault) assert getattr(e.value, "error_code", None) == APIErrorCode.DRM_ERROR assert not (tmp_path / "monalisa.ts").exists() assert memory.told == [(KID, WRONG)] and not memory.added def test_the_right_monalisa_key_keeps_a_track_that_decodes(server, tmp_path, monkeypatch) -> None: track, ctx = download(server, tmp_path, monkeypatch, bbts_sample.KEY.hex(), MemoryVault(), vault=False) assert track.path == ctx.save_path and ffmpeg_decodes(ctx.save_path) def test_an_audio_track_judges_and_copies_no_vault_key(server, tmp_path, monkeypatch) -> None: """BBTS leaves audio clear, so a decode of an audio track proves no key.""" memory = MemoryVault({KID: WRONG}) download(server, tmp_path, monkeypatch, WRONG, memory, vault=True, kind=Audio) assert (tmp_path / "monalisa.ts").exists() and not memory.told