video-upscaler-cli 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. video_upscaler_cli-0.1.1/PKG-INFO +17 -0
  2. video_upscaler_cli-0.1.1/README.md +3 -0
  3. video_upscaler_cli-0.1.1/pyproject.toml +28 -0
  4. video_upscaler_cli-0.1.1/setup.cfg +4 -0
  5. video_upscaler_cli-0.1.1/src/video_upscaler/__init__.py +50 -0
  6. video_upscaler_cli-0.1.1/src/video_upscaler/cli/__init__.py +170 -0
  7. video_upscaler_cli-0.1.1/src/video_upscaler/core/__init__.py +27 -0
  8. video_upscaler_cli-0.1.1/src/video_upscaler/core/calculator.py +199 -0
  9. video_upscaler_cli-0.1.1/src/video_upscaler/core/probe.py +182 -0
  10. video_upscaler_cli-0.1.1/src/video_upscaler/core/types.py +133 -0
  11. video_upscaler_cli-0.1.1/src/video_upscaler/engines/__init__.py +27 -0
  12. video_upscaler_cli-0.1.1/src/video_upscaler/engines/base.py +62 -0
  13. video_upscaler_cli-0.1.1/src/video_upscaler/engines/ffmpeg.py +123 -0
  14. video_upscaler_cli-0.1.1/src/video_upscaler/engines/progress.py +30 -0
  15. video_upscaler_cli-0.1.1/src/video_upscaler/engines/realesrgan.py +48 -0
  16. video_upscaler_cli-0.1.1/src/video_upscaler/filters/__init__.py +5 -0
  17. video_upscaler_cli-0.1.1/src/video_upscaler/filters/chain.py +78 -0
  18. video_upscaler_cli-0.1.1/src/video_upscaler_cli.egg-info/PKG-INFO +17 -0
  19. video_upscaler_cli-0.1.1/src/video_upscaler_cli.egg-info/SOURCES.txt +25 -0
  20. video_upscaler_cli-0.1.1/src/video_upscaler_cli.egg-info/dependency_links.txt +1 -0
  21. video_upscaler_cli-0.1.1/src/video_upscaler_cli.egg-info/entry_points.txt +2 -0
  22. video_upscaler_cli-0.1.1/src/video_upscaler_cli.egg-info/top_level.txt +1 -0
  23. video_upscaler_cli-0.1.1/tests/test_calculator.py +171 -0
  24. video_upscaler_cli-0.1.1/tests/test_engines.py +296 -0
  25. video_upscaler_cli-0.1.1/tests/test_filters.py +106 -0
  26. video_upscaler_cli-0.1.1/tests/test_probe.py +219 -0
  27. video_upscaler_cli-0.1.1/tests/test_scaffolding.py +26 -0
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.4
2
+ Name: video-upscaler-cli
3
+ Version: 0.1.1
4
+ Summary: High-precision video upscaler CLI and library using FFmpeg filter pipelines
5
+ Author: Dream-Pixels-Forge
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Topic :: Multimedia :: Video :: Conversion
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+
15
+ # Video Upscaler
16
+
17
+ High-precision video upscaler CLI and library using FFmpeg filter pipelines.
@@ -0,0 +1,3 @@
1
+ # Video Upscaler
2
+
3
+ High-precision video upscaler CLI and library using FFmpeg filter pipelines.
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "video-upscaler-cli"
7
+ version = "0.1.1"
8
+ description = "High-precision video upscaler CLI and library using FFmpeg filter pipelines"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [
13
+ { name = "Dream-Pixels-Forge" }
14
+ ]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Topic :: Multimedia :: Video :: Conversion",
21
+ ]
22
+ dependencies = []
23
+
24
+ [project.scripts]
25
+ video-upscale = "video_upscaler.cli:main"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,50 @@
1
+ """video_upscaler - High-precision video upscaling CLI and library."""
2
+
3
+ from video_upscaler.core import (
4
+ DenoiseLevel,
5
+ FitStrategy,
6
+ LowResolutionError,
7
+ Preset,
8
+ ProbeError,
9
+ QualityProfile,
10
+ ResolutionCalculator,
11
+ TargetResolution,
12
+ VideoInfo,
13
+ VideoProbe,
14
+ )
15
+ from video_upscaler.engines import (
16
+ BaseEngine,
17
+ EngineUnavailableError,
18
+ FFmpegPrecisionEngine,
19
+ ProgressReporter,
20
+ RealESRGANEngine,
21
+ UpscaleConfig,
22
+ UpscaleError,
23
+ UpscaleResult,
24
+ Upscaler,
25
+ )
26
+
27
+ __version__ = "0.1.1"
28
+
29
+ __all__ = [
30
+ "__version__",
31
+ "Preset",
32
+ "FitStrategy",
33
+ "QualityProfile",
34
+ "DenoiseLevel",
35
+ "LowResolutionError",
36
+ "ProbeError",
37
+ "VideoInfo",
38
+ "TargetResolution",
39
+ "ResolutionCalculator",
40
+ "VideoProbe",
41
+ "BaseEngine",
42
+ "EngineUnavailableError",
43
+ "FFmpegPrecisionEngine",
44
+ "ProgressReporter",
45
+ "RealESRGANEngine",
46
+ "UpscaleConfig",
47
+ "UpscaleError",
48
+ "UpscaleResult",
49
+ "Upscaler",
50
+ ]
@@ -0,0 +1,170 @@
1
+ """CLI entrypoint and argument parser for video-upscale."""
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+ from typing import List, Optional
7
+
8
+ from video_upscaler import (
9
+ DenoiseLevel,
10
+ FitStrategy,
11
+ Preset,
12
+ QualityProfile,
13
+ UpscaleConfig,
14
+ Upscaler,
15
+ VideoProbe,
16
+ )
17
+
18
+
19
+ def _build_parser() -> argparse.ArgumentParser:
20
+ parser = argparse.ArgumentParser(
21
+ prog="video-upscale",
22
+ description="High-precision video upscaler using FFmpeg filter pipelines.",
23
+ )
24
+
25
+ parser.add_argument("input", help="Input video file path.")
26
+ parser.add_argument(
27
+ "-o", "--output",
28
+ help="Output video file path. Defaults to <input>_<preset>.mp4 next to the input.",
29
+ )
30
+
31
+ parser.add_argument(
32
+ "-p", "--preset",
33
+ choices=[p.value for p in Preset],
34
+ default=Preset.RES_1080P.value,
35
+ help="Target resolution preset (default: 1080p).",
36
+ )
37
+
38
+ parser.add_argument(
39
+ "--fit",
40
+ choices=[f.value for f in FitStrategy],
41
+ default=FitStrategy.FIT.value,
42
+ help="Canvas fit strategy: fit (default), pad, or crop.",
43
+ )
44
+
45
+ parser.add_argument(
46
+ "--quality",
47
+ choices=[q.value for q in QualityProfile],
48
+ default=QualityProfile.MEDIUM.value,
49
+ help="Encoding quality/speed trade-off (default: medium).",
50
+ )
51
+
52
+ parser.add_argument(
53
+ "--denoise",
54
+ choices=[d.value for d in DenoiseLevel],
55
+ default=DenoiseLevel.GENTLE.value,
56
+ help="Denoise filtering intensity (default: gentle).",
57
+ )
58
+
59
+ parser.add_argument(
60
+ "--no-sharpen",
61
+ action="store_true",
62
+ help="Disable the unsharp sharpening filter.",
63
+ )
64
+
65
+ parser.add_argument(
66
+ "--deband",
67
+ action="store_true",
68
+ help="Enable debanding filter to reduce gradient banding.",
69
+ )
70
+
71
+ parser.add_argument(
72
+ "--codec",
73
+ default="libx264",
74
+ help="Video codec (default: libx264).",
75
+ )
76
+
77
+ parser.add_argument(
78
+ "--scale",
79
+ type=float,
80
+ metavar="N",
81
+ help="Scale factor (e.g. 2 for 2x). Overrides --preset when set.",
82
+ )
83
+
84
+ parser.add_argument(
85
+ "--width",
86
+ type=int,
87
+ metavar="W",
88
+ help="Custom canvas width (requires --preset custom or --height).",
89
+ )
90
+
91
+ parser.add_argument(
92
+ "--height",
93
+ type=int,
94
+ metavar="H",
95
+ help="Custom canvas height (requires --preset custom or --width).",
96
+ )
97
+
98
+ parser.add_argument(
99
+ "--dci",
100
+ action="store_true",
101
+ help="Use DCI 2K (2048x1080) instead of QHD 2K (2560x1440) with --preset 2k.",
102
+ )
103
+
104
+ parser.add_argument(
105
+ "--allow-low-res",
106
+ action="store_true",
107
+ help="Allow upscaling inputs below 360p.",
108
+ )
109
+
110
+ return parser
111
+
112
+
113
+ def main(argv: Optional[List[str]] = None) -> int:
114
+ """Entry point for video-upscale CLI."""
115
+ parser = _build_parser()
116
+ args = parser.parse_args(argv)
117
+
118
+ input_path = Path(args.input).resolve()
119
+ if not input_path.is_file():
120
+ print(f"Error: input file not found: {input_path}", file=sys.stderr)
121
+ return 1
122
+
123
+ # Default output path: <stem>_<preset>.mp4 next to the input
124
+ if args.output:
125
+ output_path = Path(args.output).resolve()
126
+ else:
127
+ preset_tag = args.preset
128
+ if args.scale is not None:
129
+ preset_tag = f"{args.scale}x"
130
+ output_path = input_path.with_name(f"{input_path.stem}_{preset_tag}.mp4")
131
+
132
+ # Build config
133
+ preset = Preset.from_str(args.preset)
134
+ if args.scale is not None:
135
+ preset = Preset.CUSTOM
136
+
137
+ config = UpscaleConfig(
138
+ preset=preset,
139
+ fit=FitStrategy.from_str(args.fit),
140
+ quality=QualityProfile(args.quality),
141
+ denoise=DenoiseLevel(args.denoise),
142
+ sharpen=not args.no_sharpen,
143
+ deband=args.deband,
144
+ codec=args.codec,
145
+ allow_low_res=args.allow_low_res,
146
+ scale_factor=args.scale,
147
+ custom_w=args.width,
148
+ custom_h=args.height,
149
+ dci=args.dci,
150
+ )
151
+
152
+ upscaler = Upscaler(config)
153
+
154
+ try:
155
+ result = upscaler.upscale(
156
+ input_path,
157
+ output_path,
158
+ )
159
+ except Exception as exc: # noqa: BLE001 — surface any upscale failure cleanly
160
+ print(f"Error: {exc}", file=sys.stderr)
161
+ return 1
162
+
163
+ print(f"Upscaled: {result.output_path}")
164
+ print(f"Resolution: {result.width}x{result.height}")
165
+ print(f"Duration: {result.duration:.2f}s")
166
+ return 0
167
+
168
+
169
+ if __name__ == "__main__":
170
+ raise SystemExit(main())
@@ -0,0 +1,27 @@
1
+ """Core video inspection and calculation modules."""
2
+
3
+ from video_upscaler.core.calculator import ResolutionCalculator
4
+ from video_upscaler.core.probe import VideoProbe
5
+ from video_upscaler.core.types import (
6
+ DenoiseLevel,
7
+ FitStrategy,
8
+ LowResolutionError,
9
+ Preset,
10
+ ProbeError,
11
+ QualityProfile,
12
+ TargetResolution,
13
+ VideoInfo,
14
+ )
15
+
16
+ __all__ = [
17
+ "Preset",
18
+ "FitStrategy",
19
+ "QualityProfile",
20
+ "DenoiseLevel",
21
+ "LowResolutionError",
22
+ "ProbeError",
23
+ "VideoInfo",
24
+ "TargetResolution",
25
+ "ResolutionCalculator",
26
+ "VideoProbe",
27
+ ]
@@ -0,0 +1,199 @@
1
+ """Resolution calculation, aspect ratio management, and canvas fitting."""
2
+
3
+ from typing import Optional, Union
4
+
5
+ from video_upscaler.core.types import (
6
+ FitStrategy,
7
+ LowResolutionError,
8
+ Preset,
9
+ TargetResolution,
10
+ )
11
+
12
+
13
+ def _round_even(val: float) -> int:
14
+ """Round a floating-point dimension to the nearest even integer >= 2."""
15
+ rounded = int(round(val / 2.0)) * 2
16
+ return max(2, rounded)
17
+
18
+
19
+ class ResolutionCalculator:
20
+ """Calculates target video resolutions, scaling factors, padding, and cropping."""
21
+
22
+ MIN_360P_DIM = 360
23
+
24
+ @classmethod
25
+ def calculate_target_resolution(
26
+ cls,
27
+ source_w: int,
28
+ source_h: int,
29
+ preset: Optional[Union[Preset, str]] = None,
30
+ fit_strategy: Union[FitStrategy, str] = FitStrategy.FIT,
31
+ custom_w: Optional[int] = None,
32
+ custom_h: Optional[int] = None,
33
+ scale_factor: Optional[float] = None,
34
+ allow_low_res: bool = False,
35
+ dci: bool = False,
36
+ ) -> TargetResolution:
37
+ """Calculate target resolution, scaled dimensions, padding, or crop offsets.
38
+
39
+ Args:
40
+ source_w: Source video width in pixels.
41
+ source_h: Source video height in pixels.
42
+ preset: Standard preset (720p, 1080p, 2k, dci_2k, custom).
43
+ fit_strategy: FitStrategy (FIT, PAD, CROP). Default FIT.
44
+ custom_w: Optional custom canvas/target width.
45
+ custom_h: Optional custom canvas/target height.
46
+ scale_factor: Optional multiplier (e.g. 2.0 for 2x scale).
47
+ allow_low_res: If False, raises LowResolutionError for inputs < 360p.
48
+ dci: If True, uses DCI 2K (2048x1080) for 2K preset.
49
+
50
+ Returns:
51
+ TargetResolution containing target dimensions and transformation parameters.
52
+ """
53
+ if source_w <= 0 or source_h <= 0:
54
+ raise ValueError(f"Source dimensions must be positive integers, got {source_w}x{source_h}")
55
+
56
+ # Validate minimum 360p input
57
+ min_dim = min(source_w, source_h)
58
+ if min_dim < cls.MIN_360P_DIM and not allow_low_res:
59
+ raise LowResolutionError(
60
+ f"Input resolution {source_w}x{source_h} is below minimum 360p threshold "
61
+ f"({min_dim} < {cls.MIN_360P_DIM}). Use allow_low_res=True to override."
62
+ )
63
+
64
+ # Normalize fit strategy
65
+ if isinstance(fit_strategy, str):
66
+ fit_strategy = FitStrategy.from_str(fit_strategy)
67
+
68
+ # 1. Direct scale factor case
69
+ if scale_factor is not None:
70
+ scaled_w = _round_even(source_w * scale_factor)
71
+ scaled_h = _round_even(source_h * scale_factor)
72
+ return TargetResolution(
73
+ width=scaled_w,
74
+ height=scaled_h,
75
+ scaled_width=scaled_w,
76
+ scaled_height=scaled_h,
77
+ )
78
+
79
+ # Normalize preset
80
+ if isinstance(preset, str):
81
+ preset = Preset.from_str(preset)
82
+
83
+ is_vertical = source_h > source_w
84
+
85
+ # 2. Determine target canvas dimensions
86
+ if custom_w is not None and custom_h is not None:
87
+ canvas_w = _round_even(custom_w)
88
+ canvas_h = _round_even(custom_h)
89
+ elif custom_w is not None:
90
+ canvas_w = _round_even(custom_w)
91
+ canvas_h = _round_even(custom_w * (source_h / source_w))
92
+ elif custom_h is not None:
93
+ canvas_h = _round_even(custom_h)
94
+ canvas_w = _round_even(custom_h * (source_w / source_h))
95
+ else:
96
+ if preset is None:
97
+ preset = Preset.RES_1080P
98
+
99
+ if preset == Preset.RES_720P:
100
+ canvas_w, canvas_h = (720, 1280) if is_vertical else (1280, 720)
101
+ elif preset == Preset.RES_1080P:
102
+ canvas_w, canvas_h = (1080, 1920) if is_vertical else (1920, 1080)
103
+ elif preset == Preset.RES_2K:
104
+ if dci:
105
+ canvas_w, canvas_h = (1080, 2048) if is_vertical else (2048, 1080)
106
+ else:
107
+ canvas_w, canvas_h = (1440, 2560) if is_vertical else (2560, 1440)
108
+ elif preset == Preset.RES_DCI_2K:
109
+ canvas_w, canvas_h = (1080, 2048) if is_vertical else (2048, 1080)
110
+ elif preset == Preset.RES_4K:
111
+ if dci:
112
+ canvas_w, canvas_h = (2160, 4096) if is_vertical else (4096, 2160)
113
+ else:
114
+ canvas_w, canvas_h = (2160, 3840) if is_vertical else (3840, 2160)
115
+ elif preset == Preset.RES_DCI_4K:
116
+ canvas_w, canvas_h = (2160, 4096) if is_vertical else (4096, 2160)
117
+ elif preset == Preset.RES_8K:
118
+ if dci:
119
+ canvas_w, canvas_h = (4320, 8192) if is_vertical else (8192, 4320)
120
+ else:
121
+ canvas_w, canvas_h = (4320, 7680) if is_vertical else (7680, 4320)
122
+ elif preset == Preset.RES_DCI_8K:
123
+ canvas_w, canvas_h = (4320, 8192) if is_vertical else (8192, 4320)
124
+ elif preset == Preset.CUSTOM:
125
+ raise ValueError("Preset.CUSTOM requires explicit custom_w and custom_h or scale_factor")
126
+ else:
127
+ raise ValueError(f"Unsupported preset: {preset}")
128
+
129
+ # 3. Apply fit strategy
130
+ if fit_strategy == FitStrategy.FIT:
131
+ # If explicit custom_w and custom_h were specified, use them directly
132
+ if custom_w is not None and custom_h is not None:
133
+ return TargetResolution(
134
+ width=canvas_w,
135
+ height=canvas_h,
136
+ scaled_width=canvas_w,
137
+ scaled_height=canvas_h,
138
+ )
139
+
140
+ # Preserve source aspect ratio anchored to target height (landscape) or width (portrait)
141
+ if is_vertical:
142
+ target_w = canvas_w
143
+ target_h = _round_even(canvas_w * (source_h / source_w))
144
+ else:
145
+ target_h = canvas_h
146
+ target_w = _round_even(canvas_h * (source_w / source_h))
147
+
148
+ return TargetResolution(
149
+ width=target_w,
150
+ height=target_h,
151
+ scaled_width=target_w,
152
+ scaled_height=target_h,
153
+ )
154
+
155
+ elif fit_strategy == FitStrategy.PAD:
156
+ # Scale video to fit within canvas bounds, pad the remainder
157
+ scale = min(canvas_w / source_w, canvas_h / source_h)
158
+ scaled_w = min(canvas_w, _round_even(source_w * scale))
159
+ scaled_h = min(canvas_h, _round_even(source_h * scale))
160
+
161
+ pad_total_x = canvas_w - scaled_w
162
+ pad_total_y = canvas_h - scaled_h
163
+
164
+ pad_x = _round_even(pad_total_x / 2.0) if pad_total_x >= 2 else 0
165
+ pad_y = _round_even(pad_total_y / 2.0) if pad_total_y >= 2 else 0
166
+
167
+ return TargetResolution(
168
+ width=canvas_w,
169
+ height=canvas_h,
170
+ scaled_width=scaled_w,
171
+ scaled_height=scaled_h,
172
+ pad_x=pad_x,
173
+ pad_y=pad_y,
174
+ )
175
+
176
+ elif fit_strategy == FitStrategy.CROP:
177
+ # Scale video to cover canvas bounds, center-crop overflow
178
+ scale = max(canvas_w / source_w, canvas_h / source_h)
179
+ scaled_w = max(canvas_w, _round_even(source_w * scale))
180
+ scaled_h = max(canvas_h, _round_even(source_h * scale))
181
+
182
+ crop_total_x = scaled_w - canvas_w
183
+ crop_total_y = scaled_h - canvas_h
184
+
185
+ crop_x = _round_even(crop_total_x / 2.0) if crop_total_x >= 2 else 0
186
+ crop_y = _round_even(crop_total_y / 2.0) if crop_total_y >= 2 else 0
187
+
188
+ return TargetResolution(
189
+ width=canvas_w,
190
+ height=canvas_h,
191
+ scaled_width=scaled_w,
192
+ scaled_height=scaled_h,
193
+ crop_x=crop_x,
194
+ crop_y=crop_y,
195
+ crop_w=canvas_w,
196
+ crop_h=canvas_h,
197
+ )
198
+
199
+ raise ValueError(f"Unknown fit strategy: {fit_strategy}")
@@ -0,0 +1,182 @@
1
+ """FFprobe metadata extraction and media inspection."""
2
+
3
+ import json
4
+ import subprocess
5
+ from pathlib import Path
6
+ from typing import Any, Dict, Optional, Union
7
+
8
+ from video_upscaler.core.types import ProbeError, VideoInfo
9
+
10
+
11
+ class VideoProbe:
12
+ """Probes media files using ffprobe to extract stream, codec, and timing metadata."""
13
+
14
+ @classmethod
15
+ def probe(cls, path: Union[str, Path]) -> VideoInfo:
16
+ """Probe a video file on disk using ffprobe.
17
+
18
+ Args:
19
+ path: Path to the media file.
20
+
21
+ Returns:
22
+ VideoInfo with extracted streams, codec, resolution, and timing metadata.
23
+
24
+ Raises:
25
+ FileNotFoundError: If the media file does not exist.
26
+ ProbeError: If ffprobe fails, produces invalid output, or no video stream exists.
27
+ """
28
+ p = Path(path).resolve()
29
+ if not p.exists() or not p.is_file():
30
+ raise FileNotFoundError(f"Media file not found: {path}")
31
+
32
+ cmd = [
33
+ "ffprobe",
34
+ "-v",
35
+ "quiet",
36
+ "-print_format",
37
+ "json",
38
+ "-show_format",
39
+ "-show_streams",
40
+ str(p),
41
+ ]
42
+
43
+ try:
44
+ proc = subprocess.run(
45
+ cmd,
46
+ stdout=subprocess.PIPE,
47
+ stderr=subprocess.PIPE,
48
+ text=True,
49
+ check=False,
50
+ shell=False,
51
+ )
52
+ except FileNotFoundError:
53
+ raise ProbeError("ffprobe executable not found on system PATH. Please ensure ffmpeg is installed.")
54
+ except Exception as e:
55
+ raise ProbeError(f"Failed to execute ffprobe: {e}") from e
56
+
57
+ if proc.returncode != 0:
58
+ err = proc.stderr.strip() or f"ffprobe exited with status {proc.returncode}"
59
+ raise ProbeError(f"ffprobe failed for {p}: {err}")
60
+
61
+ return cls.parse_probe_json(proc.stdout, path=p)
62
+
63
+ @classmethod
64
+ def parse_probe_json(
65
+ cls,
66
+ data: Union[str, Dict[str, Any]],
67
+ path: Optional[Union[str, Path]] = None,
68
+ ) -> VideoInfo:
69
+ """Parse raw ffprobe JSON output into a VideoInfo dataclass.
70
+
71
+ Args:
72
+ data: Raw JSON string or deserialized dict from ffprobe.
73
+ path: Optional file path to associate with the VideoInfo.
74
+
75
+ Returns:
76
+ VideoInfo dataclass.
77
+
78
+ Raises:
79
+ ProbeError: If JSON is invalid or no video stream is present.
80
+ """
81
+ if isinstance(data, str):
82
+ try:
83
+ data = json.loads(data)
84
+ except Exception as e:
85
+ raise ProbeError(f"Invalid ffprobe JSON output: {e}") from e
86
+
87
+ if not isinstance(data, dict):
88
+ raise ProbeError("Malformed probe data: expected JSON object")
89
+
90
+ streams = data.get("streams", [])
91
+ video_stream: Optional[Dict[str, Any]] = None
92
+ audio_stream: Optional[Dict[str, Any]] = None
93
+
94
+ for stream in streams:
95
+ codec_type = stream.get("codec_type")
96
+ if codec_type == "video" and video_stream is None:
97
+ video_stream = stream
98
+ elif codec_type == "audio" and audio_stream is None:
99
+ audio_stream = stream
100
+
101
+ if video_stream is None:
102
+ raise ProbeError(f"No video stream found in media file: {path or 'unknown'}")
103
+
104
+ width = int(video_stream.get("width", 0))
105
+ height = int(video_stream.get("height", 0))
106
+ codec = str(video_stream.get("codec_name", "unknown"))
107
+ pix_fmt = str(video_stream.get("pix_fmt", "unknown"))
108
+
109
+ # Frame rate parsing
110
+ fps = cls._parse_fps(video_stream.get("r_frame_rate"))
111
+ if fps == 0.0:
112
+ fps = cls._parse_fps(video_stream.get("avg_frame_rate"))
113
+
114
+ # Duration parsing
115
+ duration_raw = video_stream.get("duration") or data.get("format", {}).get("duration")
116
+ try:
117
+ duration = float(duration_raw) if duration_raw is not None else 0.0
118
+ except (ValueError, TypeError):
119
+ duration = 0.0
120
+
121
+ # Bitrate parsing
122
+ bitrate_raw = video_stream.get("bit_rate") or data.get("format", {}).get("bit_rate")
123
+ try:
124
+ bitrate = int(bitrate_raw) if bitrate_raw is not None else None
125
+ except (ValueError, TypeError):
126
+ bitrate = None
127
+
128
+ aspect_ratio = video_stream.get("display_aspect_ratio")
129
+ color_space = video_stream.get("color_space")
130
+
131
+ # Total frames parsing
132
+ nb_frames_raw = video_stream.get("nb_frames")
133
+ try:
134
+ total_frames = int(nb_frames_raw) if nb_frames_raw is not None else None
135
+ except (ValueError, TypeError):
136
+ total_frames = None
137
+
138
+ # Audio stream info
139
+ audio_codec = None
140
+ audio_channels = None
141
+ if audio_stream is not None:
142
+ audio_codec = audio_stream.get("codec_name")
143
+ try:
144
+ audio_channels = int(audio_stream["channels"]) if "channels" in audio_stream else None
145
+ except (ValueError, TypeError):
146
+ audio_channels = None
147
+
148
+ media_path = Path(path) if path else Path(data.get("format", {}).get("filename", "unknown"))
149
+
150
+ return VideoInfo(
151
+ path=media_path,
152
+ width=width,
153
+ height=height,
154
+ duration=duration,
155
+ fps=fps,
156
+ codec=codec,
157
+ pix_fmt=pix_fmt,
158
+ bitrate=bitrate,
159
+ audio_codec=audio_codec,
160
+ audio_channels=audio_channels,
161
+ aspect_ratio=aspect_ratio,
162
+ color_space=color_space,
163
+ total_frames=total_frames,
164
+ )
165
+
166
+ @staticmethod
167
+ def _parse_fps(fps_val: Optional[Union[str, float, int]]) -> float:
168
+ """Parse fractional or float fps strings (e.g. '30000/1001', '24/1', '29.97')."""
169
+ if not fps_val:
170
+ return 0.0
171
+ if isinstance(fps_val, (int, float)):
172
+ return float(fps_val)
173
+ fps_str = str(fps_val).strip()
174
+ try:
175
+ if "/" in fps_str:
176
+ num_str, den_str = fps_str.split("/", 1)
177
+ num = float(num_str)
178
+ den = float(den_str)
179
+ return (num / den) if den != 0.0 else 0.0
180
+ return float(fps_str)
181
+ except (ValueError, ZeroDivisionError):
182
+ return 0.0