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
+3 -3
View File
@@ -589,13 +589,13 @@ def test_hvcc_profile_tier_level_is_nonzero():
assert level_idc != 0
def piff_fragment(flags: int = 0x0, override: bool = False) -> bytes:
def piff_fragment(flags: int = 0x0, override: bool = False, iv_size: int = 8) -> bytes:
"""Minimal moof+mdat fragment carrying sample encryption in the PIFF uuid box."""
ivs = b"".join(bytes([i]) * 8 for i in range(1, 3))
ivs = b"".join(bytes([i]) * iv_size for i in range(1, 3))
senc_payload = struct.pack(">I", 2) + ivs
if override:
flags |= 0x1
senc_payload = b"\x00\x00\x01" + bytes([8]) + KID + senc_payload # AlgorithmID + IV_size + KID
senc_payload = b"\x00\x00\x01" + bytes([iv_size]) + KID + senc_payload # AlgorithmID + IV_size + KID
uuid_box = box(b"uuid", PIFF_SENC_UUID + bytes([0]) + flags.to_bytes(3, "big") + senc_payload)
tfhd = full_box(b"tfhd", 0, 0x20000, struct.pack(">I", 1))
trun = full_box(b"trun", 0, 0x1, struct.pack(">II", 2, 0)) # data_offset placeholder
+9 -5
View File
@@ -24,6 +24,7 @@ from unshackle.core.drm.key_args import shaka_noise, track_key_args
from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
from unshackle.core.drm.verify import kidless_track_kids
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks.segment_store import decrypted
KEY = "b5df2ae3f63b8dda9049d6e41422e075"
OTHER_KEY = "11" * 16
@@ -146,14 +147,15 @@ def test_a_failed_segment_decrypt_keeps_the_segment(
mp4decrypt_writes(output, 0, stderr)
drm = _widevine(A)
drm.content_keys[A] = KEY
segment_dir = tmp_path / "segments"
# the path holds a keyword that categorize_exception reads as a rate limit
segment_dir = tmp_path / "segments-429"
segment_dir.mkdir()
segment = segment_dir / "000.mp4"
segment.write_bytes(b"segment-0")
(segment_dir / "000.mp4.dec").write_bytes(b"stale")
(segment_dir / "000.clear.!dev").write_bytes(b"stale")
decrypter = SegmentDecrypter(drm, movie(encv(A)), tmp_path / "work", workers=1)
decrypter.submit(segment)
decrypter.submit(segment, decrypted(segment))
with pytest.raises(raises) as caught:
decrypter.finish()
@@ -284,6 +286,9 @@ def test_a_failed_mp4decrypt_keeps_the_input(
raises: type[BaseException],
) -> None:
mp4decrypt_writes(output, code, stderr)
# the path holds a keyword that categorize_exception reads as a rate limit
tmp_path = tmp_path / "work-429"
tmp_path.mkdir()
path, original, drm = mp4decrypt_track(tmp_path)
stray = tmp_path / "track_decrypted.mp4"
stray.write_bytes(b"stale")
@@ -293,8 +298,7 @@ def test_a_failed_mp4decrypt_keeps_the_input(
assert path.read_bytes() == original
assert not stray.exists()
if raises is subprocess.CalledProcessError:
assert categorize_exception(caught.value).error_code == APIErrorCode.DRM_ERROR
assert categorize_exception(caught.value).error_code == APIErrorCode.DRM_ERROR
@POSIX_STUBS
+112 -1
View File
@@ -8,12 +8,14 @@ import shutil
import time
from functools import partial
from pathlib import Path
from types import SimpleNamespace
import pytest
from filelock import FileLock
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled
from unshackle.core.temp import RESUME_STASH, STASH_MAX_AGE, resume_stash, sweep_task_dirs, task_temp_dir
from unshackle.core.temp import LOCK_NAME, RESUME_STASH, STASH_MAX_AGE, resume_stash, sweep_task_dirs, task_temp_dir
from unshackle.core.tracks import Video
from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore
@@ -112,6 +114,76 @@ def test_failed_track_resumes_in_next_run(temp_root, monkeypatch):
assert not stashed.exists()
def killed_run(temp_root: Path, name: str = "task_killed", segments: str = SEG_NAME) -> Path:
"""The task dir of a run killed mid-download: its lock file, a sidecar, a complete and a partial segment."""
task_dir = temp_root / name
task_dir.mkdir()
(task_dir / LOCK_NAME).touch()
save_dir = task_dir / segments
seed(SimpleNamespace(save_dir=save_dir))
(save_dir / "1.mp4.p.!dev").write_bytes(b"partial")
return task_dir
def test_a_killed_run_resumes_from_its_task_dir(temp_root, monkeypatch):
monkeypatch.setattr(config, "continue_downloads", True)
killed = killed_run(temp_root)
seen = {}
def second_parser(track, ctx):
seen["files"] = sorted(path.name for path in ctx.save_dir.iterdir())
seen["reusable"] = open_store(ctx.save_dir)
ctx.save_path.write_bytes(b"output")
track.path = ctx.save_path
with task_temp_dir():
run_download(monkeypatch, second_parser)
assert seen == {"files": ["0.mp4"], "reusable": True}
assert not (killed / SEG_NAME / "0.mp4").exists()
def test_the_sweep_stashes_what_a_killed_run_keeps_and_removes_the_rest(temp_root, monkeypatch):
monkeypatch.setattr(config, "continue_downloads", True)
killed = killed_run(temp_root)
(killed / "Audio_t2.mp4").write_bytes(b"a finished track")
old = killed_run(temp_root, "task_old", "Video_old.mp4_segments")
when = time.time() - STASH_MAX_AGE - 60
for save_dir in (killed / SEG_NAME, old / "Video_old.mp4_segments"):
for path in (save_dir.parent, save_dir, store(save_dir).sidecar):
os.utime(path, (when, when))
sweep_task_dirs(temp_root)
stashed = temp_root / RESUME_STASH / SEG_NAME
assert (stashed / "0.mp4").read_bytes() == b"complete segment"
assert store(stashed).sidecar.exists()
assert not killed.exists()
assert not old.exists()
# the stash ages an entry from when it arrived there, not from when the killed run wrote it
assert len(list((temp_root / RESUME_STASH).iterdir())) == 4
def test_a_killed_run_resumes_after_the_sweep_probed_its_lock(temp_root, monkeypatch):
monkeypatch.setattr(config, "continue_downloads", True)
killed = killed_run(temp_root)
when = time.time() - 120
os.utime(killed, (when, when))
with task_temp_dir() as task_dir:
store(task_dir / SEG_NAME).restore()
assert (task_dir / SEG_NAME / "0.mp4").read_bytes() == b"complete segment"
def test_a_running_task_keeps_its_segments(temp_root, monkeypatch):
monkeypatch.setattr(config, "continue_downloads", True)
running = killed_run(temp_root)
with FileLock(running / LOCK_NAME), task_temp_dir() as task_dir:
store(task_dir / SEG_NAME).restore()
assert not (task_dir / SEG_NAME).exists()
assert (running / SEG_NAME / "0.mp4").exists()
def test_flag_off_stashes_nothing(temp_root, monkeypatch):
monkeypatch.setattr(config, "continue_downloads", False)
@@ -133,6 +205,45 @@ def test_partials_are_not_stashed(temp_root, monkeypatch):
assert not list((temp_root / RESUME_STASH).rglob("*.!dev"))
def test_a_checkpointed_output_is_stashed_beside_its_segments(temp_root, monkeypatch):
monkeypatch.setattr(config, "continue_downloads", True)
with task_temp_dir() as task_dir:
save_dir = task_dir / SEG_NAME
rolling = store(save_dir)
rolling.open(make_track().url, SEGMENTS, mode=DownloadMode(rolling_merge=True))
(save_dir / "1.mp4").write_bytes(b"next segment")
(save_dir / "2.mp4").write_bytes(b"written")
(save_dir / "2.mp4.!dev").write_bytes(b"control")
(task_dir / "Video_t1.mp4").write_bytes(b"init+0")
assert rolling.checkpoint(1, 6)
rolling.abandon()
stashed = temp_root / RESUME_STASH / SEG_NAME
assert sorted(path.name for path in stashed.iterdir()) == ["1.mp4"]
assert (temp_root / RESUME_STASH / "Video_t1.mp4").read_bytes() == b"init+0"
@pytest.mark.skipif(os.name == "nt", reason="a symlink needs a privilege on Windows")
def test_a_symlinked_output_is_never_stashed(temp_root, monkeypatch, tmp_path):
monkeypatch.setattr(config, "continue_downloads", True)
elsewhere = tmp_path / "elsewhere.mp4"
elsewhere.write_bytes(b"not ours")
with task_temp_dir() as task_dir:
save_dir = task_dir / SEG_NAME
rolling = store(save_dir)
rolling.open(make_track().url, SEGMENTS, mode=DownloadMode(rolling_merge=True))
(save_dir / "1.mp4").write_bytes(b"next segment")
(task_dir / "Video_t1.mp4").symlink_to(elsewhere)
rolling._record["merge"] = [1, 6]
rolling._write()
rolling.abandon()
assert not (temp_root / RESUME_STASH / "Video_t1.mp4").exists()
assert elsewhere.read_bytes() == b"not ours"
def test_existing_stash_target_is_left_alone(temp_root, monkeypatch):
monkeypatch.setattr(config, "continue_downloads", True)
with task_temp_dir() as task_dir:
+318
View File
@@ -0,0 +1,318 @@
"""Resume in every download mode: a run that fails after some segments, then a second run, gives the bytes of a
run that never failed, and the second run fetches and decrypts only what the first did not finish."""
from __future__ import annotations
import importlib
from collections import Counter
from functools import partial
from pathlib import Path
from uuid import UUID
import pytest
import requests
from tests.core.test_ism_init import piff_fragment
from tests.core.test_rolling_merge_hls_ism import (
KID,
PARTS,
PIFF_PARTS,
FakeDRM,
dash_track,
hls_track,
ism_track,
make_ctx,
)
from tests.core.test_rolling_merge_hls_ism import no_cancel as no_cancel # noqa: F401
from tests.core.test_rolling_merge_hls_ism import (
no_decrypt,
)
from tests.core.test_rolling_merge_hls_ism import no_ffprobe as no_ffprobe # noqa: F401
from tests.core.test_rolling_merge_hls_ism import server as server # noqa: F401
from tests.core.test_rolling_merge_hls_ism import (
widevine,
)
from unshackle.core import binaries
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm.segment_decrypt import SegmentDecrypter
from unshackle.core.manifests import DASH, HLS, ISM
from unshackle.core.manifests import dash as dash_module
from unshackle.core.manifests import hls as hls_module
from unshackle.core.temp import RESUME_STASH, task_temp_dir
from unshackle.core.tracks.segment_store import SegmentStore, _index
KEY_A, KEY_B = "aa" * 16, "bb" * 16
FAIL_AT = 3
class Routes(dict):
"""The server routes, counting each request by path."""
hits: Counter
def get(self, key, default=None):
self.hits[key] += 1
return super().get(key, default)
@pytest.fixture
def routes(server):
server.routes = Routes(server.routes)
server.routes.hits = Counter()
return server.routes
@pytest.fixture(autouse=True)
def resume(monkeypatch):
monkeypatch.setattr(config, "continue_downloads", True)
monkeypatch.setattr(importlib.import_module("unshackle.core.downloaders.requests"), "MAX_ATTEMPTS", 1)
@pytest.fixture
def decrypted(monkeypatch) -> list[str]:
"""Segment decryption without mp4decrypt: the output is the input behind a mark of the key.
Returns the name of each file it decrypts.
"""
names: list[str] = []
def run(self, args):
source, target = Path(args[-2]), Path(args[-1])
names.append(source.name)
key = next(arg for arg in self.key_args if ":" in arg).split(":")[1]
target.write_bytes(f"[{key[:2]}]".encode() + source.read_bytes())
monkeypatch.setattr(SegmentDecrypter, "run", run)
monkeypatch.setattr(binaries, "Mp4decrypt", Path("mp4decrypt"))
return names
def segment_indices(names: list[str]) -> list[int]:
"""The segment indices among the decrypted file names; the init has none."""
return [index for name in names if (index := _index(Path(name))) is not None]
def segment_decryption(monkeypatch, on: bool) -> None:
for module in (dash_module, hls_module):
monkeypatch.setattr(module, "can_use", lambda *a, **kw: on)
# a 16-byte IV that only fragment 0 can tell the merge, as a PIFF override the CENC rewrite must agree with
PIFF16_PARTS = [
piff_fragment(override=True, iv_size=16).replace(b"\xab" * 64, bytes([0xD0 + i]) * 64) for i in range(len(PARTS))
]
def maker(server, parser, fragments=PIFF_PARTS):
"""A fresh track of the parser for each run, encrypted as a licence step and the decrypt step see it."""
if parser is ISM:
for i, fragment in enumerate(fragments):
server.routes[f"/x.ism/part{i}.m4s"] = fragment
def make():
if parser is ISM:
track = ism_track(server)
track.drm = [FakeDRM()]
else:
track = dash_track(server) if parser is DASH else hls_track(server, False)
track.drm = [widevine()]
return track
return make
def context(tmp_path, name: str, key: str):
ctx = make_ctx(tmp_path, name)
ctx.max_workers = 1
ctx.license_widevine = lambda drm, **kw: drm.content_keys.update({KID: key})
return ctx
def part(parser, index: int) -> str:
return f"/x.ism/part{index}.m4s" if parser is ISM else f"/part{index}.m4s"
def fail_once(server, parser, make, ctx) -> None:
"""Run a download that fails on segment FAIL_AT."""
body = server.routes.pop(part(parser, FAIL_AT))
with pytest.raises(requests.HTTPError):
parser.download_track(make(), ctx)
server.routes[part(parser, FAIL_AT)] = body
DOWNLOAD_CANCELLED.clear()
MODES = [
pytest.param(parser, segment_decrypt, merge, id=f"{parser.__name__.lower()}-{name}")
for parser in (DASH, HLS, ISM)
for segment_decrypt, merge, name in [
(False, False, "plain"),
(False, True, "rolling"),
(True, False, "segment-decrypt"),
(True, True, "segment-decrypt-rolling"),
]
if parser is not ISM or not segment_decrypt
]
@pytest.mark.parametrize("parser, segment_decrypt, merge", MODES)
def test_a_resumed_download_matches_one_that_never_failed(
server, routes, tmp_path, monkeypatch, decrypted, parser, segment_decrypt, merge
):
monkeypatch.setattr(config, "merge_segments", merge)
segment_decryption(monkeypatch, segment_decrypt)
no_decrypt(monkeypatch, mark=b"whole:")
make = maker(server, parser)
whole = context(tmp_path, "whole.mp4", KEY_A)
parser.download_track(make(), whole)
# a DASH licence step reads segment 0 for the KID; every other request is the download
probes = Counter({path: hits - 1 for path, hits in routes.hits.items()})
ctx = context(tmp_path, "resumed.mp4", KEY_A)
decrypted.clear()
fail_once(server, parser, make, ctx)
first = segment_indices(decrypted)
routes.hits.clear()
decrypted.clear()
parser.download_track(make(), ctx)
assert ctx.save_path.read_bytes() == whole.save_path.read_bytes()
assert all(routes.hits[part(parser, i)] == probes[part(parser, i)] for i in range(FAIL_AT))
# a segment that the failure stopped before its decrypt is decrypted on resume; no segment is decrypted twice
assert sorted(first + segment_indices(decrypted)) == (list(range(len(PARTS))) if segment_decrypt else [])
assert not ctx.save_dir.exists()
assert not SegmentStore(make(), ctx.save_dir).sidecar.exists()
def test_a_resumed_ism_merge_keeps_the_iv_size_of_fragment_zero(server, routes, tmp_path, monkeypatch):
monkeypatch.setattr(config, "merge_segments", True)
no_decrypt(monkeypatch)
make = maker(server, ISM, PIFF16_PARTS)
whole = context(tmp_path, "whole.mp4", KEY_A)
ISM.download_track(make(), whole)
ctx = context(tmp_path, "resumed.mp4", KEY_A)
fail_once(server, ISM, make, ctx)
routes.hits.clear()
ISM.download_track(make(), ctx)
assert ctx.save_path.read_bytes() == whole.save_path.read_bytes()
assert not routes.hits[part(ISM, 0)]
@pytest.mark.parametrize("merge", [False, True], ids=["segment-decrypt", "segment-decrypt-rolling"])
def test_keys_of_other_tracks_do_not_discard_what_the_track_key_decrypted(
server, routes, tmp_path, monkeypatch, decrypted, merge
):
monkeypatch.setattr(config, "merge_segments", merge)
segment_decryption(monkeypatch, True)
no_decrypt(monkeypatch)
make = maker(server, DASH)
whole = context(tmp_path, "whole.mp4", KEY_A)
DASH.download_track(make(), whole)
probes = Counter({path: hits - 1 for path, hits in routes.hits.items()})
ctx = context(tmp_path, "resumed.mp4", KEY_A)
# the first run licenses and gets the keys of other tracks too; the second takes the track key from a vault
ctx.license_widevine = lambda drm, **kw: drm.content_keys.update({KID: KEY_A, UUID(int=7): KEY_B})
fail_once(server, DASH, make, ctx)
ctx.license_widevine = whole.license_widevine
routes.hits.clear()
DASH.download_track(make(), ctx)
assert ctx.save_path.read_bytes() == whole.save_path.read_bytes()
assert all(routes.hits[part(DASH, i)] == probes[part(DASH, i)] for i in range(FAIL_AT))
@pytest.mark.parametrize("merge", [False, True], ids=["segment-decrypt", "segment-decrypt-rolling"])
def test_a_new_key_discards_what_the_old_key_decrypted(server, tmp_path, monkeypatch, decrypted, merge):
monkeypatch.setattr(config, "merge_segments", merge)
segment_decryption(monkeypatch, True)
no_decrypt(monkeypatch)
make = maker(server, DASH)
whole = context(tmp_path, "whole.mp4", KEY_B)
DASH.download_track(make(), whole)
ctx = context(tmp_path, "resumed.mp4", KEY_A)
fail_once(server, DASH, make, ctx)
ctx.license_widevine = whole.license_widevine
DASH.download_track(make(), ctx)
assert ctx.save_path.read_bytes() == whole.save_path.read_bytes()
assert b"[aa]" not in ctx.save_path.read_bytes()
def test_kept_decrypted_segments_past_the_checkpoint_are_merged_without_a_request(
server, routes, tmp_path, monkeypatch, decrypted
):
monkeypatch.setattr(config, "merge_segments", True)
segment_decryption(monkeypatch, True)
no_decrypt(monkeypatch)
make = maker(server, DASH)
whole = context(tmp_path, "whole.mp4", KEY_A)
DASH.download_track(make(), whole)
ctx = context(tmp_path, "resumed.mp4", KEY_A)
probes = Counter({path: hits - 1 for path, hits in routes.hits.items()})
fail_once(server, DASH, make, ctx)
# segment 4 finished before the failure: its decrypt replaced it, but a lock kept the downloaded file
raw = routes[part(DASH, 4)]
(ctx.save_dir / "4.clear").write_bytes(b"[aa]" + raw)
(ctx.save_dir / "4.mp4").write_bytes(raw)
(ctx.save_dir / "3.clear.!dev").write_bytes(b"half a decrypt")
with open(ctx.save_path, "ab") as output:
output.write(b"\xff" * 100_000)
routes.hits.clear()
decrypted.clear()
DASH.download_track(make(), ctx)
assert ctx.save_path.read_bytes() == whole.save_path.read_bytes()
assert {path for path, hits in routes.hits.items() if path.startswith("/part") and hits > probes[path]} == {
part(DASH, FAIL_AT)
}
assert [name for name in decrypted if name[0].isdigit()] == ["3.mp4"]
def test_a_rolling_output_crosses_the_run_boundary_in_the_stash(server, routes, tmp_path, monkeypatch, decrypted):
monkeypatch.setattr(config, "merge_segments", True)
monkeypatch.setattr(config.directories, "temp", tmp_path / "temp")
segment_decryption(monkeypatch, True)
no_decrypt(monkeypatch)
make = maker(server, DASH)
def download(key: str) -> object:
track = make()
track.download(
session=requests.Session(),
prepare_drm=lambda drm, **kw: drm.content_keys.update({KID: key}),
progress=partial(lambda **kw: None),
max_workers=1,
)
return track
with task_temp_dir():
whole = download(KEY_A).path.read_bytes()
probes = Counter({path: hits - 1 for path, hits in routes.hits.items()})
body = server.routes.pop(part(DASH, FAIL_AT))
with task_temp_dir():
with pytest.raises(requests.HTTPError):
download(KEY_A)
stash = config.directories.temp / RESUME_STASH
assert sorted(p.name for p in stash.iterdir()) == [
"Video_" + make().id + ".mp4",
"Video_" + make().id + ".mp4_segments",
"Video_" + make().id + ".mp4_segments.resume.json",
]
assert not list(stash.rglob("*.!dev"))
server.routes[part(DASH, FAIL_AT)] = body
DOWNLOAD_CANCELLED.clear()
routes.hits.clear()
with task_temp_dir():
assert download(KEY_A).path.read_bytes() == whole
assert all(routes.hits[part(DASH, i)] == probes[part(DASH, i)] for i in range(FAIL_AT))
+3 -1
View File
@@ -220,13 +220,15 @@ class FakeDRM:
class FakeSegmentDecrypter:
"""Per-segment decryption that hands each segment straight back, with a fixed decrypted init."""
track_keys: list[str] = []
def __init__(self, drm, init_content, workdir, max_workers):
self.submitted: list = []
def init_bytes(self) -> bytes:
return DECRYPTED_INIT
def submit(self, segment) -> Future:
def submit(self, segment, output) -> Future:
self.submitted.append(segment)
future: Future = Future()
future.set_result(segment)
+9 -5
View File
@@ -24,6 +24,7 @@ from unshackle.core.manifests.segment_pipeline import (
license_drm,
)
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks.segment_store import SegmentStore
from unshackle.core.tracks.track import DownloadContext, Track
INIT = b"init" * 8
@@ -107,10 +108,10 @@ class FakeDecrypter:
def init_bytes(self) -> bytes:
return DECRYPTED_INIT
def submit(self, segment: Path) -> Future:
def submit(self, segment: Path, output: Path) -> Future:
self.calls.append(("submit", segment.exists()))
future: Future = Future()
future.set_result(None)
future.set_result(segment)
return future
def finish(self) -> bytes:
@@ -137,7 +138,10 @@ def fetch(ctx: DownloadContext, downloader: FakeDownloader, **kw: Any) -> tuple[
ctx.save_dir.mkdir(parents=True, exist_ok=True)
track = SimpleNamespace(id="EXAMPLE", downloader=downloader)
urls = [{"url": f"https://cdn.example/{i}.m4s"} for i in range(len(PARTS))]
return fetch_segments(track, ctx, SESSION, "EXAMPLE", urls, ctx.save_dir, "{i}.mp4", **kw) # type: ignore[arg-type]
store = SegmentStore(track, ctx.save_dir) # type: ignore[arg-type]
return fetch_segments( # type: ignore[arg-type]
track, ctx, SESSION, "EXAMPLE", urls, ctx.save_dir, "{i}.mp4", store, **kw
)
def test_rolling_merge_writes_the_init_then_the_segments_in_order(tmp_path, seen):
@@ -166,13 +170,13 @@ def test_without_rolling_merge_the_segments_stay_for_the_manifest_merge(tmp_path
assert len(seen) == len(PARTS)
def test_a_decrypter_gets_each_segment_before_its_event_and_heads_the_output(tmp_path, seen):
def test_each_segment_gets_its_event_before_the_decrypter_and_the_decrypted_init_heads_the_output(tmp_path, seen):
ctx = make_ctx(tmp_path)
merger, decrypted_init = fetch(ctx, FakeDownloader(), rolling=True, init=INIT, decrypter=FakeDecrypter(seen))
assert decrypted_init == DECRYPTED_INIT
assert ctx.save_path.read_bytes() == DECRYPTED_INIT + b"".join(PARTS)
assert seen == [("submit", True), ("segment", True)] * len(PARTS) + [("finish", None)]
assert seen == [("segment", True), ("submit", True)] * len(PARTS) + [("finish", None)]
def test_a_failure_closes_the_decrypter_and_removes_the_output(tmp_path, seen):
+65 -4
View File
@@ -37,6 +37,7 @@ SEGMENTS = [
]
RESUMABLE = DownloadMode()
KID = UUID(int=1)
KEY_ARGS = ["--key", f"{KID.hex}:{'00' * 16}"]
def make_track(descriptor: Video.Descriptor = Video.Descriptor.DASH) -> Video:
@@ -115,7 +116,7 @@ def test_a_mode_that_cannot_resume_withdraws_the_sidecar(tmp_path, keep):
store.open(MPD, SEGMENTS, mode=RESUMABLE)
(store.save_dir / "0.mp4").write_bytes(b"decrypted in place")
assert store.open(MPD, SEGMENTS, mode=DownloadMode(segment_decrypt=True)) is False
assert store.open(MPD, SEGMENTS, mode=DownloadMode(rolling_merge=True, stateful_merge=True)) is False
assert not store.sidecar.exists()
assert store.open(MPD, SEGMENTS, mode=RESUMABLE) is False
@@ -124,11 +125,14 @@ def test_a_mode_that_cannot_resume_withdraws_the_sidecar(tmp_path, keep):
"descriptor, mode, resumable",
[
(Video.Descriptor.DASH, RESUMABLE, True),
(Video.Descriptor.DASH, DownloadMode(segment_decrypt=True), False),
(Video.Descriptor.DASH, DownloadMode(rolling_merge=True), False),
(Video.Descriptor.DASH, DownloadMode(segment_keys=KEY_ARGS), True),
(Video.Descriptor.DASH, DownloadMode(rolling_merge=True), True),
(Video.Descriptor.DASH, DownloadMode(rolling_merge=True, stateful_merge=True), False),
(Video.Descriptor.DASH, DownloadMode(stateful_merge=True), True),
(Video.Descriptor.DASH, DownloadMode(drm=ClearKeyCENC(kids=[KID])), True),
(Video.Descriptor.ISM, RESUMABLE, True),
(Video.Descriptor.ISM, DownloadMode(rolling_merge=True), False),
(Video.Descriptor.ISM, DownloadMode(rolling_merge=True), True),
(Video.Descriptor.HLS, DownloadMode(segment_keys=KEY_ARGS, rolling_merge=True, drm=widevine()), True),
(Video.Descriptor.HLS, RESUMABLE, True),
(Video.Descriptor.HLS, DownloadMode(drm=widevine()), True),
(Video.Descriptor.HLS, DownloadMode(aes128=True), False),
@@ -139,9 +143,12 @@ def test_a_mode_that_cannot_resume_withdraws_the_sidecar(tmp_path, keep):
"dash",
"dash-segment-decrypt",
"dash-rolling",
"dash-rolling-stateful",
"dash-stateful-post-merge",
"dash-clearkey-cenc",
"ism",
"ism-rolling",
"hls-segment-decrypt-rolling",
"hls",
"hls-widevine",
"hls-aes128",
@@ -215,6 +222,60 @@ def test_sidecar_is_never_inside_save_dir(tmp_path):
assert store.sidecar.parent == store.save_dir.parent
def test_open_keeps_decrypted_segments_only_for_the_same_keys(tmp_path, keep):
keys = DownloadMode(segment_keys=KEY_ARGS)
store = make_store(tmp_path)
store.open(MPD, SEGMENTS, mode=keys)
(store.save_dir / "0.clear").write_bytes(b"decrypted")
(store.save_dir / "0.mp4").write_bytes(b"left by a stopped decrypt")
(store.save_dir / "1.mp4").write_bytes(b"downloaded")
again = make_store(tmp_path)
assert again.open(MPD, SEGMENTS, mode=keys) is True
assert again.clear == {0: store.save_dir / "0.clear"} and again.skip == {0}
again.merging()
assert sorted(p.name for p in store.save_dir.iterdir()) == ["0.clear", "1.mp4"]
(store.save_dir / "0.mp4").write_bytes(b"left by a stopped decrypt")
other = make_store(tmp_path)
assert other.open(MPD, SEGMENTS, mode=DownloadMode(segment_keys=["--key", "other"])) is True
assert other.clear == {} and other.skip == frozenset()
assert sorted(p.name for p in store.save_dir.iterdir()) == ["0.mp4", "1.mp4"]
@pytest.mark.parametrize(
"mode, output, cursor",
[
(DownloadMode(rolling_merge=True), b"x" * 50, 2),
(DownloadMode(rolling_merge=True), b"x" * 49, 0),
(DownloadMode(), b"x" * 50, 0),
(DownloadMode(rolling_merge=True, segment_keys=KEY_ARGS), b"x" * 50, 0),
],
ids=["kept", "short-output", "no-rolling-merge", "other-keys"],
)
def test_a_checkpoint_counts_only_for_its_merge(tmp_path, keep, mode, output, cursor):
store = make_store(tmp_path)
store.open(MPD, SEGMENTS, mode=DownloadMode(rolling_merge=True))
for i in range(3):
(store.save_dir / f"{i}.mp4").write_bytes(b"segment")
(tmp_path / "Video_x.mp4").write_bytes(output)
assert store.checkpoint(2, 50)
again = make_store(tmp_path)
assert again.open(MPD, SEGMENTS, mode=mode) is True
assert (again.cursor, again.skip) == (cursor, frozenset(range(cursor)))
assert json.loads(again.sidecar.read_text()).get("merge") == ([2, 50] if cursor else None)
assert sorted(p.name for p in store.save_dir.iterdir()) == [f"{i}.mp4" for i in range(cursor, 3)]
def test_a_store_that_keeps_nothing_records_no_checkpoint(tmp_path, monkeypatch):
monkeypatch.setattr(config, "continue_downloads", False)
store = make_store(tmp_path)
store.open(MPD, SEGMENTS, mode=DownloadMode(rolling_merge=True))
assert store.checkpoint(1, 10) is False
assert not store.sidecar.exists()
@pytest.fixture
def one_attempt(monkeypatch, keep):
monkeypatch.setattr(config, "merge_segments", False)
+35 -3
View File
@@ -16,7 +16,7 @@ from filelock import FileLock
from unshackle.commands.env import clear_directory
from unshackle.core.config import config
from unshackle.core.temp import LOCK_NAME, TASK_PREFIX, is_stale, sweep_task_dirs, task_temp_dir
from unshackle.core.temp import LOCK_NAME, TASK_PREFIX, claim, is_stale, lock_free, sweep_task_dirs, task_temp_dir
pytestmark = pytest.mark.unit
@@ -169,6 +169,38 @@ def test_clear_directory_removes_stale_task_dir(temp_root: Path) -> None:
files_count, freed_bytes = clear_directory(temp_root)
assert not task_dir.exists()
assert temp_root.is_dir()
# glob("**/*") never matches dotfiles, so .lock is not counted
assert files_count == 1
assert files_count == 2 # the orphan and the lock file, which the stale probe keeps
assert freed_bytes == 5
def test_the_probe_of_a_live_lock_keeps_the_lock_file(temp_root: Path) -> None:
task_dir = make_task_dir(temp_root, lock=False)
with FileLock(task_dir / LOCK_NAME):
assert not lock_free(task_dir)
assert (task_dir / LOCK_NAME).exists()
task_dir.mkdir(exist_ok=True)
(task_dir / LOCK_NAME).touch()
assert lock_free(task_dir)
assert (task_dir / LOCK_NAME).exists()
@pytest.mark.skipif(os.name == "nt", reason="patches the POSIX lock call")
def test_a_lock_call_that_fails_counts_as_held(temp_root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import errno
import fcntl
def no_lock(fd: int, operation: int) -> None:
raise OSError(errno.ENOSYS, "no lock call")
monkeypatch.setattr(fcntl, "flock", no_lock)
task_dir = make_task_dir(temp_root)
backdate(task_dir)
sweep_task_dirs(temp_root)
assert (task_dir / LOCK_NAME).exists()
def test_a_claimed_task_dir_is_held_for_a_second_sweep(temp_root: Path) -> None:
task_dir = make_task_dir(temp_root)
with claim(task_dir) as first, claim(task_dir) as second:
assert (first, second) == (True, False)
assert not lock_free(task_dir)
+13
View File
@@ -273,3 +273,16 @@ def test_service_mounted_adapter_forces_single_process(server, tmp_path, monkeyp
pass
assert len(list(tmp_path.glob("seg_*.bin"))) == n
def test_multiprocess_skips_the_held_indices_and_counts_them_done(server, tmp_path):
n = dl.MP_MIN_SEGMENTS
urls = [{"url": url(server, f"/seg/{i}.bin")} for i in range(n)]
skip = frozenset(range(0, n, 3))
events = list(
dl.requests(urls, tmp_path, "seg_{i:04}.bin", session=Session(), max_workers=4, processes=2, skip=skip)
)
assert sum(e.get("advance", 0) for e in events) == n
assert sorted(p.name for p in tmp_path.iterdir()) == [f"seg_{i:04}.bin" for i in range(n) if i not in skip]
+48
View File
@@ -0,0 +1,48 @@
"""The downloader skips the indices it is told an earlier step already holds."""
from __future__ import annotations
import importlib
import threading
from collections import Counter
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
dl = importlib.import_module("unshackle.core.downloaders.requests")
class _Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.server.hits[self.path] += 1
body = self.path.encode() * 10
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
@pytest.fixture
def server():
srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
srv.hits = Counter()
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.shutdown()
thread.join(timeout=5)
@pytest.mark.parametrize("skip", [{1}, {0, 2}, {0, 1, 2}, {2, 7}], ids=["middle", "ends", "all", "one-and-unknown"])
def test_skipped_indices_get_no_request_and_count_as_done(server, tmp_path, skip):
urls = [f"http://127.0.0.1:{server.server_address[1]}/{i}" for i in range(3)]
events = list(dl.requests(urls, tmp_path, "{i}.mp4", max_workers=2, skip=frozenset(skip)))
kept = [i for i in range(3) if i not in skip]
assert sorted(e["file_downloaded"].name for e in events if "file_downloaded" in e) == [f"{i}.mp4" for i in kept]
assert sorted(p.name for p in tmp_path.iterdir()) == [f"{i}.mp4" for i in kept]
assert sum(server.hits.values()) == len(kept)
assert sum(e.get("advance", 0) for e in events) == 3
+3 -2
View File
@@ -39,9 +39,10 @@ def test_out_of_order_segments_match_whole_merge(tmp_path: Path) -> None:
order = list(range(len(payloads)))
rng.shuffle(order)
for index in order:
segment = save_dir / f"{index:0{width}d}.mp4"
future: Future = Future()
future.set_result(None)
merger.add(index, save_dir / f"{index:0{width}d}.mp4", future if index % 2 else None)
future.set_result(segment)
merger.add(index, segment, future if index % 2 else None)
# the cursor never rests on a segment that is ready: every contiguous run is drained
assert merger.merged not in merger.ready
+9 -8
View File
@@ -9,6 +9,7 @@ import pytest
from unshackle.core import binaries
from unshackle.core.drm.segment_decrypt import SegmentDecrypter
from unshackle.core.tracks.segment_store import decrypted
pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="the mp4decrypt stub is a shell script")
@@ -42,15 +43,15 @@ def test_segments_and_init_decrypt(tmp_path: Path, stub_mp4decrypt: Path) -> Non
decrypter = SegmentDecrypter(FakeDRM(), b"init-data", tmp_path / "work", workers=2)
work_dir = decrypter.work_dir
for segment in segments:
decrypter.submit(segment)
futures = [decrypter.submit(segment, decrypted(segment)) for segment in segments]
init_data = decrypter.finish()
assert init_data == b"init-data"
# the stub copies, so a replaced segment keeps its bytes under its original name
assert sorted(p.name for p in segment_dir.iterdir()) == ["000.mp4", "001.mp4", "002.mp4"]
for i, segment in enumerate(segments):
assert segment.read_bytes() == f"segment-{i}".encode()
# the stub copies, so each decrypted segment keeps its bytes under its decrypted name
assert sorted(p.name for p in segment_dir.iterdir()) == ["000.clear", "001.clear", "002.clear"]
for i, (segment, future) in enumerate(zip(segments, futures, strict=True)):
assert future.result() == decrypted(segment)
assert decrypted(segment).read_bytes() == f"segment-{i}".encode()
assert not work_dir.exists()
calls = read_argv(stub_mp4decrypt)
@@ -60,7 +61,7 @@ def test_segments_and_init_decrypt(tmp_path: Path, stub_mp4decrypt: Path) -> Non
assert len(segment_calls) == 3
for call in segment_calls:
assert call[call.index("--fragments-info") + 1].endswith("init.mp4")
assert call[-1].endswith(".dec")
assert call[-1].endswith(".clear.!dev")
assert Path(call[-2]).parent == segment_dir
init_calls = [call for call in calls if "--fragments-info" not in call]
@@ -85,7 +86,7 @@ def test_failure_reraises_and_leaves_no_temp_files(tmp_path: Path, monkeypatch:
segment.write_bytes(b"segment-0")
decrypter = SegmentDecrypter(FakeDRM(), b"init-data", tmp_path / "work", workers=1)
decrypter.submit(segment)
decrypter.submit(segment, decrypted(segment))
with pytest.raises(RuntimeError, match="no key"):
decrypter.finish()
+22
View File
@@ -76,6 +76,28 @@ class Harness:
self.skipped.append(track)
def test_ctrl_c_cancels_the_tracks_still_downloading():
seen = {}
def run_one(track, _index):
if track.id == "a":
raise KeyboardInterrupt
# a deadline, not a delay: without the cancel this waits it out and records False
seen[track.id] = DOWNLOAD_CANCELLED.wait(timeout=10)
with pytest.raises(KeyboardInterrupt):
download_tracks_in_passes(
[make_video(), make_audio()],
2,
run_one,
skip_subtitle_errors=False,
on_subtitle_skipped=lambda track: None,
)
assert seen == {"v": True}
assert DOWNLOAD_CANCELLED.is_set()
@pytest.fixture(autouse=True)
def clear_event():
DOWNLOAD_CANCELLED.clear()