"""Generic video helpers for sequential ComfyUI projects. The nodes in this module deliberately operate on ordinary IMAGE/AUDIO values and completed video paths. They do not depend on a particular video model or custom sampler. """ import json import os import re import subprocess import tempfile import time import wave from pathlib import Path try: import numpy as np except ImportError: # The ComfyUI runtime provides NumPy; keep import-time tests lightweight. np = None import folder_paths _SAFE_NAME = re.compile(r"[^A-Za-z0-9_.-]+") def _safe_name(value, fallback): name = _SAFE_NAME.sub("_", str(value or "").strip()).strip("._") return name or fallback def _output_path(prefix, suffix="mp4"): root = Path(folder_paths.get_output_directory()) root.mkdir(parents=True, exist_ok=True) stamp = time.strftime("%Y%m%d_%H%M%S") return root / f"{_safe_name(prefix, 'clip')}_{stamp}_{time.time_ns() % 1000000:06d}.{suffix}" def _audio_arrays(audio): if np is None: raise RuntimeError("NumPy is required to encode video frames.") if not audio: return None waveform = audio.get("waveform") if isinstance(audio, dict) else None sample_rate = int(audio.get("sample_rate", 48000)) if isinstance(audio, dict) else 48000 if waveform is None: return None values = waveform.detach().cpu().numpy() if hasattr(waveform, "detach") else np.asarray(waveform) if values.ndim == 3: values = values[0] if values.ndim == 1: values = values[None, :] if values.shape[0] == 1: values = np.repeat(values, 2, axis=0) values = values[:2] return np.clip(values, -1.0, 1.0), sample_rate def _write_wav(audio, path, start_sample=0): prepared = _audio_arrays(audio) if prepared is None: return None values, sample_rate = prepared values = values[:, start_sample:] interleaved = (values.T * 32767.0).astype("= total: raise ValueError(f"Overlap ({overlap}) must be smaller than the clip ({total} frames).") full = _output_path(f"{filename_prefix}_full") complete = _output_path(f"{filename_prefix}_complete") _encode_images(images, audio, full, float(fps), 0) _encode_images(images, audio, complete, float(fps), overlap) count = total - overlap return str(full), str(complete), count, count / float(fps) class DumasJoinVideoClipsNode: """Concatenate already-complete clips with FFmpeg stream copy.""" @classmethod def INPUT_TYPES(cls): return { "required": {"clip_1": ("STRING", {"default": "", "multiline": False})}, "optional": { "clip_2": ("STRING", {"default": ""}), "clip_3": ("STRING", {"default": ""}), "clip_4": ("STRING", {"default": ""}), "clip_5": ("STRING", {"default": ""}), "clip_6": ("STRING", {"default": ""}), "filename_prefix": ("STRING", {"default": "dumas/assembled_video"}), }, } RETURN_TYPES = ("STRING", "INT", "FLOAT") RETURN_NAMES = ("joined_clip", "clip_count", "duration") FUNCTION = "join" CATEGORY = "Dumas/Video" OUTPUT_NODE = True def join(self, clip_1, clip_2="", clip_3="", clip_4="", clip_5="", clip_6="", filename_prefix="dumas/assembled_video"): clips = [str(path).strip().strip('"').strip("'") for path in (clip_1, clip_2, clip_3, clip_4, clip_5, clip_6) if str(path or "").strip()] if not clips: raise ValueError("Connect at least one completed clip.") if any(not os.path.isfile(path) for path in clips): missing = next(path for path in clips if not os.path.isfile(path)) raise FileNotFoundError(f"Completed clip not found: {missing}") signatures = [_join_signature(_probe(path)) for path in clips] if any(signature != signatures[0] for signature in signatures[1:]): raise ValueError("Clips do not share compatible codec, dimensions, frame rate, pixel format or audio format.") output = _output_path(filename_prefix) with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False, encoding="utf-8") as handle: list_path = Path(handle.name) for path in clips: escaped = str(Path(path).resolve()).replace("'", "'\\''") handle.write(f"file '{escaped}'\n") try: command = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-f", "concat", "-safe", "0", "-i", str(list_path), "-c", "copy", "-movflags", "+faststart", str(output)] result = subprocess.run(command, capture_output=True, text=True, check=False) if result.returncode != 0: raise RuntimeError(f"ffmpeg could not join the clips without re-encoding: {result.stderr.strip()}") finally: list_path.unlink(missing_ok=True) duration = float((_probe(output).get("format") or {}).get("duration") or 0.0) return str(output), len(clips), duration NODE_CLASS_MAPPINGS = { "DumasStandaloneVideo": DumasStandaloneVideoNode, "DumasJoinVideoClips": DumasJoinVideoClipsNode, } NODE_DISPLAY_NAME_MAPPINGS = { "DumasStandaloneVideo": "Dumas Standalone Video", "DumasJoinVideoClips": "Dumas Join Video Clips (No Re-encode)", }