mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-01 13:35:09 +00:00
feat(dl): warn when the temp volume cannot hold the HLS tracks of a title
This commit is contained in:
+52
-25
@@ -110,7 +110,7 @@ from unshackle.core.utilities import (
|
||||
time_elapsed_since,
|
||||
)
|
||||
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 (
|
||||
AUDIO_CODEC_LIST,
|
||||
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."""
|
||||
|
||||
|
||||
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.
|
||||
class DiskCheck:
|
||||
"""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.
|
||||
Any error gives None, because the check only advises and must never stop a download.
|
||||
DASH and ISM tracks count at the start, an HLS track when the HLS step has read its media playlist. Any error
|
||||
ends the check, because it only advises.
|
||||
"""
|
||||
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)}"
|
||||
)
|
||||
|
||||
def __init__(self, tracks: Tracks, warn: Callable[[str], None]) -> None:
|
||||
self.warn = warn
|
||||
self.lock = Lock()
|
||||
self.temp = temp_root()
|
||||
self.need = 0.0
|
||||
self.free = 0
|
||||
self.done = False
|
||||
|
||||
def start() -> float:
|
||||
self.free = shutil.disk_usage(self.temp).free
|
||||
playable: list[Video | Audio] = [*tracks.videos, *tracks.audio]
|
||||
return sum(
|
||||
track.bitrate * seconds / 8
|
||||
for track in playable
|
||||
if track.bitrate and (seconds := manifest_seconds(track))
|
||||
)
|
||||
|
||||
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:
|
||||
@@ -2202,8 +2227,7 @@ 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)
|
||||
disk_check = None if skip_dl or sample else DiskCheck(title.tracks, self.log.warning)
|
||||
|
||||
dl_start_time = time.time()
|
||||
|
||||
@@ -2217,6 +2241,7 @@ class dl:
|
||||
title: Title_T,
|
||||
prepare_drm_for: Callable[[AnyTrack], partial],
|
||||
progress_callables: list[partial],
|
||||
disk_check: DiskCheck | None,
|
||||
) -> None:
|
||||
track.download(
|
||||
session=track.session or service.session,
|
||||
@@ -2228,6 +2253,7 @@ class dl:
|
||||
adaptive_workers=adaptive_workers,
|
||||
download_processes=download_processes,
|
||||
progress=progress_callables[i],
|
||||
on_segments=disk_check.add_segments if disk_check else None,
|
||||
)
|
||||
if (
|
||||
track.path
|
||||
@@ -2267,6 +2293,7 @@ class dl:
|
||||
title=title,
|
||||
prepare_drm_for=prepare_drm_for,
|
||||
progress_callables=tracks_progress_callables,
|
||||
disk_check=disk_check,
|
||||
),
|
||||
skip_subtitle_errors=skip_subtitle_errors,
|
||||
on_subtitle_skipped=partial(on_subtitle_skipped, title=title),
|
||||
|
||||
@@ -693,6 +693,10 @@ class HLS:
|
||||
del content[track.sample_slice(starts, window=config.sample)]
|
||||
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
|
||||
if track.drm:
|
||||
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
|
||||
# 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)
|
||||
use_segment_decrypt = (
|
||||
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,
|
||||
adaptive_workers: bool = False,
|
||||
download_processes: int = 1,
|
||||
on_segments: Callable[[Track, list[Any]], None] | None = None,
|
||||
) -> None:
|
||||
super().download(
|
||||
session,
|
||||
@@ -255,6 +256,7 @@ class Subtitle(Track):
|
||||
proxy_download=proxy_download,
|
||||
adaptive_workers=adaptive_workers,
|
||||
download_processes=download_processes,
|
||||
on_segments=on_segments,
|
||||
)
|
||||
if not self.path:
|
||||
return
|
||||
|
||||
@@ -400,6 +400,8 @@ class DownloadContext:
|
||||
download_processes: int = 1
|
||||
license_widevine: Callable | 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:
|
||||
"""Return the HTTP session, or a new ``Session`` if none was set."""
|
||||
@@ -727,6 +729,7 @@ class Track:
|
||||
proxy_download: str | None = None,
|
||||
adaptive_workers: bool = False,
|
||||
download_processes: int = 1,
|
||||
on_segments: Callable[["Track", list[Any]], None] | None = None,
|
||||
) -> None:
|
||||
"""Download and optionally Decrypt this Track.
|
||||
|
||||
@@ -826,6 +829,7 @@ class Track:
|
||||
download_processes=download_processes,
|
||||
license_widevine=prepare_drm,
|
||||
cdm=cdm,
|
||||
on_segments=on_segments,
|
||||
)
|
||||
if self.descriptor in manifest_parsers:
|
||||
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 concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from requests import Session
|
||||
@@ -301,6 +301,17 @@ def manifest_seconds(track: Track) -> float | 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]:
|
||||
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]
|
||||
res = session.get(playlist_url, timeout=PROBE_TIMEOUT)
|
||||
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] = []
|
||||
for segment in playlist.segments:
|
||||
for segment in segments:
|
||||
url = urljoin(segment.base_uri or "", segment.uri)
|
||||
byte_range = segment.byterange # "<length>[@<offset>]"
|
||||
known_size: int | None = None
|
||||
|
||||
Reference in New Issue
Block a user