Skip to content

Bulk asynchronous downloader for multiple file hosts

feat: add `--concurrent-segments` config option (#1830)

NTFSvolumeb717cabc58a0
diff --git a/cyberdrop_dl/config/_global.py b/cyberdrop_dl/config/_global.py
index a44347875..a469e2836 100755
--- a/cyberdrop_dl/config/_global.py
+++ b/cyberdrop_dl/config/_global.py
@@ -70,6 +70,8 @@ class RateLimiting(SettingsGroup):
connection_timeout: PositiveFloat = 15
read_timeout: PositiveFloat | None = 300
+ concurrent_segments: PositiveInt = 10
+ """Allow up to `<N>` HLS segments to be downloaded concurrently"""
@field_validator("read_timeout", mode="before")
@classmethod
diff --git a/cyberdrop_dl/downloader/hls.py b/cyberdrop_dl/downloader/hls.py
index a005d9ad5..8759a5a6a 100644
--- a/cyberdrop_dl/downloader/hls.py
+++ b/cyberdrop_dl/downloader/hls.py
@@ -22,7 +22,7 @@ if TYPE_CHECKING:
DownloadFn = Callable[[MediaItem], Awaitable[bool]]
-_TASK_LIMIT: ContextVar[int] = ContextVar("_TASK_LIMIT", default=10)
+CONCURRENT_SEGMENTS: ContextVar[int] = ContextVar("CONCURRENT_SEGMENTS")
logger = logging.getLogger(__name__)
@@ -78,7 +78,13 @@ def _create_media_segments(
yield seg_media_item
-async def _download_m3u8(m3u8: M3U8, temp_dir: Path, media_item: MediaItem, download_fn: DownloadFn) -> Path:
+async def _download_m3u8(
+ m3u8: M3U8,
+ temp_dir: Path,
+ media_item: MediaItem,
+ download_fn: DownloadFn,
+ sem: asyncio.BoundedSemaphore,
+) -> Path:
assert m3u8.media_type
if not m3u8.segments:
raise DownloadError(
@@ -99,15 +105,18 @@ async def _download_m3u8(m3u8: M3U8, temp_dir: Path, media_item: MediaItem, down
download_folder=temp_dir / m3u8.media_type,
)
+ logger.debug(
+ f"Starting HLS download ({m3u8.media_type}, {len(m3u8.segments):,} segments) for {media_item.real_url}"
+ )
results = await aio.map(
download_segment,
segments,
- task_limit=_TASK_LIMIT.get(),
+ task_limit=sem,
)
n_successful = sum(1 for result in results if result.downloaded)
- if n_successful != (n_segmets := len(m3u8.segments)):
- msg = f"Download of some segments failed. Successful: {n_successful:,}/{n_segmets:,} "
+ if n_successful != len(m3u8.segments):
+ msg = f"Download of some segments failed. Successful: {n_successful:,}/{len(m3u8.segments):,} "
raise DownloadError("HLS Seg Error", msg, media_item)
await _merge_segments(tuple(result.item.path for result in results), output, m3u8.media_type)
@@ -145,8 +154,10 @@ async def download(media_item: MediaItem, rendition: Rendition, download_fn: Dow
"""Download a rendition group"""
temp_dir = media_item.path.with_suffix(constants.TempExt.HLS)
+ sem = asyncio.BoundedSemaphore(CONCURRENT_SEGMENTS.get())
+
async def download(m3u8: M3U8) -> Path:
- return await _download_m3u8(m3u8, temp_dir, media_item, download_fn)
+ return await _download_m3u8(m3u8, temp_dir, media_item, download_fn, sem)
async def download_subs() -> Path | None:
if not rendition.subtitle:
@@ -166,9 +177,10 @@ async def download(media_item: MediaItem, rendition: Rendition, download_fn: Dow
return await download(rendition.audio)
async with asyncio.TaskGroup() as tg:
- video = tg.create_task(download(rendition.video))
- audio = tg.create_task(download_audio())
+ # Keep this priority for the semaphore: subs > audio > video
subs = tg.create_task(download_subs())
+ audio = tg.create_task(download_audio())
+ video = tg.create_task(download(rendition.video))
try:
await aio.rmdir(temp_dir)
diff --git a/cyberdrop_dl/downloader/http.py b/cyberdrop_dl/downloader/http.py
index 0ed50ee89..ccb0f88c3 100644
--- a/cyberdrop_dl/downloader/http.py
+++ b/cyberdrop_dl/downloader/http.py
@@ -200,6 +200,7 @@ class Downloader:
# TODO: add remux method to ffmpeg to create an mkv file instead of mp4
# Subtitles format may be incompatible with mp4 and they will be silently dropped by ffmpeg
# so we leave them as independent files for now
+ logger.debug(f"Merging audio and video stream from {media_item.real_url}")
ffmpeg_result = await ffmpeg.merge((streams.video, streams.audio), media_item.path)
if not ffmpeg_result.success:
diff --git a/cyberdrop_dl/scrape_mapper.py b/cyberdrop_dl/scrape_mapper.py
index 40d7df7af..ec32131a7 100644
--- a/cyberdrop_dl/scrape_mapper.py
+++ b/cyberdrop_dl/scrape_mapper.py
@@ -19,6 +19,7 @@ from cyberdrop_dl.crawlers.discourse import DiscourseCrawler
from cyberdrop_dl.crawlers.http_direct import DirectHttpFile
from cyberdrop_dl.crawlers.realdebrid import RealDebridCrawler
from cyberdrop_dl.crawlers.wordpress import WordPressHTMLCrawler, WordPressMediaCrawler
+from cyberdrop_dl.downloader.hls import CONCURRENT_SEGMENTS
from cyberdrop_dl.exceptions import JDownloaderError, NoExtensionError
from cyberdrop_dl.logs import log_spacer
from cyberdrop_dl.progress.scraping import ScrapingUI
@@ -165,6 +166,7 @@ class ScrapeMapper:
assert not self._done.is_set()
_ = filepath.MAX_FILE_LEN.set(self.manager.config.global_settings.general.max_file_name_length)
_ = filepath.MAX_FOLDER_LEN.set(self.manager.config.global_settings.general.max_folder_name_length)
+ _ = CONCURRENT_SEGMENTS.set(self.manager.config.global_settings.rate_limiting_options.concurrent_segments)
self.manager.config.settings.files.download_folder.mkdir(parents=True, exist_ok=True)
if self.manager.config.settings.sorting.sort_downloads: