Skip to content

Bulk asynchronous downloader for multiple file hosts

fix: sexagesimal duration parsing (#1627)

NTFSvolume40d599639c51
diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.py
index 7240a0389..5a0401d49 100644
--- a/cyberdrop_dl/managers/client_manager.py
+++ b/cyberdrop_dl/managers/client_manager.py
@@ -425,11 +425,12 @@ class ClientManager:
headers = self.download_client._get_download_headers(media_item.domain, media_item.referer)
properties = await probe(media_item.url, headers=headers)
- if is_video and (video := properties.video):
- return video.duration
- if is_audio and (audio := properties.audio):
- return audio.duration
- return None
+ if properties.format.duration:
+ return properties.format.duration
+ if is_video and properties.video:
+ return properties.video.duration
+ if is_audio and properties.audio:
+ return properties.audio.duration
duration: float | None = await get_duration()
media_item.duration = duration
diff --git a/cyberdrop_dl/utils/ffmpeg.py b/cyberdrop_dl/utils/ffmpeg.py
index 720e48f03..f7c149b4f 100644
--- a/cyberdrop_dl/utils/ffmpeg.py
+++ b/cyberdrop_dl/utils/ffmpeg.py
@@ -7,7 +7,6 @@ import json
import shutil
import subprocess
from dataclasses import asdict, dataclass
-from datetime import timedelta
from fractions import Fraction
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, NamedTuple, Required, Self, TypeAlias, TypedDict, overload
@@ -37,7 +36,16 @@ class Args:
_FFMPEG_CALL_PREFIX = "ffmpeg", "-y", "-loglevel", "error"
-_FFPROBE_CALL_PREFIX = "ffprobe", "-hide_banner", "-loglevel", "error", "-show_streams", "-print_format", "json"
+_FFPROBE_CALL_PREFIX = (
+ "ffprobe",
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-show_streams",
+ "-show_format",
+ "-print_format",
+ "json",
+)
_EMPTY_FFPROBE_OUTPUT: FFprobeOutput = {"streams": []}
@@ -178,36 +186,25 @@ def _get_bin_version(bin_path: str) -> str | None:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~ FFprobe ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class Duration(NamedTuple):
- # "00:03:48.250000000"
- days: int = 0
- hours: int = 0
- minutes: int = 0
- seconds: float = 0
+def _parse_duration(duration: str | float | None) -> TruncatedFloat | None:
+ if not duration:
+ return None
- @staticmethod
- def parse(duration: float | str) -> TruncatedFloat:
+ if isinstance(duration, (float, int)):
+ seconds = duration
+
+ else:
try:
- return TruncatedFloat(duration)
- except (ValueError, TypeError):
- pass
-
- assert isinstance(duration, str)
- days, _, other_parts = duration.partition(" ")
- if other_parts:
- days = "".join(char for char in days if char.isdigit())
- else:
- other_parts = days
+ *rest, seconds = duration.strip().split(":")
- days = days or "0"
- time_parts = other_parts.split(":")
- missing_parts = [0 for _ in range(3 - len(time_parts))]
- seconds = float(Fraction(time_parts.pop(-1)))
- int_parts = map(int, (days, *missing_parts, *time_parts))
- return TruncatedFloat(Duration(*int_parts, seconds=seconds).as_timedelta().total_seconds())
+ seconds = float(seconds)
+ for idx, value in enumerate(reversed(rest), 1):
+ seconds += int(value) * 60**idx
+ except Exception:
+ return None
- def as_timedelta(self) -> timedelta:
- return timedelta(**self._asdict())
+ if seconds > 0:
+ return TruncatedFloat(seconds)
class StreamDict(TypedDict, total=False):
@@ -230,24 +227,22 @@ class TruncatedFloat(float):
@dataclass(frozen=True, slots=True, kw_only=True)
class Stream:
index: int
- codec_name: str
+ codec: str
codec_type: str
bitrate: int | None
duration: TruncatedFloat | None
tags: Tags
- @property
- def codec(self) -> str:
- return self.codec_name
-
@classmethod
def validate(cls, stream_info: StreamDict) -> dict[str, Any]:
info = get_valid_dict(cls, stream_info)
tags = Tags(CIMultiDict(stream_info.get("tags", {})))
- duration: float | str | None = stream_info.get("duration") or tags.get("duration")
- bitrate = int(stream_info.get("bitrate") or stream_info.get("bit_rate") or 0) or None
- duration = Duration.parse(duration) if duration else None
- return info | {"tags": tags, "duration": duration, "bitrate": bitrate}
+ return info | {
+ "codec": stream_info.get("codec_name"),
+ "duration": _parse_duration(stream_info.get("duration") or tags.get("duration")),
+ "bitrate": int(stream_info.get("bitrate") or stream_info.get("bit_rate") or 0) or None,
+ "tags": tags,
+ }
@classmethod
def from_dict(cls, stream_info: StreamDict) -> Self:
@@ -292,10 +287,30 @@ class VideoStream(Stream):
return defaults | {"width": width, "height": height, "fps": fps, "resolution": resolution}
+@dataclass(frozen=True, slots=True, kw_only=True)
+class Format:
+ size: int | None
+ bitrate: int | None
+ duration: TruncatedFloat | None
+ tags: Tags
+
+ @classmethod
+ def from_dict(cls, format_info: dict[str, Any]) -> Self:
+ tags = Tags(CIMultiDict(format_info.get("tags", {})))
+
+ return cls(
+ size=int(float(format_info.get("size") or 0)) or None,
+ duration=_parse_duration(format_info.get("duration") or tags.get("duration")),
+ bitrate=int(format_info.get("bitrate") or format_info.get("bit_rate") or 0) or None,
+ tags=tags,
+ )
+
+
@dataclass(frozen=True, slots=True)
class FFprobeResult:
ffprobe_output: FFprobeOutput
streams: tuple[Stream, ...]
+ format: Format
@staticmethod
def from_output(ffprobe_output: FFprobeOutput) -> FFprobeResult:
@@ -306,7 +321,11 @@ class FFprobeResult:
elif stream["codec_type"] == "audio":
yield AudioStream.from_dict(stream)
- return FFprobeResult(ffprobe_output, tuple(streams()))
+ return FFprobeResult(
+ ffprobe_output,
+ streams=tuple(streams()),
+ format=Format.from_dict(ffprobe_output.get("format", {})),
+ )
def video_streams(self) -> Generator[VideoStream]:
for stream in self.streams:
diff --git a/cyberdrop_dl/utils/sorting.py b/cyberdrop_dl/utils/sorting.py
index 395446af3..b99e4844c 100644
--- a/cyberdrop_dl/utils/sorting.py
+++ b/cyberdrop_dl/utils/sorting.py
@@ -136,9 +136,9 @@ class Sorter:
bitrate = duration = sample_rate = None
try:
- properties = await probe(file)
- if audio := properties.audio:
- duration = audio.duration
+ probe_output = await probe(file)
+ if audio := probe_output.audio:
+ duration = audio.duration or probe_output.format.duration
bitrate = audio.bitrate
sample_rate = audio.sample_rate
@@ -190,13 +190,13 @@ class Sorter:
codec = duration = framerate = height = resolution = width = None
try:
- properties = await probe(file)
- if video := properties.video:
+ probe_output = await probe(file)
+ if video := probe_output.video:
width = video.width
height = video.height
resolution = video.resolution
- codec = video.codec_name
- duration = video.duration
+ codec = video.codec
+ duration = video.duration or probe_output.format.duration
framerate = video.fps
except (RuntimeError, CalledProcessError, OSError) as e:
diff --git a/tests/test_ffmpeg.py b/tests/test_ffmpeg.py
index 60843e0a7..659052375 100644
--- a/tests/test_ffmpeg.py
+++ b/tests/test_ffmpeg.py
@@ -1,3 +1,5 @@
+import datetime
+
import pytest
from cyberdrop_dl.data_structures import AbsoluteHttpURL
@@ -12,20 +14,54 @@ async def test_ffprobe_video_url() -> None:
output = await ffmpeg.probe(
AbsoluteHttpURL("https://videos.pexels.com/video-files/29691053/12769314_360_640_60fps.mp4")
)
- # assert output.audio
- # assert output.audio.codec == "aac"
- # assert output.audio.duration == 7.808
- # assert str(output.audio.duration) == "7.81"
- # assert output.audio.sample_rate == 48000
assert output.video
+ assert output.video.duration == 10.5105
+ assert str(output.video.duration) == "10.51"
assert output.video.codec == "h264"
assert output.video.bitrate == 4_014_556
assert output.video.fps and round(output.video.fps) == 60.0
assert output.video.width == 360
assert output.video.height == 640
+ assert output.format.bitrate == 4_019_301
+ assert output.format.duration == 10.5105
+ assert output.format.size == 5_280_609
+
tags = output.video.tags
assert tags["language"] == "und"
assert tags["handler_name"] == "Core Media Video"
assert tags["encoder"] == "Lavc60.31.102 libx264"
+
+
+ "input, hours, minutes, seconds",
+ [
+ # numbers
+ (42.5, 0, 0, 42.5),
+ (123, 0, 0, 123),
+ # minutes:seconds
+ ("3:30", 0, 3, 30),
+ ("10:07.25", 0, 10, 7.25),
+ ("00:00:30.000000000", 0, 0, 30),
+ # hours:minutes:seconds
+ ("00:08:37.503", 0, 8, 37.503),
+ ("1:23:45.6", 1, 23, 45.6),
+ ("99:59:59.999", 99, 59, 59.999),
+ # 60+ seconds
+ ("0:0:120.5", 0, 2, 0.5),
+ ],
+)
+def test_parse_duration(input: str, hours: float, minutes: float, seconds: float) -> None:
+ output = ffmpeg._parse_duration(input)
+ expected = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds).total_seconds()
+ assert output == expected
+
+
+ "input",
+ ["0", "0:00", "00:00:00", None, "", -1, False, "Invalid"],
+)
+def test_parse_null_duration(input: str) -> None:
+ output = ffmpeg._parse_duration(input)
+ assert output is None