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
+19 -9
View File
@@ -119,7 +119,10 @@ stopped instead of restarting from byte zero.
unshackle keeps the segments of a failed track in a `resume` directory inside the temp
directory, and the next download of the same track takes them back from there. It removes a
kept entry after 7 days, and `unshackle env clear temp` removes them all. A process that is
killed, or a job cancelled over the REST API, keeps nothing.
killed, and a job that the REST API cancels, keep their completed segments too. The next run
moves them into the `resume` directory, and the next download of the track takes them from
there. A merge during the download records its progress only when the download fails, so after
a kill the next download keeps only the segments that the merge had not appended yet.
unshackle reuses only whole, fully downloaded segments. It always discards partially written
segments, and no partial-byte (`Range`) resume across runs takes place. Reuse is possible only
@@ -137,8 +140,18 @@ ranges must all match the previous download, or the download silently restarts c
during its merge step. A failure before that point, such as a failed init segment
fetch, keeps the downloaded segments.
- A track downloaded with [`merge_segments`](#merge_segments) or
[`decrypt_segments`](drm.md#decrypt_segments) never resumes. Both options consume
or rewrite the segment files during the download.
[`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
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
`merge_segments`: the merge moves the decode times of each period, and the next
download cannot continue that from the middle.
- A service that puts a session token in the path of its segment URLs, or in the URL
of an HLS variant playlist, gives the track new URLs on each run. Its downloads always
restart.
For a one-off resume without changing config, pass `dl --continue-downloads` on the
command line (the flag can only enable resume, never disable it).
@@ -161,7 +174,7 @@ the next segment it needs and appends every segment that is ready in order, then
segment file. With [`decrypt_segments`](drm.md#decrypt_segments) also on, each segment is
appended after its decryption completes, never before.
This option is off by default because it disables resume. In a measurement of a 3 GiB track in
This option is off by default. In a measurement of a 3 GiB track in
1500 segments with 16 workers, on an SSD and a loopback server, the merge during the download took
0.9 s more than the merge after it on Linux and 1.1 s less on Windows. With each connection limited
to 8 MiB/s, it took 2.2 s less on Linux and 8.0 s less on Windows. On a hard disk, the append to one
@@ -173,11 +186,8 @@ 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.
!!! note "No resume"
A track that merges segment by segment always downloads from the start.
[`continue_downloads`](#continue_downloads) cannot reuse its segments, because unshackle
deletes each segment after it appends it.
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.
```yaml
merge_segments: true
+2 -5
View File
@@ -229,11 +229,8 @@ 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.
!!! note "No resume"
A track that decrypts segment by segment always downloads from the start.
[`continue_downloads`](download.md#continue_downloads) cannot reuse its segments, because a reused segment
is already decrypted.
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.
```yaml
decrypt_segments: true
+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()
+17 -5
View File
@@ -348,7 +348,8 @@ def download_tracks_in_passes(
concurrently first. The subtitles then download one at a time (a concurrent pass would let one
failure's cancel silently drop the others, unrecorded), with the event cleared before each.
Video/audio failures stay fatal. This function clears the event on entry (stale cancel from a
prior title) and in ``finally`` (never leave it set for later code).
prior title) and on exit (never leave it set for later code). A Ctrl+C leaves it set: a second
Ctrl+C while the pool waits must not let the tracks that still run carry on.
``run_one(track, index)`` downloads a single track. ``on_subtitle_skipped(track)`` records a
subtitle whose download raised (handled here).
@@ -361,11 +362,21 @@ def download_tracks_in_passes(
else:
primary, skippable = indexed, []
interrupted = False
try:
with ThreadPoolExecutor(max_concurrent) as pool:
future_to_track = {pool.submit(run_one, track, i): track for i, track in primary}
for download in futures.as_completed(future_to_track):
download.result() # a video/audio failure is fatal
pending = {pool.submit(run_one, track, i) for i, track in primary}
try:
# timed: on Windows an untimed wait holds Ctrl+C back until a track ends
while pending:
done, pending = futures.wait(pending, timeout=0.5, return_when=futures.FIRST_COMPLETED)
for download in done:
download.result() # a video/audio failure is fatal
except KeyboardInterrupt:
# Ctrl+C reaches only this thread; the pool exit waits for the tracks unless they see the cancel
interrupted = True
DOWNLOAD_CANCELLED.set()
raise
for i, track in skippable:
DOWNLOAD_CANCELLED.clear()
@@ -374,7 +385,8 @@ def download_tracks_in_passes(
except Exception:
on_subtitle_skipped(track)
finally:
DOWNLOAD_CANCELLED.clear() # never leave a failed track's cancel set for later code
if not interrupted:
DOWNLOAD_CANCELLED.clear() # never leave a failed track's cancel set for later code
LOW_FREE_SPACE = 1024**3
+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():