The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Open engine: stream-copy mux, chunked caption burn-in, clip-aware prompts
Claudefd3a5b8bb50f
diff --git a/scripts/comfy/hand-built/captions-burnin.json b/scripts/comfy/hand-built/captions-burnin.jsonindex 9707d53f..46f08368 100644--- a/scripts/comfy/hand-built/captions-burnin.json+++ b/scripts/comfy/hand-built/captions-burnin.json@@ -1,37 +1,35 @@{"1": { "class_type": "LoadVideo", "inputs": { "file": "input.mp4" }, "_meta": { "title": "Video to caption" } },- "2": { "class_type": "GetVideoComponents", "inputs": { "video": ["1", 0] }, "_meta": { "title": "Soundtrack + fps of the whole clip" } },+ "3": { "class_type": "LoadAudio", "inputs": { "audio": "input.mp4" }, "_meta": { "title": "Its soundtrack, laid under the result (dropped for silent clips)" } },"10": {"class_type": "Video Slice","inputs": { "video": ["1", 0], "start_time": 0.0, "duration": 0.5, "strict_duration": false },- "_meta": { "title": "Caption segment 1 (the app writes one per cue)" }+ "_meta": { "title": "Captioned chunk 1 (the app writes one chunk per cue piece)" }},- "11": { "class_type": "GetVideoComponents", "inputs": { "video": ["10", 0] }, "_meta": { "title": "Segment 1 frames" } },+ "11": { "class_type": "GetVideoComponents", "inputs": { "video": ["10", 0] }, "_meta": { "title": "Chunk 1 frames (only this chunk is decoded)" } },"12": {"class_type": "TextOverlay","inputs": { "images": ["11", 0], "text": "Fuobe captions", "font_size": 6.0, "color": "#ffffff", "position": "bottom", "align": "center", "outline": true },- "_meta": { "title": "Caption style (copied to every cue)" }+ "_meta": { "title": "Caption style (copied to every chunk)" }+ },+ "13": {+ "class_type": "CreateVideo",+ "inputs": { "images": ["12", 0], "fps": ["11", 2], "audio": ["11", 1], "bit_depth": "auto", "color_space": "sRGB", "codec": "h264" },+ "_meta": { "title": "Chunk 1 encoded right away (its frames can leave memory)" }},"20": {"class_type": "Video Slice","inputs": { "video": ["1", 0], "start_time": 0.5, "duration": 0.0, "strict_duration": false },- "_meta": { "title": "Caption segment 2 (to the end)" }+ "_meta": { "title": "Gap without a caption (never decoded here)" }},- "21": { "class_type": "GetVideoComponents", "inputs": { "video": ["20", 0] }, "_meta": { "title": "Segment 2 frames" } },- "22": {- "class_type": "TextOverlay",- "inputs": { "images": ["21", 0], "text": "burned into the frames", "font_size": 6.0, "color": "#ffffff", "position": "bottom", "align": "center", "outline": true },- "_meta": { "title": "Caption 2" }- },- "90": { "class_type": "BatchImagesNode", "inputs": { "images.image0": ["12", 0], "images.image1": ["22", 0] }, "_meta": { "title": "Segments in order" } },- "91": {- "class_type": "CreateVideo",- "inputs": { "images": ["90", 0], "fps": ["2", 2], "audio": ["2", 1], "bit_depth": "auto", "color_space": "sRGB", "codec": "none" },- "_meta": { "title": "Captioned video (source fps + audio)" }+ "90": {+ "class_type": "ConcatenateVideo",+ "inputs": { "videos.video0": ["13", 0], "videos.video1": ["20", 0], "codec": "auto", "complete_audio": ["3", 0] },+ "_meta": { "title": "Chunks and gaps in order, with the clip's soundtrack" }},"92": {"class_type": "SaveVideo",- "inputs": { "video": ["91", 0], "filename_prefix": "fuobe/captions-burnin", "format": "auto", "format.codec": "auto", "codec": "auto" },+ "inputs": { "video": ["90", 0], "filename_prefix": "fuobe/captions-burnin", "format": "auto", "format.codec": "auto", "codec": "auto" },"_meta": { "title": "Save video" }}}diff --git a/scripts/comfy/hand-built/captions-qwen3-asr.json b/scripts/comfy/hand-built/captions-qwen3-asr.jsonindex dbde7a5d..ac37bff7 100644--- a/scripts/comfy/hand-built/captions-qwen3-asr.json+++ b/scripts/comfy/hand-built/captions-qwen3-asr.json@@ -21,7 +21,7 @@"forced_aligner": "Qwen/Qwen3-ForcedAligner-0.6B-hf","language": "auto","hints": "",- "output_format": "srt",+ "output_format": "none","output_path": "fuobe/captions","split_mode": "split_by_punctuation_or_pause_or_length","max_gap_sec": 0.6,diff --git a/scripts/comfy/hand-built/layers-qwen-image-layered.json b/scripts/comfy/hand-built/layers-qwen-image-layered.jsonindex e58090a1..be0100fe 100644--- a/scripts/comfy/hand-built/layers-qwen-image-layered.json+++ b/scripts/comfy/hand-built/layers-qwen-image-layered.json@@ -252,7 +252,7 @@"83:78",1],- "layers": 2,+ "layers": 4,"batch_size": 1},"class_type": "EmptyQwenImageLayeredLatentImage",diff --git a/scripts/comfy/hand-built/lipsync-v2v-infinitetalk.json b/scripts/comfy/hand-built/lipsync-v2v-infinitetalk.jsonindex 29dcc97d..a6c9038d 100644--- a/scripts/comfy/hand-built/lipsync-v2v-infinitetalk.json+++ b/scripts/comfy/hand-built/lipsync-v2v-infinitetalk.json@@ -253,11 +253,8 @@"245",0],- "custom_height": [- "246",- 0- ],- "frame_load_cap": 0,+ "custom_height": 0,+ "frame_load_cap": 1000,"skip_first_frames": 0,"select_every_nth": 1,"format": "Wan"diff --git a/scripts/comfy/hand-built/video-mux-audio-replace.json b/scripts/comfy/hand-built/video-mux-audio-replace.jsonindex 96641b07..f673e311 100644--- a/scripts/comfy/hand-built/video-mux-audio-replace.json+++ b/scripts/comfy/hand-built/video-mux-audio-replace.json@@ -1,11 +1,10 @@{- "1": { "class_type": "LoadVideo", "inputs": { "file": "input.mp4" }, "_meta": { "title": "Video" } },- "2": { "class_type": "GetVideoComponents", "inputs": { "video": ["1", 0] }, "_meta": { "title": "Frames + fps" } },+ "1": { "class_type": "LoadVideo", "inputs": { "file": "input.mp4" }, "_meta": { "title": "Video (its picture is copied, never decoded)" } },"3": { "class_type": "LoadAudio", "inputs": { "audio": "soundtrack.wav" }, "_meta": { "title": "New soundtrack (audio)" } },"7": {- "class_type": "CreateVideo",- "inputs": { "images": ["2", 0], "fps": ["2", 2], "audio": ["3", 0], "bit_depth": "auto", "color_space": "sRGB", "codec": "none" },- "_meta": { "title": "Video with the new soundtrack" }+ "class_type": "ConcatenateVideo",+ "inputs": { "videos.video0": ["1", 0], "codec": "auto", "complete_audio": ["3", 0] },+ "_meta": { "title": "Same picture, new soundtrack (stream copy)" }},"8": {"class_type": "SaveVideo",diff --git a/scripts/comfy/hand-built/video-mux-audio.json b/scripts/comfy/hand-built/video-mux-audio.jsonindex 5ec7864a..dbfbab95 100644--- a/scripts/comfy/hand-built/video-mux-audio.json+++ b/scripts/comfy/hand-built/video-mux-audio.json@@ -1,110 +1,19 @@{- "1": {- "class_type": "LoadVideo",- "inputs": {- "file": "input.mp4"- },- "_meta": {- "title": "LoadVideo"- }- },- "2": {- "class_type": "GetVideoComponents",- "inputs": {- "video": [- "1",- 0- ]- },- "_meta": {- "title": "GetVideoComponents"- }- },- "3": {- "class_type": "LoadAudio",- "inputs": {- "audio": "dub_voice.mp3"- },- "_meta": {- "title": "LoadAudio"- }- },- "4": {- "class_type": "LoadAudio",- "inputs": {- "audio": "background.mp3"- },- "_meta": {- "title": "LoadAudio"- }- },- "5": {- "class_type": "AudioAdjustVolume",- "inputs": {- "audio": [- "4",- 0- ],- "volume": 0- },- "_meta": {- "title": "AudioAdjustVolume"- }- },- "6": {- "class_type": "AudioMerge",- "inputs": {- "audio1": [- "3",- 0- ],- "audio2": [- "5",- 0- ],- "merge_method": "add"- },- "_meta": {- "title": "AudioMerge"- }- },+ "1": { "class_type": "LoadVideo", "inputs": { "file": "input.mp4" }, "_meta": { "title": "Video (its picture is copied, never decoded)" } },+ "3": { "class_type": "LoadAudio", "inputs": { "audio": "dub_voice.mp3" }, "_meta": { "title": "New voice (audio)" } },+ "4": { "class_type": "LoadAudio", "inputs": { "audio": "background.mp3" }, "_meta": { "title": "Background stem or music bed (audio2)" } },+ "5": { "class_type": "AudioAdjustVolume", "inputs": { "audio": ["4", 0], "volume": 0 }, "_meta": { "title": "Background level (dB)" } },+ "9": { "class_type": "EmptyAudio", "inputs": { "duration": 60.0, "sample_rate": 44100, "channels": 2 }, "_meta": { "title": "Soundtrack length (the video's)" } },+ "10": { "class_type": "AudioMerge", "inputs": { "audio1": ["9", 0], "audio2": ["5", 0], "merge_method": "add" }, "_meta": { "title": "Background over silence" } },+ "6": { "class_type": "AudioMerge", "inputs": { "audio1": ["10", 0], "audio2": ["3", 0], "merge_method": "add" }, "_meta": { "title": "Voice over the background" } },"7": {- "class_type": "CreateVideo",- "inputs": {- "images": [- "2",- 0- ],- "fps": [- "2",- 2- ],- "audio": [- "6",- 0- ],- "bit_depth": "auto",- "color_space": "sRGB",- "codec": "none"- },- "_meta": {- "title": "CreateVideo"- }+ "class_type": "ConcatenateVideo",+ "inputs": { "videos.video0": ["1", 0], "codec": "auto", "complete_audio": ["6", 0] },+ "_meta": { "title": "Same picture, new soundtrack (stream copy)" }},"8": {"class_type": "SaveVideo",- "inputs": {- "video": [- "7",- 0- ],- "filename_prefix": "fuobe/video-mux-audio",- "format": "auto",- "format.codec": "auto",- "codec": "auto"- },- "_meta": {- "title": "SaveVideo"- }+ "inputs": { "video": ["7", 0], "filename_prefix": "fuobe/video-mux-audio", "format": "auto", "format.codec": "auto", "codec": "auto" },+ "_meta": { "title": "Save video" }}}diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjsindex 9d11e610..1c0edf0c 100644--- a/scripts/comfy/library.spec.mjs+++ b/scripts/comfy/library.spec.mjs@@ -1755,7 +1755,7 @@ export const SPEC = [license: 'Apache-2.0 (Qwen-Image-Layered weights and the Comfy-Org repack)',notes:'Template image_qwen_image_layered with the fp8mixed weights (bf16 is 40.9 GB). The input is scaled so its longest side = maxSize (640 is the trained bucket; 1024 works, slower). ' +- 'numLayers = how many RGBA layers come out (1-10; the latent holds numLayers+1 slices and slice 0, the reconstructed composite, is cut off by LatentCut). prompt = optional caption of the whole image. ' ++ 'numLayers = how many RGBA layers come out (1-10, default 4 like the model card; the latent holds numLayers+1 slices and slice 0, the reconstructed composite, is cut off by LatentCut). prompt = optional caption of the whole image. ' +'SaveImage writes one full-canvas RGBA PNG per layer, back to front: the provider reports them in that order with meta {name, z, bbox} (bbox from the alpha channel). "Separate layer" = run again on one layer.',},{@@ -1809,8 +1809,8 @@ export const SPEC = [vramGb: 10,license: 'Apache-2.0 (FLUX.2 [klein] 4B)',notes:- 'Template image_flux2_klein_image_edit_4b_distilled with two extra ReferenceLatent references and an explicit output size. All four references are required: ' +- 'the provider repeats the last image when fewer are given. Fast (4 steps, 8-10 GB). Weaker than Qwen-Image-Edit-2511 on complex prompts.',+ 'Template image_flux2_klein_image_edit_4b_distilled with two extra ReferenceLatent references and an explicit output size. 1-4 references: ' ++ 'the provider bypasses the ReferenceLatent pair of each reference not given (bypassReference). Fast (4 steps, 8-10 GB). Weaker than Qwen-Image-Edit-2511 on complex prompts.',},{id: 'style-ref-krea2',@@ -2056,15 +2056,16 @@ export const SPEC = [notes:'Default caption source for Faceless / Shorts. Changed from the research graph: LoadAudio instead of LoadVideo + GetVideoComponents (audio or video input). ' +'maxChars 32 + split_by_punctuation_or_pause_or_length gives short vertical-video lines. The text output is one "start-end: text" line per cue; the provider parses it into meta.cues. ' ++ 'output_format none: the node writes no file of its own (concurrent jobs would race on one captions.srt); SaveText returns the cues. ' +'Burn the cues in with captions-burnin (chain: transcript text -> prompt).',},{id: 'captions-burnin',- title: 'Burn captions into a video (core Draw Text Overlay, one segment per cue)',+ title: 'Burn captions into a video (core Draw Text Overlay, chunk by chunk)',capability: 'captions',handBuilt: 'hand-built/captions-burnin.json',bindings: {- video: [b('1', 'file')], fontSize: [b('12', 'font_size')], fontColor: [b('12', 'color')], captionPosition: [b('12', 'position')],+ video: [b('1', 'file'), b('3', 'audio')], fontSize: [b('12', 'font_size')], fontColor: [b('12', 'color')], captionPosition: [b('12', 'position')],},outputs: [{ node: '92', kind: 'video' }],defaults: { fontColor: '#ffffff', captionPosition: 'bottom' },@@ -2072,10 +2073,14 @@ export const SPEC = [vramGb: 0,license: 'no model (ComfyUI core TextOverlay, GPL-3.0 like ComfyUI; Pillow\'s bundled Aileron font, OFL)',notes:- 'Fuobe\'s open caption burn-in, all inside ComfyUI with core nodes. The provider rewrites the graph per request: the cues (prompt lines "start-end: text" or SRT, e.g. from captions-qwen3-asr) become ' +- 'one Trim Video segment per cue and per gap, each cue segment gets a TextOverlay with the style of node 12 (fontSize = % of the frame height, fontColor, captionPosition top | bottom, outlined), ' +- 'BatchImagesNode joins the segments in order and CreateVideo restores the source fps and soundtrack. The last cue stays up to the end of the clip (a segment may not start after the end). ' +- 'Holds the clip\'s frames in memory about three times (fine for Shorts up to a minute at 720p). Runs on CPU (verified end to end through Fuobe).',+ 'Fuobe\'s open caption burn-in, all inside ComfyUI with core nodes. The provider rewrites the graph per request (expandCaptionWorkflow): the cues (prompt lines "start-end: text" or SRT, e.g. from captions-qwen3-asr) ' ++ 'cut the clip into Trim Video windows. Gaps go straight to Concatenate Video (never decoded). A cue window is cut into chunks of at most ~384 MB of frames (about 0.5 s of 1080x1920 at 30 fps, 5 s at 360p); ' ++ 'each chunk is decoded (GetVideoComponents), gets a TextOverlay in the style of node 12 (fontSize = % of the frame height, fontColor, captionPosition top | bottom, outlined) and is encoded at once (CreateVideo codec h264), ' ++ 'so ComfyUI only needs one chunk of raw frames at a time and can evict finished chunks under memory pressure. Concatenate Video joins chunks and gaps in order and lays the clip\'s own soundtrack (LoadAudio, node 3) ' ++ 'under the result; for a silent clip node 3 is dropped. The provider reads the upload\'s MP4 header for duration, fps, size and audio: window edges sit between frames, cues past the end are dropped and the rest of the clip after the last cue stays uncaptioned. ' ++ 'Windows hold at least 3 frames (Concatenate Video rejects a 2-frame clip followed by another): a shorter pause between cues gets no gap, a shorter caption is held for 3 frames. ' ++ 'Measured on the CPU server under RAM pressure (--cache-ram 11): a 20 s 640x360 30 fps clip with 18 s of captions peaks at +0.50 GB RSS and a 40 s one at +0.45 GB (the old one-batch graph: +5.16 GB for the 20 s clip); ' ++ 'without pressure ComfyUI\'s RAM cache keeps finished chunks (+2.64 GB for 20 s) until memory runs low. Runs on CPU (verified end to end through Fuobe).',},{id: 'captions-whisper-burnin',@@ -2092,7 +2097,9 @@ export const SPEC = [autoDownloads: ['Apply Whisper downloads large-v3-turbo.pt (1.62 GB) into models/stt/whisper on first run'],notes:'All-ComfyUI alternative that transcribes and burns in one job (word-by-word captions from words_alignment). One style per run (font, size, colour, border, centred). ' +- 'Because of the NC code licence the default open route is captions-qwen3-asr + captions-burnin. Save SRT (not an output node) is dropped; the transcript text is kept.',+ 'Because of the NC code licence the default open route is captions-qwen3-asr + captions-burnin, and install-comfyui.sh only installs ComfyUI-Whisper with NC_PACKS=1. Save SRT (not an output node) is dropped; the transcript text is kept. ' ++ 'VHS_LoadVideo decodes the whole clip and Add Subtitles To Frames copies it (about 2.5 copies of the frames in RAM): the provider refuses clips that would need more than half of the ComfyUI server\'s RAM and points to the chunked route. ' ++ 'sourceLanguage takes Whisper\'s own names (the provider maps ISO codes: tl/fil -> Tagalog, he -> Hebrew).',},{id: 'translate-qwen35-textgen',@@ -2134,17 +2141,20 @@ export const SPEC = [handBuilt: 'hand-built/lipsync-v2v-infinitetalk.json',bindings: {video: [b('228', 'video')], audio: [b('125', 'audio')], prompt: [b('241', 'positive_prompt')], negativePrompt: [b('241', 'negative_prompt')],- width: [b('245', 'value')], height: [b('246', 'value')], frames: [b('270', 'value')], seed: [b('128', 'seed')], steps: [b('128', 'steps')],+ width: [b('245', 'value')], height: [b('246', 'value')], frames: [b('270', 'value'), b('228', 'frame_load_cap')], seed: [b('128', 'seed')], steps: [b('128', 'steps')],startStep: [b('128', 'start_step')], audioScale: [b('194', 'audio_scale')],},outputs: [{ node: '131', kind: 'video' }],- limits: { maxWidth: 1280, maxHeight: 1280, dimensionMultiple: 16 },+ defaults: { fps: 25 },+ limits: { maxWidth: 1280, maxHeight: 1280, dimensionMultiple: 16, maxFrames: 1000 },vramGb: 24,license: 'Apache-2.0 (Wan 2.1, InfiniteTalk, lightx2v)',autoDownloads: ['DownloadAndLoadWav2VecModel fetches TencentGameMate/chinese-wav2vec2-base (0.38 GB) on first run'],notes:'Same model files as infinitetalk-wanwrapper (no new download). The source frames are VAE-encoded and only the last steps are re-denoised (steps 4, startStep 2), so camera, background and body stay; ' +- 'mouth, head and upper body follow the new audio. 81-frame windows until the audio ends (frames = cap @25 fps). Pass the clean dubbed voice, then mux the background with video-mux-audio.',+ 'mouth, head and upper body follow the new audio. 81-frame windows until the audio ends. Changed from the research graph: VHS_LoadVideo gets only custom_width (height 0 keeps the source\'s proportions, no squashing) ' ++ 'and ImageResizeKJv2 crops to width x height, which the provider takes from the source\'s own shape (aspect ratio "auto", read from the MP4 header) at the chosen resolution; ' ++ 'frames (num_frames and VHS frame_load_cap) = the voice\'s length at 25 fps, at most 1000 (40 s): the provider refuses a longer voice instead of cutting it. Pass the clean dubbed voice, then mux the background with video-mux-audio.',},{id: 'lipsync-latentsync16',@@ -2166,16 +2176,20 @@ export const SPEC = [},{id: 'video-mux-audio',- title: 'Add a soundtrack: new voice + background stem mixed onto a video',+ title: 'Add a soundtrack: new voice + background stem mixed onto a video (picture stream-copied)',capability: 'mux',handBuilt: 'hand-built/video-mux-audio.json',- bindings: { video: [b('1', 'file')], audio: [b('3', 'audio')], audio2: [b('4', 'audio')], backgroundVolumeDb: [b('5', 'volume')] },+ bindings: {+ video: [b('1', 'file')], audio: [b('3', 'audio')], audio2: [b('4', 'audio')], backgroundVolumeDb: [b('5', 'volume')], duration: [b('9', 'duration')],+ },outputs: [{ node: '8', kind: 'video' }],vramGb: 0,license: 'n/a (no model)',notes:'audio = the new voice (Chatterbox dub, narration), audio2 = the background stem of dub-prepare-separate-transcribe or a music bed (backgroundVolumeDb, e.g. -12 under narration). ' +- 'AudioMerge resamples to the higher rate and pads the shorter clip. Video length is unchanged. Without audio2 the provider uses video-mux-audio-replace. Runs on CPU (verified end to end through Fuobe).',+ 'Both are mixed over EmptyAudio of the video\'s length (duration: the provider reads it from the MP4 header), because AudioMerge cuts audio2 to audio1\'s length. ' ++ 'Concatenate Video with complete_audio copies the video stream packet by packet (no decode, no re-encode: lossless, constant memory) and encodes only the new AAC soundtrack. ' ++ 'Video length is unchanged. Without audio2 the provider uses video-mux-audio-replace. Runs on CPU (verified end to end through Fuobe; +0.02 GB RAM for a 900-frame clip).',},{id: 'video-mux-audio-replace',@@ -2186,7 +2200,9 @@ export const SPEC = [outputs: [{ node: '8', kind: 'video' }],vramGb: 0,license: 'n/a (no model)',- notes: 'LoadVideo -> GetVideoComponents (frames, fps) + LoadAudio -> CreateVideo -> SaveVideo. The single-track variant of video-mux-audio (voice-over, narration, music). Runs on CPU (verified end to end through Fuobe).',+ notes:+ 'LoadVideo + LoadAudio -> Concatenate Video (complete_audio) -> SaveVideo: the picture is stream-copied, only the new soundtrack is encoded. The single-track variant of video-mux-audio (voice-over, narration, music). ' ++ 'A soundtrack longer than the video is cut at the video\'s end. Runs on CPU (verified end to end through Fuobe).',},// ---- Product 3D, try-on --------------------------------------------------------@@ -2231,7 +2247,8 @@ export const SPEC = [license: 'Apache-2.0 (FLUX.2 [klein] 4B, try-on LoRA by xocialize); segformer_b2_clothes MIT; ComfyUI-RMBG code GPL-3.0',autoDownloads: ['ClothesSegment (ComfyUI-RMBG) downloads segformer_b2_clothes (0.11 GB) into models/RMBG/segformer_clothes on first run'],notes:- 'Reference order is load-bearing (LoRA card): image = person, image2 = top, image3 = bottom; for a dress the provider passes image2 again as image3. The LoRA was trained on clothing-agnostic inputs, ' ++ 'Reference order is load-bearing (LoRA card): image = person, image2 = top (or a dress / whole outfit), image3 = bottom. image2 is required; without image3 the provider bypasses the bottom\'s ReferenceLatent pair ' ++ '(one garment reference) instead of passing the top as the bottom. The LoRA was trained on clothing-agnostic inputs, ' +'so ClothesSegment greys the old outfit out first. Trigger word TRYON (defaults.promptPrefix: the provider puts it at the start of the prompt). Output size = the person image (~1 MP).',},diff --git a/scripts/comfy/validation-state.json b/scripts/comfy/validation-state.jsonindex 16e848f2..cbb20635 100644--- a/scripts/comfy/validation-state.json+++ b/scripts/comfy/validation-state.json@@ -12,16 +12,16 @@"at": "2026-10-16T20:57:20.767Z"},"captions-burnin": {- "sha256": "22437cbe3fe0a87b4c1806b258b280b0dd454dd5d9f3b67d4d2a929d046b25c0",+ "sha256": "8bb4d7bca5145d94ee1d509e50e23ef40e4cd21cb7c152bbba32751eca4ea013","validated": true,"error": null,- "at": "2026-10-17T21:02:03.382Z"+ "at": "2026-10-18T06:58:45.476Z"},"captions-qwen3-asr": {- "sha256": "97802a02aefd8eee5a1abe6ca6284569a9b367dd6b0024560cc8ad61e6606b43",+ "sha256": "75286c2efad353c7285df2eea90782db99e7b7e994adeeaaf242a2e70c790bf7","validated": true,"error": null,- "at": "2026-10-17T21:02:03.322Z"+ "at": "2026-10-18T06:58:45.186Z"},"captions-whisper-burnin": {"sha256": "31b33c6ce7f5d15b97fec8367f5ad005f15162f6b76530e5ff8feca633bf3c56",@@ -174,10 +174,10 @@"at": "2026-10-16T20:57:26.862Z"},"layers-qwen-image-layered": {- "sha256": "88d1f27279ece0e954938599c7a2cf568f08cd86bc2b5bad6914cd34efed46f4",+ "sha256": "7e8aae04b028f3e0000ca59ab953c4af5be0a1a65f734481d8162179d6cc9e77","validated": true,"error": null,- "at": "2026-10-17T21:01:59.498Z"+ "at": "2026-10-18T06:58:43.946Z"},"layers-qwen-image-layered-control": {"sha256": "cf214475197005342e0966857d6817c15aec2eafb3d28727bfd07e956e53bfd7",@@ -192,10 +192,10 @@"at": "2026-10-17T21:02:50.385Z"},"lipsync-v2v-infinitetalk": {- "sha256": "7537cb5b9d35a1fe9fbc60bf48bbb2674d45be28af5170890fee8d5d430e9e8d",+ "sha256": "42e30f1bec920686a7b7bb1c41cbf336e97fd696c790526cf0e7c1b9457fb98b","validated": true,"error": null,- "at": "2026-10-17T21:02:04.091Z"+ "at": "2026-10-18T06:58:47.182Z"},"ltx2-i2v": {"sha256": "db32b2b64be6be2ec2a9e64cae5e74c042d2eada6131eee52f6a6c2866e2dab9",@@ -486,16 +486,16 @@"at": "2026-10-16T23:33:13.889Z"},"video-mux-audio": {- "sha256": "16866be82207d7578d2ad054a69b048eb69184c354ab362406baa3934f24a54f",+ "sha256": "68af795bae0c0e89749819173916044e4024a6ce3035f830b48c80e0b6899181","validated": true,"error": null,- "at": "2026-10-17T21:02:04.314Z"+ "at": "2026-10-18T06:58:47.799Z"},"video-mux-audio-replace": {- "sha256": "df3d48d40396813dc5f3c94000096cac6f783428a6c68881209c3a2428ee2672",+ "sha256": "612d36e755d90f5d62e4a8ea92dc825019b42d0882ad469d0597e6f7b9bc36dc","validated": true,"error": null,- "at": "2026-10-17T21:02:04.419Z"+ "at": "2026-10-18T06:58:49.420Z"},"video-reframe-wan22-fun-vace": {"sha256": "3d97f02a5da7badd11df1f1334de2924b4fc930c8976597b25c231d342b629de",diff --git a/src/lib/comfy.ts b/src/lib/comfy.tsindex c4e5122e..a9f1b462 100644--- a/src/lib/comfy.ts+++ b/src/lib/comfy.ts@@ -316,75 +316,185 @@ export function splitCueWords(cues: CaptionCue[], words: number): CaptionCue[] {const isLinkValue = (v: unknown): v is [string, number] => Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "number";-/** BatchImagesNode takes up to 50 images ("images.image0" … "images.image49"); two levels hold 2,500 segments. */-const BATCH_MAX = 50;-export const MAX_CAPTION_SEGMENTS = BATCH_MAX * BATCH_MAX;+/** What the provider knows about the clip being captioned (from its MP4 header); every field is optional. */+export interface CaptionClip {+ /** Seconds: cues past the end are dropped and the part after the last cue stays uncaptioned. */+ duration?: number;+ fps?: number;+ width?: number;+ height?: number;+ /** true: the clip's own soundtrack (LoadAudio) runs under the whole result. Otherwise each segment carries its own audio. */+ hasAudio?: boolean;+}++/** ConcatenateVideo joins up to 100 clips; two levels hold 10,000. */+const CONCAT_MAX = 100;+export const MAX_CAPTION_SEGMENTS = 2500;+/** Frames decoded at once per captioned chunk: about 384 MB of float32 RGB (≈0.5 s of 1080×1920 at 30 fps). */+const CAPTION_CHUNK_BYTES = 384 * 2 ** 20;+/** Shortest window the join takes safely (see expandCaptionWorkflow). */+const MIN_WINDOW_FRAMES = 3;++/** Length of the pieces a captioned stretch is cut into, so only one piece's frames are in memory at a time. */+export function captionChunkSeconds(clip: CaptionClip): number {+ if (!clip.width || !clip.height) return 1;+ const perSecond = clip.width * clip.height * 3 * 4 * (clip.fps || 30);+ return Math.max(0.25, Math.min(5, CAPTION_CHUNK_BYTES / perSecond));+}/**- * Rewrite the captions-burnin template for a list of cues: the clip is cut into consecutive Trim Video- * segments (gaps and cues), each cue segment gets a Draw Text Overlay with the template's style, and the- * segments are batched back together in order. A segment may not start after the end of the clip, so the- * last cue runs to the end of the clip.+ * Rewrite the captions-burnin template for a list of cues. The clip is cut into consecutive Trim Video+ * windows: gaps go to the join untouched (never decoded); a cue's window is cut into chunks of at most+ * `captionChunkSeconds`, and each chunk is decoded, gets a Draw Text Overlay with the template's style and is+ * encoded straight away (Create Video, codec h264). Concatenate Video joins everything in order and lays the+ * clip's soundtrack under it. So ComfyUI never holds more than one chunk of raw frames that it still needs,+ * whatever the clip's length (finished chunks can be evicted from its cache under memory pressure).+ *+ * With `clip.fps` known, window edges sit half a frame before a frame, so every frame lands in exactly one window.+ * With `clip.duration` known, cues past the end are dropped and the clip after the last cue is kept as a gap;+ * without it, the last cue's window runs to the end of the clip (a window may not start after the end).*/-export function expandCaptionWorkflow(wf: ComfyWorkflow, cues: CaptionCue[]): ComfyWorkflow {+export function expandCaptionWorkflow(wf: ComfyWorkflow, cues: CaptionCue[], clip: CaptionClip = {}): ComfyWorkflow {const out = cloneWorkflow(wf);const ids = Object.keys(out);- const loader = ids.find((id) => out[id].class_type === "LoadVideo");- const batch = ids.find((id) => out[id].class_type === "BatchImagesNode");- const template = ids.map((id) => out[id]).find((n) => n.class_type === "TextOverlay");- if (!loader || !batch || !template) throw new Error("Not a caption burn-in workflow (needs LoadVideo, TextOverlay and BatchImagesNode)");- const sorted = cues.filter((c) => c.text.trim() && c.end > c.start).sort((a, b) => a.start - b.start);- if (!sorted.length) throw new Error("No captions to burn in");-- type Segment = { start: number; duration: number; text?: string };- const segments: Segment[] = [];+ const find = (cls: string) => ids.find((id) => out[id].class_type === cls);+ const loader = find("LoadVideo");+ const join = find("ConcatenateVideo");+ const style = ids.map((id) => out[id]).find((n) => n.class_type === "TextOverlay");+ const encode = ids.map((id) => out[id]).find((n) => n.class_type === "CreateVideo");+ if (!loader || !join || !style || !encode) throw new Error("Not a caption burn-in workflow (needs LoadVideo, TextOverlay, CreateVideo and ConcatenateVideo)");++ const fps = clip.fps && clip.fps > 0 ? clip.fps : undefined;+ const end = clip.duration && clip.duration > 0 ? clip.duration : undefined;+ // Edges: half a frame before the first frame shown (fps known), else the time to the millisecond.+ const edge = (t: number) => (fps ? Math.max(0, (Math.ceil(t * fps - 1e-6) - 0.5) / fps) : Math.max(0, round3(t)));+ // Every window but the last holds at least MIN_WINDOW_FRAMES frames: an empty one fails to decode, and+ // Concatenate Video rejects a 2-frame clip followed by another one (non-monotonic timestamps).+ const minLength = fps ? (MIN_WINDOW_FRAMES - 0.5) / fps : 0.15;+ const sorted = cues+ .filter((c) => c.text.trim() && c.end > c.start && (end === undefined || edge(c.start) < end - minLength))+ .sort((a, b) => a.start - b.start);+ if (!sorted.length) throw new Error(end !== undefined && cues.length ? "Every caption starts after the end of the clip — check the cue times" : "No captions to burn in");++ // Windows in order: { start, length (0 = to the end of the clip), text? }.+ type Window = { start: number; length: number; text?: string };+ const windows: Window[] = [];let cursor = 0;- sorted.forEach((c, i) => {- let start = round3(Math.max(c.start, cursor, 0));- if (start - cursor < 0.02) start = round3(cursor); // close gaps shorter than a frame- const last = i === sorted.length - 1;- const end = last ? undefined : round3(Math.min(c.end, sorted[i + 1].start));- if (end !== undefined && end - start < 0.02) return; // swallowed by the next cue- if (start > cursor) segments.push({ start: round3(cursor), duration: round3(start - cursor) });- segments.push({ start, duration: end === undefined ? 0 : round3(end - start), text: c.text.trim() });- if (end !== undefined) cursor = end;- });- if (segments.length > MAX_CAPTION_SEGMENTS) throw new Error(`Too many captions (${segments.length} segments, max ${MAX_CAPTION_SEGMENTS})`);-- // Drop the template's segments.- const sliceIds = new Set(ids.filter((id) => out[id].class_type === "Video Slice"));- for (const id of ids) {- const n = out[id];- const fromSlice = n.class_type === "GetVideoComponents" && isLinkValue(n.inputs.video) && sliceIds.has(n.inputs.video[0]);- if (sliceIds.has(id) || n.class_type === "TextOverlay" || fromSlice) delete out[id];+ const shortest = fps ? MIN_WINDOW_FRAMES / fps : minLength;+ for (const [i, c] of sorted.entries()) {+ if (end !== undefined && cursor >= end - minLength) break; // no room left for another caption+ let start = Math.max(edge(c.start), cursor);+ if (start - cursor < minLength) start = cursor; // a pause too short for a window of its own: no gap+ const nextStart = i < sorted.length - 1 ? edge(sorted[i + 1].start) : undefined;+ let stop: number | undefined = edge(Math.min(c.end, end ?? Infinity));+ if (nextStart !== undefined) stop = Math.min(stop, nextStart);+ else if (end === undefined) stop = undefined; // last cue: to the end of the clip+ if (stop !== undefined) stop = Math.max(stop, start + shortest); // a very short caption stays up a few frames+ if (stop !== undefined && end !== undefined && end - stop < minLength) stop = undefined; // too close to the end: run to it+ if (start > cursor) windows.push({ start: cursor, length: start - cursor });+ windows.push({ start, length: stop === undefined ? 0 : stop - start, text: c.text.trim() });+ cursor = stop ?? Infinity;}- const style = Object.fromEntries(Object.entries(template.inputs).filter(([k]) => k !== "images" && k !== "text"));+ if (end !== undefined && end - cursor >= minLength) windows.push({ start: cursor, length: 0 }); // the uncaptioned rest++ // Cut captioned windows into chunks (in whole frames when the frame rate is known).+ const chunk = captionChunkSeconds(clip);+ const parts: Window[] = windows.flatMap((w) => {+ if (w.text === undefined || !w.length) return [w];+ if (fps) {+ const first = w.start > 0 ? w.start : -0.5 / fps; // the window's half-frame edge (0 is clamped)+ const frames = Math.round((w.start + w.length - first) * fps);+ const n = Math.max(1, Math.min(Math.ceil(w.length / chunk), Math.floor(frames / MIN_WINDOW_FRAMES)));+ if (n === 1) return [w];+ const at = (k: number) => (k === 0 ? w.start : k === n ? w.start + w.length : first + Math.floor((k * frames) / n) / fps);+ return Array.from({ length: n }, (_, k) => ({ start: at(k), length: at(k + 1) - at(k), text: w.text }));+ }+ if (w.length <= chunk * 1.25) return [w];+ const n = Math.ceil(w.length / chunk);+ const at = (k: number) => (k === n ? w.start + w.length : round3(w.start + (k * w.length) / n));+ return Array.from({ length: n }, (_, k) => ({ start: at(k), length: at(k + 1) - at(k), text: w.text }));+ });+ if (parts.length > MAX_CAPTION_SEGMENTS) throw new Error(`Too many caption segments (${parts.length}, max ${MAX_CAPTION_SEGMENTS}) — trim the clip or use fewer captions`);++ // Drop the template's own segments; keep the loader, the soundtrack, the join and the save node.+ const keep = new Set([loader, join, ...ids.filter((id) => ["LoadAudio", "SaveVideo"].includes(out[id].class_type))]);+ for (const id of ids) if (!keep.has(id) && ["Video Slice", "GetVideoComponents", "TextOverlay", "CreateVideo", "ConcatenateVideo"].includes(out[id].class_type)) delete out[id];+ const soundtrack = ids.find((id) => out[id]?.class_type === "LoadAudio");+ const joinInputs = Object.fromEntries(Object.entries(out[join].inputs).filter(([k]) => !k.startsWith("videos.") && k !== "complete_audio"));+ if (clip.hasAudio === true && soundtrack) joinInputs.complete_audio = [soundtrack, 0];+ else if (soundtrack) delete out[soundtrack]; // silent or unknown: each segment brings its own audio (LoadAudio fails on a silent file)++ const styleInputs = Object.fromEntries(Object.entries(style.inputs).filter(([k]) => k !== "images" && k !== "text"));+ const encodeInputs = Object.fromEntries(Object.entries(encode.inputs).filter(([k]) => !["images", "fps", "audio"].includes(k)));+ const ms = (n: number) => Math.round(n * 1e6) / 1e6;let next = Math.max(1000, ...ids.map((k) => Number(k.split(":").pop()) || 0)) + 1;- const parts: [string, number][] = segments.map((s, i) => {+ const links: [string, number][] = parts.map((p, i) => {const slice = String(next++);+ out[slice] = { class_type: "Video Slice", inputs: { video: [loader, 0], start_time: ms(p.start), duration: ms(p.length), strict_duration: false }, _meta: { title: `${p.text === undefined ? "Gap" : "Caption"} ${i + 1}` } };+ if (p.text === undefined) return [slice, 0];const frames = String(next++);- out[slice] = { class_type: "Video Slice", inputs: { video: [loader, 0], start_time: s.start, duration: s.duration, strict_duration: false }, _meta: { title: `Segment ${i + 1}` } };- out[frames] = { class_type: "GetVideoComponents", inputs: { video: [slice, 0] }, _meta: { title: `Segment ${i + 1} frames` } };- if (s.text === undefined) return [frames, 0];const overlay = String(next++);- out[overlay] = { class_type: "TextOverlay", inputs: { ...style, images: [frames, 0], text: s.text }, _meta: { title: `Caption ${i + 1}` } };- return [overlay, 0];+ const video = String(next++);+ out[frames] = { class_type: "GetVideoComponents", inputs: { video: [slice, 0] }, _meta: { title: `Frames ${i + 1}` } };+ out[overlay] = { class_type: "TextOverlay", inputs: { ...styleInputs, images: [frames, 0], text: p.text }, _meta: { title: `Caption ${i + 1}` } };+ out[video] = { class_type: "CreateVideo", inputs: { ...encodeInputs, images: [overlay, 0], fps: [frames, 2], audio: [frames, 1] }, _meta: { title: `Encoded ${i + 1}` } };+ return [video, 0];});- const batchNode = (links: [string, number][]): ComfyNode => ({- class_type: "BatchImagesNode",- inputs: Object.fromEntries(links.map((l, i) => [`images.image${i}`, l])),+ const concat = (list: [string, number][], extra: Record<string, unknown>): ComfyNode => ({+ class_type: "ConcatenateVideo",+ inputs: { ...extra, ...Object.fromEntries(list.map((l, i) => [`videos.video${i}`, l])) },_meta: { title: "Segments in order" },});- if (parts.length <= BATCH_MAX) out[batch] = batchNode(parts);+ const innerInputs = Object.fromEntries(Object.entries(joinInputs).filter(([k]) => k !== "complete_audio"));+ if (links.length <= CONCAT_MAX) out[join] = concat(links, joinInputs);else {const groups: [string, number][] = [];- for (let i = 0; i < parts.length; i += BATCH_MAX) {+ for (let i = 0; i < links.length; i += CONCAT_MAX) {const id = String(next++);- out[id] = batchNode(parts.slice(i, i + BATCH_MAX));+ out[id] = concat(links.slice(i, i + CONCAT_MAX), innerInputs);groups.push([id, 0]);}- out[batch] = batchNode(groups);+ out[join] = concat(groups, joinInputs);+ }+ return out;+}++/**+ * Drop an image slot from a FLUX.2-style reference chain: when everything downstream of `loaderId` ends in+ * ReferenceLatent "latent" inputs, those ReferenceLatent nodes are bypassed (their consumers read the+ * conditioning they were given) and the loader with its resize/encode nodes is removed. Returns null when the+ * image is used any other way (then the slot can't simply be left out).+ */+export function bypassReference(wf: ComfyWorkflow, loaderId: string): ComfyWorkflow | null {+ const consumers = (id: string) =>+ Object.entries(wf).flatMap(([cid, n]) => Object.entries(n.inputs).filter(([, v]) => isLinkValue(v) && v[0] === id).map(([input]) => ({ id: cid, input })));+ const refs = new Set<string>();+ const path = new Set<string>([loaderId]);+ const queue = [loaderId];+ while (queue.length) {+ const id = queue.shift()!;+ const users = consumers(id);+ if (!users.length) return null; // feeds an output directly+ for (const u of users) {+ const n = wf[u.id];+ if (n.class_type === "ReferenceLatent" && u.input === "latent") refs.add(u.id);+ else if (n.class_type === "ReferenceLatent" || /^(Save|Preview)/.test(n.class_type)) return null;+ else if (!path.has(u.id)) {+ path.add(u.id);+ queue.push(u.id);+ }+ }}+ if (!refs.size) return null;+ const out = cloneWorkflow(wf);+ // A chain of references: follow bypassed nodes to the first conditioning that stays.+ const source = (link: [string, number]): [string, number] => {+ let l = link;+ while (refs.has(l[0]) && isLinkValue(out[l[0]].inputs.conditioning)) l = out[l[0]].inputs.conditioning as [string, number];+ return l;+ };+ for (const n of Object.values(out)) for (const [k, v] of Object.entries(n.inputs)) if (isLinkValue(v) && refs.has(v[0])) n.inputs[k] = source(v);+ for (const id of [...refs, ...path]) delete out[id];return out;}@@ -396,16 +506,51 @@ const ASR_LANGUAGES: Record<string, string> = {tl: "Filipino", fa: "Persian", el: "Greek", hu: "Hungarian", mk: "Macedonian", ro: "Romanian",};-const LANGUAGE_NAMES: Record<string, string> = {- ...ASR_LANGUAGES, he: "Hebrew", no: "Norwegian", nb: "Norwegian", sw: "Swahili", uk: "Ukrainian", bg: "Bulgarian", hr: "Croatian",- sk: "Slovak", sl: "Slovenian", sr: "Serbian", ca: "Catalan", bn: "Bengali", ta: "Tamil", te: "Telugu", ur: "Urdu",-};+/**+ * Whisper's 100 languages (openai-whisper tokenizer.LANGUAGES), code → name. ComfyUI-Whisper's language combo+ * offers the same names with a capital first letter ("Haitian creole", "Tagalog").+ */+const WHISPER_LANGUAGES: Record<string, string> = Object.fromEntries(+ (+ "en english,zh chinese,de german,es spanish,ru russian,ko korean,fr french,ja japanese,pt portuguese,tr turkish,pl polish,ca catalan," ++ "nl dutch,ar arabic,sv swedish,it italian,id indonesian,hi hindi,fi finnish,vi vietnamese,he hebrew,uk ukrainian,el greek,ms malay," ++ "cs czech,ro romanian,da danish,hu hungarian,ta tamil,no norwegian,th thai,ur urdu,hr croatian,bg bulgarian,lt lithuanian,la latin," ++ "mi maori,ml malayalam,cy welsh,sk slovak,te telugu,fa persian,lv latvian,bn bengali,sr serbian,az azerbaijani,sl slovenian,kn kannada," ++ "et estonian,mk macedonian,br breton,eu basque,is icelandic,hy armenian,ne nepali,mn mongolian,bs bosnian,kk kazakh,sq albanian," ++ "sw swahili,gl galician,mr marathi,pa punjabi,si sinhala,km khmer,sn shona,yo yoruba,so somali,af afrikaans,oc occitan,ka georgian," ++ "be belarusian,tg tajik,sd sindhi,gu gujarati,am amharic,yi yiddish,lo lao,uz uzbek,fo faroese,ht haitian creole,ps pashto,tk turkmen," ++ "nn nynorsk,mt maltese,sa sanskrit,lb luxembourgish,my myanmar,bo tibetan,tl tagalog,mg malagasy,as assamese,tt tatar,haw hawaiian," ++ "ln lingala,ha hausa,ba bashkir,jw javanese,su sundanese,yue cantonese"+ )+ .split(",")+ .map((pair) => {+ const i = pair.indexOf(" ");+ const name = pair.slice(i + 1);+ return [pair.slice(0, i), name.charAt(0).toUpperCase() + name.slice(1)];+ }),+);+/** Codes people use that Whisper spells differently. */+const WHISPER_ALIASES: Record<string, string> = { fil: "tl", jv: "jw", iw: "he", nb: "no", zh_hans: "zh" };++const LANGUAGE_NAMES: Record<string, string> = { ...WHISPER_LANGUAGES, ...ASR_LANGUAGES, nb: "Norwegian", fil: "Filipino", jv: "Javanese" };/** The ISO code in "de", "de-DE", "pt_BR" or "German (de)". */function languageCode(v: string): string | undefined {return (/\(([a-z]{2,3})(?:-[A-Za-z]+)?\)\s*$/i.exec(v)?.[1] ?? /^([a-z]{2,3})(?:[-_][A-Za-z]+)?$/i.exec(v)?.[1])?.toLowerCase();}+/** "tl", "fil", "he", "Hebrew" or "Hebrew (he)" → ComfyUI-Whisper's combo value ("Tagalog", "Hebrew"); unknown → "auto". */+export function whisperLanguage(value: string | undefined | null): string {+ const v = (value ?? "").trim();+ if (!v || v.toLowerCase() === "auto") return "auto";+ const code = languageCode(v);+ const byCode = code && (WHISPER_LANGUAGES[code] ?? WHISPER_LANGUAGES[WHISPER_ALIASES[code] ?? ""]);+ if (byCode) return byCode;+ const name = v.replace(/\s*\(.*\)\s*$/, "").toLowerCase();+ if (name === "filipino") return "Tagalog";+ return Object.values(WHISPER_LANGUAGES).find((n) => n.toLowerCase() === name) ?? "auto";+}+/** "de", "German", "German (de)" or "de-DE" → the ASR combo value ("German"); anything unknown → "auto" (detect). */export function asrLanguage(value: string | undefined | null): string {const v = (value ?? "").trim();diff --git a/src/lib/media-probe.ts b/src/lib/media-probe.tsnew file mode 100644index 00000000..3f8df1fa--- /dev/null+++ b/src/lib/media-probe.ts@@ -0,0 +1,180 @@+/**+ * Just enough of the common media containers to know a file's shape before a job runs: duration, displayed+ * size, frame rate / count and which tracks it has. Reads MP4 / MOV / M4A (ISO-BMFF), WAV, FLAC and MP3 from+ * the bytes in memory; anything else (WebM, MKV, Ogg…) is "unknown" (null) and callers fall back to safe defaults.+ */+export interface MediaInfo {+ container: "mp4" | "wav" | "flac" | "mp3";+ /** Seconds (the longest track). */+ duration?: number;+ /** Seconds of picture (the video track alone). */+ videoDuration?: number;+ /** Displayed size (a 90° rotation matrix swaps the stored width and height). */+ width?: number;+ height?: number;+ fps?: number;+ frames?: number;+ hasVideo: boolean;+ hasAudio: boolean;+}++const fourcc = (b: Uint8Array, o: number) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3]);++export function probeMedia(data: Uint8Array): MediaInfo | null {+ try {+ if (data.length < 12) return null;+ if (fourcc(data, 0) === "RIFF" && fourcc(data, 8) === "WAVE") return probeWav(data);+ if (fourcc(data, 0) === "fLaC") return probeFlac(data);+ if (fourcc(data, 4) === "ftyp" || ["moov", "mdat", "free", "wide", "skip"].includes(fourcc(data, 4))) return probeIsoBmff(data);+ return probeMp3(data);+ } catch {+ return null;+ }+}++// ---------------------------------------------------------------------------+// ISO-BMFF (mp4, mov, m4a)++interface Box {+ type: string;+ start: number; // payload start+ end: number;+}++function* boxes(d: DataView, start: number, end: number): Generator<Box> {+ let o = start;+ while (o + 8 <= end) {+ let size = d.getUint32(o);+ const type = String.fromCharCode(d.getUint8(o + 4), d.getUint8(o + 5), d.getUint8(o + 6), d.getUint8(o + 7));+ let header = 8;+ if (size === 1) {+ if (o + 16 > end) return;+ size = Number(d.getBigUint64(o + 8));+ header = 16;+ } else if (size === 0) size = end - o;+ if (size < header) return;+ yield { type, start: o + header, end: Math.min(end, o + size) };+ o += size;+ }+}++const child = (d: DataView, parent: Box, type: string) => {+ for (const b of boxes(d, parent.start, parent.end)) if (b.type === type) return b;+ return undefined;+};++/** [timescale, duration] of an mvhd / mdhd box (same layout). */+function timing(d: DataView, b: Box): [number, number] {+ if (d.getUint8(b.start) === 1) return [d.getUint32(b.start + 20), Number(d.getBigUint64(b.start + 24))];+ return [d.getUint32(b.start + 12), d.getUint32(b.start + 16)];+}++function probeIsoBmff(data: Uint8Array): MediaInfo | null {+ const d = new DataView(data.buffer, data.byteOffset, data.byteLength);+ let moov: Box | undefined;+ for (const b of boxes(d, 0, data.length)) if (b.type === "moov") moov = b;+ if (!moov) return null;+ const info: MediaInfo = { container: "mp4", hasVideo: false, hasAudio: false };+ const mvhd = child(d, moov, "mvhd");+ if (mvhd) {+ const [scale, dur] = timing(d, mvhd);+ if (scale && dur) info.duration = dur / scale;+ }+ for (const trak of boxes(d, moov.start, moov.end)) {+ if (trak.type !== "trak") continue;+ const mdia = child(d, trak, "mdia");+ const hdlr = mdia && child(d, mdia, "hdlr");+ const handler = hdlr ? fourcc(data, hdlr.start + 8) : "";+ if (handler === "soun") info.hasAudio = true;+ if (handler !== "vide" || info.hasVideo) continue;+ info.hasVideo = true;+ const tkhd = child(d, trak, "tkhd");+ if (tkhd) {+ const v = d.getUint8(tkhd.start);+ const m = tkhd.start + (v === 1 ? 52 : 40); // the matrix+ const a = d.getInt32(m);+ const dd = d.getInt32(m + 16);+ let w = d.getUint32(m + 36) / 65536;+ let h = d.getUint32(m + 40) / 65536;+ if (a === 0 && dd === 0) [w, h] = [h, w]; // rotated 90° / 270°+ if (w && h) Object.assign(info, { width: Math.round(w), height: Math.round(h) });+ }+ const mdhd = mdia && child(d, mdia, "mdhd");+ const stbl = mdia && child(d, mdia, "minf") && child(d, child(d, mdia, "minf")!, "stbl");+ const stts = stbl && child(d, stbl, "stts");+ if (stts) {+ const n = d.getUint32(stts.start + 4);+ let frames = 0;+ for (let i = 0; i < n && stts.start + 8 + i * 8 + 8 <= stts.end; i++) frames += d.getUint32(stts.start + 8 + i * 8);+ if (frames) info.frames = frames;+ }+ if (mdhd) {+ const [scale, dur] = timing(d, mdhd);+ if (scale && dur) {+ info.videoDuration = dur / scale;+ info.duration ??= dur / scale;+ if (info.frames) info.fps = Math.round((info.frames / (dur / scale)) * 1000) / 1000;+ }+ }+ }+ return info;+}++// ---------------------------------------------------------------------------+// WAV, FLAC, MP3++function probeWav(data: Uint8Array): MediaInfo | null {+ const d = new DataView(data.buffer, data.byteOffset, data.byteLength);+ let byteRate = 0;+ for (let o = 12; o + 8 <= data.length; ) {+ const id = fourcc(data, o);+ let size = d.getUint32(o + 4, true);+ if (id === "fmt ") byteRate = d.getUint32(o + 16, true);+ if (id === "data") {+ if (!size || size === 0xffffffff || o + 8 + size > data.length) size = data.length - o - 8; // streamed header+ return byteRate ? { container: "wav", duration: size / byteRate, hasVideo: false, hasAudio: true } : null;+ }+ o += 8 + size + (size % 2);+ }+ return null;+}++function probeFlac(data: Uint8Array): MediaInfo | null {+ // STREAMINFO is always the first metadata block: 20-bit sample rate, 36-bit total samples.+ const o = 8 + 10;+ const rate = (data[o] << 12) | (data[o + 1] << 4) | (data[o + 2] >> 4);+ const total = (data[o + 3] & 0x0f) * 2 ** 32 + ((data[o + 4] << 24) >>> 0) + (data[o + 5] << 16) + (data[o + 6] << 8) + data[o + 7];+ if (!rate) return null;+ return { container: "flac", ...(total ? { duration: total / rate } : {}), hasVideo: false, hasAudio: true };+}++const MP3_BITRATES: Record<string, number[]> = {+ "1-3": [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],+ "2-3": [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],+};+const MP3_RATES: Record<number, number[]> = { 3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000] };++function probeMp3(data: Uint8Array): MediaInfo | null {+ let o = 0;+ if (fourcc(data, 0).startsWith("ID3")) o = 10 + ((data[6] & 0x7f) << 21) + ((data[7] & 0x7f) << 14) + ((data[8] & 0x7f) << 7) + (data[9] & 0x7f);+ // The first frame header within a few KB of the tag.+ for (const limit = Math.min(data.length - 4, o + 8192); o < limit; o++) if (data[o] === 0xff && (data[o + 1] & 0xe0) === 0xe0) break;+ if (o + 4 > data.length || data[o] !== 0xff) return null;+ const version = (data[o + 1] >> 3) & 3; // 3 = MPEG-1, 2 = MPEG-2, 0 = MPEG-2.5+ const layer = (data[o + 1] >> 1) & 3; // 1 = Layer III+ if (version === 1 || layer !== 1) return null;+ const bitrate = (MP3_BITRATES[version === 3 ? "1-3" : "2-3"][data[o + 2] >> 4] ?? 0) * 1000;+ const rate = MP3_RATES[version]?.[(data[o + 2] >> 2) & 3];+ if (!rate) return null;+ const mono = data[o + 3] >> 6 === 3;+ const samplesPerFrame = version === 3 ? 1152 : 576;+ const side = version === 3 ? (mono ? 17 : 32) : mono ? 9 : 17;+ const x = o + 4 + side;+ const tag = fourcc(data, x);+ if ((tag === "Xing" || tag === "Info") && data[x + 7] & 1) {+ const frames = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(x + 8);+ return { container: "mp3", duration: (frames * samplesPerFrame) / rate, hasVideo: false, hasAudio: true };+ }+ if (!bitrate) return null;+ return { container: "mp3", duration: ((data.length - o) * 8) / bitrate, hasVideo: false, hasAudio: true };+}diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 12c9f53a..8a3b5793 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -8,6 +8,7 @@ import {alphaBBox,applyBindings,asrLanguage,+ bypassReference,computeDimensions,computeFrames,expandCaptionWorkflow,@@ -19,6 +20,7 @@ import {randomSeed,splitCueWords,swatchPixels,+ whisperLanguage,type BindingKey,type CaptionCue,type ComfyWorkflow,@@ -28,6 +30,7 @@ import {} from "@/lib/comfy";import { guessKind } from "@/lib/catalog/payload";import type { GenInput, MediaKind, Operation } from "@/lib/catalog/types";+import { probeMedia, type MediaInfo } from "@/lib/media-probe";import { getSetting } from "../settings";import { decodePng, encodePng } from "../png";import { readRef } from "../storage";@@ -319,6 +322,36 @@ export function probeComfySync(timeoutMs = 1500): boolean {/** Loader classes whose input is an uploaded file, and which input holds it. */const MEDIA_LOADERS: Record<string, string> = { LoadImage: "image", LoadImageMask: "image", LoadVideo: "file", VHS_LoadVideo: "video", LoadAudio: "audio", VHS_LoadAudioUpload: "audio" };+// What we learned about each uploaded clip / track from its header (duration, size, fps, audio), by ComfyUI file name.+declare global {+ var __fuobeComfyMedia: Map<string, MediaInfo> | undefined;+}+const MEDIA_FILE = /^(video|audio)\//;+const MEDIA_EXT = /\.(mp4|m4v|mov|m4a|wav|flac|mp3)$/i;++function rememberMedia(name: string, info: MediaInfo) {+ const seen = (globalThis.__fuobeComfyMedia ??= new Map());+ seen.set(name, info);+ if (seen.size > 256) seen.delete(seen.keys().next().value!);+}++/** The header facts of a file this server uploaded to ComfyUI (undefined for images and unreadable containers). */+export function mediaInfoFor(name: unknown): MediaInfo | undefined {+ return typeof name === "string" ? globalThis.__fuobeComfyMedia?.get(name) : undefined;+}++/** Inputs a workflow handles its own way (the manifest doesn't say). */+const SLOT_RULES: Record<string, { reuse?: boolean; required?: string[]; hints?: Record<string, string> }> = {+ // Edit graphs whose extra images feed TextEncodeQwenImageEditPlus: a repeated reference is harmless.+ "qwen-image-edit-2511-multi": { reuse: true },+ "storyboard-qwen-edit-2509-next-scene": { reuse: true },+ "tryon-flux2-klein-4b": { required: ["image2"], hints: { image: "Add a photo of the person", image2: "Add the garment to try on" } },+ "palette-transfer-image": { hints: { image2: "Pick a palette or add a reference image" } },+ "palette-transfer-video": { hints: { image: "Pick a palette or add a reference image" } },+ "relight-qwen-edit-2509-reference": { hints: { image2: "Add the photo whose light to copy" } },+ "face-swap-reactor": { hints: { image2: "Add the face to put in" } },+};+const MEDIA_HINT: Record<string, string> = {image: "Add an image",image2: "Add a second image",@@ -349,6 +382,10 @@ export interface PrepareContext {op: Operation;/** Upload a file to ComfyUI's input folder; returns the name LoadImage/LoadAudio/LoadVideo take. */upload: (data: Buffer, contentType: string, name: string) => Promise<string>;+ /** Header facts (duration, size, fps, audio track) of an uploaded clip or track, by its ComfyUI name. */+ media?: (name: string) => MediaInfo | undefined;+ /** The ComfyUI server's RAM in bytes, for graphs that hold a whole clip in memory. */+ serverRam?: () => Promise<number | undefined>;}export interface PreparedPrompt {@@ -365,11 +402,16 @@ function captionCues(input: GenInput, extra: Record<string, unknown>): CaptionCureturn splitCueWords(given, Number(extra.wordsPerCaption ?? 0));}+const seconds = (n: number) => (n >= 10 ? String(Math.round(n)) : String(Math.round(n * 10) / 10));+const GB = 2 ** 30;+/*** Turn a canonical request into the exact ComfyUI prompt: picks the workflow variant, maps Fuobe's inputs* onto the workflow's bindings (sizes, frames, trim times, languages, palettes, layers…), uploads files the* provider makes itself (palette swatches, media refs in params.extra) and rewrites graphs that depend on the- * request (caption cues). Pure apart from `ctx.upload` and reading the workflow files.+ * request (caption cues, left-out references). What the uploads' headers say (`ctx.media`) sizes clips to+ * their source, checks times against the clip's length and times lip re-sync by the voice. Pure apart from+ * `ctx.upload` / `ctx.serverRam` and reading the workflow files.*/export async function prepareWorkflow(endpointTemplate: string, input: GenInput, ctx: PrepareContext): Promise<PreparedPrompt> {// "video-concat-{n}": one workflow per clip count.@@ -377,6 +419,10 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,if (endpointTemplate.includes("{n}") && clips.length > 4) throw new ProviderError("ComfyUI joins up to 4 clips at a time");let endpoint = endpointTemplate.replace("{n}", String(Math.max(2, Math.min(4, clips.length))));const extra: Record<string, unknown> = { ...(input.extra ?? {}) };+ // The second audio track (mux background): the canonical input when the runtime sends it, else params.extra.audio2.+ const given2 = (input as GenInput & { audio2?: unknown }).audio2;+ const audio2 = typeof given2 === "string" && given2 ? given2 : undefined;+ if (audio2) delete extra.audio2;// Media refs in params.extra (e.g. a background stem for "audio2") are uploaded like regular inputs.for (const [k, v] of Object.entries(extra)) {@@ -385,11 +431,12 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,extra[k] = await ctx.upload(f.data, f.contentType, f.name);}// Soundtrack without a background stem: the single-track graph.- if (ctx.op === "mux" && !extra.audio2 && loadManifest().workflows.some((w) => w.id === `${endpoint}-replace`)) endpoint = `${endpoint}-replace`;+ if (ctx.op === "mux" && !audio2 && !extra.audio2 && loadManifest().workflows.some((w) => w.id === `${endpoint}-replace`)) endpoint = `${endpoint}-replace`;const { manifest, workflow } = getWorkflow(endpoint);const d = manifest.defaults;const b = manifest.bindings;+ const rules = SLOT_RULES[manifest.id] ?? {};const images = input.images ?? [];const values: Partial<Record<BindingKey, unknown>> = {prompt: input.prompt,@@ -419,7 +466,10 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,// Speech workflows read the soundtrack with LoadAudio, which also takes a video upload.if ((ctx.op === "transcribe" || ctx.op === "separate-audio" || ctx.op === "translate") && b.audio && !b.video) values.audio = input.audio ?? input.video ?? clips[0];if (b.language && input.targetLanguage) values.language = input.targetLanguage;- if (b.sourceLanguage && input.sourceLanguage) values.sourceLanguage = asrLanguage(input.sourceLanguage);+ if (b.sourceLanguage && input.sourceLanguage) {+ const whisper = b.sourceLanguage.some((t) => workflow[t.node]?.class_type === "Apply Whisper");+ values.sourceLanguage = whisper ? whisperLanguage(input.sourceLanguage) : asrLanguage(input.sourceLanguage);+ }if (b.instruction) {const template = String(extra.instruction ?? d.instruction ?? "");delete extra.instruction;@@ -427,11 +477,19 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,values.instruction = template.replaceAll("{language}", languageName(input.targetLanguage));}+ // What the upload headers say about the clip (and the voice).+ const clip = ctx.media?.(String(values.video ?? ""));+ const clipLength = clip?.videoDuration ?? clip?.duration;+// Frame rate (params.fps, or a model's fps control), trim window and frame counts.const fpsIn = input.fps ?? (typeof extra.fps === "number" && extra.fps > 0 ? extra.fps : undefined);if (b.fps && fpsIn) values.fps = fpsIn;const fps = Number(values.fps ?? d.fps ?? 16);const start = Math.max(0, input.startTime ?? 0);+ if (b.startTime || b.startFrame) {+ if (input.endTime !== undefined && input.endTime <= start) throw new ProviderError("The end time must be after the start time");+ if (clipLength && start >= clipLength) throw new ProviderError(`The start time is past the end of the clip (it is ${seconds(clipLength)} s long)`);+ }const span = input.endTime !== undefined ? Math.max(0, input.endTime - start) : input.duration;if (b.startTime && input.startTime !== undefined) values.startTime = start;if (b.startFrame && input.startTime !== undefined) values.startFrame = Math.round(start * fps);@@ -442,14 +500,11 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,}if (b.width || b.height) {const multiple = Number(manifest.limits?.dimensionMultiple ?? 16);- // With motion paths the frame keeps the start image's shape, so the paths need no cropping.+ // With motion paths the frame keeps the start image's shape, so the paths need no cropping;+ // "auto" keeps the source clip's shape when its header told us.const srcAspect = (extra.motionPaths as MotionPaths | undefined)?.aspect;- const dims = computeDimensions(- srcAspect ? `${srcAspect[0]}:${srcAspect[1]}` : input.aspectRatio === "auto" ? undefined : input.aspectRatio,- input.resolution,- { width: Number(d.width ?? 1024), height: Number(d.height ?? 1024) },- multiple,- );+ const shape = srcAspect ? `${srcAspect[0]}:${srcAspect[1]}` : input.aspectRatio === "auto" ? (clip?.width && clip.height ? `${clip.width}:${clip.height}` : undefined) : input.aspectRatio;+ const dims = computeDimensions(shape, input.resolution, { width: Number(d.width ?? 1024), height: Number(d.height ?? 1024) }, multiple);// Respect the workflow's size limits while keeping the aspect ratio.const maxW = Number(manifest.limits?.maxWidth ?? Infinity);const maxH = Number(manifest.limits?.maxHeight ?? Infinity);@@ -458,6 +513,17 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,values.height = Math.max(multiple, Math.floor((dims.height * k) / multiple) * multiple);}if (b.frames && span) values.frames = computeFrames(span, fps, Number(d.frameStep ?? 4), manifest.limits?.maxFrames);+ // Lip re-sync runs as long as the new voice; a voice past the frame cap is refused, not cut.+ const voiceLength = ctx.op === "lipsync" && b.frames && !span ? ctx.media?.(String(values.audio ?? ""))?.duration : undefined;+ if (voiceLength) {+ const step = Number(d.frameStep ?? 4);+ const frames = Math.ceil((voiceLength * fps) / step) * step + 1;+ const cap = Number(manifest.limits?.maxFrames ?? 0);+ if (cap && frames > cap) {+ throw new ProviderError(`Lip re-sync on the open engine takes up to ${seconds(cap / fps)} s of speech per job (this voice is ${seconds(voiceLength)} s) — split it into shorter parts`);+ }+ values.frames = frames;+ }// Drawn motion paths (normalised to the start frame) → one pixel point per output frame (Wan-Move).const paths = extra.motionPaths as MotionPaths | undefined;delete extra.motionPaths;@@ -501,22 +567,53 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,delete extra.cues;delete extra.wordsPerCaption;for (const [k, v] of Object.entries(extra)) values[k as BindingKey] = v;+ if (audio2 && ctx.op !== "dialogue" && ctx.op !== "voice-change") values.audio2 = audio2;+ // Soundtrack mix: a silent bed as long as the video, so neither track cuts the other short.+ if (ctx.op === "mux" && b.duration) {+ const tracks = [values.audio, values.audio2].map((n) => ctx.media?.(String(n ?? ""))?.duration ?? 0);+ values.duration = Math.round((clipLength ?? (Math.max(...tracks) || 600)) * 100) / 100 + 0.5; // the mux trims it to the picture+ }- // Reference slots the user left empty reuse the previous image (style references want all four; a dress- // is both the top and the bottom of a try-on).+ // Reference images the user left out: dropped from a FLUX.2 reference chain, else the previous image+ // again where that's harmless (style boards, multi-reference edits), else a clear "add …" message.+ let graph = workflow;+ const left: string[] = [];for (const [k, prev] of [["image2", "image"], ["image3", "image2"], ["image4", "image3"]] as const) {- if (b[k] && values[k] === undefined && values[prev] !== undefined) values[k] = values[prev];+ if (!b[k] || values[k] !== undefined || rules.required?.includes(k)) continue;+ if (values[prev] === undefined && !left.includes(prev)) continue;+ const bypassed = b[k]!.length === 1 ? bypassReference(graph, b[k]![0].node) : null;+ if (bypassed) {+ graph = bypassed;+ left.push(k);+ } else if ((rules.reuse || manifest.capability === "style-reference") && values[prev] !== undefined) values[k] = values[prev];}for (const k of mediaKeys(manifest, workflow)) {- if (values[k] === undefined || values[k] === "") throw new ProviderError(MEDIA_HINT[k] ?? `Add the ${k} input`);+ if (left.includes(k)) continue;+ if (values[k] === undefined || values[k] === "") throw new ProviderError(rules.hints?.[k] ?? MEDIA_HINT[k] ?? `Add the ${k} input`);}- const bound = applyBindings(workflow, b, values);+ // Whisper captions hold the whole clip in RAM (decoded + subtitled copy): refuse what the server can't hold.+ if (manifest.capability === "captions" && !manifest.expand && clip?.width && clip.height && clipLength) {+ const need = clip.width * clip.height * 12 * (clip.frames ?? clipLength * (clip.fps ?? 30)) * 2.5;+ const budget = ((await ctx.serverRam?.()) ?? 16 * GB) / 2;+ if (need > budget) {+ throw new ProviderError(+ `Whisper captions hold the whole clip in memory: this one needs about ${Math.ceil(need / GB)} GB of RAM and this ComfyUI can spare ${Math.floor(budget / GB)} GB. ` ++ "Use Qwen3-ASR + Caption burn-in for long clips, or trim it first",+ );+ }+ }++ const bound = applyBindings(graph, b, Object.fromEntries(Object.entries(values).filter(([k]) => !left.includes(k))));if (bound.missing.length) throw new ProviderError(`Workflow ${manifest.id} bindings point at missing nodes: ${bound.missing.join(", ")}`);let wf = bound.workflow;if (manifest.expand === "captions") {if (!cues.length) throw new ProviderError("No timed captions to burn in. Transcribe the clip first, or write lines like “0.00-2.40: Hello there”");- wf = expandCaptionWorkflow(wf, cues);+ try {+ wf = expandCaptionWorkflow(wf, cues, clip ? { duration: clipLength, fps: clip.fps, width: clip.width, height: clip.height, hasAudio: clip.hasAudio } : {});+ } catch (e) {+ throw new ProviderError((e as Error).message);+ }}if (input.loras?.length) wf = injectLoras(wf, input.loras);const metaBatch = Object.values(wf).some((n) => n.class_type === "VHS_BatchManager");@@ -531,13 +628,15 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,function explainExecutionError(err: { exception_message?: string; node_type?: string } | undefined, manifest?: ManifestWorkflow): string {if (!err) return "Execution error";const msg = (err.exception_message ?? "").trim();- if (manifest?.expand === "captions" && /division by zero|failed to slice video|no frames exist/i.test(msg)) {- return "A caption starts after the end of the video — check the cue times";- }+ const outOfClip = /division by zero|failed to slice video|failed to trim video|no frames exist/i.test(msg);+ if (manifest?.expand === "captions" && outOfClip) return "A caption starts after the end of the video — check the cue times";+ if (manifest?.capability === "trim" && outOfClip) return "The start time is past the end of the clip";if (/no audio stream/i.test(msg)) return "That file has no sound to work with";return `${err.node_type}: ${msg}`;}+const executionError = (entry: HistoryEntry) => entry.status?.messages?.find(([t]) => t === "execution_error")?.[1] as { exception_message?: string; node_type?: string } | undefined;+const promptHasPrefix = (prompt: unknown, prefix: string) =>!!prompt && typeof prompt === "object" && Object.values(prompt as ComfyWorkflow).some((n) => n?.inputs?.filename_prefix === prefix);@@ -545,13 +644,16 @@ const promptHasPrefix = (prompt: unknown, prefix: string) =>* VHS meta-batching re-queues the prompt (new prompt ids) until every frame is done; only the last pass* saves the video. Follow the passes by their shared filename prefix.*/-async function followMetaBatch(prefix: string, manifest: ManifestWorkflow | undefined): Promise<ComfyOutput[] | "running" | null> {+async function followMetaBatch(prefix: string, manifest: ManifestWorkflow | undefined): Promise<ComfyOutput[] | "running" | { error: string } | null> {const queue = await comfyJson<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue");if ([...(queue.queue_running ?? []), ...(queue.queue_pending ?? [])].some((q) => promptHasPrefix(q[2], prefix))) return "running";const hist = await comfyJson<Record<string, HistoryEntry>>("/history?max_items=64");const passes = Object.values(hist).filter((e) => promptHasPrefix(e.prompt?.[2], prefix)).sort((a, c) => Number(c.prompt?.[0] ?? 0) - Number(a.prompt?.[0] ?? 0));+ // A pass that failed (out of memory, a node exception) ends the job: say why instead of "no output".+ const failed = passes.find((e) => e.status?.status_str === "error");+ if (failed) return { error: explainExecutionError(executionError(failed), manifest) };for (const e of passes) {const files = collectOutputs(e, manifest, baseUrl(), authHeaders());if (files.length) return files;@@ -579,7 +681,13 @@ export const comfyProvider: ProviderAdapter = {const res = await comfyFetch("/upload/image", { method: "POST", body: form });if (!res.ok) throw new ProviderError(`ComfyUI upload failed: ${res.status} ${await res.text()}`);const j = (await res.json()) as { name: string; subfolder?: string };- return j.subfolder ? `${j.subfolder}/${j.name}` : j.name;+ const uploaded = j.subfolder ? `${j.subfolder}/${j.name}` : j.name;+ // Remember a clip's / track's header facts (length, size, fps, audio) for prepareWorkflow.+ if (MEDIA_FILE.test(contentType) || MEDIA_EXT.test(name)) {+ const info = probeMedia(data);+ if (info) rememberMedia(uploaded, info);+ }+ return uploaded;},async submit({ route, input, generationId }) {@@ -587,6 +695,8 @@ export const comfyProvider: ProviderAdapter = {generationId,op: route.op,upload: (data, contentType, name) => comfyProvider.prepareFile(data, contentType, name),+ media: mediaInfoFor,+ serverRam: async () => (await comfyJson<{ system?: { ram_total?: number } }>("/system_stats").catch(() => undefined))?.system?.ram_total,});const { clientId } = ensureSocket();const res = await comfyFetch("/prompt", {@@ -594,9 +704,13 @@ export const comfyProvider: ProviderAdapter = {headers: { "Content-Type": "application/json" },body: JSON.stringify({ prompt: wf, client_id: clientId }),});- const body = (await res.json().catch(() => ({}))) as { prompt_id?: string; error?: { message?: string }; node_errors?: unknown };+ const body = (await res.json().catch(() => ({}))) as { prompt_id?: string; error?: { type?: string; message?: string }; node_errors?: unknown };if (!res.ok || !body.prompt_id) {- const detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...(input.loras ?? []).map((l) => ({ file: l.file, folder: "loras", url: l.url }))] }) : body.error?.message;+ // A node class the server doesn't have: name the pack to install (opt-in packs like ComfyUI-Whisper).+ const packs = manifest.customNodes.map((c) => c.name);+ const missingPack =+ body.error?.type === "missing_node_type" && packs.length ? `This workflow needs the ${packs.join(" + ")} node pack${packs.length > 1 ? "s" : ""} on your ComfyUI (see scripts/comfy/README.md)` : undefined;+ const detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...(input.loras ?? []).map((l) => ({ file: l.file, folder: "loras", url: l.url }))] }) : (missingPack ?? body.error?.message);throw new ProviderError(detail ?? `ComfyUI /prompt failed (${res.status})`, res.status);}return { externalId: body.prompt_id, meta, payload: wf };@@ -610,13 +724,16 @@ export const comfyProvider: ProviderAdapter = {const finished = async (entry: HistoryEntry) => {if (entry.status?.status_str === "error") {forget(externalId);- const err = entry.status.messages?.find(([t]) => t === "execution_error")?.[1] as { exception_message?: string; node_type?: string } | undefined;- return { state: "failed" as const, error: explainExecutionError(err, manifest) };+ return { state: "failed" as const, error: explainExecutionError(executionError(entry), manifest) };}let outputs = collectOutputs(entry, manifest, baseUrl(), authHeaders());if (!outputs.length && meta.metaBatch && typeof meta.prefix === "string") {const next = await followMetaBatch(meta.prefix, manifest);if (next === "running") return { state: "running" as const, message: "Rendering the next batch of frames" };+ if (next && "error" in next) {+ forget(externalId);+ return { state: "failed" as const, error: next.error };+ }outputs = next ?? [];}forget(externalId);diff --git a/tests/comfy-provider.test.ts b/tests/comfy-provider.test.tsindex 4a8d9b1d..556c1f26 100644--- a/tests/comfy-provider.test.ts+++ b/tests/comfy-provider.test.ts@@ -5,6 +5,7 @@ import path from "node:path";import zlib from "node:zlib";import { afterAll, afterEach, beforeEach, describe, expect, it } from "vitest";import type { ManifestWorkflow } from "@/lib/comfy";+import type { MediaInfo } from "@/lib/media-probe";import type { ModelDef, ModelRoute } from "@/lib/catalog/types";const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-provider-"));@@ -12,7 +13,7 @@ process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://comfy.test:8188";const { setSetting } = await import("@/server/settings");-const { comfyProvider, collectOutputs, getWorkflow, loadManifest, prepareWorkflow } = await import("@/server/providers/comfyui");+const { comfyProvider, collectOutputs, getWorkflow, loadManifest, mediaInfoFor, prepareWorkflow } = await import("@/server/providers/comfyui");const { MODELS } = await import("@/lib/catalog");const { computeFrames } = await import("@/lib/comfy");@@ -293,6 +294,28 @@ describe("ComfyUI output mapping", () => {expect(res).toMatchObject({ state: "succeeded", outputs: [{ kind: "video", url: expect.stringContaining("gen-mm_00001.mp4") }] });});+ it("reports a meta-batch pass that failed instead of 'no output'", async () => {+ const prefix = "fuobe/gen-mm-fail";+ const graph = { "22": { class_type: "VHS_VideoCombine", inputs: { filename_prefix: prefix } } };+ handler = (url) => {+ if (url.includes("/history/p-mmf")) return json({ "p-mmf": { prompt: [1, "p-mmf", graph], ...done({}) } });+ if (url.endsWith("/queue")) return json({ queue_running: [], queue_pending: [] });+ if (url.includes("/history?max_items"))+ return json({+ "p-mmf": { prompt: [1, "p-mmf", graph], ...done({}) },+ "pass-2": { prompt: [2, "pass-2", graph], status: { status_str: "error", messages: [["execution_error", { node_type: "KSampler", exception_message: "CUDA out of memory" }]] }, outputs: {} },+ });+ return json({});+ };+ const meta = { workflowId: "mixed-media-zimage-frames", nodeCount: 17, prefix, metaBatch: true };+ expect(await comfyProvider.poll(pollCtx("p-mmf", meta))).toEqual({ state: "failed", error: "KSampler: CUDA out of memory" });+ });++ it("explains a trim that starts past the end of the clip", async () => {+ handler = () => json({ "p-trim": { status: { status_str: "error", messages: [["execution_error", { node_type: "SaveVideo", exception_message: "No frames exist for start_time 9.0" }]] }, outputs: {} } });+ expect(await comfyProvider.poll(pollCtx("p-trim", { workflowId: "video-trim", nodeCount: 3 }))).toEqual({ state: "failed", error: "The start time is past the end of the clip" });+ });+it("explains a caption that starts after the end of the clip", async () => {handler = () =>json({@@ -308,6 +331,48 @@ describe("ComfyUI output mapping", () => {});});+describe("ComfyUI uploads and submit", () => {+ /** A minimal MP4: ftyp + moov with mvhd and one video trak (tkhd 1280x720, mdhd, hdlr vide, stts 50 frames). */+ function tinyMp4(): Buffer {+ const box = (type: string, ...parts: Buffer[]) => {+ const body = Buffer.concat(parts);+ const head = Buffer.alloc(8);+ head.writeUInt32BE(8 + body.length);+ head.write(type, 4);+ return Buffer.concat([head, body]);+ };+ const u32 = (...v: number[]) => Buffer.concat(v.map((n) => { const b = Buffer.alloc(4); b.writeUInt32BE(n >>> 0); return b; }));+ const mvhd = box("mvhd", u32(0, 0, 0, 1000, 2000), Buffer.alloc(80));+ const matrix = u32(0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000);+ const tkhd = box("tkhd", u32(0, 0, 0, 1, 0, 2000), Buffer.alloc(8), Buffer.alloc(8), matrix, u32(1280 << 16, 720 << 16));+ const mdhd = box("mdhd", u32(0, 0, 0, 25, 50), Buffer.alloc(4));+ const hdlr = box("hdlr", u32(0, 0), Buffer.from("vide"), Buffer.alloc(12));+ const stts = box("stts", u32(0, 1, 50, 1));+ const trak = box("trak", tkhd, box("mdia", mdhd, hdlr, box("minf", box("stbl", stts))));+ return Buffer.concat([box("ftyp", Buffer.from("isom"), u32(0)), box("moov", mvhd, trak)]);+ }++ it("remembers what an uploaded clip's header says, for the next prompt", async () => {+ handler = (url) => (url.endsWith("/upload/image") ? json({ name: "fuobe_abc.mp4", subfolder: "" }) : json({}));+ const name = await comfyProvider.prepareFile(tinyMp4(), "video/mp4", "clip.mp4");+ expect(name).toBe("fuobe_abc.mp4");+ expect(mediaInfoFor(name)).toMatchObject({ container: "mp4", hasVideo: true, hasAudio: false, width: 1280, height: 720, frames: 50, fps: 25, duration: 2, videoDuration: 2 });+ handler = (url) => (url.endsWith("/upload/image") ? json({ name: "fuobe_img.png", subfolder: "" }) : json({}));+ expect(mediaInfoFor(await comfyProvider.prepareFile(Buffer.from("\x89PNG...."), "image/png", "a.png"))).toBeUndefined();+ });++ it("names the node pack to install when ComfyUI lacks a node class", async () => {+ handler = (url) =>+ url.endsWith("/prompt")+ ? json({ error: { type: "missing_node_type", message: "Node 'Apply Whisper' not found. The custom node may not be installed." }, node_errors: {} }, 400)+ : json({});+ const whisperRoute: ModelRoute = { op: "captions", provider: "comfyui", endpoint: "captions-whisper-burnin" };+ await expect(+ comfyProvider.submit({ generationId: "g-np", model, route: whisperRoute, input: { video: "clip.mp4", prompt: "" } }),+ ).rejects.toThrow("This workflow needs the ComfyUI-VideoHelperSuite + ComfyUI-Whisper node packs on your ComfyUI (see scripts/comfy/README.md)");+ });+});+// ---------------------------------------------------------------------------// Every round-3 workflow, bound for real (applyBindings on the library graph through prepareWorkflow)@@ -324,7 +389,8 @@ const CUES = "0.00-1.00: Hello there\n1.20-2.00: Second line";const GIVEN = new Set(["img1.png", "img2.png", "clip.mp4", "voice.wav", "bg.wav", "up_palette_swatch.png"]);const opFor = (id: string) => MODELS.flatMap((m) => m.routes).find((r) => r.provider === "comfyui" && r.endpoint === id)?.op ?? (id.startsWith("video-mux") ? "mux" : "t2i");-async function prepare(id: string, over: Record<string, unknown> = {}, op = opFor(id)) {+type Facts = { media?: Record<string, MediaInfo>; ram?: number };+async function prepare(id: string, over: Record<string, unknown> = {}, op = opFor(id), facts: Facts = {}) {const input = {prompt: CUES,negativePrompt: "blurry",@@ -350,9 +416,13 @@ async function prepare(id: string, over: Record<string, unknown> = {}, op = opFouploads.push(name);return `up_${name}`;},+ media: (name) => facts.media?.[name],+ serverRam: async () => facts.ram,});return { ...res, uploads };}+const mp4 = (over: Partial<MediaInfo> = {}): MediaInfo => ({ container: "mp4", hasVideo: true, hasAudio: true, duration: 6, videoDuration: 6, width: 640, height: 360, fps: 30, frames: 180, ...over });+const wavOf = (duration: number): MediaInfo => ({ container: "wav", hasVideo: false, hasAudio: true, duration });const at = (wf: Record<string, { inputs: Record<string, unknown> }>, m: ManifestWorkflow, key: string) => (m.bindings[key] ?? []).map((t) => wf[t.node].inputs[t.input]);describe("round-3 workflow bindings", () => {@@ -417,27 +487,107 @@ describe("round-3 workflow bindings", () => {});it("fills reference slots, trigger words and grid framing", async () => {+ // FLUX.2 reference chains: references not given are left out (their ReferenceLatent pair bypassed), not repeatedconst klein = await prepare("style-ref-flux2-klein-4b");- expect(at(klein.workflow, klein.manifest, "image3")).toEqual(["img2.png"]);- expect(at(klein.workflow, klein.manifest, "image4")).toEqual(["img2.png"]);+ expect(klein.workflow["77"]).toBeUndefined();+ expect(klein.workflow["78"]).toBeUndefined();+ expect(klein.workflow["75:63"].inputs.positive).toEqual(["75:200", 0]);const tryon = await prepare("tryon-flux2-klein-4b", { prompt: "wear these" });expect(tryon.workflow["75:74"].inputs.text).toBe("TRYON wear these");- expect(tryon.workflow["77"].inputs.image).toBe("img2.png"); // a dress is both top and bottom+ expect(tryon.workflow["81"].inputs.image).toBe("img2.png"); // the garment+ expect(tryon.workflow["77"]).toBeUndefined(); // no bottom given: one garment reference, not the top twiceconst grid = await prepare("grid-zimage-contact-sheet", { prompt: "a heist", extra: { columns: 2, rows: 2 } });expect(grid.workflow["20"].inputs.string_a).toMatch(/^A 2x2 grid contact sheet of 4 film stills/);expect(grid.workflow["27"].inputs).toMatchObject({ columns: 2, rows: 2 });await expect(prepare("style-ref-qwen-edit-2511", { images: [] })).rejects.toThrow(/Add an image/);});+ it("repeats a reference only where that is harmless, and otherwise asks for the missing image", async () => {+ // style boards (TextEncodeQwenImageEditPlus): one collage passed twice+ const board = await prepare("style-ref-qwen-edit-2511", { images: ["img1.png"] });+ expect(at(board.workflow, board.manifest, "image2")).toEqual(["img1.png"]);+ // a photo is not its own palette, lighting reference or garment+ await expect(prepare("palette-transfer-image", { images: ["img1.png"], palette: [] }, "color-match")).rejects.toThrow("Pick a palette or add a reference image");+ await expect(prepare("relight-qwen-edit-2509-reference", { images: ["img1.png"] }, "edit")).rejects.toThrow("Add the photo whose light to copy");+ await expect(prepare("tryon-flux2-klein-4b", { images: ["img1.png"], prompt: "x" })).rejects.toThrow("Add the garment to try on");+ // with a palette the swatch fills the reference slot+ const swatch = await prepare("palette-transfer-image", { images: ["img1.png"] }, "color-match");+ expect(swatch.workflow["2"].inputs.image).toBe("up_palette_swatch.png");+ });++ it("checks trim times against each other and the clip's length", async () => {+ await expect(prepare("video-trim", { startTime: 3, endTime: 2 })).rejects.toThrow("The end time must be after the start time");+ await expect(prepare("video-segment-resample", { startTime: 2, endTime: 2 })).rejects.toThrow("The end time must be after the start time");+ await expect(prepare("video-trim", { startTime: 7, endTime: 9 }, "trim", { media: { "clip.mp4": mp4() } })).rejects.toThrow("The start time is past the end of the clip (it is 6 s long)");+ const ok = await prepare("video-trim", { startTime: 1, endTime: 3 }, "trim", { media: { "clip.mp4": mp4() } });+ expect(ok.workflow["2"].inputs).toMatchObject({ start_time: 1, duration: 2 });+ });++ it("takes the source clip's shape for 'auto' and times lip re-sync by the voice, refusing more than the frame cap", async () => {+ const portrait = mp4({ width: 1080, height: 1920 });+ const lip = await prepare("lipsync-v2v-infinitetalk", { aspectRatio: "auto", resolution: "480p", startTime: undefined, endTime: undefined }, "lipsync", {+ media: { "clip.mp4": portrait, "voice.wav": wavOf(12.3) },+ });+ const { workflow: wf, manifest } = lip;+ expect(at(wf, manifest, "width")).toEqual([480]);+ expect(at(wf, manifest, "height")).toEqual([848]); // 9:16 at 480p, multiple of 16: no squashing into 16:9+ expect(wf["228"].inputs.custom_height).toBe(0); // VHS keeps the proportions, ImageResizeKJv2 crops+ expect(at(wf, manifest, "frames")).toEqual([309, 309]); // ceil(12.3 s × 25 fps / 4) × 4 + 1, also VHS frame_load_cap+ await expect(+ prepare("lipsync-v2v-infinitetalk", { aspectRatio: "auto", startTime: undefined, endTime: undefined }, "lipsync", { media: { "voice.wav": wavOf(55) } }),+ ).rejects.toThrow(/up to 40 s of speech per job \(this voice is 55 s\)/);+ // without header facts: the old 16:9 default, the 1000-frame cap+ const blind = await prepare("lipsync-v2v-infinitetalk", { aspectRatio: "auto", startTime: undefined, endTime: undefined }, "lipsync");+ expect(at(blind.workflow, blind.manifest, "frames")).toEqual([1000, 1000]);+ });++ it("maps the source language to Whisper's names and refuses clips Whisper can't hold in RAM", async () => {+ const tl = await prepare("captions-whisper-burnin", { sourceLanguage: "tl" }, "captions");+ expect(tl.workflow["3"].inputs.language).toBe("Tagalog");+ const he = await prepare("captions-whisper-burnin", { sourceLanguage: "he" }, "captions");+ expect(he.workflow["3"].inputs.language).toBe("Hebrew");+ const short = { "clip.mp4": mp4() };+ await expect(prepare("captions-whisper-burnin", {}, "captions", { media: short, ram: 16 * 2 ** 30 })).resolves.toBeTruthy();+ const long = { "clip.mp4": mp4({ width: 1080, height: 1920, duration: 30, videoDuration: 30, frames: 900 }) };+ await expect(prepare("captions-whisper-burnin", {}, "captions", { media: long, ram: 16 * 2 ** 30 })).rejects.toThrow(/needs about 53 GB of RAM and this ComfyUI can spare 8 GB/);+ });+it("uses the one-track soundtrack graph without a background stem", async () => {const mix = await prepare("video-mux-audio");expect(mix.manifest.id).toBe("video-mux-audio");expect(mix.workflow["4"].inputs.audio).toBe("bg.wav");+ expect(mix.workflow["7"]).toMatchObject({ class_type: "ConcatenateVideo", inputs: { "videos.video0": ["1", 0], complete_audio: ["6", 0] } });const one = await prepare("video-mux-audio", { extra: {} });expect(one.manifest.id).toBe("video-mux-audio-replace");expect(one.workflow["3"].inputs.audio).toBe("voice.wav");});+ it("takes the background from inputs.audio2 when the runtime sends it, and mixes over a bed as long as the video", async () => {+ const canonical = await prepare("video-mux-audio", { audio2: "stem_bg.wav", extra: { audio2: "bg.wav" } }, "mux", { media: { "clip.mp4": mp4({ videoDuration: 61.2, duration: 61.25 }) } });+ expect(canonical.manifest.id).toBe("video-mux-audio");+ expect(canonical.workflow["4"].inputs.audio).toBe("stem_bg.wav");+ expect(canonical.workflow["9"].inputs.duration).toBe(61.7); // the video's length (+0.5 s; the mux trims to the picture)+ const onlyCanonical = await prepare("video-mux-audio", { audio2: "stem_bg.wav", extra: {} });+ expect(onlyCanonical.manifest.id).toBe("video-mux-audio");+ // no video header: the longer of the two tracks+ const blind = await prepare("video-mux-audio", {}, "mux", { media: { "voice.wav": wavOf(5), "bg.wav": wavOf(8.04) } });+ expect(blind.workflow["9"].inputs.duration).toBe(8.54);+ });++ it("burns captions with the clip's facts: a gap after the last cue and the clip's own soundtrack", async () => {+ const { workflow } = await prepare("captions-burnin", {}, "captions", { media: { "clip.mp4": mp4() } });+ const joins = Object.values(workflow).filter((n) => n.class_type === "ConcatenateVideo");+ expect(joins).toHaveLength(1);+ expect(joins[0].inputs.complete_audio).toEqual(["3", 0]);+ expect(workflow["3"].inputs.audio).toBe("clip.mp4");+ const slices = Object.values(workflow).filter((n) => n.class_type === "Video Slice");+ expect(slices.at(-1)!.inputs.duration).toBe(0); // the uncaptioned rest of the clip+ expect(slices).toHaveLength(4); // cue, gap, cue, rest+ const silent = await prepare("captions-burnin", {}, "captions", { media: { "clip.mp4": mp4({ hasAudio: false }) } });+ expect(Object.values(silent.workflow).some((n) => n.class_type === "LoadAudio")).toBe(false);+ await expect(prepare("captions-burnin", { prompt: "9.00-10.00: too late" }, "captions", { media: { "clip.mp4": mp4() } })).rejects.toThrow(/after the end of the clip/);+ });+it("writes one segment per caption cue with the chosen style", async () => {const { workflow } = await prepare("captions-burnin", { extra: { fontSize: 8, captionPosition: "top", fontColor: "#ffd400" } });const slices = Object.values(workflow).filter((n) => n.class_type === "Video Slice").map((n) => [n.inputs.start_time, n.inputs.duration]);diff --git a/tests/comfy.test.ts b/tests/comfy.test.tsindex 577cbb60..8e3c3a38 100644--- a/tests/comfy.test.ts+++ b/tests/comfy.test.ts@@ -5,6 +5,8 @@ import {alphaBBox,applyBindings,asrLanguage,+ bypassReference,+ captionChunkSeconds,computeDimensions,computeFrames,expandCaptionWorkflow,@@ -17,6 +19,7 @@ import {referencedModels,splitCueWords,swatchPixels,+ whisperLanguage,type ComfyWorkflow,} from "@/lib/comfy";@@ -121,35 +124,124 @@ describe("caption cues", () => {describe("caption burn-in graph", () => {const template = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui/captions-burnin.json"), "utf8")) as ComfyWorkflow;const kinds = (wf: ComfyWorkflow, t: string) => Object.entries(wf).filter(([, n]) => n.class_type === t);+ const windows = (wf: ComfyWorkflow) => kinds(wf, "Video Slice").map(([, n]) => [n.inputs.start_time, n.inputs.duration]);+ const linksResolve = (wf: ComfyWorkflow) => Object.values(wf).every((n) => Object.values(n.inputs).every((v) => !Array.isArray(v) || typeof v[0] !== "string" || !!wf[v[0]]));- it("cuts the clip into gap and cue segments that tile the timeline; the last cue runs to the end", () => {+ it("cuts the clip into gap and cue windows that tile the timeline; without a known length the last cue runs to the end", () => {const wf = expandCaptionWorkflow(template, [{ start: 0.5, end: 1.5, text: "Hello" },{ start: 1.5, end: 2.0, text: "world" },{ start: 3.0, end: 4.0, text: "again" },]);- const slices = kinds(wf, "Video Slice").map(([, n]) => [n.inputs.start_time, n.inputs.duration]);- expect(slices).toEqual([[0, 0.5], [0.5, 1], [1.5, 0.5], [2, 1], [3, 0]]);+ expect(windows(wf)).toEqual([[0, 0.5], [0.5, 1], [1.5, 0.5], [2, 1], [3, 0]]);expect(kinds(wf, "TextOverlay").map(([, n]) => n.inputs.text)).toEqual(["Hello", "world", "again"]);- // style copied from the template's overlay; frames come from each segment+ // style copied from the template's overlay; each captioned chunk is decoded, overlaid and encoded on its ownfor (const [, n] of kinds(wf, "TextOverlay")) expect(n.inputs).toMatchObject({ font_size: 6, position: "bottom", align: "center", outline: true });- // the batch keeps segment order, CreateVideo / SaveVideo are untouched- const batch = wf["90"];- expect(Object.keys(batch.inputs)).toEqual(["images.image0", "images.image1", "images.image2", "images.image3", "images.image4"]);- expect(wf["91"].inputs).toMatchObject({ images: ["90", 0], fps: ["2", 2], audio: ["2", 1] });- expect(Object.values(wf).every((n) => Object.values(n.inputs).every((v) => !Array.isArray(v) || !!wf[v[0] as string]))).toBe(true);+ for (const [, n] of kinds(wf, "CreateVideo")) expect(n.inputs.codec).toBe("h264");+ expect(kinds(wf, "GetVideoComponents")).toHaveLength(3); // gaps are never decoded+ // the join keeps window order (encoded chunks and raw gaps); the soundtrack node is dropped when we don't know the clip has sound+ const join = wf["90"].inputs;+ expect(Object.keys(join).filter((k) => k.startsWith("videos."))).toEqual(["videos.video0", "videos.video1", "videos.video2", "videos.video3", "videos.video4"]);+ expect(wf[(join["videos.video0"] as [string, number])[0]].class_type).toBe("Video Slice");+ expect(wf[(join["videos.video1"] as [string, number])[0]].class_type).toBe("CreateVideo");+ expect(join.complete_audio).toBeUndefined();+ expect(kinds(wf, "LoadAudio")).toHaveLength(0);+ expect(wf["92"].inputs.video).toEqual(["90", 0]);+ expect(linksResolve(wf)).toBe(true);});- it("nests batches past 50 segments and refuses an empty cue list", () => {- const cues = Array.from({ length: 60 }, (_, i) => ({ start: i, end: i + 1, text: `cue ${i}` }));+ it("uses what the MP4 header says: edges between frames, a gap after the last cue, cues past the end dropped, the clip's own soundtrack", () => {+ const clip = { duration: 6, fps: 30, width: 640, height: 360, hasAudio: true };+ const wf = expandCaptionWorkflow(template, [+ { start: 0, end: 1, text: "First" },+ { start: 1.2, end: 2, text: "Second" },+ { start: 7, end: 8, text: "after the end" },+ ], clip);+ const half = 0.5 / 30;+ const w = windows(wf).map(([s, d]) => [Number(s).toFixed(4), Number(d).toFixed(4)]);+ expect(w).toEqual([+ ["0.0000", (1 - half).toFixed(4)], // frames 0-29+ [(1 - half).toFixed(4), "0.2000"], // gap, frames 30-35+ [(1.2 - half).toFixed(4), "0.8000"], // frames 36-59+ [(2 - half).toFixed(4), "0.0000"], // the rest of the clip, uncaptioned+ ]);+ expect(kinds(wf, "TextOverlay").map(([, n]) => n.inputs.text)).toEqual(["First", "Second"]);+ expect(wf["90"].inputs.complete_audio).toEqual(["3", 0]);+ expect(wf["3"]).toMatchObject({ class_type: "LoadAudio" });+ expect(linksResolve(wf)).toBe(true);+ expect(() => expandCaptionWorkflow(template, [{ start: 7, end: 8, text: "late" }], clip)).toThrow(/after the end of the clip/);+ });++ it("cuts long captioned stretches into chunks sized to the frame (one chunk of raw frames in memory at a time)", () => {+ expect(captionChunkSeconds({})).toBe(1);+ expect(captionChunkSeconds({ width: 1080, height: 1920, fps: 30 })).toBeCloseTo(0.54, 2);+ expect(captionChunkSeconds({ width: 320, height: 240, fps: 8 })).toBe(5);+ const clip = { duration: 10, fps: 30, width: 1080, height: 1920, hasAudio: false };+ const wf = expandCaptionWorkflow(template, [{ start: 0, end: 4, text: "A long line" }], clip);+ const overlays = kinds(wf, "TextOverlay");+ expect(overlays.length).toBe(8); // 4 s in ~0.5 s chunks+ expect(overlays.every(([, n]) => n.inputs.text === "A long line")).toBe(true);+ // chunks tile the cue exactly, each starting half a frame before its first frame+ const w = windows(wf);+ const cue = w.slice(0, 8);+ expect(cue[0][0]).toBe(0);+ for (let i = 1; i < cue.length; i++) expect(Number(cue[i][0])).toBeCloseTo(Number(cue[i - 1][0]) + Number(cue[i - 1][1]), 6);+ for (const [s] of cue.slice(1)) {+ const frame = Number(s) * 30 + 0.5;+ expect(Math.abs(frame - Math.round(frame))).toBeLessThan(1e-4); // windows are written to the microsecond+ }+ expect(Number(cue[7][0]) + Number(cue[7][1])).toBeCloseTo(4 - 0.5 / 30, 6);+ expect(w[8]).toEqual([Number(cue[7][0]) + Number(cue[7][1]), 0]);+ });++ it("never writes a window shorter than three frames (Concatenate Video rejects a 2-frame clip followed by another)", () => {+ const clip = { duration: 3, fps: 8, width: 320, height: 240, hasAudio: true };+ const wf = expandCaptionWorkflow(template, [+ { start: 0, end: 1, text: "Hello" },+ { start: 1.2, end: 2.5, text: "Open captions" }, // 0.2 s pause = 2 frames at 8 fps: no gap window+ { start: 2.6, end: 2.65, text: "blip" }, // shorter than a frame, near the end: runs to the end+ ], clip);+ const w = windows(wf).map(([s, d]) => [Number(s), Number(d)]);+ expect(w).toEqual([[0, 0.9375], [0.9375, 1.5], [2.4375, 0]]);+ expect(kinds(wf, "TextOverlay").map(([, n]) => n.inputs.text)).toEqual(["Hello", "Open captions", "blip"]);+ // a lone very short caption in the middle is held for three frames+ const held = windows(expandCaptionWorkflow(template, [{ start: 1, end: 1.05, text: "Hi" }], { ...clip, duration: 10 })).map(([s, d]) => [Number(s), Number(d)]);+ expect(held).toEqual([[0, 0.9375], [0.9375, 0.375], [1.3125, 0]]);+ });++ it("nests joins past 100 clips and refuses an empty cue list", () => {+ const cues = Array.from({ length: 120 }, (_, i) => ({ start: i, end: i + 1, text: `cue ${i}` }));const wf = expandCaptionWorkflow(template, cues);- const batches = kinds(wf, "BatchImagesNode");- expect(batches.length).toBe(3); // 60 segments: 50 + 10, then the top level- expect(Object.keys(wf["90"].inputs)).toEqual(["images.image0", "images.image1"]);+ const joins = kinds(wf, "ConcatenateVideo");+ expect(joins.length).toBe(3); // 120 clips: 100 + 20, then the top level+ expect(Object.keys(wf["90"].inputs).filter((k) => k.startsWith("videos."))).toEqual(["videos.video0", "videos.video1"]);+ expect(linksResolve(wf)).toBe(true);expect(() => expandCaptionWorkflow(template, [])).toThrow(/No captions/);});});+describe("reference slots", () => {+ const load = (id: string) => JSON.parse(fs.readFileSync(path.join(process.cwd(), `workflows/comfyui/${id}.json`), "utf8")) as ComfyWorkflow;++ it("leaves an image out of a FLUX.2 reference chain by bypassing its ReferenceLatent pair", () => {+ const tryon = load("tryon-flux2-klein-4b");+ const wf = bypassReference(tryon, "77")!; // the bottom garment+ expect(wf).not.toBeNull();+ for (const gone of ["77", "75:181", "75:191", "75:201", "75:211"]) expect(wf[gone]).toBeUndefined();+ expect(wf["75:63"].inputs).toMatchObject({ positive: ["75:200", 0], negative: ["75:210", 0] });+ expect(wf["81"]).toBeDefined(); // the top stays+ // two left out in a row (style board with one image): the chain falls back to the first reference+ const klein = load("style-ref-flux2-klein-4b");+ const one = bypassReference(bypassReference(bypassReference(klein, "81")!, "77")!, "78")!;+ expect(one["75:63"].inputs).toMatchObject({ positive: ["75:123", 0], negative: ["75:121", 0] });+ });++ it("refuses when the image is used another way", () => {+ expect(bypassReference(load("palette-transfer-image"), "2")).toBeNull();+ expect(bypassReference(load("relight-qwen-edit-2509-reference"), "1003")).toBeNull();+ });+});+describe("languages, palettes, layers", () => {it("maps languages to the ASR list and to instruction words", () => {expect(asrLanguage("de")).toBe("German");@@ -163,6 +255,20 @@ describe("languages, palettes, layers", () => {expect(languageName("Klingon")).toBe("Klingon");});+ it("maps languages to Whisper's own names, every one of them in ComfyUI-Whisper's combo", () => {+ expect(whisperLanguage("tl")).toBe("Tagalog");+ expect(whisperLanguage("fil")).toBe("Tagalog");+ expect(whisperLanguage("Filipino")).toBe("Tagalog");+ expect(whisperLanguage("he")).toBe("Hebrew");+ expect(whisperLanguage("uk-UA")).toBe("Ukrainian");+ expect(whisperLanguage("Swahili (sw)")).toBe("Swahili");+ expect(whisperLanguage("ht")).toBe("Haitian creole");+ expect(whisperLanguage("Klingon")).toBe("auto");+ const subset = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui/object_info.subset.json"), "utf8"));+ const combo = new Set<string>(subset["Apply Whisper"].input.optional.language[0]);+ for (const code of ["en", "tl", "he", "uk", "sw", "yue", "haw", "jw", "my", "ht", "nn", "zh", "pt"]) expect(combo.has(whisperLanguage(code)), code).toBe(true);+ });+it("writes the palette sentence and a banded swatch", () => {expect(parseHex("#fff")).toEqual([255, 255, 255]);expect(parseHex("nope")).toBeNull();diff --git a/tests/media-probe.test.ts b/tests/media-probe.test.tsnew file mode 100644index 00000000..6e551bd5--- /dev/null+++ b/tests/media-probe.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from "vitest";+import { probeMedia } from "@/lib/media-probe";++const u32 = (...v: number[]) =>+ Buffer.concat(+ v.map((n) => {+ const b = Buffer.alloc(4);+ b.writeUInt32BE(n >>> 0);+ return b;+ }),+ );+const box = (type: string, ...parts: Buffer[]) => {+ const body = Buffer.concat(parts);+ const head = Buffer.alloc(8);+ head.writeUInt32BE(8 + body.length);+ head.write(type, 4);+ return Buffer.concat([head, body]);+};++/** ISO-BMFF with a video trak (optionally rotated 90°) and an optional sound trak; moov after mdat like a camera file. */+function mp4({ w = 1920, h = 1080, rotate = false, audio = true, frames = 300, fps = 30 } = {}): Buffer {+ const scale = 600;+ const dur = Math.round((frames / fps) * scale);+ const mvhd = box("mvhd", u32(0, 0, 0, scale, dur + (audio ? 12 : 0)), Buffer.alloc(80));+ const matrix = rotate ? u32(0, 0x10000, 0, 0xffff0000, 0, 0, 0, 0, 0x40000000) : u32(0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000);+ const tkhd = box("tkhd", u32(0, 0, 0, 1, 0, dur), Buffer.alloc(16), matrix, u32(w << 16, h << 16));+ const video = box(+ "trak",+ tkhd,+ box("mdia", box("mdhd", u32(0, 0, 0, fps * 1000, frames * 1000), Buffer.alloc(4)), box("hdlr", u32(0, 0), Buffer.from("vide"), Buffer.alloc(12)), box("minf", box("stbl", box("stts", u32(0, 2, frames - 1, 1000, 1, 1000))))),+ );+ const sound = box("trak", box("mdia", box("mdhd", u32(0, 0, 0, 48000, 48000 * 10), Buffer.alloc(4)), box("hdlr", u32(0, 0), Buffer.from("soun"), Buffer.alloc(12))));+ return Buffer.concat([box("ftyp", Buffer.from("mp42"), u32(0)), box("mdat", Buffer.alloc(64)), box("moov", mvhd, video, ...(audio ? [sound] : []))]);+}++function wav(seconds: number, rate = 22050, channels = 1): Buffer {+ const data = Buffer.alloc(Math.round(seconds * rate) * 2 * channels);+ const h = Buffer.alloc(44);+ h.write("RIFF", 0);+ h.writeUInt32LE(36 + data.length, 4);+ h.write("WAVEfmt ", 8);+ h.writeUInt32LE(16, 16);+ h.writeUInt16LE(1, 20);+ h.writeUInt16LE(channels, 22);+ h.writeUInt32LE(rate, 24);+ h.writeUInt32LE(rate * 2 * channels, 28);+ h.writeUInt16LE(2 * channels, 32);+ h.writeUInt16LE(16, 34);+ h.write("data", 36);+ h.writeUInt32LE(data.length, 40);+ return Buffer.concat([h, data]);+}++describe("media probe", () => {+ it("reads an MP4's length, size, frame rate and tracks, with moov after the media data", () => {+ expect(probeMedia(mp4())).toEqual({ container: "mp4", hasVideo: true, hasAudio: true, duration: 10.02, videoDuration: 10, width: 1920, height: 1080, frames: 300, fps: 30 });+ expect(probeMedia(mp4({ audio: false, frames: 120, fps: 24 }))).toMatchObject({ hasAudio: false, duration: 5, videoDuration: 5, fps: 24, frames: 120 });+ });++ it("swaps width and height for a phone clip stored with a 90° rotation", () => {+ expect(probeMedia(mp4({ rotate: true }))).toMatchObject({ width: 1080, height: 1920 });+ });++ it("reads WAV, FLAC and MP3 lengths", () => {+ expect(probeMedia(wav(2.5))).toEqual({ container: "wav", duration: 2.5, hasVideo: false, hasAudio: true });+ expect(probeMedia(wav(1, 48000, 2))?.duration).toBe(1);+ // FLAC STREAMINFO: 44.1 kHz, 132300 samples = 3 s+ const flac = Buffer.alloc(42);+ flac.write("fLaC", 0);+ flac.writeUInt32BE(34, 4); // block header: STREAMINFO, 34 bytes+ const rate = 44100;+ const total = 132300;+ flac[18] = rate >> 12;+ flac[19] = (rate >> 4) & 0xff;+ flac[20] = ((rate & 0xf) << 4) | (1 << 1);+ flac[21] = 0xf0 | Math.floor(total / 2 ** 32);+ flac.writeUInt32BE(total >>> 0, 22);+ expect(probeMedia(flac)).toEqual({ container: "flac", duration: 3, hasVideo: false, hasAudio: true });+ // MP3 with a Xing header: MPEG-1 Layer III, 44.1 kHz stereo, 100 frames × 1152 samples+ const mp3 = Buffer.alloc(417 * 3);+ mp3.set([0xff, 0xfb, 0x90, 0x00], 0);+ mp3.write("Xing", 4 + 32);+ mp3.writeUInt32BE(1, 4 + 32 + 4);+ mp3.writeUInt32BE(100, 4 + 32 + 8);+ expect(probeMedia(mp3)?.duration).toBeCloseTo((100 * 1152) / 44100, 6);+ // CBR without a header: 128 kbps → bytes × 8 / bitrate+ const cbr = Buffer.alloc(16000);+ cbr.set([0xff, 0xfb, 0x90, 0x00], 0);+ expect(probeMedia(cbr)?.duration).toBeCloseTo(1, 6);+ });++ it("says nothing about containers it doesn't read", () => {+ expect(probeMedia(Buffer.from("\x1aE\xdf\xa3 webm header....."))).toBeNull();+ expect(probeMedia(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]))).toBeNull();+ expect(probeMedia(Buffer.alloc(4))).toBeNull();+ });+});diff --git a/workflows/comfyui/captions-burnin.json b/workflows/comfyui/captions-burnin.jsonindex 60624865..666e9e92 100644--- a/workflows/comfyui/captions-burnin.json+++ b/workflows/comfyui/captions-burnin.json@@ -8,16 +8,13 @@"title": "Video to caption"}},- "2": {- "class_type": "GetVideoComponents",+ "3": {+ "class_type": "LoadAudio","inputs": {- "video": [- "1",- 0- ]+ "audio": "input.mp4"},"_meta": {- "title": "Soundtrack + fps of the whole clip"+ "title": "Its soundtrack, laid under the result (dropped for silent clips)"}},"10": {@@ -32,7 +29,7 @@"strict_duration": false},"_meta": {- "title": "Caption segment 1 (the app writes one per cue)"+ "title": "Captioned chunk 1 (the app writes one chunk per cue piece)"}},"11": {@@ -44,7 +41,7 @@]},"_meta": {- "title": "Segment 1 frames"+ "title": "Chunk 1 frames (only this chunk is decoded)"}},"12": {@@ -62,98 +59,73 @@"outline": true},"_meta": {- "title": "Caption style (copied to every cue)"+ "title": "Caption style (copied to every chunk)"}},- "20": {- "class_type": "Video Slice",+ "13": {+ "class_type": "CreateVideo","inputs": {- "video": [- "1",+ "images": [+ "12",0],- "start_time": 0.5,- "duration": 0,- "strict_duration": false+ "fps": [+ "11",+ 2+ ],+ "audio": [+ "11",+ 1+ ],+ "bit_depth": "auto",+ "color_space": "sRGB",+ "codec": "h264"},"_meta": {- "title": "Caption segment 2 (to the end)"+ "title": "Chunk 1 encoded right away (its frames can leave memory)"}},- "21": {- "class_type": "GetVideoComponents",+ "20": {+ "class_type": "Video Slice","inputs": {"video": [- "20",- 0- ]- },- "_meta": {- "title": "Segment 2 frames"- }- },- "22": {- "class_type": "TextOverlay",- "inputs": {- "images": [- "21",+ "1",0],- "text": "burned into the frames",- "font_size": 6,- "color": "#ffffff",- "position": "bottom",- "align": "center",- "outline": true+ "start_time": 0.5,+ "duration": 0,+ "strict_duration": false},"_meta": {- "title": "Caption 2"+ "title": "Gap without a caption (never decoded here)"}},"90": {- "class_type": "BatchImagesNode",+ "class_type": "ConcatenateVideo","inputs": {- "images.image0": [- "12",+ "videos.video0": [+ "13",0],- "images.image1": [- "22",- 0- ]- },- "_meta": {- "title": "Segments in order"- }- },- "91": {- "class_type": "CreateVideo",- "inputs": {- "images": [- "90",+ "videos.video1": [+ "20",0],- "fps": [- "2",- 2- ],- "audio": [- "2",- 1- ],- "bit_depth": "auto",- "color_space": "sRGB",- "codec": "none"+ "codec": "auto",+ "complete_audio": [+ "3",+ 0+ ]},"_meta": {- "title": "Captioned video (source fps + audio)"+ "title": "Chunks and gaps in order, with the clip's soundtrack"}},"92": {"class_type": "SaveVideo","inputs": {"video": [- "91",+ "90",0],"filename_prefix": "fuobe/captions-burnin",diff --git a/workflows/comfyui/captions-qwen3-asr.json b/workflows/comfyui/captions-qwen3-asr.jsonindex dbde7a5d..ac37bff7 100644--- a/workflows/comfyui/captions-qwen3-asr.json+++ b/workflows/comfyui/captions-qwen3-asr.json@@ -21,7 +21,7 @@"forced_aligner": "Qwen/Qwen3-ForcedAligner-0.6B-hf","language": "auto","hints": "",- "output_format": "srt",+ "output_format": "none","output_path": "fuobe/captions","split_mode": "split_by_punctuation_or_pause_or_length","max_gap_sec": 0.6,diff --git a/workflows/comfyui/layers-qwen-image-layered.json b/workflows/comfyui/layers-qwen-image-layered.jsonindex 8a0fa0b3..dd421e9a 100644--- a/workflows/comfyui/layers-qwen-image-layered.json+++ b/workflows/comfyui/layers-qwen-image-layered.json@@ -247,7 +247,7 @@"83:78",1],- "layers": 2,+ "layers": 4,"batch_size": 1},"class_type": "EmptyQwenImageLayeredLatentImage",diff --git a/workflows/comfyui/lipsync-v2v-infinitetalk.json b/workflows/comfyui/lipsync-v2v-infinitetalk.jsonindex 8dd25e86..6a1483bd 100644--- a/workflows/comfyui/lipsync-v2v-infinitetalk.json+++ b/workflows/comfyui/lipsync-v2v-infinitetalk.json@@ -253,11 +253,8 @@"245",0],- "custom_height": [- "246",- 0- ],- "frame_load_cap": 0,+ "custom_height": 0,+ "frame_load_cap": 1000,"skip_first_frames": 0,"select_every_nth": 1,"format": "Wan"diff --git a/workflows/comfyui/manifest.json b/workflows/comfyui/manifest.jsonindex 88d3fc63..16d6914b 100644--- a/workflows/comfyui/manifest.json+++ b/workflows/comfyui/manifest.json@@ -1,6 +1,6 @@{"version": 1,- "generatedAt": "2026-10-17T21:22:08.981Z",+ "generatedAt": "2026-10-18T07:15:22.469Z","comfyuiCommit": "fc04da91b2ab12f99e4716371a7e4f98ac982597","comfyuiVersion": "0.41.0","workflowTemplatesVersion": "0.11.86",@@ -7452,7 +7452,7 @@"defaults": {"steps": 20,"cfg": 2.5,- "numLayers": 2,+ "numLayers": 4,"maxSize": 640},"limits": {@@ -7482,7 +7482,7 @@"vramGb": 24,"license": "Apache-2.0 (Qwen-Image-Layered weights and the Comfy-Org repack)","validated": true,- "notes": "Template image_qwen_image_layered with the fp8mixed weights (bf16 is 40.9 GB). The input is scaled so its longest side = maxSize (640 is the trained bucket; 1024 works, slower). numLayers = how many RGBA layers come out (1-10; the latent holds numLayers+1 slices and slice 0, the reconstructed composite, is cut off by LatentCut). prompt = optional caption of the whole image. SaveImage writes one full-canvas RGBA PNG per layer, back to front: the provider reports them in that order with meta {name, z, bbox} (bbox from the alpha channel). \"Separate layer\" = run again on one layer."+ "notes": "Template image_qwen_image_layered with the fp8mixed weights (bf16 is 40.9 GB). The input is scaled so its longest side = maxSize (640 is the trained bucket; 1024 works, slower). numLayers = how many RGBA layers come out (1-10, default 4 like the model card; the latent holds numLayers+1 slices and slice 0, the reconstructed composite, is cut off by LatentCut). prompt = optional caption of the whole image. SaveImage writes one full-canvas RGBA PNG per layer, back to front: the provider reports them in that order with meta {name, z, bbox} (bbox from the alpha channel). \"Separate layer\" = run again on one layer."},{"id": "layers-qwen-image-layered-control",@@ -7816,7 +7816,7 @@"vramGb": 10,"license": "Apache-2.0 (FLUX.2 [klein] 4B)","validated": true,- "notes": "Template image_flux2_klein_image_edit_4b_distilled with two extra ReferenceLatent references and an explicit output size. All four references are required: the provider repeats the last image when fewer are given. Fast (4 steps, 8-10 GB). Weaker than Qwen-Image-Edit-2511 on complex prompts."+ "notes": "Template image_flux2_klein_image_edit_4b_distilled with two extra ReferenceLatent references and an explicit output size. 1-4 references: the provider bypasses the ReferenceLatent pair of each reference not given (bypassReference). Fast (4 steps, 8-10 GB). Weaker than Qwen-Image-Edit-2511 on complex prompts."},{"id": "style-ref-krea2",@@ -9328,14 +9328,14 @@"vramGb": 4,"license": "Qwen3-ASR / ForcedAligner Apache-2.0; ComfyUI-QwenASR code GPL-3.0","validated": true,- "notes": "Default caption source for Faceless / Shorts. Changed from the research graph: LoadAudio instead of LoadVideo + GetVideoComponents (audio or video input). maxChars 32 + split_by_punctuation_or_pause_or_length gives short vertical-video lines. The text output is one \"start-end: text\" line per cue; the provider parses it into meta.cues. Burn the cues in with captions-burnin (chain: transcript text -> prompt).",+ "notes": "Default caption source for Faceless / Shorts. Changed from the research graph: LoadAudio instead of LoadVideo + GetVideoComponents (audio or video input). maxChars 32 + split_by_punctuation_or_pause_or_length gives short vertical-video lines. The text output is one \"start-end: text\" line per cue; the provider parses it into meta.cues. output_format none: the node writes no file of its own (concurrent jobs would race on one captions.srt); SaveText returns the cues. Burn the cues in with captions-burnin (chain: transcript text -> prompt).","autoDownloads": ["AILab_Qwen3ASRSubtitle downloads Qwen/Qwen3-ASR-0.6B-hf (1.56 GB) and Qwen/Qwen3-ForcedAligner-0.6B-hf (1.84 GB) into models/Qwen3-ASR on first run"]},{"id": "captions-burnin",- "title": "Burn captions into a video (core Draw Text Overlay, one segment per cue)",+ "title": "Burn captions into a video (core Draw Text Overlay, chunk by chunk)","capability": "captions","file": "captions-burnin.json","source": "hand-built (scripts/comfy/hand-built/captions-burnin.json)",@@ -9344,6 +9344,10 @@{"node": "1","input": "file"+ },+ {+ "node": "3",+ "input": "audio"}],"fontSize": [@@ -9388,7 +9392,7 @@"vramGb": 0,"license": "no model (ComfyUI core TextOverlay, GPL-3.0 like ComfyUI; Pillow's bundled Aileron font, OFL)","validated": true,- "notes": "Fuobe's open caption burn-in, all inside ComfyUI with core nodes. The provider rewrites the graph per request: the cues (prompt lines \"start-end: text\" or SRT, e.g. from captions-qwen3-asr) become one Trim Video segment per cue and per gap, each cue segment gets a TextOverlay with the style of node 12 (fontSize = % of the frame height, fontColor, captionPosition top | bottom, outlined), BatchImagesNode joins the segments in order and CreateVideo restores the source fps and soundtrack. The last cue stays up to the end of the clip (a segment may not start after the end). Holds the clip's frames in memory about three times (fine for Shorts up to a minute at 720p). Runs on CPU (verified end to end through Fuobe).",+ "notes": "Fuobe's open caption burn-in, all inside ComfyUI with core nodes. The provider rewrites the graph per request (expandCaptionWorkflow): the cues (prompt lines \"start-end: text\" or SRT, e.g. from captions-qwen3-asr) cut the clip into Trim Video windows. Gaps go straight to Concatenate Video (never decoded). A cue window is cut into chunks of at most ~384 MB of frames (about 0.5 s of 1080x1920 at 30 fps, 5 s at 360p); each chunk is decoded (GetVideoComponents), gets a TextOverlay in the style of node 12 (fontSize = % of the frame height, fontColor, captionPosition top | bottom, outlined) and is encoded at once (CreateVideo codec h264), so ComfyUI only needs one chunk of raw frames at a time and can evict finished chunks under memory pressure. Concatenate Video joins chunks and gaps in order and lays the clip's own soundtrack (LoadAudio, node 3) under the result; for a silent clip node 3 is dropped. The provider reads the upload's MP4 header for duration, fps, size and audio: window edges sit between frames, cues past the end are dropped and the rest of the clip after the last cue stays uncaptioned. Windows hold at least 3 frames (Concatenate Video rejects a 2-frame clip followed by another): a shorter pause between cues gets no gap, a shorter caption is held for 3 frames. Measured on the CPU server under RAM pressure (--cache-ram 11): a 20 s 640x360 30 fps clip with 18 s of captions peaks at +0.50 GB RSS and a 40 s one at +0.45 GB (the old one-batch graph: +5.16 GB for the 20 s clip); without pressure ComfyUI's RAM cache keeps finished chunks (+2.64 GB for 20 s) until memory runs low. Runs on CPU (verified end to end through Fuobe).","expand": "captions"},{@@ -9471,7 +9475,7 @@"vramGb": 6,"license": "Whisper weights MIT (OpenAI); ComfyUI-Whisper code CC-BY-NC-SA-4.0 (NON-COMMERCIAL: the author asks to be contacted for commercial use)","validated": true,- "notes": "All-ComfyUI alternative that transcribes and burns in one job (word-by-word captions from words_alignment). One style per run (font, size, colour, border, centred). Because of the NC code licence the default open route is captions-qwen3-asr + captions-burnin. Save SRT (not an output node) is dropped; the transcript text is kept.",+ "notes": "All-ComfyUI alternative that transcribes and burns in one job (word-by-word captions from words_alignment). One style per run (font, size, colour, border, centred). Because of the NC code licence the default open route is captions-qwen3-asr + captions-burnin, and install-comfyui.sh only installs ComfyUI-Whisper with NC_PACKS=1. Save SRT (not an output node) is dropped; the transcript text is kept. VHS_LoadVideo decodes the whole clip and Add Subtitles To Frames copies it (about 2.5 copies of the frames in RAM): the provider refuses clips that would need more than half of the ComfyUI server's RAM and points to the chunked route. sourceLanguage takes Whisper's own names (the provider maps ISO codes: tl/fil -> Tagalog, he -> Hebrew).","autoDownloads": ["Apply Whisper downloads large-v3-turbo.pt (1.62 GB) into models/stt/whisper on first run"]@@ -9649,6 +9653,10 @@{"node": "270","input": "value"+ },+ {+ "node": "228",+ "input": "frame_load_cap"}],"seed": [@@ -9694,12 +9702,14 @@"frames": 1000,"steps": 4,"startStep": 2,- "audioScale": 1.5+ "audioScale": 1.5,+ "fps": 25},"limits": {"maxWidth": 1280,"maxHeight": 1280,- "dimensionMultiple": 16+ "dimensionMultiple": 16,+ "maxFrames": 1000},"models": [{@@ -9756,7 +9766,7 @@"vramGb": 24,"license": "Apache-2.0 (Wan 2.1, InfiniteTalk, lightx2v)","validated": true,- "notes": "Same model files as infinitetalk-wanwrapper (no new download). The source frames are VAE-encoded and only the last steps are re-denoised (steps 4, startStep 2), so camera, background and body stay; mouth, head and upper body follow the new audio. 81-frame windows until the audio ends (frames = cap @25 fps). Pass the clean dubbed voice, then mux the background with video-mux-audio.",+ "notes": "Same model files as infinitetalk-wanwrapper (no new download). The source frames are VAE-encoded and only the last steps are re-denoised (steps 4, startStep 2), so camera, background and body stay; mouth, head and upper body follow the new audio. 81-frame windows until the audio ends. Changed from the research graph: VHS_LoadVideo gets only custom_width (height 0 keeps the source's proportions, no squashing) and ImageResizeKJv2 crops to width x height, which the provider takes from the source's own shape (aspect ratio \"auto\", read from the MP4 header) at the chosen resolution; frames (num_frames and VHS frame_load_cap) = the voice's length at 25 fps, at most 1000 (40 s): the provider refuses a longer voice instead of cutting it. Pass the clean dubbed voice, then mux the background with video-mux-audio.","autoDownloads": ["DownloadAndLoadWav2VecModel fetches TencentGameMate/chinese-wav2vec2-base (0.38 GB) on first run"]@@ -9845,7 +9855,7 @@},{"id": "video-mux-audio",- "title": "Add a soundtrack: new voice + background stem mixed onto a video",+ "title": "Add a soundtrack: new voice + background stem mixed onto a video (picture stream-copied)","capability": "mux","file": "video-mux-audio.json","source": "hand-built (scripts/comfy/hand-built/video-mux-audio.json)",@@ -9874,6 +9884,12 @@"input": "volume"}],+ "duration": [+ {+ "node": "9",+ "input": "duration"+ }+ ],"filenamePrefix": [{"node": "8",@@ -9888,6 +9904,7 @@}],"defaults": {+ "duration": 60,"backgroundVolumeDb": 0},"limits": {},@@ -9896,7 +9913,7 @@"vramGb": 0,"license": "n/a (no model)","validated": true,- "notes": "audio = the new voice (Chatterbox dub, narration), audio2 = the background stem of dub-prepare-separate-transcribe or a music bed (backgroundVolumeDb, e.g. -12 under narration). AudioMerge resamples to the higher rate and pads the shorter clip. Video length is unchanged. Without audio2 the provider uses video-mux-audio-replace. Runs on CPU (verified end to end through Fuobe)."+ "notes": "audio = the new voice (Chatterbox dub, narration), audio2 = the background stem of dub-prepare-separate-transcribe or a music bed (backgroundVolumeDb, e.g. -12 under narration). Both are mixed over EmptyAudio of the video's length (duration: the provider reads it from the MP4 header), because AudioMerge cuts audio2 to audio1's length. Concatenate Video with complete_audio copies the video stream packet by packet (no decode, no re-encode: lossless, constant memory) and encodes only the new AAC soundtrack. Video length is unchanged. Without audio2 the provider uses video-mux-audio-replace. Runs on CPU (verified end to end through Fuobe; +0.02 GB RAM for a 900-frame clip)."},{"id": "video-mux-audio-replace",@@ -9937,7 +9954,7 @@"vramGb": 0,"license": "n/a (no model)","validated": true,- "notes": "LoadVideo -> GetVideoComponents (frames, fps) + LoadAudio -> CreateVideo -> SaveVideo. The single-track variant of video-mux-audio (voice-over, narration, music). Runs on CPU (verified end to end through Fuobe)."+ "notes": "LoadVideo + LoadAudio -> Concatenate Video (complete_audio) -> SaveVideo: the picture is stream-copied, only the new soundtrack is encoded. The single-track variant of video-mux-audio (voice-over, narration, music). A soundtrack longer than the video is cut at the video's end. Runs on CPU (verified end to end through Fuobe)."},{"id": "image-to-3d-trellis2",@@ -10220,7 +10237,7 @@"vramGb": 10,"license": "Apache-2.0 (FLUX.2 [klein] 4B, try-on LoRA by xocialize); segformer_b2_clothes MIT; ComfyUI-RMBG code GPL-3.0","validated": true,- "notes": "Reference order is load-bearing (LoRA card): image = person, image2 = top, image3 = bottom; for a dress the provider passes image2 again as image3. The LoRA was trained on clothing-agnostic inputs, so ClothesSegment greys the old outfit out first. Trigger word TRYON (defaults.promptPrefix: the provider puts it at the start of the prompt). Output size = the person image (~1 MP).",+ "notes": "Reference order is load-bearing (LoRA card): image = person, image2 = top (or a dress / whole outfit), image3 = bottom. image2 is required; without image3 the provider bypasses the bottom's ReferenceLatent pair (one garment reference) instead of passing the top as the bottom. The LoRA was trained on clothing-agnostic inputs, so ClothesSegment greys the old outfit out first. Trigger word TRYON (defaults.promptPrefix: the provider puts it at the start of the prompt). Output size = the person image (~1 MP).","autoDownloads": ["ClothesSegment (ComfyUI-RMBG) downloads segformer_b2_clothes (0.11 GB) into models/RMBG/segformer_clothes on first run"]diff --git a/workflows/comfyui/video-mux-audio-replace.json b/workflows/comfyui/video-mux-audio-replace.jsonindex ccd79f31..d3eb469f 100644--- a/workflows/comfyui/video-mux-audio-replace.json+++ b/workflows/comfyui/video-mux-audio-replace.json@@ -5,19 +5,7 @@"file": "input.mp4"},"_meta": {- "title": "Video"- }- },- "2": {- "class_type": "GetVideoComponents",- "inputs": {- "video": [- "1",- 0- ]- },- "_meta": {- "title": "Frames + fps"+ "title": "Video (its picture is copied, never decoded)"}},"3": {@@ -30,26 +18,20 @@}},"7": {- "class_type": "CreateVideo",+ "class_type": "ConcatenateVideo","inputs": {- "images": [- "2",+ "videos.video0": [+ "1",0],- "fps": [- "2",- 2- ],- "audio": [+ "codec": "auto",+ "complete_audio": ["3",0- ],- "bit_depth": "auto",- "color_space": "sRGB",- "codec": "none"+ ]},"_meta": {- "title": "Video with the new soundtrack"+ "title": "Same picture, new soundtrack (stream copy)"}},"8": {diff --git a/workflows/comfyui/video-mux-audio.json b/workflows/comfyui/video-mux-audio.jsonindex 5ec7864a..ea79b1e3 100644--- a/workflows/comfyui/video-mux-audio.json+++ b/workflows/comfyui/video-mux-audio.json@@ -5,19 +5,7 @@"file": "input.mp4"},"_meta": {- "title": "LoadVideo"- }- },- "2": {- "class_type": "GetVideoComponents",- "inputs": {- "video": [- "1",- 0- ]- },- "_meta": {- "title": "GetVideoComponents"+ "title": "Video (its picture is copied, never decoded)"}},"3": {@@ -26,7 +14,7 @@"audio": "dub_voice.mp3"},"_meta": {- "title": "LoadAudio"+ "title": "New voice (audio)"}},"4": {@@ -35,7 +23,7 @@"audio": "background.mp3"},"_meta": {- "title": "LoadAudio"+ "title": "Background stem or music bed (audio2)"}},"5": {@@ -48,47 +36,41 @@"volume": 0},"_meta": {- "title": "AudioAdjustVolume"+ "title": "Background level (dB)"}},"6": {"class_type": "AudioMerge","inputs": {"audio1": [- "3",+ "10",0],"audio2": [- "5",+ "3",0],"merge_method": "add"},"_meta": {- "title": "AudioMerge"+ "title": "Voice over the background"}},"7": {- "class_type": "CreateVideo",+ "class_type": "ConcatenateVideo","inputs": {- "images": [- "2",+ "videos.video0": [+ "1",0],- "fps": [- "2",- 2- ],- "audio": [+ "codec": "auto",+ "complete_audio": ["6",0- ],- "bit_depth": "auto",- "color_space": "sRGB",- "codec": "none"+ ]},"_meta": {- "title": "CreateVideo"+ "title": "Same picture, new soundtrack (stream copy)"}},"8": {@@ -104,7 +86,35 @@"codec": "auto"},"_meta": {- "title": "SaveVideo"+ "title": "Save video"+ }+ },+ "9": {+ "class_type": "EmptyAudio",+ "inputs": {+ "duration": 60,+ "sample_rate": 44100,+ "channels": 2+ },+ "_meta": {+ "title": "Soundtrack length (the video's)"+ }+ },+ "10": {+ "class_type": "AudioMerge",+ "inputs": {+ "audio1": [+ "9",+ 0+ ],+ "audio2": [+ "5",+ 0+ ],+ "merge_method": "add"+ },+ "_meta": {+ "title": "Background over silence"}}}