"""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 DiskCheck
from unshackle.core.config import config
from unshackle.core.manifests import DASH, HLS, ISM
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
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")
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."""
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_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
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, "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
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)