diff --git a/docs/reference/configuration/download.md b/docs/reference/configuration/download.md index 58f65dd4..6345bfec 100644 --- a/docs/reference/configuration/download.md +++ b/docs/reference/configuration/download.md @@ -132,8 +132,10 @@ 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, and so does - a failure of a multi-period DASH WebVTT subtitle during its merge step. + restarts. An HLS failure after the post-download merge step starts to join or decrypt + segments also restarts, and so does a failure of a multi-period DASH WebVTT subtitle + 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. diff --git a/tests/core/test_resume_across_runs.py b/tests/core/test_resume_across_runs.py index aa28abf6..fd240fb7 100644 --- a/tests/core/test_resume_across_runs.py +++ b/tests/core/test_resume_across_runs.py @@ -140,7 +140,7 @@ def test_existing_stash_target_is_left_alone(temp_root, monkeypatch): target.mkdir(parents=True) (target / "old.mp4").write_bytes(b"old") save_dir = task_dir / SEG_NAME - save_dir.mkdir() + open_store(save_dir) (save_dir / "new.mp4").write_bytes(b"new") store(save_dir).abandon() @@ -168,7 +168,7 @@ def test_restore_is_a_noop_without_stash_or_with_present_dir(temp_root, monkeypa assert not (save_dir / "a.mp4").exists() -def test_rename_failure_never_replaces_download_error(temp_root, monkeypatch): +def test_move_failure_never_replaces_download_error(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) def deny(self, target): @@ -176,6 +176,7 @@ def test_rename_failure_never_replaces_download_error(temp_root, monkeypatch): with task_temp_dir(): monkeypatch.setattr(Path, "rename", deny) + monkeypatch.setattr(Path, "replace", deny) with pytest.raises(RuntimeError, match="simulated crash"): run_download(monkeypatch, failing_parser) @@ -278,3 +279,49 @@ def test_stash_refreshes_mtime(temp_root, monkeypatch): target = temp_root / RESUME_STASH / SEG_NAME assert time.time() - target.stat().st_mtime < 60 + + +def test_a_partial_still_open_does_not_block_the_stash(temp_root, monkeypatch): + """On Windows a worker that still writes a partial file after the failure blocks the rename of its directory. + + The directory patches emulate that, so a stash that renames the directory finds nothing stashed. + """ + monkeypatch.setattr(config, "continue_downloads", True) + rename, replace, unlink = Path.rename, Path.replace, Path.unlink + + def refuse_dir(move): + def windows(self, target): + if self.is_dir(): + raise PermissionError(5, "Access is denied", str(self)) + return move(self, target) + + return windows + + def locked(self, missing_ok=False): + if self.name.endswith(".!dev"): + raise PermissionError(32, "being used by another process", str(self)) + unlink(self, missing_ok=missing_ok) + + with task_temp_dir(), pytest.MonkeyPatch.context() as windows_fs: + windows_fs.setattr(Path, "rename", refuse_dir(rename)) + windows_fs.setattr(Path, "replace", refuse_dir(replace)) + windows_fs.setattr(Path, "unlink", locked) + with pytest.raises(RuntimeError): + run_download(monkeypatch, failing_parser) + + stashed = temp_root / RESUME_STASH / SEG_NAME + assert store(stashed).sidecar.exists() + assert not list(stashed.rglob("*.!dev")) + + seen = {} + + def second_parser(track, ctx): + seen["bytes"] = (ctx.save_dir / "0.mp4").read_bytes() + seen["reused"] = 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 == {"bytes": b"complete segment", "reused": True} diff --git a/tests/core/test_segment_store.py b/tests/core/test_segment_store.py index 4800fe25..39a94307 100644 --- a/tests/core/test_segment_store.py +++ b/tests/core/test_segment_store.py @@ -6,12 +6,14 @@ from __future__ import annotations import importlib import json import shutil +from collections import Counter from pathlib import Path from uuid import UUID import pytest import requests +from tests.core.test_hls_kid_from_init import KEY_LINE, no_kid_pssh 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 @@ -23,6 +25,7 @@ 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.temp import RESUME_STASH, task_temp_dir from unshackle.core.tracks import Video from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore, fingerprint @@ -261,3 +264,103 @@ def test_hls_resumes_when_the_init_turns_segment_decryption_off(server, tmp_path 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:]) + + +class Routes(dict): + """Server routes that count the requests for each path and fail them from a given request on.""" + + def __init__(self, routes: dict[str, bytes]) -> None: + super().__init__(routes) + self.hits: Counter[str] = Counter() + self.fail_from: dict[str, int] = {} + + def get(self, path, default=None): + self.hits[path] += 1 + if path in self.fail_from and self.hits[path] >= self.fail_from[path]: + return default + return super().get(path, default) + + +@pytest.mark.parametrize("encrypted", [False, True], ids=["clear", "widevine"]) +def test_hls_resumes_after_a_failure_in_the_merge(server, tmp_path, monkeypatch, one_attempt, encrypted): + """The init fetch of the merge fails after every segment landed: the next run reuses all of them.""" + no_decrypt(monkeypatch) + + def make(): + track = hls_track(server, False) + track.drm = [widevine()] if encrypted else [] + return track + + ctx = make_ctx(tmp_path, "hls.mp4") + ctx.license_widevine = lambda *a, **kw: None + + output = two_runs(server, ctx, HLS, make, "/init.mp4", ctx.save_dir / "segments" / "1.m4s") + + assert output == INIT + PARTS[0] + b"\xee" * 10 + b"".join(PARTS[2:]) + + +def test_hls_never_reuses_segments_after_the_merge_rewrote_them(server, tmp_path, monkeypatch, one_attempt): + """A failure after the first discontinuity merge leaves no sidecar, so the next run downloads every segment.""" + server.routes = Routes(server.routes) + ctx = make_ctx(tmp_path, "hls.mp4") + server.routes.fail_from["/init.mp4"] = 2 + with pytest.raises(requests.HTTPError): + HLS.download_track(hls_track(server, True), ctx) + assert not SegmentStore(hls_track(server, True), ctx.save_dir).sidecar.exists() + + server.routes.fail_from.clear() + server.routes.hits.clear() + DOWNLOAD_CANCELLED.clear() + HLS.download_track(hls_track(server, True), ctx) + + assert ctx.save_path.read_bytes().endswith(INIT + b"".join(PARTS[2:])) + assert all(server.routes.hits[f"/part{i}.m4s"] == 1 for i in range(len(PARTS))) + + +def test_hls_never_reuses_segments_after_a_key_change_merged_them(server, tmp_path, monkeypatch, one_attempt): + """The licence of a later key fails after the merge joined the first key range: the next run starts clean.""" + no_decrypt(monkeypatch) + server.routes = Routes(server.routes) + + def make(): + track = hls_track(server, False) + lines = ["#EXTM3U", "#EXT-X-VERSION:7", "#EXT-X-TARGETDURATION:4", '#EXT-X-MAP:URI="init.mp4"'] + for i in range(len(PARTS)): + if i in (0, 2): + lines.append(KEY_LINE.format(pssh=no_kid_pssh(bytes([i])))) + lines += ["#EXTINF:4.0,", f"part{i}.m4s"] + server.routes["/media.m3u8"] = "\n".join(lines + ["#EXT-X-ENDLIST"]).encode() + monkeypatch.setattr(type(track), "get_key_id", lambda self, *a, **kw: KID) + return track + + licences: list[object] = [] + + def licence(drm, **kw): + licences.append(drm) + if len(licences) == 2: + raise PermissionError("EXAMPLE licence refused") + + ctx = make_ctx(tmp_path, "hls.mp4") + ctx.license_widevine = licence + with pytest.raises(PermissionError): + HLS.download_track(make(), ctx) + assert not SegmentStore(make(), ctx.save_dir).sidecar.exists() + + server.routes.hits.clear() + DOWNLOAD_CANCELLED.clear() + HLS.download_track(make(), ctx) + + assert all(server.routes.hits[f"/part{i}.m4s"] == 1 for i in range(len(PARTS))) + + +def test_abandon_drops_a_directory_without_a_sidecar(tmp_path, keep, monkeypatch): + monkeypatch.setattr(config.directories, "temp", tmp_path) + with task_temp_dir() as task_dir: + store = SegmentStore(make_track(), task_dir / "Video_x.mp4_segments") + store.save_dir.mkdir() + (store.save_dir / "0.mp4").write_bytes(b"segment") + + store.abandon() + + assert not store.save_dir.exists() + assert not (tmp_path / RESUME_STASH).exists() diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py index a01d1ec9..8f0f4b5f 100644 --- a/unshackle/core/manifests/hls.py +++ b/unshackle/core/manifests/hls.py @@ -816,7 +816,6 @@ class HLS: 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, ), ) segment_save_dir.mkdir(exist_ok=True) @@ -899,6 +898,7 @@ class HLS: delete: Delete each source file after this function merges it. include_map_data: Whether to include the init map data. """ + store.rewriting() prepend = include_map_data and map_data and map_data[1] if len(via) == 1 and not prepend and delete: try: @@ -974,6 +974,7 @@ class HLS: # AES segments must be decrypted individually before merging: each segment # likely carries its own 16-byte padding key_obj = encryption_data[0] + store.rewriting() # AES-128 with no explicit IV: each segment's IV is its media sequence # number (RFC 8216 ยง5.2). Without this the engine used a zero IV and the # output decrypted to garbage. @@ -1040,6 +1041,7 @@ class HLS: .encode("utf8") ) if segment_data != original_data: + store.rewriting() segment_file_path.write_bytes(segment_data) if segment.discontinuity and i != 0: diff --git a/unshackle/core/tracks/segment_store.py b/unshackle/core/tracks/segment_store.py index eb48646c..1eafa7b0 100644 --- a/unshackle/core/tracks/segment_store.py +++ b/unshackle/core/tracks/segment_store.py @@ -6,8 +6,9 @@ directory. The sidecar is never a file inside the directory: the parsers merge b 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. +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 +never opens the store: it makes no segment files. """ from __future__ import annotations @@ -146,15 +147,23 @@ class SegmentStore: 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. + 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 + 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) + self.rewriting() + + def rewriting(self) -> None: + """Withdraw the sidecar before the merge rewrites a segment in place, so no later run reuses a rewritten one. + + Call it before every in-place write. Until then the merge only reads segments, so a merge step that fails + (an init fetch, a licence) keeps them. + """ + 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.""" @@ -165,22 +174,26 @@ 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() - self._sweep() + self._sweep(self.keeps) def abandon(self) -> None: - """Clean up a failed or cancelled download and stash the directory when it keeps its segments. + """Clean up a failed or cancelled download and stash the directory when a later run can use it. - 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. + A directory without a sidecar goes: the next run would wipe it. 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. """ + keep = self.keeps and self.sidecar.exists() with contextlib.suppress(OSError): - self._sweep() - if self.keeps: - self._stash() + self._sweep(keep) + if keep: + with contextlib.suppress(OSError): + self._stash() @property def _owned(self) -> bool: @@ -195,11 +208,11 @@ class SegmentStore: 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.""" + def _sweep(self, keep: bool) -> None: + """Keep only completed segments and the sidecar when keep is set, else remove both.""" if not self._owned: return - if self.keeps: + if keep: if self.save_dir.exists(): for partial in self.save_dir.rglob("*.!dev"): partial.with_name(partial.name.removesuffix(".!dev")).unlink(missing_ok=True) @@ -209,38 +222,45 @@ class SegmentStore: 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.""" + 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 False + 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) - return True def _stash(self) -> None: - """Move the directory and its sidecar into the stash. Leave them in place on any OS error.""" + """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. + """ 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) + if target.exists(): 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) + 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) def _unstash(self) -> None: """Move a stashed directory and its sidecar back, if the stash has them and the directory is free."""