Swooftee commited on
Commit
4781932
·
verified ·
1 Parent(s): cb8137f

Upload 10 files

Browse files
Comfyui delay tool/README.md ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUI GIF Delay Tools
2
+
3
+ Delay-aware GIF loading, interpolation and saving.
4
+
5
+ Install: copy this folder to `ComfyUI/custom_nodes/` and restart. Needs `ffmpeg` in PATH
6
+ (or set `FFMPEG_PATH`; `imageio-ffmpeg` is also detected). Without it the saver falls back to Pillow.
7
+
8
+ ## Nodes (category `image/GIF Delay Tools`)
9
+ | Node | Purpose |
10
+ |---|---|
11
+ | GIF Load (with delays) | frames, per-frame delays (ms, `GIF_DELAYS`), `gif_info` (STRING) |
12
+ | GIF Save (delays + FFmpeg palette) | writes the exact delays; outputs delays, `gif_info` (STRING), file path |
13
+ | GIF Plan Interpolation | RIFE multiplier so the result stays <= target fps (50) |
14
+ | GIF Loop Pair | `[last, first]` batch to interpolate for the seamless loop |
15
+ | GIF Batch Interpolate (low-memory RIFE) | drop-in replacement for ComfyUI's `FrameInterpolate`; processes in batches with float16 accumulation to avoid OOM on large GIFs |
16
+ | GIF Delay-Aware Interpolation | rebuilds frames + delays after `FrameInterpolate`; outputs multiplier (INT), `gif_info` (STRING) |
17
+ | GIF Deduplicate (merge delays) | removes consecutive identical frames, adds their delays; outputs removed_frames, `gif_info` (STRING), summary |
18
+ | GIF Delays Info / From FPS | helpers |
19
+
20
+ ## Timing (GIF Delay-Aware Interpolation)
21
+
22
+ Settings that control the timing behaviour (all of them are explained in detail in `SETTINGS_GUIDE.txt`,
23
+ which is also the text of the Note node in the bundled workflow):
24
+ - **deduce_from_original** (3 options, default `deduce`):
25
+ - `deduce`: new frames' time is deducted from the original frame's delay.
26
+ - `deduce - not held frame`: like `deduce`, but frames whose delay is `held_frame_factor` x the average or more ("held" frames) keep
27
+ their full delay. They are still interpolated; all their new frames are added on top (the gif gets longer).
28
+ - `don't deduce`: originals keep their full delay (gif grows).
29
+ (Workflows saved with the old ON/OFF switch must re-select this option once.)
30
+ - **held_frame_factor** (slider 1.1-10, default 2.0): how many times the average delay a frame needs to count as "held". Used by `deduce - not held frame` and by the hold cap of `smart_delays`.
31
+ - **force_custom_multiplier** (fused node and GIF Batch Interpolate, 0-16): 0 = off (the `multiplier` input is used). 1 = forces x1: no interpolation at all (the model is not even loaded), the original frames are kept and only the timing settings apply - use it to just change the speed or convert to WebP/GIF. 2-16 forces that multiplier and ignores the `multiplier` input. Other settings are respected; `allow_longer` is switched ON while forcing x2 or more (except in `uniform_delays`), because OFF would drop frames and the forced multiplier could not be honoured. **Workflows saved with the old "1 = off" value now force x1: set the slider to 0.**
32
+ - **allow_longer** (default ON): all interpolated frames are kept, gif may get longer. OFF = preserve original duration; frames that don't fit are dropped.
33
+
34
+ Three timing modes:
35
+ | mode | description |
36
+ |---|---|
37
+ | `keep_original_delays` | Original frames keep their own delays (or lose time to new frames if deduce ON). New frames get `interp_delay_ms`. Affected by both toggles. |
38
+ | `uniform_delays` | Every frame gets the same delay. Not affected by deduce, except for the loop transition. If allow_longer OFF, the uniform delay is computed so the original total duration is kept (with deduce ON the loop transition frames share that budget, otherwise they are added on top). |
39
+ | `smart_delays` | New frames glide at a pace derived from the original frame's delay (`d/(k+1)`). Frames longer than `held_frame_factor` × the average (2× by default) are treated as "holds" — their new frames glide at a capped pace (`factor*avg/(k+1)`). Affected by both toggles. |
40
+
41
+ **Loop transition** (when `looping` is ON): follows the same rules as every other frame pair. With `deduce_from_original` ON its time is taken out of the LAST frame's delay (and with `allow_longer` OFF only the frames that fit are kept). With `deduce_from_original` OFF the transition frames are always kept and added on top of the original duration, so the gif gets a bit longer.
42
+
43
+ `interp_delay_ms`: delay of the interpolated frames (0 = fastest allowed by `max_fps`, 20 ms at 50 fps). Only used by `keep_original_delays` and `uniform_delays` (when allow_longer ON).
44
+
45
+ **Outputs**: `multiplier` (INT) = the inferred interpolation factor (x2/x4/…), `gif_info` (STRING) = total duration, frame count, average fps, and delay list.
46
+
47
+ ### Old → new mapping
48
+ | old mode | new equivalent |
49
+ |---|---|
50
+ | `hold_original` | `keep_original_delays` + deduce ON + allow_longer OFF |
51
+ | `hold_original_plus` | `keep_original_delays` + deduce ON + allow_longer ON |
52
+ | `keep_original_delays` (old) | `keep_original_delays` + deduce OFF + allow_longer ON |
53
+ | `uniform_delay` | `uniform_delays` + allow_longer ON |
54
+ | `split_evenly` | `smart_delays` + deduce ON + allow_longer OFF (non-hold frames) |
55
+ | `smart` | `smart_delays` + deduce OFF |
56
+ | `smart_deduce` | `smart_delays` + deduce ON + allow_longer ON |
57
+
58
+ ## gif_info output format
59
+ All four main nodes (Load, Deduplicate, Interpolation, Save) expose a `gif_info` STRING output:
60
+ ```
61
+ total duration : 200ms
62
+ Number of frames : 10
63
+ Average fps : 50
64
+
65
+ Delay list :
66
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
67
+ ```
68
+
69
+ ## GIF Batch Interpolate (low-memory RIFE)
70
+ Drop-in replacement for ComfyUI's built-in `FrameInterpolate` node.
71
+
72
+ **Why:** `FrameInterpolate` pre-allocates a single output tensor for ALL interpolated frames at once. For a 72-frame × 2900×2900px GIF at multiplier 8, that's ~57 GB — and it OOMs even with 64 GB RAM.
73
+
74
+ **How it works:**
75
+ - Accumulates results in **float16** (halves peak: 57.4 GB → ~28.7 GB)
76
+ - Processes frame pairs in blocks of `batch_size` (default 10), clearing GPU caches between blocks
77
+ - Same API: takes `interp_model`, `images`, `multiplier`; outputs `IMAGE`
78
+ - Extra optional input: `batch_size` (1–1000, default 10) — lower = less peak memory
79
+ - Graceful OOM fallback (reduces internal timestep batch, same as the original)
80
+
81
+ **When to use:** Replace every `FrameInterpolate` node with `GIF Batch Interpolate` when your GIF is large enough to OOM the original. For small GIFs either works identically.
82
+
83
+ ## GIF Plan Interpolation: reference
84
+ `average_fps`, `median_delay`, `minimum_fps` (slowest part of the gif, longest delay, bigger multiplier),
85
+ `maximum_fps` (fastest part, shortest delay, smaller multiplier so nothing exceeds the target).
86
+
87
+ ## Quality
88
+ Per-frame palette (`palettegen stats_mode=single` + `paletteuse new=1`, no reserved transparency =
89
+ 256 real colours). Error-diffusion dithers leave frames with <= 256 colours unchanged.
90
+ Delays are written directly into the GIF (centiseconds, error-diffused), not via FFmpeg timestamps.
91
+ `optimize_size` gives smaller files but is not lossless.
92
+
93
+ ## Looping toggle
94
+ `GIF Delay-Aware Interpolation` has a `looping` switch. ON inserts the interpolated last -> first
95
+ transition (seamless loop); OFF ignores it, for non-looping gifs. (When OFF you can also bypass the
96
+ Loop Pair + its FrameInterpolate node to save time. `loop_count` on the saver controls playback looping.)
97
+
98
+ ## Deduplicate
99
+ Place it right after the loader, before interpolation. Only CONSECUTIVE duplicates are merged, kept
100
+ frames are the untouched originals, total duration is unchanged. Threshold 0 = exact duplicates only
101
+ (lossless); `strict_max_difference` never merges a frame with a visible local change.
102
+
103
+ ## Output format: GIF or WebP
104
+ The save node has an `output_format` switch (gif / webp).
105
+ - **webp**: full colour (no 256-colour limit), millisecond delays, can be truly lossless
106
+ (`webp_lossless` ON, default). `quality` = image quality when lossy, compression effort when
107
+ lossless. `webp_method` 0-6 = encoder effort (6 = slowest, smallest). `max_fps` still applies.
108
+ - The GIF-only settings (`palette_mode`, `dither`, `max_colors`, `optimize_size`, `backend`) are ignored for WebP.
109
+ - **quality** (0-100, default 90) also applies to GIF: 90-100 = the full `max_colors` palette, below 90 the palette shrinks linearly (about 129 colours at 45, 2 at 0) for smaller files and more banding. (The widget used to be called `webp_quality`.)
110
+ - `loop_count` works for both (0 = forever, -1 = play once).
111
+ - Lossless WebP files are usually bigger than GIFs for noisy content; lossy WebP is much smaller.
112
+ - `batch_size` (default 100, 1–1000): encodes frames in chunks to keep peak memory bounded. Important for large animations — especially WebP and Pillow-GIF, which otherwise materialise all frames at once. Lower = less RAM, slightly slower; 50–100 is a good default.
113
+
114
+ ### Maximum file size (`max_size_mb`)
115
+
116
+ Set `max_size_mb` on the save node (0 = off) and the quality is chosen for you: the size is
117
+ estimated from a sample of the frames, the best setting estimated to fit is picked, the file is
118
+ written and its real size verified (corrected and re-written if needed, 3 passes at most; the
119
+ console shows estimate vs real size). WebP: lossless is kept when it fits, otherwise lossy at the
120
+ highest quality that fits (`quality` is the upper limit). GIF: the smallest possible palette
121
+ reduction (`quality` / `max_colors` are the upper limit). If even the lowest setting is too big the
122
+ smallest file is saved and a warning is printed. The new `file_info` output gives the real size and
123
+ the setting used.
124
+
125
+ ## Low-RAM pipeline: "GIF Delay-Aware Interpolate (fused, lowest RAM)"
126
+
127
+ The classic chain (GIF Batch Interpolate -> GIF Delay-Aware Interpolation) first builds EVERY
128
+ in-between frame (originals x multiplier) and only then drops the ones that do not fit the
129
+ timing. For big frames this needs gigabytes of RAM for frames that are thrown away.
130
+
131
+ The fused node plans the timeline first and asks RIFE only for the frames that end up in the
132
+ final gif, including the seamless-loop transition (no GIF Loop Pair needed).
133
+
134
+ Wiring: GIF Load -> GIF Deduplicate -> **GIF Delay-Aware Interpolate (fused)** -> GIF Save
135
+ (model from the interpolation model loader; `multiplier` can come from GIF Plan Interpolation).
136
+
137
+ RAM = final frame count x frame size (float16 by default). Rule of thumb for the final gif:
138
+ `duration / (1000 / max_fps)` frames. Lower `max_fps` or the resolution if that is still too much.
139
+
140
+ ### Using VRAM instead of RAM
141
+
142
+ - **output_device** (fused node and GIF Batch Interpolate, `auto` / `ram` / `vram`): where the big
143
+ output batch lives. `auto` (default) keeps it in VRAM when it fits with head-room (checked after
144
+ the model is loaded), otherwise in RAM. `vram` forces the GPU (falls back to RAM if it does not
145
+ fit), `ram` is the old behaviour. The batch stays in VRAM while ComfyUI keeps the node's result,
146
+ so use `ram` if later nodes run out of VRAM. With a forced x1 nothing is interpolated and the copy
147
+ stays in RAM.
148
+ - **frame_storage** (GIF Load, optional, last setting): `ram_float32` (default, ComfyUI standard),
149
+ `ram_float16` (half the RAM, 8-bit values stay exact) or `vram_float16` (frames on the GPU,
150
+ almost no RAM). Frames are now converted chunk by chunk, which also lowers the RAM peak while
151
+ loading. Falls back to RAM if the VRAM is full.
152
+ - GIF Deduplicate no longer copies the batch when nothing is removed.
153
+
154
+ ## Batch loading a folder (GIF Load)
155
+
156
+ Put a folder path in `custom_path` (instead of a file): the dropdown is ignored and each run loads the NEXT
157
+ .gif/.webp of that folder (natural order, wraps to the first file after the last). `folder_start_index` restarts
158
+ the sequence at a given file. A new `filename` output gives the loaded file's name (without extension).
Comfyui delay tool/SETTINGS_GUIDE.txt ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GIF DELAY TOOLS - EVERY SETTING EXPLAINED
2
+ =========================================
3
+
4
+ RECOMMENDED CHAIN (lowest RAM)
5
+ GIF Load -> GIF Deduplicate -> GIF Delay-Aware Interpolate (fused) -> GIF Save
6
+ (model from Frame Interpolation Model Loader; GIF Plan Interpolation can feed "multiplier")
7
+ CLASSIC CHAIN (still works)
8
+ GIF Load -> GIF Deduplicate -> GIF Batch Interpolate (frames) + GIF Loop Pair -> GIF Batch Interpolate (loop pair)
9
+ -> GIF Delay-Aware Interpolation (+ loop_interpolated) -> GIF Save
10
+ Delays are always in milliseconds. A GIF stores delays in 10 ms steps (centiseconds); the rounding error is
11
+ spread over the frames so the total duration stays accurate.
12
+
13
+
14
+ === GIF LOAD (with delays) ===
15
+ gif ............................ file from the ComfyUI input folder (.gif or .webp). Use "upload" to add one.
16
+ custom_path (optional) ......... empty: the gif/webp chosen in "gif" is loaded (the one you uploaded or picked).
17
+ path to a FILE: that file is loaded, the dropdown is ignored.
18
+ path to a FOLDER: FOLDER MODE. The dropdown is ignored and the .gif/.webp files of
19
+ the folder are loaded one by one, ONE PER RUN: 1st click on Run = 1st file, 2nd click
20
+ = 2nd file, and so on (natural order: gif2 before gif10; sub-folders are not read).
21
+ After the last file it starts again from the first. "Run (N)" / batch count works
22
+ too. The node always re-runs in folder mode, so everything after it re-runs as well.
23
+ folder_start_index ............. folder mode only: the file the sequence starts at (0 = first file). Change the value
24
+ to restart the sequence from that file. It also restarts when the folder path
25
+ changes or ComfyUI is restarted. Each Load node has its own counter.
26
+ frame_storage (optional) .... where the loaded frames are kept. ram_float32 = ComfyUI standard (most RAM).
27
+ ram_float16 = half the RAM, the 8-bit values stay exact. vram_float16 = the frames live
28
+ on the GPU: almost no RAM is used, but they take as much VRAM as ram_float16 takes RAM
29
+ for as long as ComfyUI keeps this node's result. Falls back to RAM if the VRAM is full.
30
+ (The frames are also converted chunk by chunk now, which lowers the RAM peak while loading.)
31
+ transparent_background ......... colour that transparent pixels are painted on (black / white / gray / green).
32
+ Frames are loaded as plain RGB, so transparency is lost.
33
+ fix_browser_min_delay .......... ON: a GIF frame with a delay of 0 or 1 cs (0-10 ms) is treated as 100 ms, the way
34
+ browsers play it (WebP: only a 0 ms delay). OFF: use the raw value.
35
+ skip_first_frames .............. drop the first N frames. Their delay is dropped too.
36
+ select_every_nth ............... keep every Nth frame (1 = all). The delays of the skipped frames are ADDED to the
37
+ kept frame, so the animation keeps its duration (it just gets choppier).
38
+ frame_load_cap ................. maximum number of frames to keep (0 = no limit). Counted after skip / every_nth.
39
+ Outputs: images, delays, gif_info (duration, frame count, average fps, delay list; in folder mode the first line
40
+ is "file 3/12: name.gif"), filename (name of the loaded file without extension: handy for naming the saved result
41
+ when you process a folder).
42
+
43
+
44
+ === GIF DEDUPLICATE (merge delays) ===
45
+ Merges CONSECUTIVE identical frames into one and adds their delays together. The kept frames are untouched
46
+ originals and the total duration does not change. Put it right after the loader.
47
+ similarity_threshold ........... 0 = only exactly identical frames (lossless). Otherwise the largest allowed
48
+ difference, in colour levels (0-255), for two frames to count as the same.
49
+ comparison_mode ................ strict_max_difference: NO single pixel may differ by more than the threshold
50
+ (never hides a small visible change). mean_difference: compares the average
51
+ difference over the whole frame (can hide small local changes).
52
+ compare_against ................ previous_frame: compare with the frame just before. group_first_frame: compare
53
+ with the first frame of the current group (stops slow drift from being merged away).
54
+ Outputs: images, delays, removed_frames (count), gif_info, summary.
55
+ If nothing is removed the input batch is passed through without a copy.
56
+
57
+
58
+ === GIF PLAN INTERPOLATION ===
59
+ Computes the interpolation multiplier so the result does not go above a target fps.
60
+ multiplier = floor(target_fps / source_fps), limited to 1..max_multiplier.
61
+ target_fps ..................... the fps you do not want to exceed (default 50 = fastest speed browsers play reliably).
62
+ reference ...................... which speed of the source decides source_fps:
63
+ average_fps = overall average | median_delay = the typical frame |
64
+ minimum_fps = the SLOWEST part (longest delay) -> bigger multiplier |
65
+ maximum_fps = the FASTEST part (shortest delay) -> smaller multiplier.
66
+ max_multiplier ................. upper limit (default 16).
67
+ Outputs: multiplier, source_fps, resulting_fps (= source_fps x multiplier).
68
+
69
+
70
+ === GIF DELAY-AWARE INTERPOLATE (fused, lowest RAM) ===
71
+ Does RIFE/FILM interpolation AND the timing in one step. It plans the final timeline first and only creates the
72
+ frames that really end up in the GIF, so RAM depends on the FINAL frame count, not on originals x multiplier.
73
+ The seamless-loop transition (last -> first frame) is computed here too: no GIF Loop Pair needed.
74
+ Inputs: interp_model, images (the original frames), original_delays.
75
+ multiplier ..................... frames per original frame (x2, x4...). Can be wired from GIF Plan Interpolation.
76
+ A high value costs time only for frames that are kept.
77
+ timing_mode .................... see TIMING MODES below.
78
+ deduce_from_original ........... see DEDUCE below.
79
+ allow_longer ................... see ALLOW_LONGER below.
80
+ max_fps ........................ speed limit. The smallest delay allowed is ceil(100 / max_fps) cs: 50 fps = 20 ms.
81
+ interp_delay_ms ................ delay given to new frames (0 = the smallest allowed by max_fps). Used by
82
+ keep_original_delays (new frames) and uniform_delays (all frames, when allow_longer
83
+ is ON). Ignored by smart_delays.
84
+ looping ........................ ON: insert interpolated frames between the LAST and the FIRST frame so the loop is
85
+ seamless. OFF: no transition (for gifs that do not loop).
86
+ output_dtype ................... float16 (default) uses half the RAM of float32. No visible difference for GIF/WebP.
87
+ clear_cache_every .............. free GPU caches every N frame pairs (0 = never). Lower = less VRAM, slightly slower.
88
+ held_frame_factor .............. slider 1.1 - 10 (default 2.0). A frame is "held" when its delay is at least this many
89
+ times the AVERAGE delay of the gif (2.0 = twice the average). It decides which frames
90
+ count as held for "deduce - not held frame" AND for the hold cap of smart_delays.
91
+ Lower = more frames count as held. Example: average 200 ms -> 2.0 means 400 ms or more,
92
+ 1.5 means 300 ms or more, 4.0 means 800 ms or more.
93
+ force_custom_multiplier ........ slider 0 - 16 (the last of the main settings). 0 = off (the multiplier input is
94
+ used). 1 = FORCE x1: NO interpolation at all (the model is not even loaded). The original
95
+ frames are kept and only the timing settings (timing_mode, max_fps, interp_delay_ms...)
96
+ are applied: use it to just change the speed or convert to WebP/GIF.
97
+ 2 - 16 = FORCE that multiplier and ignore the multiplier input (for example the
98
+ one coming from GIF Plan Interpolation). Every other setting is respected, except
99
+ allow_longer: with it OFF, new frames that do not fit would be dropped, so the forced
100
+ multiplier could not be honoured - it is switched ON while forcing x2 or more (the
101
+ console prints a line when this happens). uniform_delays is not affected (it shortens
102
+ the delay instead of dropping frames), and neither is x1 (there are no new frames).
103
+ Things that cannot be avoided are still clamped: the delay of a frame never goes below
104
+ the minimum of max_fps, so the gif can end up longer.
105
+ NOTE: older workflows saved with the old "1 = off" value now force x1: set it to 0.
106
+ output_device (optional) .... where the OUTPUT batch lives (it is the big one). auto (default) = in VRAM when it fits
107
+ with head-room, otherwise in RAM (the model is loaded first, so the free VRAM is known).
108
+ ram = always RAM. vram = always the GPU (falls back to RAM if it does not fit). It stays
109
+ in VRAM for as long as ComfyUI keeps the result: choose ram if later nodes run out of VRAM.
110
+ With a forced x1 nothing is interpolated and the copy stays in RAM.
111
+ Outputs: images, delays, multiplier (text), gif_info. Wire BOTH images and delays into GIF Save.
112
+
113
+
114
+ === TIMING MODES (timing_mode) ===
115
+ keep_original_delays
116
+ Original frames keep their own delays (minus time given to new frames when deduce is on).
117
+ Every new frame gets interp_delay_ms (20 ms at 50 fps).
118
+ uniform_delays
119
+ EVERY frame, old and new, gets the same delay -> constant speed. With allow_longer ON that delay is
120
+ interp_delay_ms. With allow_longer OFF it is chosen so the GIF keeps its original duration. The deduce setting
121
+ is ignored, except for the loop transition (with a deduce option it shares the original duration, with
122
+ "don't deduce" it is added on top).
123
+ smart_delays
124
+ New frames glide at the pace of the original frame they follow: k new frames share that frame's delay d, each
125
+ getting d / (k + 1) (never less than the minimum delay). A frame whose delay is above held_frame_factor x the
126
+ average (2x by default) is a "hold": its new frames glide at the capped pace held_frame_factor x average / (k + 1),
127
+ so a long pause does not become a slow transition. interp_delay_ms is ignored.
128
+
129
+
130
+ === DEDUCE (deduce_from_original) ===
131
+ deduce
132
+ The time of the new frames is taken OUT of the original frame's delay (the original frame gets shorter, never
133
+ below the minimum delay). Example: 100 ms frame + 3 new frames of 20 ms -> original 40 ms, total still 100 ms.
134
+ deduce - not held frame
135
+ Same as "deduce", EXCEPT for held frames: frames whose delay is held_frame_factor x the average delay or MORE
136
+ (2x by default, adjustable with the held_frame_factor slider). A held frame keeps
137
+ its full delay, but it is still interpolated as usual: all its new frames are kept and added ON TOP, so the GIF
138
+ gets longer by the time of those frames. (allow_longer does not apply to held frames.)
139
+ Example: delays 100, 100, 100, 500 (average 200, so 500 is held), x4, keep_original_delays:
140
+ normal frames -> 40 + 20 + 20 + 20 (duration kept), held frame -> 500 + 20 + 20 + 20 (60 ms longer).
141
+ don't deduce
142
+ Original frames always keep their full delay and the new frames are added on top: the GIF gets longer.
143
+ (keep_original_delays + allow_longer OFF cannot add anything without changing the duration, so new frames are
144
+ dropped there. smart_delays keeps them on top.)
145
+ The loop transition belongs to the LAST frame: with a deduce option its time comes out of the last frame's delay
146
+ (unless the last frame is held); with "don't deduce" it is added on top.
147
+
148
+
149
+ === ALLOW_LONGER ===
150
+ ON - every new frame is kept, the GIF may get longer than the original.
151
+ OFF - each frame keeps its original duration: only as many new frames as fit are kept, evenly spread.
152
+ Only relevant when a deduce option is used (held frames of "deduce - not held frame" are always kept in full).
153
+
154
+
155
+ === GIF LOOP PAIR / GIF BATCH INTERPOLATE / GIF DELAY-AWARE INTERPOLATION (classic chain) ===
156
+ GIF Loop Pair: outputs the batch [last frame, first frame]. Interpolate it with the same multiplier as the frames.
157
+ GIF Batch Interpolate (low-memory):
158
+ multiplier ................... frames per original (minimum 2). Must be the SAME for frames and loop pair.
159
+ batch_size ................... frame pairs processed before GPU caches are cleared. Lower = less VRAM.
160
+ force_custom_multiplier ...... slider 0 - 16 (last setting). 0 = off. 1 = force x1 (no interpolation, the frames are
161
+ returned untouched). 2 - 16 = use this multiplier instead of the
162
+ multiplier input. Use the SAME value on the node that interpolates the [last, first]
163
+ pair, and keep allow_longer ON in GIF Delay-Aware Interpolation, otherwise it drops
164
+ the frames that do not fit.
165
+ output_device (optional) ..... auto / ram / vram, same meaning as in the fused node (where the output batch lives).
166
+ Creates EVERY in-between frame in float16 RAM; the fused node needs far less RAM.
167
+ GIF Delay-Aware Interpolation: same timing settings as the fused node (timing_mode, deduce_from_original,
168
+ allow_longer, max_fps, interp_delay_ms, looping, held_frame_factor). Extra inputs: interpolated_images must contain
169
+ (N-1) x multiplier + 1 frames; loop_interpolated (optional) is the interpolated loop pair.
170
+
171
+
172
+ === GIF SAVE (delays + FFmpeg palette) ===
173
+ images / delays ................ wire the delays output of the interpolation node. Without delays, fallback_fps is used.
174
+ save_location ................. folder the file is saved into. Empty = the ComfyUI output (or temp) folder.
175
+ Absolute path (C:\Users\you\Desktop\GIFs) or relative to that folder
176
+ (e.g. GIFs/exports). Missing folders are created.
177
+ filename ...................... file name without extension. Connect the 'filename' output of 'GIF Load'
178
+ here to keep the original name.
179
+ filename_suffix ............... added at the end with an underscore: 1234 + 'interpolated' -> 1234_interpolated.gif.
180
+ multip_suffix ................. second suffix, after filename_suffix: 1234 + 'interp' + 'x4' -> 1234_interp_x4.gif.
181
+ Connect the 'multiplier' output of an interpolation node here so the file also
182
+ bears the multiplier used. A plain number ('4') is written as 'x4'. Empty = none.
183
+ If name + suffixes are longer than 255 characters, the original name is cut
184
+ from the end so the suffixes always fit at the tail.
185
+ Collision: if the file already exists, a number is added (name_2.gif, name_3.gif, ...) - never overwrites.
186
+ output_format .................. gif (256 colours per frame) or webp (full colour, optional lossless, ms delays).
187
+ max_fps ........................ hard speed cap (50 fps = 2 cs minimum delay). Shorter delays are raised to it.
188
+ fallback_fps ................... speed used only when no delays are connected.
189
+ quality ........................ 0 - 100, default 90, works for GIF AND WebP.
190
+ GIF: 90-100 = the full palette (max_colors). Below 90 the palette shrinks linearly:
191
+ about 200 colours at 70, 129 at 45, 58 at 20, 2 at 0 -> smaller files, more banding
192
+ (a "quality" setting does not exist in the GIF format, so it controls the palette size;
193
+ the dither setting is left as you chose it). Works with both backends.
194
+ WebP: lossy = image quality, lossless = compression effort (higher = smaller, slower).
195
+ loop_count ..................... 0 = loop forever, -1 = play once, N = repeat N times.
196
+ save_to ........................ output (kept) or temp (deleted by ComfyUI later).
197
+ batch_size ..................... frames encoded per chunk (GIF via Pillow, WebP). Lower = less RAM, slightly slower.
198
+ animated_preview ............... mark the preview as animated (desktop frontend). Turn off if your frontend shows none.
199
+ GIF only:
200
+ backend ...................... ffmpeg_palette (best quality, needs ffmpeg) or pillow_fallback (no ffmpeg needed).
201
+ palette_mode ................. per_frame: every frame gets its own 256-colour palette (best). global: one palette
202
+ for the whole gif (smaller file, more banding).
203
+ dither ....................... none (banding) | floyd_steinberg, sierra2, sierra2_4a (error diffusion, sierra2_4a is
204
+ the gentlest and leaves frames that already have <=256 colours unchanged) |
205
+ bayer (ordered pattern) | heckbert (simple, no real dither).
206
+ max_colors ................... 2-256 colours per palette at best quality (the quality slider can lower it).
207
+ optimize_size ................ smaller file via transparency/rectangle tricks, but 255 colours and not lossless.
208
+ WebP only:
209
+ webp_lossless ................ ON = exact pixels (big files), OFF = lossy (much smaller).
210
+ webp_method .................. encoder effort 0 (fast) - 6 (slowest, smallest).
211
+ max_size_mb (optional) ......... maximum file size in MB, 0 = off (default). Above 0 the quality is chosen AUTOMATICALLY:
212
+ the size is estimated from a sample of the frames, the best setting estimated to fit is
213
+ picked, the file is written and its real size checked (if it is too big, or leaves more
214
+ than 15 % of the budget unused, the estimate is corrected and the file written again:
215
+ 3 passes at most; the console shows the estimate and the real size of each pass).
216
+ WebP: lossless is kept when it fits, otherwise lossy at the highest quality that fits
217
+ (the quality slider is the upper limit). Every WebP frame is encoded on its own, so the
218
+ estimate is very accurate. GIF: the palette is reduced as little as possible (quality and
219
+ max_colors are the upper limit); the estimate comes from short runs of real frames.
220
+ If even the lowest setting is too big, the smallest file is saved, the console warns and
221
+ file_info says STILL OVER THE LIMIT: use fewer frames, a lower max_fps or a smaller resolution.
222
+ Extra time: a few sample encodes, plus one more full encode when a correction is needed.
223
+ Outputs: delays, gif_info, filepath, file_info (real size and the setting used, e.g. "1.48 MB (limit 1.5 MB), GIF palette of 48 colours").
224
+
225
+
226
+ === HELPERS ===
227
+ GIF Delays Info ................ delays -> avg_fps, min_ms, max_ms.
228
+ GIF Delays From FPS ............ images + fps -> constant delays (for a video / image batch), plus avg_fps.
Comfyui delay tool/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
2
+
3
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
Comfyui delay tool/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (353 Bytes). View file
 
