Files
unshackle/unshackle/core/drm/segment_decrypt.py
T

137 lines
5.5 KiB
Python

from __future__ import annotations
import contextlib
import os
import shutil
import subprocess
import tempfile
from concurrent.futures import Future, ThreadPoolExecutor
from pathlib import Path
from typing import Any
from unshackle.core import binaries
from unshackle.core.config import config
from unshackle.core.drm.clearkey_cenc import ClearKeyCENC
from unshackle.core.drm.playready import PlayReady
from unshackle.core.drm.verify import kidless_track_kids
from unshackle.core.drm.widevine import Widevine
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.utils.subprocess import ToolFailed
SEGMENT_DRM_T = Widevine | PlayReady | ClearKeyCENC
MAX_WORKERS = 16
def can_use(drm: Any, decryption: str, init: bytes | None = None) -> bool:
"""Whether unshackle can decrypt a track's segments one by one as they download.
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.
"""
return (
isinstance(drm, (Widevine, PlayReady, ClearKeyCENC))
and str(decryption).lower() == "mp4decrypt"
and config.decrypt_segments
and bool(binaries.Mp4decrypt)
and not (init and set(kidless_track_kids(init).values()) - set(drm.content_keys))
and set(getattr(drm, "kids", None) or []) <= set(drm.content_keys)
)
class SegmentDecrypter:
"""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
track's init segment through --fragments-info for the moov it needs. One last call
decrypts the init segment itself without that flag, which rewrites encv/enca back to the
real codec 4CC. Concatenating that init segment with the decrypted segments gives the same
bytes as decrypting the merged file in one pass.
"""
def __init__(self, drm: SEGMENT_DRM_T, init_data: bytes, work_dir: Path, workers: int | None = None) -> None:
if not binaries.Mp4decrypt:
raise coded(OSError("mp4decrypt executable not found but is required."), APIErrorCode.DRM_ERROR)
self.drm = drm
self.key_args = drm.mp4decrypt_key_args(kidless_track_kids(init_data))
work_dir.mkdir(parents=True, exist_ok=True)
self.work_dir = Path(tempfile.mkdtemp(prefix="segdec-", dir=work_dir))
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] = []
self._init_bytes: bytes | None = None
def submit(self, segment: Path) -> Future:
"""Queue one downloaded segment for decryption and return its future."""
future = self.pool.submit(self.decrypt_segment, segment)
self.futures.append(future)
return future
def decrypt_segment(self, segment: Path) -> None:
output = segment.with_suffix(segment.suffix + ".dec")
output.unlink(missing_ok=True)
try:
self.run(["--fragments-info", str(self.init_path), str(segment), str(output)])
os.replace(output, segment)
finally:
with contextlib.suppress(OSError):
output.unlink(missing_ok=True)
def init_bytes(self) -> bytes:
"""Decrypt the init segment on first call and return its bytes.
Independent of the media segments, so a rolling merge can write it at the head of the
output before any segment lands.
"""
if self._init_bytes is None:
decrypted_init = self.work_dir / "init_decrypted.mp4"
self.run([str(self.init_path), str(decrypted_init)])
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)
shutil.rmtree(self.work_dir, ignore_errors=True)
def run(self, args: list[str]) -> None:
"""Run mp4decrypt with the track keys and check its output.
mp4decrypt exits 0 after it fails to process a file, so this also reads its stderr.
"""
cmd = [str(binaries.Mp4decrypt), *self.key_args, *args]
try:
p = subprocess.run(
cmd,
check=True,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
except subprocess.CalledProcessError as e:
raise RuntimeError(
f"mp4decrypt failed on {args[-2]}: {e.stderr.strip() if e.stderr else f'exit code {e.returncode}'}"
) from e
if "failed to process" in p.stderr:
raise coded(ToolFailed("mp4decrypt", p.returncode, cmd, p.stdout, p.stderr), APIErrorCode.DRM_ERROR)
output = Path(args[-1])
if not output.exists() or not output.stat().st_size:
raise RuntimeError(f"mp4decrypt failed on {args[-2]}: output file {output.name} is missing or empty")