diff --git a/docs/reference/configuration/download.md b/docs/reference/configuration/download.md index de3fda5e..58f65dd4 100644 --- a/docs/reference/configuration/download.md +++ b/docs/reference/configuration/download.md @@ -132,7 +132,8 @@ ranges must all match the previous download, or the download silently restarts c download never make segment files, so this option does not apply to them (the downloader has its own in-flight partial-file handling for those). - HLS resumes Widevine/PlayReady and unencrypted titles only. An AES-128 title always - restarts. An HLS failure during the post-download merge step also restarts. + restarts. An HLS failure during the post-download merge step also restarts, and so does + a failure of a multi-period DASH WebVTT subtitle during its merge step. - 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. diff --git a/tests/core/test_resume_across_runs.py b/tests/core/test_resume_across_runs.py index afd7d5db..aa28abf6 100644 --- a/tests/core/test_resume_across_runs.py +++ b/tests/core/test_resume_across_runs.py @@ -13,20 +13,13 @@ import pytest 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, - restore_segments, - resume_stash, - stash_segments, - sweep_task_dirs, - task_temp_dir, -) -from unshackle.core.tracks import Video, resume +from unshackle.core.temp import 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 pytestmark = pytest.mark.unit -DIGEST = "f" * 64 +SEGMENTS = [("https://example.test/0.mp4", None)] SEG_NAME = "Video_t1.mp4_segments" @@ -68,10 +61,17 @@ def run_download(monkeypatch: pytest.MonkeyPatch, parser) -> None: ) +def store(save_dir: Path) -> SegmentStore: + return SegmentStore(make_track(), save_dir) + + +def open_store(save_dir: Path) -> bool: + return store(save_dir).open(make_track().url, SEGMENTS, mode=DownloadMode()) + + def seed(ctx): - ctx.save_dir.mkdir(parents=True, exist_ok=True) + open_store(ctx.save_dir) (ctx.save_dir / "0.mp4").write_bytes(b"complete segment") - resume.write_sidecar(ctx.save_dir, DIGEST) def failing_parser(track, ctx): @@ -95,13 +95,13 @@ def test_failed_track_resumes_in_next_run(temp_root, monkeypatch): stashed = temp_root / RESUME_STASH / SEG_NAME assert (stashed / "0.mp4").read_bytes() == b"complete segment" - assert resume.sidecar_path(stashed).exists() + assert store(stashed).sidecar.exists() seen = {} def second_parser(track, ctx): seen["bytes"] = (ctx.save_dir / "0.mp4").read_bytes() - seen["reusable"] = resume.reusable(ctx.save_dir, DIGEST) + seen["reusable"] = open_store(ctx.save_dir) ctx.save_path.write_bytes(b"output") track.path = ctx.save_path @@ -133,7 +133,8 @@ def test_partials_are_not_stashed(temp_root, monkeypatch): assert not list((temp_root / RESUME_STASH).rglob("*.!dev")) -def test_existing_stash_target_is_left_alone(temp_root): +def test_existing_stash_target_is_left_alone(temp_root, monkeypatch): + monkeypatch.setattr(config, "continue_downloads", True) with task_temp_dir() as task_dir: target = temp_root / RESUME_STASH / SEG_NAME target.mkdir(parents=True) @@ -142,17 +143,18 @@ def test_existing_stash_target_is_left_alone(temp_root): save_dir.mkdir() (save_dir / "new.mp4").write_bytes(b"new") - stash_segments(save_dir) + store(save_dir).abandon() assert (target / "old.mp4").read_bytes() == b"old" assert not (target / "new.mp4").exists() assert save_dir.exists() -def test_restore_is_a_noop_without_stash_or_with_present_dir(temp_root): +def test_restore_is_a_noop_without_stash_or_with_present_dir(temp_root, monkeypatch): + monkeypatch.setattr(config, "continue_downloads", True) with task_temp_dir() as task_dir: save_dir = task_dir / SEG_NAME - restore_segments(save_dir) + store(save_dir).restore() assert not save_dir.exists() target = temp_root / RESUME_STASH / SEG_NAME @@ -160,7 +162,7 @@ def test_restore_is_a_noop_without_stash_or_with_present_dir(temp_root): (target / "a.mp4").write_bytes(b"a") save_dir.mkdir() - restore_segments(save_dir) + store(save_dir).restore() assert (target / "a.mp4").exists() assert not (save_dir / "a.mp4").exists() @@ -184,7 +186,7 @@ def test_locked_segment_never_replaces_download_error(temp_root, monkeypatch): rmtree = shutil.rmtree def locked(path, *args, **kwargs): - if Path(path).name == SEG_NAME: + if Path(path).name == SEG_NAME and not kwargs.get("ignore_errors"): raise PermissionError(32, "being used by another process", str(path)) rmtree(path, *args, **kwargs) @@ -242,7 +244,7 @@ def test_cancelled_track_is_stashed(temp_root, monkeypatch): stashed = temp_root / RESUME_STASH / SEG_NAME assert (stashed / "0.mp4").read_bytes() == b"complete segment" - assert resume.sidecar_path(stashed).exists() + assert store(stashed).sidecar.exists() def test_presized_data_file_is_dropped_with_its_control_file(temp_root, monkeypatch): @@ -264,15 +266,15 @@ def test_presized_data_file_is_dropped_with_its_control_file(temp_root, monkeypa assert not (stashed / "1.mp4.!dev").exists() -def test_stash_refreshes_mtime(temp_root): +def test_stash_refreshes_mtime(temp_root, monkeypatch): + monkeypatch.setattr(config, "continue_downloads", True) with task_temp_dir() as task_dir: save_dir = task_dir / SEG_NAME - save_dir.mkdir() - resume.write_sidecar(save_dir, DIGEST) + open_store(save_dir) stamp = time.time() - STASH_MAX_AGE - 60 os.utime(save_dir, (stamp, stamp)) - stash_segments(save_dir) + store(save_dir).abandon() target = temp_root / RESUME_STASH / SEG_NAME assert time.time() - target.stat().st_mtime < 60 diff --git a/tests/core/test_resume_fingerprint.py b/tests/core/test_resume_fingerprint.py deleted file mode 100644 index ec81540a..00000000 --- a/tests/core/test_resume_fingerprint.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Offline unit tests for the cross-run segment-resume sidecar: fingerprint stability -across rotating query tokens, sensitivity to real segmentation changes, sidecar -read/write robustness, and the sidecar-outside-save_dir invariant that protects the -merge glob from concatenating it into the output.""" - -from __future__ import annotations - -import json -from pathlib import Path - -from unshackle.core.tracks import resume - -MPD = "https://cdn/manifest.mpd" -SEGMENTS = [ - ("https://cdn/media.mp4", "863-1999"), - ("https://cdn/media.mp4", "2000-3999"), - ("https://cdn/media.mp4", "4000-5999"), -] - - -def test_identical_inputs_identical_digest(): - assert resume.fingerprint(MPD, SEGMENTS) == resume.fingerprint(MPD, SEGMENTS) - - -def test_rotating_query_token_ignored(): - tokenised = [(f"{url}?token=abc123&expires=999", rng) for url, rng in SEGMENTS] - assert resume.fingerprint(f"{MPD}?auth=xyz", tokenised) == resume.fingerprint(MPD, SEGMENTS) - - -def test_changed_byte_range_changes_digest(): - changed = [SEGMENTS[0], ("https://cdn/media.mp4", "2000-4000"), SEGMENTS[2]] - assert resume.fingerprint(MPD, changed) != resume.fingerprint(MPD, SEGMENTS) - - -def test_changed_segment_count_changes_digest(): - assert resume.fingerprint(MPD, SEGMENTS[:2]) != resume.fingerprint(MPD, SEGMENTS) - - -def test_changed_url_path_changes_digest(): - moved = [("https://cdn/other.mp4", rng) for _, rng in SEGMENTS] - assert resume.fingerprint(MPD, moved) != resume.fingerprint(MPD, SEGMENTS) - - -def test_query_carried_identity_is_not_collapsed(): - # all segments share a path and differ only in the query (e.g. $Time$ as a query - # param): stripping must not collapse them into false matches; the digest goes - # verbatim and distinct segmentations stay distinct - a = [("https://cdn/seg?t=0", None), ("https://cdn/seg?t=100", None)] - b = [("https://cdn/seg?t=0", None), ("https://cdn/seg?t=200", None)] - assert resume.fingerprint(MPD, a) != resume.fingerprint(MPD, b) - - -def test_extra_inputs_change_digest(): - assert resume.fingerprint(MPD, SEGMENTS, extra=["100", "3"]) != resume.fingerprint(MPD, SEGMENTS) - - -def test_reusable_roundtrip(tmp_path: Path): - save_dir = tmp_path / "Video_x_segments" - digest = resume.fingerprint(MPD, SEGMENTS) - resume.write_sidecar(save_dir, digest) - assert resume.reusable(save_dir, digest) is True - assert resume.reusable(save_dir, "0" * 64) is False - - -def test_reusable_never_raises(tmp_path: Path): - save_dir = tmp_path / "Video_x_segments" - digest = resume.fingerprint(MPD, SEGMENTS) - assert resume.reusable(save_dir, digest) is False # no sidecar - resume.sidecar_path(save_dir).write_text("{not json", encoding="utf-8") - assert resume.reusable(save_dir, digest) is False # malformed - resume.sidecar_path(save_dir).write_text(json.dumps({"version": 1}), encoding="utf-8") - assert resume.reusable(save_dir, digest) is False # no digest key - - -def test_clear_sidecar(tmp_path: Path): - save_dir = tmp_path / "Video_x_segments" - digest = resume.fingerprint(MPD, SEGMENTS) - resume.write_sidecar(save_dir, digest) - resume.clear_sidecar(save_dir) - assert resume.reusable(save_dir, digest) is False - resume.clear_sidecar(save_dir) # idempotent on a missing file - - -def test_sidecar_is_never_inside_save_dir(tmp_path: Path): - save_dir = tmp_path / "Video_x_segments" - assert resume.sidecar_path(save_dir).parent == save_dir.parent diff --git a/tests/core/test_resume_hls_integration.py b/tests/core/test_resume_hls_integration.py index 0effed6d..9f51b232 100644 --- a/tests/core/test_resume_hls_integration.py +++ b/tests/core/test_resume_hls_integration.py @@ -19,7 +19,8 @@ import requests from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.manifests import HLS -from unshackle.core.tracks import resume +from unshackle.core.tracks import Video +from unshackle.core.tracks.segment_store import SegmentStore from unshackle.core.tracks.track import DownloadContext PART0 = bytes([0xA0]) * 300 @@ -95,6 +96,10 @@ def make_track(srv): return HLS.from_text(MASTER, url=f"{base(srv)}master.m3u8").to_tracks(language="en").videos[0] +def sidecar(ctx): + return SegmentStore(Video(url="", language="en"), ctx.save_dir).sidecar + + def make_ctx(tmp_path): return DownloadContext( save_path=tmp_path / "out.mp4", @@ -114,7 +119,7 @@ def test_hls_second_run_reuses_completed_segments(server, tmp_path): HLS.download_track(make_track(server), ctx) assert (ctx.save_dir / "segments" / "0.bin").read_bytes() == PART0 - assert resume.sidecar_path(ctx.save_dir).exists() + assert sidecar(ctx).exists() part0_fetches_run1 = server.requests.count("/part0.bin") DOWNLOAD_CANCELLED.clear() @@ -123,7 +128,7 @@ def test_hls_second_run_reuses_completed_segments(server, tmp_path): assert ctx.save_path.read_bytes() == PART0 + PART1 assert server.requests.count("/part0.bin") == part0_fetches_run1 - assert not resume.sidecar_path(ctx.save_dir).exists() + assert not sidecar(ctx).exists() def test_hls_aes128_content_never_writes_sidecar(server, tmp_path): @@ -137,4 +142,4 @@ def test_hls_aes128_content_never_writes_sidecar(server, tmp_path): with pytest.raises(requests.HTTPError): HLS.download_track(make_track(server), ctx) - assert not resume.sidecar_path(ctx.save_dir).exists() + assert not sidecar(ctx).exists() diff --git a/tests/core/test_resume_integration.py b/tests/core/test_resume_integration.py index 4f2bcfa1..3c781cbd 100644 --- a/tests/core/test_resume_integration.py +++ b/tests/core/test_resume_integration.py @@ -21,7 +21,8 @@ import requests from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.manifests import DASH -from unshackle.core.tracks import resume +from unshackle.core.tracks import Video +from unshackle.core.tracks.segment_store import SegmentStore from unshackle.core.tracks.track import DownloadContext pytestmark = pytest.mark.skipif(shutil.which("ffprobe") is None, reason="requires ffprobe") @@ -101,6 +102,10 @@ def make_track(text: str, srv): return DASH.from_text(text, url=f"{base(srv)}manifest.mpd").to_tracks(language="en").videos[0] +def sidecar(ctx): + return SegmentStore(Video(url="", language="en"), ctx.save_dir).sidecar + + def make_ctx(tmp_path): return DownloadContext( save_path=tmp_path / "out.mp4", @@ -121,7 +126,7 @@ def test_second_run_reuses_completed_segments(server, tmp_path): DASH.download_track(make_track(mpd(server), server), ctx) assert (ctx.save_dir / "0.mp4").read_bytes() == PART0 - assert resume.sidecar_path(ctx.save_dir).exists() + assert sidecar(ctx).exists() part0_fetches_run1 = server.requests.count("/part0.bin") DOWNLOAD_CANCELLED.clear() @@ -130,7 +135,7 @@ def test_second_run_reuses_completed_segments(server, tmp_path): assert ctx.save_path.read_bytes() == INIT + PART0 + PART1 assert server.requests.count("/part0.bin") == part0_fetches_run1 - assert not resume.sidecar_path(ctx.save_dir).exists() + assert not sidecar(ctx).exists() assert not ctx.save_dir.exists() diff --git a/tests/core/test_resume_track_lifecycle.py b/tests/core/test_resume_track_lifecycle.py index ecfe2af0..272cad97 100644 --- a/tests/core/test_resume_track_lifecycle.py +++ b/tests/core/test_resume_track_lifecycle.py @@ -16,7 +16,8 @@ import pytest from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY -from unshackle.core.tracks import Video, resume +from unshackle.core.tracks import Video +from unshackle.core.tracks.segment_store import SegmentStore @pytest.fixture(autouse=True) @@ -48,10 +49,14 @@ def seed_prior_run(tmp_path: Path) -> Path: (save_dir / "0.mp4").write_bytes(b"complete segment") (save_dir / "1.mp4.p.!dev").write_bytes(b"partial") (save_dir / "segments" / "2.bin.h.!dev").write_bytes(b"hedge partial") - resume.write_sidecar(save_dir, "f" * 64) + sidecar(save_dir).write_text("{}") return save_dir +def sidecar(save_dir: Path) -> Path: + return SegmentStore(make_track(), save_dir).sidecar + + def run_download(track: Video, monkeypatch, fail: bool): import requests as requests_lib @@ -80,7 +85,7 @@ def test_flag_on_keeps_segments_and_sidecar_sweeps_partials(tmp_path, monkeypatc run_download(track, monkeypatch, fail=True) assert (save_dir / "0.mp4").read_bytes() == b"complete segment" - assert resume.sidecar_path(save_dir).exists() + assert sidecar(save_dir).exists() assert not list(save_dir.rglob("*.!dev")) @@ -93,17 +98,17 @@ def test_flag_off_wipes_segments_and_sidecar(tmp_path, monkeypatch): run_download(track, monkeypatch, fail=True) assert not save_dir.exists() - assert not resume.sidecar_path(save_dir).exists() + assert not sidecar(save_dir).exists() def test_flag_off_clears_orphaned_sidecar_without_dir(tmp_path, monkeypatch): monkeypatch.setattr(config, "continue_downloads", False) save_dir = tmp_path / "Video_t1.mp4_segments" # a kill between a parser's dir removal and its sidecar clear leaves exactly this - resume.write_sidecar(save_dir, "f" * 64) + sidecar(save_dir).write_text("{}") track = make_track() with pytest.raises(RuntimeError): run_download(track, monkeypatch, fail=True) - assert not resume.sidecar_path(save_dir).exists() + assert not sidecar(save_dir).exists() diff --git a/tests/core/test_segment_store.py b/tests/core/test_segment_store.py new file mode 100644 index 00000000..4800fe25 --- /dev/null +++ b/tests/core/test_segment_store.py @@ -0,0 +1,263 @@ +"""The segment store through its interface: the identity digest, the resume verdict, the sidecar lifecycle, +and a resume across two runs of the HLS and ISM parsers.""" + +from __future__ import annotations + +import importlib +import json +import shutil +from pathlib import Path +from uuid import UUID + +import pytest +import requests + +from tests.core.test_rolling_merge_hls_ism import INIT, PARTS, 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.config import config +from unshackle.core.constants import DOWNLOAD_CANCELLED +from unshackle.core.drm import ClearKey, ClearKeyCENC +from unshackle.core.manifests import HLS, ISM +from unshackle.core.manifests import hls as hls_module +from unshackle.core.tracks import Video +from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore, fingerprint + +MPD = "https://cdn/manifest.mpd" +SEGMENTS = [ + ("https://cdn/media.mp4", "863-1999"), + ("https://cdn/media.mp4", "2000-3999"), + ("https://cdn/media.mp4", "4000-5999"), +] +RESUMABLE = DownloadMode() +KID = UUID(int=1) + + +def make_track(descriptor: Video.Descriptor = Video.Descriptor.DASH) -> Video: + return Video(url=MPD, language="en", descriptor=descriptor) + + +def make_store(tmp_path: Path, descriptor: Video.Descriptor = Video.Descriptor.DASH) -> SegmentStore: + return SegmentStore(make_track(descriptor), tmp_path / "Video_x.mp4_segments") + + +@pytest.fixture +def keep(monkeypatch): + monkeypatch.setattr(config, "continue_downloads", True) + + +def test_identical_inputs_identical_digest(): + assert fingerprint(MPD, SEGMENTS) == fingerprint(MPD, SEGMENTS) + + +def test_rotating_query_token_ignored(): + tokenised = [(f"{url}?token=abc123&expires=999", rng) for url, rng in SEGMENTS] + assert fingerprint(f"{MPD}?auth=xyz", tokenised) == fingerprint(MPD, SEGMENTS) + + +def test_changed_byte_range_changes_digest(): + changed = [SEGMENTS[0], ("https://cdn/media.mp4", "2000-4000"), SEGMENTS[2]] + assert fingerprint(MPD, changed) != fingerprint(MPD, SEGMENTS) + + +def test_changed_segment_count_changes_digest(): + assert fingerprint(MPD, SEGMENTS[:2]) != fingerprint(MPD, SEGMENTS) + + +def test_changed_url_path_changes_digest(): + moved = [("https://cdn/other.mp4", rng) for _, rng in SEGMENTS] + assert fingerprint(MPD, moved) != fingerprint(MPD, SEGMENTS) + + +def test_query_carried_identity_is_not_collapsed(): + a = [("https://cdn/seg?t=0", None), ("https://cdn/seg?t=100", None)] + b = [("https://cdn/seg?t=0", None), ("https://cdn/seg?t=200", None)] + assert fingerprint(MPD, a) != fingerprint(MPD, b) + + +def test_extra_inputs_change_digest(): + assert fingerprint(MPD, SEGMENTS, extra=["100", "3"]) != fingerprint(MPD, SEGMENTS) + + +def test_open_keeps_segments_only_for_the_same_identity(tmp_path, keep): + store = make_store(tmp_path) + assert store.open(MPD, SEGMENTS, mode=RESUMABLE) is False + (store.save_dir / "0.mp4").write_bytes(b"segment") + + assert store.open(MPD, SEGMENTS, mode=RESUMABLE) is True + assert (store.save_dir / "0.mp4").read_bytes() == b"segment" + + assert store.open(MPD, SEGMENTS[:2], mode=RESUMABLE) is False + assert store.save_dir.is_dir() and not list(store.save_dir.iterdir()) + + +@pytest.mark.parametrize( + "content", ["{not json", json.dumps({"version": 1}), "[]"], ids=["malformed", "no-digest", "list"] +) +def test_a_bad_sidecar_starts_clean(tmp_path, keep, content): + store = make_store(tmp_path) + store.save_dir.mkdir() + (store.save_dir / "0.mp4").write_bytes(b"segment") + store.sidecar.write_text(content, encoding="utf-8") + + assert store.open(MPD, SEGMENTS, mode=RESUMABLE) is False + assert not (store.save_dir / "0.mp4").exists() + + +def test_a_mode_that_cannot_resume_withdraws_the_sidecar(tmp_path, keep): + store = make_store(tmp_path) + 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 not store.sidecar.exists() + assert store.open(MPD, SEGMENTS, mode=RESUMABLE) is False + + +@pytest.mark.parametrize( + "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(drm=ClearKeyCENC(kids=[KID])), True), + (Video.Descriptor.ISM, RESUMABLE, True), + (Video.Descriptor.ISM, DownloadMode(rolling_merge=True), False), + (Video.Descriptor.HLS, RESUMABLE, True), + (Video.Descriptor.HLS, DownloadMode(drm=widevine()), True), + (Video.Descriptor.HLS, DownloadMode(aes128=True), False), + (Video.Descriptor.HLS, DownloadMode(drm=ClearKeyCENC(kids=[KID])), False), + (Video.Descriptor.HLS, DownloadMode(drm=ClearKey(key=bytes(16))), False), + ], + ids=[ + "dash", + "dash-segment-decrypt", + "dash-rolling", + "dash-clearkey-cenc", + "ism", + "ism-rolling", + "hls", + "hls-widevine", + "hls-aes128", + "hls-clearkey-cenc", + "hls-clearkey", + ], +) +def test_resume_verdict(tmp_path, keep, descriptor, mode, resumable): + assert make_store(tmp_path, descriptor).resumable(mode) is resumable + + +def test_no_resume_with_the_option_off(tmp_path, monkeypatch): + monkeypatch.setattr(config, "continue_downloads", False) + store = make_store(tmp_path) + assert store.resumable(RESUMABLE) is False + store.open(MPD, SEGMENTS, mode=RESUMABLE) + assert not store.sidecar.exists() + + +@pytest.mark.parametrize("rewrites", [False, True], ids=["reads", "rewrites"]) +def test_merging_drops_control_files_and_keeps_segments(tmp_path, keep, rewrites): + store = make_store(tmp_path) + store.open(MPD, SEGMENTS, mode=DownloadMode(merge_rewrites=rewrites)) + (store.save_dir / "segments").mkdir() + (store.save_dir / "0.mp4").write_bytes(b"segment") + (store.save_dir / "0.mp4.h.!dev").write_bytes(b"superseded") + (store.save_dir / "segments" / "1.ts.!dev").write_bytes(b"superseded") + + store.merging() + + assert (store.save_dir / "0.mp4").exists() + assert not list(store.save_dir.rglob("*.!dev")) + assert store.sidecar.exists() is not rewrites + + +def test_a_file_the_wipe_left_gets_no_sidecar(tmp_path, keep, monkeypatch): + store = make_store(tmp_path) + store.save_dir.mkdir() + (store.save_dir / "0.mp4").write_bytes(b"locked") + monkeypatch.setattr(shutil, "rmtree", lambda *a, **kw: None) + + assert store.open(MPD, SEGMENTS, mode=RESUMABLE) is False + assert not store.sidecar.exists() + + +def test_the_store_never_removes_a_directory_it_does_not_own(tmp_path, keep): + store = SegmentStore(make_track(Video.Descriptor.URL), tmp_path) + assert store.resumable(RESUMABLE) is False + (tmp_path / "other.mp4").write_bytes(b"other") + + store.complete() + store.restore() + + assert (tmp_path / "other.mp4").exists() + + +def test_complete_removes_the_directory_and_sidecar(tmp_path, keep): + store = make_store(tmp_path) + store.open(MPD, SEGMENTS, mode=RESUMABLE) + (store.save_dir / "stray.mp4.!dev").write_bytes(b"late hedge") + + store.complete() + + assert not store.save_dir.exists() + assert not store.sidecar.exists() + store.complete() + + +def test_sidecar_is_never_inside_save_dir(tmp_path): + store = make_store(tmp_path) + assert store.sidecar.parent == store.save_dir.parent + + +@pytest.fixture +def one_attempt(monkeypatch, keep): + monkeypatch.setattr(config, "merge_segments", False) + monkeypatch.setattr(importlib.import_module("unshackle.core.downloaders.requests"), "MAX_ATTEMPTS", 1) + + +def two_runs(server, ctx, parser, make, missing: str, segment: Path) -> bytes: + """Fail the first run on a missing segment, mark a kept segment, and return the output of the second run.""" + route = server.routes.pop(missing) + with pytest.raises(requests.HTTPError): + parser.download_track(make(), ctx) + assert SegmentStore(make(), ctx.save_dir).sidecar.exists() + + segment.write_bytes(b"\xee" * 10) + server.routes[missing] = route + DOWNLOAD_CANCELLED.clear() + parser.download_track(make(), ctx) + assert not ctx.save_dir.exists() + assert not SegmentStore(make(), ctx.save_dir).sidecar.exists() + return ctx.save_path.read_bytes() + + +def test_ism_resumes_from_the_kept_segments(server, tmp_path, one_attempt): + ctx = make_ctx(tmp_path, "ism.mp4") + ctx.max_workers = 1 + + output = two_runs(server, ctx, ISM, lambda: ism_track(server), "/x.ism/part3.m4s", ctx.save_dir / "1.mp4") + + assert b"\xee" * 10 in output + assert PARTS[1] not in output + assert output.endswith(PARTS[2] + PARTS[3] + PARTS[4]) + + +def test_hls_resumes_when_the_init_turns_segment_decryption_off(server, tmp_path, monkeypatch, one_attempt): + monkeypatch.setattr(hls_module, "can_use", lambda drm, decryption, init=None: init is None) + no_decrypt(monkeypatch) + + def make(): + track = hls_track(server, False) + track.drm = [widevine()] + return track + + ctx = make_ctx(tmp_path, "hls.mp4") + ctx.max_workers = 1 + ctx.license_widevine = lambda *a, **kw: None + + output = two_runs(server, ctx, HLS, make, "/part3.m4s", ctx.save_dir / "segments" / "1.m4s") + + assert output == INIT + PARTS[0] + b"\xee" * 10 + b"".join(PARTS[2:]) diff --git a/unshackle/core/manifests/dash.py b/unshackle/core/manifests/dash.py index fa2fbab9..136a3130 100644 --- a/unshackle/core/manifests/dash.py +++ b/unshackle/core/manifests/dash.py @@ -43,7 +43,8 @@ from unshackle.core.manifests.segment_pipeline import ( ) from unshackle.core.manifests.trim import trim_overlaps from unshackle.core.session import RnetSession, unrecorded -from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume +from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video +from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track, parse_sidx from unshackle.core.utilities import is_close_match, log_event, try_ensure_utf8 from unshackle.core.utils import run_proxy @@ -684,18 +685,23 @@ class DASH: # subtitle segments are tiny, the post-download merge costs nothing there use_rolling_merge = not collapse_single_url and config.merge_segments and not isinstance(track, Subtitle) + is_text_subtitle = ( + not drm and isinstance(track, Subtitle) and track.codec not in (Subtitle.Codec.fVTT, Subtitle.Codec.fTTML) + ) + known = timed and len(period_starts) > 1 + rebase_vtt = known and is_text_subtitle and track.codec == Subtitle.Codec.WebVTT + + store = SegmentStore(track, save_dir) if not collapse_single_url: - # per-segment decryption rewrites each segment in place, so a segment kept from an - # earlier run would either be decrypted twice or never at all; a rolling merge - # unlinks each segment as it is appended, so there is nothing left to reuse - can_resume = config.continue_downloads and not use_segment_decrypt and not use_rolling_merge - # reuse a prior run's segments only when the fingerprint proves the segmentation unchanged - digest = resume.fingerprint(track.url, segments) - if not (can_resume and resume.reusable(save_dir, digest)): - shutil.rmtree(save_dir, ignore_errors=True) - save_dir.mkdir(parents=True, exist_ok=True) - if can_resume: - resume.write_sidecar(save_dir, digest) + store.open( + track.url, + segments, + mode=DownloadMode( + segment_decrypt=use_segment_decrypt, + rolling_merge=use_rolling_merge, + merge_rewrites=rebase_vtt, + ), + ) urls: list[dict[str, Any]] if collapse_single_url: @@ -723,16 +729,11 @@ class DASH: }, ) - is_text_subtitle = ( - not drm and isinstance(track, Subtitle) and track.codec not in (Subtitle.Codec.fVTT, Subtitle.Codec.fTTML) - ) - 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 - known = timed and len(period_starts) > 1 timescale = mdhd_timescale(init_data) if known and init_data and not is_text_subtitle else None if timescale: rebase = PeriodRebase(period_starts, timescale) @@ -756,8 +757,7 @@ class DASH: with open(save_path, "r+b") as collapsed: collapsed.truncate(collapse_span[1] + 1) elif merger: - for control_file in save_dir.glob("*.!dev"): - control_file.unlink(missing_ok=True) + store.merging() check_merged(merger, len(segments), track, ctx, "DASH") else: if not save_dir.exists(): @@ -776,8 +776,7 @@ class DASH: ) raise FileNotFoundError(error_msg) - for control_file in save_dir.glob("*.!dev"): - control_file.unlink(missing_ok=True) + store.merging() segments_to_merge = [x for x in sorted(save_dir.iterdir()) if x.is_file()] @@ -813,7 +812,7 @@ class DASH: ) raise FileNotFoundError(error_msg) - if known and is_text_subtitle and track.codec == Subtitle.Codec.WebVTT: + if rebase_vtt: firsts = sorted(period_starts) groups: list[list[Path]] = [[] for _ in firsts] for segment_file in segments_to_merge: diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py index 1279d4b5..a01d1ec9 100644 --- a/unshackle/core/manifests/hls.py +++ b/unshackle/core/manifests/hls.py @@ -44,10 +44,10 @@ from unshackle.core.manifests.segment_pipeline import ( fetch_segments, license_drm, licensing, - remove_segment_dir, ) from unshackle.core.session import RnetResponse, RnetSession, unrecorded, utf8_text -from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume +from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video +from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track, assert_fragments_decrypted from unshackle.core.utilities import get_extension, is_close_match, log_event, try_ensure_utf8 from unshackle.core.utils import run_proxy @@ -798,26 +798,28 @@ class HLS: segment_save_dir = save_dir / "segments" - # no resume for AES-128/ClearKey: in-place decryption at merge time makes numbered files ambiguous - # per-segment decryption rewrites each segment in place, so a segment kept from an - # earlier run would either be decrypted twice or never at all - resumable_drm = ( - not use_segment_decrypt - and not use_rolling_merge - and (session_drm is None or isinstance(session_drm, (Widevine, PlayReady))) - and not any(key and key.method == "AES-128" for key in (master.keys or [])) - ) - # media_sequence feeds AES IVs; total_segments pins the OnSegmentFilter verdict (shifts every index) - digest = resume.fingerprint( + map_data: tuple[m3u8.model.InitializationSection, bytes] | None = None + if use_segment_decrypt or use_rolling_merge: + init_section = wanted_segments[0].init_section + init_content, _ = HLS.fetch_init_section(session, init_section, 0) + map_data = (init_section, init_content) + use_segment_decrypt = use_segment_decrypt and can_use(session_drm, config.decryption, init_content) + + store = SegmentStore(track, save_dir) + store.open( track.url, [(url["url"], url["headers"].get("Range")) for url in urls], + # 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, + rolling_merge=use_rolling_merge, + drm=session_drm, + aes128=any(key and key.method == "AES-128" for key in (master.keys or [])), + merge_rewrites=True, + ), ) - if not (config.continue_downloads and resumable_drm and resume.reusable(save_dir, digest)): - shutil.rmtree(save_dir, ignore_errors=True) - segment_save_dir.mkdir(parents=True, exist_ok=True) - if config.continue_downloads and resumable_drm: - resume.write_sidecar(save_dir, digest) + segment_save_dir.mkdir(exist_ok=True) log_event( "manifest_hls_download_start", @@ -833,13 +835,7 @@ class HLS: }, ) - map_data: tuple[m3u8.model.InitializationSection, bytes] | None = None segment_decrypter: SegmentDecrypter | None = None - if use_segment_decrypt or use_rolling_merge: - init_section = wanted_segments[0].init_section - init_content, _ = HLS.fetch_init_section(session, init_section, 0) - map_data = (init_section, init_content) - use_segment_decrypt = use_segment_decrypt and can_use(session_drm, config.decryption, init_content) if use_segment_decrypt: assert isinstance(session_drm, (Widevine, PlayReady, ClearKeyCENC)) segment_decrypter = SegmentDecrypter(session_drm, init_content, save_dir.parent, ctx.max_workers) @@ -857,15 +853,11 @@ class HLS: decrypter=segment_decrypter, ) - for control_file in segment_save_dir.glob("*.!dev"): - control_file.unlink(missing_ok=True) - - # merge mutates segment files in place from here on; withdraw the reuse proof - resume.clear_sidecar(save_dir) + store.merging() if merger: check_merged(merger, total_segments, track, ctx, "HLS") - remove_segment_dir(save_dir) + store.complete() log_event( "manifest_hls_download_complete", level="DEBUG", @@ -1164,7 +1156,7 @@ class HLS: with suppress(OSError): discontinuity_file.unlink() - remove_segment_dir(save_dir) + store.complete() progress(downloaded="Downloaded", completed=100, total=100) diff --git a/unshackle/core/manifests/ism.py b/unshackle/core/manifests/ism.py index 5c4d58e1..543e9281 100644 --- a/unshackle/core/manifests/ism.py +++ b/unshackle/core/manifests/ism.py @@ -37,7 +37,8 @@ from unshackle.core.manifests.segment_pipeline import ( license_drm, ) from unshackle.core.session import RnetSession -from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video, resume +from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video +from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore 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 @@ -426,15 +427,10 @@ class ISM: progress(total=len(segments)) use_rolling_merge = config.merge_segments and not isinstance(track, Subtitle) - can_resume = config.continue_downloads and not use_rolling_merge assert isinstance(track.url, str) - digest = resume.fingerprint(track.url, [(url, None) for url in segments]) - if not (can_resume and resume.reusable(save_dir, digest)): - shutil.rmtree(save_dir, ignore_errors=True) - save_dir.mkdir(parents=True, exist_ok=True) - if can_resume: - resume.write_sidecar(save_dir, digest) + store = SegmentStore(track, save_dir) + store.open(track.url, [(url, None) for url in segments], mode=DownloadMode(rolling_merge=use_rolling_merge)) log_event( "manifest_ism_download_start", @@ -496,8 +492,7 @@ class ISM: ) raise FileNotFoundError(error_msg) - for control_file in save_dir.glob("*.!dev"): - control_file.unlink(missing_ok=True) + store.merging() if merger: check_merged(merger, len(segments), track, ctx, "ISM") diff --git a/unshackle/core/manifests/segment_pipeline.py b/unshackle/core/manifests/segment_pipeline.py index d4660850..5edc81c2 100644 --- a/unshackle/core/manifests/segment_pipeline.py +++ b/unshackle/core/manifests/segment_pipeline.py @@ -22,7 +22,8 @@ from unshackle.core.drm.verify import decrypt_track 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, resume +from unshackle.core.tracks import DownloadContext, Track +from unshackle.core.tracks.segment_store import SegmentStore from unshackle.core.tracks.track import assert_fragments_decrypted from unshackle.core.utilities import log_event, try_ensure_utf8 @@ -243,15 +244,6 @@ def decrypt_output(track: AnyTrack, ctx: DownloadContext, drm: DRM_T, decrypt: b events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=None) -def remove_segment_dir(save_dir: Path) -> None: - """Remove the segment directory, also when a superseded hedge download still dropped a .!dev file in it.""" - if save_dir.exists() and save_dir.name.endswith("_segments"): - try: - save_dir.rmdir() - except OSError: - shutil.rmtree(save_dir, ignore_errors=True) - - def complete_track(track: AnyTrack, ctx: DownloadContext, drm: DRM_T | None, decrypt: bool = True) -> None: """Hand the merged file to the track, decrypt it, and remove the segment directory.""" track.path = ctx.save_path @@ -260,8 +252,7 @@ def complete_track(track: AnyTrack, ctx: DownloadContext, drm: DRM_T | None, dec decrypt_output(track, ctx, drm, decrypt) ctx.progress(downloaded="Decrypted", completed=100, total=100) - remove_segment_dir(ctx.save_dir) - resume.clear_sidecar(ctx.save_dir) + SegmentStore(track, ctx.save_dir).complete() ctx.progress(downloaded="Downloaded") @@ -274,5 +265,4 @@ __all__ = ( "fetch_segments", "license_drm", "licensing", - "remove_segment_dir", ) diff --git a/unshackle/core/temp.py b/unshackle/core/temp.py index e7452911..ef580154 100644 --- a/unshackle/core/temp.py +++ b/unshackle/core/temp.py @@ -1,9 +1,7 @@ from __future__ import annotations -import contextlib import functools import logging -import os import shutil import time import uuid @@ -85,57 +83,6 @@ def resume_stash() -> Path | None: return None if root == config.directories.temp else root / RESUME_STASH -def _move_with_sidecar(source: Path, target: Path) -> bool: - """Rename a segment dir, then its resume sidecar. False if the dir rename fails; a sidecar failure only logs.""" - from unshackle.core.tracks import resume - - try: - source.rename(target) - except OSError as e: - log.debug("Could not move %s: %s", source, e) - return False - sidecar = resume.sidecar_path(source) - try: - if sidecar.exists(): - sidecar.replace(resume.sidecar_path(target)) - except OSError as e: - log.debug("Could not move %s: %s", sidecar, e) - return True - - -def stash_segments(save_dir: Path) -> None: - """Move save_dir and its resume sidecar into the stash. Leave them in place on any OS error.""" - from unshackle.core.tracks import resume - - stash = resume_stash() - if stash is None or not save_dir.is_dir(): - return - target = stash / save_dir.name - try: - stash.mkdir(parents=True, exist_ok=True) - if target.exists(): - return - except OSError as e: - log.debug("Could not stash %s: %s", save_dir, e) - return - if _move_with_sidecar(save_dir, target): - # rename keeps the old mtime, and the sweep ages entries by it - for path in (target, resume.sidecar_path(target)): - with contextlib.suppress(OSError): - os.utime(path) - - -def restore_segments(save_dir: Path) -> None: - """Move a stashed save_dir and its sidecar back to save_dir, if the stash has them and save_dir is free.""" - stash = resume_stash() - if stash is None: - return - source = stash / save_dir.name - if source.is_symlink() or not source.is_dir() or save_dir.exists(): - return - _move_with_sidecar(source, save_dir) - - @contextmanager def task_temp_dir(task_id: str | None = None) -> Iterator[Path]: """Point config.directories.temp at a private dir for this task. Remove it on any exit.""" diff --git a/unshackle/core/tracks/resume.py b/unshackle/core/tracks/resume.py deleted file mode 100644 index 445292aa..00000000 --- a/unshackle/core/tracks/resume.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Cross-run segment-resume sidecars. - -A later download can reuse a track's completed segment files, but only after -the manifest proves that the segmentation did not change. The proof is a fingerprint -of the segmentation stored in a JSON sidecar next to the segment directory. - -The sidecar is deliberately a sibling of the segment directory, never a file -inside it: the manifest parsers merge by globbing the directory with no -extension filter, so they would concatenate any file left in there into the -final output. -""" - -from __future__ import annotations - -import hashlib -import json -from collections.abc import Sequence -from pathlib import Path -from urllib.parse import urlsplit, urlunsplit - -_VERSION = 1 - - -def sidecar_path(save_dir: Path) -> Path: - """Path of the resume sidecar for save_dir (always a sibling, see module docstring).""" - return save_dir.with_name(save_dir.name + ".resume.json") - - -def _strip_url(url: str | None) -> str: - """Drop query and fragment: auth tokens rotate between runs and would make every digest unique.""" - if not url: - return "" - scheme, netloc, path, _, _ = urlsplit(url) - return urlunsplit((scheme, netloc, path, "", "")) - - -def fingerprint( - manifest_url: str | None, - segments: Sequence[tuple[str, str | None]], - extra: Sequence[str] = (), -) -> str: - """Stable digest of a track's segmentation. - - Hashes the manifest URL (sans query), the segment count, and each - segment's URL (sans query) with its byte-range string verbatim. Byte - ranges are the strongest identity signal available and never carry - tokens. extra carries protocol-specific identity inputs (HLS: the - media_sequence start and post-filter segment count). - """ - stripped = [[_strip_url(url), byte_range or ""] for url, byte_range in segments] - if len({tuple(pair) for pair in stripped}) != len(stripped): - stripped = [[url, byte_range or ""] for url, byte_range in segments] - payload = { - "version": _VERSION, - "manifest": _strip_url(manifest_url), - "count": len(segments), - "segments": stripped, - "extra": list(extra), - } - canonical = json.dumps(payload, separators=(",", ":"), sort_keys=True) - return hashlib.sha256(canonical.encode("utf-8")).hexdigest() - - -def reusable(save_dir: Path, digest: str) -> bool: - """True when save_dir's sidecar records this exact digest. - - Never raises: a missing, unreadable, or malformed sidecar means "cannot - prove reuse is safe", which means restart clean. - """ - try: - data = json.loads(sidecar_path(save_dir).read_text(encoding="utf-8")) - return bool(data.get("digest")) and data["digest"] == digest - except (OSError, ValueError): - return False - - -def write_sidecar(save_dir: Path, digest: str) -> None: - """Record digest so a later download can prove that save_dir's segments are reusable.""" - sidecar_path(save_dir).write_text(json.dumps({"version": _VERSION, "digest": digest}), encoding="utf-8") - - -def clear_sidecar(save_dir: Path) -> None: - """Withdraw the reuse proof (merge is about to mutate files, or the track completed).""" - sidecar_path(save_dir).unlink(missing_ok=True) diff --git a/unshackle/core/tracks/segment_store.py b/unshackle/core/tracks/segment_store.py new file mode 100644 index 00000000..eb48646c --- /dev/null +++ b/unshackle/core/tracks/segment_store.py @@ -0,0 +1,253 @@ +"""The segment store: the segment directory of one segmented track, from restore to removal. + +A later run can reuse the completed segment files of a track only after the manifest proves that the +segmentation did not change. The proof is a digest of the segmentation, kept in a JSON sidecar beside the +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. + +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 and complete() after the +merge. A DASH track collapsed to one ranged download never opens the store: it makes no segment files. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import json +import logging +import os +import shutil +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING +from urllib.parse import urlsplit, urlunsplit + +from unshackle.core.config import config +from unshackle.core.drm import DRM_T, PlayReady, Widevine +from unshackle.core.temp import resume_stash + +if TYPE_CHECKING: + from unshackle.core.tracks.track import Track + +_VERSION = 1 + +log = logging.getLogger("track") + + +@dataclass(frozen=True) +class DownloadMode: + """The final download mode of a track: what the resume verdict reads.""" + + segment_decrypt: bool = False + rolling_merge: bool = False + drm: DRM_T | None = None + aes128: bool = False + merge_rewrites: bool = False + """The merge rewrites segment files in place before it reads them.""" + + +def _strip_url(url: str | None) -> str: + """Drop query and fragment: auth tokens rotate between runs and would make every digest unique.""" + if not url: + return "" + scheme, netloc, path, _, _ = urlsplit(url) + return urlunsplit((scheme, netloc, path, "", "")) + + +def fingerprint( + manifest_url: str | None, + segments: Sequence[tuple[str, str | None]], + extra: Sequence[str] = (), +) -> str: + """Stable digest of the segmentation of a track. + + Hashes the manifest URL and each segment URL without their query, the segment count, and each byte + range as it is. When the stripped URLs are not unique, the query is the only identity and is kept. + extra carries identity inputs of one protocol. + """ + stripped = [[_strip_url(url), byte_range or ""] for url, byte_range in segments] + if len({tuple(pair) for pair in stripped}) != len(stripped): + stripped = [[url, byte_range or ""] for url, byte_range in segments] + payload = { + "version": _VERSION, + "manifest": _strip_url(manifest_url), + "count": len(segments), + "segments": stripped, + "extra": list(extra), + } + canonical = json.dumps(payload, separators=(",", ":"), sort_keys=True) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +def _sidecar(save_dir: Path) -> Path: + return save_dir.with_name(save_dir.name + ".resume.json") + + +class SegmentStore: + """The segment directory of one track, its resume sidecar and its stash entry.""" + + def __init__(self, track: Track, save_dir: Path) -> None: + self.track = track + self.save_dir = save_dir + self.mode = DownloadMode() + + @property + def sidecar(self) -> Path: + return _sidecar(self.save_dir) + + @property + def keeps(self) -> bool: + """True when a failed download keeps its completed segments for the next run.""" + return config.continue_downloads and self._owned + + 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. + """ + if not self.keeps or mode.segment_decrypt or mode.rolling_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))) + return True + + def open( + self, + manifest_url: str | None, + segments: Sequence[tuple[str, str | None]], + extra: Sequence[str] = (), + *, + mode: DownloadMode, + ) -> bool: + """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. + """ + self.mode = mode + resumable = self.resumable(mode) + digest = fingerprint(manifest_url, segments, extra) + reused = resumable and self._recorded_digest() == digest + if not reused: + 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) + return reused + + def merging(self) -> None: + """End the download phase: remove the .!dev files that superseded downloads left, so no merge reads one. + + When the merge rewrites segments in place (every HLS merge, the WebVTT rebase of a multi-period DASH + subtitle), the sidecar goes now. Any other merge only reads and deletes segments, so a merge that fails + leaves segments that are still good. + """ + if self.save_dir.is_dir(): + for control_file in self.save_dir.rglob("*.!dev"): + control_file.unlink(missing_ok=True) + if self.mode.merge_rewrites: + self.sidecar.unlink(missing_ok=True) + + def complete(self) -> None: + """Remove the directory and its sidecar after the merge, also when a superseded download left a file.""" + if self._owned: + shutil.rmtree(self.save_dir, ignore_errors=True) + self.sidecar.unlink(missing_ok=True) + + 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. + """ + if self.keeps: + self._unstash() + self._sweep() + + def abandon(self) -> None: + """Clean up a failed or cancelled download and stash the directory when it keeps its segments. + + The downloader does not wait for its workers on failure, so on Windows one can still hold a .!dev file + open (WinError 32). A cleanup error must not replace the error of the download. + """ + with contextlib.suppress(OSError): + self._sweep() + if self.keeps: + self._stash() + + @property + def _owned(self) -> bool: + """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.""" + try: + data = json.loads(self.sidecar.read_text(encoding="utf-8")) + return data.get("digest") or None + except (OSError, ValueError, AttributeError): + return None + + def _sweep(self) -> None: + """Keep only completed segments and the sidecar when the directory is kept, else remove both.""" + if not self._owned: + return + if self.keeps: + if self.save_dir.exists(): + for partial in self.save_dir.rglob("*.!dev"): + partial.with_name(partial.name.removesuffix(".!dev")).unlink(missing_ok=True) + partial.unlink(missing_ok=True) + else: + if self.save_dir.exists(): + shutil.rmtree(self.save_dir) + self.sidecar.unlink(missing_ok=True) + + def _move(self, target: Path) -> bool: + """Rename the directory, then its sidecar. False if the directory rename fails; a sidecar 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 False + try: + if self.sidecar.exists(): + self.sidecar.replace(_sidecar(target)) + except OSError as e: + log.debug("Could not move %s: %s", self.sidecar, e) + return True + + def _stash(self) -> None: + """Move the directory and its sidecar into the stash. Leave them in place on any OS error.""" + stash = resume_stash() + if stash is None or not self.save_dir.is_dir(): + return + target = stash / self.save_dir.name + try: + stash.mkdir(parents=True, exist_ok=True) + if target.exists(): + return + except OSError as e: + log.debug("Could not stash %s: %s", self.save_dir, e) + return + if self._move(target): + # rename keeps the old mtime, and the stash sweep ages entries by it + for path in (target, _sidecar(target)): + with contextlib.suppress(OSError): + os.utime(path) + + def _unstash(self) -> None: + """Move a stashed directory and its sidecar back, if the stash has them and the directory is free.""" + stash = resume_stash() + if stash is None: + 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) diff --git a/unshackle/core/tracks/track.py b/unshackle/core/tracks/track.py index 3f5ca831..f81112a5 100644 --- a/unshackle/core/tracks/track.py +++ b/unshackle/core/tracks/track.py @@ -40,8 +40,7 @@ from unshackle.core.drm.verify import ( ) from unshackle.core.events import events from unshackle.core.session import MAX_BACKOFF, AnySession, RnetSession, unrecorded, utf8_text -from unshackle.core.temp import restore_segments, stash_segments -from unshackle.core.tracks import resume +from unshackle.core.tracks.segment_store import SegmentStore from unshackle.core.utilities import language_name, log_event, try_ensure_utf8 from unshackle.core.utils import run_proxy from unshackle.core.utils.subprocess import run_tool @@ -774,31 +773,13 @@ class Track: else: save_dir = save_path.parent - keep_segments = config.continue_downloads and self.descriptor != self.Descriptor.URL - - def cleanup() -> None: - save_path.unlink(missing_ok=True) - if save_dir.name.endswith("_segments"): - if keep_segments: - if save_dir.exists(): - for partial in save_dir.rglob("*.!dev"): - partial.with_name(partial.name.removesuffix(".!dev")).unlink(missing_ok=True) - partial.unlink(missing_ok=True) - else: - if save_dir.exists(): - shutil.rmtree(save_dir) - resume.clear_sidecar(save_dir) + store = SegmentStore(self, save_dir) def abandon() -> None: - """Clean up a failed or cancelled download and stash its segments when resume is on. - - The downloader does not wait for its workers on failure, so on Windows one can still hold a - .!dev file open (WinError 32). A cleanup error must not replace the download's own error. - """ + """Remove the output of a failed or cancelled download; a cleanup error must not replace its error.""" with contextlib.suppress(OSError): - cleanup() - if keep_segments: - stash_segments(save_dir) + save_path.unlink(missing_ok=True) + store.abandon() if not DOWNLOAD_LICENCE_ONLY.is_set(): if config.directories.temp.is_file(): @@ -806,11 +787,8 @@ class Track: config.directories.temp.mkdir(parents=True, exist_ok=True) - # completed segments are reusable once the parser proves the segmentation - # unchanged (resume sidecar); partial .!dev files never survive a run boundary - if keep_segments: - restore_segments(save_dir) - cleanup() + save_path.unlink(missing_ok=True) + store.restore() try: manifest_parsers: dict[Track.Descriptor, type[DASH] | type[HLS] | type[ISM]] = {