diff --git a/README.md b/README.md index c1396b1..2a538cc 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,14 @@ frame count. It produces a clean presentation clip and a `next_reference` tail clip. Only the tail is intended to feed the next generation; the entire previous clip is never passed forward as the continuity input. +### Save Video DUMAS + +Save an IMAGE batch as an H.264 MP4 in any server-side folder. The folder can +be typed directly or selected with the Browse folder button; leaving it empty +uses ComfyUI's output folder. Filename patterns support nested folders and +`%counter%`, and existing files are never overwritten. Optional audio is +encoded as AAC, and preview mode writes to ComfyUI's temporary directory. + ## Other nodes - Dumas Image Compare diff --git a/dumas_video_nodes.py b/dumas_video_nodes.py index fcade67..b3a860f 100644 --- a/dumas_video_nodes.py +++ b/dumas_video_nodes.py @@ -21,6 +21,11 @@ except ImportError: # The ComfyUI runtime provides NumPy; keep import-time test import folder_paths +try: + from .dumas_image_nodes import _next_available_relative_path +except ImportError: # Support the lightweight standalone test import. + from dumas_image_nodes import _next_available_relative_path + _SAFE_NAME = re.compile(r"[^A-Za-z0-9_.-]+") @@ -72,7 +77,7 @@ def _write_wav(audio, path, start_sample=0): return sample_rate -def _encode_images(images, audio, output_path, fps, start_frame=0): +def _encode_images(images, audio, output_path, fps, start_frame=0, quality=18): if images is None or len(images) <= start_frame: raise ValueError("Dumas video output has no frames after the requested overlap.") first = images[0].detach().cpu().numpy() if hasattr(images[0], "detach") else np.asarray(images[0]) @@ -93,7 +98,8 @@ def _encode_images(images, audio, output_path, fps, start_frame=0): ] if wav_path is not None: command += ["-i", str(wav_path)] - command += ["-map", "0:v:0", "-c:v", "libx264", "-preset", "fast", "-crf", "18", "-pix_fmt", "yuv420p"] + crf = max(1, min(51, int(quality))) + command += ["-map", "0:v:0", "-c:v", "libx264", "-preset", "fast", "-crf", str(crf), "-pix_fmt", "yuv420p"] if wav_path is not None: command += ["-map", "1:a:0", "-c:a", "aac", "-b:a", "192k", "-shortest"] command += ["-movflags", "+faststart", str(output_path)] @@ -238,6 +244,62 @@ class DumasStandaloneVideoNode: return str(full), str(complete), count, count / float(fps), reference +class DumasSaveVideoNode: + """Save an IMAGE batch as an MP4 in any user-selected folder.""" + + DESCRIPTION = ( + "Save Video DUMAS writes an image batch as an MP4 to any folder on the " + "server. Leave the folder empty for ComfyUI's output folder, or type " + "an absolute path. Existing files are never overwritten." + ) + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "fps": ("FLOAT", {"default": 24.0, "min": 1.0, "max": 240.0, "step": 0.001}), + "folder": ("STRING", {"default": "", "multiline": False}), + "filename": ("STRING", {"default": "dumas_video_%counter%", "multiline": False}), + "quality": ("INT", {"default": 18, "min": 1, "max": 51}), + "save_on_run": ("BOOLEAN", {"default": True}), + }, + "optional": {"audio": ("AUDIO",)}, + } + + @classmethod + def IS_CHANGED(cls, **_kwargs): + return float("nan") + + RETURN_TYPES = ("STRING", "INT", "FLOAT") + RETURN_NAMES = ("video_path", "frames", "duration") + FUNCTION = "save" + CATEGORY = "Dumas/Video" + OUTPUT_NODE = True + + def save(self, images, fps, folder, filename, quality, save_on_run=True, audio=None): + if images is None or len(images) == 0: + raise ValueError("Save Video DUMAS received no frames.") + fps = float(fps) + if fps <= 0: + raise ValueError("FPS must be greater than zero.") + base = Path(folder).expanduser() if str(folder or "").strip() else Path(folder_paths.get_output_directory()) + if not save_on_run: + base = Path(folder_paths.get_temp_directory()) + base = base.resolve() + base.mkdir(parents=True, exist_ok=True) + relative = str(filename or "dumas_video_%counter%").replace("\\", "/").strip().lstrip("/") + if not relative.lower().endswith(".mp4"): + relative += ".mp4" + relative = _next_available_relative_path(str(base), relative) + target = (base / relative).resolve() + if os.path.commonpath((str(base), str(target))) != str(base): + raise ValueError("Video filename must stay inside the selected folder.") + _encode_images(images, audio, target, fps, 0, quality) + frames = len(images) + return {"ui": {"text": [str(target)]}, "result": (str(target), frames, frames / fps)} + + class DumasPrepareContinuationNode: """Prepare a generated continuation for chaining and presentation. @@ -369,12 +431,14 @@ class DumasJoinVideoClipsNode: NODE_CLASS_MAPPINGS = { "DumasStandaloneVideo": DumasStandaloneVideoNode, + "DumasSaveVideo": DumasSaveVideoNode, "DumasPrepareContinuation": DumasPrepareContinuationNode, "DumasJoinVideoClips": DumasJoinVideoClipsNode, } NODE_DISPLAY_NAME_MAPPINGS = { "DumasStandaloneVideo": "Dumas Standalone Video", + "DumasSaveVideo": "Save Video DUMAS", "DumasPrepareContinuation": "Dumas Prepare Continuation", "DumasJoinVideoClips": "Dumas Join Video Clips (No Re-encode)", } diff --git a/js/dumas_save_video.js b/js/dumas_save_video.js new file mode 100644 index 0000000..63fed8d --- /dev/null +++ b/js/dumas_save_video.js @@ -0,0 +1,45 @@ +import { app } from "/scripts/app.js"; + +const CLASS = "DumasSaveVideo"; + +function widget(node, name) { return node.widgets?.find((item) => item.name === name); } + +app.registerExtension({ + name: "Dumas.SaveVideo", + nodeCreated(node) { + if (node.comfyClass !== CLASS) return; + const folder = widget(node, "folder"); + if (!folder || typeof node.addDOMWidget !== "function") return; + const root = document.createElement("div"); + root.style.cssText = "display:flex;gap:5px;align-items:center;padding:4px 0;color:#bbb;font:11px system-ui"; + const button = document.createElement("button"); + button.type = "button"; + button.textContent = "Browse folder"; + button.title = "Choose the server-side folder used for the next save"; + const label = document.createElement("span"); + label.textContent = "Any server folder"; + root.append(button, label); + const dom = node.addDOMWidget("dumas_save_video_folder", "custom", root, { serialize: false, getMinHeight: () => 28 }); + dom.computeLayoutSize = () => ({ minHeight: 28, minWidth: 1 }); + button.addEventListener("click", async (event) => { + event.preventDefault(); + event.stopPropagation(); + button.disabled = true; + try { + const response = await fetch(`/dumas/api/pick_directory?path=${encodeURIComponent(String(folder.value || ""))}`); + const data = await response.json(); + if (data?.ok && data.path) { + folder.value = data.path; + folder.callback?.(data.path); + label.textContent = data.path; + node.setDirtyCanvas?.(true, true); + } + } catch (error) { + console.warn("DUMAS Save Video folder picker failed", error); + } finally { + button.disabled = false; + } + }); + node._dumasSaveVideoFolderWidget = dom; + }, +}); diff --git a/tests/test_dumas_video_nodes.py b/tests/test_dumas_video_nodes.py index fb64632..5410167 100644 --- a/tests/test_dumas_video_nodes.py +++ b/tests/test_dumas_video_nodes.py @@ -17,9 +17,16 @@ class DumasVideoNodeTests(unittest.TestCase): def test_registers_generic_video_nodes(self): self.assertEqual( set(self.module.NODE_CLASS_MAPPINGS), - {"DumasStandaloneVideo", "DumasPrepareContinuation", "DumasJoinVideoClips"}, + {"DumasStandaloneVideo", "DumasSaveVideo", "DumasPrepareContinuation", "DumasJoinVideoClips"}, ) + def test_save_video_exposes_external_folder_and_safe_outputs(self): + node = self.module.DumasSaveVideoNode + required = node.INPUT_TYPES()["required"] + self.assertIn("folder", required) + self.assertIn("filename", required) + self.assertEqual(node.RETURN_NAMES, ("video_path", "frames", "duration")) + def test_standalone_node_exposes_full_and_complete_outputs(self): node = self.module.DumasStandaloneVideoNode self.assertEqual(