From f1f91a7d5c5680aa88765207841f51de3adae911 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Thu, 3 Dec 2026 15:51:42 -0700 Subject: [PATCH] feat(drm): decrypt plugin segments as they land on the fetch_segments decrypter seam --- docs/reference/configuration/download.md | 12 +- docs/reference/configuration/drm.md | 4 + tests/core/test_drm_plugin_decode_check.py | 10 +- tests/core/test_hls_key_plan.py | 19 ++- tests/core/test_rolling_merge_hls_ism.py | 132 ++++++++++++++++++- tests/core/test_segment_store.py | 2 + unshackle/core/drm/custom.py | 10 +- unshackle/core/drm/segment_decrypt.py | 131 ++++++++++++------ unshackle/core/manifests/dash.py | 6 +- unshackle/core/manifests/hls.py | 26 ++-- unshackle/core/manifests/hls_key_plan.py | 12 +- unshackle/core/manifests/segment_pipeline.py | 20 ++- unshackle/core/plugins.py | 3 +- unshackle/core/tracks/segment_store.py | 6 +- 14 files changed, 309 insertions(+), 84 deletions(-) diff --git a/docs/reference/configuration/download.md b/docs/reference/configuration/download.md index 7b2610d4..f5ca9687 100644 --- a/docs/reference/configuration/download.md +++ b/docs/reference/configuration/download.md @@ -198,8 +198,8 @@ ranges must all match the previous download, or the download silently restarts c - Single-file (non-segmented) downloads and DASH tracks collapsed to a single ranged download never make segment files, so this option does not apply to them (the downloader has its own in-flight partial-file handling for those). - - HLS resumes Widevine/PlayReady and unencrypted titles only. An AES-128 title always - restarts. An HLS failure after the post-download merge step starts to join or decrypt + - HLS resumes Widevine/PlayReady titles, unencrypted titles, and titles of a DRM plugin + that decrypts each segment. An AES-128 title always restarts. An HLS failure after the post-download merge step starts to join or decrypt segments also restarts, and so does a failure of a multi-period DASH WebVTT subtitle during its merge step. A failure before that point, such as a failed init segment fetch, keeps the downloaded segments. @@ -207,7 +207,7 @@ ranges must all match the previous download, or the download silently restarts c [`decrypt_segments`](drm.md#decrypt_segments) resumes too. A merge during the download keeps its output file up to the last segment it appended, and the next download cuts the file back to that point and appends from there. A segment that - [`decrypt_segments`](drm.md#decrypt_segments) decrypted stays decrypted. The next + [`decrypt_segments`](drm.md#decrypt_segments) or a DRM plugin decrypted stays decrypted. The next download reuses it only with the same content key, and downloads it again when the content key changed. - A multi-period DASH track whose periods restart their timeline does not resume with @@ -247,8 +247,10 @@ with the option on, turn it off. This applies to video and audio tracks from DASH, ISM, and HLS. An HLS track qualifies only when every segment shares one init segment and one `EXT-X-KEY`, with no -`EXT-X-DISCONTINUITY`, and the DRM is Widevine, PlayReady, or none. AES-128 tracks, tracks -with content key rotation or discontinuities, and subtitle tracks keep the merge after the download. +`EXT-X-DISCONTINUITY`, and the DRM is Widevine, PlayReady, or none. A track of a DRM plugin that +decrypts each segment needs no init segment and no `EXT-X-KEY`, only no `EXT-X-DISCONTINUITY`. +AES-128 tracks, tracks with content key rotation or discontinuities, and subtitle tracks keep the +merge after the download. With [`continue_downloads`](#continue_downloads) on, a failed track keeps its output file and the number of segments in it, and the next download continues from there. diff --git a/docs/reference/configuration/drm.md b/docs/reference/configuration/drm.md index 30db2f7c..88e2b70a 100644 --- a/docs/reference/configuration/drm.md +++ b/docs/reference/configuration/drm.md @@ -231,6 +231,10 @@ tracks that use one init segment, one `EXT-X-KEY` and no `EXT-X-DISCONTINUITY`. track keeps the whole-file decryption, and so does a track whose init segment mp4decrypt cannot key by KID when no content key has that KID. +A DRM plugin that decrypts each segment does so as the segments arrive, whatever this option +and `decryption` say, on an HLS track with no `EXT-X-DISCONTINUITY`. The plugin then runs its +fix on the merged file once. + With [`continue_downloads`](download.md#continue_downloads) on, a failed track keeps its decrypted segments, and the next download reuses them when it has the same content key. diff --git a/tests/core/test_drm_plugin_decode_check.py b/tests/core/test_drm_plugin_decode_check.py index f071752e..85294096 100644 --- a/tests/core/test_drm_plugin_decode_check.py +++ b/tests/core/test_drm_plugin_decode_check.py @@ -16,6 +16,7 @@ from tests.core.key_resolver import MemoryVault, resolver, vaults_of from tests.core.test_rolling_merge_hls_ism import _Handler, base, make_ctx from tests.drm_plugins import EXAMPLE, xor from unshackle.core import binaries, plugins +from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.drm import CustomDRM, key_resolution, verify from unshackle.core.manifests import HLS @@ -27,9 +28,12 @@ KEY, WRONG = "a5" * 16, "5a" * 16 PLAIN = [b"EXAMPLE clear segment %d. " % i * 8 for i in range(3)] -@pytest.fixture -def server(monkeypatch: pytest.MonkeyPatch, example_plugins: None) -> Iterator[ThreadingHTTPServer]: - """An HLS playlist of EXAMPLE segments; ffmpeg "decodes" a file only when it is the plaintext.""" +@pytest.fixture(params=[False, True], ids=["post-merge", "rolling"]) +def server( + request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, example_plugins: None +) -> Iterator[ThreadingHTTPServer]: + """An HLS playlist of EXAMPLE segments, merged after or during the download; ffmpeg "decodes" only the plaintext.""" + monkeypatch.setattr(config, "merge_segments", request.param) monkeypatch.setattr(binaries, "FFMPEG", Path("ffmpeg")) monkeypatch.setattr(verify, "kid_windows", lambda path: None) monkeypatch.setattr(key_resolution, "ffmpeg_decodes", lambda path, **kw: path.read_bytes() == b"".join(PLAIN)) diff --git a/tests/core/test_hls_key_plan.py b/tests/core/test_hls_key_plan.py index d4548d4f..3949d067 100644 --- a/tests/core/test_hls_key_plan.py +++ b/tests/core/test_hls_key_plan.py @@ -13,7 +13,7 @@ from tests.core.test_hls_kid_from_init import keyed_segment, no_kid_pssh, playli from tests.core.test_hls_service_drm_keys import KID, OTHER_KID, SKD_KEY, encrypted_init from unshackle.core.cdm.detect import cdm_type_stub from unshackle.core.constants import DOWNLOAD_CANCELLED -from unshackle.core.drm import PlayReady, Widevine, cenc +from unshackle.core.drm import CustomDRM, PlayReady, Widevine, cenc from unshackle.core.manifests.hls import HLS from unshackle.core.manifests.hls_key_plan import HlsKeyPlan from unshackle.core.tracks import Video @@ -170,6 +170,23 @@ def test_one_init_segment_and_one_key_tag_make_a_single_init_track(text: str, si assert plan.single_init(manifest.segments) is single +@pytest.mark.parametrize( + "text, single", + [ + pytest.param(playlist("#EXTINF:6.0,\nseg.ts\n"), True, id="no-init-segment"), + pytest.param(playlist("#EXT-X-KEY:METHOD=NONE\n#EXTINF:6.0,\nseg.ts\n"), True, id="method-none"), + pytest.param(playlist("#EXTINF:6.0,\nseg.ts\n", "#EXTINF:6.0,\nnext.ts\n"), False, id="discontinuity"), + ], +) +def test_a_cipher_that_is_not_cenc_needs_no_init_segment_or_key_tag( + example_plugins: None, text: str, single: bool +) -> None: + plan, _ = plan_of(text) + plan.drm = CustomDRM("example") + + assert plan.single_init(m3u8.loads(text).segments) is single + + @pytest.mark.parametrize("system, drm_class", [("playready", PlayReady), ("widevine", Widevine)]) def test_a_track_with_only_fairplay_tags_is_bridged_and_keeps_no_tag(system: str, drm_class: type) -> None: text = playlist(f'#EXT-X-MAP:URI="a.mp4"\n{SKD_KEY}\n#EXTINF:6.0,\nseg.m4s\n') diff --git a/tests/core/test_rolling_merge_hls_ism.py b/tests/core/test_rolling_merge_hls_ism.py index 20c379dc..149ce57e 100644 --- a/tests/core/test_rolling_merge_hls_ism.py +++ b/tests/core/test_rolling_merge_hls_ism.py @@ -222,6 +222,16 @@ class FakeDRM: kids = [KID] +CIPHER = [b"CIPHER%d" % i + b"X" * (50 + i) for i in range(len(PARTS))] + + +def keyed_example() -> CustomDRM: + """An EXAMPLE plugin DRM that holds the content key of KID.""" + drm = CustomDRM("example", kids=[KID]) + drm.content_keys[KID] = "00" * 16 + return drm + + class FakeSegmentDecrypter: """Per-segment decryption that hands each segment straight back, with a fixed decrypted init.""" @@ -292,7 +302,7 @@ def test_ism_encrypted_rolling_matches_post_merge(server, tmp_path, monkeypatch) def test_hls_segment_decrypt_rolling_writes_decrypted_init(server, tmp_path, monkeypatch): monkeypatch.setattr(hls_module, "can_use", lambda *a, **kw: True) - monkeypatch.setattr(hls_module, "SegmentDecrypter", FakeSegmentDecrypter) + monkeypatch.setattr(hls_module, "make_decrypter", FakeSegmentDecrypter) decrypted = no_decrypt(monkeypatch) def make(): @@ -333,7 +343,7 @@ def test_dash_hands_the_drm_to_the_decrypt_step(server, tmp_path, monkeypatch): @pytest.mark.parametrize("merge_segments", [False, True], ids=["post-merge", "rolling"]) def test_dash_segment_decrypt_writes_decrypted_init_and_only_checks(server, tmp_path, monkeypatch, merge_segments): monkeypatch.setattr(dash_module, "can_use", lambda *a, **kw: True) - monkeypatch.setattr(dash_module, "SegmentDecrypter", FakeSegmentDecrypter) + monkeypatch.setattr(dash_module, "make_decrypter", FakeSegmentDecrypter) monkeypatch.setattr(config, "merge_segments", merge_segments) decrypted = no_decrypt(monkeypatch) track = dash_track(server) @@ -345,6 +355,31 @@ def test_dash_segment_decrypt_writes_decrypted_init_and_only_checks(server, tmp_ assert [decrypt for _, decrypt in decrypted] == [False] +@pytest.mark.parametrize("merge_segments", [False, True], ids=["post-merge", "rolling"]) +def test_dash_segment_plugin_decrypts_each_segment_then_finishes( + server, tmp_path, monkeypatch, example_plugins, merge_segments +): + monkeypatch.setattr(config, "merge_segments", merge_segments) + monkeypatch.setattr( + plugins, + "PLUGINS", + { + "example": dataclasses.replace( + EXAMPLE, decrypt=lambda drm, src, dst: dst.write_bytes(src.read_bytes().upper()) + ) + }, + ) + decrypted = no_decrypt(monkeypatch) + drm = keyed_example() + track = dash_track(server) + track.drm = [drm] + ctx = make_ctx(tmp_path, "dash.mp4") + DASH.download_track(track, ctx) + assert ctx.save_path.read_bytes() == INIT + b"".join(PARTS).upper() + assert FINISHED == [ctx.save_path] + assert decrypted == [(drm, False)] + + @pytest.mark.parametrize("site", ["session-drm", "plugin"]) def test_hls_licence_failure_cancels_the_other_tracks(server, tmp_path, example_plugins, site): drm = CustomDRM("example") if site == "plugin" else widevine() @@ -391,7 +426,7 @@ def test_hls_plugin_decrypts_every_segment_once(server, tmp_path, monkeypatch, e hook = resolver(vaults_of(MemoryVault())).decrypt_verified if hooked else None monkeypatch.setattr(verify, "DECRYPT_HOOK", hook) monkeypatch.setattr(key_resolution, "ffmpeg_decodes", lambda *args, **kwargs: True) - parts = [b"CIPHER%d" % i + b"X" * (50 + i) for i in range(len(PARTS))] + parts = CIPHER for i, part in enumerate(parts): server.routes[f"/part{i}.m4s"] = part lines = ["#EXTM3U", "#EXT-X-VERSION:6", "#EXT-X-TARGETDURATION:4"] @@ -406,8 +441,7 @@ def test_hls_plugin_decrypts_every_segment_once(server, tmp_path, monkeypatch, e lines += ["#EXTINF:4.0,", f"part{i}.m4s"] server.routes["/v.m3u8"] = "\n".join([*lines, "#EXT-X-ENDLIST"]).encode() track = Video(url=f"{base(server)}v.m3u8", language="en", codec=Video.Codec.HEVC, descriptor=Video.Descriptor.HLS) - drm = CustomDRM("example", kids=[KID]) - drm.content_keys[KID] = "00" * 16 + drm = keyed_example() track.drm = [drm] ctx = make_ctx(tmp_path, "plugin.mp4") @@ -420,6 +454,94 @@ def test_hls_plugin_decrypts_every_segment_once(server, tmp_path, monkeypatch, e assert len(FINISHED) == (mode == "segment") +def plugin_track(srv, parts: list[bytes], method_none: bool = False) -> Video: + """An HLS track of `parts` with no init segment, whose EXAMPLE plugin DRM holds its content key.""" + for i, part in enumerate(parts): + srv.routes[f"/part{i}.ts"] = part + lines = ["#EXTM3U", "#EXT-X-VERSION:3", "#EXT-X-TARGETDURATION:4"] + if method_none: + lines.append("#EXT-X-KEY:METHOD=NONE") + for i in range(len(parts)): + lines += ["#EXTINF:4.0,", f"part{i}.ts"] + srv.routes["/ts.m3u8"] = "\n".join([*lines, "#EXT-X-ENDLIST"]).encode() + track = Video(url=f"{base(srv)}ts.m3u8", language="en", codec=Video.Codec.HEVC, descriptor=Video.Descriptor.HLS) + drm = keyed_example() + track.drm = [drm] + return track + + +@pytest.mark.parametrize("merge_segments", [False, True]) +@pytest.mark.parametrize("method_none", [False, True]) +def test_hls_segment_plugin_decrypts_as_segments_land( + server, tmp_path, monkeypatch, example_plugins, merge_segments, method_none +): + """A segment plugin decrypts on the decrypter pool, joins the rolling merge, and finishes before the decode check.""" + monkeypatch.setattr(config, "merge_segments", merge_segments) + order: list[str] = [] + threads: set[str] = set() + + def run_tool(drm, src, dst): + threads.add(threading.current_thread().name) + dst.write_bytes(src.read_bytes().swapcase()) + + def finish(drm, path, track): + order.append("finish") + return True + + monkeypatch.setattr(plugins, "PLUGINS", {"example": dataclasses.replace(EXAMPLE, decrypt=run_tool, finish=finish)}) + + def decrypt_track(drm, path, licence=None, track_kid=None, decrypt=True, track=None): + order.append(f"check decrypt={decrypt}") + + for module in (segment_pipeline, hls_module): + monkeypatch.setattr(module, "decrypt_track", decrypt_track) + parts = CIPHER + ctx = make_ctx(tmp_path, "plugin.ts") + ctx.license_widevine = lambda *a, **kw: None + HLS.download_track(plugin_track(server, parts, method_none), ctx) + + assert ctx.save_path.read_bytes() == b"".join(parts).swapcase() + assert threading.main_thread().name not in threads + assert order == ["finish", "check decrypt=False"] + assert ("Merging" in ctx.statuses) is not merge_segments + assert not ctx.save_dir.exists() or not list(ctx.save_dir.glob("*")) + + +def test_hls_segment_plugin_resumes_with_its_clear_segments(server, tmp_path, monkeypatch, example_plugins): + """A failed segment plugin download keeps its decrypted segments, and the next run decrypts only the others.""" + monkeypatch.setattr(config, "continue_downloads", True) + runs: list[bytes] = [] + fail = threading.Event() + fail.set() + others_done = threading.Event() + + def run_tool(drm, src, dst): + data = src.read_bytes() + if fail.is_set() and data.startswith(b"CIPHER3"): + others_done.wait(10) + raise RuntimeError("EXAMPLE decrypt failed") + dst.write_bytes(data.swapcase()) + runs.append(data[:7]) + if len(runs) == len(parts) - 1: + others_done.set() + + monkeypatch.setattr(plugins, "PLUGINS", {"example": dataclasses.replace(EXAMPLE, decrypt=run_tool)}) + no_decrypt(monkeypatch) + parts = CIPHER + ctx = make_ctx(tmp_path, "plugin.ts") + ctx.license_widevine = lambda *a, **kw: None + with pytest.raises(RuntimeError, match="EXAMPLE decrypt failed"): + HLS.download_track(plugin_track(server, parts), ctx) + kept = {int(path.stem) for path in ctx.save_dir.rglob("*.clear")} + assert kept == {0, 1, 2, 4} + + fail.clear() + runs.clear() + HLS.download_track(plugin_track(server, parts), ctx) + assert runs == [b"CIPHER3"] + assert ctx.save_path.read_bytes() == b"".join(parts).swapcase() + + def test_hls_aes128_keeps_post_merge(server, tmp_path, monkeypatch): # AES-128 with no IV attribute: each segment's IV is its media sequence number for i, part in enumerate(PARTS): diff --git a/tests/core/test_segment_store.py b/tests/core/test_segment_store.py index e79e3dee..79f208c4 100644 --- a/tests/core/test_segment_store.py +++ b/tests/core/test_segment_store.py @@ -138,6 +138,7 @@ def test_a_mode_that_cannot_resume_withdraws_the_sidecar(tmp_path, keep): (Video.Descriptor.HLS, DownloadMode(aes128=True), False), (Video.Descriptor.HLS, DownloadMode(drm=ClearKeyCENC(kids=[KID])), False), (Video.Descriptor.HLS, DownloadMode(drm=ClearKey(key=bytes(16))), False), + (Video.Descriptor.HLS, DownloadMode(segment_keys=KEY_ARGS, drm=ClearKey(key=bytes(16))), True), ], ids=[ "dash", @@ -154,6 +155,7 @@ def test_a_mode_that_cannot_resume_withdraws_the_sidecar(tmp_path, keep): "hls-aes128", "hls-clearkey-cenc", "hls-clearkey", + "hls-segment-decrypt-other-drm", ], ) def test_resume_verdict(tmp_path, keep, descriptor, mode, resumable): diff --git a/unshackle/core/drm/custom.py b/unshackle/core/drm/custom.py index cfbcacf7..6bf2c3fa 100644 --- a/unshackle/core/drm/custom.py +++ b/unshackle/core/drm/custom.py @@ -69,14 +69,18 @@ class CustomDRM: raise ValueError(f"Target file does not exist: {path}") output = path.with_name(f"{path.stem}.decrypted{path.suffix}") try: - self.plugin.decrypt(self, path, output) - if not output.is_file(): - raise ValueError(f"The {self.label} decrypter wrote no output for {path.name}") + self.decrypt_to(path, output) output.replace(path) finally: with contextlib.suppress(OSError): output.unlink(missing_ok=True) + def decrypt_to(self, path: Path, output: Path) -> None: + """Decrypt ``path`` with the plugin into ``output``.""" + self.plugin.decrypt(self, path, output) + if not output.is_file(): + raise ValueError(f"The {self.label} decrypter wrote no output for {path.name}") + def finish(self, path: Path, track: Any) -> bool: """Run the plugin's fix of a merged file that the plugin decrypted per segment; False when it proves no content key.""" return self.plugin.finish(self, path, track) if self.plugin.finish is not None else True diff --git a/unshackle/core/drm/segment_decrypt.py b/unshackle/core/drm/segment_decrypt.py index 1a01c73c..6b1f24c6 100644 --- a/unshackle/core/drm/segment_decrypt.py +++ b/unshackle/core/drm/segment_decrypt.py @@ -11,7 +11,7 @@ from typing import Any from unshackle.core import binaries from unshackle.core.config import config -from unshackle.core.drm import real_kids +from unshackle.core.drm import CustomDRM, real_kids from unshackle.core.drm.clearkey_cenc import ClearKeyCENC from unshackle.core.drm.key_args import _hex from unshackle.core.drm.playready import PlayReady @@ -30,7 +30,10 @@ def can_use(drm: Any, decryption: str, init: bytes | None = None) -> bool: A track whose ``init`` mp4decrypt cannot key goes to the whole-file decrypt, which has the shaka fallback. So does a track whose DRM names a KID with no content key, as only that decrypt can license a KID the file uses. + A plugin DRM that decrypts per segment always can: it needs neither mp4decrypt nor an init segment. """ + if isinstance(drm, CustomDRM): + return drm.plugin.mode == "segment" return ( isinstance(drm, (Widevine, PlayReady, ClearKeyCENC)) and str(decryption).lower() == "mp4decrypt" @@ -41,7 +44,66 @@ def can_use(drm: Any, decryption: str, init: bytes | None = None) -> bool: ) -class SegmentDecrypter: +class SegmentPool: + """Decrypts segments on a thread pool as they arrive; a subclass decrypts one segment file into another.""" + + track_keys: list[str] + """The KID:KEY pairs that decrypt the segments: a resume reuses a decrypted segment only with the same pairs.""" + + def __init__(self, workers: int | None = None) -> None: + self.pool = ThreadPoolExecutor(max_workers=min(workers or os.cpu_count() or 4, MAX_WORKERS)) + self.futures: list[Future] = [] + + def submit(self, segment: Path, output: Path) -> Future: + """Queue one downloaded segment for decryption to output; the future gives output.""" + future = self.pool.submit(self.decrypt_segment, segment, output) + self.futures.append(future) + return future + + def decrypt_segment(self, segment: Path, output: Path) -> Path: + """Decrypt segment to output, then remove segment. + + The output appears only once it is complete, so a segment file and its output never hold the same + bytes in two states. A segment file that Windows still locks stays; the segment store removes it. + """ + partial = output.with_name(output.name + ".!dev") + partial.unlink(missing_ok=True) + try: + self.write(segment, partial) + os.replace(partial, output) + finally: + with contextlib.suppress(OSError): + partial.unlink(missing_ok=True) + with contextlib.suppress(OSError): + segment.unlink() + return output + + def write(self, segment: Path, output: Path) -> None: + """Write the clear bytes of one segment to output.""" + raise NotImplementedError + + def init_bytes(self) -> bytes: + """The init segment that heads the clear output.""" + raise NotImplementedError + + def finish(self) -> bytes: + """Wait for every queued segment, then return the init segment bytes of the clear output.""" + try: + for future in self.futures: + future.result() + return self.init_bytes() + finally: + self.close() + + def close(self) -> None: + """Drop any pending work. Safe to call twice.""" + for future in self.futures: + future.cancel() + self.futures.clear() + self.pool.shutdown(wait=True) + + +class SegmentDecrypter(SegmentPool): """Decrypts fMP4 segments as they arrive, via mp4decrypt --fragments-info, on a thread pool. mp4decrypt cannot read a bare `moof+mdat` segment on its own, so every call passes the @@ -69,33 +131,11 @@ class SegmentDecrypter: self.init_path = self.work_dir / "init.mp4" self.init_path.write_bytes(init_data) - self.pool = ThreadPoolExecutor(max_workers=min(workers or os.cpu_count() or 4, MAX_WORKERS)) - self.futures: list[Future] = [] + super().__init__(workers) self._init_bytes: bytes | None = None - def submit(self, segment: Path, output: Path) -> Future: - """Queue one downloaded segment for decryption to output; the future gives output.""" - future = self.pool.submit(self.decrypt_segment, segment, output) - self.futures.append(future) - return future - - def decrypt_segment(self, segment: Path, output: Path) -> Path: - """Decrypt segment to output, then remove segment. - - The output appears only once it is complete, so a segment file and its output never hold the same - bytes in two states. A segment file that Windows still locks stays; the segment store removes it. - """ - partial = output.with_name(output.name + ".!dev") - partial.unlink(missing_ok=True) - try: - self.run(["--fragments-info", str(self.init_path), str(segment), str(partial)]) - os.replace(partial, output) - finally: - with contextlib.suppress(OSError): - partial.unlink(missing_ok=True) - with contextlib.suppress(OSError): - segment.unlink() - return output + def write(self, segment: Path, output: Path) -> None: + self.run(["--fragments-info", str(self.init_path), str(segment), str(output)]) def init_bytes(self) -> bytes: """Decrypt the init segment on first call and return its bytes. @@ -109,21 +149,9 @@ class SegmentDecrypter: self._init_bytes = decrypted_init.read_bytes() return self._init_bytes - def finish(self) -> bytes: - """Wait for every queued segment, then return the decrypted init segment bytes.""" - try: - for future in self.futures: - future.result() - return self.init_bytes() - finally: - self.close() - def close(self) -> None: """Drop any pending work and remove the temporary files. Safe to call twice.""" - for future in self.futures: - future.cancel() - self.futures.clear() - self.pool.shutdown(wait=True) + super().close() shutil.rmtree(self.work_dir, ignore_errors=True) def run(self, args: list[str]) -> None: @@ -150,3 +178,26 @@ class SegmentDecrypter: if not output.exists() or not output.stat().st_size: error = f"mp4decrypt failed on {args[-2]}: output file {output.name} is missing or empty" raise coded(RuntimeError(error), APIErrorCode.DRM_ERROR) + + +class PluginSegmentDecrypter(SegmentPool): + """Decrypts each segment with the plugin of a DRM in segment mode. The init segment stays as it is.""" + + def __init__(self, drm: CustomDRM, init_data: bytes, workers: int | None = None) -> None: + super().__init__(workers) + self.drm = drm + self.init_data = init_data + self.track_keys = [f"{_hex(drm.kid)}:{_hex(drm.key)}"] if drm.kid and drm.key else [] + + def write(self, segment: Path, output: Path) -> None: + self.drm.decrypt_to(segment, output) + + def init_bytes(self) -> bytes: + return self.init_data + + +def make_decrypter(drm: Any, init_data: bytes, work_dir: Path, workers: int | None = None) -> SegmentPool: + """The segment decrypter of a DRM that `can_use` accepts.""" + if isinstance(drm, CustomDRM): + return PluginSegmentDecrypter(drm, init_data, workers) + return SegmentDecrypter(drm, init_data, work_dir, workers) diff --git a/unshackle/core/manifests/dash.py b/unshackle/core/manifests/dash.py index 5f1e9773..6c59f084 100644 --- a/unshackle/core/manifests/dash.py +++ b/unshackle/core/manifests/dash.py @@ -31,7 +31,7 @@ from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, An 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, PLAYREADY_ID, common_pssh_kids -from unshackle.core.drm.segment_decrypt import SEGMENT_DRM_T, SegmentDecrypter, can_use +from unshackle.core.drm.segment_decrypt import SegmentPool, can_use, make_decrypter from unshackle.core.drm.verify import has_encrypted_entry, has_encrypted_sample_entry, walk from unshackle.core.manifests.segment_pipeline import ( append_segment, @@ -698,9 +698,9 @@ class DASH: known = timed and len(period_starts) > 1 rebase_vtt = known and is_text_subtitle and track.codec == Subtitle.Codec.WebVTT - decrypter: SegmentDecrypter | None = None + decrypter: SegmentPool | None = None if use_segment_decrypt and init_data: - decrypter = SegmentDecrypter(cast(SEGMENT_DRM_T, drm), init_data, save_dir.parent, ctx.max_workers) + decrypter = make_decrypter(drm, init_data, save_dir.parent, ctx.max_workers) rebase: PeriodRebase | None = None timescale = mdhd_timescale(init_data) if known and init_data and not is_text_subtitle else None diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py index 49b65d3f..8c4f3faa 100644 --- a/unshackle/core/manifests/hls.py +++ b/unshackle/core/manifests/hls.py @@ -31,7 +31,7 @@ from unshackle.core import binaries from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm, is_widevine_cdm from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY, AnyTrack -from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, CustomDRM, PlayReady, Widevine +from unshackle.core.drm import DRM_T, ClearKey, CustomDRM, PlayReady, Widevine from unshackle.core.drm.cenc import ( PLACEHOLDER_KIDS, PLAYREADY_ID, @@ -44,7 +44,7 @@ from unshackle.core.drm.cenc import ( key_data, key_system, ) -from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use +from unshackle.core.drm.segment_decrypt import SegmentPool, can_use, make_decrypter from unshackle.core.drm.verify import decrypt_track from unshackle.core.events import events from unshackle.core.manifests.dash import PeriodRebase, mdhd_timescale, missing_language, rebase_webvtt_files @@ -53,6 +53,7 @@ from unshackle.core.manifests.segment_pipeline import ( append_segment, check_decrypted, check_merged, + check_segments, complete_track, fetch_segments, ) @@ -703,13 +704,15 @@ class HLS: single_init = plan.single_init(wanted_segments) use_segment_decrypt = ( - isinstance(session_drm, (Widevine, PlayReady)) and can_use(session_drm, config.decryption) and single_init + isinstance(session_drm, (Widevine, PlayReady, CustomDRM)) + and can_use(session_drm, config.decryption) + and single_init ) use_rolling_merge = ( config.merge_segments and single_init and not isinstance(track, Subtitle) - and (session_drm is None or isinstance(session_drm, (Widevine, PlayReady))) + and (session_drm is None or isinstance(session_drm, (Widevine, PlayReady)) or use_segment_decrypt) ) total_segments = len(master.segments) - len(unwanted_segments) @@ -743,16 +746,16 @@ class HLS: segment_save_dir = save_dir / "segments" map_data: tuple[m3u8.model.InitializationSection, bytes] | None = None - if use_segment_decrypt or use_rolling_merge: - init_section = wanted_segments[0].init_section + init_section = wanted_segments[0].init_section if use_segment_decrypt or use_rolling_merge else None + if init_section: init_content, _ = HLS.fetch_init_section(session, init_section, 0) map_data = (init_section, init_content) use_segment_decrypt = use_segment_decrypt and can_use(session_drm, config.decryption, init_content) - segment_decrypter: SegmentDecrypter | None = None + segment_decrypter: SegmentPool | None = None if use_segment_decrypt: - assert isinstance(session_drm, (Widevine, PlayReady, ClearKeyCENC)) - segment_decrypter = SegmentDecrypter(session_drm, init_content, save_dir.parent, ctx.max_workers) + init = map_data[1] if map_data else b"" + segment_decrypter = make_decrypter(session_drm, init, save_dir.parent, ctx.max_workers) store = SegmentStore(track, save_dir) store.open( @@ -916,6 +919,8 @@ class HLS: merge(to=merged_path, via=files, delete=True, include_map_data=True) decrypt_track(drm, merged_path, license_widevine, track=track) merged_path.rename(decrypted_path) + elif segment_decrypter: + merge(to=merged_path, via=files, delete=True, include_map_data=True) else: # AES segments must be decrypted individually before merging: each segment # likely carries its own 16-byte padding @@ -1099,8 +1104,7 @@ class HLS: store.complete() if isinstance(session_drm, CustomDRM) and session_drm.plugin.mode == "segment": - if session_drm.finish(save_path, track): - decrypt_track(session_drm, save_path, decrypt=False, track=track) + check_segments(track, save_path, session_drm) if session_drm: track.drm = None complete_track(track, ctx, None) diff --git a/unshackle/core/manifests/hls_key_plan.py b/unshackle/core/manifests/hls_key_plan.py index c086b363..2caa27cc 100644 --- a/unshackle/core/manifests/hls_key_plan.py +++ b/unshackle/core/manifests/hls_key_plan.py @@ -13,7 +13,7 @@ from m3u8 import M3U8 from unshackle.core.cdm.choice import drm_system from unshackle.core.cdm.detect import cdm_system from unshackle.core.constants import DOWNLOAD_ALL_DRM, AnyTrack -from unshackle.core.drm import DRM_T, PlayReady, Widevine +from unshackle.core.drm import DRM_T, PlayReady, Widevine, own_cipher from unshackle.core.manifests.hls import HLS from unshackle.core.manifests.hls_keys import KeySpan, ReadInit, key_spans from unshackle.core.manifests.segment_pipeline import license_drm, licensing @@ -196,10 +196,10 @@ class HlsKeyPlan: """Whether every wanted segment shares one init segment and one EXT-X-KEY tag, with no discontinuity. Only then does the track merge into a single file with one init segment and one set of content keys, which - segment-by-segment decryption needs. + segment-by-segment decryption needs. A cipher that is not CENC decrypts every segment alike, so it needs neither + an init segment nor an EXT-X-KEY tag. """ - if len(self.spans) != 1 or not self.spans[0].init_section: + if len(self.spans) != 1 or any(segment.discontinuity for segment in wanted_segments[1:]): return False - return not any(segment.discontinuity for segment in wanted_segments[1:]) and ( - not self.spans[0].keys or self.first is not None - ) + span = self.spans[0] + return own_cipher(self.drm) or (bool(span.init_section) and (not span.keys or self.first is not None)) diff --git a/unshackle/core/manifests/segment_pipeline.py b/unshackle/core/manifests/segment_pipeline.py index a2b2737d..679f6610 100644 --- a/unshackle/core/manifests/segment_pipeline.py +++ b/unshackle/core/manifests/segment_pipeline.py @@ -30,7 +30,7 @@ from unshackle.core.drm import ( own_cipher, ) from unshackle.core.drm.cbcs import SampleDecrypter -from unshackle.core.drm.segment_decrypt import SegmentDecrypter +from unshackle.core.drm.segment_decrypt import SegmentPool from unshackle.core.drm.verify import decrypt_track, has_encrypted_sample_entry from unshackle.core.events import events from unshackle.core.remote_protocol import APIErrorCode, coded @@ -202,7 +202,7 @@ def fetch_segments( rolling: bool = False, init: bytes | None = None, append: Callable[[BinaryIO, Path], None] | None = None, - decrypter: SegmentDecrypter | None = None, + decrypter: SegmentPool | None = None, ) -> tuple[RollingMerge | None, bytes | None]: """Download the segment requests and return the rolling merge, if any, and the init that heads the output. @@ -382,14 +382,25 @@ def check_decrypted(track: AnyTrack, path: Path, drm: DRM_T | None) -> None: track.needs_repack = True +def check_segments( + track: AnyTrack, path: Path, drm: DRM_T, licence: Callable | None = None, kid: UUID | None = None +) -> None: + """Check a file whose segments are already clear; a plugin first runs its finish, which says if it proves a content key.""" + if not isinstance(drm, CustomDRM) or drm.finish(path, track): + decrypt_track(drm, path, licence, kid, decrypt=False, track=track) + + def decrypt_output( track: AnyTrack, ctx: DownloadContext, drm: DRM_T, decrypt: bool = True, kid: UUID | None = None ) -> None: """Decrypt ctx.save_path through decrypt_track, check it, and emit TRACK_DECRYPTED. - `decrypt=False` means a SegmentDecrypter already decrypted the segments, so only the check runs. + `decrypt=False` means a segment decrypter already decrypted the segments, so only the check runs. """ - decrypt_track(drm, ctx.save_path, ctx.license_widevine, kid, decrypt=decrypt, track=track) + if decrypt: + decrypt_track(drm, ctx.save_path, ctx.license_widevine, kid, track=track) + else: + check_segments(track, ctx.save_path, drm, ctx.license_widevine, kid) check_decrypted(track, ctx.save_path, drm) track.drm = None events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=None) @@ -430,6 +441,7 @@ __all__ = ( "append_segment", "check_decrypted", "check_merged", + "check_segments", "text_subtitle_bytes", "complete_track", "decrypt_output", diff --git a/unshackle/core/plugins.py b/unshackle/core/plugins.py index 41ddb133..ff791c82 100644 --- a/unshackle/core/plugins.py +++ b/unshackle/core/plugins.py @@ -38,7 +38,8 @@ class DrmPlugin: ``id`` names the system on the wire, in an export and in the CDM catalogue. ``licensing`` is "held" when the DRM holds its content key from the start, or "local" when a plugin device licenses it. ``media`` "own" is a cipher that is not CENC: no KID to probe and no fragment to check. ``mode`` "segment" decrypts each - segment, then calls ``finish`` on the merged file; "track" decrypts the merged file once. + segment as it lands, several at once, then calls ``finish`` on the merged file; "track" decrypts the merged file once. + ``decrypt`` writes only its destination path, whatever its name. ``wire_data`` names the keys of ``CustomDRM.data`` that a peer and an export may carry. ``finish`` returns False for a track that the cipher leaves clear: its merged file proves no content key, so it gets no decode check. The CDM that ``load_device`` builds may carry a ``device_name`` for the load log. diff --git a/unshackle/core/tracks/segment_store.py b/unshackle/core/tracks/segment_store.py index a6316b35..be48d573 100644 --- a/unshackle/core/tracks/segment_store.py +++ b/unshackle/core/tracks/segment_store.py @@ -186,12 +186,14 @@ class SegmentStore: A rolling merge whose append keeps state from one segment to the next cannot restart at a checkpoint. The HLS merge decrypts AES-128 segments and every DRM other than Widevine and PlayReady in place, - segment by segment, so a kept file can be plain or encrypted. + segment by segment, so a kept file can be plain or encrypted; a segment decrypter writes .clear files instead. """ if not self.keeps or (mode.rolling_merge and mode.stateful_merge): return False if self.track.descriptor is self.track.Descriptor.HLS: - return not mode.aes128 and (mode.drm is None or isinstance(mode.drm, (Widevine, PlayReady))) + return not mode.aes128 and ( + mode.drm is None or isinstance(mode.drm, (Widevine, PlayReady)) or bool(mode.segment_keys) + ) return True def open(