"""The segment pipeline: the steps DASH, HLS and ISM share to download a segmented track. Each manifest finds its own segments and supplies its own quirks; the pipeline runs the licence step, the download with its rolling merge, the decrypt hand-off and the cleanup. """ from __future__ import annotations import html import shutil import zlib from collections.abc import Callable, Iterator from concurrent.futures import Future from contextlib import ExitStack, closing, contextmanager from pathlib import Path from typing import Any, BinaryIO from uuid import UUID from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack from unshackle.core.drm import DRM_T, WHOLE_FILE_DRM, ClearKeyCENC, ClearKeyCTR, MonaLisa, PlayReady, Widevine, cbcs from unshackle.core.drm.cbcs import SampleDecrypter from unshackle.core.drm.segment_decrypt import SegmentDecrypter 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 from unshackle.core.session import AnySession from unshackle.core.temp import low_free_space from unshackle.core.tracks import DownloadContext, Track from unshackle.core.tracks.segment_store import SegmentStore, decrypted from unshackle.core.tracks.track import assert_fragments_decrypted from unshackle.core.utilities import log_event, try_ensure_utf8 def text_subtitle_bytes(data: bytes) -> bytes: """`data` as UTF-8, with the ‎ and ‏ entities as their characters.""" return ( try_ensure_utf8(data) .decode("utf8") .replace("‎", html.unescape("‎")) .replace("‏", html.unescape("‏")) .encode("utf8") ) def append_segment(dst: BinaryIO, segment_file: Path, is_text_subtitle: bool) -> None: """Append one segment file to the output, with the text subtitle fixups when they apply.""" if is_text_subtitle: dst.write(text_subtitle_bytes(segment_file.read_bytes())) else: with open(segment_file, "rb") as src: shutil.copyfileobj(src, dst, 1024 * 1024) class RollingMerge: """Appends segments to the output in index order as they arrive, out of order, and unlinks them. A cursor holds the next expected index; every `add` records one ready segment and then drains every contiguous ready segment from the cursor onward. A segment that carries a future (per-segment decryption) appends the file that future gives, so the output never holds raw bytes. A merge that resumes a checkpoint starts at its cursor, with dst at the checkpoint length. `append(dst, segment_file)` writes one segment; the default is a plain byte copy. A parser whose merge needs a per-segment transform, or a head that only exists once segment 0 has landed (ISM), passes its own. """ def __init__( self, dst: BinaryIO, append: Callable[[BinaryIO, Path], None] | None = None, cursor: int = 0, ) -> None: self.dst = dst self.append = append or (lambda dst, path: append_segment(dst, path, is_text_subtitle=False)) self.cursor = cursor self.length = dst.tell() self.ready: dict[int, tuple[Path, Future | None]] = {} def add(self, index: int, segment_file: Path, future: Future | None = None) -> None: # runs on the downloader's own loop, so a decrypt wait or a catch-up burst # delays new submissions; move the drain to a writer thread if throughput measurably drops self.ready[index] = (segment_file, future) while self.cursor in self.ready: path, pending = self.ready.pop(self.cursor) if pending is not None: path = pending.result() self.append(self.dst, path) self.cursor, self.length = self.cursor + 1, self.dst.tell() # the bytes are already in the output; a handle another process still holds on # the just-replaced file (Windows) must not fail the track, the segment dir sweep # after the download removes any leftover try: path.unlink() except OSError: pass @property def merged(self) -> int: return self.cursor @contextmanager def licensing(ctx: DownloadContext) -> Iterator[None]: """Show FAILED and cancel the pending track downloads when the body raises.""" try: yield except Exception: DOWNLOAD_CANCELLED.set() ctx.progress(downloaded="[red]FAILED") raise LICENSABLE: dict[Track.Descriptor, tuple[type, ...]] = { Track.Descriptor.URL: (Widevine, PlayReady, ClearKeyCENC, ClearKeyCTR), Track.Descriptor.DASH: (Widevine, PlayReady, ClearKeyCENC), Track.Descriptor.HLS: (Widevine, PlayReady, MonaLisa), Track.Descriptor.ISM: (Widevine, PlayReady), } """The DRM systems the licence step licenses, by the kind of manifest the track comes from.""" def inflate_gzip(path: Path) -> None: """Inflate in place a segment whose body is one whole gzip member, which a CDN can send with no Content-Encoding. Any other body stays as it is: AES-128 ciphertext can start with the gzip magic too. """ with open(path, "rb") as f: if f.read(3) != b"\x1f\x8b\x08": return from unshackle.core.api.compression import MAX_INFLATE_BYTES decompressor = zlib.decompressobj(31) try: data = decompressor.decompress(path.read_bytes(), MAX_INFLATE_BYTES + 1) except zlib.error: return if len(data) > MAX_INFLATE_BYTES: raise ValueError(f"Segment {path.name} inflates beyond {MAX_INFLATE_BYTES} bytes") if decompressor.eof and not decompressor.unused_data: inflated = path.with_name(path.name + ".inflated") inflated.write_bytes(data) inflated.replace(path) def license_drm( track: AnyTrack, drm: DRM_T | None, ctx: DownloadContext, kid: UUID | None = None, probe: Callable[[], UUID | None] | None = 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( track: AnyTrack, ctx: DownloadContext, session: AnySession, label: str, urls: list[dict[str, Any]], output_dir: Path, filename: str, store: SegmentStore, *, rolling: bool = False, init: bytes | None = None, append: Callable[[BinaryIO, Path], None] | None = None, decrypter: SegmentDecrypter | 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. With rolling, the init (or the decrypter's decrypted init) and each segment go into ctx.save_path as they land, from the checkpoint of the store when it kept one. The download skips each segment the store already holds. Each segment gets its SEGMENT_DOWNLOADED event before the decrypter gets it. Any failure closes the decrypter, and a rolling output stays for the next run only when the store records its checkpoint. The returned init is the decrypter's decrypted init, else init. """ merger: RollingMerge | None = None skip = store.skip skipping: dict[str, Any] = {"skip": skip} if skip else {} output: BinaryIO try: with ExitStack() as stack: if rolling: if store.cursor: output = stack.enter_context(open(ctx.save_path, "r+b")) output.truncate(store.length) output.seek(store.length) else: output = stack.enter_context(open(ctx.save_path, "wb")) head = decrypter.init_bytes() if decrypter else init if head: output.write(head) merger = RollingMerge(output, append, store.cursor) for index, path in sorted(store.clear.items()): merger.add(index, path) # an exception raised in this body (a decrypt failure re-raised by the merge) # must close the generator now, so its finally aborts the workers stream = stack.enter_context( closing( track.downloader( urls=urls, output_dir=output_dir, filename=filename, headers=session.headers, cookies=session.cookies, proxy=ctx.proxy, max_workers=ctx.max_workers, session=session, adaptive=ctx.adaptive_workers, processes=ctx.download_processes, **skipping, ) ) ) for status_update in stream: file_downloaded = status_update.get("file_downloaded") if file_downloaded: if skip and int(file_downloaded.stem) in skip: # a service downloader that ignores skip fetched a segment the store holds file_downloaded.unlink(missing_ok=True) continue inflate_gzip(file_downloaded) events.emit(events.Types.SEGMENT_DOWNLOADED, track=track, segment=file_downloaded) future = decrypter.submit(file_downloaded, decrypted(file_downloaded)) if decrypter else None if merger: merger.add(int(file_downloaded.stem), file_downloaded, future) else: downloaded = status_update.get("downloaded") if downloaded and downloaded.endswith("/s"): status_update["downloaded"] = f"{label} {downloaded}" ctx.progress(**status_update) head_init = decrypter.finish() if decrypter else init except BaseException as e: if decrypter: decrypter.close() if merger and not store.checkpoint(merger.cursor, merger.length): low_free_space(e) ctx.save_path.unlink(missing_ok=True) raise return merger, head_init def check_merged(merger: RollingMerge, total: int, track: AnyTrack, ctx: DownloadContext, label: str) -> None: """Remove the output and raise FileNotFoundError when the rolling merge appended fewer than total segments.""" if merger.merged == total: return error_msg = f"Rolling merge appended {merger.merged} of {total} segments: {ctx.save_dir}" log_event( f"manifest_{label.lower()}_rolling_merge_incomplete", level="ERROR", message=error_msg, context={ "track_id": getattr(track, "id", None), "track_type": track.__class__.__name__, "save_dir": str(ctx.save_dir), "merged": merger.merged, "total_segments": total, "downloader": "requests", }, ) ctx.save_path.unlink(missing_ok=True) raise FileNotFoundError(error_msg) def check_decrypted(track: AnyTrack, path: Path, drm: DRM_T | None) -> None: """Raise if a fragment of `path` still carries encryption, and mark the track for a repack when its moov does. A whole-file cipher leaves no fragments to check. An encrypted sample entry that survives the decrypt would lock the muxer to a generic codec. """ if not isinstance(drm, WHOLE_FILE_DRM): assert_fragments_decrypted(path) if has_encrypted_sample_entry(path): track.needs_repack = True 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_track(drm, ctx.save_path, ctx.license_widevine, kid, decrypt=decrypt, track=track) check_decrypted(track, ctx.save_path, drm) track.drm = None events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=None) def decrypt_samples(track: AnyTrack, ctx: DownloadContext, decrypter: Callable[[int], bytes | SampleDecrypter]) -> None: """Decrypt ctx.save_path with the service sample decrypter, check it, and emit TRACK_DECRYPTED with no DRM.""" cbcs.decrypt_file(ctx.save_path, lambda _layout, entry: decrypter(entry.index)) check_decrypted(track, ctx.save_path, None) events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=None, segment=None) def complete_track( track: AnyTrack, ctx: DownloadContext, drm: DRM_T | None, decrypt: bool = True, kid: UUID | None = None ) -> None: """Hand the merged file to the track, decrypt it, and remove the segment directory. The track decrypts with `drm` (key ID `kid`), with the service sample decrypter of ctx, or both. """ track.path = ctx.save_path samples = None if DOWNLOAD_CANCELLED.is_set() else ctx.sample_decrypter if drm or samples: ctx.progress(downloaded="Decrypting", completed=0, total=None) if drm: decrypt_output(track, ctx, drm, decrypt, kid) if samples: decrypt_samples(track, ctx, samples) if drm or samples: ctx.progress(downloaded="Decrypted", completed=100, total=100) SegmentStore(track, ctx.save_dir).complete() ctx.progress(downloaded="Downloaded", completed=100, total=100) __all__ = ( "RollingMerge", "append_segment", "check_decrypted", "check_merged", "text_subtitle_bytes", "complete_track", "decrypt_output", "decrypt_samples", "fetch_segments", "license_drm", "licensing", )