fix(tracks): keep segment resume across an hls merge failure and a locked partial on windows

This commit is contained in:
imSp4rky
2026-11-28 20:26:40 -07:00
parent 37357673fe
commit 74fa29b6f1
5 changed files with 212 additions and 38 deletions
+3 -1
View File
@@ -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:
+53 -33
View File
@@ -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."""