video-upscaler-cli 0.1.1__py3-none-any.whl
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.
- video_upscaler/__init__.py +50 -0
- video_upscaler/cli/__init__.py +170 -0
- video_upscaler/core/__init__.py +27 -0
- video_upscaler/core/calculator.py +199 -0
- video_upscaler/core/probe.py +182 -0
- video_upscaler/core/types.py +133 -0
- video_upscaler/engines/__init__.py +27 -0
- video_upscaler/engines/base.py +62 -0
- video_upscaler/engines/ffmpeg.py +123 -0
- video_upscaler/engines/progress.py +30 -0
- video_upscaler/engines/realesrgan.py +48 -0
- video_upscaler/filters/__init__.py +5 -0
- video_upscaler/filters/chain.py +78 -0
- video_upscaler_cli-0.1.1.dist-info/METADATA +17 -0
- video_upscaler_cli-0.1.1.dist-info/RECORD +18 -0
- video_upscaler_cli-0.1.1.dist-info/WHEEL +5 -0
- video_upscaler_cli-0.1.1.dist-info/entry_points.txt +2 -0
- video_upscaler_cli-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -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
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Data types, Enums, and exceptions for video_upscaler core."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Iterator, Optional, Tuple
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Preset(str, Enum):
|
|
10
|
+
"""Standard target resolution presets."""
|
|
11
|
+
RES_720P = "720p"
|
|
12
|
+
RES_1080P = "1080p"
|
|
13
|
+
RES_2K = "2k"
|
|
14
|
+
RES_DCI_2K = "dci_2k"
|
|
15
|
+
RES_4K = "4k"
|
|
16
|
+
RES_DCI_4K = "dci_4k"
|
|
17
|
+
RES_8K = "8k"
|
|
18
|
+
RES_DCI_8K = "dci_8k"
|
|
19
|
+
CUSTOM = "custom"
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def from_str(cls, value: str) -> "Preset":
|
|
23
|
+
normalized = value.strip().lower()
|
|
24
|
+
for member in cls:
|
|
25
|
+
if member.value == normalized or member.name.lower() == normalized:
|
|
26
|
+
return member
|
|
27
|
+
raise ValueError(f"Unknown preset '{value}'. Supported: {[p.value for p in cls]}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class FitStrategy(str, Enum):
|
|
31
|
+
"""Strategy for fitting source video into target bounding box or canvas."""
|
|
32
|
+
FIT = "fit"
|
|
33
|
+
PAD = "pad"
|
|
34
|
+
CROP = "crop"
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def from_str(cls, value: str) -> "FitStrategy":
|
|
38
|
+
normalized = value.strip().lower()
|
|
39
|
+
for member in cls:
|
|
40
|
+
if member.value == normalized or member.name.lower() == normalized:
|
|
41
|
+
return member
|
|
42
|
+
raise ValueError(f"Unknown fit strategy '{value}'. Supported: {[f.value for f in cls]}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class QualityProfile(str, Enum):
|
|
46
|
+
"""Quality and speed trade-off profiles."""
|
|
47
|
+
FAST = "fast"
|
|
48
|
+
MEDIUM = "medium"
|
|
49
|
+
HIGH = "high"
|
|
50
|
+
BEST = "best"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class DenoiseLevel(str, Enum):
|
|
54
|
+
"""Denoise filtering intensity."""
|
|
55
|
+
NONE = "none"
|
|
56
|
+
GENTLE = "gentle"
|
|
57
|
+
MEDIUM = "medium"
|
|
58
|
+
STRONG = "strong"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class LowResolutionError(ValueError):
|
|
62
|
+
"""Raised when input video resolution is below minimum allowed threshold (360p)."""
|
|
63
|
+
pass
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ProbeError(RuntimeError):
|
|
67
|
+
"""Raised when probing video metadata fails or media contains no video stream."""
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class VideoInfo:
|
|
73
|
+
"""Metadata container for a probed video file."""
|
|
74
|
+
path: Path
|
|
75
|
+
width: int
|
|
76
|
+
height: int
|
|
77
|
+
duration: float
|
|
78
|
+
fps: float
|
|
79
|
+
codec: str
|
|
80
|
+
pix_fmt: str
|
|
81
|
+
bitrate: Optional[int] = None
|
|
82
|
+
audio_codec: Optional[str] = None
|
|
83
|
+
audio_channels: Optional[int] = None
|
|
84
|
+
aspect_ratio: Optional[str] = None
|
|
85
|
+
color_space: Optional[str] = None
|
|
86
|
+
total_frames: Optional[int] = None
|
|
87
|
+
|
|
88
|
+
def __post_init__(self) -> None:
|
|
89
|
+
if not isinstance(self.path, Path):
|
|
90
|
+
self.path = Path(self.path)
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def is_vertical(self) -> bool:
|
|
94
|
+
"""True if height is strictly greater than width (portrait orientation)."""
|
|
95
|
+
return self.height > self.width
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def aspect_ratio_float(self) -> float:
|
|
99
|
+
"""Aspect ratio as float (width / height)."""
|
|
100
|
+
return self.width / self.height if self.height else 0.0
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def resolution(self) -> Tuple[int, int]:
|
|
104
|
+
"""(width, height) tuple."""
|
|
105
|
+
return (self.width, self.height)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True)
|
|
109
|
+
class TargetResolution:
|
|
110
|
+
"""Calculated target resolution and transformation parameters."""
|
|
111
|
+
width: int
|
|
112
|
+
height: int
|
|
113
|
+
scaled_width: int
|
|
114
|
+
scaled_height: int
|
|
115
|
+
pad_x: int = 0
|
|
116
|
+
pad_y: int = 0
|
|
117
|
+
crop_x: int = 0
|
|
118
|
+
crop_y: int = 0
|
|
119
|
+
crop_w: int = 0
|
|
120
|
+
crop_h: int = 0
|
|
121
|
+
|
|
122
|
+
def __iter__(self) -> Iterator[int]:
|
|
123
|
+
"""Allow tuple unpacking (w, h) = target_resolution."""
|
|
124
|
+
yield self.width
|
|
125
|
+
yield self.height
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def is_padded(self) -> bool:
|
|
129
|
+
return self.pad_x > 0 or self.pad_y > 0
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def is_cropped(self) -> bool:
|
|
133
|
+
return self.crop_w > 0 and (self.crop_w < self.scaled_width or self.crop_h < self.scaled_height)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Upscale engines and public upscaler API."""
|
|
2
|
+
|
|
3
|
+
from video_upscaler.engines.base import (
|
|
4
|
+
BaseEngine,
|
|
5
|
+
EngineUnavailableError,
|
|
6
|
+
UpscaleConfig,
|
|
7
|
+
UpscaleError,
|
|
8
|
+
UpscaleResult,
|
|
9
|
+
)
|
|
10
|
+
from video_upscaler.engines.ffmpeg import FFmpegPrecisionEngine
|
|
11
|
+
from video_upscaler.engines.progress import ProgressReporter
|
|
12
|
+
from video_upscaler.engines.realesrgan import RealESRGANEngine
|
|
13
|
+
|
|
14
|
+
# Public facade: the ffmpeg precision engine is the default upscaler.
|
|
15
|
+
Upscaler = FFmpegPrecisionEngine
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"BaseEngine",
|
|
19
|
+
"EngineUnavailableError",
|
|
20
|
+
"FFmpegPrecisionEngine",
|
|
21
|
+
"ProgressReporter",
|
|
22
|
+
"RealESRGANEngine",
|
|
23
|
+
"UpscaleConfig",
|
|
24
|
+
"UpscaleError",
|
|
25
|
+
"UpscaleResult",
|
|
26
|
+
"Upscaler",
|
|
27
|
+
]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Base engine contract, shared config/result types, and engine exceptions."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Callable, Optional, Tuple, Union
|
|
7
|
+
|
|
8
|
+
from video_upscaler.core.types import DenoiseLevel, FitStrategy, Preset, QualityProfile
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EngineUnavailableError(RuntimeError):
|
|
12
|
+
"""Raised when an engine's required external binary is not available."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class UpscaleError(RuntimeError):
|
|
16
|
+
"""Raised when the upscale subprocess fails."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class UpscaleConfig:
|
|
21
|
+
"""User-facing configuration for an upscale run."""
|
|
22
|
+
|
|
23
|
+
preset: Preset = Preset.RES_1080P
|
|
24
|
+
fit: FitStrategy = FitStrategy.FIT
|
|
25
|
+
quality: QualityProfile = QualityProfile.MEDIUM
|
|
26
|
+
denoise: DenoiseLevel = DenoiseLevel.GENTLE
|
|
27
|
+
sharpen: bool = True
|
|
28
|
+
deband: bool = False
|
|
29
|
+
codec: str = "libx264"
|
|
30
|
+
allow_low_res: bool = False
|
|
31
|
+
scale_factor: Optional[float] = None
|
|
32
|
+
custom_w: Optional[int] = None
|
|
33
|
+
custom_h: Optional[int] = None
|
|
34
|
+
dci: bool = False
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class UpscaleResult:
|
|
39
|
+
"""Outcome of a successful upscale run."""
|
|
40
|
+
|
|
41
|
+
output_path: Path
|
|
42
|
+
width: int
|
|
43
|
+
height: int
|
|
44
|
+
duration: float
|
|
45
|
+
input_path: Path
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def resolution(self) -> Tuple[int, int]:
|
|
49
|
+
return (self.width, self.height)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class BaseEngine(ABC):
|
|
53
|
+
"""Common interface for upscale engines."""
|
|
54
|
+
|
|
55
|
+
@abstractmethod
|
|
56
|
+
def upscale(
|
|
57
|
+
self,
|
|
58
|
+
input_path: Union[str, Path],
|
|
59
|
+
output_path: Union[str, Path],
|
|
60
|
+
progress_callback: Optional[Callable[[float, str], None]] = None,
|
|
61
|
+
) -> UpscaleResult:
|
|
62
|
+
"""Upscale input_path into output_path, reporting progress as (percent, message)."""
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""FFmpeg precision upscale engine."""
|
|
2
|
+
|
|
3
|
+
import subprocess
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Callable, List, Optional, Union
|
|
6
|
+
|
|
7
|
+
from video_upscaler.core.calculator import ResolutionCalculator
|
|
8
|
+
from video_upscaler.core.probe import VideoProbe
|
|
9
|
+
from video_upscaler.core.types import QualityProfile, VideoInfo
|
|
10
|
+
|
|
11
|
+
from video_upscaler.engines.base import (
|
|
12
|
+
BaseEngine,
|
|
13
|
+
UpscaleConfig,
|
|
14
|
+
UpscaleError,
|
|
15
|
+
UpscaleResult,
|
|
16
|
+
)
|
|
17
|
+
from video_upscaler.engines.progress import ProgressReporter
|
|
18
|
+
|
|
19
|
+
# QualityProfile -> (x264 preset, CRF)
|
|
20
|
+
_QUALITY_MAP = {
|
|
21
|
+
QualityProfile.FAST.value: ("veryfast", 20),
|
|
22
|
+
QualityProfile.MEDIUM.value: ("medium", 18),
|
|
23
|
+
QualityProfile.HIGH.value: ("slow", 16),
|
|
24
|
+
QualityProfile.BEST.value: ("slower", 14),
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
FilterChainFn = Callable[..., str]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _default_filter_chain_fn(
|
|
31
|
+
target_w: int,
|
|
32
|
+
target_h: int,
|
|
33
|
+
denoise: str = "gentle",
|
|
34
|
+
sharpen: bool = True,
|
|
35
|
+
deband: bool = False,
|
|
36
|
+
) -> str:
|
|
37
|
+
# Lazy import: filters.chain may be delivered by a parallel workstream.
|
|
38
|
+
from video_upscaler.filters.chain import build_filter_chain
|
|
39
|
+
|
|
40
|
+
return build_filter_chain(target_w, target_h, denoise=denoise, sharpen=sharpen, deband=deband)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class FFmpegPrecisionEngine(BaseEngine):
|
|
44
|
+
"""Upscales video via a single ffmpeg invocation with precision filters."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, config: UpscaleConfig, filter_chain_fn: Optional[FilterChainFn] = None) -> None:
|
|
47
|
+
self.config = config
|
|
48
|
+
self._filter_chain_fn = filter_chain_fn
|
|
49
|
+
|
|
50
|
+
def build_command(
|
|
51
|
+
self,
|
|
52
|
+
input_path: Union[str, Path],
|
|
53
|
+
output_path: Union[str, Path],
|
|
54
|
+
video_info: VideoInfo,
|
|
55
|
+
chain: str,
|
|
56
|
+
) -> List[str]:
|
|
57
|
+
"""Assemble the full ffmpeg argument list from config, probe info, and -vf chain."""
|
|
58
|
+
x264_preset, crf = _QUALITY_MAP[QualityProfile(self.config.quality).value]
|
|
59
|
+
cmd = [
|
|
60
|
+
"ffmpeg",
|
|
61
|
+
"-y",
|
|
62
|
+
"-i",
|
|
63
|
+
str(input_path),
|
|
64
|
+
"-vf",
|
|
65
|
+
chain,
|
|
66
|
+
"-c:v",
|
|
67
|
+
self.config.codec,
|
|
68
|
+
"-preset",
|
|
69
|
+
x264_preset,
|
|
70
|
+
"-crf",
|
|
71
|
+
str(crf),
|
|
72
|
+
]
|
|
73
|
+
if video_info.audio_codec is not None:
|
|
74
|
+
cmd += ["-c:a", "copy"]
|
|
75
|
+
cmd += ["-pix_fmt", "yuv420p", str(output_path)]
|
|
76
|
+
return cmd
|
|
77
|
+
|
|
78
|
+
def upscale(
|
|
79
|
+
self,
|
|
80
|
+
input_path: Union[str, Path],
|
|
81
|
+
output_path: Union[str, Path],
|
|
82
|
+
progress_callback: Optional[Callable[[float, str], None]] = None,
|
|
83
|
+
) -> UpscaleResult:
|
|
84
|
+
info = VideoProbe.probe(input_path)
|
|
85
|
+
# LowResolutionError propagates from here unless config.allow_low_res.
|
|
86
|
+
target = ResolutionCalculator.calculate_target_resolution(
|
|
87
|
+
source_w=info.width,
|
|
88
|
+
source_h=info.height,
|
|
89
|
+
preset=self.config.preset,
|
|
90
|
+
fit_strategy=self.config.fit,
|
|
91
|
+
custom_w=self.config.custom_w,
|
|
92
|
+
custom_h=self.config.custom_h,
|
|
93
|
+
scale_factor=self.config.scale_factor,
|
|
94
|
+
allow_low_res=self.config.allow_low_res,
|
|
95
|
+
dci=self.config.dci,
|
|
96
|
+
)
|
|
97
|
+
chain_fn = self._filter_chain_fn or _default_filter_chain_fn
|
|
98
|
+
chain = chain_fn(
|
|
99
|
+
target.width,
|
|
100
|
+
target.height,
|
|
101
|
+
denoise=self.config.denoise.value,
|
|
102
|
+
sharpen=self.config.sharpen,
|
|
103
|
+
deband=self.config.deband,
|
|
104
|
+
)
|
|
105
|
+
cmd = self.build_command(input_path, output_path, info, chain)
|
|
106
|
+
|
|
107
|
+
reporter = ProgressReporter(info.duration, progress_callback)
|
|
108
|
+
stderr_lines: List[str] = []
|
|
109
|
+
proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
|
|
110
|
+
for line in proc.stderr:
|
|
111
|
+
stderr_lines.append(line)
|
|
112
|
+
reporter.report(line)
|
|
113
|
+
if proc.wait() != 0:
|
|
114
|
+
tail = "".join(stderr_lines[-5:]).strip()
|
|
115
|
+
raise UpscaleError(f"ffmpeg failed with exit code {proc.returncode}: {tail}")
|
|
116
|
+
|
|
117
|
+
return UpscaleResult(
|
|
118
|
+
output_path=Path(output_path),
|
|
119
|
+
width=target.width,
|
|
120
|
+
height=target.height,
|
|
121
|
+
duration=info.duration,
|
|
122
|
+
input_path=Path(input_path),
|
|
123
|
+
)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Progress parsing for ffmpeg stderr output."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import Callable, Optional
|
|
5
|
+
|
|
6
|
+
_TIME_RE = re.compile(r"time=(\d+):(\d+):(\d+(?:\.\d+)?)")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ProgressReporter:
|
|
10
|
+
"""Parses ffmpeg stderr lines and reports completion percent via callback."""
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
total_duration: float,
|
|
15
|
+
progress_callback: Optional[Callable[[float, str], None]] = None,
|
|
16
|
+
) -> None:
|
|
17
|
+
self.total_duration = max(total_duration, 0.0)
|
|
18
|
+
self.progress_callback = progress_callback
|
|
19
|
+
|
|
20
|
+
def report(self, line: str) -> None:
|
|
21
|
+
"""Parse one stderr line; invoke callback when a time= stamp is present."""
|
|
22
|
+
if self.progress_callback is None or self.total_duration <= 0:
|
|
23
|
+
return
|
|
24
|
+
match = _TIME_RE.search(line)
|
|
25
|
+
if match is None:
|
|
26
|
+
return
|
|
27
|
+
hours, minutes, seconds = match.groups()
|
|
28
|
+
elapsed = int(hours) * 3600 + int(minutes) * 60 + float(seconds)
|
|
29
|
+
percent = min(100.0, max(0.0, elapsed / self.total_duration * 100.0))
|
|
30
|
+
self.progress_callback(percent, line)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Real-ESRGAN (ncnn-vulkan) engine adapter."""
|
|
2
|
+
|
|
3
|
+
import shutil
|
|
4
|
+
import subprocess
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Callable, Optional, Union
|
|
7
|
+
|
|
8
|
+
from video_upscaler.core.probe import VideoProbe
|
|
9
|
+
|
|
10
|
+
from video_upscaler.engines.base import (
|
|
11
|
+
BaseEngine,
|
|
12
|
+
EngineUnavailableError,
|
|
13
|
+
UpscaleConfig,
|
|
14
|
+
UpscaleResult,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
BINARY = "realesrgan-ncnn-vulkan"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RealESRGANEngine(BaseEngine):
|
|
21
|
+
"""Thin adapter around the realesrgan-ncnn-vulkan binary."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, config: UpscaleConfig) -> None:
|
|
24
|
+
self.config = config
|
|
25
|
+
|
|
26
|
+
@staticmethod
|
|
27
|
+
def is_available() -> bool:
|
|
28
|
+
return shutil.which(BINARY) is not None
|
|
29
|
+
|
|
30
|
+
def upscale(
|
|
31
|
+
self,
|
|
32
|
+
input_path: Union[str, Path],
|
|
33
|
+
output_path: Union[str, Path],
|
|
34
|
+
progress_callback: Optional[Callable[[float, str], None]] = None,
|
|
35
|
+
) -> UpscaleResult:
|
|
36
|
+
if not self.is_available():
|
|
37
|
+
raise EngineUnavailableError(
|
|
38
|
+
f"'{BINARY}' not found on PATH. Install it or use the ffmpeg precision engine."
|
|
39
|
+
)
|
|
40
|
+
subprocess.run([BINARY, "-i", str(input_path), "-o", str(output_path)], check=True)
|
|
41
|
+
info = VideoProbe.probe(output_path)
|
|
42
|
+
return UpscaleResult(
|
|
43
|
+
output_path=Path(output_path),
|
|
44
|
+
width=info.width,
|
|
45
|
+
height=info.height,
|
|
46
|
+
duration=info.duration,
|
|
47
|
+
input_path=Path(input_path),
|
|
48
|
+
)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Precision filter chain builder (SPEC.md §3).
|
|
2
|
+
|
|
3
|
+
Assembles the ffmpeg video filter chain: denoise -> scale (lanczos) ->
|
|
4
|
+
sharpen -> deband, comma-joined for use with `-vf`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import List
|
|
8
|
+
|
|
9
|
+
_DENOISE_FILTERS = {
|
|
10
|
+
"none": None,
|
|
11
|
+
"gentle": "hqdn3d=1.5:1.5:3:3",
|
|
12
|
+
"medium": "hqdn3d=3:3:6:6",
|
|
13
|
+
"strong": "atadenoise",
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
_SHARPEN_FILTER = "unsharp=lx=5:ly=5:la=0.6:cx=3:cy=3:ca=0.3"
|
|
17
|
+
_DEBAND_FILTER = "deband=1:64:16:16"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _denoise_filter(denoise: str) -> str | None:
|
|
21
|
+
try:
|
|
22
|
+
return _DENOISE_FILTERS[denoise]
|
|
23
|
+
except KeyError:
|
|
24
|
+
raise ValueError(
|
|
25
|
+
f"Unknown denoise level '{denoise}'. "
|
|
26
|
+
f"Supported: {sorted(k for k in _DENOISE_FILTERS)}"
|
|
27
|
+
) from None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _scale_filter(target_w: int, target_h: int) -> str:
|
|
31
|
+
if not isinstance(target_w, int) or not isinstance(target_h, int):
|
|
32
|
+
raise ValueError("target_w and target_h must be integers")
|
|
33
|
+
if target_w <= 0 or target_h <= 0:
|
|
34
|
+
raise ValueError("target_w and target_h must be positive")
|
|
35
|
+
if target_w % 2 != 0 or target_h % 2 != 0:
|
|
36
|
+
raise ValueError(
|
|
37
|
+
"target_w and target_h must be even "
|
|
38
|
+
"(required by 4:2:0 chroma subsampling)"
|
|
39
|
+
)
|
|
40
|
+
return (
|
|
41
|
+
f"scale={target_w}:{target_h}:"
|
|
42
|
+
"flags=lanczos+accurate_rnd+full_chroma_int+full_chroma_inp"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def build_filter_chain(
|
|
47
|
+
target_w: int,
|
|
48
|
+
target_h: int,
|
|
49
|
+
denoise: str = "gentle",
|
|
50
|
+
sharpen: bool = True,
|
|
51
|
+
deband: bool = False,
|
|
52
|
+
) -> str:
|
|
53
|
+
"""Build the ffmpeg video filter chain for upscaling.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
target_w: Target width in pixels (positive, even).
|
|
57
|
+
target_h: Target height in pixels (positive, even).
|
|
58
|
+
denoise: One of "none" | "gentle" | "medium" | "strong".
|
|
59
|
+
sharpen: Append the unsharp detail-restoration filter.
|
|
60
|
+
deband: Append the gradient-debanding filter.
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
Comma-joined filter chain string (video filters only), usable
|
|
64
|
+
directly with ffmpeg's `-vf` option.
|
|
65
|
+
|
|
66
|
+
Raises:
|
|
67
|
+
ValueError: On unknown denoise level or invalid target dimensions.
|
|
68
|
+
"""
|
|
69
|
+
stages: List[str] = []
|
|
70
|
+
denoise_filter = _denoise_filter(denoise)
|
|
71
|
+
if denoise_filter is not None:
|
|
72
|
+
stages.append(denoise_filter)
|
|
73
|
+
stages.append(_scale_filter(target_w, target_h))
|
|
74
|
+
if sharpen:
|
|
75
|
+
stages.append(_SHARPEN_FILTER)
|
|
76
|
+
if deband:
|
|
77
|
+
stages.append(_DEBAND_FILTER)
|
|
78
|
+
return ",".join(stages)
|
|
@@ -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,18 @@
|
|
|
1
|
+
video_upscaler/__init__.py,sha256=61yNUf15Le4yI0vqPLDPFLFA6a_z3SuYqM54hR5fo8k,984
|
|
2
|
+
video_upscaler/cli/__init__.py,sha256=eIM3FsIidq8lTvxUvOe6Z8LXmiKoEsMxibYyrNICY2I,4525
|
|
3
|
+
video_upscaler/core/__init__.py,sha256=A3QtwhEGrdckvBk92p3OKryMRpnB_75iusCklrzYGDQ,574
|
|
4
|
+
video_upscaler/core/calculator.py,sha256=_TMm7jgnsMy1SjvlzVxjBYOPLZ3uBoNxTSJ7US_GFMs,8041
|
|
5
|
+
video_upscaler/core/probe.py,sha256=8PqPARxpt8BYjGv3IMcT9BugRAA3KuGt-Fm-qFwsGL4,6297
|
|
6
|
+
video_upscaler/core/types.py,sha256=JnfLF5WRWqT92Cre45HWQ08znZCgzmONsl_jZBgBrBk,3648
|
|
7
|
+
video_upscaler/engines/__init__.py,sha256=2GMfoVyx6Nl2vnSIIxg6p1uVHngCi4fMYd8tlNBVJkU,702
|
|
8
|
+
video_upscaler/engines/base.py,sha256=ZpWAx4FS8CXnhHSxzW6it3VMscb0GAnaV54fIVtJpxk,1707
|
|
9
|
+
video_upscaler/engines/ffmpeg.py,sha256=sFP6kvdII7g041OGUy6yZ3K-iT4Xp4Ex2OpMYRikUiI,4140
|
|
10
|
+
video_upscaler/engines/progress.py,sha256=WGYmK0w5xgbTES2HFZeoCFK-y1PhPyRWnCjgZ_m3Kuk,1070
|
|
11
|
+
video_upscaler/engines/realesrgan.py,sha256=LjpHI1VxiGSX2mSr8m8jIkOd3YAJ0hzuKiGZA-Xwsgc,1404
|
|
12
|
+
video_upscaler/filters/__init__.py,sha256=7XBCjwNdhn9lrYwfyLJAOwuCTpmKB3AQczJuMEqbJIc,150
|
|
13
|
+
video_upscaler/filters/chain.py,sha256=dZEtESqsksSVEmbNcQD3B6qXSbQRQj7roeHgaJYJkeA,2424
|
|
14
|
+
video_upscaler_cli-0.1.1.dist-info/METADATA,sha256=BOAw-g_hf524fCxy3cHUaaNSmOW9at47THulGKWxPFg,603
|
|
15
|
+
video_upscaler_cli-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
16
|
+
video_upscaler_cli-0.1.1.dist-info/entry_points.txt,sha256=qOooki0vHp-ftMmurwEcjriBigi-ioiYs7Z8PYNIRq8,58
|
|
17
|
+
video_upscaler_cli-0.1.1.dist-info/top_level.txt,sha256=n8jcwF7Mb-pzdHQOiJD3BfxcXWJMTvRqlMuWPs7lakI,15
|
|
18
|
+
video_upscaler_cli-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
video_upscaler
|