Skip to content

DLSS 5 Neural Rendering for Images & Video with Frame Generation, RTX Video Super Resolution, HDR, and Color Grading

Add files via upload

Merserk15c80456d71c
diff --git a/src/core/ffmpeg/codecs.py b/src/core/ffmpeg/codecs.py
index 0aae3f2..69861e0 100644
--- a/src/core/ffmpeg/codecs.py
+++ b/src/core/ffmpeg/codecs.py
@@ -6,8 +6,14 @@ import math
ENCODING_QUALITIES = ("Auto (Default)", "Max", "Best", "Good")
CONTAINER_CHOICES = ("MP4", "MKV", "MOV")
-# Backend-neutral codec choices; FFmpeg/Vulkan settings select acceleration.
-CODEC_CHOICES = ("H.264", "H.265", "AV1", "ProRes Proxy", "ProRes HQ", "FFV1 Lossless RGB 10-bit")
+# Plain codecs use the selected FFmpeg/Vulkan backend. Explicit NVIDIA choices
+# keep decoded, processed, and encoded video in CUDA where the pipeline allows it.
+CODEC_CHOICES = (
+ "H.264", "H.264 (NVIDIA NVENC)",
+ "H.265", "H.265 (NVIDIA NVENC)",
+ "AV1", "AV1 (NVIDIA NVENC)",
+ "ProRes Proxy", "ProRes HQ", "FFV1 Lossless RGB 10-bit",
+)
_CODEC_ALIASES = {
"HEVC": "H.265",
@@ -75,11 +81,11 @@ FIXED_QUALITY_CODECS = frozenset({
"ProRes HQ", "FFV1 Lossless RGB 10-bit",
})
-def _normalize_codec(codec: str) -> str:
+def _normalize_codec(codec: str) -> str:
if not isinstance(codec, str):
return codec
c = codec.strip()
- return _CODEC_ALIASES.get(c, c).removesuffix(" (NVIDIA NVENC)")
+ return _CODEC_ALIASES.get(c, c)
def _base_codec(codec: str) -> str:
@@ -167,14 +173,11 @@ def validate_codec_container(codec: str, container: str) -> None:
if container not in CONTAINER_CHOICES:
raise ValueError(f"Unknown output container: {container!r}.")
norm = _normalize_codec(codec)
+ base = _base_codec(norm)
if norm in {"ProRes Proxy", "ProRes HQ"} and container == "MP4":
raise ValueError(f"{norm} is not supported in MP4. Choose the MOV or MKV container.")
- if norm == "AV1" and container == "MOV":
+ if base == "AV1" and container == "MOV":
raise ValueError("AV1 is not supported in MOV. Choose the MP4 or MKV container.")
- if norm not in CODEC_CHOICES and norm not in _CODEC_ALIASES.values():
- # Allow alias but error on truly unknown for early feedback; _codec_command will also validate.
- if norm not in _BASE_CODEC_MAP:
- raise ValueError(f"Unknown video codec: {codec!r}.")
def containers_for_codec(codec: str) -> tuple[str, ...]:
diff --git a/src/core/ffmpeg/encoder.py b/src/core/ffmpeg/encoder.py
index 2c09474..079f4c8 100644
--- a/src/core/ffmpeg/encoder.py
+++ b/src/core/ffmpeg/encoder.py
@@ -83,16 +83,33 @@ def probe_nvenc_codecs(gpu_ordinal: int) -> tuple[str, ...]:
return tuple(supported)
-def resolve_video_gpu(
+def resolve_video_gpu(
gpus: tuple[dict, ...],
gpu_uuid: str,
codec: str,
width: int,
height: int,
-) -> dict | None:
- """Legacy NVIDIA selector; FFmpeg/Vulkan now owns codec assignment."""
- _base_codec(codec)
- return None
+) -> dict | None:
+ """Resolve an explicit NVENC choice; plain codecs use FFmpeg/Vulkan."""
+ _base_codec(codec)
+ if not _is_nvenc_codec(codec):
+ return None
+ encoder = _NVENC_ENCODERS[_normalize_codec(codec)]
+ candidates = [gpu for gpu in gpus if gpu.get("cuda_ordinal") is not None]
+ if gpu_uuid != "auto":
+ candidates = [gpu for gpu in candidates if gpu.get("uuid") == gpu_uuid]
+ if not candidates:
+ raise RuntimeError("The selected Video Processing GPU is unavailable.")
+ for gpu in candidates:
+ ordinal = int(gpu["cuda_ordinal"])
+ if _encoder_probe(encoder, width, height, ordinal):
+ selected = dict(gpu)
+ selected["nvenc_codec"] = encoder
+ return selected
+ raise RuntimeError(
+ f"{codec} cannot encode {width}×{height} on the selected NVIDIA GPU. "
+ "Choose another Video Processing GPU, codec, or output size."
+ )
def _codec_command(
@@ -231,12 +248,26 @@ def _codec_command(
"libaom-av1",
quality,
)
- raise RuntimeError(
- "AV1 CPU encoding is unavailable: neither libsvtav1 nor libaom-av1 can initialize. "
+ raise RuntimeError(
+ "AV1 CPU encoding is unavailable: neither libsvtav1 nor libaom-av1 can initialize. "
"Choose H.264 or H.265."
- )
-
- raise ValueError(f"Unknown video codec: {codec!r}.")
+ )
+
+ if norm in _NVENC_ENCODERS:
+ encoder = _NVENC_ENCODERS[norm]
+ if not _encoder_probe(encoder, width, height, gpu_ordinal):
+ raise RuntimeError(f"{norm} cannot encode {width}×{height} on the selected NVIDIA GPU.")
+ if norm == "H.264 (NVIDIA NVENC)" and hdr_mode:
+ raise ValueError("HDR Mode is unavailable for H.264 (NVIDIA NVENC).")
+ pix_fmt = ("p010le" if high_depth else "yuv420p") if encoder != "h264_nvenc" else "yuv420p"
+ return (
+ ["-c:v", encoder, *gpu_args, "-preset", "p6",
+ *(["-tune", "hq"] if encoder != "av1_nvenc" else []),
+ *nvenc_quality, "-pix_fmt", pix_fmt, *hdr_color],
+ encoder, quality,
+ )
+
+ raise ValueError(f"Unknown video codec: {codec!r}.")
def start_encoder(
diff --git a/src/core/ffmpeg/frames.py b/src/core/ffmpeg/frames.py
index bdb3764..fc9fa26 100644
--- a/src/core/ffmpeg/frames.py
+++ b/src/core/ffmpeg/frames.py
@@ -5,6 +5,7 @@ PyAV here only demuxes/muxes raw NUT packets; it never encodes compressed video.
"""
from __future__ import annotations
+import math
import subprocess
import threading
from fractions import Fraction
@@ -29,8 +30,14 @@ class _Reader:
class VideoDecoder:
- def __init__(self, source, controller, *, pixel_format: str | None = None, selection=None, video_filter="", cwd=None):
+ def __init__(self, source, controller, *, pixel_format: str | None = None,
+ selection=None, video_filter="", cwd=None, start_seconds: float = 0.0):
self.controller, self.container = controller, None
+ if not math.isfinite(start_seconds) or start_seconds < 0:
+ raise ValueError("Decoder start time must be positive and finite.")
+ aligned = max(0.0, start_seconds - .002)
+ fast = max(0.0, aligned - 2.0)
+ accurate = max(0.0, aligned - fast)
info = stream_info(source)
if pixel_format is None:
source_format = info.get("pix_fmt", "yuv420p")
@@ -38,7 +45,10 @@ class VideoDecoder:
# to RGB/YUV required by a consumer is an explicit GPU operation.
pixel_format = source_format if source_format in {"yuv420p", "yuv420p10le", "yuv422p10le", "gbrp10le", "rgba", "rgba64le", "nv12", "p010le"} else "rgba64le"
command = [str(FFMPEG), "-v", "warning", "-xerror", "-copyts", "-noautorotate",
- "-i", str(source), "-map", "0:v:0", "-an", "-sn", "-dn", "-c:v", "rawvideo",
+ *(["-ss", f"{fast:.6f}"] if start_seconds > 0 else []),
+ "-i", str(source),
+ *(["-ss", f"{accurate:.6f}"] if start_seconds > 0 else []),
+ "-map", "0:v:0", "-an", "-sn", "-dn", "-c:v", "rawvideo",
*(["-vf", video_filter] if video_filter else []),
"-pix_fmt", pixel_format, "-fps_mode", "passthrough", "-enc_time_base", "demux",
"-f", "nut", "-write_index", "0", "pipe:1"]
@@ -89,8 +99,11 @@ class VideoDecoder:
self.close()
-def open_video_decoder(source, controller, *, pixel_format=None, selection=None, video_filter="", cwd=None):
- return VideoDecoder(source, controller, pixel_format=pixel_format, selection=selection, video_filter=video_filter, cwd=cwd)
+def open_video_decoder(source, controller, *, pixel_format=None, selection=None,
+ video_filter="", cwd=None, start_seconds=0.0):
+ return VideoDecoder(source, controller, pixel_format=pixel_format,
+ selection=selection, video_filter=video_filter, cwd=cwd,
+ start_seconds=start_seconds)
def packed_frame(frame) -> np.ndarray:
diff --git a/src/core/ffmpeg/mux.py b/src/core/ffmpeg/mux.py
index d10e097..177bf9b 100644
--- a/src/core/ffmpeg/mux.py
+++ b/src/core/ffmpeg/mux.py
@@ -103,9 +103,10 @@ def final_mux(
source_time_origin: float | None = None, audio_diagnostics: dict | None = None,
video_bitstream_filter: str | None = None,
video_color_metadata: dict | None = None,
+ video_only: bool = False,
) -> None:
check_cancelled(controller)
- audio_plan = plan_audio_streams(source, container, controller)
+ audio_plan = AudioPlan(()) if video_only else plan_audio_streams(source, container, controller)
if audio_diagnostics is not None:
audio_diagnostics["streams"] = audio_plan.diagnostics()
if render_note is None or container not in VIDEO_NOTE_FORMATS:
@@ -113,7 +114,7 @@ def final_mux(
record_embedding(metadata_diagnostics, "skipped", reason="unsupported_format")
elif metadata_diagnostics is not None and not metadata_diagnostics:
record_embedding(metadata_diagnostics, "not_requested")
- _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles, audio_plan, source_time_origin=source_time_origin, video_bitstream_filter=video_bitstream_filter, video_color_metadata=video_color_metadata)
+ _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles, audio_plan, source_time_origin=source_time_origin, video_bitstream_filter=video_bitstream_filter, video_color_metadata=video_color_metadata, video_only=video_only)
return
try:
@@ -126,12 +127,12 @@ def final_mux(
except (ValueError, TypeError, RuntimeError) as exc:
check_cancelled(controller)
embedding_warning(metadata_diagnostics, exc)
- _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles, audio_plan, source_time_origin=source_time_origin, video_bitstream_filter=video_bitstream_filter, video_color_metadata=video_color_metadata)
+ _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles, audio_plan, source_time_origin=source_time_origin, video_bitstream_filter=video_bitstream_filter, video_color_metadata=video_color_metadata, video_only=video_only)
return
try:
_final_mux_once(temp_video, source, output, container, controller,
- preserve_supported_subtitles, audio_plan, comment=comment, source_time_origin=source_time_origin, video_bitstream_filter=video_bitstream_filter, video_color_metadata=video_color_metadata)
+ preserve_supported_subtitles, audio_plan, comment=comment, source_time_origin=source_time_origin, video_bitstream_filter=video_bitstream_filter, video_color_metadata=video_color_metadata, video_only=video_only)
except Cancelled:
raise
except (ValueError, RuntimeError) as exc:
@@ -141,7 +142,7 @@ def final_mux(
# A mux failure caused by optional metadata should not destroy the render.
# Retry once without the note because there is not yet a valid output.
embedding_warning(metadata_diagnostics, exc)
- _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles, audio_plan, source_time_origin=source_time_origin, video_bitstream_filter=video_bitstream_filter, video_color_metadata=video_color_metadata)
+ _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles, audio_plan, source_time_origin=source_time_origin, video_bitstream_filter=video_bitstream_filter, video_color_metadata=video_color_metadata, video_only=video_only)
return
# Verification is deliberately read-only. If the optional settings note did
@@ -182,10 +183,14 @@ def _final_mux_once(
*, comment: str | None = None, source_time_origin: float | None = None,
video_bitstream_filter: str | None = None,
video_color_metadata: dict | None = None,
+ video_only: bool = False,
) -> None:
check_cancelled(controller)
duration = _probe_rendered_duration(temp_video, controller)
- if container == "MKV":
+ if video_only:
+ maps = ["-map", "0:v:0"]
+ streams = ["-c:v", "copy"]
+ elif container == "MKV":
maps = ["-map", "0:v:0", "-map", "1:a?", "-map", "1:s?"]
streams = ["-c:v", "copy", *audio_plan.encoder_args(), "-c:s", "copy"]
else:
diff --git a/src/core/ffmpeg/preview.py b/src/core/ffmpeg/preview.py
index 7ba5bc6..ad6c122 100644
--- a/src/core/ffmpeg/preview.py
+++ b/src/core/ffmpeg/preview.py
@@ -10,7 +10,123 @@ from ..paths import FFMPEG
LOSSLESS_PREVIEW_CODEC = "FFV1 Lossless RGB 10-bit"
-def extract_preview_subclip(
+def decode_timeline_frame(source: str | Path, metadata: dict, *,
+ start_seconds: float = 0.0, controller=None):
+ """Seek to one timeline frame and return its RGBA samples in memory."""
+ import numpy as np
+ from ..jobs import Cancelled, current_job_controller
+
+ controller = controller or current_job_controller()
+ if controller is not None and controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ width, height = int(metadata["width"]), int(metadata["height"])
+ high_depth = int(metadata.get("depth") or 8) > 8
+ pixel_format = "rgba64le" if high_depth else "rgba"
+ start = max(0.0, float(start_seconds))
+ aligned = max(0.0, start - 0.002)
+ fast = max(0.0, aligned - 2.0)
+ accurate = max(0.0, aligned - fast)
+ command = [str(FFMPEG), "-hide_banner", "-loglevel", "error", "-xerror",
+ "-noautorotate", "-ss", f"{fast:.6f}", "-i", str(source),
+ "-ss", f"{accurate:.6f}", "-map", "0:v:0", "-frames:v", "1",
+ "-an", "-sn", "-dn", "-fps_mode", "passthrough",
+ "-f", "rawvideo", "-pix_fmt", pixel_format, "pipe:1"]
+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
+ if controller is not None:
+ controller.register(process)
+ try:
+ while True:
+ if controller is not None and controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ try:
+ pixels, error = process.communicate(timeout=.2)
+ break
+ except subprocess.TimeoutExpired:
+ continue
+ if process.returncode:
+ raise RuntimeError("Timeline frame decoding failed: " + error.decode("utf-8", "replace")[-2000:])
+ dtype = "<u2" if high_depth else np.uint8
+ if len(pixels) != width * height * 4 * (2 if high_depth else 1):
+ raise RuntimeError("Timeline frame decoding returned unexpected dimensions.")
+ return np.frombuffer(pixels, dtype=dtype).reshape(height, width, 4).copy()
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.communicate()
+ if controller is not None:
+ controller.unregister(process)
+ process.stdout.close()
+ process.stderr.close()
+
+
+def tone_map_hdr_preview_frame(pixels, *, controller=None):
+ """Show one processed PQ frame through the established HDR display mapping."""
+ import tempfile
+
+ import numpy as np
+
+ from ..jobs import Cancelled, current_job_controller
+ from ..paths import JOBS
+
+ controller = controller or current_job_controller()
+ if (pixels.ndim != 3 or pixels.shape[2] != 4 or pixels.dtype != np.uint16):
+ raise ValueError("HDR preview requires a 16-bit RGBA frame.")
+ if controller is not None and controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ height, width = pixels.shape[:2]
+ JOBS.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix="visual-hdr-frame-", dir=JOBS) as temp:
+ output = Path(temp) / "frame.mkv"
+ command = [
+ str(FFMPEG), "-hide_banner", "-loglevel", "error", "-y",
+ "-f", "rawvideo", "-pixel_format", "rgba64le",
+ "-video_size", f"{width}x{height}", "-framerate", "25", "-i", "pipe:0",
+ "-frames:v", "1", "-vf",
+ "format=gbrp10le,setparams=colorspace=gbr:range=full:"
+ "color_primaries=bt2020:color_trc=smpte2084",
+ "-c:v", "ffv1", "-level", "3", "-slicecrc", "1",
+ "-pix_fmt", "gbrp10le", "-colorspace", "0", "-color_range", "pc",
+ "-color_primaries", "bt2020", "-color_trc", "smpte2084",
+ str(output),
+ ]
+ process = subprocess.Popen(
+ command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
+ stderr=subprocess.PIPE,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ if controller is not None:
+ controller.register(process)
+ try:
+ payload = np.ascontiguousarray(pixels).tobytes()
+ try:
+ _, error = process.communicate(input=payload, timeout=.2)
+ except subprocess.TimeoutExpired:
+ while True:
+ if controller is not None and controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ try:
+ _, error = process.communicate(timeout=.2)
+ break
+ except subprocess.TimeoutExpired:
+ continue
+ if controller is not None and controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ if process.returncode:
+ raise RuntimeError("HDR preview encoding failed: " +
+ error.decode("utf-8", "replace")[-2000:])
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.communicate()
+ if controller is not None:
+ controller.unregister(process)
+ process.stdin.close()
+ process.stderr.close()
+ return decode_preview_frame(output, controller=controller)
+
+
+def extract_preview_subclip(
source: str | Path,
dest_dir: str | Path | None = None,
*,
@@ -87,7 +203,8 @@ def extract_preview_subclip(
]
process = None
try:
- command = prepare_command(command)
+ command = prepare_command(
+ command, selection=getattr(controller, "ffmpeg_device", None))
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, encoding="utf-8", errors="replace",
diff --git a/src/core/ffmpeg/vulkan.py b/src/core/ffmpeg/vulkan.py
index e8ef85c..7277060 100644
--- a/src/core/ffmpeg/vulkan.py
+++ b/src/core/ffmpeg/vulkan.py
@@ -332,11 +332,10 @@ def quote_filter_path(path: str | Path) -> str:
return "'" + value + "'"
-_VK_ENCODERS = {"libx264": "h264_vulkan", "h264_nvenc": "h264_vulkan",
- "libx265": "hevc_vulkan", "hevc_nvenc": "hevc_vulkan",
- "libsvtav1": "av1_vulkan", "libaom-av1": "av1_vulkan", "av1_nvenc": "av1_vulkan",
+_VK_ENCODERS = {"libx264": "h264_vulkan",
+ "libx265": "hevc_vulkan",
+ "libsvtav1": "av1_vulkan", "libaom-av1": "av1_vulkan",
"ffv1": "ffv1_vulkan", "prores_ks": "prores_ks_vulkan"}
-_SOFTWARE_ENCODERS = {"h264_nvenc": "libx264", "hevc_nvenc": "libx265", "av1_nvenc": "libsvtav1"}
def _option(command: list[str], name: str, default=None):
@@ -538,9 +537,6 @@ def prepare_command(command: list[str], *, selection: str | None = None,
command[-1:-1] = ["-rc_mode", "cqp", "-qp", quality]
else:
graph = (graph + "," if graph else "") + f"{output_format(pix_fmt)},hwdownload,format={pix_fmt}"
- if encoder in _SOFTWARE_ENCODERS:
- command[command.index("-c:v") + 1] = _SOFTWARE_ENCODERS[encoder]
- command = _remove_options(command, {"-gpu", "-tune", "-rc", "-cq", "-preset"})
if "-vf" in command:
command[command.index("-vf") + 1] = graph
else:
diff --git a/src/core/gpu_selection.py b/src/core/gpu_selection.py
index b1fb63b..c9c485d 100644
--- a/src/core/gpu_selection.py
+++ b/src/core/gpu_selection.py
@@ -47,6 +47,25 @@ def detect_gpu(gpu_uuid: str = "auto") -> dict:
return _detect_gpu_cached(gpu_uuid)
+def prefer_cuda_video(ffmpeg_device: str, ai_gpu_uuid: str = "auto",
+ video_gpu_uuid: str = "auto") -> bool:
+ """Use the native CUDA video path for automatic or matching NVIDIA devices."""
+ if ffmpeg_device == "cpu":
+ return False
+ if ffmpeg_device == "auto" and video_gpu_uuid == "auto":
+ return True
+ if ffmpeg_device != "auto" and not ffmpeg_device.startswith("vulkan:"):
+ return False
+ try:
+ gpu_uuid = str(detect_gpu(ai_gpu_uuid)["uuid"])
+ except (OSError, RuntimeError, ValueError, KeyError):
+ return False
+ if video_gpu_uuid not in {"auto", gpu_uuid}:
+ return False
+ return (ffmpeg_device == "auto" or
+ ffmpeg_device[7:].lower() == gpu_uuid.removeprefix("GPU-").lower())
+
+
def _clear_gpu_detection_cache() -> None:
_detect_gpu_cached.cache_clear()
clear_gpu_detection_cache()
diff --git a/src/desktop/bridge.py b/src/desktop/bridge.py
index 3325fa6..cc465b6 100644
--- a/src/desktop/bridge.py
+++ b/src/desktop/bridge.py
@@ -4144,10 +4144,14 @@ class AppBridge(QObject):
generate_previews=True, create_zip=False, same_as_input=same_as_input)
def _nr_video_batch_worker(self, paths: list[str], settings: UISettings,
- output_dir: Path | None, same_as_input: bool) -> JobWorker:
+ output_dir: Path | None, same_as_input: bool) -> JobWorker:
+ from ..core.gpu_selection import prefer_cuda_video
+
opts = ConversionOptions(
ai_gpu_uuid=settings.ai_gpu_uuid,
video_gpu_uuid=settings.video_gpu_uuid,
+ prefer_nvenc=prefer_cuda_video(settings.ffmpeg_device,
+ settings.ai_gpu_uuid, settings.video_gpu_uuid),
nr_style=settings.nr_style,
nr_intensity=settings.nr_intensity,
nr_passes=settings.nr_passes,
diff --git a/src/desktop/qml/views/SettingsView.qml b/src/desktop/qml/views/SettingsView.qml
index be80260..e6729e5 100644
--- a/src/desktop/qml/views/SettingsView.qml
+++ b/src/desktop/qml/views/SettingsView.qml
@@ -85,10 +85,10 @@ Rectangle {
objectName: "cache-memory-mode"
width: parent.width
model: [
- {label: qsTranslate("App", "Stage by Stage"), value: "stage"},
- {label: qsTranslate("App", "Rolling Cache (5 GB)"), value: "rolling"}
+ {label: qsTranslate("App", "Rolling Cache (5 GB)"), value: "rolling"},
+ {label: qsTranslate("App", "Stage by Stage"), value: "stage"}
]
- currentValue: appBridge ? appBridge.cacheMemoryMode : "stage"
+ currentValue: appBridge ? appBridge.cacheMemoryMode : "rolling"
onActivated: (v) => { if (appBridge) appBridge.cacheMemoryMode = v }
}
}
diff --git a/src/desktop/rolling_workflow.py b/src/desktop/rolling_workflow.py
index d7d1e0f..13fd913 100644
--- a/src/desktop/rolling_workflow.py
+++ b/src/desktop/rolling_workflow.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import itertools
import math
import subprocess
+import tempfile
import threading
import time
from collections import deque
@@ -26,6 +27,7 @@ from ..core.ffmpeg.audio import plan_audio_streams
from ..core.ffmpeg.encoder import _codec_command
from ..core.ffmpeg.filters import scaling_filter
from ..core.ffmpeg.frames import _Reader, open_video_decoder, packed_frame
+from ..core.ffmpeg.preview import decode_timeline_frame
from ..core.ffmpeg.nut import RawVideoPacketMuxer
from ..core.ffmpeg.sharpening import sharpening_filter
from ..core.ffmpeg.vulkan import prepare_command
@@ -511,6 +513,49 @@ def native_stage(stage, frames, state, settings, controller, directory, *, norma
return pipe_filter(transformed, raw, after, "ve_gpu,format=gbrp10le", controller, directory), after
+def render_preview_frame(source: Path, settings: UISettings, controller,
+ start_seconds: float, stages, metadata: dict) -> np.ndarray:
+ """Process one parked frame in memory; the caller maps HDR for display."""
+ from ..core.paths import JOBS
+
+ state = VideoState.from_metadata(metadata)
+ pixels = decode_timeline_frame(source, metadata, start_seconds=start_seconds,
+ controller=controller)
+ frame = av.VideoFrame.from_ndarray(pixels, format="rgba64le" if pixels.dtype == np.uint16 else "rgba")
+ frame.pts = 0
+ frame.time_base = Fraction(1, 1) / state.rate
+ frame.duration = 1
+ frames = iter((frame,))
+ with active_job(controller), ExitStack() as resources:
+ control = _Control(controller)
+ JOBS.mkdir(parents=True, exist_ok=True)
+ directory = Path(resources.enter_context(
+ tempfile.TemporaryDirectory(prefix="visual-frame-preview-", dir=JOBS)))
+ for group in filter_groups(stages):
+ before = state
+ if isinstance(group, tuple):
+ graph, state = build_filter_group(group, state, settings, directory, control)
+ frames = pipe_filter(frames, before, state, graph, control, directory)
+ elif group == "neural_model" and len(stages) == 1:
+ frames = neural_frames(frames, state, settings, control)
+ state = state.rgb()
+ elif group == "dlss_super_resolution" and len(stages) == 1:
+ from ..core.dlss_modes import dlss_output_size
+ width, height = dlss_output_size(state.width, state.height,
+ settings.upscale_dlss_mode, even=True)
+ frames = dlss_frames(frames, state, settings, control)
+ state = state.rgb(width=width, height=height)
+ else:
+ frames, state = native_stage(group, frames, state, settings,
+ control, directory)
+ resources.callback(frames.close)
+ rendered = list(frames)
+ if len(rendered) != 1:
+ raise RuntimeError(f"Frame preview produced {len(rendered)} frames instead of one.")
+ result = rendered[0].to_ndarray(format="rgba64le")
+ return np.ascontiguousarray(result)
+
+
def _encode(frames, state, source, destination, settings, controller, progress, stats):
frames = iter(frames)
first = next(frames)
@@ -524,7 +569,9 @@ def _encode(frames, state, source, destination, settings, controller, progress,
if meta["color_space"] in {None, "", "unknown", "gbr"}:
meta["color_space"] = "bt709"
meta["color_range"] = "tv"
- gpu = ffmpeg.resolve_video_gpu((), settings.video_gpu_uuid, settings.codec, state.width, state.height)
+ from ..core.gpu_detection import detect_gpus
+ gpu = ffmpeg.resolve_video_gpu(detect_gpus(), settings.video_gpu_uuid,
+ settings.codec, state.width, state.height)
codec_args, selected, _ = _codec_command(settings.codec, settings.quality, state.width, state.height,
float(state.rate), None if gpu is None else int(gpu["cuda_ordinal"]),
hdr_mode=state.hdr, hdr_metadata=meta)
diff --git a/src/desktop/workflow.py b/src/desktop/workflow.py
index a1be2cd..4001ca9 100644
--- a/src/desktop/workflow.py
+++ b/src/desktop/workflow.py
@@ -4,10 +4,13 @@ from __future__ import annotations
import subprocess
import os
-import shutil
-import tempfile
-import time
-from dataclasses import dataclass, replace
+import math
+import shutil
+import tempfile
+import threading
+import time
+from collections import OrderedDict
+from dataclasses import dataclass, replace
from pathlib import Path
import numpy as np
@@ -20,7 +23,8 @@ from ..core.disk_paths import OutputFile, prepare_output_dir
from ..core.dlss_modes import dlss_output_size
from ..core.ffmpeg.audio import plan_audio_streams
from ..core.ffmpeg.encoder import _codec_command
-from ..core.ffmpeg.preview import decode_preview_frame, extract_preview_subclip
+from ..core.ffmpeg.preview import (decode_preview_frame, extract_preview_subclip,
+ tone_map_hdr_preview_frame)
from ..core.gpu_detection import detect_gpus
from ..core.jobs import Cancelled, JobController
from ..core.naming import output_filename, unique_output_path
@@ -51,8 +55,41 @@ from .cas_sharpening import sharpen_image, sharpen_video
from .preview_cache import PreviewStageCache, cache_key, file_identity, optional_file_identity
-LOSSLESS_VIDEO = "FFV1 Lossless RGB 10-bit"
-STAGE_LABELS = {
+LOSSLESS_VIDEO = "FFV1 Lossless RGB 10-bit"
+_FRAME_PREVIEW_CACHE_LIMIT = 128 * 1024 * 1024
+_frame_preview_cache: OrderedDict[str, np.ndarray] = OrderedDict()
+_frame_preview_cache_bytes = 0
+_frame_preview_cache_lock = threading.RLock()
+
+
+def _cached_frame_preview(key: str) -> np.ndarray | None:
+ with _frame_preview_cache_lock:
+ pixels = _frame_preview_cache.get(key)
+ if pixels is None:
+ return None
+ _frame_preview_cache.move_to_end(key)
+ return pixels.copy()
+
+
+def _remember_frame_preview(key: str, pixels: np.ndarray) -> None:
+ global _frame_preview_cache_bytes
+
+ if pixels.nbytes > _FRAME_PREVIEW_CACHE_LIMIT:
+ return
+ retained = pixels.copy()
+ with _frame_preview_cache_lock:
+ previous = _frame_preview_cache.pop(key, None)
+ if previous is not None:
+ _frame_preview_cache_bytes -= previous.nbytes
+ while (_frame_preview_cache and
+ _frame_preview_cache_bytes + retained.nbytes > _FRAME_PREVIEW_CACHE_LIMIT):
+ _, evicted = _frame_preview_cache.popitem(last=False)
+ _frame_preview_cache_bytes -= evicted.nbytes
+ _frame_preview_cache[key] = retained
+ _frame_preview_cache_bytes += retained.nbytes
+
+
+STAGE_LABELS = {
"neural_model": "DLSS Neural Rendering",
"scale_method": "Scaling",
"dlss_super_resolution": "DLSS Super Resolution",
@@ -97,19 +134,32 @@ def _preview_runtime_identity() -> list[dict | None]:
# A replaced processing engine must never inherit intermediates produced
# by the previous engine, including when the app is updated in place.
source_root = Path(__file__).resolve().parents[1]
- return [optional_file_identity(path) for path in
- (Path(__file__), Path(__file__).with_name("coloring.py"),
- Path(__file__).with_name("cas_sharpening.py"),
- source_root / "core" / "ffmpeg" / "vulkan.py",
- source_root / "core" / "ffmpeg" / "filters.py",
- source_root / "core" / "ffmpeg" / "sharpening.py",
- source_root / "core" / "dlss_bridge.py",
+ return [optional_file_identity(path) for path in
+ (Path(__file__), Path(__file__).with_name("rolling_workflow.py"),
+ Path(__file__).with_name("coloring.py"),
+ Path(__file__).with_name("cas_sharpening.py"),
+ source_root / "core" / "ffmpeg" / "preview.py",
+ source_root / "core" / "ffmpeg" / "frames.py",
+ source_root / "core" / "ffmpeg" / "encoder.py",
+ source_root / "core" / "ffmpeg" / "mux.py",
+ source_root / "core" / "ffmpeg" / "vulkan.py",
+ source_root / "core" / "ffmpeg" / "filters.py",
+ source_root / "core" / "ffmpeg" / "sharpening.py",
+ source_root / "core" / "dlss_bridge.py",
+ source_root / "core" / "neural_bridge.py",
+ source_root / "core" / "runtime.py",
source_root / "upscale" / "image" / "processor.py",
source_root / "upscale" / "video" / "processor.py",
+ source_root / "upscale" / "video" / "preview.py",
+ source_root / "upscale" / "video" / "dlss_pipeline.py",
+ source_root / "upscale" / "video" / "cuda_pipeline.py",
+ source_root / "upscale" / "video" / "native.py",
source_root / "upscale" / "video" / "media.py",
source_root / "upscale" / "video" / "host_pipeline.py",
- source_root / "neural_rendering" / "image" / "batch.py",
- source_root / "neural_rendering" / "video" / "processor.py",
+ source_root / "neural_rendering" / "image" / "batch.py",
+ source_root / "neural_rendering" / "video" / "processor.py",
+ source_root / "neural_rendering" / "video" / "cuda_pipeline.py",
+ source_root / "neural_rendering" / "video" / "fast_preview.py",
source_root / "frame_interpolation" / "processor.py",
FFMPEG, DLSSSR_BRIDGE, DLSSSR_RUNTIME, DLSSNR_BRIDGE,
DLSSNR_CALLER_SHIM, NEURAL_RUNTIME,
@@ -205,6 +255,32 @@ def enabled_stages(settings: UISettings, mode: str) -> tuple[str, ...]:
return tuple(stage for stage in order if stage in enabled)
+def _preferred_native_codec(settings: UISettings, estimate: PipelineEstimate,
+ stages: tuple[str, ...]) -> UISettings:
+ """Keep a native NVIDIA pipeline on CUDA when the encoder is automatic."""
+ from ..core.gpu_selection import prefer_cuda_video
+
+ if (not prefer_cuda_video(settings.ffmpeg_device, settings.ai_gpu_uuid,
+ settings.video_gpu_uuid) or
+ settings.codec not in {"H.264", "H.265", "AV1"} or
+ not set(stages) & {"neural_model", "dlss_super_resolution",
+ "super_resolution", "rtx_video_hdr", "frame_generation"}):
+ return settings
+ try:
+ from ..core.gpu_selection import detect_gpu
+
+ gpu = detect_gpu(settings.ai_gpu_uuid)
+ uuid = str(gpu["uuid"])
+ if settings.video_gpu_uuid not in {"auto", uuid}:
+ return settings
+ codec = settings.codec + " (NVIDIA NVENC)"
+ ffmpeg.resolve_video_gpu((gpu,), uuid, codec, estimate.width, estimate.height)
+ except (OSError, RuntimeError, ValueError):
+ return settings
+ app_log.info("video-render", f"automatic NVIDIA NVENC selected for {settings.codec}")
+ return replace(settings, codec=codec, video_gpu_uuid=uuid)
+
+
def preview_settings_key(settings: UISettings, mode: str, *, hdr: bool = False) -> str:
"""Identify the active pipeline, ignoring controls in disabled cards."""
stages = []
@@ -299,7 +375,8 @@ def estimate_pipeline(width: int, height: int, fps: float, hdr: bool,
return PipelineEstimate(width, height, fps, hdr)
-def preflight_source(source: Path, settings: UISettings, mode: str) -> PipelineEstimate:
+def preflight_source(source: Path, settings: UISettings, mode: str,
+ *, metadata: dict | None = None) -> PipelineEstimate:
if not source.is_file():
raise FileNotFoundError(source)
if "coloring" in enabled_stages(settings, mode) and (mode == "Video" or settings.coloring_mode == "LUT"):
@@ -329,8 +406,8 @@ def preflight_source(source: Path, settings: UISettings, mode: str) -> PipelineE
return estimate_pipeline(width, height, 0.0, False, settings, mode)
native_fg = ("frame_generation" in enabled_stages(settings, mode)
and settings.frame_interpolation_engine == "Native DLSSG")
- metadata = ffmpeg.probe_video(source, count_mode="metadata",
- inspect_timestamps=native_fg)
+ metadata = metadata or ffmpeg.probe_video(source, count_mode="metadata",
+ inspect_timestamps=native_fg)
result = estimate_pipeline(int(metadata["width"]), int(metadata["height"]),
float(metadata["fps"]), bool(metadata.get("hdr")), settings, mode)
if "(NVIDIA NVENC)" in settings.codec:
@@ -351,14 +428,16 @@ def preflight_source(source: Path, settings: UISettings, mode: str) -> PipelineE
def preflight_capabilities(settings: UISettings, mode: str,
- controller: JobController | None = None,
- stages_override: tuple[str, ...] | None = None) -> None:
+ controller: JobController | None = None,
+ stages_override: tuple[str, ...] | None = None,
+ *, require_filter: bool = True) -> None:
"""Reject unavailable processing hardware before writing any stage output."""
stages = stages_override if stages_override is not None else enabled_stages(settings, mode)
if not stages:
return
- from ..core.ffmpeg.vulkan import filter_device
- filter_device(settings.ffmpeg_device)
+ if require_filter:
+ from ..core.ffmpeg.vulkan import filter_device
+ filter_device(settings.ffmpeg_device)
needs_ai_gpu = bool(set(stages) & {"neural_model", "dlss_super_resolution", "super_resolution", "rtx_video_hdr", "frame_generation"})
if needs_ai_gpu:
from ..core.gpu_selection import detect_gpu
@@ -405,9 +484,13 @@ def _neural_image_options(settings: UISettings) -> ImageConversionOptions:
def _neural_video_options(settings: UISettings, hdr: bool) -> ConversionOptions:
+ from ..core.gpu_selection import prefer_cuda_video
+
cache_codec, cache_container, _ = cache_video_format(settings.cache_codec)
return ConversionOptions(
- ai_gpu_uuid=settings.ai_gpu_uuid, video_gpu_uuid=settings.video_gpu_uuid,
+ ai_gpu_uuid=settings.ai_gpu_uuid, video_gpu_uuid=settings.video_gpu_uuid,
+ prefer_nvenc=prefer_cuda_video(settings.ffmpeg_device, settings.ai_gpu_uuid,
+ settings.video_gpu_uuid),
nr_style=settings.nr_style, nr_intensity=settings.nr_intensity,
nr_passes=settings.nr_passes, local_tone_strength=settings.local_tone_strength,
local_structure_strength=settings.local_structure_strength,
@@ -520,13 +603,19 @@ def _coloring_video_stage(source: Path, settings: UISettings, directory: Path,
return output
-def _video_stage(source: Path, stage: str, settings: UISettings, hdr: bool,
- directory: Path, controller: JobController, progress) -> Path:
+def _video_stage(source: Path, stage: str, settings: UISettings, hdr: bool,
+ directory: Path, controller: JobController, progress,
+ *, delivery: bool = False) -> Path:
if stage == "cas_sharpening":
return sharpen_video(source, settings, directory, controller, progress)
- if stage == "neural_model":
- result = convert_video(source, _neural_video_options(settings, hdr), progress,
- output_dir=directory, controller=controller)
+ if stage == "neural_model":
+ options = _neural_video_options(settings, hdr)
+ if delivery:
+ options = replace(options, codec=settings.codec,
+ container=ffmpeg.resolve_container(settings.codec, settings.container),
+ quality=settings.quality)
+ result = convert_video(source, options, progress,
+ output_dir=directory, controller=controller)
elif stage == "scale_method":
metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)
width, height = resolve_output_size(int(metadata["width"]), int(metadata["height"]),
@@ -542,21 +631,71 @@ def _video_stage(source: Path, stage: str, settings: UISettings, hdr: bool,
return output
elif stage in {"dlss_super_resolution", "super_resolution", "rtx_video_hdr"}:
opts = _video_upscale_stage_options(settings, stage)
- result = upscale_video(source, opts, progress, output_dir=directory, controller=controller)
+ if delivery:
+ opts = replace(opts, codec=settings.codec,
+ container=ffmpeg.resolve_container(settings.codec, settings.container),
+ quality=settings.quality)
+ result = upscale_video(source, opts, progress, output_dir=directory, controller=controller)
elif stage == "frame_generation":
- cache_codec, cache_container, _ = cache_video_format(settings.cache_codec)
+ cache_codec, cache_container, _ = (cache_video_format(settings.cache_codec)
+ if not delivery else
+ (settings.codec,
+ ffmpeg.resolve_container(settings.codec, settings.container), ""))
opts = FrameInterpolationOptions(
ai_gpu_uuid=settings.ai_gpu_uuid, video_gpu_uuid=settings.video_gpu_uuid,
target_fps=settings.frame_interpolation_target_fps,
engine=settings.frame_interpolation_engine,
- codec=cache_codec, container=cache_container, quality="Auto (Default)",
+ codec=cache_codec, container=cache_container,
+ quality=settings.quality if delivery else "Auto (Default)",
hdr_mode=hdr,
)
result = interpolate_video(source, opts, progress, output_dir=directory,
controller=controller)
else:
raise ValueError(f"Unknown video processing card: {stage}")
- return Path(result.output_path)
+ return Path(result.output_path)
+
+
+def _render_single_video_stage(source: Path, stage: str, settings: UISettings,
+ hdr: bool, destination: Path, directory: Path,
+ controller: JobController, progress) -> str:
+ """Deliver a native stage with the requested codec in one processing pass."""
+ container = ffmpeg.resolve_container(settings.codec, settings.container)
+
+ def report(value, message):
+ if progress:
+ progress(min(.98, max(0.0, float(value)) * .98),
+ f"Stage 1 of 1 · {STAGE_LABELS[stage]}: {message}")
+
+ if stage == "neural_model":
+ options = replace(_neural_video_options(settings, hdr),
+ codec=settings.codec, container=container,
+ quality=settings.quality)
+ result = convert_video(source, options, report, output_dir=directory,
+ controller=controller)
+ elif stage in {"dlss_super_resolution", "super_resolution", "rtx_video_hdr"}:
+ options = replace(_video_upscale_stage_options(settings, stage),
+ codec=settings.codec, container=container,
+ quality=settings.quality)
+ result = upscale_video(source, options, report, output_dir=directory,
+ controller=controller)
+ elif stage == "frame_generation":
+ options = FrameInterpolationOptions(
+ ai_gpu_uuid=settings.ai_gpu_uuid, video_gpu_uuid=settings.video_gpu_uuid,
+ target_fps=settings.frame_interpolation_target_fps,
+ engine=settings.frame_interpolation_engine,
+ codec=settings.codec, container=container, quality=settings.quality,
+ hdr_mode=hdr,
+ )
+ result = interpolate_video(source, options, report, output_dir=directory,
+ controller=controller)
+ else:
+ raise ValueError(f"Unknown native video stage: {stage}.")
+
+ _publish_video(Path(result.output_path), destination, controller)
+ if progress:
+ progress(1.0, "Export complete")
+ return str(destination)
def _image_at_bit_depth(rgba: np.ndarray, settings: UISettings) -> np.ndarray:
@@ -594,18 +733,22 @@ def _export_image(current: Path, destination: Path,
output.cleanup()
-def _publish_video_preview(current: Path, destination: Path, controller: JobController) -> Path:
- """Keep the completed lossless clip available without another encode.
+def _publish_video(current: Path, destination: Path, controller: JobController,
+ *, preview: bool = False) -> Path:
+ """Publish a completed video without another encode.
A hard link is enough on the same volume. Cross-volume or optional-cache
fallback copies remain cancellable and are published atomically.
"""
- destination = destination.with_suffix(current.suffix)
+ if preview:
+ destination = destination.with_suffix(current.suffix)
+ elif destination.suffix.casefold() != current.suffix.casefold():
+ raise ValueError("The processed video container does not match the export destination.")
destination.parent.mkdir(parents=True, exist_ok=True)
output = OutputFile(destination)
try:
if controller.cancel.is_set():
- raise Cancelled("Preview cancelled.")
+ raise Cancelled("Video processing cancelled.")
output.temporary.unlink()
try:
os.link(current, output.temporary)
@@ -613,10 +756,10 @@ def _publish_video_preview(current: Path, destination: Path, controller: JobCont
with current.open("rb") as source, output.temporary.open("wb") as target:
while data := source.read(1024 * 1024):
if controller.cancel.is_set():
- raise Cancelled("Preview cancelled.")
+ raise Cancelled("Video processing cancelled.")
target.write(data)
if controller.cancel.is_set():
- raise Cancelled("Preview cancelled.")
+ raise Cancelled("Video processing cancelled.")
output.publish()
finally:
output.cleanup()
@@ -650,8 +793,8 @@ def _export_video(source: Path, current: Path, destination: Path,
encode_metadata["color_primaries"] = "bt2020"
encode_metadata["color_transfer"] = "smpte2084"
encode_metadata["color_space"] = "bt2020nc"
- gpu = ffmpeg.resolve_video_gpu((), settings.video_gpu_uuid,
- codec, width, height)
+ gpu = ffmpeg.resolve_video_gpu(detect_gpus(), settings.video_gpu_uuid,
+ codec, width, height)
codec_args, _, _ = _codec_command(codec, quality, width, height,
float(metadata["fps"]),
None if gpu is None else int(gpu["cuda_ordinal"]),
@@ -688,31 +831,43 @@ def _export_video(source: Path, current: Path, destination: Path,
output.cleanup()
-def render_item(source: Path, settings: UISettings, mode: str, destination: Path,
- controller: JobController, progress=None, *, preview: bool = False,
- capabilities_checked: bool = False,
- preview_cache: PreviewStageCache | None = None,
- source_cache_key: str | None = None) -> str:
+def render_item(source: Path, settings: UISettings, mode: str, destination: Path,
+ controller: JobController, progress=None, *, preview: bool = False,
+ capabilities_checked: bool = False,
+ preview_cache: PreviewStageCache | None = None,
+ source_cache_key: str | None = None,
+ preflight_estimate: PipelineEstimate | None = None) -> str:
controller.ffmpeg_device = settings.ffmpeg_device
- preflight_source(source, settings, mode)
- if not capabilities_checked and preview_cache is None:
- preflight_capabilities(settings, mode, controller)
- stages = enabled_stages(settings, mode)
+ estimate = preflight_estimate or preflight_source(source, settings, mode)
+ stages = enabled_stages(settings, mode)
+ direct_native = (mode == "Video" and not preview and len(stages) == 1
+ and stages[0] in {"neural_model", "dlss_super_resolution",
+ "super_resolution", "rtx_video_hdr", "frame_generation"})
+ if not capabilities_checked and preview_cache is None:
+ preflight_capabilities(settings, mode, controller,
+ require_filter=not direct_native)
+ if mode == "Video" and not preview:
+ settings = _preferred_native_codec(settings, estimate, stages)
upstream_key = (source_cache_key or cache_key({"kind": "source", "mode": mode,
"source": file_identity(source)})) if preview_cache else ""
JOBS.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="visual-workflow-", dir=JOBS) as temp:
+ if direct_native:
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ return _render_single_video_stage(source, stages[0], settings, estimate.hdr,
+ destination, Path(temp), controller, progress)
if mode == "Video" and not preview and settings.cache_memory_mode == "rolling":
from .rolling_workflow import render_rolling_video
destination.parent.mkdir(parents=True, exist_ok=True)
return render_rolling_video(source, settings, destination, controller,
Path(temp), stages, progress)
current = source
+ final_native = (mode == "Video" and not preview and bool(stages)
+ and stages[-1] in {"neural_model", "dlss_super_resolution",
+ "super_resolution", "rtx_video_hdr", "frame_generation"})
# Smart previews remain lossless and share their existing FFV1 cache keys.
stage_settings = replace(settings, cache_codec="FFV1") if preview else settings
- hdr = False
- if mode == "Video":
- hdr = bool(ffmpeg.probe_video(source, count_mode="metadata", controller=controller).get("hdr"))
+ hdr = estimate.hdr if mode == "Video" else False
for index, stage in enumerate(stages):
if controller.cancel.is_set():
raise Cancelled("Render stopped by user.")
@@ -747,8 +902,10 @@ def render_item(source: Path, settings: UISettings, mode: str, destination: Path
_coloring_video_stage(current, stage_settings, directory, controller, report))
elif mode == "Image":
current = _image_stage(current, stage, settings, directory, controller, report)
- else:
- current = _video_stage(current, stage, stage_settings, hdr, directory, controller, report)
+ else:
+ current = _video_stage(current, stage, stage_settings, hdr, directory,
+ controller, report,
+ delivery=final_native and index == len(stages) - 1)
if controller.cancel.is_set():
raise Cancelled("Render stopped by user.")
if preview_cache:
@@ -765,7 +922,18 @@ def render_item(source: Path, settings: UISettings, mode: str, destination: Path
if mode == "Image":
_export_image(current, destination, settings, controller)
elif preview:
- destination = _publish_video_preview(current, destination, controller)
+ destination = _publish_video(current, destination, controller, preview=True)
+ elif final_native:
+ output = OutputFile(destination)
+ try:
+ ffmpeg.final_mux(current, source, output.temporary,
+ ffmpeg.resolve_container(settings.codec, settings.container),
+ controller)
+ if controller.cancel.is_set():
+ raise Cancelled("Render stopped by user.")
+ output.publish()
+ finally:
+ output.cleanup()
else:
def report_export(value, message):
if progress:
@@ -785,9 +953,13 @@ def render_pipeline_batch(input_paths, settings: UISettings, mode: str,
if not paths:
raise ValueError("Add a file before rendering.")
controller = controller or JobController()
- for path in paths:
- preflight_source(path, settings, mode)
- preflight_capabilities(settings, mode, controller)
+ estimates = [preflight_source(path, settings, mode) for path in paths]
+ stages = enabled_stages(settings, mode)
+ direct_native = (mode == "Video" and len(stages) == 1
+ and stages[0] in {"neural_model", "dlss_super_resolution",
+ "super_resolution", "rtx_video_hdr", "frame_generation"})
+ preflight_capabilities(settings, mode, controller,
+ require_filter=not direct_native)
reporter = BatchProgress(paths, on_item_update, progress)
successes: list[PipelineSuccess] = []
failures: list[PipelineFailure] = []
@@ -808,9 +980,10 @@ def render_pipeline_batch(input_paths, settings: UISettings, mode: str,
path, extension, rename_mode, suffix, f"{path.stem}_Pipeline_{stamp}"), reserved)
reserved.add(output)
try:
- rendered = render_item(path, settings, mode, output, controller,
- lambda value, message, i=index: reporter.advance(i, value, message),
- capabilities_checked=True)
+ rendered = render_item(path, settings, mode, output, controller,
+ lambda value, message, i=index: reporter.advance(i, value, message),
+ capabilities_checked=True,
+ preflight_estimate=estimates[index])
except Exception as exc:
cancelled = isinstance(exc, Cancelled) or controller.cancel.is_set()
failures.append(PipelineFailure(str(path), str(exc), cancelled))
@@ -836,16 +1009,177 @@ def render_pipeline_preview(source: str, settings: UISettings, mode: str, *,
clip_seconds: float | None = None,
cache_dir: Path = PREVIEW_CACHE) -> tuple[str | np.ndarray, str]:
controller = controller or JobController()
+ controller.ffmpeg_device = settings.ffmpeg_device
source_path = Path(source).resolve()
if controller.cancel.is_set():
raise Cancelled("Preview cancelled.")
if not source_path.is_file():
raise FileNotFoundError(source_path)
- if not enabled_stages(settings, mode):
+ stages = enabled_stages(settings, mode)
+ if not stages:
# The native player already seeks/plays the unprocessed video. Do not
# probe, convert to FFV1, or decode another copy just to show it again.
media = decode_image(source_path).rgba if mode == "Image" else str(source_path)
return media, "Source preview (all processing cards are off)."
+ if mode == "Video" and clip_seconds is None:
+ frame_key = None
+ if "frame_generation" not in stages:
+ frame_key = cache_key({
+ "kind": "parked-frame", "source": file_identity(source_path),
+ "settings": preview_settings_key(settings, mode, hdr=False),
+ "start_seconds": round(float(start_seconds), 6),
+ "runtime": _preview_runtime_identity(),
+ })
+ cached = _cached_frame_preview(frame_key)
+ if cached is not None:
+ if controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ return cached, "Pipeline frame preview complete."
+ metadata = ffmpeg.probe_video(source_path, count_mode="metadata", controller=controller)
+ hdr_preview = bool(metadata.get("hdr") or "rtx_video_hdr" in stages)
+ pq_input = (not metadata.get("hdr") or
+ metadata.get("color_transfer") == "smpte2084")
+ fast_hdr = hdr_preview and pq_input and stages in {
+ ("neural_model",), ("rtx_video_hdr",),
+ }
+ if (not int(metadata.get("rotation") or 0) and frame_key is not None
+ and (not hdr_preview or fast_hdr)):
+ preview_settings = (replace(settings, codec=LOSSLESS_VIDEO, container="MKV",
+ quality="Auto (Default)", hdr_mode=True)
+ if hdr_preview else settings)
+ preflight_source(source_path, preview_settings, mode, metadata=metadata)
+ preflight_capabilities(
+ settings, mode, controller,
+ require_filter=hdr_preview or not set(stages).issubset({
+ "neural_model", "dlss_super_resolution", "super_resolution",
+ "rtx_video_hdr",
+ }),
+ )
+ from .rolling_workflow import render_preview_frame
+ pixels = render_preview_frame(source_path, replace(settings, cache_codec="FFV1"),
+ controller, start_seconds, stages, metadata)
+ if hdr_preview:
+ pixels = tone_map_hdr_preview_frame(pixels, controller=controller)
+ if controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ _remember_frame_preview(frame_key, pixels)
+ return pixels, "Pipeline frame preview complete."
+ if (mode == "Video" and clip_seconds is not None and clip_seconds > 0
+ and stages == ("neural_model",)):
+ from ..neural_rendering.video.fast_preview import (
+ FastClipUnavailable, render_lossless_cuda_preview_clip)
+
+ options = _neural_video_options(replace(settings, cache_codec="FFV1"), False)
+ if options.prefer_nvenc:
+ metadata = ffmpeg.probe_video(source_path, count_mode="metadata",
+ controller=controller)
+ color_fields = ("color_space", "color_primaries", "color_transfer")
+ compatible_color = all(metadata.get(field) == "bt709"
+ for field in color_fields)
+ if (metadata.get("cfr") and not metadata.get("hdr")
+ and not int(metadata.get("rotation") or 0)
+ and int(metadata.get("depth") or 8) <= 8
+ and compatible_color):
+ preview_settings = replace(settings, codec=LOSSLESS_VIDEO,
+ container="MKV", quality="Auto (Default)",
+ hdr_mode=True)
+ preflight_source(source_path, preview_settings, mode, metadata=metadata)
+ frame_count = max(1, math.ceil(float(clip_seconds) *
+ float(metadata["fps"]) - 1e-6))
+ stage_cache = PreviewStageCache(cache_dir)
+ clip_key = cache_key({
+ "kind": "neural-cuda-lossless-clip",
+ "source": file_identity(source_path),
+ "settings": preview_settings_key(settings, mode, hdr=False),
+ "start_seconds": round(float(start_seconds), 6),
+ "clip_seconds": round(float(clip_seconds), 6),
+ "frames": frame_count,
+ "runtime": _preview_runtime_identity(),
+ })
+ cached = stage_cache.lookup(clip_key)
+ if cached is not None:
+ if controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ return str(cached.resolve()), "Pipeline video preview complete."
+ preflight_capabilities(settings, mode, controller,
+ require_filter=False)
+ JOBS.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(
+ prefix="visual-cuda-preview-", dir=JOBS) as temp:
+ directory = Path(temp) / "clip"
+ directory.mkdir()
+ try:
+ result = render_lossless_cuda_preview_clip(
+ source_path, options, metadata,
+ start_seconds=start_seconds, frame_count=frame_count,
+ output_dir=directory, controller=controller,
+ progress=progress)
+ except FastClipUnavailable:
+ pass
+ else:
+ published = stage_cache.publish(clip_key, directory, result)
+ if published.resolve() == result.resolve():
+ output_dir = prepare_output_dir(output_dir)
+ durable = unique_output_path(
+ output_dir / f"pipeline-preview-{time.time_ns()}.mkv")
+ shutil.move(str(result), str(durable))
+ published = durable
+ prune_preview_cache(root=stage_cache.root,
+ protected_keys=stage_cache.used_keys,
+ min_idle_seconds=0)
+ return str(published.resolve()), "Pipeline video preview complete."
+ if (mode == "Video" and clip_seconds is not None and clip_seconds > 0
+ and stages in {("dlss_super_resolution",), ("super_resolution",)}):
+ metadata = ffmpeg.probe_video(source_path, count_mode="metadata",
+ controller=controller)
+ if (metadata.get("cfr") and not metadata.get("hdr")
+ and not int(metadata.get("rotation") or 0)
+ and int(metadata.get("depth") or 8) <= 8
+ and all(metadata.get(field) == "bt709" for field in
+ ("color_space", "color_primaries", "color_transfer"))):
+ from ..upscale.video.preview import preview_upscale_native
+
+ preview_settings = replace(settings, codec=LOSSLESS_VIDEO,
+ container="MKV", quality="Auto (Default)",
+ hdr_mode=True)
+ preflight_source(source_path, preview_settings, mode, metadata=metadata)
+ stage_cache = PreviewStageCache(cache_dir)
+ clip_key = cache_key({
+ "kind": "upscale-direct-seek-lossless-clip",
+ "stage": stages[0],
+ "source": file_identity(source_path),
+ "settings": preview_settings_key(settings, mode, hdr=False),
+ "start_seconds": round(float(start_seconds), 6),
+ "clip_seconds": round(float(clip_seconds), 6),
+ "runtime": _preview_runtime_identity(),
+ })
+ cached = stage_cache.lookup(clip_key)
+ if cached is not None:
+ if controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ return str(cached.resolve()), "Pipeline video preview complete."
+ preflight_capabilities(settings, mode, controller, require_filter=False)
+ JOBS.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(
+ prefix="visual-upscale-preview-", dir=JOBS) as temp:
+ directory = Path(temp) / "clip"
+ directory.mkdir()
+ result, _ = preview_upscale_native(
+ str(source_path), _video_upscale_stage_options(settings, stages[0]),
+ one_frame=False, progress=progress, controller=controller,
+ output_dir=directory, start_seconds=start_seconds,
+ preview_seconds=clip_seconds)
+ published = stage_cache.publish(clip_key, directory, Path(result))
+ if published.resolve() == Path(result).resolve():
+ output_dir = prepare_output_dir(output_dir)
+ durable = unique_output_path(
+ output_dir / f"pipeline-preview-{time.time_ns()}.mkv")
+ shutil.move(str(result), str(durable))
+ published = durable
+ prune_preview_cache(root=stage_cache.root,
+ protected_keys=stage_cache.used_keys,
+ min_idle_seconds=0)
+ return str(published.resolve()), "Pipeline video preview complete."
if mode == "Video":
# Preview storage and playback are independent of delivery settings.
settings = replace(settings, codec=LOSSLESS_VIDEO, container="MKV",
diff --git a/src/neural_rendering/video/fast_preview.py b/src/neural_rendering/video/fast_preview.py
new file mode 100644
index 0000000..107bc57
--- /dev/null
+++ b/src/neural_rendering/video/fast_preview.py
@@ -0,0 +1,221 @@
+"""Lossless timed Neural Rendering previews from the original CUDA video frames."""
+
+from __future__ import annotations
+
+import math
+import subprocess
+import tempfile
+import time
+from contextlib import suppress
+from fractions import Fraction
+from pathlib import Path
+
+import av
+import numpy as np
+from av.codec.hwaccel import HWAccel
+
+from ...core import ffmpeg
+from ...core.disk_paths import OutputFile, prepare_output_dir
+from ...core.gpu_selection import resolve_runtime_ai_gpu
+from ...core.jobs import Cancelled, JobController, active_job
+from ...core.naming import unique_output_path
+from ...core.paths import FFMPEG
+from ...core.runtime import (DLSSFrameSession, prepare_runtime,
+ resolve_native_settings, resolve_upscaling_mode)
+from .models import ConversionOptions
+
+
+class FastClipUnavailable(RuntimeError):
+ """The source cannot use the exact-frame CUDA preview route."""
+
+
+def render_lossless_cuda_preview_clip(
+ source: Path, options: ConversionOptions, metadata: dict, *,
+ start_seconds: float, frame_count: int, output_dir: Path,
+ controller: JobController, progress=None,
+) -> Path:
+ """Seek to a parked frame, render on CUDA, and encode its RGB samples to FFV1."""
+ if (not metadata.get("cfr") or metadata.get("hdr")
+ or int(metadata.get("rotation") or 0)
+ or int(metadata.get("depth") or 8) > 8
+ or any(metadata.get(field) != "bt709" for field in
+ ("color_space", "color_primaries", "color_transfer"))
+ or options.scale_method != "Standard"
+ or options.upscaling_factor != 1.0
+ or options.preserve_hdr):
+ raise FastClipUnavailable("Source needs the established lossless clip route.")
+ if not source.is_file():
+ raise FileNotFoundError(source)
+ if frame_count < 1 or not math.isfinite(start_seconds) or start_seconds < 0:
+ raise ValueError("Invalid preview frame range.")
+ if controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+
+ prepared = prepare_runtime()
+ gpu = resolve_runtime_ai_gpu(prepared.gpus, prepared.runtime_bundle,
+ options.ai_gpu_uuid)
+ ordinal = int(gpu["cuda_ordinal"])
+ width, height = int(metadata["width"]), int(metadata["height"])
+ factor, mode = resolve_upscaling_mode(1.0)
+ destination = unique_output_path(
+ prepare_output_dir(output_dir) / f"neural-preview-{time.time_ns()}.mkv")
+ output = OutputFile(destination)
+ process = session = None
+ published = False
+ try:
+ with active_job(controller):
+ decoder_device = HWAccel(
+ "cuda", device=str(ordinal), allow_software_fallback=True,
+ options={"primary_ctx": "1"}, is_hw_owned=True,
+ )
+ with av.open(str(source), hwaccel=decoder_device) as decoded:
+ stream = decoded.streams.video[0]
+ stream.thread_type = "AUTO"
+ origin = float(Fraction(stream.start_time or 0) * stream.time_base)
+ aligned = origin + max(0.0, start_seconds - .002)
+ if start_seconds > 0:
+ decoded.seek(max(0, math.floor(aligned / float(stream.time_base))),
+ stream=stream, backward=True, any_frame=False)
+ frames = iter(decoded.decode(stream))
+ first = None
+ for frame in frames:
+ if controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ if frame.pts is None:
+ raise FastClipUnavailable("Source frames have no timestamps.")
+ timestamp = float(Fraction(frame.pts) *
+ (frame.time_base or stream.time_base))
+ if timestamp + 1e-9 >= aligned:
+ first = frame
+ break
+ if first is None or first.format.name != "cuda":
+ raise FastClipUnavailable("Source has no CUDA frame at this position.")
+
+ command = [
+ str(FFMPEG), "-hide_banner", "-loglevel", "error", "-y",
+ "-f", "rawvideo", "-pixel_format", "rgba64le",
+ "-video_size", f"{width}x{height}",
+ "-framerate", str(metadata["rate"]), "-i", "pipe:0",
+ "-frames:v", str(frame_count), "-an", "-vf",
+ "format=gbrp10le,setparams=colorspace=gbr:range=full:"
+ "color_primaries=bt709:color_trc=bt709",
+ "-c:v", "ffv1", "-level", "3", "-slicecrc", "1",
+ "-pix_fmt", "gbrp10le", "-colorspace", "0", "-color_range", "pc",
+ "-color_primaries", "bt709", "-color_trc", "bt709",
+ str(output.temporary),
+ ]
+ with tempfile.TemporaryFile() as errors:
+ process = subprocess.Popen(
+ command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
+ stderr=errors,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ controller.register(process)
+ session = DLSSFrameSession(
+ input_width=width, input_height=height,
+ output_width=width, output_height=height,
+ frame_count=None, warmup_frames=options.warmup_frames,
+ factor=factor, mode=mode,
+ native_settings=resolve_native_settings(options),
+ composition_mask=options.nr_mask, gpu=gpu,
+ runtime_bundle=prepared.runtime_bundle,
+ controller=controller, cuda_video=True,
+ )
+ pixels = np.empty((height, width, 4), dtype=np.uint16)
+ color_space = str(metadata.get("color_space") or "").casefold()
+ matrix = 2 if "2020" in color_space else (
+ 0 if color_space in {"bt470bg", "smpte170m", "smpte240m", "fcc"}
+ else 1)
+ full_range = int(str(metadata.get("color_range") or "").casefold()
+ in {"pc", "jpeg", "full"})
+ chroma = ffmpeg.chroma_location_code(metadata)
+ delivered = 0
+ last_progress = 0.0
+ pending = first
+ while delivered < frame_count:
+ if controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ if pending is None:
+ try:
+ pending = next(frames)
+ except StopIteration:
+ break
+ if pending.is_corrupt:
+ raise RuntimeError("Preview source contains a corrupt frame.")
+ if pending.format.name != "cuda" or pending.pts is None:
+ raise FastClipUnavailable("CUDA decode stopped during preview.")
+ score, reset = session.score_cuda_frame(
+ pending, color_matrix=matrix, color_range=full_range)
+ result, result_pts = session.process_cuda_frame_to_host(
+ index=delivered, frame=pending, reset=reset,
+ scene_score=score, pts=int(pending.pts),
+ color_matrix=matrix, color_range=full_range,
+ chroma_location=chroma, output_buffer=pixels)
+ if result_pts != int(pending.pts):
+ raise RuntimeError("Neural preview changed a frame timestamp.")
+ assert process.stdin is not None
+ try:
+ process.stdin.write(memoryview(result).cast("B"))
+ except (OSError, ValueError) as exc:
+ if controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.") from exc
+ raise RuntimeError("Lossless preview encoder stopped early.") from exc
+ delivered += 1
+ pending = None
+ now = time.perf_counter()
+ if progress and (now - last_progress >= .1 or delivered == frame_count):
+ progress(min(.95, delivered / frame_count * .95),
+ f"Rendering preview frames: {delivered:,} / {frame_count:,}")
+ last_progress = now
+ if not delivered:
+ raise FastClipUnavailable("No frames remain at the preview position.")
+ session.close()
+ session = None
+ assert process.stdin is not None
+ try:
+ process.stdin.close()
+ except OSError as exc:
+ if controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.") from exc
+ raise RuntimeError("Lossless preview encoder stopped early.") from exc
+ while True:
+ if controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ try:
+ code = process.wait(timeout=.2)
+ break
+ except subprocess.TimeoutExpired:
+ continue
+ if code:
+ errors.seek(0)
+ raise RuntimeError("Lossless preview encoding failed: " +
+ errors.read().decode("utf-8", "replace")[-2000:])
+ controller.unregister(process)
+ process = None
+
+ verified = ffmpeg.probe_video(output.temporary, count_mode="metadata",
+ controller=controller)
+ if ((int(verified["width"]), int(verified["height"])) != (width, height)
+ or int(verified.get("depth") or 0) < 10):
+ raise RuntimeError("Lossless preview lost dimensions or precision.")
+ if controller.cancel.is_set():
+ raise Cancelled("Preview cancelled.")
+ output.publish()
+ published = True
+ if progress:
+ progress(1.0, "Preview complete")
+ return destination
+ finally:
+ if session is not None:
+ with suppress(Exception):
+ session.abort()
+ if process is not None:
+ if process.poll() is None:
+ process.kill()
+ with suppress(Exception):
+ process.wait(timeout=5)
+ controller.unregister(process)
+ if process.stdin is not None:
+ with suppress(OSError):
+ process.stdin.close()
+ output.cleanup(rollback=not published)
diff --git a/src/neural_rendering/video/models.py b/src/neural_rendering/video/models.py
index 2f0d2c5..31b7934 100644
--- a/src/neural_rendering/video/models.py
+++ b/src/neural_rendering/video/models.py
@@ -8,7 +8,8 @@ from ...core.runtime import NR_STYLES, UPSCALING_MODES
@dataclass(slots=True)
class ConversionOptions:
ai_gpu_uuid: str = "auto"
- video_gpu_uuid: str = "auto"
+ video_gpu_uuid: str = "auto"
+ prefer_nvenc: bool = True
nr_style: str = "Default"
nr_intensity: float = 1.0
nr_passes: int = 1
diff --git a/src/neural_rendering/video/processor.py b/src/neural_rendering/video/processor.py
index 75a99b4..fde5a3f 100644
--- a/src/neural_rendering/video/processor.py
+++ b/src/neural_rendering/video/processor.py
@@ -36,9 +36,35 @@ validate_codec_container = ffmpeg.validate_codec_container
_BATCH_CONTEXT = threading.local()
-def uses_nvenc_frame_boundary(codec: str) -> bool:
+def uses_nvenc_frame_boundary(codec: str) -> bool:
"""Keep decoded and encoded frames on CUDA when NVENC is selected."""
- return ffmpeg._is_nvenc_codec(codec)
+ return ffmpeg._is_nvenc_codec(codec)
+
+
+def _preferred_neural_codec(source: Path, options: ConversionOptions,
+ prepared_runtime, controller) -> ConversionOptions:
+ if not options.prefer_nvenc or options.codec not in {"H.264", "H.265", "AV1"}:
+ return options
+ try:
+ metadata = ffmpeg.probe_video(source, count_mode="metadata", controller=controller)
+ gpu = resolve_runtime_ai_gpu(prepared_runtime.gpus,
+ prepared_runtime.runtime_bundle, options.ai_gpu_uuid)
+ uuid = str(gpu["uuid"])
+ if options.video_gpu_uuid not in {"auto", uuid}:
+ return options
+ if options.scale_method == "DLSS":
+ from ...core.dlss_modes import dlss_output_size
+ width, height = dlss_output_size(int(metadata["width"]), int(metadata["height"]),
+ options.dlss_mode, even=True)
+ else:
+ width, height = resolve_output_size(int(metadata["width"]), int(metadata["height"]),
+ options.upscaling_factor)
+ codec = options.codec + " (NVIDIA NVENC)"
+ ffmpeg.resolve_video_gpu((gpu,), uuid, codec, width, height)
+ except (OSError, RuntimeError, ValueError):
+ return options
+ app_log.info("video-render", f"automatic NVIDIA NVENC selected for {options.codec}")
+ return replace(options, codec=codec, video_gpu_uuid=uuid)
def _validate_preview_options(
options: ConversionOptions,
@@ -86,8 +112,7 @@ def convert_video(
if options.scale_method not in {"Standard", "DLSS"}:
raise ValueError("Unknown Neural Rendering scale method.")
validate_dlss(options.dlss_mode, options.dlss_preset)
- cuda_path = uses_nvenc_frame_boundary(options.codec)
- hdr_requested = bool(options.preserve_hdr)
+ hdr_requested = bool(options.preserve_hdr)
if hdr_requested and not ffmpeg.hdr_mode_supported(options.codec):
raise ValueError(
f"HDR Mode is only available for a 10-bit or higher codec; "
@@ -99,9 +124,11 @@ def convert_video(
batch_controller = getattr(_BATCH_CONTEXT, "controller", None)
job_context = nullcontext(batch_controller) if batch_controller is not None else active_job(controller)
- with job_context as controller:
- assert controller is not None
- if cuda_path:
+ with job_context as controller:
+ assert controller is not None
+ options = _preferred_neural_codec(source, options, prepared_runtime, controller)
+ cuda_path = uses_nvenc_frame_boundary(options.codec)
+ if cuda_path:
from .cuda_pipeline import convert_video_cuda_nvenc
return convert_video_cuda_nvenc(
diff --git a/src/settings/models.py b/src/settings/models.py
index 67e45f4..9d2dc01 100644
--- a/src/settings/models.py
+++ b/src/settings/models.py
@@ -189,7 +189,7 @@ class UISettings:
ai_gpu_uuid: str = "auto"
video_gpu_uuid: str = "auto"
ffmpeg_device: str = "auto"
- cache_memory_mode: str = "stage"
+ cache_memory_mode: str = "rolling"
cache_codec: str = "FFV1"
nr_style: str = "Default"
nr_intensity: float = 1.0
diff --git a/src/upscale/video/dlss_pipeline.py b/src/upscale/video/dlss_pipeline.py
index 088fe6f..f7734ba 100644
--- a/src/upscale/video/dlss_pipeline.py
+++ b/src/upscale/video/dlss_pipeline.py
@@ -29,8 +29,8 @@ from .models import UpscaleResult, output_size
from .native import FORMAT_RGBA8, FORMAT_R10, RTXVideoSession, probe_capabilities
-def convert_video_dlss(source, options, *, controller, progress=None, output_dir=None,
- metadata=None, video_gpu=None):
+def convert_video_dlss(source, options, *, controller, progress=None, output_dir=None,
+ metadata=None, video_gpu=None, preview_start_seconds=0.0):
started = time.perf_counter()
metadata = metadata or inspect_video(source, controller, reject_hdr=True)
width, height = int(metadata["width"]), int(metadata["height"])
@@ -94,7 +94,10 @@ def convert_video_dlss(source, options, *, controller, progress=None, output_dir
decode_device = HWAccel(
"cuda", device=str(ordinal), allow_software_fallback=True,
options={"primary_ctx": "1"}, is_hw_owned=True)
- input_container = open_video_decoder(source, controller, pixel_format="rgba64le" if source_high_depth else "rgba")
+ input_container = open_video_decoder(
+ source, controller,
+ pixel_format="rgba64le" if source_high_depth else "rgba",
+ start_seconds=preview_start_seconds)
stream = input_container.streams.video[0]
stream.thread_type = "AUTO"
stream_tb = stream.time_base or Fraction(1, max(1, round(float(metadata["rate"]))))
@@ -194,10 +197,11 @@ def convert_video_dlss(source, options, *, controller, progress=None, output_dir
dlss.close(); dlss = None
update(.90, "Muxing audio and metadata")
audio_info = {}
- ffmpeg.final_mux(temp_video, source, output_file.temporary, options.container,
- controller, preserve_supported_subtitles=True,
- source_time_origin=metadata["origin"], audio_diagnostics=audio_info,
- video_color_metadata={
+ ffmpeg.final_mux(temp_video, source, output_file.temporary, options.container,
+ controller, preserve_supported_subtitles=True,
+ source_time_origin=metadata["origin"], audio_diagnostics=audio_info,
+ video_only=preview_start_seconds > 0,
+ video_color_metadata={
"color_space": "bt2020nc" if options.hdr_enabled else "bt709",
"color_primaries": "bt2020" if options.hdr_enabled else "bt709",
"color_transfer": "smpte2084" if options.hdr_enabled else "bt709",
diff --git a/src/upscale/video/host_pipeline.py b/src/upscale/video/host_pipeline.py
index be8a78c..b7543df 100644
--- a/src/upscale/video/host_pipeline.py
+++ b/src/upscale/video/host_pipeline.py
@@ -273,9 +273,10 @@ def convert_video_inprocess_host(
controller: Any,
progress: Callable[[float, str], None] | None,
output_dir: str | os.PathLike[str] | None,
- metadata: dict[str, Any] | None = None,
- capabilities: UpscaleCapabilities | None = None,
-) -> UpscaleResult:
+ metadata: dict[str, Any] | None = None,
+ capabilities: UpscaleCapabilities | None = None,
+ preview_start_seconds: float = 0.0,
+) -> UpscaleResult:
"""Run CPU/ProRes encoding without raw frame or NUT subprocess pipes."""
started = time.perf_counter()
report_path = app_log.session_path()
@@ -352,7 +353,10 @@ def convert_video_inprocess_host(
options={"primary_ctx": "1"}, is_hw_owned=True)
from .media import decode_filter
normalization, _ = decode_filter(metadata)
- decoded_container = open_video_decoder(source, controller, pixel_format="gbrp10le" if input_format == 2 else "rgba", video_filter=normalization)
+ decoded_container = open_video_decoder(
+ source, controller,
+ pixel_format="gbrp10le" if input_format == 2 else "rgba",
+ video_filter=normalization, start_seconds=preview_start_seconds)
input_stream = decoded_container.streams.video[0]
input_stream.thread_type = "AUTO"
decoder_iterator = iter(decoded_container.decode(input_stream))
@@ -571,10 +575,11 @@ def convert_video_inprocess_host(
update(0.90, "Muxing original audio, subtitles, chapters, and metadata")
mux_tick = time.perf_counter()
audio_diagnostics: dict = {}
- ffmpeg.final_mux(
- temp_video, source, destination_file.temporary, options.container, controller,
- preserve_supported_subtitles=True, source_time_origin=metadata["origin"],
- audio_diagnostics=audio_diagnostics)
+ ffmpeg.final_mux(
+ temp_video, source, destination_file.temporary, options.container, controller,
+ preserve_supported_subtitles=True, source_time_origin=metadata["origin"],
+ audio_diagnostics=audio_diagnostics,
+ video_only=preview_start_seconds > 0)
timings["final_mux_seconds"] = time.perf_counter() - mux_tick
update(0.96, "Verifying output frames, resolution, chroma, and HDR signaling")
verified = ffmpeg.probe_video(destination_file.temporary, count_mode="packets",
diff --git a/src/upscale/video/models.py b/src/upscale/video/models.py
index 4cda0e6..1fddf61 100644
--- a/src/upscale/video/models.py
+++ b/src/upscale/video/models.py
@@ -40,15 +40,16 @@ class UpscaleOptions:
rename_mode: str = "Auto"
custom_suffix: str = "_Upscale"
ai_gpu_uuid: str = "auto"
- video_gpu_uuid: str = "auto"
- preview_seconds: float | None = None
+ video_gpu_uuid: str = "auto"
+ prefer_nvenc: bool = True
+ preview_seconds: float | None = None
preview_frames: int | None = None
def validate(self, *, for_render: bool = True) -> None:
if self.engine not in UPSCALE_ENGINES:
raise ValueError(f"Unknown upscale engine: {self.engine!r}.")
validate_dlss(self.dlss_mode, self.dlss_preset)
- for name in ("vsr_enabled", "hdr_enabled", "aspect_lock"):
+ for name in ("vsr_enabled", "hdr_enabled", "aspect_lock", "prefer_nvenc"):
if not isinstance(getattr(self, name), bool):
raise ValueError(f"{name} must be on or off.")
for name, low, high in (
@@ -87,16 +88,21 @@ class UpscaleOptions:
raise ValueError("Select one preview limit.")
-SETTING_FIELDS = tuple(f.name for f in fields(UpscaleOptions) if f.name not in {
- "ai_gpu_uuid", "video_gpu_uuid", "preview_seconds", "preview_frames",
+SETTING_FIELDS = tuple(f.name for f in fields(UpscaleOptions) if f.name not in {
+ "ai_gpu_uuid", "video_gpu_uuid", "prefer_nvenc", "preview_seconds", "preview_frames",
})
-def options_from_settings(settings) -> UpscaleOptions:
+def options_from_settings(settings) -> UpscaleOptions:
+ from ...core.gpu_selection import prefer_cuda_video
+
values = {name: getattr(settings, "upscale_" + name) for name in SETTING_FIELDS}
values["container"] = resolve_container(values["codec"], values["container"])
- return UpscaleOptions(**values,
- ai_gpu_uuid=settings.ai_gpu_uuid, video_gpu_uuid=settings.video_gpu_uuid)
+ return UpscaleOptions(**values,
+ ai_gpu_uuid=settings.ai_gpu_uuid, video_gpu_uuid=settings.video_gpu_uuid,
+ prefer_nvenc=prefer_cuda_video(settings.ffmpeg_device,
+ settings.ai_gpu_uuid,
+ settings.video_gpu_uuid))
def output_size(width: int, height: int, options: UpscaleOptions, sar: Fraction = Fraction(1)) -> tuple[int, int, str]:
diff --git a/src/upscale/video/preview.py b/src/upscale/video/preview.py
index 28d3e7b..07ba359 100644
--- a/src/upscale/video/preview.py
+++ b/src/upscale/video/preview.py
@@ -4,6 +4,7 @@ import math
from dataclasses import replace
from pathlib import Path
+from ...core import ffmpeg
from ...core.ffmpeg.preview import LOSSLESS_PREVIEW_CODEC, decode_preview_frame
from .processor import upscale_video
@@ -26,6 +27,8 @@ def preview_upscale_native(
start = max(0.0, float(start_seconds or 0.0))
except (TypeError, ValueError):
start = 0.0
+ if not math.isfinite(start):
+ raise ValueError("Preview position must be finite.")
try:
frame_no = max(1, int(frame_index or 1)) if frame_index else 1
except (TypeError, ValueError):
@@ -35,10 +38,19 @@ def preview_upscale_native(
raise ValueError("Preview duration must be positive and finite.")
effective_path = str(path)
temp_clip: str | None = None
+ direct_seek = False
+ if start > 0 and not options.hdr_enabled:
+ metadata = ffmpeg.probe_video(path, count_mode="metadata", controller=controller)
+ direct_seek = bool(
+ metadata.get("cfr") and not metadata.get("hdr")
+ and not int(metadata.get("rotation") or 0)
+ and int(metadata.get("depth") or 8) <= 8
+ and all(metadata.get(field) == "bt709" for field in
+ ("color_space", "color_primaries", "color_transfer")))
# Both preview modes start at the parked timeline frame. Extract only
# when seeking: processing the original directly avoids an extra encode
# at the beginning of the source.
- if start > 0:
+ if start > 0 and not direct_seek:
from ...core.ffmpeg.preview import extract_preview_subclip
if progress:
try:
@@ -61,7 +73,9 @@ def preview_upscale_native(
preview_seconds=None if one_frame else length_seconds,
)
result = upscale_video(
- effective_path, opts, progress=progress, controller=controller, output_dir=output_dir
+ effective_path, opts, progress=progress, controller=controller,
+ output_dir=output_dir,
+ _preview_start_seconds=start if direct_seek else 0.0,
)
finally:
if temp_clip:
diff --git a/src/upscale/video/processor.py b/src/upscale/video/processor.py
index cf620e3..d62b9d4 100644
--- a/src/upscale/video/processor.py
+++ b/src/upscale/video/processor.py
@@ -1,10 +1,12 @@
from __future__ import annotations
+import math
from contextlib import nullcontext
from dataclasses import replace
from pathlib import Path
from ...core import app_log, ffmpeg
+from ...core.ffmpeg.preview import LOSSLESS_PREVIEW_CODEC
from ...core.gpu_detection import detect_gpus
from ...core.jobs import Cancelled, active_job
from .cuda_pipeline import convert_video_cuda_nvenc, is_nvenc
@@ -16,25 +18,53 @@ from .native import probe_capabilities
def upscale_video(input_path, options: UpscaleOptions | None = None, progress=None, *,
output_dir=None, controller=None, _owns_slot=False,
- _capabilities=None) -> UpscaleResult:
+ _capabilities=None, _preview_start_seconds: float = 0.0) -> UpscaleResult:
options = replace(options) if options else UpscaleOptions()
options.validate()
source = Path(input_path).resolve()
if not source.is_file():
raise FileNotFoundError(source)
+ if (not math.isfinite(_preview_start_seconds) or _preview_start_seconds < 0):
+ raise ValueError("Invalid preview seek position.")
+ if _preview_start_seconds > 0 and (
+ (options.preview_frames is None and options.preview_seconds is None)
+ or options.codec != LOSSLESS_PREVIEW_CODEC):
+ raise ValueError("Direct seeking requires a lossless preview.")
context = nullcontext(controller) if _owns_slot else active_job(controller)
with context as controller:
- return _process(source, options, progress, output_dir, controller, _capabilities)
+ return _process(source, options, progress, output_dir, controller,
+ _capabilities, _preview_start_seconds)
-def _process(source, options, progress, output_dir, controller, capabilities):
+def _process(source, options, progress, output_dir, controller, capabilities,
+ preview_start_seconds):
app_log.info("upscale", f"start src={source.name}")
try:
if progress:
progress(0.01, "Checking SDR source and RTX Video capabilities")
metadata = inspect_video(source, controller, reject_hdr=True)
+ if preview_start_seconds > 0:
+ # The established preview's FFV1 seek clip promotes SDR samples to
+ # 10-bit RGB before the RTX/DLSS host boundary. Preserve that
+ # processing precision while decoding the original video directly.
+ metadata = {**metadata, "depth": max(10, int(metadata["depth"]))}
output_width, output_height, _ = output_size(
metadata["width"], metadata["height"], options)
+ if options.prefer_nvenc and options.codec in {"H.264", "H.265", "AV1"}:
+ from ...core.gpu_selection import detect_gpu
+
+ try:
+ ai_gpu = detect_gpu(options.ai_gpu_uuid)
+ preferred_uuid = (str(ai_gpu["uuid"]) if options.video_gpu_uuid == "auto"
+ else options.video_gpu_uuid)
+ candidate = options.codec + " (NVIDIA NVENC)"
+ ffmpeg.resolve_video_gpu(detect_gpus(), preferred_uuid, candidate,
+ output_width, output_height)
+ except (OSError, RuntimeError, ValueError):
+ pass
+ else:
+ app_log.info("upscale", f"automatic NVIDIA NVENC selected for {options.codec}")
+ options = replace(options, codec=candidate, video_gpu_uuid=preferred_uuid)
capabilities = capabilities or (probe_capabilities(
options.ai_gpu_uuid, controller=controller)
if options.engine != "DLSS" or options.hdr_enabled else None)
@@ -61,7 +91,8 @@ def _process(source, options, progress, output_dir, controller, capabilities):
app_log.info("upscale-dlss", "NVDEC unavailable; using the host frame boundary")
return convert_video_dlss(
source, options, controller=controller, progress=progress,
- output_dir=output_dir, metadata=metadata, video_gpu=video_gpu)
+ output_dir=output_dir, metadata=metadata, video_gpu=video_gpu,
+ preview_start_seconds=preview_start_seconds)
requested_video_gpu = (
str(capabilities.gpu["uuid"])
if options.video_gpu_uuid == "auto"
@@ -82,7 +113,7 @@ def _process(source, options, progress, output_dir, controller, capabilities):
return convert_video_inprocess_host(
source, options, controller=controller, progress=progress,
output_dir=output_dir, metadata=metadata,
- capabilities=capabilities)
+ capabilities=capabilities, preview_start_seconds=preview_start_seconds)
except BaseException as exc:
cancelled = controller.cancel.is_set() or isinstance(exc, Cancelled)
if cancelled: