mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-29 04:15:09 +00:00
feat(dl): warn when the temp volume cannot hold the HLS tracks of a title
This commit is contained in:
@@ -1,18 +1,24 @@
|
||||
"""The free-space preflight warns before the downloads when the temp volume cannot hold a title's tracks."""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import m3u8
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
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.commands.dl import DiskCheck
|
||||
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
|
||||
from unshackle.core.tracks import Audio, Subtitle, Tracks
|
||||
from unshackle.core.tracks.track import Track
|
||||
from unshackle.core.utils.bitrate import manifest_seconds, playlist_size
|
||||
|
||||
GB = 1_000_000_000
|
||||
|
||||
@@ -42,6 +48,33 @@ def dash_tracks(manifest: str) -> Tracks:
|
||||
return DASH.from_text(manifest, "https://cdn.example/x.mpd").to_tracks("en")
|
||||
|
||||
|
||||
def new_check(tracks: Tracks | None = None) -> tuple[DiskCheck, list[str]]:
|
||||
"""A check of ``tracks`` and the list of lines it warns with."""
|
||||
lines: list[str] = []
|
||||
return DiskCheck(tracks or Tracks(), lines.append), lines
|
||||
|
||||
|
||||
def low_disk_warning(tracks: Tracks) -> str | None:
|
||||
"""The line a new check of ``tracks`` warns with, else None."""
|
||||
lines = new_check(tracks)[1]
|
||||
return lines[0] if lines else None
|
||||
|
||||
|
||||
HLS_MASTER = '#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=16000000,RESOLUTION=3840x2160,CODECS="hvc1.2.4.L153"\nv.m3u8\n'
|
||||
|
||||
|
||||
def media_segments(count: int, byterange: str | None = None) -> list[Any]:
|
||||
"""``count`` media segments of 6 s, each with ``byterange`` when one is given."""
|
||||
entry = (f"#EXT-X-BYTERANGE:{byterange}\n" if byterange else "") + "#EXTINF:6.0,\nseg.m4s\n"
|
||||
return list(m3u8.loads("#EXTM3U\n#EXT-X-TARGETDURATION:6\n" + entry * count + "#EXT-X-ENDLIST\n").segments)
|
||||
|
||||
|
||||
def hls_audio() -> Audio:
|
||||
return Audio(
|
||||
url="https://cdn.example/a.m3u8", language="en", descriptor=Track.Descriptor.HLS, codec=Audio.Codec.AAC
|
||||
)
|
||||
|
||||
|
||||
@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."""
|
||||
@@ -68,11 +101,9 @@ def test_enough_free_space_gives_no_warning(free_space: list[int]) -> None:
|
||||
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")
|
||||
def test_hls_tracks_count_nothing_before_their_playlist_is_read(free_space: list[int]) -> None:
|
||||
free_space[0] = 0
|
||||
tracks = HLS.from_text(HLS_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
|
||||
@@ -140,7 +171,7 @@ def test_an_unreadable_temp_volume_gives_no_warning(free_space: list[int], monke
|
||||
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")
|
||||
monkeypatch.setattr(dl_module, "DiskCheck", lambda tracks, warn: warn("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
|
||||
@@ -148,3 +179,139 @@ def test_dl_logs_the_warning_once_per_title_and_not_with_skip_dl(
|
||||
caplog.clear()
|
||||
harness.run(monkeypatch, caplog, {1: {}}, to_end=True, skip_dl=True)
|
||||
assert "Temp volume is short" not in caplog.text
|
||||
|
||||
|
||||
def test_an_hls_track_warns_once_when_its_playlist_is_read(free_space: list[int], tmp_path: Path) -> None:
|
||||
free_space[0] = 3_100_000_000
|
||||
video = HLS.from_text(HLS_MASTER, "https://cdn.example/x.m3u8").to_tracks("en").videos[0]
|
||||
check, lines = new_check(Tracks([video]))
|
||||
assert lines == []
|
||||
|
||||
check.add_segments(video, media_segments(600))
|
||||
check.add_segments(video, media_segments(600))
|
||||
|
||||
assert lines == [f"Temp volume {tmp_path} has 3.1 GB free, the selected tracks need about 14.4 GB"]
|
||||
|
||||
|
||||
def test_a_mixed_title_counts_each_track_once_against_one_free_space_reading(
|
||||
free_space: list[int], tmp_path: Path
|
||||
) -> None:
|
||||
free_space[0] = 20 * GB
|
||||
check, lines = new_check(dash_tracks(mpd(period())))
|
||||
assert lines == []
|
||||
|
||||
free_space[0] = 0
|
||||
check.add_segments(hls_audio(), media_segments(3, byterange="1000000000"))
|
||||
|
||||
assert lines == [f"Temp volume {tmp_path} has 20.0 GB free, the selected tracks need about 21.0 GB"]
|
||||
|
||||
|
||||
def test_a_second_worker_waits_for_the_first_and_gives_no_second_warning(free_space: list[int]) -> None:
|
||||
free_space[0] = GB
|
||||
check, lines = new_check()
|
||||
second_started = threading.Event()
|
||||
|
||||
def first_size() -> float:
|
||||
assert second_started.wait(5)
|
||||
return 2 * GB
|
||||
|
||||
second = threading.Thread(target=lambda: (second_started.set(), check.add(lambda: 2 * GB)))
|
||||
first = threading.Thread(target=check.add, args=(first_size,))
|
||||
first.start()
|
||||
deadline = time.monotonic() + 5
|
||||
while not check.lock.locked() and time.monotonic() < deadline:
|
||||
time.sleep(0.001)
|
||||
second.start()
|
||||
first.join(5)
|
||||
second.join(5)
|
||||
|
||||
assert len(lines) == 1
|
||||
|
||||
|
||||
def test_a_subtitle_counts_nothing(free_space: list[int]) -> None:
|
||||
free_space[0] = 0
|
||||
check, lines = new_check()
|
||||
subtitle = Subtitle(url="https://cdn.example/s.m3u8", language="en", codec=Subtitle.Codec.WebVTT)
|
||||
|
||||
check.add_segments(subtitle, media_segments(3, byterange="1000000000"))
|
||||
|
||||
assert lines == []
|
||||
|
||||
|
||||
def test_an_estimate_error_ends_the_check(free_space: list[int]) -> None:
|
||||
free_space[0] = 0
|
||||
check, lines = new_check()
|
||||
|
||||
check.add(lambda: 1 / 0)
|
||||
check.add_segments(hls_audio(), media_segments(1, byterange="1000000000"))
|
||||
|
||||
assert lines == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("bitrate", "segments", "size"),
|
||||
[
|
||||
(16_000_000, media_segments(3, byterange="1000@0"), 3000),
|
||||
(16_000_000, media_segments(2, byterange="1000@0") + media_segments(1), 16_000_000 * 18 / 8),
|
||||
(8, media_segments(1, byterange="x"), 6),
|
||||
(None, media_segments(3), 0),
|
||||
],
|
||||
ids=["byte ranges", "a segment without a range", "an unreadable range", "no bitrate"],
|
||||
)
|
||||
def test_playlist_size(bitrate: int | None, segments: list[Any], size: float) -> None:
|
||||
assert playlist_size(bitrate, segments) == size
|
||||
|
||||
|
||||
def test_the_hls_step_hands_over_its_wanted_segments_before_any_segment_downloads(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
playlist = tmp_path / "media.m3u8"
|
||||
playlist.write_text(
|
||||
"#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6.0,\nad.m4s\n#EXTINF:6.0,\nseg.m4s\n#EXT-X-ENDLIST\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
track = hls_audio()
|
||||
track.from_file = playlist
|
||||
track.OnSegmentFilter = lambda segment: segment.uri == "ad.m4s"
|
||||
handed: list[tuple[Any, list[str]]] = []
|
||||
|
||||
class Stop(Exception):
|
||||
pass
|
||||
|
||||
def on_segments(track: Any, segments: list[Any]) -> None:
|
||||
handed.append((track, [segment.uri for segment in segments]))
|
||||
raise Stop
|
||||
|
||||
with pytest.raises(Stop):
|
||||
track.download(
|
||||
requests.Session(),
|
||||
partial(lambda *a, **k: None),
|
||||
progress=partial(lambda **_: None),
|
||||
on_segments=on_segments,
|
||||
)
|
||||
|
||||
assert handed == [(track, ["seg.m4s"])]
|
||||
assert not list(tmp_path.glob("*_segments/*"))
|
||||
|
||||
|
||||
def test_dl_hands_each_track_download_the_check_of_its_title(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
class Recorder(DiskCheck):
|
||||
def __init__(self, tracks: Tracks, warn: Any) -> None:
|
||||
checks.append(self)
|
||||
|
||||
checks: list[Recorder] = []
|
||||
handed: list[Any] = []
|
||||
monkeypatch.setattr(dl_module, "DiskCheck", Recorder)
|
||||
monkeypatch.setattr(Track, "download", lambda self, *a, **k: handed.append(k["on_segments"]))
|
||||
|
||||
def download_all(tracks: Any, workers: int, run_one: Any, **_: Any) -> None:
|
||||
for i, track in enumerate(tracks):
|
||||
run_one(track, i)
|
||||
|
||||
harness.run(monkeypatch, caplog, {1: {}}, to_end=True, no_mux=True, download=download_all)
|
||||
|
||||
assert len(checks) == 1 and len(handed) == 3
|
||||
assert all(on_segments == checks[0].add_segments for on_segments in handed)
|
||||
|
||||
@@ -99,13 +99,17 @@ def run(
|
||||
episodes: dict,
|
||||
service: FakeService | None = None,
|
||||
to_end: bool = False,
|
||||
download: Any = None,
|
||||
**flags: Any,
|
||||
) -> Any:
|
||||
"""Return the Selected ids, the exit code, or None for a run that completes; to_end runs past selection."""
|
||||
"""Return the Selected ids, the exit code, or None for a run that completes; to_end runs past selection.
|
||||
|
||||
A run to the end downloads nothing unless ``download`` stands in for ``download_tracks_in_passes``.
|
||||
"""
|
||||
if not to_end:
|
||||
monkeypatch.setattr(Tracks, "tree", lambda self, *a, **k: (_ for _ in ()).throw(Selected(self)))
|
||||
else:
|
||||
monkeypatch.setattr("unshackle.commands.dl.download_tracks_in_passes", lambda *a, **k: None)
|
||||
monkeypatch.setattr("unshackle.commands.dl.download_tracks_in_passes", download or (lambda *a, **k: None))
|
||||
monkeypatch.setattr("unshackle.core.providers.search_metadata", lambda *a, **k: None)
|
||||
cmd = Harness.__new__(Harness)
|
||||
cmd.log = logging.getLogger("test_kind_only")
|
||||
|
||||
Reference in New Issue
Block a user