mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-29 12:35:13 +00:00
feat(dl): warn when the temp volume cannot hold the HLS tracks of a title
This commit is contained in:
@@ -311,7 +311,9 @@ Each command reports how many files it removed and how much space it freed, then
|
|||||||
!!! example "The temp directory is nearly full"
|
!!! 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. A full disk during the mux gives a line like `mkvmerge failed (exit 2): An exception occurred when writing the destination file. The drive may be full. ..., 38.0 MB free on C:\unshackle\temp`.
|
**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. A full disk during the mux gives a line like `mkvmerge failed (exit 2): An exception occurred when writing the destination file. The drive may be full. ..., 38.0 MB free on C:\unshackle\temp`.
|
||||||
|
|
||||||
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.
|
Before or during the track downloads, 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.
|
||||||
|
|
||||||
|
For a DASH or ISM track, the estimate is the manifest bitrate multiplied by the playing time, and unshackle checks before the downloads start. An HLS track has no playing time until unshackle reads its media playlist, so unshackle adds its estimate when the playlist is read, before the segments of that track download. The HLS estimate is the sum of the byte ranges when each segment has one, else the bitrate multiplied by the segment durations. An HLS video bitrate includes the audio, so the warning can come early when the free space is near the estimate. A URL track gives no estimate. You get one warning for each title at most. 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`.
|
**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`.
|
||||||
|
|
||||||
|
|||||||
@@ -1,18 +1,24 @@
|
|||||||
"""The free-space preflight warns before the downloads when the temp volume cannot hold a title's tracks."""
|
"""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 pathlib import Path
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
import m3u8
|
||||||
import pytest
|
import pytest
|
||||||
|
import requests
|
||||||
|
|
||||||
from tests.lang_selection import test_kind_only_selection as harness
|
from tests.lang_selection import test_kind_only_selection as harness
|
||||||
from unshackle.commands import dl as dl_module
|
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.config import config
|
||||||
from unshackle.core.manifests import DASH, HLS, ISM
|
from unshackle.core.manifests import DASH, HLS, ISM
|
||||||
from unshackle.core.tracks import Tracks
|
from unshackle.core.tracks import Audio, Subtitle, Tracks
|
||||||
from unshackle.core.utils.bitrate import manifest_seconds
|
from unshackle.core.tracks.track import Track
|
||||||
|
from unshackle.core.utils.bitrate import manifest_seconds, playlist_size
|
||||||
|
|
||||||
GB = 1_000_000_000
|
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")
|
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
|
@pytest.fixture
|
||||||
def free_space(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> list[int]:
|
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."""
|
"""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
|
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:
|
def test_hls_tracks_count_nothing_before_their_playlist_is_read(free_space: list[int]) -> None:
|
||||||
monkeypatch.setattr(dl_module.shutil, "disk_usage", lambda path: pytest.fail("read the disk"))
|
free_space[0] = 0
|
||||||
master = '#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=16000000,RESOLUTION=3840x2160,CODECS="hvc1.2.4.L153"\nv.m3u8\n'
|
tracks = HLS.from_text(HLS_MASTER, "https://cdn.example/x.m3u8").to_tracks("en")
|
||||||
|
|
||||||
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 tracks.videos and manifest_seconds(tracks.videos[0]) is None
|
||||||
assert low_disk_warning(tracks) 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(
|
def test_dl_logs_the_warning_once_per_title_and_not_with_skip_dl(
|
||||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||||
) -> None:
|
) -> 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)
|
harness.run(monkeypatch, caplog, {1: {}, 2: {}}, to_end=True, no_mux=True)
|
||||||
assert caplog.text.count("Temp volume is short") == 2
|
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()
|
caplog.clear()
|
||||||
harness.run(monkeypatch, caplog, {1: {}}, to_end=True, skip_dl=True)
|
harness.run(monkeypatch, caplog, {1: {}}, to_end=True, skip_dl=True)
|
||||||
assert "Temp volume is short" not in caplog.text
|
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,
|
episodes: dict,
|
||||||
service: FakeService | None = None,
|
service: FakeService | None = None,
|
||||||
to_end: bool = False,
|
to_end: bool = False,
|
||||||
|
download: Any = None,
|
||||||
**flags: Any,
|
**flags: Any,
|
||||||
) -> 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:
|
if not to_end:
|
||||||
monkeypatch.setattr(Tracks, "tree", lambda self, *a, **k: (_ for _ in ()).throw(Selected(self)))
|
monkeypatch.setattr(Tracks, "tree", lambda self, *a, **k: (_ for _ in ()).throw(Selected(self)))
|
||||||
else:
|
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)
|
monkeypatch.setattr("unshackle.core.providers.search_metadata", lambda *a, **k: None)
|
||||||
cmd = Harness.__new__(Harness)
|
cmd = Harness.__new__(Harness)
|
||||||
cmd.log = logging.getLogger("test_kind_only")
|
cmd.log = logging.getLogger("test_kind_only")
|
||||||
|
|||||||
+52
-25
@@ -110,7 +110,7 @@ from unshackle.core.utilities import (
|
|||||||
time_elapsed_since,
|
time_elapsed_since,
|
||||||
)
|
)
|
||||||
from unshackle.core.utils import tags
|
from unshackle.core.utils import tags
|
||||||
from unshackle.core.utils.bitrate import apply_real_bitrates, manifest_seconds
|
from unshackle.core.utils.bitrate import apply_real_bitrates, manifest_seconds, playlist_size
|
||||||
from unshackle.core.utils.click_types import (
|
from unshackle.core.utils.click_types import (
|
||||||
AUDIO_CODEC_LIST,
|
AUDIO_CODEC_LIST,
|
||||||
LANGUAGE_RANGE,
|
LANGUAGE_RANGE,
|
||||||
@@ -403,30 +403,55 @@ DISK_NEED_FACTOR = 2
|
|||||||
"""Times its estimated track size that a title needs on the temp volume: each encrypted track and its decrypted copy."""
|
"""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:
|
class DiskCheck:
|
||||||
"""The warning line when the temp volume has less free space than a title's video and audio need, else None.
|
"""One title's free-space preflight against the free space when the title starts; it warns once.
|
||||||
|
|
||||||
The size of a track is its manifest bitrate times its playing time; a track without both counts as 0 bytes.
|
DASH and ISM tracks count at the start, an HLS track when the HLS step has read its media playlist. Any error
|
||||||
Any error gives None, because the check only advises and must never stop a download.
|
ends the check, because it only advises.
|
||||||
"""
|
"""
|
||||||
playable: list[Video | Audio] = [*tracks.videos, *tracks.audio]
|
|
||||||
temp = temp_root()
|
def __init__(self, tracks: Tracks, warn: Callable[[str], None]) -> None:
|
||||||
try:
|
self.warn = warn
|
||||||
size = sum(
|
self.lock = Lock()
|
||||||
track.bitrate * seconds / 8 for track in playable if track.bitrate and (seconds := manifest_seconds(track))
|
self.temp = temp_root()
|
||||||
)
|
self.need = 0.0
|
||||||
if not size:
|
self.free = 0
|
||||||
return None
|
self.done = False
|
||||||
need = int(size * DISK_NEED_FACTOR)
|
|
||||||
free = shutil.disk_usage(temp).free
|
def start() -> float:
|
||||||
except Exception as e:
|
self.free = shutil.disk_usage(self.temp).free
|
||||||
logging.getLogger("download").debug(f"Free-space check skipped: {e!r}")
|
playable: list[Video | Audio] = [*tracks.videos, *tracks.audio]
|
||||||
return None
|
return sum(
|
||||||
if free >= need:
|
track.bitrate * seconds / 8
|
||||||
return None
|
for track in playable
|
||||||
return (
|
if track.bitrate and (seconds := manifest_seconds(track))
|
||||||
f"Temp volume {temp} has {filesize.decimal(free)} free, the selected tracks need about {filesize.decimal(need)}"
|
)
|
||||||
)
|
|
||||||
|
self.add(start)
|
||||||
|
|
||||||
|
def add_segments(self, track: Track, segments: list[Any]) -> None:
|
||||||
|
"""Count the media segments of an HLS video or audio track; download workers call it."""
|
||||||
|
if isinstance(track, (Video, Audio)):
|
||||||
|
self.add(lambda: playlist_size(track.bitrate, segments))
|
||||||
|
|
||||||
|
def add(self, size: Callable[[], float]) -> None:
|
||||||
|
"""Add the bytes that ``size`` gives and warn when the title now needs more than the free space."""
|
||||||
|
with self.lock:
|
||||||
|
if self.done:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
self.need += size()
|
||||||
|
except Exception as e:
|
||||||
|
logging.getLogger("download").debug(f"Free-space check skipped: {e!r}")
|
||||||
|
self.done = True
|
||||||
|
return
|
||||||
|
need = int(self.need * DISK_NEED_FACTOR)
|
||||||
|
if self.free < need:
|
||||||
|
self.done = True
|
||||||
|
self.warn(
|
||||||
|
f"Temp volume {self.temp} has {filesize.decimal(self.free)} free, "
|
||||||
|
f"the selected tracks need about {filesize.decimal(need)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class dl:
|
class dl:
|
||||||
@@ -2202,8 +2227,7 @@ class dl:
|
|||||||
f"{self.service} gives each one as one file with no segment index."
|
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)):
|
disk_check = None if skip_dl or sample else DiskCheck(title.tracks, self.log.warning)
|
||||||
self.log.warning(disk_warning)
|
|
||||||
|
|
||||||
dl_start_time = time.time()
|
dl_start_time = time.time()
|
||||||
|
|
||||||
@@ -2217,6 +2241,7 @@ class dl:
|
|||||||
title: Title_T,
|
title: Title_T,
|
||||||
prepare_drm_for: Callable[[AnyTrack], partial],
|
prepare_drm_for: Callable[[AnyTrack], partial],
|
||||||
progress_callables: list[partial],
|
progress_callables: list[partial],
|
||||||
|
disk_check: DiskCheck | None,
|
||||||
) -> None:
|
) -> None:
|
||||||
track.download(
|
track.download(
|
||||||
session=track.session or service.session,
|
session=track.session or service.session,
|
||||||
@@ -2228,6 +2253,7 @@ class dl:
|
|||||||
adaptive_workers=adaptive_workers,
|
adaptive_workers=adaptive_workers,
|
||||||
download_processes=download_processes,
|
download_processes=download_processes,
|
||||||
progress=progress_callables[i],
|
progress=progress_callables[i],
|
||||||
|
on_segments=disk_check.add_segments if disk_check else None,
|
||||||
)
|
)
|
||||||
if (
|
if (
|
||||||
track.path
|
track.path
|
||||||
@@ -2267,6 +2293,7 @@ class dl:
|
|||||||
title=title,
|
title=title,
|
||||||
prepare_drm_for=prepare_drm_for,
|
prepare_drm_for=prepare_drm_for,
|
||||||
progress_callables=tracks_progress_callables,
|
progress_callables=tracks_progress_callables,
|
||||||
|
disk_check=disk_check,
|
||||||
),
|
),
|
||||||
skip_subtitle_errors=skip_subtitle_errors,
|
skip_subtitle_errors=skip_subtitle_errors,
|
||||||
on_subtitle_skipped=partial(on_subtitle_skipped, title=title),
|
on_subtitle_skipped=partial(on_subtitle_skipped, title=title),
|
||||||
|
|||||||
@@ -693,6 +693,10 @@ class HLS:
|
|||||||
del content[track.sample_slice(starts, window=config.sample)]
|
del content[track.sample_slice(starts, window=config.sample)]
|
||||||
unwanted_segments += content
|
unwanted_segments += content
|
||||||
|
|
||||||
|
wanted_segments = [seg for seg in master.segments if seg not in unwanted_segments]
|
||||||
|
if ctx.on_segments:
|
||||||
|
ctx.on_segments(track, wanted_segments)
|
||||||
|
|
||||||
# Get session DRM as fallback but prefer media playlist keys for accurate KID matching
|
# Get session DRM as fallback but prefer media playlist keys for accurate KID matching
|
||||||
if track.drm:
|
if track.drm:
|
||||||
session_drm = track.get_drm_for_cdm(cdm)
|
session_drm = track.get_drm_for_cdm(cdm)
|
||||||
@@ -753,8 +757,6 @@ class HLS:
|
|||||||
|
|
||||||
# Downloaded segment files are named by post-filter index; map that back to the wanted
|
# Downloaded segment files are named by post-filter index; map that back to the wanted
|
||||||
# segment so the IV uses the absolute media sequence number, not the download index.
|
# segment so the IV uses the absolute media sequence number, not the download index.
|
||||||
wanted_segments = [seg for seg in master.segments if seg not in unwanted_segments]
|
|
||||||
|
|
||||||
single_init = HLS.single_init_no_rotation(wanted_segments, initial_drm_key, cdm, track.drm_preference)
|
single_init = HLS.single_init_no_rotation(wanted_segments, initial_drm_key, cdm, track.drm_preference)
|
||||||
use_segment_decrypt = (
|
use_segment_decrypt = (
|
||||||
isinstance(session_drm, (Widevine, PlayReady)) and can_use(session_drm, config.decryption) and single_init
|
isinstance(session_drm, (Widevine, PlayReady)) and can_use(session_drm, config.decryption) and single_init
|
||||||
|
|||||||
@@ -244,6 +244,7 @@ class Subtitle(Track):
|
|||||||
proxy_download: str | None = None,
|
proxy_download: str | None = None,
|
||||||
adaptive_workers: bool = False,
|
adaptive_workers: bool = False,
|
||||||
download_processes: int = 1,
|
download_processes: int = 1,
|
||||||
|
on_segments: Callable[[Track, list[Any]], None] | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
super().download(
|
super().download(
|
||||||
session,
|
session,
|
||||||
@@ -255,6 +256,7 @@ class Subtitle(Track):
|
|||||||
proxy_download=proxy_download,
|
proxy_download=proxy_download,
|
||||||
adaptive_workers=adaptive_workers,
|
adaptive_workers=adaptive_workers,
|
||||||
download_processes=download_processes,
|
download_processes=download_processes,
|
||||||
|
on_segments=on_segments,
|
||||||
)
|
)
|
||||||
if not self.path:
|
if not self.path:
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -400,6 +400,8 @@ class DownloadContext:
|
|||||||
download_processes: int = 1
|
download_processes: int = 1
|
||||||
license_widevine: Callable | None = None
|
license_widevine: Callable | None = None
|
||||||
cdm: object | None = None
|
cdm: object | None = None
|
||||||
|
on_segments: Callable[["Track", list[Any]], None] | None = None
|
||||||
|
"""Called by the HLS step with a track and its wanted media segments, before they download."""
|
||||||
|
|
||||||
def ensure_session(self) -> AnySession:
|
def ensure_session(self) -> AnySession:
|
||||||
"""Return the HTTP session, or a new ``Session`` if none was set."""
|
"""Return the HTTP session, or a new ``Session`` if none was set."""
|
||||||
@@ -727,6 +729,7 @@ class Track:
|
|||||||
proxy_download: str | None = None,
|
proxy_download: str | None = None,
|
||||||
adaptive_workers: bool = False,
|
adaptive_workers: bool = False,
|
||||||
download_processes: int = 1,
|
download_processes: int = 1,
|
||||||
|
on_segments: Callable[["Track", list[Any]], None] | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Download and optionally Decrypt this Track.
|
"""Download and optionally Decrypt this Track.
|
||||||
|
|
||||||
@@ -826,6 +829,7 @@ class Track:
|
|||||||
download_processes=download_processes,
|
download_processes=download_processes,
|
||||||
license_widevine=prepare_drm,
|
license_widevine=prepare_drm,
|
||||||
cdm=cdm,
|
cdm=cdm,
|
||||||
|
on_segments=on_segments,
|
||||||
)
|
)
|
||||||
if self.descriptor in manifest_parsers:
|
if self.descriptor in manifest_parsers:
|
||||||
manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx)
|
manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx)
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from collections import OrderedDict, defaultdict
|
|||||||
from collections.abc import Callable, Hashable, Sequence
|
from collections.abc import Callable, Hashable, Sequence
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import TYPE_CHECKING, cast
|
from typing import TYPE_CHECKING, Any, cast
|
||||||
from urllib.parse import urljoin
|
from urllib.parse import urljoin
|
||||||
|
|
||||||
from requests import Session
|
from requests import Session
|
||||||
@@ -301,6 +301,17 @@ def manifest_seconds(track: Track) -> float | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def playlist_size(bitrate: int | None, segments: list[Any]) -> float:
|
||||||
|
"""The bytes of HLS media segments from their playlist; it sends no request.
|
||||||
|
|
||||||
|
It is the sum of the EXT-X-BYTERANGE lengths when each segment has one, else the bitrate times the EXTINF time.
|
||||||
|
"""
|
||||||
|
parsed = hls_segments(segments)
|
||||||
|
if parsed and all(segment.known_size is not None for segment in parsed):
|
||||||
|
return float(sum(segment.known_size or 0 for segment in parsed))
|
||||||
|
return (bitrate or 0) * sum(segment.duration for segment in parsed) / 8
|
||||||
|
|
||||||
|
|
||||||
def extract_dash(track: Track, session: Session | RnetSession) -> list[Segment]:
|
def extract_dash(track: Track, session: Session | RnetSession) -> list[Segment]:
|
||||||
from unshackle.core.manifests import DASH
|
from unshackle.core.manifests import DASH
|
||||||
|
|
||||||
@@ -348,9 +359,13 @@ def extract_hls(track: Track, session: Session | RnetSession) -> list[Segment]:
|
|||||||
playlist_url = track.url if isinstance(track.url, str) else track.url[0]
|
playlist_url = track.url if isinstance(track.url, str) else track.url[0]
|
||||||
res = session.get(playlist_url, timeout=PROBE_TIMEOUT)
|
res = session.get(playlist_url, timeout=PROBE_TIMEOUT)
|
||||||
playlist = m3u8.loads(utf8_text(res), uri=playlist_url)
|
playlist = m3u8.loads(utf8_text(res), uri=playlist_url)
|
||||||
|
return hls_segments(playlist.segments)
|
||||||
|
|
||||||
|
|
||||||
|
def hls_segments(segments: list[Any]) -> list[Segment]:
|
||||||
|
"""Parsed HLS media segments as Segments, each with its EXT-X-BYTERANGE length when it has one."""
|
||||||
out: list[Segment] = []
|
out: list[Segment] = []
|
||||||
for segment in playlist.segments:
|
for segment in segments:
|
||||||
url = urljoin(segment.base_uri or "", segment.uri)
|
url = urljoin(segment.base_uri or "", segment.uri)
|
||||||
byte_range = segment.byterange # "<length>[@<offset>]"
|
byte_range = segment.byterange # "<length>[@<offset>]"
|
||||||
known_size: int | None = None
|
known_size: int | None = None
|
||||||
|
|||||||
Reference in New Issue
Block a user