diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md
index 319162f7..9c4a8959 100644
--- a/docs/guide/troubleshooting.md
+++ b/docs/guide/troubleshooting.md
@@ -311,6 +311,8 @@ Each command reports how many files it removed and how much space it freed, then
!!! example "The temp directory is nearly full"
**Symptom:** the failure line ends with the free space of the temp volume, for example `CalledProcessError: Command '[...]' returned non-zero exit status 2, 38.0 MB free on C:\unshackle\temp`. A tool such as shaka-packager often reports a full disk only as a write failure.
+ Before the track downloads start, a warning can also show the problem, for example `Temp volume C:\unshackle\temp has 3.1 GB free, the selected tracks need about 9.4 GB`. unshackle gives this warning when the free space is less than two times the estimated size of the video and audio tracks of the title. The factor is two because each encrypted track and its decrypted copy are on the temp volume together. The estimate is the manifest bitrate multiplied by the playing time, so only DASH and ISM tracks get it: an HLS or URL track gives no warning. The warning does not stop the download, and `--skip-dl` and `--sample` runs do not check.
+
**Inspect:** unshackle adds this part when the volume of `directories.temp` has less than 1 GiB free. Make space on that volume, or set `directories.temp` to a larger volume (see [Directories](../reference/configuration/directories.md)), and run the download again. Over the REST API the job error carries the same line, and a full disk in the downloader gives `DOWNLOAD_ERROR`.
!!! example "The wrong titles/metadata keep coming back"
diff --git a/tests/commands/test_disk_preflight.py b/tests/commands/test_disk_preflight.py
new file mode 100644
index 00000000..953c39c0
--- /dev/null
+++ b/tests/commands/test_disk_preflight.py
@@ -0,0 +1,150 @@
+"""The free-space preflight warns before the downloads when the temp volume cannot hold a title's tracks."""
+
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from tests.lang_selection import test_kind_only_selection as harness
+from unshackle.commands import dl as dl_module
+from unshackle.commands.dl import low_disk_warning
+from unshackle.core.config import config
+from unshackle.core.manifests import DASH, HLS, ISM
+from unshackle.core.tracks import Tracks
+from unshackle.core.utils.bitrate import manifest_seconds
+
+GB = 1_000_000_000
+
+
+def mpd(periods: str, total: str = "PT1H") -> str:
+ return (
+ f'{periods}'
+ )
+
+
+def period(attrs: str = "") -> str:
+ return (
+ f""
+ ''
+ ''
+ ''
+ ""
+ ''
+ ''
+ ''
+ ""
+ ""
+ )
+
+
+def dash_tracks(manifest: str) -> Tracks:
+ return DASH.from_text(manifest, "https://cdn.example/x.mpd").to_tracks("en")
+
+
+@pytest.fixture
+def free_space(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> list[int]:
+ """Report the bytes in the returned list as the free space of the temp volume."""
+ monkeypatch.setattr(config.directories, "temp", tmp_path)
+ free = [100 * GB]
+
+ monkeypatch.setattr(dl_module.shutil, "disk_usage", lambda path: SimpleNamespace(free=free[0]))
+ return free
+
+
+def test_a_temp_volume_too_small_for_twice_the_tracks_gets_one_warning_line(
+ free_space: list[int], tmp_path: Path
+) -> None:
+ free_space[0] = 3_100_000_000
+
+ line = low_disk_warning(dash_tracks(mpd(period())))
+
+ assert line == f"Temp volume {tmp_path} has 3.1 GB free, the selected tracks need about 15.0 GB"
+
+
+def test_enough_free_space_gives_no_warning(free_space: list[int]) -> None:
+ free_space[0] = 15 * GB
+
+ assert low_disk_warning(dash_tracks(mpd(period()))) is None
+
+
+def test_hls_tracks_have_no_estimate_and_read_no_disk(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(dl_module.shutil, "disk_usage", lambda path: pytest.fail("read the disk"))
+ master = '#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=16000000,RESOLUTION=3840x2160,CODECS="hvc1.2.4.L153"\nv.m3u8\n'
+
+ tracks = HLS.from_text(master, "https://cdn.example/x.m3u8").to_tracks("en")
+
+ assert tracks.videos and manifest_seconds(tracks.videos[0]) is None
+ assert low_disk_warning(tracks) is None
+
+
+def test_a_dash_track_counts_only_its_content_periods() -> None:
+ manifest = mpd(period('id="ad" duration="PT10M"') + period('id="main" duration="PT50M"'))
+ track = DASH.from_text(manifest, "https://cdn.example/x.mpd").to_tracks("en").videos[0]
+ track.data["dash"]["filtered_period_ids"] = ["ad"]
+
+ assert manifest_seconds(track) == 3000
+
+
+def test_a_dash_track_skips_a_period_that_does_not_carry_it() -> None:
+ other = period('id="b" duration="PT30M"').replace('width="3840" height="2160"', 'width="1920" height="1080"')
+ manifest = mpd(period('id="a" duration="PT30M"') + other)
+ video = dash_tracks(manifest).videos[0]
+
+ assert video.height == 2160
+ assert manifest_seconds(video) == 1800
+
+
+def test_a_duration_the_parser_cannot_read_gives_no_warning(free_space: list[int]) -> None:
+ free_space[0] = 0
+
+ assert low_disk_warning(dash_tracks(mpd(period(), total="P0DT1H"))) is None
+
+
+def test_a_dash_period_of_unknown_length_takes_the_presentation_length() -> None:
+ manifest = mpd(period('id="a"') + period('id="b"'), total="PT1H")
+
+ assert manifest_seconds(dash_tracks(manifest).videos[0]) == 3600
+
+
+def test_a_dash_manifest_with_no_length_gives_no_estimate() -> None:
+ manifest = '' + period() + ""
+
+ assert manifest_seconds(dash_tracks(manifest).videos[0]) is None
+
+
+def test_an_ism_track_takes_the_manifest_duration() -> None:
+ manifest = (
+ ''
+ ''
+ ''
+ ''
+ ""
+ )
+
+ video = ISM.from_text(manifest, url="https://cdn.example/x/manifest").to_tracks(language="en").videos[0]
+
+ assert manifest_seconds(video) == 3600
+
+
+def test_an_unreadable_temp_volume_gives_no_warning(free_space: list[int], monkeypatch: pytest.MonkeyPatch) -> None:
+ def broken(path: Any) -> Any:
+ raise PermissionError(13, "Access is denied")
+
+ monkeypatch.setattr(dl_module.shutil, "disk_usage", broken)
+
+ assert low_disk_warning(dash_tracks(mpd(period()))) is None
+
+
+def test_dl_logs_the_warning_once_per_title_and_not_with_skip_dl(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ monkeypatch.setattr(dl_module, "low_disk_warning", lambda tracks: "Temp volume is short")
+
+ harness.run(monkeypatch, caplog, {1: {}, 2: {}}, to_end=True, no_mux=True)
+ assert caplog.text.count("Temp volume is short") == 2
+
+ caplog.clear()
+ harness.run(monkeypatch, caplog, {1: {}}, to_end=True, skip_dl=True)
+ assert "Temp volume is short" not in caplog.text
diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py
index 6764a2c5..90f6a895 100644
--- a/unshackle/commands/dl.py
+++ b/unshackle/commands/dl.py
@@ -104,7 +104,7 @@ from unshackle.core.utilities import (
time_elapsed_since,
)
from unshackle.core.utils import tags
-from unshackle.core.utils.bitrate import apply_real_bitrates
+from unshackle.core.utils.bitrate import apply_real_bitrates, manifest_seconds
from unshackle.core.utils.click_types import (
AUDIO_CODEC_LIST,
LANGUAGE_RANGE,
@@ -393,6 +393,36 @@ def low_free_space(e: BaseException) -> str:
return note
+DISK_NEED_FACTOR = 2
+"""Times its estimated track size that a title needs on the temp volume: each encrypted track and its decrypted copy."""
+
+
+def low_disk_warning(tracks: Tracks) -> str | None:
+ """The warning line when the temp volume has less free space than a title's video and audio need, else None.
+
+ The size of a track is its manifest bitrate times its playing time; a track without both counts as 0 bytes.
+ Any error gives None, because the check only advises and must never stop a download.
+ """
+ playable: list[Video | Audio] = [*tracks.videos, *tracks.audio]
+ temp = temp_root()
+ try:
+ size = sum(
+ track.bitrate * seconds / 8 for track in playable if track.bitrate and (seconds := manifest_seconds(track))
+ )
+ if not size:
+ return None
+ need = int(size * DISK_NEED_FACTOR)
+ free = shutil.disk_usage(temp).free
+ except Exception as e:
+ logging.getLogger("download").debug(f"Free-space check skipped: {e!r}")
+ return None
+ if free >= need:
+ return None
+ return (
+ f"Temp volume {temp} has {filesize.decimal(free)} free, the selected tracks need about {filesize.decimal(need)}"
+ )
+
+
class dl:
def find_custom_font(self, font_name: str) -> Path | None:
"""
@@ -2165,6 +2195,9 @@ class dl:
f"{self.service} gives each one as one file with no segment index."
)
+ if not skip_dl and not sample and (disk_warning := low_disk_warning(title.tracks)):
+ self.log.warning(disk_warning)
+
dl_start_time = time.time()
try:
diff --git a/unshackle/core/utils/bitrate.py b/unshackle/core/utils/bitrate.py
index 706d29c4..095219d9 100644
--- a/unshackle/core/utils/bitrate.py
+++ b/unshackle/core/utils/bitrate.py
@@ -274,6 +274,33 @@ def uniform_segments(
return [Segment(url, byte_range, range_size(byte_range), per_segment) for url, byte_range in raw_segments]
+def manifest_seconds(track: Track) -> float | None:
+ """The playing time of a DASH or ISM track from the manifest it holds, else None; it sends no request.
+
+ A DASH track counts the content periods that carry its Representation, else the whole presentation.
+ """
+ from unshackle.core.manifests import DASH
+
+ if (dash := track.data.get("dash")) and (manifest := dash.get("manifest")) is not None:
+ filtered = dash.get("filtered_period_ids", [])
+ rep_id = dash.get("representation_id") or dash["representation"].get("id")
+ durations = [
+ duration
+ for period, duration in zip(manifest.findall("Period"), DASH.period_durations(manifest), strict=True)
+ if DASH.is_content_period(period, filtered)
+ and (period is dash.get("period") or DASH.resolve_representation(period, rep_id, dash["adaptation_set"]))
+ ]
+ if durations and None not in durations:
+ return sum(cast(list[float], durations))
+ total = manifest.get("mediaPresentationDuration")
+ return DASH.pt_to_sec(total) if total else None
+ if (ism := track.data.get("ism")) and (manifest := ism.get("manifest")) is not None:
+ ticks = int(manifest.get("Duration") or 0)
+ timescale = int(manifest.get("TimeScale") or ISM_DEFAULT_TIMESCALE)
+ return ticks / timescale if ticks and timescale else None
+ return None
+
+
def extract_dash(track: Track, session: Session | RnetSession) -> list[Segment]:
from unshackle.core.manifests import DASH
@@ -291,7 +318,6 @@ def extract_dash(track: Track, session: Session | RnetSession) -> list[Segment]:
content_periods = [p for p in periods if DASH.is_content_period(p, filtered_period_ids)]
raw_segments: list[tuple[str, str | None]] = []
- kept: list[float | None] = []
for period in content_periods:
# rep ids are only unique within an AdaptationSet, so resolve like DASH.download_track
if period is stored_period:
@@ -312,15 +338,8 @@ def extract_dash(track: Track, session: Session | RnetSession) -> list[Segment]:
duration=durations[id(period)],
)
raw_segments.extend(period_segments)
- kept.append(durations[id(period)])
- # the kept periods only, so filtered ad time does not lower the estimate
- total_duration: float | None = sum(cast(list[float], kept)) if kept and None not in kept else None
- mpd_duration = manifest.get("mediaPresentationDuration")
- if total_duration is None and mpd_duration:
- total_duration = DASH.pt_to_sec(mpd_duration)
-
- return uniform_segments(raw_segments, total_duration)
+ return uniform_segments(raw_segments, manifest_seconds(track))
def extract_hls(track: Track, session: Session | RnetSession) -> list[Segment]:
@@ -345,15 +364,8 @@ def extract_hls(track: Track, session: Session | RnetSession) -> list[Segment]:
def extract_ism(track: Track, session: Session | RnetSession) -> list[Segment]:
- data = track.data["ism"]
- segments: list[str] = data.get("segments") or []
- manifest = data["manifest"]
-
- timescale = int(manifest.get("TimeScale") or ISM_DEFAULT_TIMESCALE)
- duration_ticks = int(manifest.get("Duration") or 0)
- total_duration = (duration_ticks / timescale) if timescale else 0.0
-
- return uniform_segments([(url, None) for url in segments], total_duration)
+ segments: list[str] = track.data["ism"].get("segments") or []
+ return uniform_segments([(url, None) for url in segments], manifest_seconds(track))
def extract_url(track: Track, session: Session | RnetSession, *, log: logging.Logger) -> list[Segment]:
@@ -371,13 +383,7 @@ def extract_url(track: Track, session: Session | RnetSession, *, log: logging.Lo
if mpd_duration:
duration = DASH.pt_to_sec(mpd_duration)
else:
- ism_data = track.data.get("ism")
- if ism_data and ism_data.get("manifest") is not None:
- manifest = ism_data["manifest"]
- timescale = int(manifest.get("TimeScale") or ISM_DEFAULT_TIMESCALE)
- duration_ticks = int(manifest.get("Duration") or 0)
- if timescale and duration_ticks:
- duration = duration_ticks / timescale
+ duration = manifest_seconds(track)
if not duration or duration <= 0:
# Some services clear the manifest data after collapsing to a single