feat(tracks): resume segment decryption and rolling merge through the segment store

This commit is contained in:
imSp4rky
2026-11-28 22:09:44 -07:00
parent f4d178c26b
commit 82991dd823
26 changed files with 1125 additions and 186 deletions
+18 -3
View File
@@ -12,7 +12,7 @@ import threading
import time
import traceback
from collections import OrderedDict, deque
from collections.abc import Callable, Generator, MutableMapping
from collections.abc import Callable, Collection, Generator, MutableMapping
from concurrent.futures import FIRST_COMPLETED, wait
from concurrent.futures.thread import ThreadPoolExecutor
from copy import copy
@@ -1408,6 +1408,7 @@ def download_multiprocess(
spec: dict[str, Any],
processes: int,
debug_logger: Any,
skip: Collection[int] = frozenset(),
) -> Generator[dict[str, Any], None, None]:
"""Fan segments across spawned children, each running ``requests()`` on a strided slice.
@@ -1461,6 +1462,7 @@ def download_multiprocess(
processes=1,
index_offset=offset,
index_stride=processes,
skip=skip,
_session_spec=spec,
)
p = mp_ctx.Process(target=mp_worker, args=(queue, child_kwargs), daemon=True)
@@ -1468,6 +1470,9 @@ def download_multiprocess(
procs.append(p)
yield dict(total=n)
# the parent drops the advance events of the children, so it counts the skipped files itself
if skipped := sum(0 <= index < n for index in skip):
yield dict(advance=skipped)
total_bytes = 0
start_time = time.time()
@@ -1565,6 +1570,7 @@ def requests(
processes: int = 1,
index_offset: int = 0,
index_stride: int = 1,
skip: Collection[int] = frozenset(),
) -> Generator[dict[str, Any], None, None]:
"""
Download files with optimized I/O and adaptive chunk sizing.
@@ -1623,6 +1629,8 @@ def requests(
index_stride: Multiplies each url's enumerate index before ``index_offset`` is
added, mapping a strided slice (``urls[k::stride]``) back to global indices.
Internal: set by the multiprocess path, leave at 1 otherwise.
skip: The indices of the files an earlier step already holds in another form. This function makes
no request for them and counts them as done in one {advance: n}, never as file_downloaded.
"""
if not urls:
raise ValueError("urls must be provided and not empty")
@@ -1693,6 +1701,7 @@ def requests(
spec=spec,
processes=processes,
debug_logger=debug_logger,
skip=skip,
)
if DOWNLOAD_CANCELLED.is_set():
raise DownloadCancelled()
@@ -1708,9 +1717,11 @@ def requests(
# only resolve each URL's extension when the template actually references {ext};
# DASH/ISM use "{i}.mp4" (no ext), so this skips a urlparse per segment for them
needs_ext = any(name == "ext" for _, name, _, _ in Formatter().parse(filename))
given = len(urls)
urls = [
dict(save_path=save_path, **url) if isinstance(url, dict) else dict(url=url, save_path=save_path)
for i, url in enumerate(urls)
if i * index_stride + index_offset not in skip
for save_path in [
output_dir
/ filename.format(
@@ -1721,6 +1732,10 @@ def requests(
]
# once per batch; download() skips it for segments
output_dir.mkdir(parents=True, exist_ok=True)
if given > len(urls):
yield dict(advance=given - len(urls))
if not urls:
return
# Provided sessions may be shared across tracks: don't mutate or remount them. Remounting
# drops the service's 429/5xx Retry config and races get_adapter() in other track threads.
@@ -1757,9 +1772,9 @@ def requests(
},
)
segmented_batch = len(urls) > 1
segmented_batch = given > 1
if len(urls) == 1:
if given == 1:
url_item = urls[0]
try:
ranged_used = False
+1 -1
View File
@@ -101,7 +101,7 @@ def mp4decrypt(path: Path, key_args_for: Callable[[dict[int, UUID]], list[str]])
if output_path.stat().st_size == 0:
raise RuntimeError(f"mp4decrypt failed: output file {output_path} is empty")
output_path.replace(path)
except ToolFailed as e:
except (ToolFailed, RuntimeError) as e:
raise coded(e, APIErrorCode.DRM_ERROR) from None
finally:
with contextlib.suppress(OSError):
+30 -14
View File
@@ -11,7 +11,9 @@ 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.clearkey_cenc import ClearKeyCENC
from unshackle.core.drm.key_args import _hex
from unshackle.core.drm.playready import PlayReady
from unshackle.core.drm.verify import kidless_track_kids
from unshackle.core.drm.widevine import Widevine
@@ -54,7 +56,13 @@ class SegmentDecrypter:
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))
track_kids = kidless_track_kids(init_data)
self.key_args = drm.mp4decrypt_key_args(track_kids)
keys = drm.content_keys
self.track_keys = sorted(
f"{_hex(kid)}:{_hex(keys[kid])}" for kid in {*real_kids(drm), *track_kids.values()} if kid in keys
)
"""The KID:KEY pairs of the KIDs this track names: a licence can return keys for other tracks too."""
work_dir.mkdir(parents=True, exist_ok=True)
self.work_dir = Path(tempfile.mkdtemp(prefix="segdec-", dir=work_dir))
@@ -65,21 +73,29 @@ class SegmentDecrypter:
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)
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) -> None:
output = segment.with_suffix(segment.suffix + ".dec")
output.unlink(missing_ok=True)
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(output)])
os.replace(output, segment)
self.run(["--fragments-info", str(self.init_path), str(segment), str(partial)])
os.replace(partial, output)
finally:
with contextlib.suppress(OSError):
output.unlink(missing_ok=True)
partial.unlink(missing_ok=True)
with contextlib.suppress(OSError):
segment.unlink()
return output
def init_bytes(self) -> bytes:
"""Decrypt the init segment on first call and return its bytes.
@@ -126,11 +142,11 @@ class SegmentDecrypter:
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
error = f"mp4decrypt failed on {args[-2]}: {e.stderr.strip() if e.stderr else f'exit code {e.returncode}'}"
raise coded(RuntimeError(error), APIErrorCode.DRM_ERROR) 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")
error = f"mp4decrypt failed on {args[-2]}: output file {output.name} is missing or empty"
raise coded(RuntimeError(error), APIErrorCode.DRM_ERROR)
+13 -11
View File
@@ -691,14 +691,25 @@ 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
if use_segment_decrypt and init_data:
decrypter = SegmentDecrypter(cast(SEGMENT_DRM_T, 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
if timescale:
rebase = PeriodRebase(period_starts, timescale)
append = rebase.append if rebase else partial(append_segment, is_text_subtitle=is_text_subtitle)
store = SegmentStore(track, save_dir)
if not collapse_single_url:
store.open(
track.url,
segments,
mode=DownloadMode(
segment_decrypt=use_segment_decrypt,
segment_keys=decrypter.track_keys if decrypter else (),
rolling_merge=use_rolling_merge,
stateful_merge=rebase is not None,
merge_rewrites=rebase_vtt,
),
)
@@ -729,16 +740,6 @@ class DASH:
},
)
decrypter: SegmentDecrypter | None = None
if use_segment_decrypt and init_data:
decrypter = SegmentDecrypter(cast(SEGMENT_DRM_T, 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
if timescale:
rebase = PeriodRebase(period_starts, timescale)
append = rebase.append if rebase else partial(append_segment, is_text_subtitle=is_text_subtitle)
merger, init_data = fetch_segments(
track,
ctx,
@@ -747,6 +748,7 @@ class DASH:
urls,
output_dir,
filename,
store,
rolling=use_rolling_merge,
init=init_data,
append=append,
+7 -6
View File
@@ -805,6 +805,11 @@ class HLS:
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
if use_segment_decrypt:
assert isinstance(session_drm, (Widevine, PlayReady, ClearKeyCENC))
segment_decrypter = SegmentDecrypter(session_drm, init_content, save_dir.parent, ctx.max_workers)
store = SegmentStore(track, save_dir)
store.open(
track.url,
@@ -812,7 +817,7 @@ class HLS:
# media_sequence feeds AES IVs; total_segments pins the OnSegmentFilter verdict (shifts every index)
extra=[str(getattr(master, "media_sequence", None) or 0), str(total_segments)],
mode=DownloadMode(
segment_decrypt=use_segment_decrypt,
segment_keys=segment_decrypter.track_keys if segment_decrypter else (),
rolling_merge=use_rolling_merge,
drm=session_drm,
aes128=any(key and key.method == "AES-128" for key in (master.keys or [])),
@@ -834,11 +839,6 @@ class HLS:
},
)
segment_decrypter: SegmentDecrypter | 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)
merger, decrypted_init = fetch_segments(
track,
ctx,
@@ -847,6 +847,7 @@ class HLS:
urls,
segment_save_dir,
f"{{i:0{len(str(len(urls)))}}}{{ext}}",
store,
rolling=use_rolling_merge,
init=map_data[1] if map_data else None,
decrypter=segment_decrypter,
+13 -1
View File
@@ -39,6 +39,7 @@ from unshackle.core.manifests.segment_pipeline import (
from unshackle.core.session import RnetSession
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video
from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore
from unshackle.core.tracks.track import iter_top_level_boxes
from unshackle.core.utilities import log_event, try_ensure_utf8
from unshackle.core.utils import run_proxy
from unshackle.core.utils.redact import safe_display_url
@@ -51,6 +52,16 @@ AUDIO_TAG_FOURCC = {"255": "AACL", "65534": "EC-3"}
FOURCC_MIME = {"H264": "avc1", "H265": "hvc1", "HEVC": "hvc1", "AACL": "mp4a", "AACH": "mp4a", "AACP": "mp4a"}
def first_iv_size(path: Path) -> int:
"""The per-sample IV size of the first fragment of a merged output, which the merge read from fragment 0."""
for box_type, offset, size in iter_top_level_boxes(path):
if box_type == b"moof":
with path.open("rb") as f:
f.seek(offset)
return read_per_sample_iv_size(f.read(size)) or 8
return 8
class ISM:
def __init__(self, manifest: Element, url: str) -> None:
if manifest.tag != "SmoothStreamingMedia":
@@ -447,7 +458,7 @@ class ISM:
},
)
iv_size = 8
iv_size = first_iv_size(save_path) if store.cursor and session_drm else 8
def append_ism(dst: BinaryIO, segment_file: Path) -> None:
"""Write one fragment; segment 0 also synthesises the init box the fragments lack."""
@@ -472,6 +483,7 @@ class ISM:
[{"url": url} for url in segments],
save_dir,
f"{{i:0{len(str(len(segments)))}}}.mp4",
store,
rolling=use_rolling_merge,
append=append_ism,
)
+41 -17
View File
@@ -23,7 +23,7 @@ from unshackle.core.events import events
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.session import AnySession
from unshackle.core.tracks import DownloadContext, Track
from unshackle.core.tracks.segment_store import SegmentStore
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
@@ -49,17 +49,24 @@ class RollingMerge:
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) waits for that future before the append, so the output never holds raw bytes.
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) -> None:
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 = 0
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:
@@ -69,9 +76,9 @@ class RollingMerge:
while self.cursor in self.ready:
path, pending = self.ready.pop(self.cursor)
if pending is not None:
pending.result()
path = pending.result()
self.append(self.dst, path)
self.cursor += 1
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
@@ -146,6 +153,7 @@ def fetch_segments(
urls: list[dict[str, Any]],
output_dir: Path,
filename: str,
store: SegmentStore,
*,
rolling: bool = False,
init: bytes | None = None,
@@ -154,19 +162,31 @@ def fetch_segments(
) -> 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. A decrypter gets every segment before its SEGMENT_DOWNLOADED event. Any failure closes
the decrypter and removes a rolling output. The returned init is the decrypter's decrypted init, else `init`.
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:
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)
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
@@ -183,15 +203,19 @@ def fetch_segments(
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:
future = decrypter.submit(file_downloaded) if decrypter else None
# listeners get the segment while it still exists; the merge unlinks it
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
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:
@@ -204,7 +228,7 @@ def fetch_segments(
except BaseException:
if decrypter:
decrypter.close()
if merger:
if merger and not store.checkpoint(merger.cursor, merger.length):
ctx.save_path.unlink(missing_ok=True)
raise
return merger, head_init
+77 -13
View File
@@ -1,8 +1,11 @@
from __future__ import annotations
import contextlib
import functools
import logging
import os
import shutil
import sys
import time
import uuid
from collections.abc import Callable, Iterator
@@ -10,7 +13,7 @@ from contextlib import contextmanager
from pathlib import Path
from typing import ParamSpec, TypeVar
from filelock import FileLock, Timeout
from filelock import FileLock
from unshackle.core.config import config
@@ -33,27 +36,78 @@ def is_stale(task_dir: Path) -> bool:
return False
except OSError:
return False
lock_path = task_dir / LOCK_NAME
if not lock_path.exists():
return True
lock = FileLock(lock_path, timeout=0)
return lock_free(task_dir)
def lock_free(task_dir: Path) -> bool:
"""Whether nothing holds the lock of a task dir."""
with claim(task_dir) as free:
return free
@contextmanager
def claim(task_dir: Path) -> Iterator[bool]:
"""Hold the lock of a task dir for the block when nothing else holds it; yield whether it did.
A plain lock call, not FileLock: FileLock deletes the lock file on release, and where the file system has no
lock call it falls back to a lock that it removes even when a live run holds it. A missing lock file counts as
free, any other OS error as held.
"""
try:
lock.acquire()
except (Timeout, OSError):
return False
lock.release()
return True
fd = os.open(task_dir / LOCK_NAME, os.O_RDWR)
except FileNotFoundError:
yield True
return
except OSError:
yield False
return
try:
try:
if sys.platform == "win32":
import msvcrt
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
yield False
return
yield True
finally:
os.close(fd)
def sweep_task_dirs(root: Path) -> None:
"""Remove task dirs left by processes that died without cleaning up, and resume stash entries past their age."""
"""Remove task dirs left by processes that died without cleaning up, and resume stash entries past their age.
Each task dir that nothing holds the lock of first gives the stash the segment directories it keeps for resume,
also inside the setup grace: a task dir still in setup keeps none. The sweep holds that lock meanwhile, so a
concurrent sweep leaves the task dir alone.
"""
# the segment store imports this module
from unshackle.core.tracks.segment_store import stash_kept
if not root.is_dir():
return
stash = root / RESUME_STASH
for entry in root.iterdir():
if entry.is_dir() and not entry.is_symlink() and entry.name.startswith(TASK_PREFIX) and is_stale(entry):
if not entry.is_dir() or entry.is_symlink() or not entry.name.startswith(TASK_PREFIX):
continue
try:
young = time.time() - entry.stat().st_mtime < STALE_GRACE
except OSError:
continue
with claim(entry) as free:
if free:
stash_kept(entry, stash)
if not young:
shutil.rmtree(entry, ignore_errors=True)
if free and not young:
# Windows keeps the lock file that the claim held open
shutil.rmtree(entry, ignore_errors=True)
stash = root / RESUME_STASH
if stash.is_dir():
cutoff = time.time() - STASH_MAX_AGE
for entry in stash.iterdir():
@@ -99,6 +153,16 @@ def task_temp_dir(task_id: str | None = None) -> Iterator[Path]:
yield task_dir
finally:
config.directories.temp = root
# empty it under the lock, so the sweep of another run never takes from a half-deleted task dir
with contextlib.suppress(OSError):
for child in task_dir.iterdir():
if child.name == LOCK_NAME:
continue
if child.is_dir() and not child.is_symlink():
shutil.rmtree(child, ignore_errors=True)
else:
with contextlib.suppress(OSError):
child.unlink()
lock.release()
shutil.rmtree(task_dir, ignore_errors=True)
+233 -67
View File
@@ -5,6 +5,12 @@ segmentation did not change. The proof is a digest of the segmentation, kept in
directory. The sidecar is never a file inside the directory: the parsers merge by globbing the directory with
no extension filter, so they would join any file in there into the output.
Each segment has its state in its name: NNNN.<ext> is a segment as the server sent it, and NNNN.clear is the
same segment after segment decryption. The sidecar records a digest of the content keys that made the .clear
files, and the checkpoint of a failed rolling merge: the first segment the output does not hold and the output
length at that segment. On resume the output is cut back to the checkpoint, and the download skips every
segment that the output or a .clear file already holds.
Track.download calls restore() before the parser and abandon() when the download fails. The parser calls
open() once its download mode is final, merging() when the last segment is on disk, rewriting() before its
merge first changes a segment file, and complete() after the merge. A DASH track collapsed to one ranged download
@@ -22,7 +28,7 @@ import shutil
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any
from urllib.parse import urlsplit, urlunsplit
from unshackle.core.config import config
@@ -33,6 +39,9 @@ if TYPE_CHECKING:
from unshackle.core.tracks.track import Track
_VERSION = 1
SIDECAR = ".resume.json"
CLEAR = ".clear"
"""The suffix of a decrypted segment."""
log = logging.getLogger("track")
@@ -41,8 +50,11 @@ log = logging.getLogger("track")
class DownloadMode:
"""The final download mode of a track: what the resume verdict reads."""
segment_decrypt: bool = False
segment_keys: Sequence[str] = ()
"""The KID:KEY pairs that decrypt each segment as it lands; empty when the segments stay encrypted."""
rolling_merge: bool = False
stateful_merge: bool = False
"""The rolling merge carries state from one segment to the next, so it cannot restart at a checkpoint."""
drm: DRM_T | None = None
aes128: bool = False
merge_rewrites: bool = False
@@ -82,8 +94,60 @@ def fingerprint(
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def decrypted(segment: Path) -> Path:
"""The name of a segment once segment decryption has decrypted it."""
return segment.with_suffix(CLEAR)
def _sidecar(save_dir: Path) -> Path:
return save_dir.with_name(save_dir.name + ".resume.json")
return save_dir.with_name(save_dir.name + SIDECAR)
def _output(save_dir: Path) -> Path:
"""The merged file of a segmented track; Track.download names the segment directory after it."""
return save_dir.with_name(save_dir.name.removesuffix("_segments"))
def _sidecar_record(save_dir: Path) -> dict[str, Any]:
"""The sidecar record of a segment directory; empty when it is missing, unreadable, malformed or has no digest."""
try:
data = json.loads(_sidecar(save_dir).read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return data if isinstance(data, dict) and data.get("digest") else {}
def _move(save_dir: Path, target: Path) -> None:
"""Rename a stashed segment directory back, then its sidecar, then the output of its merge checkpoint.
A failure only logs: a checkpoint without its output does not count on resume. A symlinked output stays
where it is.
"""
merged = "merge" in _sidecar_record(save_dir)
try:
save_dir.rename(target)
except OSError as e:
log.debug("Could not move %s: %s", save_dir, e)
return
moves = [(_sidecar(save_dir), _sidecar(target))]
if merged and not _output(save_dir).is_symlink():
moves.append((_output(save_dir), _output(target)))
for source, destination in moves:
try:
if source.exists():
source.replace(destination)
except OSError as e:
log.debug("Could not move %s: %s", source, e)
def _index(path: Path) -> int | None:
"""The segment index at the start of a segment file name; None for any other file."""
head = path.name.split(".", 1)[0]
return int(head) if head.isdigit() else None
def _key_digest(key_args: Sequence[str]) -> str | None:
return hashlib.sha256("\n".join(sorted(key_args)).encode("utf-8")).hexdigest() if key_args else None
class SegmentStore:
@@ -93,11 +157,25 @@ class SegmentStore:
self.track = track
self.save_dir = save_dir
self.mode = DownloadMode()
self.resumes = False
"""True once open() started a sidecar: a failed download then keeps its segments and its merge."""
self.cursor = 0
"""The first segment the kept rolling-merge output does not hold."""
self.length = 0
"""The byte length of the kept rolling-merge output at the cursor."""
self.clear: dict[int, Path] = {}
"""The kept decrypted segments by index."""
self._record: dict[str, Any] = {}
@property
def sidecar(self) -> Path:
return _sidecar(self.save_dir)
@property
def skip(self) -> frozenset[int]:
"""The segment indices the download skips: the kept output or a kept .clear file holds them."""
return frozenset(range(self.cursor)) | frozenset(self.clear)
@property
def keeps(self) -> bool:
"""True when a failed download keeps its completed segments for the next run."""
@@ -106,12 +184,11 @@ class SegmentStore:
def resumable(self, mode: DownloadMode) -> bool:
"""True when the segments of a download in this mode can cross a run boundary.
Segment decryption decrypts each segment in place, so a kept one would be decrypted twice or never.
A rolling merge unlinks each segment once it appends it, so nothing is left to reuse. 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.
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.
"""
if not self.keeps or mode.segment_decrypt or mode.rolling_merge:
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)))
@@ -128,24 +205,58 @@ class SegmentStore:
"""Make the directory ready for the download and return True when it keeps the segments of a prior run.
Call it once the download mode is final. The segments of a prior run stay only when the mode is
resumable and the sidecar records the same digest; otherwise the directory starts empty.
resumable and the sidecar records the same digest; otherwise the directory starts empty. Kept .clear
files stay only when this run decrypts segments with the same keys, and a kept rolling-merge output
only when this run also merges as it downloads.
"""
self.mode = mode
resumable = self.resumable(mode)
digest = fingerprint(manifest_url, segments, extra)
reused = resumable and self._recorded_digest() == digest
if not reused:
record = _sidecar_record(self.save_dir)
reused = resumable and record.get("digest") == digest
keys = _key_digest(mode.segment_keys)
if reused:
self._settle(record, keys)
else:
shutil.rmtree(self.save_dir, ignore_errors=True)
self.save_dir.mkdir(parents=True, exist_ok=True)
# a file the wipe could not remove (locked on Windows) belongs to another segmentation
if resumable and (reused or not any(self.save_dir.iterdir())):
self.sidecar.write_text(json.dumps({"version": _VERSION, "digest": digest}), encoding="utf-8")
else:
self.sidecar.unlink(missing_ok=True)
self.resumes = resumable and (reused or not any(self.save_dir.iterdir()))
if self.resumes:
self._record = {"version": _VERSION, "digest": digest, "keys": keys}
if self.cursor:
self._record["merge"] = [self.cursor, self.length]
try:
self._write()
except OSError as e:
log.debug("Could not write the resume sidecar of %s: %s", self.save_dir, e)
self.resumes = False
if not self.resumes:
with contextlib.suppress(OSError):
self.sidecar.unlink(missing_ok=True)
return reused
def checkpoint(self, cursor: int, length: int) -> bool:
"""Record that the first length bytes of the rolling-merge output hold the init and the segments below cursor.
The output goes to disk first, because the record vouches for its bytes. False when the store keeps
nothing; the caller then removes the output.
"""
if not self.resumes:
return False
self._record["merge"] = [cursor, length]
try:
with open(_output(self.save_dir), "rb+") as output:
os.fsync(output.fileno())
self._write()
except OSError as e:
log.debug("Could not record the merge checkpoint of %s: %s", self.save_dir, e)
return False
return True
def merging(self) -> None:
"""End the download phase: remove the .!dev files that superseded downloads left, so no merge reads one.
"""End the download phase: remove the .!dev files that superseded downloads left and each segment a
.clear file replaces, so no merge reads one.
When the mode says the merge rewrites segments in place (the WebVTT rebase of a multi-period DASH
subtitle), the sidecar goes now. HLS calls rewriting() itself before its first rewrite. Any other merge
@@ -154,6 +265,8 @@ class SegmentStore:
if self.save_dir.is_dir():
for control_file in self.save_dir.rglob("*.!dev"):
control_file.unlink(missing_ok=True)
if self.mode.segment_keys:
self._drop_replaced()
if self.mode.merge_rewrites:
self.rewriting()
@@ -174,8 +287,8 @@ class SegmentStore:
def restore(self) -> None:
"""Start a download: take back a stashed directory and drop its partial files, or wipe it when nothing is kept.
A partial file never crosses a run boundary. A completed segment does, and open() decides if the download
uses it.
A partial file never crosses a run boundary. A completed segment does, and open() decides if the
download uses it.
"""
if self.keeps:
self._unstash()
@@ -200,13 +313,53 @@ class SegmentStore:
"""False for a directory the store must never remove, such as the temp directory of a URL track."""
return self.save_dir.name.endswith("_segments")
def _recorded_digest(self) -> str | None:
"""The digest in the sidecar; None when it is missing, unreadable or malformed."""
def _write(self) -> None:
partial = self.sidecar.with_name(self.sidecar.name + ".tmp")
partial.write_text(json.dumps(self._record), encoding="utf-8")
os.replace(partial, self.sidecar)
def _segment_files(self) -> list[tuple[int, Path]]:
return [
(index, path)
for path in self.save_dir.rglob("*")
if path.is_file() and not path.name.endswith(".!dev") and (index := _index(path)) is not None
]
def _settle(self, record: dict[str, Any], keys: str | None) -> None:
"""Keep the state of a prior run that this run can continue from, and read it into the store.
A .clear file made with other keys, or kept for a run that does not decrypt segments, goes, and the decrypt
runs again on a segment file that its decrypt left behind. merging() removes a segment file beside a kept
.clear file. A checkpoint counts only when this run merges as it
downloads with the same keys, and the output is at least as long as the checkpoint records.
"""
same_keys = record.get("keys") == keys
try:
data = json.loads(self.sidecar.read_text(encoding="utf-8"))
return data.get("digest") or None
except (OSError, ValueError, AttributeError):
return None
cursor, length = map(int, record["merge"])
except (KeyError, TypeError, ValueError):
cursor, length = 0, 0
output = _output(self.save_dir)
if (
self.mode.rolling_merge
and same_keys
and cursor > 0
and output.is_file()
and output.stat().st_size >= length
):
self.cursor, self.length = cursor, length
for index, path in self._segment_files():
if index < self.cursor or (path.suffix == CLEAR and not (same_keys and keys)):
path.unlink(missing_ok=True)
elif path.suffix == CLEAR:
self.clear[index] = path
def _drop_replaced(self) -> None:
"""Remove each segment that a .clear file of the same index replaces; a decrypt that stopped left it."""
files = self._segment_files()
clear = {index for index, path in files if path.suffix == CLEAR}
for index, path in files:
if index in clear and path.suffix != CLEAR:
path.unlink(missing_ok=True)
def _sweep(self, keep: bool) -> None:
"""Keep only completed segments and the sidecar when keep is set, else remove both."""
@@ -222,52 +375,65 @@ class SegmentStore:
shutil.rmtree(self.save_dir)
self.sidecar.unlink(missing_ok=True)
def _move(self, target: Path) -> None:
"""Rename the directory, then its sidecar. A failure only logs."""
try:
self.save_dir.rename(target)
except OSError as e:
log.debug("Could not move %s: %s", self.save_dir, e)
return
try:
if self.sidecar.exists():
self.sidecar.replace(_sidecar(target))
except OSError as e:
log.debug("Could not move %s: %s", self.sidecar, e)
def _stash(self) -> None:
"""Move the completed segments, then the sidecar, into the stash file by file. Skip a segment on an OS error.
A directory rename would be simpler, but on Windows a worker that still writes a partial file after the
failure blocks the rename of its directory (WinError 5), and the task directory removal then loses it all.
"""
"""Move what the directory keeps for resume into the stash; see _stash_into."""
stash = resume_stash()
if stash is None or not self.save_dir.is_dir():
return
target = stash / self.save_dir.name
if target.exists():
return
target.mkdir(parents=True)
for path in self.save_dir.rglob("*"):
if not path.is_file() or path.name.endswith(".!dev") or path.with_name(path.name + ".!dev").exists():
continue
moved = target / path.relative_to(self.save_dir)
try:
moved.parent.mkdir(parents=True, exist_ok=True)
path.replace(moved)
except OSError as e:
log.debug("Could not stash %s: %s", path, e)
sidecar = _sidecar(target)
self.sidecar.replace(sidecar)
# replace keeps the old mtime, and the stash sweep ages entries by it
os.utime(sidecar)
if stash is not None and self.save_dir.is_dir():
_stash_into(self.save_dir, stash)
def _unstash(self) -> None:
"""Move a stashed directory and its sidecar back, if the stash has them and the directory is free."""
"""Move a stashed directory, its sidecar and its output back.
Only when the stash has them and the directory is free. The stash keeps the directory of a failed run, and
the sweep moves there the directory of a killed run.
"""
stash = resume_stash()
if stash is None:
if stash is None or self.save_dir.exists():
return
stashed = SegmentStore(self.track, stash / self.save_dir.name)
if stashed.save_dir.is_symlink() or not stashed.save_dir.is_dir() or self.save_dir.exists():
return
stashed._move(self.save_dir)
kept = stash / self.save_dir.name
if not kept.is_symlink() and kept.is_dir():
_move(kept, self.save_dir)
def _stash_into(save_dir: Path, stash: Path) -> None:
"""Move the completed segments of a directory, then its checkpointed output, then its sidecar into the stash.
File by file, skipping a segment on an OS error: on Windows a worker that still writes a partial file after the
failure blocks the rename of its directory (WinError 5), and the task directory removal then loses it all. A
partial file, the segment it would replace and a symlinked output stay where they are.
"""
target = stash / save_dir.name
if target.exists():
return
merged = "merge" in _sidecar_record(save_dir)
target.mkdir(parents=True)
for path in save_dir.rglob("*"):
if not path.is_file() or path.name.endswith(".!dev") or path.with_name(path.name + ".!dev").exists():
continue
moved = target / path.relative_to(save_dir)
try:
moved.parent.mkdir(parents=True, exist_ok=True)
path.replace(moved)
except OSError as e:
log.debug("Could not stash %s: %s", path, e)
output = _output(save_dir)
if merged and output.is_file() and not output.is_symlink():
try:
output.replace(_output(target))
except OSError as e:
log.debug("Could not stash %s: %s", output, e)
sidecar = _sidecar(target)
_sidecar(save_dir).replace(sidecar)
# replace keeps the old mtime, and the stash sweep ages entries by it
for path in (target, sidecar, _output(target)):
with contextlib.suppress(OSError):
os.utime(path)
def stash_kept(task_dir: Path, stash: Path) -> None:
"""Move each segment directory that a dead task dir keeps for resume into the stash."""
for sidecar in task_dir.glob(f"*{SIDECAR}"):
save_dir = sidecar.with_name(sidecar.name.removesuffix(SIDECAR))
if save_dir.is_dir() and not save_dir.is_symlink():
with contextlib.suppress(OSError):
_stash_into(save_dir, stash)
+5 -2
View File
@@ -776,10 +776,13 @@ class Track:
store = SegmentStore(self, save_dir)
def abandon() -> None:
"""Remove the output of a failed or cancelled download; a cleanup error must not replace its error."""
"""Stash or remove the output of a failed or cancelled download.
A cleanup error must not replace the error of the download.
"""
store.abandon()
with contextlib.suppress(OSError):
save_path.unlink(missing_ok=True)
store.abandon()
if not DOWNLOAD_LICENCE_ONLY.is_set():
if config.directories.temp.is_file():