Comfyui delay tool/__pycache__/gif_core.cpython-313.pyc ADDED
Binary file (47.6 kB). View file
 
Comfyui delay tool/__pycache__/nodes.cpython-313.pyc ADDED
Binary file (63 kB). View file
 
Comfyui delay tool/gif_core.py ADDED
@@ -0,0 +1,909 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ gif_core.py - torch-free helpers for ComfyUI_GIF_Delay_Tools.
3
+
4
+ Everything here works on numpy uint8 arrays [N, H, W, 3] and delay lists in
5
+ milliseconds, so it can be tested without ComfyUI.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import io
10
+ import math
11
+ import os
12
+ import shutil
13
+ import statistics
14
+ import struct
15
+ import subprocess
16
+ import tempfile
17
+
18
+ import numpy as np
19
+ from PIL import Image, ImageSequence
20
+
21
+ BG_COLORS = {
22
+ "black": (0, 0, 0),
23
+ "white": (255, 255, 255),
24
+ "gray": (128, 128, 128),
25
+ "green": (0, 255, 0),
26
+ }
27
+
28
+
29
+ # --------------------------------------------------------------------------
30
+ # Delay helpers
31
+ # --------------------------------------------------------------------------
32
+ def avg_fps(delays_ms) -> float:
33
+ """Average fps = frame count / total duration."""
34
+ total = float(sum(delays_ms))
35
+ if total <= 0 or len(delays_ms) == 0:
36
+ return 0.0
37
+ return 1000.0 * len(delays_ms) / total
38
+
39
+
40
+ def delays_to_text(delays_ms) -> str:
41
+ return ", ".join(str(int(round(d))) for d in delays_ms)
42
+
43
+
44
+ def min_delay_cs_for_fps(max_fps: float) -> int:
45
+ """Smallest GIF delay (centiseconds) that keeps playback <= max_fps."""
46
+ return max(1, int(math.ceil(100.0 / max(1e-6, float(max_fps)) - 1e-9)))
47
+
48
+
49
+ def quantize_delays_cs(delays_ms, min_cs: int = 2):
50
+ """
51
+ ms -> GIF centiseconds with error diffusion, so the total duration of the
52
+ animation stays correct even when single delays are not multiples of 10 ms.
53
+ """
54
+ out = []
55
+ target = 0.0
56
+ emitted = 0
57
+ for d in delays_ms:
58
+ target += float(d) / 10.0
59
+ cs = max(min_cs, int(math.floor(target - emitted + 0.5)))
60
+ cs = min(cs, 65535)
61
+ out.append(cs)
62
+ emitted += cs
63
+ return out
64
+
65
+
66
+ # --------------------------------------------------------------------------
67
+ # GIF / WebP reading
68
+ # --------------------------------------------------------------------------
69
+ def read_webp_delays(path):
70
+ """Per-frame durations (ms) read straight from the ANMF chunks.
71
+ (Pillow's WebP `duration` is shifted by one frame in some versions.)"""
72
+ with open(path, "rb") as f:
73
+ data = f.read()
74
+ if data[:4] != b"RIFF" or data[8:12] != b"WEBP":
75
+ return []
76
+ pos, out = 12, []
77
+ while pos + 8 <= len(data):
78
+ tag = data[pos:pos + 4]
79
+ size = struct.unpack_from("<I", data, pos + 4)[0]
80
+ if tag == b"ANMF":
81
+ out.append(int.from_bytes(data[pos + 8 + 12:pos + 8 + 15], "little"))
82
+ pos += 8 + size + (size & 1)
83
+ return out
84
+
85
+
86
+ def read_gif(path, bg="black", fix_browser_delay=True, skip_first=0, cap=0, nth=1):
87
+ """
88
+ Returns (frames uint8 [N,H,W,3], delays_ms list[int], loop_count int).
89
+ Disposal methods are handled by Pillow (frames come out fully composited).
90
+ When select_every_nth > 1 the delays of skipped frames are added to the
91
+ kept frame, so the overall rhythm/duration is preserved.
92
+
93
+ The output array is pre-allocated (frame count known up front), so peak RAM is
94
+ ~1x the final array instead of ~2x (python list + np.stack).
95
+ """
96
+ bg_rgb = BG_COLORS.get(bg, (0, 0, 0))
97
+ nth = max(1, int(nth))
98
+ skip_first = max(0, int(skip_first))
99
+ frames, delays = None, []
100
+ with Image.open(path) as im: # closes the file handle (Windows keeps it locked otherwise)
101
+ is_webp = im.format == "WEBP"
102
+ webp_d = read_webp_delays(path) if is_webp else []
103
+ loop = int(im.info.get("loop", 0))
104
+ total = int(getattr(im, "n_frames", 1))
105
+ n_keep = max(0, -(-(total - skip_first) // nth)) # ceil division
106
+ if cap:
107
+ n_keep = min(n_keep, int(cap))
108
+ for i, fr in enumerate(ImageSequence.Iterator(im)):
109
+ d = int(fr.info.get("duration", 0) or 0)
110
+ if is_webp and i < len(webp_d):
111
+ d = webp_d[i]
112
+ # GIF: browsers play 0/1 cs delays at 100 ms; WebP: only 0 is invalid
113
+ if fix_browser_delay and d <= (0 if is_webp else 10):
114
+ d = 100
115
+ if i < skip_first:
116
+ continue
117
+ if ((i - skip_first) % nth) == 0:
118
+ if len(delays) >= n_keep:
119
+ break
120
+ rgba = fr.convert("RGBA")
121
+ if rgba.getextrema()[3][0] < 255:
122
+ canvas = Image.new("RGBA", rgba.size, bg_rgb + (255,))
123
+ canvas.alpha_composite(rgba)
124
+ rgba = canvas
125
+ arr = np.asarray(rgba.convert("RGB"), dtype=np.uint8)
126
+ if frames is None:
127
+ frames = np.empty((n_keep,) + arr.shape, dtype=np.uint8)
128
+ frames[len(delays)] = arr
129
+ delays.append(d)
130
+ elif delays:
131
+ delays[-1] += d
132
+ if not delays:
133
+ raise ValueError(f"No frames could be read from {path}")
134
+ if len(delays) < frames.shape[0]:
135
+ frames = frames[:len(delays)]
136
+ return frames, delays, loop
137
+
138
+
139
+ # --------------------------------------------------------------------------
140
+ # Raw GIF block walker (read / patch Graphic Control Extension delays)
141
+ # --------------------------------------------------------------------------
142
+ def _gce_delay_offsets(data) -> list:
143
+ if bytes(data[:3]) != b"GIF":
144
+ raise ValueError("Not a GIF file")
145
+ n = len(data)
146
+ flags = data[10]
147
+ pos = 13
148
+ if flags & 0x80:
149
+ pos += 3 * (1 << ((flags & 7) + 1))
150
+
151
+ def skip_sub(p):
152
+ while p < n and data[p] != 0:
153
+ p += data[p] + 1
154
+ return p + 1
155
+
156
+ offs = []
157
+ while pos < n:
158
+ b = data[pos]
159
+ if b == 0x3B:
160
+ break
161
+ if b == 0x21:
162
+ if data[pos + 1] == 0xF9:
163
+ offs.append(pos + 4)
164
+ pos = skip_sub(pos + 2)
165
+ elif b == 0x2C:
166
+ lf = data[pos + 9]
167
+ pos += 10
168
+ if lf & 0x80:
169
+ pos += 3 * (1 << ((lf & 7) + 1))
170
+ pos = skip_sub(pos + 1)
171
+ else:
172
+ raise ValueError(f"Unexpected GIF block 0x{b:02x} at {pos}")
173
+ return offs
174
+
175
+
176
+ def read_gif_delays(path) -> list:
177
+ """Per-frame delays (ms) exactly as stored in the file."""
178
+ with open(path, "rb") as f:
179
+ data = f.read()
180
+ return [struct.unpack_from("<H", data, o)[0] * 10 for o in _gce_delay_offsets(data)]
181
+
182
+
183
+ def patch_gif_delays(path, delays_cs) -> int:
184
+ """Overwrite every frame's delay with our exact centisecond values."""
185
+ with open(path, "rb") as f:
186
+ data = bytearray(f.read())
187
+ offs = _gce_delay_offsets(data)
188
+ if len(offs) != len(delays_cs):
189
+ raise RuntimeError(
190
+ f"GIF has {len(offs)} frames but {len(delays_cs)} delays were expected"
191
+ )
192
+ for o, cs in zip(offs, delays_cs):
193
+ struct.pack_into("<H", data, o, int(cs))
194
+ with open(path, "wb") as f:
195
+ f.write(data)
196
+ return len(offs)
197
+
198
+
199
+ # --------------------------------------------------------------------------
200
+ # GIF writing
201
+ # --------------------------------------------------------------------------
202
+ def find_ffmpeg():
203
+ p = os.environ.get("FFMPEG_PATH")
204
+ if p and os.path.exists(p):
205
+ return p
206
+ w = shutil.which("ffmpeg")
207
+ if w:
208
+ return w
209
+ try:
210
+ import imageio_ffmpeg # shipped with many ComfyUI setups
211
+
212
+ return imageio_ffmpeg.get_ffmpeg_exe()
213
+ except Exception:
214
+ return None
215
+
216
+
217
+ def _run_ffmpeg(cmd):
218
+ return subprocess.run(cmd, capture_output=True, text=True)
219
+
220
+
221
+ def save_gif_ffmpeg(frames, delays_cs, path, loop=0, palette_mode="per_frame",
222
+ dither="sierra2_4a", max_colors=256, optimize_size=False,
223
+ bayer_scale=3):
224
+ """
225
+ Encode with FFmpeg palettegen/paletteuse.
226
+
227
+ * palette_mode "per_frame": palettegen stats_mode=single + paletteuse new=1
228
+ (every frame gets its own 256-colour palette -> best fidelity)
229
+ * palette_mode "global": one palette from all frames (stats_mode=full)
230
+ * Delays are NOT taken from ffmpeg timestamps (GIF muxer rounding is
231
+ unreliable for variable timing): the GIF is encoded frame-for-frame and
232
+ the exact delays are then written into the file.
233
+ """
234
+ ff = find_ffmpeg()
235
+ if ff is None:
236
+ raise FileNotFoundError("ffmpeg not found (install it, or set FFMPEG_PATH)")
237
+
238
+ per_frame = palette_mode == "per_frame"
239
+ reserve = 1 if optimize_size else 0
240
+ # rectangle diff is incompatible with per-frame palettes (corrupts colours)
241
+ diff = "rectangle" if (optimize_size and not per_frame) else "none"
242
+ pal = (f"palettegen=max_colors={int(max_colors)}:reserve_transparent={reserve}"
243
+ f":stats_mode={'single' if per_frame else 'full'}")
244
+ use = f"paletteuse=dither={dither}:diff_mode={diff}"
245
+ if per_frame:
246
+ use += ":new=1"
247
+ if dither == "bayer":
248
+ use += f":bayer_scale={int(bayer_scale)}"
249
+
250
+ def run(args):
251
+ # -fps_mode is new; older ffmpeg builds only know -vsync
252
+ res = _run_ffmpeg(args + ["-fps_mode", "passthrough"])
253
+ if res.returncode != 0 and ("fps_mode" in res.stderr or "Unrecognized option" in res.stderr):
254
+ res = _run_ffmpeg(args + ["-vsync", "0"])
255
+ return res
256
+
257
+ with tempfile.TemporaryDirectory(prefix="gifdelay_") as tmp:
258
+ for i, fr in enumerate(frames):
259
+ Image.fromarray(fr).save(os.path.join(tmp, f"f_{i:06d}.png"), compress_level=1)
260
+ seq = os.path.join(tmp, "f_%06d.png")
261
+ head = [ff, "-y", "-hide_banner", "-loglevel", "error"]
262
+ tail = ["-loop", str(int(loop)), path]
263
+ if per_frame:
264
+ res = run(head + ["-framerate", "50", "-start_number", "0", "-i", seq,
265
+ "-vf", f"split[a][b];[a]{pal}[p];[b][p]{use}"] + tail)
266
+ else:
267
+ # stats_mode=full only emits its palette at EOF, so a one-pass
268
+ # split->palettegen->paletteuse graph keeps EVERY frame in RAM inside ffmpeg
269
+ # (grows with N and gets the process OOM-killed). Two passes read from disk instead.
270
+ palfile = os.path.join(tmp, "palette.png")
271
+ r1 = _run_ffmpeg(head + ["-start_number", "0", "-i", seq, "-vf", pal,
272
+ "-frames:v", "1", "-update", "1", palfile])
273
+ if r1.returncode != 0:
274
+ raise RuntimeError("ffmpeg palettegen failed:\n" + r1.stderr[-2000:])
275
+ res = run(head + ["-framerate", "50", "-start_number", "0", "-i", seq, "-i", palfile,
276
+ "-lavfi", f"[0:v][1:v]{use}"] + tail)
277
+ if res.returncode != 0:
278
+ raise RuntimeError("ffmpeg failed:\n" + res.stderr[-2000:])
279
+
280
+ patch_gif_delays(path, delays_cs)
281
+
282
+
283
+ def _parse_gif_frame(gif_bytes):
284
+ """
285
+ Parse a single-frame GIF (as produced by Pillow) and return
286
+ (color_table_bytes, lzw_bytes) where lzw_bytes = min_code_size + sub-blocks + 0x00.
287
+ """
288
+ pos = 6 # skip "GIF89a"
289
+ # Logical Screen Descriptor (7 bytes)
290
+ packed = gif_bytes[10]
291
+ pos = 13
292
+ gct = b""
293
+ if packed & 0x80:
294
+ sz = 3 * (1 << ((packed & 0x07) + 1))
295
+ gct = gif_bytes[pos:pos + sz]
296
+ pos += sz
297
+ # Walk extension blocks until Image Descriptor
298
+ n = len(gif_bytes)
299
+ while pos < n and gif_bytes[pos] not in (0x2C, 0x3B):
300
+ pos += 2 # skip 0x21 + label
301
+ while pos < n and gif_bytes[pos] != 0:
302
+ pos += gif_bytes[pos] + 1
303
+ pos += 1 # skip 0x00 block terminator
304
+ # Image Descriptor (10 bytes: 0x2C + left2 + top2 + w2 + h2 + packed)
305
+ ip = gif_bytes[pos + 9]
306
+ pos += 10
307
+ lct = b""
308
+ if ip & 0x80:
309
+ sz = 3 * (1 << ((ip & 0x07) + 1))
310
+ lct = gif_bytes[pos:pos + sz]
311
+ pos += sz
312
+ # LZW data: min_code_size + sub-blocks + 0x00
313
+ min_code = gif_bytes[pos]
314
+ pos += 1
315
+ chunks = [bytes([min_code])]
316
+ while gif_bytes[pos] != 0:
317
+ sz = gif_bytes[pos]
318
+ chunks.append(gif_bytes[pos:pos + 1 + sz]) # keep the length byte
319
+ pos += sz + 1
320
+ chunks.append(b"\x00") # block terminator
321
+ return (lct if lct else gct), b"".join(chunks)
322
+
323
+
324
+ def _write_gif_frame(f, fr, delay_cs, w, h, max_colors, dmode):
325
+ """Quantize one frame, encode via Pillow single-frame GIF, write GCE+ID+LCT+LZW to f."""
326
+ im = Image.fromarray(fr).quantize(
327
+ colors=int(max_colors), method=Image.Quantize.MEDIANCUT, dither=dmode)
328
+ buf = io.BytesIO()
329
+ im.save(buf, format="GIF", optimize=False)
330
+ buf.seek(0)
331
+ ct, lzw = _parse_gif_frame(buf.getvalue())
332
+
333
+ # Graphic Control Extension: disposal=1 (do not dispose), no transparency
334
+ f.write(b"\x21\xF9\x04\x04" + struct.pack("<H", delay_cs) + b"\x00\x00")
335
+ # Image Descriptor: local color table flag set
336
+ ct_entries = len(ct) // 3
337
+ ct_bits = max(0, int(math.log2(ct_entries)) - 1) if ct_entries > 1 else 0
338
+ f.write(b"\x2C" + struct.pack("<HHHH", 0, 0, w, h) + bytes([0x80 | (ct_bits & 0x07)]))
339
+ # Local Color Table
340
+ f.write(ct)
341
+ # LZW data (min code size + sub-blocks + 0x00 terminator)
342
+ f.write(lzw)
343
+
344
+
345
+ def save_gif_pillow(frames, delays_cs, path, loop=0, dither=True, max_colors=256,
346
+ batch_size=100):
347
+ """
348
+ Memory-bounded GIF writer (no ffmpeg required).
349
+
350
+ Instead of Pillow's `save_all` (which buffers every frame in RAM), each frame
351
+ is quantised and encoded to a single-frame GIF in a BytesIO buffer, then the
352
+ colour table + LZW payload are extracted and written straight to the output
353
+ file. Peak memory ≈ one frame + its quantised copy, regardless of total N.
354
+ Accepts any iterable of uint8 [H, W, 3] arrays (numpy array or generator).
355
+ """
356
+ dmode = Image.Dither.FLOYDSTEINBERG if dither else Image.Dither.NONE
357
+ it = iter(frames)
358
+ try:
359
+ first = next(it)
360
+ except StopIteration:
361
+ raise ValueError("save_gif_pillow: no frames")
362
+ h, w = first.shape[0], first.shape[1]
363
+
364
+ with open(path, "wb") as f:
365
+ # GIF89a header + Logical Screen Descriptor (no GCT)
366
+ f.write(b"GIF89a")
367
+ f.write(struct.pack("<HHBBB", w, h, 0x00, 0, 0))
368
+
369
+ # NETSCAPE 2.0 loop extension
370
+ # loop == 0: infinite; loop < 0: play once; loop > 0: play that many times
371
+ if loop == 0:
372
+ f.write(b"\x21\xFF\x0BNETSCAPE2.0\x03\x01" + struct.pack("<H", 0xFFFF) + b"\x00")
373
+ elif loop > 0:
374
+ f.write(b"\x21\xFF\x0BNETSCAPE2.0\x03\x01" + struct.pack("<H", min(loop - 1, 0xFFFE)) + b"\x00")
375
+ # loop < 0: no NETSCAPE block (GIF default = play once)
376
+
377
+ # Write first frame
378
+ d0 = delays_cs[0] if delays_cs else 10
379
+ _write_gif_frame(f, first, d0, w, h, max_colors, dmode)
380
+
381
+ # Write remaining frames
382
+ for i, fr in enumerate(it, start=1):
383
+ d = delays_cs[i] if i < len(delays_cs) else (delays_cs[-1] if delays_cs else 10)
384
+ _write_gif_frame(f, fr, d, w, h, max_colors, dmode)
385
+
386
+ f.write(b"\x3B") # GIF trailer
387
+
388
+
389
+ # --------------------------------------------------------------------------
390
+ # WebP writing
391
+ # --------------------------------------------------------------------------
392
+ def quantize_delays_ms(delays_ms, min_ms: int = 20):
393
+ """Integer milliseconds (WebP precision) with error diffusion; keeps total duration."""
394
+ out, target, emitted = [], 0.0, 0
395
+ for d in delays_ms:
396
+ target += float(d)
397
+ v = max(int(min_ms), int(math.floor(target - emitted + 0.5)))
398
+ out.append(v)
399
+ emitted += v
400
+ return out
401
+
402
+
403
+ def _webp_chunk(tag, payload):
404
+ """RIFF chunk = tag + 4-byte little-endian size + payload (+ 1 pad byte if odd)."""
405
+ out = tag + struct.pack("<I", len(payload)) + payload
406
+ return out + (b"\x00" if len(payload) & 1 else b"")
407
+
408
+
409
+ def _webp_frame_bitstream(rgb, lossless, quality, method):
410
+ """Encode ONE frame to a standalone WebP and return its full VP8/VP8L chunk
411
+ (tag + size + payload + pad). A single image is encoded at a time, so libwebp
412
+ never has to hold the whole animation in RAM."""
413
+ buf = io.BytesIO()
414
+ rgb.convert("RGB").save(buf, format="WEBP", lossless=bool(lossless),
415
+ quality=int(quality), method=int(method))
416
+ d = buf.getvalue()
417
+ p = 12 # skip the RIFF....WEBP header
418
+ while True:
419
+ tag = d[p:p + 4]
420
+ sz = struct.unpack_from("<I", d, p + 4)[0]
421
+ if tag in (b"VP8 ", b"VP8L"):
422
+ o = d[p:p + 8 + sz]
423
+ return o + (b"\x00" if sz & 1 else b"")
424
+ p += 8 + sz + (sz & 1)
425
+
426
+
427
+ def save_webp(frames, delays_ms, path, loop=0, lossless=True, quality=90, method=4,
428
+ batch_size=100):
429
+ """
430
+ Animated WebP with per-frame durations, written STREAMING one frame at a time
431
+ so peak memory stays bounded regardless of total frame count.
432
+
433
+ Accepts any iterable of uint8 [H, W, 3] arrays (numpy array or generator).
434
+ loop_count: 0 = forever, -1 = play once, N = repeat N times.
435
+ """
436
+ it = iter(frames)
437
+ try:
438
+ first = next(it)
439
+ except StopIteration:
440
+ raise ValueError("save_webp: no frames")
441
+
442
+ h, w = first.shape[0], first.shape[1]
443
+
444
+ # Single frame? (no animation chunks needed)
445
+ try:
446
+ second = next(it)
447
+ except StopIteration:
448
+ Image.fromarray(first).save(path, format="WEBP", lossless=bool(lossless),
449
+ quality=int(quality), method=int(method))
450
+ return
451
+
452
+ loopcount = 1 if loop == -1 else (0 if loop == 0 else int(loop) + 1)
453
+
454
+ def _write_anmf(f, fr, delay_ms, flags):
455
+ bs = _webp_frame_bitstream(Image.fromarray(fr), lossless, quality, method)
456
+ hdr = (struct.pack("<I", 0)[:3]
457
+ + struct.pack("<I", 0)[:3]
458
+ + struct.pack("<I", w - 1)[:3]
459
+ + struct.pack("<I", h - 1)[:3]
460
+ + struct.pack("<I", int(delay_ms))[:3]
461
+ + struct.pack("<B", flags))
462
+ f.write(_webp_chunk(b"ANMF", hdr + bs))
463
+
464
+ with open(path, "wb") as f:
465
+ f.write(b"RIFF")
466
+ f.write(struct.pack("<I", 0))
467
+ f.write(b"WEBP")
468
+ f.write(_webp_chunk(b"VP8X",
469
+ struct.pack("<B3s", 0x02, b"\x00\x00\x00")
470
+ + struct.pack("<L", w - 1)[:3]
471
+ + struct.pack("<L", h - 1)[:3]))
472
+ f.write(_webp_chunk(b"ANIM", b"\x00\x00\x00\x00" + struct.pack("<H", loopcount)))
473
+
474
+ _write_anmf(f, first, delays_ms[0], 0x02)
475
+ _write_anmf(f, second, delays_ms[1], 0x00)
476
+ for i, fr in enumerate(it, start=2):
477
+ _write_anmf(f, fr, delays_ms[i], 0x00)
478
+
479
+ # patch the RIFF size field
480
+ f.seek(0, 2)
481
+ total = f.tell() - 8
482
+ f.seek(4)
483
+ f.write(struct.pack("<I", total))
484
+
485
+
486
+ # --------------------------------------------------------------------------
487
+ # Delay-aware interpolation timing
488
+ # --------------------------------------------------------------------------
489
+ def plan_multiplier(delays_ms, target_fps=50.0, reference="average_fps", max_mult=16):
490
+ """Largest integer multiplier that keeps the result <= target_fps.
491
+ reference: average_fps | median_delay | minimum_fps (slowest part of the gif)
492
+ | maximum_fps (fastest part of the gif)."""
493
+ if reference == "median_delay":
494
+ src = 1000.0 / max(1.0, statistics.median(delays_ms))
495
+ elif reference == "minimum_fps":
496
+ src = 1000.0 / max(1.0, float(max(delays_ms))) # longest delay = slowest part
497
+ elif reference == "maximum_fps":
498
+ src = 1000.0 / max(1.0, float(min(delays_ms))) # shortest delay = fastest part
499
+ else:
500
+ src = avg_fps(delays_ms)
501
+ src = max(src, 1e-6)
502
+ m = int(math.floor(target_fps / src + 1e-9))
503
+ return max(1, min(int(max_mult), m)), src
504
+
505
+
506
+ def infer_multiplier(n, total):
507
+ if n <= 1:
508
+ if total != 1:
509
+ raise ValueError(f"Original has {n} frame(s) but interpolated batch has {total}")
510
+ return 1
511
+ if (total - 1) % (n - 1) != 0:
512
+ raise ValueError(
513
+ f"Interpolated batch has {total} frames, which is not (N-1)*m+1 for the "
514
+ f"{n} original delays. Connect the interpolation of the SAME gif frames."
515
+ )
516
+ return (total - 1) // (n - 1)
517
+
518
+
519
+ TIMING_MODES = ["keep_original_delays", "uniform_delays", "smart_delays"]
520
+
521
+ # deduce_from_original is a 3-way choice (older workflows stored a boolean: True / False)
522
+ DEDUCE_ALL, DEDUCE_NOT_HELD, DEDUCE_NONE = "deduce", "deduce - not held frame", "don't deduce"
523
+ DEDUCE_MODES = [DEDUCE_ALL, DEDUCE_NOT_HELD, DEDUCE_NONE]
524
+
525
+
526
+ def parse_deduce(v):
527
+ """-> (deduce_on, skip_held). Accepts the 3 option strings or a legacy bool."""
528
+ if isinstance(v, str):
529
+ if v == DEDUCE_NOT_HELD:
530
+ return True, True
531
+ if v == DEDUCE_NONE:
532
+ return False, False
533
+ return True, False
534
+ return bool(v), False
535
+
536
+
537
+ def is_held(d, avg, factor=2.0):
538
+ """A 'held' frame stays on screen at least `factor` times as long as the average frame."""
539
+ return d >= float(factor) * avg - 1e-9
540
+
541
+
542
+ def plan_segment(d, k, mode, deduce, allow_longer, interp_ms, min_ms,
543
+ hold_cap=None, is_loop=False):
544
+ """
545
+ One original frame (delay d ms) followed by up to k interpolated frames.
546
+ Returns (original_delay, picks (1..k, evenly spread), interp_delays).
547
+
548
+ deduce: True -> the time of the interpolated frames is taken out of the
549
+ original frame's delay (the original frame gets shorter).
550
+ False -> the original frame keeps its full delay (the gif grows).
551
+ allow_longer: True -> all k interpolated frames are kept (the gif may get longer).
552
+ False -> the segment keeps its original duration: only as many
553
+ interpolated frames as fit are kept (evenly spread).
554
+ is_loop: the seamless-loop transition segment (last frame -> first frame).
555
+ deduce ON : handled exactly like every other segment, so the time
556
+ of its frames is taken out of the LAST frame's delay.
557
+ deduce OFF: its frames are always kept and added on top of the
558
+ original duration (otherwise a seamless loop would
559
+ silently lose its transition frames).
560
+ hold_cap: smart_delays: a frame longer than hold_cap is a "hold"; its new
561
+ frames glide at the capped pace instead of its own (so a long
562
+ hold does not turn into a slow transition).
563
+ """
564
+ d = max(float(d), float(min_ms))
565
+ interp_ms = float(interp_ms)
566
+ if k <= 0:
567
+ return d, [], []
568
+
569
+ if mode == "smart_delays":
570
+ # glide at the original pace: the k new frames share one original delay
571
+ # between them (capped for hold frames)
572
+ r = max(float(min_ms), min(float(d), float(hold_cap or float(d))) / (k + 1))
573
+ if not deduce:
574
+ # no deduction: original frame keeps its full delay, new frames are added on top
575
+ j, orig = k, d
576
+ elif allow_longer:
577
+ j, orig = k, max(float(min_ms), d - k * r)
578
+ else: # keep the duration: only as many new frames as fit
579
+ j = min(k, max(0, int((d - float(min_ms)) // r)))
580
+ orig = d - j * r
581
+ dl = [r] * j
582
+ else: # keep_original_delays
583
+ if not deduce and (allow_longer or is_loop):
584
+ # "original delays kept, new frames added on top" (always for the loop transition)
585
+ j, orig = k, d
586
+ elif deduce and allow_longer:
587
+ # deduction allowed, gif may grow: original shrinks down to the minimum
588
+ j, orig = k, max(float(min_ms), d - k * interp_ms)
589
+ elif deduce: # deduction, duration kept: only as many new frames as fit
590
+ j = min(k, max(0, int((d - float(min_ms)) // interp_ms)))
591
+ orig = d - j * interp_ms
592
+ else:
593
+ # no deduction but duration must be kept: no time left for new frames
594
+ j, orig = 0, d
595
+ dl = [interp_ms] * j
596
+
597
+ picks = [int(math.floor(t * (k + 1) / (j + 1) + 0.5)) for t in range(1, j + 1)]
598
+ return orig, picks, dl
599
+
600
+
601
+ def build_timeline(delays, total_interp, mode, deduce, allow_longer, interp_ms, min_ms,
602
+ loop_k=0, held_factor=2.0):
603
+ """
604
+ Source sequence = interpolated batch (total_interp frames) followed by the
605
+ loop-transition frames (loop_k frames). Returns (indices, delays_ms).
606
+
607
+ The loop-transition frames follow the same rules as every other segment: with
608
+ "deduce" ON their time is taken out of the last frame's delay; with "deduce" OFF
609
+ they are added on top of the original duration (the gif gets a bit longer).
610
+
611
+ deduce is one of DEDUCE_MODES (or a legacy bool):
612
+ "deduce" every frame gives up time for its new frames
613
+ "deduce - not held frame" same, except held frames (delay >= held_factor x the average):
614
+ they keep their full delay and ALL their new frames are
615
+ added on top (so the gif gets longer by that amount)
616
+ "don't deduce" originals always keep their delay, new frames go on top
617
+ """
618
+ deduce, skip_held = parse_deduce(deduce)
619
+ n = len(delays)
620
+ m = infer_multiplier(n, total_interp)
621
+ if n <= 1:
622
+ loop_k = 0
623
+ delays = [max(float(x), 1.0) for x in delays]
624
+
625
+ if mode == "uniform_delays":
626
+ # every frame (original + interpolated + loop transition) gets the same delay
627
+ n_nonloop = n + (n - 1) * (m - 1) # == total_interp
628
+ if allow_longer or n_nonloop <= 0:
629
+ u = float(interp_ms)
630
+ else:
631
+ # keep the original total duration; with "deduce" ON the loop transition
632
+ # frames share that budget too, otherwise they are added on top
633
+ u = sum(delays) / (n_nonloop + (loop_k if deduce else 0)) # uniform has no held frames
634
+ u = max(float(min_ms), u)
635
+ total = total_interp + loop_k
636
+ cs = quantize_delays_cs([u] * total,
637
+ min_cs=max(1, int(math.ceil(min_ms / 10.0 - 1e-9))))
638
+ return list(range(total)), [c * 10 for c in cs]
639
+
640
+ # smart_delays: frames longer than held_factor x the average are "holds"; the glide
641
+ # pace of their new frames is capped so they do not slow the transition down
642
+ held_factor = max(1.0, float(held_factor))
643
+ hold_cap = held_factor * (sum(delays) / n) if mode == "smart_delays" else None
644
+
645
+ avg = sum(delays) / n
646
+ idx, out = [], []
647
+ for i in range(n):
648
+ base = i * m
649
+ is_last = (i == n - 1)
650
+ k = loop_k if is_last else (m - 1)
651
+ if skip_held and is_held(delays[i], avg, held_factor):
652
+ # held frame: keeps its full delay, ALL its new frames are added on top
653
+ seg_deduce, seg_longer = False, True
654
+ else:
655
+ seg_deduce, seg_longer = deduce, allow_longer
656
+ orig, picks, dl = plan_segment(
657
+ delays[i], k, mode, seg_deduce, seg_longer, interp_ms, min_ms,
658
+ hold_cap=hold_cap, is_loop=is_last)
659
+ idx.append(base)
660
+ out.append(orig)
661
+ for t, dd in zip(picks, dl):
662
+ idx.append(base + t)
663
+ out.append(dd)
664
+ cs = quantize_delays_cs(out, min_cs=max(1, int(math.ceil(min_ms / 10.0 - 1e-9))))
665
+ return idx, [c * 10 for c in cs]
666
+
667
+
668
+ def gif_colors_for_quality(max_colors, quality):
669
+ """
670
+ GIF has no real quality setting, so the quality slider (0-100) drives the palette size:
671
+ 90-100 = the full max_colors palette (unchanged), below 90 the palette shrinks linearly
672
+ down to 2 colours at 0 (smaller files, more banding).
673
+ """
674
+ max_colors = max(2, min(256, int(max_colors)))
675
+ q = max(0, min(100, int(quality)))
676
+ if q >= 90:
677
+ return max_colors
678
+ return max(2, min(max_colors, int(round(2 + (max_colors - 2) * q / 90.0))))
679
+
680
+
681
+ def apply_forced_multiplier(multiplier, force, timing_mode, allow_longer):
682
+ """
683
+ "force custom multiplier" (0 = off, 1..16 = forced) replaces the incoming multiplier.
684
+ 1 forces x1: no interpolation at all, the original frames are kept and only the timing
685
+ settings apply (change the speed / just convert). Every other setting is respected,
686
+ except where it makes a forced value of 2 or more impossible: with allow_longer OFF the
687
+ frames that do not fit are dropped, so not all the requested frames would exist.
688
+ allow_longer is therefore switched ON (uniform_delays does not drop frames - it shortens
689
+ the delay instead - so it is left alone; x1 has no new frames, so it is left alone too).
690
+ Returns (multiplier, allow_longer, note or None).
691
+ """
692
+ m = max(1, int(multiplier))
693
+ if int(force) < 1:
694
+ return m, allow_longer, None
695
+ m = int(force)
696
+ if m == 1:
697
+ return m, allow_longer, "multiplier forced to x1 - no interpolation, timing settings only"
698
+ note = f"multiplier forced to x{m}"
699
+ if not allow_longer and timing_mode != "uniform_delays":
700
+ allow_longer = True
701
+ note += (" - allow_longer overridden to ON (with it OFF, new frames that do not fit "
702
+ "would be dropped, so the forced multiplier could not be honoured)")
703
+ return m, allow_longer, note
704
+
705
+
706
+ # --------------------------------------------------------------------------
707
+ # Fused interpolation planner (generate ONLY the frames the final timeline keeps)
708
+ # --------------------------------------------------------------------------
709
+ def plan_fused(delays, m, mode, deduce, allow_longer, interp_ms, min_ms, looping=True,
710
+ held_factor=2.0):
711
+ """
712
+ Same timeline as build_timeline(), but expressed as work for the interpolator
713
+ so frames that would be dropped afterwards are never computed or stored.
714
+
715
+ Returns (idx, out_delays_ms, originals, jobs):
716
+ originals: [(out_pos, original_frame_index)] -> plain copies
717
+ jobs: [[frame_a, frame_b, out_start, [t1, t2, ...]]] -> RIFE(a, b) at each t,
718
+ written to consecutive output positions starting at out_start.
719
+ The loop transition is the pair (last, first).
720
+ """
721
+ n = len(delays)
722
+ m = max(1, int(m))
723
+ total_interp = (n - 1) * m + 1
724
+ loop_k = (m - 1) if (looping and n >= 2) else 0
725
+ idx, out_delays = build_timeline(list(delays), total_interp, mode, deduce, allow_longer,
726
+ interp_ms, min_ms, loop_k=loop_k, held_factor=held_factor)
727
+ originals, jobs = [], []
728
+ for o, k in enumerate(idx):
729
+ if k < total_interp:
730
+ i, r = divmod(k, m)
731
+ if r == 0:
732
+ originals.append((o, i))
733
+ continue
734
+ a, b, t = i, i + 1, r / m
735
+ else:
736
+ a, b, t = n - 1, 0, (k - total_interp + 1) / m
737
+ last = jobs[-1] if jobs else None
738
+ if last and last[0] == a and last[1] == b and last[2] + len(last[3]) == o:
739
+ last[3].append(t)
740
+ else:
741
+ jobs.append([a, b, o, [t]])
742
+ return idx, out_delays, originals, jobs
743
+
744
+
745
+ # --------------------------------------------------------------------------
746
+ # Duplicate-frame removal
747
+ # --------------------------------------------------------------------------
748
+ def dedupe_frames(frames, delays, threshold=0.0, mode="strict_max_difference",
749
+ compare_against="group_first_frame"):
750
+ """
751
+ Merge CONSECUTIVE duplicate frames and add up their delays
752
+ (4 identical frames x 20 ms -> 1 frame x 80 ms).
753
+ Kept frames are the untouched originals (first frame of each run).
754
+
755
+ threshold: 0 = exact duplicates only; otherwise in 0-255 pixel levels.
756
+ mode: strict_max_difference (no single pixel may differ by more than
757
+ threshold) or mean_difference (average over the image; can hide
758
+ small but visible changes).
759
+ compare_against: group_first_frame (no drift) or previous_frame.
760
+ Returns (kept_indices, merged_delays_ms).
761
+ """
762
+ n = len(frames) # `frames` may be a lazy sequence: only [i] and len() are used
763
+ strict = mode != "mean_difference"
764
+ previous = compare_against == "previous_frame"
765
+ keep, out = [], []
766
+ ref = prev = None # cached, so a lazy sequence converts each frame once
767
+ for i in range(n):
768
+ cur = frames[i]
769
+ if keep:
770
+ r = prev if previous else ref
771
+ if threshold <= 0 and strict:
772
+ same = np.array_equal(r, cur)
773
+ else:
774
+ diff = np.abs(r.astype(np.int16) - cur.astype(np.int16))
775
+ score = float(diff.max()) if strict else float(diff.mean())
776
+ same = score <= threshold
777
+ if same:
778
+ out[-1] += int(round(delays[i]))
779
+ prev = cur
780
+ continue
781
+ keep.append(i)
782
+ out.append(int(round(delays[i])))
783
+ ref = prev = cur
784
+ return keep, out
785
+
786
+
787
+ # --------------------------------------------------------------------------
788
+ # Maximum file size: estimate the size from a sample, pick the best setting that fits, verify
789
+ # --------------------------------------------------------------------------
790
+ def spread_indices(n, k=16):
791
+ """k frames evenly spread over the animation (all of them when n <= k)."""
792
+ if n <= k:
793
+ return list(range(n))
794
+ return sorted({int(round(i * (n - 1) / (k - 1))) for i in range(k)})
795
+
796
+
797
+ def run_indices(n, runs=5, length=6):
798
+ """`runs` short runs of consecutive frames (GIF size depends on neighbouring frames)."""
799
+ if n <= runs * length:
800
+ return list(range(n))
801
+ out = []
802
+ for i in range(runs):
803
+ s = int(round(i * (n - length) / (runs - 1)))
804
+ out.extend(range(s, s + length))
805
+ return sorted(set(out))
806
+
807
+
808
+ def webp_size_estimator(sample, n, method):
809
+ """
810
+ est(cfg) -> estimated bytes of the whole animated WebP, cfg = (lossless, quality).
811
+ Every WebP frame is encoded on its own (no inter-frame compression), so the file size is the
812
+ sum of the frame sizes: the average of the sample frames x n, plus the container overhead.
813
+ """
814
+ cache = {}
815
+
816
+ def est(cfg):
817
+ if cfg not in cache:
818
+ lossless, q = cfg
819
+ tot = sum(len(_webp_frame_bitstream(Image.fromarray(fr), lossless, q, method))
820
+ for fr in sample)
821
+ cache[cfg] = tot / len(sample) * n + 24 * n + 64
822
+ return cache[cfg]
823
+ return est
824
+
825
+
826
+ def gif_size_estimator(sample, n, encode_sample):
827
+ """
828
+ est(colors) -> estimated bytes of the whole GIF. A small GIF made of the sample frames is really
829
+ encoded with the same encoder / settings and its size is scaled up to n frames.
830
+ encode_sample(frames, path, colors) writes that small GIF.
831
+ """
832
+ cache = {}
833
+
834
+ def est(colors):
835
+ if colors not in cache:
836
+ with tempfile.TemporaryDirectory(prefix="gifdelay_est_") as tmp:
837
+ p = os.path.join(tmp, "sample.gif")
838
+ encode_sample(sample, p, colors)
839
+ size = os.path.getsize(p)
840
+ cache[colors] = max(0, size - 800) / len(sample) * n + 800 # ~800 bytes: header + palette
841
+ return cache[colors]
842
+ return est
843
+
844
+
845
+ def fit_to_size(ladder, est, encode, path, max_bytes, margin=0.97, passes=3, log=print):
846
+ """
847
+ Pick, from `ladder` (settings ordered from the BEST quality / biggest file to the worst /
848
+ smallest), the best one whose file fits in max_bytes, and write it to `path`.
849
+
850
+ 1. est(cfg) estimates the size from a sample -> the best cfg estimated under margin*max_bytes
851
+ (binary search: sizes only go down along the ladder).
852
+ 2. encode(cfg, out_path) really writes it. The real size is compared with the estimate; if the
853
+ file is too big (or leaves more than 15 % of the budget unused) the estimate is corrected by
854
+ the real/estimated ratio and the search is repeated (at most `passes` real encodes).
855
+ Returns (cfg, size_bytes, fits). When nothing fits, the smallest file is kept and fits=False.
856
+ """
857
+ base, ext = os.path.splitext(path)
858
+ target = max_bytes * margin
859
+ calib = 1.0
860
+ last = len(ladder) - 1
861
+
862
+ def pick():
863
+ if est(ladder[0]) * calib <= target:
864
+ return 0
865
+ if est(ladder[last]) * calib > target:
866
+ return last
867
+ lo, hi = 0, last # ladder[lo] does not fit, ladder[hi] fits
868
+ while hi - lo > 1:
869
+ mid = (lo + hi) // 2
870
+ if est(ladder[mid]) * calib <= target:
871
+ hi = mid
872
+ else:
873
+ lo = mid
874
+ return hi
875
+
876
+ tried = {} # ladder index -> (size, tmp path)
877
+ try:
878
+ for k in range(passes):
879
+ i = pick()
880
+ if i in tried:
881
+ break
882
+ tmp = f"{base}._fit{k}{ext}"
883
+ encode(ladder[i], tmp)
884
+ size = os.path.getsize(tmp)
885
+ tried[i] = (size, tmp)
886
+ e = est(ladder[i])
887
+ log(f"[GIF Delay Tools] size fit, pass {k + 1}: estimated {e / 2**20:.2f} MB, "
888
+ f"real {size / 2**20:.2f} MB (limit {max_bytes / 2**20:.2f} MB)")
889
+ if size <= max_bytes and (size >= 0.85 * max_bytes or i == 0):
890
+ break # fits, and the budget is well used (or already the best setting)
891
+ if size > max_bytes and i == last:
892
+ break # cannot go any lower
893
+ calib = size / max(e, 1.0)
894
+ fitting = [(i, s) for i, (s, _p) in tried.items() if s <= max_bytes]
895
+ if fitting:
896
+ best = min(fitting, key=lambda t: t[0])[0] # smallest index = best quality that fits
897
+ fits = True
898
+ else:
899
+ best = min(tried, key=lambda i: tried[i][0]) # nothing fits: keep the smallest file
900
+ fits = False
901
+ os.replace(tried[best][1], path)
902
+ tried.pop(best)
903
+ return ladder[best], os.path.getsize(path), fits
904
+ finally:
905
+ for _s, p in tried.values():
906
+ try:
907
+ os.remove(p)
908
+ except OSError:
909
+ pass
Comfyui delay tool/nodes.py ADDED
@@ -0,0 +1,1073 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import math
4
+
5
+ import numpy as np
6
+ import torch
7
+
8
+ import folder_paths
9
+
10
+ from . import gif_core as core
11
+
12
+ GIF_DELAYS = "GIF_DELAYS" # custom type: list[int] of per-frame delays in ms
13
+ CATEGORY = "image/GIF Delay Tools"
14
+
15
+
16
+ # ---------------------------------------------------------------- helpers
17
+ _ANIM_EXT = (".gif", ".webp")
18
+ _FOLDER_STATE = {} # per Load node: which file of the folder comes next (lives until ComfyUI restarts)
19
+
20
+
21
+ def _natural_key(name):
22
+ """'gif2' sorts before 'gif10'."""
23
+ return [int(p) if p.isdigit() else p.lower() for p in re.split(r"(\d+)", name)]
24
+
25
+
26
+ def _list_anim_files(folder):
27
+ names = [f for f in os.listdir(folder)
28
+ if f.lower().endswith(_ANIM_EXT) and os.path.isfile(os.path.join(folder, f))]
29
+ return sorted(names, key=_natural_key)
30
+
31
+
32
+ def _frame_u8(images, i):
33
+ """One frame of an IMAGE batch as uint8 [H,W,3] (float32 first: float16 loses precision at x255)."""
34
+ fr = images[i].detach().float().cpu().numpy()
35
+ return np.clip(fr[..., :3] * 255.0 + 0.5, 0, 255).astype(np.uint8)
36
+
37
+
38
+ class _LazyU8:
39
+ """Sequence view over an IMAGE batch: converts ONE frame at a time (no full uint8 copy)."""
40
+ def __init__(self, images):
41
+ self.images = images
42
+
43
+ def __len__(self):
44
+ return int(self.images.shape[0])
45
+
46
+ def __getitem__(self, i):
47
+ return _frame_u8(self.images, i)
48
+
49
+
50
+ FRAME_STORAGE = ["ram_float32", "ram_float16", "vram_float16"]
51
+
52
+
53
+ def _to_tensor(frames, storage="ram_float32"):
54
+ """
55
+ uint8 [N,H,W,3] -> IMAGE tensor, converted in chunks straight into the final tensor.
56
+ Peak RAM = the uint8 array + the final tensor (was uint8 + a full float32 copy + ...).
57
+ storage: ram_float32 (ComfyUI standard) | ram_float16 (half the RAM) |
58
+ vram_float16 (the frames live on the GPU: almost no RAM left). float16 holds every
59
+ 8-bit value exactly (value/255 survives the round trip back to 8 bit).
60
+ """
61
+ dtype = torch.float32 if storage == "ram_float32" else torch.float16
62
+ dev = torch.device("cpu")
63
+ if storage == "vram_float16":
64
+ try:
65
+ from comfy import model_management
66
+ dev = torch.device(model_management.get_torch_device())
67
+ except Exception:
68
+ dev = torch.device("cpu")
69
+
70
+ def build(target):
71
+ out = torch.empty(frames.shape, dtype=dtype, device=target)
72
+ per_frame = int(np.prod(frames.shape[1:])) * 4
73
+ step = max(1, (256 * 2 ** 20) // max(1, per_frame)) # ~256 MB of float32 per chunk
74
+ for a in range(0, frames.shape[0], step):
75
+ chunk = torch.from_numpy(np.ascontiguousarray(frames[a:a + step])).to(target)
76
+ out[a:a + step] = chunk.to(torch.float32).div_(255.0) # cast to float16 on assignment
77
+ return out
78
+
79
+ if dev.type != "cpu":
80
+ try:
81
+ return build(dev)
82
+ except RuntimeError as e: # GPU out of memory: keep the frames in RAM instead
83
+ print(f"[GIF Delay Tools] frame_storage vram_float16: not enough VRAM ({e}); using RAM.")
84
+ torch.cuda.empty_cache()
85
+ return build(torch.device("cpu"))
86
+
87
+
88
+ def _pick_output_device(mode, nbytes, gpu, cpu, activation_mem=0):
89
+ """
90
+ Where the (big) output batch of an interpolation node lives.
91
+ ram -> ComfyUI's offload device (normally system RAM). vram -> the GPU.
92
+ auto -> the GPU when the batch fits with head-room (the model is already loaded, so the free
93
+ VRAM is what is really left), otherwise RAM.
94
+ """
95
+ if mode == "ram" or torch.device(gpu).type == "cpu":
96
+ return cpu
97
+ if mode == "vram":
98
+ return gpu
99
+ try:
100
+ from comfy import model_management
101
+ free = float(model_management.get_free_memory(gpu))
102
+ except Exception:
103
+ return cpu
104
+ reserve = max(2 * 2 ** 30, 4 * int(activation_mem)) # keep room for the model's own work
105
+ return gpu if nbytes + reserve <= free else cpu
106
+
107
+
108
+ def _alloc_output(shape, dtype, device, fallback, what):
109
+ """torch.empty on `device` (RAM-checked when it is the CPU); a GPU out-of-memory falls back to RAM."""
110
+ nbytes = int(np.prod(shape)) * (torch.finfo(dtype).bits // 8)
111
+ if torch.device(device).type == "cpu":
112
+ _check_ram(nbytes, what)
113
+ return torch.empty(shape, dtype=dtype, device=device)
114
+ try:
115
+ out = torch.empty(shape, dtype=dtype, device=device)
116
+ print(f"[GIF Delay Tools] {what}: output batch ({nbytes / 2**30:.1f} GB) kept in VRAM")
117
+ return out
118
+ except RuntimeError as e:
119
+ print(f"[GIF Delay Tools] {what}: not enough VRAM for the output ({e}); using RAM.")
120
+ torch.cuda.empty_cache()
121
+ _check_ram(nbytes, what)
122
+ return torch.empty(shape, dtype=dtype, device=fallback)
123
+
124
+
125
+ def _check_ram(nbytes, what):
126
+ """Raise a normal ComfyUI error instead of letting the OS kill the whole process."""
127
+ try:
128
+ import psutil
129
+ avail = psutil.virtual_memory().available
130
+ except Exception:
131
+ return
132
+ if nbytes > avail * 0.9:
133
+ raise RuntimeError(
134
+ f"[GIF Delay Tools] {what} needs about {nbytes / 2**30:.1f} GB of RAM but only "
135
+ f"{avail / 2**30:.1f} GB is free. Use fewer frames (select_every_nth / frame_load_cap), "
136
+ f"a smaller resolution or a lower multiplier.")
137
+
138
+
139
+ def _gif_info(delays):
140
+ d = [int(round(x)) for x in delays]
141
+ total = sum(d)
142
+ n = len(d)
143
+ fps = core.avg_fps(d)
144
+ fps_str = str(int(fps)) if fps == int(fps) else f"{fps:.1f}"
145
+ delay_list = ", ".join(str(x) for x in d)
146
+ return (f"total duration : {total}ms\n"
147
+ f"Number of frames : {n}\n"
148
+ f"Average fps : {fps_str}\n"
149
+ f"\n"
150
+ f"Delay list :\n"
151
+ f"{delay_list},")
152
+
153
+
154
+ # ---------------------------------------------------------------- loader
155
+ class GIFLoadWithDelays:
156
+ @classmethod
157
+ def INPUT_TYPES(cls):
158
+ d = folder_paths.get_input_directory()
159
+ files = sorted(f for f in os.listdir(d)
160
+ if os.path.isfile(os.path.join(d, f))
161
+ and f.lower().endswith((".gif", ".webp")))
162
+ return {
163
+ "required": {
164
+ # standard ComfyUI upload widget, same mechanism as LoadAnimAdv / LoadImage
165
+ "gif": (files, {"image_upload": True}),
166
+ "transparent_background": (list(core.BG_COLORS.keys()), {"default": "black"}),
167
+ "fix_browser_min_delay": ("BOOLEAN", {"default": True, "tooltip":
168
+ "Delays of 0/1 cs (GIF) or 0 ms (WebP) are played at 100 ms by browsers. Apply the same here."}),
169
+ "skip_first_frames": ("INT", {"default": 0, "min": 0, "max": 100000}),
170
+ "select_every_nth": ("INT", {"default": 1, "min": 1, "max": 1000, "tooltip":
171
+ "Keep every Nth frame; delays of skipped frames are added to the kept one."}),
172
+ "frame_load_cap": ("INT", {"default": 0, "min": 0, "max": 100000,
173
+ "tooltip": "0 = all frames"}),
174
+ },
175
+ "optional": {
176
+ "custom_path": ("STRING", {"default": "", "tooltip":
177
+ "Empty: the gif/webp chosen above is loaded.\n"
178
+ "Path to a .gif/.webp file: that file is loaded (the dropdown is ignored).\n"
179
+ "Path to a FOLDER: the dropdown is ignored and the folder's .gif/.webp files are "
180
+ "loaded one by one, one per run (natural order: gif2 before gif10). After the last "
181
+ "file it starts again from the first."}),
182
+ "folder_start_index": ("INT", {"default": 0, "min": 0, "max": 1000000, "tooltip":
183
+ "Folder mode only. Which file the sequence starts at (0 = the first file). "
184
+ "Change this value to restart the sequence from that file. The sequence also "
185
+ "restarts when the folder path changes or ComfyUI is restarted."}),
186
+ "frame_storage": (FRAME_STORAGE, {"default": "ram_float32", "tooltip":
187
+ "Where the loaded frames are kept.\n"
188
+ "ram_float32: ComfyUI standard (4 bytes per colour value, most RAM).\n"
189
+ "ram_float16: half the RAM, the 8-bit values stay exact.\n"
190
+ "vram_float16: the frames live on the GPU: almost no RAM is used, but they take VRAM "
191
+ "(as much as ram_float16 takes RAM) for as long as ComfyUI keeps this node's result."}),
192
+ },
193
+ "hidden": {"unique_id": "UNIQUE_ID"},
194
+ }
195
+
196
+ RETURN_TYPES = ("IMAGE", GIF_DELAYS, "STRING", "STRING")
197
+ RETURN_NAMES = ("images", "delays", "gif_info", "filename")
198
+ FUNCTION = "load"
199
+ CATEGORY = CATEGORY
200
+
201
+ @staticmethod
202
+ def _clean(custom_path):
203
+ return custom_path.strip().strip('"') if custom_path and custom_path.strip() else ""
204
+
205
+ @classmethod
206
+ def _path(cls, gif, custom_path):
207
+ cp = cls._clean(custom_path)
208
+ if cp:
209
+ return cp
210
+ return folder_paths.get_annotated_filepath(gif)
211
+
212
+ @classmethod
213
+ def _next_in_folder(cls, folder, start_index, unique_id):
214
+ """Pick the next file of `folder` (one per run) -> (path, position, total)."""
215
+ files = _list_anim_files(folder)
216
+ if not files:
217
+ raise FileNotFoundError(f"No .gif / .webp files in folder: {folder}")
218
+ key = str(unique_id) if unique_id is not None else "default"
219
+ norm = os.path.normcase(os.path.abspath(folder))
220
+ start = int(start_index)
221
+ st = _FOLDER_STATE.get(key)
222
+ if st is None or st["folder"] != norm or st["start"] != start:
223
+ st = {"folder": norm, "start": start, "next": start} # new folder / new start: restart
224
+ _FOLDER_STATE[key] = st
225
+ pos = st["next"] % len(files)
226
+ st["next"] = pos + 1
227
+ return os.path.join(folder, files[pos]), pos, len(files)
228
+
229
+ def load(self, gif, transparent_background, fix_browser_min_delay, skip_first_frames,
230
+ select_every_nth, frame_load_cap, custom_path="", folder_start_index=0,
231
+ frame_storage="ram_float32", unique_id=None):
232
+ cp = self._clean(custom_path)
233
+ prefix = ""
234
+ if cp and os.path.isdir(cp):
235
+ path, pos, total = self._next_in_folder(cp, folder_start_index, unique_id)
236
+ prefix = f"file {pos + 1}/{total}: {os.path.basename(path)}\n"
237
+ print(f"[GIF Delay Tools] folder mode: file {pos + 1}/{total} -> {os.path.basename(path)}")
238
+ else:
239
+ path = self._path(gif, custom_path)
240
+ frames, delays, _loop = core.read_gif(
241
+ path, bg=transparent_background, fix_browser_delay=fix_browser_min_delay,
242
+ skip_first=skip_first_frames, cap=frame_load_cap, nth=select_every_nth)
243
+ name = os.path.splitext(os.path.basename(path))[0]
244
+ return (_to_tensor(frames, frame_storage), list(delays), prefix + _gif_info(delays), name)
245
+
246
+ @classmethod
247
+ def IS_CHANGED(cls, gif, custom_path="", **kw):
248
+ cp = cls._clean(custom_path)
249
+ if cp and os.path.isdir(cp):
250
+ return float("nan") # folder mode: a new file on EVERY run
251
+ try:
252
+ p = cls._path(gif, custom_path)
253
+ return f"{p}:{os.path.getmtime(p)}"
254
+ except Exception:
255
+ return "missing"
256
+
257
+ @classmethod
258
+ def VALIDATE_INPUTS(cls, gif, custom_path=""):
259
+ cp = cls._clean(custom_path)
260
+ if cp:
261
+ if os.path.isdir(cp):
262
+ if not _list_anim_files(cp):
263
+ return f"No .gif / .webp files in folder: {cp}"
264
+ return True
265
+ if not os.path.isfile(cp):
266
+ return f"File or folder not found: {cp}"
267
+ return True
268
+ if not folder_paths.exists_annotated_filepath(gif):
269
+ return f"Invalid gif file: {gif}"
270
+ return True
271
+
272
+
273
+ # ---------------------------------------------------------------- saver
274
+ class GIFSaveWithDelays:
275
+ @classmethod
276
+ def INPUT_TYPES(cls):
277
+ return {
278
+ "required": {
279
+ "images": ("IMAGE",),
280
+ "save_location": ("STRING", {"default": "", "tooltip":
281
+ "Folder the file is saved into.\n"
282
+ "Empty: the ComfyUI output (or temp) folder.\n"
283
+ "Absolute path (C:\\Users\\you\\Desktop\\GIFs) or a path relative to that folder "
284
+ "(e.g. GIFs/exports). Missing folders are created."}),
285
+ "filename": ("STRING", {"default": "animation", "tooltip":
286
+ "File name, without extension. Connect the 'filename' output of "
287
+ "'Load GIF With Delays' here to keep the original name.\n"
288
+ "If it is longer than 255 characters it is cut from the end first."}),
289
+ "filename_suffix": ("STRING", {"default": "", "tooltip":
290
+ "Added at the end, separated by an underscore: '1234' + 'interpolated' -> "
291
+ "1234_interpolated.gif.\n"
292
+ "If name + suffix is longer than 255 characters, the original name is "
293
+ "cut from the end so the suffix always fits at the tail."}),
294
+ "multip_suffix": ("STRING", {"default": "", "tooltip":
295
+ "Second suffix, after filename_suffix: '1234' + 'interp' + 'x4' -> "
296
+ "1234_interp_x4.gif.\n"
297
+ "Connect the 'multiplier' output of an interpolation node here so the file "
298
+ "also bears the multiplier used. A plain number ('4') is written as 'x4'.\n"
299
+ "Empty = no second suffix."}),
300
+ "output_format": (["gif", "webp"], {"tooltip":
301
+ "gif: 256 colours per frame (FFmpeg palette). webp: full colour, can be truly "
302
+ "lossless, millisecond delays, usually smaller for photos/video."}),
303
+ "webp_lossless": ("BOOLEAN", {"default": True, "tooltip":
304
+ "WebP only. ON = lossless (exact pixels). OFF = lossy, much smaller files."}),
305
+ "quality": ("INT", {"default": 90, "min": 0, "max": 100, "tooltip":
306
+ "0-100, applies to GIF and WebP.\n"
307
+ "GIF: 90-100 = the full palette (max_colors). Below 90 the palette shrinks linearly "
308
+ "(about 129 colours at 45, 2 colours at 0): smaller files, more banding.\n"
309
+ "WebP: lossy = image quality, lossless = compression effort (higher = smaller, slower)."}),
310
+ "webp_method": ("INT", {"default": 4, "min": 0, "max": 6, "tooltip":
311
+ "WebP only. Encoder effort: 0 = fastest, 6 = slowest / smallest."}),
312
+ "fallback_fps": ("FLOAT", {"default": 10.0, "min": 0.1, "max": 100.0, "step": 0.1,
313
+ "tooltip": "Used only when no delays are connected."}),
314
+ "max_fps": ("FLOAT", {"default": 50.0, "min": 1.0, "max": 100.0, "step": 1.0,
315
+ "tooltip": "Hard cap. 50 fps = 2 cs minimum delay "
316
+ "(the fastest speed browsers play reliably)."}),
317
+ "backend": (["ffmpeg_palette", "pillow_fallback"],),
318
+ "palette_mode": (["per_frame", "global"], {"tooltip":
319
+ "per_frame: every frame gets its own 256-colour palette (best quality). "
320
+ "global: one palette for the whole gif."}),
321
+ "dither": (["sierra2_4a", "none", "floyd_steinberg", "sierra2", "bayer", "heckbert"],
322
+ {"tooltip": "Error-diffusion dithers (sierra2_4a, floyd_steinberg) "
323
+ "leave colours untouched when a frame already has <=256 "
324
+ "colours, so they stay lossless for such frames."}),
325
+ "max_colors": ("INT", {"default": 256, "min": 2, "max": 256, "tooltip":
326
+ "GIF only. Palette size at best quality. The quality slider can lower it further."}),
327
+ "loop_count": ("INT", {"default": 0, "min": -1, "max": 65535, "tooltip":
328
+ "0 = loop forever, -1 = play once, N = repeat N times"}),
329
+ "optimize_size": ("BOOLEAN", {"default": False, "tooltip":
330
+ "Transparency/rectangle optimisation: smaller file, but 255 colours and "
331
+ "not strictly lossless."}),
332
+ "batch_size": ("INT", {"default": 100, "min": 1, "max": 1000, "tooltip":
333
+ "Encode frames in chunks of this size to keep peak memory bounded "
334
+ "(WebP + Pillow-GIF). 50-100 is a good default for large animations; "
335
+ "lower = less RAM, slightly slower."}),
336
+ "save_to": (["output", "temp"],),
337
+ "animated_preview": ("BOOLEAN", {"default": False, "tooltip":
338
+ "Flag the preview as animated (desktop frontend shows it playing). "
339
+ "Leave off if your frontend (e.g. a mobile one) shows no preview."}),
340
+ },
341
+ "optional": {
342
+ "delays": (GIF_DELAYS,),
343
+ "max_size_mb": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 4096.0, "step": 0.1, "tooltip":
344
+ "Maximum file size in MB. 0 = off (the settings above are used as they are).\n"
345
+ "Above 0, the quality is chosen AUTOMATICALLY: the size is estimated from a sample of the "
346
+ "frames, the best setting estimated to fit is picked, the file is written and its real size "
347
+ "checked (the estimate is corrected and the file re-written if needed, 3 passes at most).\n"
348
+ "WebP: lossless is kept when it fits, otherwise lossy at the highest quality that fits "
349
+ "(the quality slider is the upper limit). GIF: the palette is reduced as little as "
350
+ "possible (the quality / max_colors settings are the upper limit).\n"
351
+ "If even the lowest setting is too big, the smallest file is saved and a warning is "
352
+ "printed: use fewer frames, a lower max_fps or a smaller resolution."}),
353
+ },
354
+ }
355
+
356
+ RETURN_TYPES = (GIF_DELAYS, "STRING", "STRING", "STRING")
357
+ RETURN_NAMES = ("delays", "gif_info", "filepath", "file_info")
358
+ FUNCTION = "save"
359
+ OUTPUT_NODE = True
360
+ CATEGORY = CATEGORY
361
+
362
+ def save(self, images, save_location, filename, filename_suffix, multip_suffix, output_format,
363
+ webp_lossless, quality, webp_method, fallback_fps, max_fps, backend,
364
+ palette_mode, dither, max_colors, loop_count, optimize_size, batch_size,
365
+ save_to, animated_preview=False, delays=None, max_size_mb=0.0):
366
+ # Per-frame generator: converts one frame at a time from the ComfyUI tensor,
367
+ # so the full N×H×W×C array is never materialised in RAM.
368
+ n, h, w = images.shape[0], images.shape[1], images.shape[2]
369
+
370
+ def frames():
371
+ for i in range(n):
372
+ yield _frame_u8(images, i)
373
+
374
+ if delays is None:
375
+ delays = [1000.0 / fallback_fps] * n
376
+ if len(delays) != n:
377
+ raise ValueError(f"{n} images but {len(delays)} delays. They must match "
378
+ "(use 'GIF Delay-Aware Interpolation' to rebuild both together).")
379
+
380
+ min_cs = core.min_delay_cs_for_fps(max_fps)
381
+ delays_cs = core.quantize_delays_cs(delays, min_cs=min_cs)
382
+
383
+ # ---- where to save ---------------------------------------------------------
384
+ out_dir = folder_paths.get_output_directory() if save_to == "output" \
385
+ else folder_paths.get_temp_directory()
386
+ loc = (save_location or "").strip().strip('"').strip()
387
+ if loc:
388
+ loc = loc.replace("\\", os.sep)
389
+ if os.path.isabs(loc) or (len(loc) >= 2 and loc[1] == ":"):
390
+ full_folder = os.path.abspath(loc) # absolute: use as given
391
+ else:
392
+ full_folder = os.path.abspath(os.path.join(out_dir, loc)) # relative: under out_dir
393
+ else:
394
+ full_folder = out_dir
395
+ os.makedirs(full_folder, exist_ok=True)
396
+
397
+ # ---- file name: <name>[_<suffix>], the suffix is always kept --------
398
+ def _sanitize(name):
399
+ return "".join(c for c in name if c.isalnum() or c in "_-[]()")
400
+ base = (filename or "").strip().strip('"')
401
+ if base.lower().endswith((".gif", ".webp")): # strip the extension before sanitising
402
+ base = os.path.splitext(base)[0]
403
+ base = _sanitize(base).rstrip("_-") or "animation"
404
+ suffix = _sanitize((filename_suffix or "").strip().strip('"').lstrip("_- "))[:255]
405
+ mult = _sanitize((multip_suffix or "").strip().strip('"').lstrip("_- "))[:255]
406
+ if mult.isdigit() and not mult.lower().startswith("x"): # '4' -> 'x4', 'x4' stays 'x4'
407
+ mult = "x" + mult
408
+ tail = "_".join(p for p in (suffix, mult) if p) # both suffixes are always kept
409
+ max_name_len = 255 # single-file-name limit on NTFS / ext4
410
+ if tail:
411
+ room = max_name_len - len(tail) - 1 # -1 = the "_" separator after the name
412
+ if len(base) > room:
413
+ base = base[:max(room, 1)].rstrip("_-") # cut the END of the original name
414
+ name = f"{base}_{tail}"
415
+ else:
416
+ name = base[:max_name_len]
417
+ ext = ".webp" if output_format == "webp" else ".gif"
418
+ file = f"{name}{ext}"
419
+ i = 2
420
+ while os.path.exists(os.path.join(full_folder, file)): # never clobber an older file
421
+ file = f"{name}_{i}{ext}"
422
+ i += 1
423
+ path = os.path.join(full_folder, file)
424
+ try:
425
+ rel = os.path.relpath(full_folder, out_dir)
426
+ except ValueError:
427
+ rel = "" # different drive: the preview may not resolve, saving still works
428
+ subfolder = "" if rel in ("", ".") else rel.replace(os.sep, "/")
429
+
430
+ max_bytes = int(float(max_size_mb) * 1024 * 1024) if max_size_mb and max_size_mb > 0 else 0
431
+ file_info = ""
432
+ if output_format == "webp":
433
+ d_ms = core.quantize_delays_ms(delays, min_ms=min_cs * 10)
434
+
435
+ def write_webp(cfg, out):
436
+ core.save_webp(frames(), d_ms, out, loop=loop_count, lossless=cfg[0],
437
+ quality=cfg[1], method=webp_method, batch_size=batch_size)
438
+
439
+ if max_bytes:
440
+ sample = [_frame_u8(images, i) for i in core.spread_indices(n)]
441
+ top = int(quality)
442
+ ladder = ([(True, top)] if webp_lossless else []) + \
443
+ [(False, q) for q in range(100 if webp_lossless else top, -1, -1)]
444
+ est = core.webp_size_estimator(sample, n, webp_method)
445
+ cfg, size, fits = core.fit_to_size(ladder, est, write_webp, path, max_bytes)
446
+ del sample
447
+ file_info = (f"{size / 2**20:.2f} MB (limit {max_size_mb:g} MB), WebP "
448
+ + ("lossless" if cfg[0] else f"lossy quality {cfg[1]}")
449
+ + ("" if fits else " - STILL OVER THE LIMIT"))
450
+ print(f"[GIF Delay Tools] {file_info}")
451
+ else:
452
+ write_webp((bool(webp_lossless), int(quality)), path)
453
+ file_info = f"{os.path.getsize(path) / 2**20:.2f} MB"
454
+ saved = core.read_webp_delays(path) or d_ms[:1] # what is really in the file
455
+ else:
456
+ top_colors = core.gif_colors_for_quality(max_colors, quality)
457
+ use_ffmpeg = backend == "ffmpeg_palette" and core.find_ffmpeg() is not None
458
+ if backend == "ffmpeg_palette" and not use_ffmpeg:
459
+ print("[GIF Delay Tools] ffmpeg not found, using Pillow fallback.")
460
+
461
+ def write_gif(frame_iter, dcs, out, colors):
462
+ if use_ffmpeg:
463
+ core.save_gif_ffmpeg(frame_iter, dcs, out, loop=loop_count,
464
+ palette_mode=palette_mode, dither=dither,
465
+ max_colors=colors, optimize_size=optimize_size)
466
+ else:
467
+ core.save_gif_pillow(frame_iter, dcs, out, loop=loop_count,
468
+ dither=dither != "none", max_colors=colors,
469
+ batch_size=batch_size)
470
+
471
+ if max_bytes:
472
+ sample = [_frame_u8(images, i) for i in core.run_indices(n, 5, 4)]
473
+ est = core.gif_size_estimator(
474
+ sample, n, lambda fr, p, colors: write_gif(iter(fr), [10] * len(fr), p, colors))
475
+ # a coarse palette ladder: 55 vs 56 colours makes no difference, and every step of the
476
+ # search costs a real sample encode
477
+ steps = [256, 224, 192, 160, 128, 112, 96, 80, 64, 56, 48, 40, 32, 24, 16, 12, 8, 6, 4, 3, 2]
478
+ ladder = [top_colors] + [c for c in steps if c < top_colors]
479
+ colors, size, fits = core.fit_to_size(
480
+ ladder, est, lambda c, out: write_gif(frames(), delays_cs, out, c), path, max_bytes)
481
+ del sample
482
+ file_info = (f"{size / 2**20:.2f} MB (limit {max_size_mb:g} MB), GIF palette of {colors} colours"
483
+ + ("" if fits else " - STILL OVER THE LIMIT"))
484
+ print(f"[GIF Delay Tools] {file_info}")
485
+ else:
486
+ if top_colors < 256:
487
+ print(f"[GIF Delay Tools] GIF quality {quality} -> palette of {top_colors} colours")
488
+ write_gif(frames(), delays_cs, path, top_colors)
489
+ file_info = f"{os.path.getsize(path) / 2**20:.2f} MB"
490
+ saved = core.read_gif_delays(path) # what is really in the file
491
+ ui = {"images": [{"filename": file, "subfolder": subfolder, "type": save_to}]}
492
+ if animated_preview:
493
+ ui["animated"] = (True,)
494
+ return {"ui": ui, "result": (saved, _gif_info(saved), path, file_info)}
495
+
496
+
497
+ # ---------------------------------------------------------------- utilities
498
+ class GIFDelaysInfo:
499
+ @classmethod
500
+ def INPUT_TYPES(cls):
501
+ return {"required": {"delays": (GIF_DELAYS,)}}
502
+
503
+ RETURN_TYPES = ("FLOAT", "INT", "INT")
504
+ RETURN_NAMES = ("avg_fps", "min_ms", "max_ms")
505
+ FUNCTION = "run"
506
+ CATEGORY = CATEGORY
507
+
508
+ def run(self, delays):
509
+ d = [int(round(x)) for x in delays]
510
+ return (float(core.avg_fps(d)), min(d), max(d))
511
+
512
+
513
+ class GIFDelaysFromFPS:
514
+ """Constant delays for any IMAGE batch (e.g. a video)."""
515
+ @classmethod
516
+ def INPUT_TYPES(cls):
517
+ return {"required": {"images": ("IMAGE",),
518
+ "fps": ("FLOAT", {"default": 10.0, "min": 0.1, "max": 100.0, "step": 0.1})}}
519
+
520
+ RETURN_TYPES = (GIF_DELAYS, "FLOAT")
521
+ RETURN_NAMES = ("delays", "avg_fps")
522
+ FUNCTION = "run"
523
+ CATEGORY = CATEGORY
524
+
525
+ def run(self, images, fps):
526
+ cs = core.quantize_delays_cs([1000.0 / fps] * images.shape[0], min_cs=1)
527
+ d = [c * 10 for c in cs]
528
+ return (d, float(core.avg_fps(d)))
529
+
530
+
531
+ class GIFPlanInterpolation:
532
+ """Computes the RIFE multiplier so the result does not exceed target fps."""
533
+ @classmethod
534
+ def INPUT_TYPES(cls):
535
+ return {"required": {
536
+ "delays": (GIF_DELAYS,),
537
+ "target_fps": ("FLOAT", {"default": 50.0, "min": 1.0, "max": 100.0, "step": 1.0}),
538
+ "reference": (["average_fps", "median_delay", "minimum_fps", "maximum_fps"], {"tooltip":
539
+ "Which speed of the source gif decides the multiplier.\n"
540
+ "average_fps: overall average. median_delay: typical frame.\n"
541
+ "minimum_fps: the SLOWEST part of the gif (longest delay) -> bigger multiplier.\n"
542
+ "maximum_fps: the FASTEST part of the gif (shortest delay) -> smaller multiplier, "
543
+ "nothing exceeds the target."}),
544
+ "max_multiplier": ("INT", {"default": 16, "min": 1, "max": 64}),
545
+ }}
546
+
547
+ RETURN_TYPES = ("INT", "FLOAT", "FLOAT")
548
+ RETURN_NAMES = ("multiplier", "source_fps", "resulting_fps")
549
+ FUNCTION = "run"
550
+ CATEGORY = CATEGORY
551
+
552
+ def run(self, delays, target_fps, reference, max_multiplier):
553
+ m, src = core.plan_multiplier(delays, target_fps, reference, max_multiplier)
554
+ return (int(m), float(src), float(src * m))
555
+
556
+
557
+ class GIFDeduplicate:
558
+ """Merge consecutive duplicate frames and add their delays together."""
559
+ @classmethod
560
+ def INPUT_TYPES(cls):
561
+ return {"required": {
562
+ "images": ("IMAGE",),
563
+ "delays": (GIF_DELAYS,),
564
+ "similarity_threshold": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 30.0, "step": 0.1,
565
+ "tooltip": "0 = exact duplicates only (lossless). Otherwise max pixel difference "
566
+ "(0-255 levels) still counted as the same frame."}),
567
+ "comparison_mode": (["strict_max_difference", "mean_difference"], {"tooltip":
568
+ "strict: no single pixel may differ more than the threshold. "
569
+ "mean: average difference (can hide small visible changes)."}),
570
+ "compare_against": (["group_first_frame", "previous_frame"], {"tooltip":
571
+ "group_first_frame avoids slow drift being merged away."}),
572
+ }}
573
+
574
+ RETURN_TYPES = ("IMAGE", GIF_DELAYS, "INT", "STRING", "STRING")
575
+ RETURN_NAMES = ("images", "delays", "removed_frames", "gif_info", "summary")
576
+ FUNCTION = "run"
577
+ CATEGORY = CATEGORY
578
+
579
+ def run(self, images, delays, similarity_threshold, comparison_mode, compare_against):
580
+ n = images.shape[0]
581
+ if len(delays) != n:
582
+ raise ValueError(f"{n} images but {len(delays)} delays. They must match.")
583
+ keep, merged = core.dedupe_frames(_LazyU8(images), list(delays), similarity_threshold,
584
+ comparison_mode, compare_against)
585
+ out = images if len(keep) == n else images[torch.as_tensor(keep, dtype=torch.long)] # nothing removed: no copy
586
+ summary = (f"{n} -> {len(keep)} frames ({n - len(keep)} removed); duration "
587
+ f"{int(sum(delays))} ms -> {sum(merged)} ms")
588
+ print(f"[GIF Delay Tools] dedupe: {summary}")
589
+ return (out, merged, n - len(keep), _gif_info(merged), summary)
590
+
591
+
592
+ class GIFLoopPair:
593
+ """[last, first] pair to interpolate for a seamless loop transition."""
594
+ @classmethod
595
+ def INPUT_TYPES(cls):
596
+ return {"required": {"images": ("IMAGE",)}}
597
+
598
+ RETURN_TYPES = ("IMAGE",)
599
+ RETURN_NAMES = ("last_first_pair",)
600
+ FUNCTION = "run"
601
+ CATEGORY = CATEGORY
602
+
603
+ def run(self, images):
604
+ if images.shape[0] < 2:
605
+ raise ValueError("Need at least 2 frames for a loop transition")
606
+ return (torch.cat([images[-1:], images[:1]], dim=0),)
607
+
608
+
609
+ class GIFDelayAwareInterpolation:
610
+ """
611
+ Rebuilds frames + delays after RIFE so the original rhythm survives.
612
+ """
613
+ @classmethod
614
+ def INPUT_TYPES(cls):
615
+ return {
616
+ "required": {
617
+ "original_delays": (GIF_DELAYS,),
618
+ "interpolated_images": ("IMAGE", {"tooltip":
619
+ "Output of FrameInterpolate on the original frames: (N-1)*m+1 frames."}),
620
+ "timing_mode": (core.TIMING_MODES, {"tooltip":
621
+ "keep_original_delays: the original frames keep their delays, the new frames get "
622
+ "interp_delay_ms.\n"
623
+ "uniform_delays: EVERY frame (old and new) gets the same delay -> constant speed. "
624
+ "With 'allow longer' OFF the delay is chosen so the gif keeps its original duration. "
625
+ "'deduce' is ignored.\n"
626
+ "smart_delays: the new frames glide at the pace of the original frame they follow. "
627
+ "Frames longer than 2x the average ('holds') do not slow the glide down. "
628
+ "interp_delay_ms is ignored."}),
629
+ "deduce_from_original": (core.DEDUCE_MODES, {"default": "deduce", "tooltip":
630
+ "deduce: the time of the new frames is taken out of the original frame's delay "
631
+ "(the original frame gets shorter).\n"
632
+ "deduce - not held frame: same, but frames whose delay is 2x the average or more "
633
+ "('held' frames) keep their full delay. They are still interpolated, and their new "
634
+ "frames are added on top (the gif gets longer by that amount).\n"
635
+ "don't deduce: originals always keep their full delay, the gif gets longer.\n"
636
+ "'uniform_delays' ignores this (except for the loop transition)."}),
637
+ "allow_longer": ("BOOLEAN", {"default": True, "tooltip":
638
+ "ON: keep every new frame, the gif may get longer. OFF: keep the original total "
639
+ "duration; new frames that do not fit are dropped.\n"
640
+ "With \'don\'t deduce\' there is no time left for new frames in keep_original_delays, so they are all dropped (smart_delays keeps them on top). Held frames of 'deduce - not held frame' always keep all their new frames.\n"
641
+ "The loop transition follows the same rules: with 'deduce' ON its time comes out of "
642
+ "the LAST frame's delay; with 'deduce' OFF it is added on top."}),
643
+ "max_fps": ("FLOAT", {"default": 50.0, "min": 1.0, "max": 100.0, "step": 1.0}),
644
+ "interp_delay_ms": ("INT", {"default": 0, "min": 0, "max": 5000, "step": 10, "tooltip":
645
+ "Delay of the new frames ('uniform_delays': of ALL frames). 0 = fastest allowed by "
646
+ "max_fps (20 ms at 50 fps). Ignored by 'smart_delays'."}),
647
+ "looping": ("BOOLEAN", {"default": True, "tooltip":
648
+ "ON: insert the interpolated last->first transition (seamless loop). With 'deduce' ON "
649
+ "its time is taken out of the last frame's delay, with 'deduce' OFF it is added on top. "
650
+ "OFF: non-looping gif."}),
651
+ "held_frame_factor": ("FLOAT", {"default": 2.0, "min": 1.1, "max": 10.0, "step": 0.1, "tooltip":
652
+ "A frame is 'held' when its delay is at least this many times the AVERAGE delay "
653
+ "(2.0 = twice the average). Used by 'deduce - not held frame' and by the hold cap of "
654
+ "'smart_delays'. Lower = more frames count as held."}),
655
+ },
656
+ "optional": {
657
+ "loop_interpolated": ("IMAGE", {"tooltip":
658
+ "Interpolated [last, first] pair (m+1 frames). Its middle frames are inserted "
659
+ "after the last frame for a seamless loop."}),
660
+ },
661
+ }
662
+
663
+ RETURN_TYPES = ("IMAGE", GIF_DELAYS, "STRING", "STRING")
664
+ RETURN_NAMES = ("images", "delays", "multiplier", "gif_info")
665
+ FUNCTION = "run"
666
+ CATEGORY = CATEGORY
667
+
668
+ def run(self, original_delays, interpolated_images, timing_mode, deduce_from_original,
669
+ allow_longer, max_fps, interp_delay_ms, looping=True, held_frame_factor=2.0,
670
+ loop_interpolated=None):
671
+ min_ms = core.min_delay_cs_for_fps(max_fps) * 10
672
+ interp_ms = max(min_ms, int(interp_delay_ms) if interp_delay_ms > 0 else min_ms)
673
+ n_orig = len(original_delays)
674
+
675
+ total_interp = int(interpolated_images.shape[0])
676
+ mid = None
677
+ loop_k = 0
678
+ if looping and loop_interpolated is not None and n_orig >= 2:
679
+ mid = loop_interpolated[1:-1] # view, no copy
680
+ loop_k = int(mid.shape[0])
681
+ if loop_k == 0:
682
+ mid = None
683
+
684
+ idx, delays = core.build_timeline(
685
+ list(original_delays), total_interp, timing_mode,
686
+ deduce_from_original, allow_longer, interp_ms, min_ms, loop_k=loop_k,
687
+ held_factor=held_frame_factor)
688
+
689
+ if mid is None and idx == list(range(total_interp)):
690
+ out = interpolated_images # nothing dropped or added: reuse, zero copies
691
+ else:
692
+ shape = (len(idx),) + tuple(interpolated_images.shape[1:])
693
+ if interpolated_images.device.type == "cpu":
694
+ _check_ram(int(np.prod(shape)) * interpolated_images.element_size(),
695
+ "GIF Delay-Aware Interpolation")
696
+ out = torch.empty(shape, dtype=interpolated_images.dtype,
697
+ device=interpolated_images.device)
698
+ for o, k in enumerate(idx):
699
+ out[o] = interpolated_images[k] if k < total_interp else mid[k - total_interp]
700
+ mult = core.infer_multiplier(n_orig, interpolated_images.shape[0])
701
+ return (out, delays, f"x{int(mult)}", _gif_info(delays))
702
+
703
+
704
+ class GIFBatchInterpolate:
705
+ """
706
+ Batched frame interpolation — drop-in replacement for ComfyUI's FrameInterpolate.
707
+ Uses float16 accumulation (halves peak RAM) and clears GPU caches in blocks
708
+ to stay well within memory limits on large GIFs.
709
+ """
710
+ @classmethod
711
+ def INPUT_TYPES(cls):
712
+ return {
713
+ "required": {
714
+ "interp_model": ("INTERP_MODEL",),
715
+ "images": ("IMAGE",),
716
+ "multiplier": ("INT", {"default": 2, "min": 2, "max": 64}),
717
+ },
718
+ "optional": {
719
+ "batch_size": ("INT", {"default": 10, "min": 1, "max": 1000, "tooltip":
720
+ "Process this many frame pairs before clearing GPU caches. "
721
+ "Lower = less peak memory usage, slightly slower due to cache overhead."}),
722
+ "force_custom_multiplier": ("INT", {"default": 0, "min": 0, "max": 16, "step": 1, "tooltip":
723
+ "0 = off (use the multiplier input). 1 = FORCE x1: no interpolation at all, the frames "
724
+ "pass through untouched (only the timing changes downstream). 2-16 = FORCE this "
725
+ "multiplier, ignoring the multiplier input (e.g. from GIF Plan Interpolation). Use the "
726
+ "SAME value on the [last, first] loop-pair interpolation, and keep allow_longer ON in "
727
+ "GIF Delay-Aware Interpolation so none of the frames is dropped."}),
728
+ "output_device": (["auto", "ram", "vram"], {"default": "auto", "tooltip":
729
+ "Where the output batch lives.\n"
730
+ "auto: in VRAM when it fits with head-room (the model is loaded first, so the free VRAM is known), "
731
+ "otherwise in RAM.\n"
732
+ "ram: always RAM (ComfyUI offload device).\n"
733
+ "vram: always the GPU (falls back to RAM if it does not fit). Saves a lot of RAM; the batch "
734
+ "stays in VRAM for as long as ComfyUI keeps this node's result, so use ram if the nodes after it run out of VRAM."}),
735
+ },
736
+ }
737
+
738
+ RETURN_TYPES = ("IMAGE",)
739
+ RETURN_NAMES = ("images",)
740
+ FUNCTION = "interpolate"
741
+ CATEGORY = CATEGORY
742
+
743
+ def interpolate(self, interp_model, images, multiplier, batch_size=10, force_custom_multiplier=0,
744
+ output_device="auto"):
745
+ # 0 = off, 1 = forced x1 (no interpolation: the frames are returned as they are), 2-16 = forced
746
+ if int(force_custom_multiplier) >= 1:
747
+ multiplier = int(force_custom_multiplier)
748
+ from comfy import model_management
749
+ import comfy.utils
750
+ from tqdm import tqdm
751
+
752
+ offload_device = model_management.intermediate_device()
753
+ num_frames = images.shape[0]
754
+ if num_frames < 2 or multiplier < 2:
755
+ return (images,)
756
+
757
+ device = interp_model.load_device
758
+ dtype = interp_model.model_dtype()
759
+ inference_model = interp_model.model
760
+ activation_mem = inference_model.memory_used_forward(images.shape, dtype)
761
+ model_management.load_models_gpu([interp_model], memory_required=activation_mem)
762
+ align = getattr(inference_model, "pad_align", 1)
763
+ H, W = images.shape[1], images.shape[2]
764
+
765
+ def prepare_frame(idx):
766
+ frame = images[idx:idx + 1].movedim(-1, 1).to(dtype=dtype, device=device)
767
+ if align > 1:
768
+ from comfy.ldm.common_dit import pad_to_patch_size
769
+ frame = pad_to_patch_size(frame, (align, align), padding_mode="reflect")
770
+ return frame
771
+
772
+ total_pairs = num_frames - 1
773
+ num_interp = multiplier - 1
774
+ total_steps = total_pairs * num_interp
775
+ pbar = comfy.utils.ProgressBar(total_steps)
776
+ tqdm_bar = tqdm(total=total_steps, desc="GIF Batch Interpolate")
777
+
778
+ # Key difference from FrameInterpolate: force float16 accumulator.
779
+ # This halves peak RAM: 57.4 GB (float32) -> 28.7 GB (float16), fits in 64 GB.
780
+ out_dtype = torch.float16
781
+ total_out_frames = total_pairs * multiplier + 1
782
+ out_dev = _pick_output_device(output_device, total_out_frames * H * W * 3 * 2, device,
783
+ offload_device, activation_mem)
784
+ # BHWC and contiguous from the start: downstream nodes never need a second full copy
785
+ result = _alloc_output((total_out_frames, H, W, 3), out_dtype, out_dev, offload_device,
786
+ "GIF Batch Interpolate")
787
+ result[0] = images[0][..., :3].to(out_dtype)
788
+ out_idx = 1
789
+
790
+ # Pre-compute timestep tensor on device (padded dimensions needed)
791
+ sample = prepare_frame(0)
792
+ pH, pW = sample.shape[2], sample.shape[3]
793
+ t_values = [t / multiplier for t in range(1, multiplier)]
794
+ ts_full = torch.tensor(t_values, device=device, dtype=dtype).reshape(num_interp, 1, 1, 1)
795
+ ts_full = ts_full.expand(-1, 1, pH, pW)
796
+ del sample
797
+
798
+ multi_fn = getattr(inference_model, "forward_multi_timestep", None)
799
+ feat_cache = {}
800
+ prev_frame = None
801
+ batch = num_interp # per-pair timestep batch, reduced on OOM
802
+
803
+ try:
804
+ for i in range(total_pairs):
805
+ img0_single = prev_frame if prev_frame is not None else prepare_frame(i)
806
+ img1_single = prepare_frame(i + 1)
807
+ prev_frame = img1_single
808
+
809
+ # Cache features: img1 of pair N becomes img0 of pair N+1
810
+ feat_cache["img0"] = (feat_cache.pop("next") if "next" in feat_cache
811
+ else inference_model.extract_features(img0_single))
812
+ feat_cache["img1"] = inference_model.extract_features(img1_single)
813
+ feat_cache["next"] = feat_cache["img1"]
814
+
815
+ used_multi = False
816
+ if multi_fn is not None:
817
+ try:
818
+ mids = multi_fn(img0_single, img1_single, t_values, cache=feat_cache)
819
+ result[out_idx:out_idx + num_interp] = mids[:, :, :H, :W].permute(0, 2, 3, 1).clamp(0.0, 1.0).to(out_dtype)
820
+ out_idx += num_interp
821
+ pbar.update(num_interp)
822
+ tqdm_bar.update(num_interp)
823
+ used_multi = True
824
+ except model_management.OOM_EXCEPTION:
825
+ model_management.soft_empty_cache()
826
+ multi_fn = None # fall through to single-timestep path
827
+
828
+ if not used_multi:
829
+ j = 0
830
+ while j < num_interp:
831
+ b = min(batch, num_interp - j)
832
+ try:
833
+ img0 = img0_single.expand(b, -1, -1, -1)
834
+ img1 = img1_single.expand(b, -1, -1, -1)
835
+ mids = inference_model(img0, img1, timestep=ts_full[j:j + b], cache=feat_cache)
836
+ result[out_idx:out_idx + b] = mids[:, :, :H, :W].permute(0, 2, 3, 1).clamp(0.0, 1.0).to(out_dtype)
837
+ out_idx += b
838
+ pbar.update(b)
839
+ tqdm_bar.update(b)
840
+ j += b
841
+ except model_management.OOM_EXCEPTION:
842
+ if batch <= 1:
843
+ raise
844
+ batch = max(1, batch // 2)
845
+ model_management.soft_empty_cache()
846
+
847
+ result[out_idx] = images[i + 1][..., :3].to(out_dtype)
848
+ out_idx += 1
849
+
850
+ # Clear GPU caches every batch_size pairs to free intermediate tensors
851
+ if batch_size > 0 and (i + 1) % batch_size == 0 and i + 1 < total_pairs:
852
+ if torch.cuda.is_available():
853
+ torch.cuda.empty_cache()
854
+ model_management.soft_empty_cache()
855
+ finally:
856
+ tqdm_bar.close()
857
+
858
+ return (result,)
859
+
860
+
861
+ class GIFFusedInterpolate:
862
+ """
863
+ Delay-aware interpolation in ONE step (RIFE + timeline).
864
+
865
+ The separate pipeline (Batch Interpolate -> Delay-Aware Interpolation) first creates
866
+ EVERY in-between frame (original x multiplier) and only afterwards throws away the ones
867
+ that do not fit the timing. This node plans the timeline first and asks RIFE only for the
868
+ frames that will really be in the final gif, so RAM scales with the FINAL frame count.
869
+ The loop transition (last -> first) is computed here too: no GIF Loop Pair needed.
870
+ """
871
+ @classmethod
872
+ def INPUT_TYPES(cls):
873
+ return {
874
+ "required": {
875
+ "interp_model": ("INTERP_MODEL",),
876
+ "images": ("IMAGE", {"tooltip": "The ORIGINAL frames (e.g. after GIF Deduplicate)."}),
877
+ "original_delays": (GIF_DELAYS,),
878
+ "multiplier": ("INT", {"default": 4, "min": 1, "max": 64, "tooltip":
879
+ "Can be wired from GIF Plan Interpolation. Frames that do not fit the timing "
880
+ "are never computed, so a high multiplier no longer costs RAM."}),
881
+ "timing_mode": (core.TIMING_MODES,),
882
+ "deduce_from_original": (core.DEDUCE_MODES, {"default": "deduce", "tooltip":
883
+ "deduce: the time of the new frames comes out of the original frame's delay.\n"
884
+ "deduce - not held frame: same, but frames with a delay of 2x the average or more "
885
+ "keep their full delay (still interpolated, new frames added on top).\n"
886
+ "don't deduce: originals keep their full delay, the gif gets longer."}),
887
+ "allow_longer": ("BOOLEAN", {"default": True}),
888
+ "max_fps": ("FLOAT", {"default": 50.0, "min": 1.0, "max": 100.0, "step": 1.0}),
889
+ "interp_delay_ms": ("INT", {"default": 0, "min": 0, "max": 5000, "step": 10}),
890
+ "looping": ("BOOLEAN", {"default": True, "tooltip":
891
+ "Insert the interpolated last->first transition (seamless loop)."}),
892
+ "output_dtype": (["float16", "float32"], {"default": "float16", "tooltip":
893
+ "float16 halves RAM. GIF/WebP Save handles both."}),
894
+ "clear_cache_every": ("INT", {"default": 10, "min": 0, "max": 1000, "tooltip":
895
+ "Free GPU caches every N frame pairs (0 = never)."}),
896
+ "held_frame_factor": ("FLOAT", {"default": 2.0, "min": 1.1, "max": 10.0, "step": 0.1, "tooltip":
897
+ "A frame is 'held' when its delay is at least this many times the AVERAGE delay "
898
+ "(2.0 = twice the average). Used by 'deduce - not held frame' and by the hold cap of "
899
+ "'smart_delays'. Lower = more frames count as held."}),
900
+ "force_custom_multiplier": ("INT", {"default": 0, "min": 0, "max": 16, "step": 1, "tooltip":
901
+ "0 = off (use the multiplier input).\n"
902
+ "1 = FORCE x1: NO interpolation at all (RIFE is not even loaded). The original frames "
903
+ "are kept and only the timing settings are applied - use it to change the speed or just "
904
+ "convert to WebP/GIF.\n"
905
+ "2-16 = FORCE this multiplier, ignoring the multiplier input (e.g. from GIF Plan "
906
+ "Interpolation).\n"
907
+ "All other settings are respected, except 'allow_longer': with it OFF the frames that do "
908
+ "not fit would be dropped, so it is switched ON while a multiplier of 2 or more is forced "
909
+ "(not needed for uniform_delays, nor for x1)."}),
910
+ },
911
+ "optional": {
912
+ "output_device": (["auto", "ram", "vram"], {"default": "auto", "tooltip":
913
+ "Where the output batch lives.\n"
914
+ "auto: in VRAM when it fits with head-room (the model is loaded first, so the free VRAM is known), "
915
+ "otherwise in RAM.\n"
916
+ "ram: always RAM (ComfyUI offload device).\n"
917
+ "vram: always the GPU (falls back to RAM if it does not fit). Saves a lot of RAM; the batch "
918
+ "stays in VRAM for as long as ComfyUI keeps this node's result, so use ram if the nodes after it run out of VRAM."}),
919
+ },
920
+ }
921
+
922
+ RETURN_TYPES = ("IMAGE", GIF_DELAYS, "STRING", "STRING")
923
+ RETURN_NAMES = ("images", "delays", "multiplier", "gif_info")
924
+ FUNCTION = "run"
925
+ CATEGORY = CATEGORY
926
+
927
+ def run(self, interp_model, images, original_delays, multiplier, timing_mode,
928
+ deduce_from_original, allow_longer, max_fps, interp_delay_ms, looping,
929
+ output_dtype, clear_cache_every, held_frame_factor=2.0,
930
+ force_custom_multiplier=0, output_device="auto"):
931
+ from comfy import model_management
932
+ import comfy.utils
933
+ from tqdm import tqdm
934
+
935
+ n = int(images.shape[0])
936
+ if len(original_delays) != n:
937
+ raise ValueError(f"{n} images but {len(original_delays)} delays. They must match.")
938
+ m, allow_longer, force_note = core.apply_forced_multiplier(
939
+ multiplier, force_custom_multiplier, timing_mode, allow_longer)
940
+ if force_note:
941
+ print(f"[GIF Delay Tools] {force_note}")
942
+ min_ms = core.min_delay_cs_for_fps(max_fps) * 10
943
+ interp_ms = max(min_ms, int(interp_delay_ms) if interp_delay_ms > 0 else min_ms)
944
+
945
+ idx, delays, originals, jobs = core.plan_fused(
946
+ list(original_delays), m, timing_mode, deduce_from_original, allow_longer,
947
+ interp_ms, min_ms, looping=looping, held_factor=held_frame_factor)
948
+
949
+ H, W = int(images.shape[1]), int(images.shape[2])
950
+ out_dtype = torch.float16 if output_dtype == "float16" else torch.float32
951
+ offload_device = model_management.intermediate_device()
952
+ out_shape = (len(idx), H, W, 3)
953
+ out_bytes = len(idx) * H * W * 3 * (2 if output_dtype == "float16" else 4)
954
+ what = "GIF Delay-Aware Interpolate (fused)"
955
+
956
+ def fill_originals(out):
957
+ for o, i in originals:
958
+ out[o] = images[i][..., :3].to(out_dtype)
959
+
960
+ n_new = sum(len(j[3]) for j in jobs)
961
+ print(f"[GIF Delay Tools] fused: {n} originals x{m} -> {len(idx)} output frames "
962
+ f"({len(originals)} copied, {n_new} interpolated)")
963
+ if not jobs:
964
+ # nothing to interpolate (e.g. forced x1): plain copy, the model is not even loaded
965
+ out = _alloc_output(out_shape, out_dtype, offload_device, offload_device, what)
966
+ fill_originals(out)
967
+ return (out, delays, f"x{m}", _gif_info(delays))
968
+
969
+ device = interp_model.load_device
970
+ dtype = interp_model.model_dtype()
971
+ inference_model = interp_model.model
972
+ activation_mem = inference_model.memory_used_forward((1,) + tuple(images.shape[1:]), dtype)
973
+ model_management.load_models_gpu([interp_model], memory_required=activation_mem)
974
+ # the model is loaded now, so the free VRAM is known: decide where the output batch goes
975
+ out_dev = _pick_output_device(output_device, out_bytes, device, offload_device, activation_mem)
976
+ out = _alloc_output(out_shape, out_dtype, out_dev, offload_device, what)
977
+ fill_originals(out)
978
+ align = getattr(inference_model, "pad_align", 1)
979
+
980
+ def prepare_frame(i):
981
+ frame = images[i:i + 1].movedim(-1, 1).to(dtype=dtype, device=device)
982
+ if align > 1:
983
+ from comfy.ldm.common_dit import pad_to_patch_size
984
+ frame = pad_to_patch_size(frame, (align, align), padding_mode="reflect")
985
+ return frame
986
+
987
+ def store(pos, mids):
988
+ res = mids[:, :, :H, :W].permute(0, 2, 3, 1).clamp(0.0, 1.0).to(out_dtype)
989
+ out[pos:pos + res.shape[0]] = res
990
+
991
+ probe = prepare_frame(0)
992
+ pH, pW = probe.shape[2], probe.shape[3]
993
+ del probe
994
+
995
+ pbar = comfy.utils.ProgressBar(n_new)
996
+ tqdm_bar = tqdm(total=n_new, desc="GIF Fused Interpolate")
997
+ multi_fn = getattr(inference_model, "forward_multi_timestep", None)
998
+ batch = max(1, m - 1) # timesteps per forward call, halved on OOM
999
+ prev_b = prev_img1 = prev_f1 = None
1000
+ try:
1001
+ for ji, (a, b, o0, ts) in enumerate(jobs):
1002
+ if prev_b == a: # previous pair ended on this frame: reuse its features
1003
+ img0, f0 = prev_img1, prev_f1
1004
+ else:
1005
+ img0 = prepare_frame(a)
1006
+ f0 = inference_model.extract_features(img0)
1007
+ img1 = prepare_frame(b)
1008
+ f1 = inference_model.extract_features(img1)
1009
+ prev_b, prev_img1, prev_f1 = b, img1, f1
1010
+ cache = {"img0": f0, "img1": f1}
1011
+
1012
+ done = False
1013
+ if multi_fn is not None:
1014
+ try:
1015
+ store(o0, multi_fn(img0, img1, ts, cache=cache))
1016
+ done = True
1017
+ except model_management.OOM_EXCEPTION:
1018
+ model_management.soft_empty_cache()
1019
+ multi_fn = None # fall back to the single-timestep path
1020
+ if not done:
1021
+ j = 0
1022
+ while j < len(ts):
1023
+ bs = min(batch, len(ts) - j)
1024
+ try:
1025
+ tt = (torch.tensor(ts[j:j + bs], device=device, dtype=dtype)
1026
+ .reshape(bs, 1, 1, 1).expand(-1, 1, pH, pW))
1027
+ mids = inference_model(img0.expand(bs, -1, -1, -1),
1028
+ img1.expand(bs, -1, -1, -1),
1029
+ timestep=tt, cache=cache)
1030
+ store(o0 + j, mids)
1031
+ j += bs
1032
+ except model_management.OOM_EXCEPTION:
1033
+ if batch <= 1:
1034
+ raise
1035
+ batch = max(1, batch // 2)
1036
+ model_management.soft_empty_cache()
1037
+ pbar.update(len(ts))
1038
+ tqdm_bar.update(len(ts))
1039
+
1040
+ if clear_cache_every > 0 and (ji + 1) % clear_cache_every == 0 and ji + 1 < len(jobs):
1041
+ if torch.cuda.is_available():
1042
+ torch.cuda.empty_cache()
1043
+ model_management.soft_empty_cache()
1044
+ finally:
1045
+ tqdm_bar.close()
1046
+
1047
+ return (out, delays, f"x{m}", _gif_info(delays))
1048
+
1049
+
1050
+ NODE_CLASS_MAPPINGS = {
1051
+ "GIFLoadWithDelays": GIFLoadWithDelays,
1052
+ "GIFSaveWithDelays": GIFSaveWithDelays,
1053
+ "GIFDelaysInfo": GIFDelaysInfo,
1054
+ "GIFDelaysFromFPS": GIFDelaysFromFPS,
1055
+ "GIFPlanInterpolation": GIFPlanInterpolation,
1056
+ "GIFLoopPair": GIFLoopPair,
1057
+ "GIFDeduplicate": GIFDeduplicate,
1058
+ "GIFDelayAwareInterpolation": GIFDelayAwareInterpolation,
1059
+ "GIFBatchInterpolate": GIFBatchInterpolate,
1060
+ "GIFFusedInterpolate": GIFFusedInterpolate,
1061
+ }
1062
+ NODE_DISPLAY_NAME_MAPPINGS = {
1063
+ "GIFLoadWithDelays": "GIF/WebP Load (with delays)",
1064
+ "GIFSaveWithDelays": "GIF/WebP Save (delays + FFmpeg palette)",
1065
+ "GIFDelaysInfo": "GIF Delays Info",
1066
+ "GIFDelaysFromFPS": "GIF Delays From FPS",
1067
+ "GIFPlanInterpolation": "GIF Plan Interpolation (multiplier)",
1068
+ "GIFLoopPair": "GIF Loop Pair (last + first)",
1069
+ "GIFDeduplicate": "GIF Deduplicate (merge delays)",
1070
+ "GIFDelayAwareInterpolation": "GIF Delay-Aware Interpolation",
1071
+ "GIFBatchInterpolate": "GIF Batch Interpolate (low-memory RIFE)",
1072
+ "GIFFusedInterpolate": "GIF Delay-Aware Interpolate (fused, lowest RAM)",
1073
+ }
Delay aware Gif-Webp intepolation nodes+workflow V1.1.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:097b39a1ad91035ac03095666fa632042c50fffd897f350401018058cf98876a
3
+ size 288059
GIF INTERPOLATION WORKFLOW.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"id":"18fe56fc-68a0-4a1f-96b5-233b9475d638","revision":0,"last_node_id":23,"last_link_id":44,"nodes":[{"id":1,"type":"FrameInterpolationModelLoader","pos":[1199.3988636363565,-141.33873106060594],"size":[320,80],"flags":{},"order":0,"mode":0,"inputs":[{"localized_name":"model_name","name":"model_name","type":"COMBO","widget":{"name":"model_name"},"link":null}],"outputs":[{"localized_name":"INTERP_MODEL","name":"INTERP_MODEL","type":"INTERP_MODEL","links":[32]}],"properties":{"Node name for S&R":"FrameInterpolationModelLoader"},"widgets_values":["rife_v4.26.safetensors"],"widgets_values_named":{"model_name":"rife_v4.26.safetensors"}},{"id":2,"type":"GIFLoadWithDelays","pos":[459.49791666666664,-49.117708333333326],"size":[330,546],"flags":{},"order":1,"mode":0,"inputs":[{"localized_name":"gif","name":"gif","type":"COMBO","widget":{"name":"gif"},"link":null},{"localized_name":"transparent_background","name":"transparent_background","type":"COMBO","widget":{"name":"transparent_background"},"link":null},{"localized_name":"fix_browser_min_delay","name":"fix_browser_min_delay","type":"BOOLEAN","widget":{"name":"fix_browser_min_delay"},"link":null},{"localized_name":"skip_first_frames","name":"skip_first_frames","type":"INT","widget":{"name":"skip_first_frames"},"link":null},{"localized_name":"select_every_nth","name":"select_every_nth","type":"INT","widget":{"name":"select_every_nth"},"link":null},{"localized_name":"frame_load_cap","name":"frame_load_cap","type":"INT","widget":{"name":"frame_load_cap"},"link":null},{"localized_name":"custom_path","name":"custom_path","shape":7,"type":"STRING","widget":{"name":"custom_path"},"link":null},{"localized_name":"folder_start_index","name":"folder_start_index","shape":7,"type":"INT","widget":{"name":"folder_start_index"},"link":null},{"localized_name":"frame_storage","name":"frame_storage","shape":7,"type":"COMBO","widget":{"name":"frame_storage"},"link":null},{"localized_name":"upload","name":"upload","type":"IMAGEUPLOAD","widget":{"name":"upload"},"link":null}],"outputs":[{"localized_name":"images","name":"images","type":"IMAGE","links":[3]},{"localized_name":"delays","name":"delays","type":"GIF_DELAYS","links":[4]},{"localized_name":"gif_info","name":"gif_info","type":"STRING","links":[17]},{"localized_name":"filename","name":"filename","type":"STRING","links":[42]}],"properties":{"Node name for S&R":"GIFLoadWithDelays"},"widgets_values":["nopic.jpg","black",true,0,1,0,"",0,"vram_float16","image"],"widgets_values_named":{"gif":"nopic.jpg","transparent_background":"black","fix_browser_min_delay":true,"skip_first_frames":0,"select_every_nth":1,"frame_load_cap":0,"custom_path":"","folder_start_index":0,"frame_storage":"vram_float16","upload":"image"}},{"id":3,"type":"GIFPlanInterpolation","pos":[810.3673295454547,200.23484848484824],"size":[338.007205581665,181.99999504089354],"flags":{},"order":5,"mode":0,"inputs":[{"localized_name":"delays","name":"delays","type":"GIF_DELAYS","link":6},{"localized_name":"target_fps","name":"target_fps","type":"FLOAT","widget":{"name":"target_fps"},"link":null},{"localized_name":"reference","name":"reference","type":"COMBO","widget":{"name":"reference"},"link":null},{"localized_name":"max_multiplier","name":"max_multiplier","type":"INT","widget":{"name":"max_multiplier"},"link":null}],"outputs":[{"localized_name":"multiplier","name":"multiplier","type":"INT","links":[29]},{"localized_name":"source_fps","name":"source_fps","type":"FLOAT","links":[]},{"localized_name":"resulting_fps","name":"resulting_fps","type":"FLOAT","links":[]}],"properties":{"Node name for S&R":"GIFPlanInterpolation"},"widgets_values":[50,"average_fps",16],"widgets_values_named":{"target_fps":50,"reference":"average_fps","max_multiplier":16}},{"id":9,"type":"GIFDeduplicate","pos":[812.525,-44.633333333333326],"size":[300,190],"flags":{},"order":3,"mode":0,"inputs":[{"localized_name":"images","name":"images","type":"IMAGE","link":3},{"localized_name":"delays","name":"delays","type":"GIF_DELAYS","link":4},{"localized_name":"similarity_threshold","name":"similarity_threshold","type":"FLOAT","widget":{"name":"similarity_threshold"},"link":null},{"localized_name":"comparison_mode","name":"comparison_mode","type":"COMBO","widget":{"name":"comparison_mode"},"link":null},{"localized_name":"compare_against","name":"compare_against","type":"COMBO","widget":{"name":"compare_against"},"link":null}],"outputs":[{"localized_name":"images","name":"images","type":"IMAGE","links":[30]},{"localized_name":"delays","name":"delays","type":"GIF_DELAYS","links":[6,31]},{"localized_name":"removed_frames","name":"removed_frames","type":"INT","links":[]},{"localized_name":"gif_info","name":"gif_info","type":"STRING","links":[20]},{"localized_name":"summary","name":"summary","type":"STRING","links":[]}],"properties":{"Node name for S&R":"GIFDeduplicate"},"widgets_values":[0,"strict_max_difference","previous_frame"],"widgets_values_named":{"similarity_threshold":0,"comparison_mode":"strict_max_difference","compare_against":"previous_frame"}},{"id":8,"type":"GIFSaveWithDelays","pos":[1871.6854166666678,229.42500000000015],"size":[340,742],"flags":{},"order":9,"mode":0,"inputs":[{"localized_name":"images","name":"images","type":"IMAGE","link":37},{"localized_name":"delays","name":"delays","shape":7,"type":"GIF_DELAYS","link":40},{"localized_name":"save_location","name":"save_location","type":"STRING","widget":{"name":"save_location"},"link":null},{"localized_name":"filename","name":"filename","type":"STRING","widget":{"name":"filename"},"link":42},{"localized_name":"filename_suffix","name":"filename_suffix","type":"STRING","widget":{"name":"filename_suffix"},"link":null},{"localized_name":"multip_suffix","name":"multip_suffix","type":"STRING","widget":{"name":"multip_suffix"},"link":43},{"localized_name":"output_format","name":"output_format","type":"COMBO","widget":{"name":"output_format"},"link":null},{"localized_name":"webp_lossless","name":"webp_lossless","type":"BOOLEAN","widget":{"name":"webp_lossless"},"link":null},{"localized_name":"quality","name":"quality","type":"INT","widget":{"name":"quality"},"link":null},{"localized_name":"webp_method","name":"webp_method","type":"INT","widget":{"name":"webp_method"},"link":null},{"localized_name":"fallback_fps","name":"fallback_fps","type":"FLOAT","widget":{"name":"fallback_fps"},"link":null},{"localized_name":"max_fps","name":"max_fps","type":"FLOAT","widget":{"name":"max_fps"},"link":null},{"localized_name":"backend","name":"backend","type":"COMBO","widget":{"name":"backend"},"link":null},{"localized_name":"palette_mode","name":"palette_mode","type":"COMBO","widget":{"name":"palette_mode"},"link":null},{"localized_name":"dither","name":"dither","type":"COMBO","widget":{"name":"dither"},"link":null},{"localized_name":"max_colors","name":"max_colors","type":"INT","widget":{"name":"max_colors"},"link":null},{"localized_name":"loop_count","name":"loop_count","type":"INT","widget":{"name":"loop_count"},"link":null},{"localized_name":"optimize_size","name":"optimize_size","type":"BOOLEAN","widget":{"name":"optimize_size"},"link":null},{"localized_name":"batch_size","name":"batch_size","type":"INT","widget":{"name":"batch_size"},"link":null},{"localized_name":"save_to","name":"save_to","type":"COMBO","widget":{"name":"save_to"},"link":null},{"localized_name":"animated_preview","name":"animated_preview","type":"BOOLEAN","widget":{"name":"animated_preview"},"link":null},{"localized_name":"max_size_mb","name":"max_size_mb","shape":7,"type":"FLOAT","widget":{"name":"max_size_mb"},"link":null}],"outputs":[{"localized_name":"delays","name":"delays","type":"GIF_DELAYS","links":[]},{"localized_name":"gif_info","name":"gif_info","type":"STRING","links":[16]},{"localized_name":"filepath","name":"filepath","type":"STRING","links":[]},{"localized_name":"file_info","name":"file_info","type":"STRING","links":[44]}],"properties":{"Node name for S&R":"GIFSaveWithDelays"},"widgets_values":["GIFS/INTERPOLATED","webp","INTERP","webp","webp",false,90,4,10,50,"ffmpeg_palette","per_frame","sierra2_4a",256,0,true,100,"output",false,0],"widgets_values_named":{"save_location":"GIFS/INTERPOLATED","filename":"webp","filename_suffix":"INTERP","multip_suffix":"webp","output_format":"webp","webp_lossless":false,"quality":90,"webp_method":4,"fallback_fps":10,"max_fps":50,"backend":"ffmpeg_palette","palette_mode":"per_frame","dither":"sierra2_4a","max_colors":256,"loop_count":0,"optimize_size":true,"batch_size":100,"save_to":"output","animated_preview":false,"max_size_mb":0}},{"id":11,"type":"PreviewAny","pos":[463.91282291666687,-451.95633333333274],"size":[324.21995788574225,344.9099774169922],"flags":{},"order":4,"mode":0,"inputs":[{"localized_name":"source","name":"source","type":"*","link":17}],"outputs":[{"localized_name":"STRING","name":"STRING","type":"STRING","links":[]}],"properties":{"Node name for S&R":"PreviewAny"},"widgets_values":[],"widgets_values_named":{}},{"id":12,"type":"PreviewAny","pos":[813.3346979166668,-447.052166666666],"size":[330.34893506367996,338.7759948412577],"flags":{},"order":6,"mode":0,"inputs":[{"localized_name":"source","name":"source","type":"*","link":20}],"outputs":[{"localized_name":"STRING","name":"STRING","type":"STRING","links":[]}],"properties":{"Node name for S&R":"PreviewAny"},"widgets_values":[],"widgets_values_named":{}},{"id":13,"type":"PreviewAny","pos":[1577.9084668560627,-62.40945833333255],"size":[225,145.06144892374675],"flags":{},"order":8,"mode":0,"inputs":[{"localized_name":"source","name":"source","type":"*","link":39}],"outputs":[{"localized_name":"STRING","name":"STRING","type":"STRING","links":[]}],"properties":{"Node name for S&R":"PreviewAny"},"widgets_values":[],"widgets_values_named":{}},{"id":14,"type":"PreviewAny","pos":[1881.2169895833324,-166.28862499999997],"size":[324.21995788574225,344.9099774169922],"flags":{},"order":10,"mode":0,"inputs":[{"localized_name":"source","name":"source","type":"*","link":16}],"outputs":[{"localized_name":"STRING","name":"STRING","type":"STRING","links":[]}],"properties":{"Node name for S&R":"PreviewAny"},"widgets_values":[],"widgets_values_named":{}},{"id":19,"type":"GIFFusedInterpolate","pos":[1170.036999885453,11.421231382192808],"size":[362.843359375,382],"flags":{},"order":7,"mode":0,"inputs":[{"localized_name":"interp_model","name":"interp_model","type":"INTERP_MODEL","link":32},{"localized_name":"images","name":"images","type":"IMAGE","link":30},{"localized_name":"original_delays","name":"original_delays","type":"GIF_DELAYS","link":31},{"localized_name":"multiplier","name":"multiplier","type":"INT","widget":{"name":"multiplier"},"link":29},{"localized_name":"timing_mode","name":"timing_mode","type":"COMBO","widget":{"name":"timing_mode"},"link":null},{"localized_name":"deduce_from_original","name":"deduce_from_original","type":"COMBO","widget":{"name":"deduce_from_original"},"link":null},{"localized_name":"allow_longer","name":"allow_longer","type":"BOOLEAN","widget":{"name":"allow_longer"},"link":null},{"localized_name":"max_fps","name":"max_fps","type":"FLOAT","widget":{"name":"max_fps"},"link":null},{"localized_name":"interp_delay_ms","name":"interp_delay_ms","type":"INT","widget":{"name":"interp_delay_ms"},"link":null},{"localized_name":"looping","name":"looping","type":"BOOLEAN","widget":{"name":"looping"},"link":null},{"localized_name":"output_dtype","name":"output_dtype","type":"COMBO","widget":{"name":"output_dtype"},"link":null},{"localized_name":"clear_cache_every","name":"clear_cache_every","type":"INT","widget":{"name":"clear_cache_every"},"link":null},{"localized_name":"held_frame_factor","name":"held_frame_factor","type":"FLOAT","widget":{"name":"held_frame_factor"},"link":null},{"localized_name":"force_custom_multiplier","name":"force_custom_multiplier","type":"INT","widget":{"name":"force_custom_multiplier"},"link":null},{"localized_name":"output_device","name":"output_device","shape":7,"type":"COMBO","widget":{"name":"output_device"},"link":null}],"outputs":[{"localized_name":"images","name":"images","type":"IMAGE","links":[37]},{"localized_name":"delays","name":"delays","type":"GIF_DELAYS","links":[40]},{"localized_name":"multiplier","name":"multiplier","type":"STRING","links":[39,43]},{"localized_name":"gif_info","name":"gif_info","type":"STRING","links":null}],"properties":{"Node name for S&R":"GIFFusedInterpolate"},"widgets_values":[4,"keep_original_delays","deduce - not held frame",true,50,0,true,"float16",10,1.5,1,"auto"],"widgets_values_named":{"multiplier":4,"timing_mode":"keep_original_delays","deduce_from_original":"deduce - not held frame","allow_longer":true,"max_fps":50,"interp_delay_ms":0,"looping":true,"output_dtype":"float16","clear_cache_every":10,"held_frame_factor":1.5,"force_custom_multiplier":1,"output_device":"auto"}},{"id":22,"type":"Note","pos":[854.4188211977521,525.1784035428501],"size":[900,1100],"flags":{},"order":2,"mode":0,"inputs":[],"outputs":[],"properties":{},"widgets_values":["GIF DELAY TOOLS - EVERY SETTING EXPLAINED\n=========================================\n\nRECOMMENDED CHAIN (lowest RAM)\n GIF Load -> GIF Deduplicate -> GIF Delay-Aware Interpolate (fused) -> GIF Save\n (model from Frame Interpolation Model Loader; GIF Plan Interpolation can feed \"multiplier\")\nCLASSIC CHAIN (still works)\n GIF Load -> GIF Deduplicate -> GIF Batch Interpolate (frames) + GIF Loop Pair -> GIF Batch Interpolate (loop pair)\n -> GIF Delay-Aware Interpolation (+ loop_interpolated) -> GIF Save\nDelays are always in milliseconds. A GIF stores delays in 10 ms steps (centiseconds); the rounding error is\nspread over the frames so the total duration stays accurate.\n\n\n=== GIF LOAD (with delays) ===\ngif ............................ file from the ComfyUI input folder (.gif or .webp). Use \"upload\" to add one.\ncustom_path (optional) ......... empty: the gif/webp chosen in \"gif\" is loaded (the one you uploaded or picked).\n path to a FILE: that file is loaded, the dropdown is ignored.\n path to a FOLDER: FOLDER MODE. The dropdown is ignored and the .gif/.webp files of\n the folder are loaded one by one, ONE PER RUN: 1st click on Run = 1st file, 2nd click\n = 2nd file, and so on (natural order: gif2 before gif10; sub-folders are not read).\n After the last file it starts again from the first. \"Run (N)\" / batch count works\n too. The node always re-runs in folder mode, so everything after it re-runs as well.\nfolder_start_index ............. folder mode only: the file the sequence starts at (0 = first file). Change the value\n to restart the sequence from that file. It also restarts when the folder path\n changes or ComfyUI is restarted. Each Load node has its own counter.\nframe_storage (optional) .... where the loaded frames are kept. ram_float32 = ComfyUI standard (most RAM).\n ram_float16 = half the RAM, the 8-bit values stay exact. vram_float16 = the frames live\n on the GPU: almost no RAM is used, but they take as much VRAM as ram_float16 takes RAM\n for as long as ComfyUI keeps this node's result. Falls back to RAM if the VRAM is full.\n (The frames are also converted chunk by chunk now, which lowers the RAM peak while loading.)\ntransparent_background ......... colour that transparent pixels are painted on (black / white / gray / green).\n Frames are loaded as plain RGB, so transparency is lost.\nfix_browser_min_delay .......... ON: a GIF frame with a delay of 0 or 1 cs (0-10 ms) is treated as 100 ms, the way\n browsers play it (WebP: only a 0 ms delay). OFF: use the raw value.\nskip_first_frames .............. drop the first N frames. Their delay is dropped too.\nselect_every_nth ............... keep every Nth frame (1 = all). The delays of the skipped frames are ADDED to the\n kept frame, so the animation keeps its duration (it just gets choppier).\nframe_load_cap ................. maximum number of frames to keep (0 = no limit). Counted after skip / every_nth.\nOutputs: images, delays, gif_info (duration, frame count, average fps, delay list; in folder mode the first line\nis \"file 3/12: name.gif\"), filename (name of the loaded file without extension: handy for naming the saved result\nwhen you process a folder).\n\n\n=== GIF DEDUPLICATE (merge delays) ===\nMerges CONSECUTIVE identical frames into one and adds their delays together. The kept frames are untouched\noriginals and the total duration does not change. Put it right after the loader.\nsimilarity_threshold ........... 0 = only exactly identical frames (lossless). Otherwise the largest allowed\n difference, in colour levels (0-255), for two frames to count as the same.\ncomparison_mode ................ strict_max_difference: NO single pixel may differ by more than the threshold\n (never hides a small visible change). mean_difference: compares the average\n difference over the whole frame (can hide small local changes).\ncompare_against ................ previous_frame: compare with the frame just before. group_first_frame: compare\n with the first frame of the current group (stops slow drift from being merged away).\nOutputs: images, delays, removed_frames (count), gif_info, summary.\nIf nothing is removed the input batch is passed through without a copy.\n\n\n=== GIF PLAN INTERPOLATION ===\nComputes the interpolation multiplier so the result does not go above a target fps.\nmultiplier = floor(target_fps / source_fps), limited to 1..max_multiplier.\ntarget_fps ..................... the fps you do not want to exceed (default 50 = fastest speed browsers play reliably).\nreference ...................... which speed of the source decides source_fps:\n average_fps = overall average | median_delay = the typical frame |\n minimum_fps = the SLOWEST part (longest delay) -> bigger multiplier |\n maximum_fps = the FASTEST part (shortest delay) -> smaller multiplier.\nmax_multiplier ................. upper limit (default 16).\nOutputs: multiplier, source_fps, resulting_fps (= source_fps x multiplier).\n\n\n=== GIF DELAY-AWARE INTERPOLATE (fused, lowest RAM) ===\nDoes RIFE/FILM interpolation AND the timing in one step. It plans the final timeline first and only creates the\nframes that really end up in the GIF, so RAM depends on the FINAL frame count, not on originals x multiplier.\nThe seamless-loop transition (last -> first frame) is computed here too: no GIF Loop Pair needed.\nInputs: interp_model, images (the original frames), original_delays.\nmultiplier ..................... frames per original frame (x2, x4...). Can be wired from GIF Plan Interpolation.\n A high value costs time only for frames that are kept.\ntiming_mode .................... see TIMING MODES below.\ndeduce_from_original ........... see DEDUCE below.\nallow_longer ................... see ALLOW_LONGER below.\nmax_fps ........................ speed limit. The smallest delay allowed is ceil(100 / max_fps) cs: 50 fps = 20 ms.\ninterp_delay_ms ................ delay given to new frames (0 = the smallest allowed by max_fps). Used by\n keep_original_delays (new frames) and uniform_delays (all frames, when allow_longer\n is ON). Ignored by smart_delays.\nlooping ........................ ON: insert interpolated frames between the LAST and the FIRST frame so the loop is\n seamless. OFF: no transition (for gifs that do not loop).\noutput_dtype ................... float16 (default) uses half the RAM of float32. No visible difference for GIF/WebP.\nclear_cache_every .............. free GPU caches every N frame pairs (0 = never). Lower = less VRAM, slightly slower.\nheld_frame_factor .............. slider 1.1 - 10 (default 2.0). A frame is \"held\" when its delay is at least this many\n times the AVERAGE delay of the gif (2.0 = twice the average). It decides which frames\n count as held for \"deduce - not held frame\" AND for the hold cap of smart_delays.\n Lower = more frames count as held. Example: average 200 ms -> 2.0 means 400 ms or more,\n 1.5 means 300 ms or more, 4.0 means 800 ms or more.\nforce_custom_multiplier ........ slider 0 - 16 (the last of the main settings). 0 = off (the multiplier input is\n used). 1 = FORCE x1: NO interpolation at all (the model is not even loaded). The original\n frames are kept and only the timing settings (timing_mode, max_fps, interp_delay_ms...)\n are applied: use it to just change the speed or convert to WebP/GIF.\n 2 - 16 = FORCE that multiplier and ignore the multiplier input (for example the\n one coming from GIF Plan Interpolation). Every other setting is respected, except\n allow_longer: with it OFF, new frames that do not fit would be dropped, so the forced\n multiplier could not be honoured - it is switched ON while forcing x2 or more (the\n console prints a line when this happens). uniform_delays is not affected (it shortens\n the delay instead of dropping frames), and neither is x1 (there are no new frames).\n Things that cannot be avoided are still clamped: the delay of a frame never goes below\n the minimum of max_fps, so the gif can end up longer.\n NOTE: older workflows saved with the old \"1 = off\" value now force x1: set it to 0.\noutput_device (optional) .... where the OUTPUT batch lives (it is the big one). auto (default) = in VRAM when it fits\n with head-room, otherwise in RAM (the model is loaded first, so the free VRAM is known).\n ram = always RAM. vram = always the GPU (falls back to RAM if it does not fit). It stays\n in VRAM for as long as ComfyUI keeps the result: choose ram if later nodes run out of VRAM.\n With a forced x1 nothing is interpolated and the copy stays in RAM.\nOutputs: images, delays, multiplier (text), gif_info. Wire BOTH images and delays into GIF Save.\n\n\n=== TIMING MODES (timing_mode) ===\nkeep_original_delays\n Original frames keep their own delays (minus time given to new frames when deduce is on).\n Every new frame gets interp_delay_ms (20 ms at 50 fps).\nuniform_delays\n EVERY frame, old and new, gets the same delay -> constant speed. With allow_longer ON that delay is\n interp_delay_ms. With allow_longer OFF it is chosen so the GIF keeps its original duration. The deduce setting\n is ignored, except for the loop transition (with a deduce option it shares the original duration, with\n \"don't deduce\" it is added on top).\nsmart_delays\n New frames glide at the pace of the original frame they follow: k new frames share that frame's delay d, each\n getting d / (k + 1) (never less than the minimum delay). A frame whose delay is above held_frame_factor x the\n average (2x by default) is a \"hold\": its new frames glide at the capped pace held_frame_factor x average / (k + 1),\n so a long pause does not become a slow transition. interp_delay_ms is ignored.\n\n\n=== DEDUCE (deduce_from_original) ===\ndeduce\n The time of the new frames is taken OUT of the original frame's delay (the original frame gets shorter, never\n below the minimum delay). Example: 100 ms frame + 3 new frames of 20 ms -> original 40 ms, total still 100 ms.\ndeduce - not held frame\n Same as \"deduce\", EXCEPT for held frames: frames whose delay is held_frame_factor x the average delay or MORE\n (2x by default, adjustable with the held_frame_factor slider). A held frame keeps\n its full delay, but it is still interpolated as usual: all its new frames are kept and added ON TOP, so the GIF\n gets longer by the time of those frames. (allow_longer does not apply to held frames.)\n Example: delays 100, 100, 100, 500 (average 200, so 500 is held), x4, keep_original_delays:\n normal frames -> 40 + 20 + 20 + 20 (duration kept), held frame -> 500 + 20 + 20 + 20 (60 ms longer).\ndon't deduce\n Original frames always keep their full delay and the new frames are added on top: the GIF gets longer.\n (keep_original_delays + allow_longer OFF cannot add anything without changing the duration, so new frames are\n dropped there. smart_delays keeps them on top.)\nThe loop transition belongs to the LAST frame: with a deduce option its time comes out of the last frame's delay\n(unless the last frame is held); with \"don't deduce\" it is added on top.\n\n\n=== ALLOW_LONGER ===\nON - every new frame is kept, the GIF may get longer than the original.\nOFF - each frame keeps its original duration: only as many new frames as fit are kept, evenly spread.\nOnly relevant when a deduce option is used (held frames of \"deduce - not held frame\" are always kept in full).\n\n\n=== GIF LOOP PAIR / GIF BATCH INTERPOLATE / GIF DELAY-AWARE INTERPOLATION (classic chain) ===\nGIF Loop Pair: outputs the batch [last frame, first frame]. Interpolate it with the same multiplier as the frames.\nGIF Batch Interpolate (low-memory):\n multiplier ................... frames per original (minimum 2). Must be the SAME for frames and loop pair.\n batch_size ................... frame pairs processed before GPU caches are cleared. Lower = less VRAM.\n force_custom_multiplier ...... slider 0 - 16 (last setting). 0 = off. 1 = force x1 (no interpolation, the frames are\n returned untouched). 2 - 16 = use this multiplier instead of the\n multiplier input. Use the SAME value on the node that interpolates the [last, first]\n pair, and keep allow_longer ON in GIF Delay-Aware Interpolation, otherwise it drops\n the frames that do not fit.\n output_device (optional) ..... auto / ram / vram, same meaning as in the fused node (where the output batch lives).\n Creates EVERY in-between frame in float16 RAM; the fused node needs far less RAM.\nGIF Delay-Aware Interpolation: same timing settings as the fused node (timing_mode, deduce_from_original,\n allow_longer, max_fps, interp_delay_ms, looping, held_frame_factor). Extra inputs: interpolated_images must contain\n (N-1) x multiplier + 1 frames; loop_interpolated (optional) is the interpolated loop pair.\n\n\n=== GIF SAVE (delays + FFmpeg palette) ===\nimages / delays ................ wire the delays output of the interpolation node. Without delays, fallback_fps is used.\nsave_location .................. folder the file is saved into; absolute, or relative to the output/temp folder (empty = that folder).\nfilename ....................... name without extension; connect the load node's 'filename' output to keep the original name.\nfilename_suffix ................ added with an underscore: 1234 + interpolated -> 1234_interpolated.gif.\nmultip_suffix .................. second suffix after filename_suffix; connect the interpolation node's 'multiplier' output: 1234 + interp + x4 -> 1234_interp_x4.gif.\noutput_format .................. gif (256 colours per frame) or webp (full colour, optional lossless, ms delays).\nmax_fps ........................ hard speed cap (50 fps = 2 cs minimum delay). Shorter delays are raised to it.\nfallback_fps ................... speed used only when no delays are connected.\nquality ........................ 0 - 100, default 90, works for GIF AND WebP.\n GIF: 90-100 = the full palette (max_colors). Below 90 the palette shrinks linearly:\n about 200 colours at 70, 129 at 45, 58 at 20, 2 at 0 -> smaller files, more banding\n (a \"quality\" setting does not exist in the GIF format, so it controls the palette size;\n the dither setting is left as you chose it). Works with both backends.\n WebP: lossy = image quality, lossless = compression effort (higher = smaller, slower).\nloop_count ..................... 0 = loop forever, -1 = play once, N = repeat N times.\nsave_to ........................ output (kept) or temp (deleted by ComfyUI later).\nbatch_size ..................... frames encoded per chunk (GIF via Pillow, WebP). Lower = less RAM, slightly slower.\nanimated_preview ............... mark the preview as animated (desktop frontend). Turn off if your frontend shows none.\nGIF only:\n backend ...................... ffmpeg_palette (best quality, needs ffmpeg) or pillow_fallback (no ffmpeg needed).\n palette_mode ................. per_frame: every frame gets its own 256-colour palette (best). global: one palette\n for the whole gif (smaller file, more banding).\n dither ....................... none (banding) | floyd_steinberg, sierra2, sierra2_4a (error diffusion, sierra2_4a is\n the gentlest and leaves frames that already have <=256 colours unchanged) |\n bayer (ordered pattern) | heckbert (simple, no real dither).\n max_colors ................... 2-256 colours per palette at best quality (the quality slider can lower it).\n optimize_size ................ smaller file via transparency/rectangle tricks, but 255 colours and not lossless.\nWebP only:\n webp_lossless ................ ON = exact pixels (big files), OFF = lossy (much smaller).\n webp_method .................. encoder effort 0 (fast) - 6 (slowest, smallest).\nOutputs: delays, gif_info, filepath.\n\n\n=== HELPERS ===\nGIF Delays Info ................ delays -> avg_fps, min_ms, max_ms.\nGIF Delays From FPS ............ images + fps -> constant delays (for a video / image batch), plus avg_fps."],"widgets_values_named":{"text":"GIF DELAY TOOLS - EVERY SETTING EXPLAINED\n=========================================\n\nRECOMMENDED CHAIN (lowest RAM)\n GIF Load -> GIF Deduplicate -> GIF Delay-Aware Interpolate (fused) -> GIF Save\n (model from Frame Interpolation Model Loader; GIF Plan Interpolation can feed \"multiplier\")\nCLASSIC CHAIN (still works)\n GIF Load -> GIF Deduplicate -> GIF Batch Interpolate (frames) + GIF Loop Pair -> GIF Batch Interpolate (loop pair)\n -> GIF Delay-Aware Interpolation (+ loop_interpolated) -> GIF Save\nDelays are always in milliseconds. A GIF stores delays in 10 ms steps (centiseconds); the rounding error is\nspread over the frames so the total duration stays accurate.\n\n\n=== GIF LOAD (with delays) ===\ngif ............................ file from the ComfyUI input folder (.gif or .webp). Use \"upload\" to add one.\ncustom_path (optional) ......... empty: the gif/webp chosen in \"gif\" is loaded (the one you uploaded or picked).\n path to a FILE: that file is loaded, the dropdown is ignored.\n path to a FOLDER: FOLDER MODE. The dropdown is ignored and the .gif/.webp files of\n the folder are loaded one by one, ONE PER RUN: 1st click on Run = 1st file, 2nd click\n = 2nd file, and so on (natural order: gif2 before gif10; sub-folders are not read).\n After the last file it starts again from the first. \"Run (N)\" / batch count works\n too. The node always re-runs in folder mode, so everything after it re-runs as well.\nfolder_start_index ............. folder mode only: the file the sequence starts at (0 = first file). Change the value\n to restart the sequence from that file. It also restarts when the folder path\n changes or ComfyUI is restarted. Each Load node has its own counter.\nframe_storage (optional) .... where the loaded frames are kept. ram_float32 = ComfyUI standard (most RAM).\n ram_float16 = half the RAM, the 8-bit values stay exact. vram_float16 = the frames live\n on the GPU: almost no RAM is used, but they take as much VRAM as ram_float16 takes RAM\n for as long as ComfyUI keeps this node's result. Falls back to RAM if the VRAM is full.\n (The frames are also converted chunk by chunk now, which lowers the RAM peak while loading.)\ntransparent_background ......... colour that transparent pixels are painted on (black / white / gray / green).\n Frames are loaded as plain RGB, so transparency is lost.\nfix_browser_min_delay .......... ON: a GIF frame with a delay of 0 or 1 cs (0-10 ms) is treated as 100 ms, the way\n browsers play it (WebP: only a 0 ms delay). OFF: use the raw value.\nskip_first_frames .............. drop the first N frames. Their delay is dropped too.\nselect_every_nth ............... keep every Nth frame (1 = all). The delays of the skipped frames are ADDED to the\n kept frame, so the animation keeps its duration (it just gets choppier).\nframe_load_cap ................. maximum number of frames to keep (0 = no limit). Counted after skip / every_nth.\nOutputs: images, delays, gif_info (duration, frame count, average fps, delay list; in folder mode the first line\nis \"file 3/12: name.gif\"), filename (name of the loaded file without extension: handy for naming the saved result\nwhen you process a folder).\n\n\n=== GIF DEDUPLICATE (merge delays) ===\nMerges CONSECUTIVE identical frames into one and adds their delays together. The kept frames are untouched\noriginals and the total duration does not change. Put it right after the loader.\nsimilarity_threshold ........... 0 = only exactly identical frames (lossless). Otherwise the largest allowed\n difference, in colour levels (0-255), for two frames to count as the same.\ncomparison_mode ................ strict_max_difference: NO single pixel may differ by more than the threshold\n (never hides a small visible change). mean_difference: compares the average\n difference over the whole frame (can hide small local changes).\ncompare_against ................ previous_frame: compare with the frame just before. group_first_frame: compare\n with the first frame of the current group (stops slow drift from being merged away).\nOutputs: images, delays, removed_frames (count), gif_info, summary.\nIf nothing is removed the input batch is passed through without a copy.\n\n\n=== GIF PLAN INTERPOLATION ===\nComputes the interpolation multiplier so the result does not go above a target fps.\nmultiplier = floor(target_fps / source_fps), limited to 1..max_multiplier.\ntarget_fps ..................... the fps you do not want to exceed (default 50 = fastest speed browsers play reliably).\nreference ...................... which speed of the source decides source_fps:\n average_fps = overall average | median_delay = the typical frame |\n minimum_fps = the SLOWEST part (longest delay) -> bigger multiplier |\n maximum_fps = the FASTEST part (shortest delay) -> smaller multiplier.\nmax_multiplier ................. upper limit (default 16).\nOutputs: multiplier, source_fps, resulting_fps (= source_fps x multiplier).\n\n\n=== GIF DELAY-AWARE INTERPOLATE (fused, lowest RAM) ===\nDoes RIFE/FILM interpolation AND the timing in one step. It plans the final timeline first and only creates the\nframes that really end up in the GIF, so RAM depends on the FINAL frame count, not on originals x multiplier.\nThe seamless-loop transition (last -> first frame) is computed here too: no GIF Loop Pair needed.\nInputs: interp_model, images (the original frames), original_delays.\nmultiplier ..................... frames per original frame (x2, x4...). Can be wired from GIF Plan Interpolation.\n A high value costs time only for frames that are kept.\ntiming_mode .................... see TIMING MODES below.\ndeduce_from_original ........... see DEDUCE below.\nallow_longer ................... see ALLOW_LONGER below.\nmax_fps ........................ speed limit. The smallest delay allowed is ceil(100 / max_fps) cs: 50 fps = 20 ms.\ninterp_delay_ms ................ delay given to new frames (0 = the smallest allowed by max_fps). Used by\n keep_original_delays (new frames) and uniform_delays (all frames, when allow_longer\n is ON). Ignored by smart_delays.\nlooping ........................ ON: insert interpolated frames between the LAST and the FIRST frame so the loop is\n seamless. OFF: no transition (for gifs that do not loop).\noutput_dtype ................... float16 (default) uses half the RAM of float32. No visible difference for GIF/WebP.\nclear_cache_every .............. free GPU caches every N frame pairs (0 = never). Lower = less VRAM, slightly slower.\nheld_frame_factor .............. slider 1.1 - 10 (default 2.0). A frame is \"held\" when its delay is at least this many\n times the AVERAGE delay of the gif (2.0 = twice the average). It decides which frames\n count as held for \"deduce - not held frame\" AND for the hold cap of smart_delays.\n Lower = more frames count as held. Example: average 200 ms -> 2.0 means 400 ms or more,\n 1.5 means 300 ms or more, 4.0 means 800 ms or more.\nforce_custom_multiplier ........ slider 0 - 16 (the last of the main settings). 0 = off (the multiplier input is\n used). 1 = FORCE x1: NO interpolation at all (the model is not even loaded). The original\n frames are kept and only the timing settings (timing_mode, max_fps, interp_delay_ms...)\n are applied: use it to just change the speed or convert to WebP/GIF.\n 2 - 16 = FORCE that multiplier and ignore the multiplier input (for example the\n one coming from GIF Plan Interpolation). Every other setting is respected, except\n allow_longer: with it OFF, new frames that do not fit would be dropped, so the forced\n multiplier could not be honoured - it is switched ON while forcing x2 or more (the\n console prints a line when this happens). uniform_delays is not affected (it shortens\n the delay instead of dropping frames), and neither is x1 (there are no new frames).\n Things that cannot be avoided are still clamped: the delay of a frame never goes below\n the minimum of max_fps, so the gif can end up longer.\n NOTE: older workflows saved with the old \"1 = off\" value now force x1: set it to 0.\noutput_device (optional) .... where the OUTPUT batch lives (it is the big one). auto (default) = in VRAM when it fits\n with head-room, otherwise in RAM (the model is loaded first, so the free VRAM is known).\n ram = always RAM. vram = always the GPU (falls back to RAM if it does not fit). It stays\n in VRAM for as long as ComfyUI keeps the result: choose ram if later nodes run out of VRAM.\n With a forced x1 nothing is interpolated and the copy stays in RAM.\nOutputs: images, delays, multiplier (text), gif_info. Wire BOTH images and delays into GIF Save.\n\n\n=== TIMING MODES (timing_mode) ===\nkeep_original_delays\n Original frames keep their own delays (minus time given to new frames when deduce is on).\n Every new frame gets interp_delay_ms (20 ms at 50 fps).\nuniform_delays\n EVERY frame, old and new, gets the same delay -> constant speed. With allow_longer ON that delay is\n interp_delay_ms. With allow_longer OFF it is chosen so the GIF keeps its original duration. The deduce setting\n is ignored, except for the loop transition (with a deduce option it shares the original duration, with\n \"don't deduce\" it is added on top).\nsmart_delays\n New frames glide at the pace of the original frame they follow: k new frames share that frame's delay d, each\n getting d / (k + 1) (never less than the minimum delay). A frame whose delay is above held_frame_factor x the\n average (2x by default) is a \"hold\": its new frames glide at the capped pace held_frame_factor x average / (k + 1),\n so a long pause does not become a slow transition. interp_delay_ms is ignored.\n\n\n=== DEDUCE (deduce_from_original) ===\ndeduce\n The time of the new frames is taken OUT of the original frame's delay (the original frame gets shorter, never\n below the minimum delay). Example: 100 ms frame + 3 new frames of 20 ms -> original 40 ms, total still 100 ms.\ndeduce - not held frame\n Same as \"deduce\", EXCEPT for held frames: frames whose delay is held_frame_factor x the average delay or MORE\n (2x by default, adjustable with the held_frame_factor slider). A held frame keeps\n its full delay, but it is still interpolated as usual: all its new frames are kept and added ON TOP, so the GIF\n gets longer by the time of those frames. (allow_longer does not apply to held frames.)\n Example: delays 100, 100, 100, 500 (average 200, so 500 is held), x4, keep_original_delays:\n normal frames -> 40 + 20 + 20 + 20 (duration kept), held frame -> 500 + 20 + 20 + 20 (60 ms longer).\ndon't deduce\n Original frames always keep their full delay and the new frames are added on top: the GIF gets longer.\n (keep_original_delays + allow_longer OFF cannot add anything without changing the duration, so new frames are\n dropped there. smart_delays keeps them on top.)\nThe loop transition belongs to the LAST frame: with a deduce option its time comes out of the last frame's delay\n(unless the last frame is held); with \"don't deduce\" it is added on top.\n\n\n=== ALLOW_LONGER ===\nON - every new frame is kept, the GIF may get longer than the original.\nOFF - each frame keeps its original duration: only as many new frames as fit are kept, evenly spread.\nOnly relevant when a deduce option is used (held frames of \"deduce - not held frame\" are always kept in full).\n\n\n=== GIF LOOP PAIR / GIF BATCH INTERPOLATE / GIF DELAY-AWARE INTERPOLATION (classic chain) ===\nGIF Loop Pair: outputs the batch [last frame, first frame]. Interpolate it with the same multiplier as the frames.\nGIF Batch Interpolate (low-memory):\n multiplier ................... frames per original (minimum 2). Must be the SAME for frames and loop pair.\n batch_size ................... frame pairs processed before GPU caches are cleared. Lower = less VRAM.\n force_custom_multiplier ...... slider 0 - 16 (last setting). 0 = off. 1 = force x1 (no interpolation, the frames are\n returned untouched). 2 - 16 = use this multiplier instead of the\n multiplier input. Use the SAME value on the node that interpolates the [last, first]\n pair, and keep allow_longer ON in GIF Delay-Aware Interpolation, otherwise it drops\n the frames that do not fit.\n output_device (optional) ..... auto / ram / vram, same meaning as in the fused node (where the output batch lives).\n Creates EVERY in-between frame in float16 RAM; the fused node needs far less RAM.\nGIF Delay-Aware Interpolation: same timing settings as the fused node (timing_mode, deduce_from_original,\n allow_longer, max_fps, interp_delay_ms, looping, held_frame_factor). Extra inputs: interpolated_images must contain\n (N-1) x multiplier + 1 frames; loop_interpolated (optional) is the interpolated loop pair.\n\n\n=== GIF SAVE (delays + FFmpeg palette) ===\nimages / delays ................ wire the delays output of the interpolation node. Without delays, fallback_fps is used.\nsave_location .................. folder the file is saved into; absolute, or relative to the output/temp folder (empty = that folder).\nfilename ....................... name without extension; connect the load node's 'filename' output to keep the original name.\nfilename_suffix ................ added with an underscore: 1234 + interpolated -> 1234_interpolated.gif.\nmultip_suffix .................. second suffix after filename_suffix; connect the interpolation node's 'multiplier' output: 1234 + interp + x4 -> 1234_interp_x4.gif.\noutput_format .................. gif (256 colours per frame) or webp (full colour, optional lossless, ms delays).\nmax_fps ........................ hard speed cap (50 fps = 2 cs minimum delay). Shorter delays are raised to it.\nfallback_fps ................... speed used only when no delays are connected.\nquality ........................ 0 - 100, default 90, works for GIF AND WebP.\n GIF: 90-100 = the full palette (max_colors). Below 90 the palette shrinks linearly:\n about 200 colours at 70, 129 at 45, 58 at 20, 2 at 0 -> smaller files, more banding\n (a \"quality\" setting does not exist in the GIF format, so it controls the palette size;\n the dither setting is left as you chose it). Works with both backends.\n WebP: lossy = image quality, lossless = compression effort (higher = smaller, slower).\nloop_count ..................... 0 = loop forever, -1 = play once, N = repeat N times.\nsave_to ........................ output (kept) or temp (deleted by ComfyUI later).\nbatch_size ..................... frames encoded per chunk (GIF via Pillow, WebP). Lower = less RAM, slightly slower.\nanimated_preview ............... mark the preview as animated (desktop frontend). Turn off if your frontend shows none.\nGIF only:\n backend ...................... ffmpeg_palette (best quality, needs ffmpeg) or pillow_fallback (no ffmpeg needed).\n palette_mode ................. per_frame: every frame gets its own 256-colour palette (best). global: one palette\n for the whole gif (smaller file, more banding).\n dither ....................... none (banding) | floyd_steinberg, sierra2, sierra2_4a (error diffusion, sierra2_4a is\n the gentlest and leaves frames that already have <=256 colours unchanged) |\n bayer (ordered pattern) | heckbert (simple, no real dither).\n max_colors ................... 2-256 colours per palette at best quality (the quality slider can lower it).\n optimize_size ................ smaller file via transparency/rectangle tricks, but 255 colours and not lossless.\nWebP only:\n webp_lossless ................ ON = exact pixels (big files), OFF = lossy (much smaller).\n webp_method .................. encoder effort 0 (fast) - 6 (slowest, smallest).\nOutputs: delays, gif_info, filepath.\n\n\n=== HELPERS ===\nGIF Delays Info ................ delays -> avg_fps, min_ms, max_ms.\nGIF Delays From FPS ............ images + fps -> constant delays (for a video / image batch), plus avg_fps."},"color":"#232","bgcolor":"#353"},{"id":23,"type":"PreviewAny","pos":[2290.2048060462344,-115.20038433593515],"size":[324.21995788574225,344.9099774169922],"flags":{},"order":11,"mode":0,"inputs":[{"localized_name":"source","name":"source","type":"*","link":44}],"outputs":[{"localized_name":"STRING","name":"STRING","type":"STRING","links":[]}],"properties":{"Node name for S&R":"PreviewAny"},"widgets_values":[],"widgets_values_named":{}}],"links":[[3,2,0,9,0,"IMAGE"],[4,2,1,9,1,"GIF_DELAYS"],[6,9,1,3,0,"GIF_DELAYS"],[16,8,1,14,0,"STRING"],[17,2,2,11,0,"STRING"],[20,9,3,12,0,"STRING"],[29,3,0,19,3,"INT"],[30,9,0,19,1,"IMAGE"],[31,9,1,19,2,"GIF_DELAYS"],[32,1,0,19,0,"INTERP_MODEL"],[39,19,2,13,0,"STRING"],[37,19,0,8,0,"IMAGE"],[40,19,1,8,1,"GIF_DELAYS"],[42,2,3,8,3,"STRING"],[43,19,2,8,5,"STRING"],[44,8,3,23,0,"STRING"]],"groups":[],"config":{},"extra":{"ds":{"scale":0.9869158878504688,"offset":[-387.3070787735098,293.5337176692671]}},"version":0.4}