Delete Delay aware Gif-Webp intepolation nodes
Browse files- Delay aware Gif-Webp intepolation nodes/README.md +0 -147
- Delay aware Gif-Webp intepolation nodes/SETTINGS_GUIDE.txt +0 -216
- Delay aware Gif-Webp intepolation nodes/__init__.py +0 -3
- Delay aware Gif-Webp intepolation nodes/__pycache__/__init__.cpython-313.pyc +0 -0
- Delay aware Gif-Webp intepolation nodes/__pycache__/gif_core.cpython-313.pyc +0 -0
- Delay aware Gif-Webp intepolation nodes/__pycache__/nodes.cpython-313.pyc +0 -0
- Delay aware Gif-Webp intepolation nodes/gif_core.py +0 -784
- Delay aware Gif-Webp intepolation nodes/nodes.py +0 -1022
Delay aware Gif-Webp intepolation nodes/README.md
DELETED
|
@@ -1,147 +0,0 @@
|
|
| 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 |
-
## Low-RAM pipeline: "GIF Delay-Aware Interpolate (fused, lowest RAM)"
|
| 115 |
-
|
| 116 |
-
The classic chain (GIF Batch Interpolate -> GIF Delay-Aware Interpolation) first builds EVERY
|
| 117 |
-
in-between frame (originals x multiplier) and only then drops the ones that do not fit the
|
| 118 |
-
timing. For big frames this needs gigabytes of RAM for frames that are thrown away.
|
| 119 |
-
|
| 120 |
-
The fused node plans the timeline first and asks RIFE only for the frames that end up in the
|
| 121 |
-
final gif, including the seamless-loop transition (no GIF Loop Pair needed).
|
| 122 |
-
|
| 123 |
-
Wiring: GIF Load -> GIF Deduplicate -> **GIF Delay-Aware Interpolate (fused)** -> GIF Save
|
| 124 |
-
(model from the interpolation model loader; `multiplier` can come from GIF Plan Interpolation).
|
| 125 |
-
|
| 126 |
-
RAM = final frame count x frame size (float16 by default). Rule of thumb for the final gif:
|
| 127 |
-
`duration / (1000 / max_fps)` frames. Lower `max_fps` or the resolution if that is still too much.
|
| 128 |
-
|
| 129 |
-
### Using VRAM instead of RAM
|
| 130 |
-
|
| 131 |
-
- **output_device** (fused node and GIF Batch Interpolate, `auto` / `ram` / `vram`): where the big
|
| 132 |
-
output batch lives. `auto` (default) keeps it in VRAM when it fits with head-room (checked after
|
| 133 |
-
the model is loaded), otherwise in RAM. `vram` forces the GPU (falls back to RAM if it does not
|
| 134 |
-
fit), `ram` is the old behaviour. The batch stays in VRAM while ComfyUI keeps the node's result,
|
| 135 |
-
so use `ram` if later nodes run out of VRAM. With a forced x1 nothing is interpolated and the copy
|
| 136 |
-
stays in RAM.
|
| 137 |
-
- **frame_storage** (GIF Load, optional, last setting): `ram_float32` (default, ComfyUI standard),
|
| 138 |
-
`ram_float16` (half the RAM, 8-bit values stay exact) or `vram_float16` (frames on the GPU,
|
| 139 |
-
almost no RAM). Frames are now converted chunk by chunk, which also lowers the RAM peak while
|
| 140 |
-
loading. Falls back to RAM if the VRAM is full.
|
| 141 |
-
- GIF Deduplicate no longer copies the batch when nothing is removed.
|
| 142 |
-
|
| 143 |
-
## Batch loading a folder (GIF Load)
|
| 144 |
-
|
| 145 |
-
Put a folder path in `custom_path` (instead of a file): the dropdown is ignored and each run loads the NEXT
|
| 146 |
-
.gif/.webp of that folder (natural order, wraps to the first file after the last). `folder_start_index` restarts
|
| 147 |
-
the sequence at a given file. A new `filename` output gives the loaded file's name (without extension).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Delay aware Gif-Webp intepolation nodes/SETTINGS_GUIDE.txt
DELETED
|
@@ -1,216 +0,0 @@
|
|
| 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 |
-
Outputs: delays, gif_info, filepath.
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
=== HELPERS ===
|
| 215 |
-
GIF Delays Info ................ delays -> avg_fps, min_ms, max_ms.
|
| 216 |
-
GIF Delays From FPS ............ images + fps -> constant delays (for a video / image batch), plus avg_fps.
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Delay aware Gif-Webp intepolation nodes/__init__.py
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
|
| 2 |
-
|
| 3 |
-
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
|
|
|
|
|
|
|
|
|
|
|
|
Delay aware Gif-Webp intepolation nodes/__pycache__/__init__.cpython-313.pyc
DELETED
|
Binary file (353 Bytes)
|
|
|
Delay aware Gif-Webp intepolation nodes/__pycache__/gif_core.cpython-313.pyc
DELETED
|
Binary file (40.2 kB)
|
|
|
Delay aware Gif-Webp intepolation nodes/__pycache__/nodes.cpython-313.pyc
DELETED
|
Binary file (58.8 kB)
|
|
|
Delay aware Gif-Webp intepolation nodes/gif_core.py
DELETED
|
@@ -1,784 +0,0 @@
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Delay aware Gif-Webp intepolation nodes/nodes.py
DELETED
|
@@ -1,1022 +0,0 @@
|
|
| 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 |
-
},
|
| 344 |
-
}
|
| 345 |
-
|
| 346 |
-
RETURN_TYPES = (GIF_DELAYS, "STRING", "STRING")
|
| 347 |
-
RETURN_NAMES = ("delays", "gif_info", "filepath")
|
| 348 |
-
FUNCTION = "save"
|
| 349 |
-
OUTPUT_NODE = True
|
| 350 |
-
CATEGORY = CATEGORY
|
| 351 |
-
|
| 352 |
-
def save(self, images, save_location, filename, filename_suffix, multip_suffix, output_format,
|
| 353 |
-
webp_lossless, quality, webp_method, fallback_fps, max_fps, backend,
|
| 354 |
-
palette_mode, dither, max_colors, loop_count, optimize_size, batch_size,
|
| 355 |
-
save_to, animated_preview=False, delays=None):
|
| 356 |
-
# Per-frame generator: converts one frame at a time from the ComfyUI tensor,
|
| 357 |
-
# so the full N×H×W×C array is never materialised in RAM.
|
| 358 |
-
n, h, w = images.shape[0], images.shape[1], images.shape[2]
|
| 359 |
-
|
| 360 |
-
def frames():
|
| 361 |
-
for i in range(n):
|
| 362 |
-
yield _frame_u8(images, i)
|
| 363 |
-
|
| 364 |
-
if delays is None:
|
| 365 |
-
delays = [1000.0 / fallback_fps] * n
|
| 366 |
-
if len(delays) != n:
|
| 367 |
-
raise ValueError(f"{n} images but {len(delays)} delays. They must match "
|
| 368 |
-
"(use 'GIF Delay-Aware Interpolation' to rebuild both together).")
|
| 369 |
-
|
| 370 |
-
min_cs = core.min_delay_cs_for_fps(max_fps)
|
| 371 |
-
delays_cs = core.quantize_delays_cs(delays, min_cs=min_cs)
|
| 372 |
-
|
| 373 |
-
# ---- where to save ---------------------------------------------------------
|
| 374 |
-
out_dir = folder_paths.get_output_directory() if save_to == "output" \
|
| 375 |
-
else folder_paths.get_temp_directory()
|
| 376 |
-
loc = (save_location or "").strip().strip('"').strip()
|
| 377 |
-
if loc:
|
| 378 |
-
loc = loc.replace("\\", os.sep)
|
| 379 |
-
if os.path.isabs(loc) or (len(loc) >= 2 and loc[1] == ":"):
|
| 380 |
-
full_folder = os.path.abspath(loc) # absolute: use as given
|
| 381 |
-
else:
|
| 382 |
-
full_folder = os.path.abspath(os.path.join(out_dir, loc)) # relative: under out_dir
|
| 383 |
-
else:
|
| 384 |
-
full_folder = out_dir
|
| 385 |
-
os.makedirs(full_folder, exist_ok=True)
|
| 386 |
-
|
| 387 |
-
# ---- file name: <name>[_<suffix>], the suffix is always kept --------
|
| 388 |
-
def _sanitize(name):
|
| 389 |
-
return "".join(c for c in name if c.isalnum() or c in "_-[]()")
|
| 390 |
-
base = (filename or "").strip().strip('"')
|
| 391 |
-
if base.lower().endswith((".gif", ".webp")): # strip the extension before sanitising
|
| 392 |
-
base = os.path.splitext(base)[0]
|
| 393 |
-
base = _sanitize(base).rstrip("_-") or "animation"
|
| 394 |
-
suffix = _sanitize((filename_suffix or "").strip().strip('"').lstrip("_- "))[:255]
|
| 395 |
-
mult = _sanitize((multip_suffix or "").strip().strip('"').lstrip("_- "))[:255]
|
| 396 |
-
if mult.isdigit() and not mult.lower().startswith("x"): # '4' -> 'x4', 'x4' stays 'x4'
|
| 397 |
-
mult = "x" + mult
|
| 398 |
-
tail = "_".join(p for p in (suffix, mult) if p) # both suffixes are always kept
|
| 399 |
-
max_name_len = 255 # single-file-name limit on NTFS / ext4
|
| 400 |
-
if tail:
|
| 401 |
-
room = max_name_len - len(tail) - 1 # -1 = the "_" separator after the name
|
| 402 |
-
if len(base) > room:
|
| 403 |
-
base = base[:max(room, 1)].rstrip("_-") # cut the END of the original name
|
| 404 |
-
name = f"{base}_{tail}"
|
| 405 |
-
else:
|
| 406 |
-
name = base[:max_name_len]
|
| 407 |
-
ext = ".webp" if output_format == "webp" else ".gif"
|
| 408 |
-
file = f"{name}{ext}"
|
| 409 |
-
i = 2
|
| 410 |
-
while os.path.exists(os.path.join(full_folder, file)): # never clobber an older file
|
| 411 |
-
file = f"{name}_{i}{ext}"
|
| 412 |
-
i += 1
|
| 413 |
-
path = os.path.join(full_folder, file)
|
| 414 |
-
try:
|
| 415 |
-
rel = os.path.relpath(full_folder, out_dir)
|
| 416 |
-
except ValueError:
|
| 417 |
-
rel = "" # different drive: the preview may not resolve, saving still works
|
| 418 |
-
subfolder = "" if rel in ("", ".") else rel.replace(os.sep, "/")
|
| 419 |
-
|
| 420 |
-
if output_format == "webp":
|
| 421 |
-
d_ms = core.quantize_delays_ms(delays, min_ms=min_cs * 10)
|
| 422 |
-
core.save_webp(frames(), d_ms, path, loop=loop_count, lossless=webp_lossless,
|
| 423 |
-
quality=quality, method=webp_method, batch_size=batch_size)
|
| 424 |
-
saved = core.read_webp_delays(path) or d_ms[:1] # what is really in the file
|
| 425 |
-
else:
|
| 426 |
-
max_colors = core.gif_colors_for_quality(max_colors, quality)
|
| 427 |
-
if max_colors < 256:
|
| 428 |
-
print(f"[GIF Delay Tools] GIF quality {quality} -> palette of {max_colors} colours")
|
| 429 |
-
if backend == "ffmpeg_palette" and core.find_ffmpeg() is not None:
|
| 430 |
-
core.save_gif_ffmpeg(frames(), delays_cs, path, loop=loop_count,
|
| 431 |
-
palette_mode=palette_mode, dither=dither,
|
| 432 |
-
max_colors=max_colors, optimize_size=optimize_size)
|
| 433 |
-
else:
|
| 434 |
-
if backend == "ffmpeg_palette":
|
| 435 |
-
print("[GIF Delay Tools] ffmpeg not found, using Pillow fallback.")
|
| 436 |
-
core.save_gif_pillow(frames(), delays_cs, path, loop=loop_count,
|
| 437 |
-
dither=dither != "none", max_colors=max_colors,
|
| 438 |
-
batch_size=batch_size)
|
| 439 |
-
saved = core.read_gif_delays(path) # what is really in the file
|
| 440 |
-
ui = {"images": [{"filename": file, "subfolder": subfolder, "type": save_to}]}
|
| 441 |
-
if animated_preview:
|
| 442 |
-
ui["animated"] = (True,)
|
| 443 |
-
return {"ui": ui, "result": (saved, _gif_info(saved), path)}
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
# ---------------------------------------------------------------- utilities
|
| 447 |
-
class GIFDelaysInfo:
|
| 448 |
-
@classmethod
|
| 449 |
-
def INPUT_TYPES(cls):
|
| 450 |
-
return {"required": {"delays": (GIF_DELAYS,)}}
|
| 451 |
-
|
| 452 |
-
RETURN_TYPES = ("FLOAT", "INT", "INT")
|
| 453 |
-
RETURN_NAMES = ("avg_fps", "min_ms", "max_ms")
|
| 454 |
-
FUNCTION = "run"
|
| 455 |
-
CATEGORY = CATEGORY
|
| 456 |
-
|
| 457 |
-
def run(self, delays):
|
| 458 |
-
d = [int(round(x)) for x in delays]
|
| 459 |
-
return (float(core.avg_fps(d)), min(d), max(d))
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
class GIFDelaysFromFPS:
|
| 463 |
-
"""Constant delays for any IMAGE batch (e.g. a video)."""
|
| 464 |
-
@classmethod
|
| 465 |
-
def INPUT_TYPES(cls):
|
| 466 |
-
return {"required": {"images": ("IMAGE",),
|
| 467 |
-
"fps": ("FLOAT", {"default": 10.0, "min": 0.1, "max": 100.0, "step": 0.1})}}
|
| 468 |
-
|
| 469 |
-
RETURN_TYPES = (GIF_DELAYS, "FLOAT")
|
| 470 |
-
RETURN_NAMES = ("delays", "avg_fps")
|
| 471 |
-
FUNCTION = "run"
|
| 472 |
-
CATEGORY = CATEGORY
|
| 473 |
-
|
| 474 |
-
def run(self, images, fps):
|
| 475 |
-
cs = core.quantize_delays_cs([1000.0 / fps] * images.shape[0], min_cs=1)
|
| 476 |
-
d = [c * 10 for c in cs]
|
| 477 |
-
return (d, float(core.avg_fps(d)))
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
class GIFPlanInterpolation:
|
| 481 |
-
"""Computes the RIFE multiplier so the result does not exceed target fps."""
|
| 482 |
-
@classmethod
|
| 483 |
-
def INPUT_TYPES(cls):
|
| 484 |
-
return {"required": {
|
| 485 |
-
"delays": (GIF_DELAYS,),
|
| 486 |
-
"target_fps": ("FLOAT", {"default": 50.0, "min": 1.0, "max": 100.0, "step": 1.0}),
|
| 487 |
-
"reference": (["average_fps", "median_delay", "minimum_fps", "maximum_fps"], {"tooltip":
|
| 488 |
-
"Which speed of the source gif decides the multiplier.\n"
|
| 489 |
-
"average_fps: overall average. median_delay: typical frame.\n"
|
| 490 |
-
"minimum_fps: the SLOWEST part of the gif (longest delay) -> bigger multiplier.\n"
|
| 491 |
-
"maximum_fps: the FASTEST part of the gif (shortest delay) -> smaller multiplier, "
|
| 492 |
-
"nothing exceeds the target."}),
|
| 493 |
-
"max_multiplier": ("INT", {"default": 16, "min": 1, "max": 64}),
|
| 494 |
-
}}
|
| 495 |
-
|
| 496 |
-
RETURN_TYPES = ("INT", "FLOAT", "FLOAT")
|
| 497 |
-
RETURN_NAMES = ("multiplier", "source_fps", "resulting_fps")
|
| 498 |
-
FUNCTION = "run"
|
| 499 |
-
CATEGORY = CATEGORY
|
| 500 |
-
|
| 501 |
-
def run(self, delays, target_fps, reference, max_multiplier):
|
| 502 |
-
m, src = core.plan_multiplier(delays, target_fps, reference, max_multiplier)
|
| 503 |
-
return (int(m), float(src), float(src * m))
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
class GIFDeduplicate:
|
| 507 |
-
"""Merge consecutive duplicate frames and add their delays together."""
|
| 508 |
-
@classmethod
|
| 509 |
-
def INPUT_TYPES(cls):
|
| 510 |
-
return {"required": {
|
| 511 |
-
"images": ("IMAGE",),
|
| 512 |
-
"delays": (GIF_DELAYS,),
|
| 513 |
-
"similarity_threshold": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 30.0, "step": 0.1,
|
| 514 |
-
"tooltip": "0 = exact duplicates only (lossless). Otherwise max pixel difference "
|
| 515 |
-
"(0-255 levels) still counted as the same frame."}),
|
| 516 |
-
"comparison_mode": (["strict_max_difference", "mean_difference"], {"tooltip":
|
| 517 |
-
"strict: no single pixel may differ more than the threshold. "
|
| 518 |
-
"mean: average difference (can hide small visible changes)."}),
|
| 519 |
-
"compare_against": (["group_first_frame", "previous_frame"], {"tooltip":
|
| 520 |
-
"group_first_frame avoids slow drift being merged away."}),
|
| 521 |
-
}}
|
| 522 |
-
|
| 523 |
-
RETURN_TYPES = ("IMAGE", GIF_DELAYS, "INT", "STRING", "STRING")
|
| 524 |
-
RETURN_NAMES = ("images", "delays", "removed_frames", "gif_info", "summary")
|
| 525 |
-
FUNCTION = "run"
|
| 526 |
-
CATEGORY = CATEGORY
|
| 527 |
-
|
| 528 |
-
def run(self, images, delays, similarity_threshold, comparison_mode, compare_against):
|
| 529 |
-
n = images.shape[0]
|
| 530 |
-
if len(delays) != n:
|
| 531 |
-
raise ValueError(f"{n} images but {len(delays)} delays. They must match.")
|
| 532 |
-
keep, merged = core.dedupe_frames(_LazyU8(images), list(delays), similarity_threshold,
|
| 533 |
-
comparison_mode, compare_against)
|
| 534 |
-
out = images if len(keep) == n else images[torch.as_tensor(keep, dtype=torch.long)] # nothing removed: no copy
|
| 535 |
-
summary = (f"{n} -> {len(keep)} frames ({n - len(keep)} removed); duration "
|
| 536 |
-
f"{int(sum(delays))} ms -> {sum(merged)} ms")
|
| 537 |
-
print(f"[GIF Delay Tools] dedupe: {summary}")
|
| 538 |
-
return (out, merged, n - len(keep), _gif_info(merged), summary)
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
class GIFLoopPair:
|
| 542 |
-
"""[last, first] pair to interpolate for a seamless loop transition."""
|
| 543 |
-
@classmethod
|
| 544 |
-
def INPUT_TYPES(cls):
|
| 545 |
-
return {"required": {"images": ("IMAGE",)}}
|
| 546 |
-
|
| 547 |
-
RETURN_TYPES = ("IMAGE",)
|
| 548 |
-
RETURN_NAMES = ("last_first_pair",)
|
| 549 |
-
FUNCTION = "run"
|
| 550 |
-
CATEGORY = CATEGORY
|
| 551 |
-
|
| 552 |
-
def run(self, images):
|
| 553 |
-
if images.shape[0] < 2:
|
| 554 |
-
raise ValueError("Need at least 2 frames for a loop transition")
|
| 555 |
-
return (torch.cat([images[-1:], images[:1]], dim=0),)
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
class GIFDelayAwareInterpolation:
|
| 559 |
-
"""
|
| 560 |
-
Rebuilds frames + delays after RIFE so the original rhythm survives.
|
| 561 |
-
"""
|
| 562 |
-
@classmethod
|
| 563 |
-
def INPUT_TYPES(cls):
|
| 564 |
-
return {
|
| 565 |
-
"required": {
|
| 566 |
-
"original_delays": (GIF_DELAYS,),
|
| 567 |
-
"interpolated_images": ("IMAGE", {"tooltip":
|
| 568 |
-
"Output of FrameInterpolate on the original frames: (N-1)*m+1 frames."}),
|
| 569 |
-
"timing_mode": (core.TIMING_MODES, {"tooltip":
|
| 570 |
-
"keep_original_delays: the original frames keep their delays, the new frames get "
|
| 571 |
-
"interp_delay_ms.\n"
|
| 572 |
-
"uniform_delays: EVERY frame (old and new) gets the same delay -> constant speed. "
|
| 573 |
-
"With 'allow longer' OFF the delay is chosen so the gif keeps its original duration. "
|
| 574 |
-
"'deduce' is ignored.\n"
|
| 575 |
-
"smart_delays: the new frames glide at the pace of the original frame they follow. "
|
| 576 |
-
"Frames longer than 2x the average ('holds') do not slow the glide down. "
|
| 577 |
-
"interp_delay_ms is ignored."}),
|
| 578 |
-
"deduce_from_original": (core.DEDUCE_MODES, {"default": "deduce", "tooltip":
|
| 579 |
-
"deduce: the time of the new frames is taken out of the original frame's delay "
|
| 580 |
-
"(the original frame gets shorter).\n"
|
| 581 |
-
"deduce - not held frame: same, but frames whose delay is 2x the average or more "
|
| 582 |
-
"('held' frames) keep their full delay. They are still interpolated, and their new "
|
| 583 |
-
"frames are added on top (the gif gets longer by that amount).\n"
|
| 584 |
-
"don't deduce: originals always keep their full delay, the gif gets longer.\n"
|
| 585 |
-
"'uniform_delays' ignores this (except for the loop transition)."}),
|
| 586 |
-
"allow_longer": ("BOOLEAN", {"default": True, "tooltip":
|
| 587 |
-
"ON: keep every new frame, the gif may get longer. OFF: keep the original total "
|
| 588 |
-
"duration; new frames that do not fit are dropped.\n"
|
| 589 |
-
"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"
|
| 590 |
-
"The loop transition follows the same rules: with 'deduce' ON its time comes out of "
|
| 591 |
-
"the LAST frame's delay; with 'deduce' OFF it is added on top."}),
|
| 592 |
-
"max_fps": ("FLOAT", {"default": 50.0, "min": 1.0, "max": 100.0, "step": 1.0}),
|
| 593 |
-
"interp_delay_ms": ("INT", {"default": 0, "min": 0, "max": 5000, "step": 10, "tooltip":
|
| 594 |
-
"Delay of the new frames ('uniform_delays': of ALL frames). 0 = fastest allowed by "
|
| 595 |
-
"max_fps (20 ms at 50 fps). Ignored by 'smart_delays'."}),
|
| 596 |
-
"looping": ("BOOLEAN", {"default": True, "tooltip":
|
| 597 |
-
"ON: insert the interpolated last->first transition (seamless loop). With 'deduce' ON "
|
| 598 |
-
"its time is taken out of the last frame's delay, with 'deduce' OFF it is added on top. "
|
| 599 |
-
"OFF: non-looping gif."}),
|
| 600 |
-
"held_frame_factor": ("FLOAT", {"default": 2.0, "min": 1.1, "max": 10.0, "step": 0.1, "tooltip":
|
| 601 |
-
"A frame is 'held' when its delay is at least this many times the AVERAGE delay "
|
| 602 |
-
"(2.0 = twice the average). Used by 'deduce - not held frame' and by the hold cap of "
|
| 603 |
-
"'smart_delays'. Lower = more frames count as held."}),
|
| 604 |
-
},
|
| 605 |
-
"optional": {
|
| 606 |
-
"loop_interpolated": ("IMAGE", {"tooltip":
|
| 607 |
-
"Interpolated [last, first] pair (m+1 frames). Its middle frames are inserted "
|
| 608 |
-
"after the last frame for a seamless loop."}),
|
| 609 |
-
},
|
| 610 |
-
}
|
| 611 |
-
|
| 612 |
-
RETURN_TYPES = ("IMAGE", GIF_DELAYS, "STRING", "STRING")
|
| 613 |
-
RETURN_NAMES = ("images", "delays", "multiplier", "gif_info")
|
| 614 |
-
FUNCTION = "run"
|
| 615 |
-
CATEGORY = CATEGORY
|
| 616 |
-
|
| 617 |
-
def run(self, original_delays, interpolated_images, timing_mode, deduce_from_original,
|
| 618 |
-
allow_longer, max_fps, interp_delay_ms, looping=True, held_frame_factor=2.0,
|
| 619 |
-
loop_interpolated=None):
|
| 620 |
-
min_ms = core.min_delay_cs_for_fps(max_fps) * 10
|
| 621 |
-
interp_ms = max(min_ms, int(interp_delay_ms) if interp_delay_ms > 0 else min_ms)
|
| 622 |
-
n_orig = len(original_delays)
|
| 623 |
-
|
| 624 |
-
total_interp = int(interpolated_images.shape[0])
|
| 625 |
-
mid = None
|
| 626 |
-
loop_k = 0
|
| 627 |
-
if looping and loop_interpolated is not None and n_orig >= 2:
|
| 628 |
-
mid = loop_interpolated[1:-1] # view, no copy
|
| 629 |
-
loop_k = int(mid.shape[0])
|
| 630 |
-
if loop_k == 0:
|
| 631 |
-
mid = None
|
| 632 |
-
|
| 633 |
-
idx, delays = core.build_timeline(
|
| 634 |
-
list(original_delays), total_interp, timing_mode,
|
| 635 |
-
deduce_from_original, allow_longer, interp_ms, min_ms, loop_k=loop_k,
|
| 636 |
-
held_factor=held_frame_factor)
|
| 637 |
-
|
| 638 |
-
if mid is None and idx == list(range(total_interp)):
|
| 639 |
-
out = interpolated_images # nothing dropped or added: reuse, zero copies
|
| 640 |
-
else:
|
| 641 |
-
shape = (len(idx),) + tuple(interpolated_images.shape[1:])
|
| 642 |
-
if interpolated_images.device.type == "cpu":
|
| 643 |
-
_check_ram(int(np.prod(shape)) * interpolated_images.element_size(),
|
| 644 |
-
"GIF Delay-Aware Interpolation")
|
| 645 |
-
out = torch.empty(shape, dtype=interpolated_images.dtype,
|
| 646 |
-
device=interpolated_images.device)
|
| 647 |
-
for o, k in enumerate(idx):
|
| 648 |
-
out[o] = interpolated_images[k] if k < total_interp else mid[k - total_interp]
|
| 649 |
-
mult = core.infer_multiplier(n_orig, interpolated_images.shape[0])
|
| 650 |
-
return (out, delays, f"x{int(mult)}", _gif_info(delays))
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
class GIFBatchInterpolate:
|
| 654 |
-
"""
|
| 655 |
-
Batched frame interpolation — drop-in replacement for ComfyUI's FrameInterpolate.
|
| 656 |
-
Uses float16 accumulation (halves peak RAM) and clears GPU caches in blocks
|
| 657 |
-
to stay well within memory limits on large GIFs.
|
| 658 |
-
"""
|
| 659 |
-
@classmethod
|
| 660 |
-
def INPUT_TYPES(cls):
|
| 661 |
-
return {
|
| 662 |
-
"required": {
|
| 663 |
-
"interp_model": ("INTERP_MODEL",),
|
| 664 |
-
"images": ("IMAGE",),
|
| 665 |
-
"multiplier": ("INT", {"default": 2, "min": 2, "max": 64}),
|
| 666 |
-
},
|
| 667 |
-
"optional": {
|
| 668 |
-
"batch_size": ("INT", {"default": 10, "min": 1, "max": 1000, "tooltip":
|
| 669 |
-
"Process this many frame pairs before clearing GPU caches. "
|
| 670 |
-
"Lower = less peak memory usage, slightly slower due to cache overhead."}),
|
| 671 |
-
"force_custom_multiplier": ("INT", {"default": 0, "min": 0, "max": 16, "step": 1, "tooltip":
|
| 672 |
-
"0 = off (use the multiplier input). 1 = FORCE x1: no interpolation at all, the frames "
|
| 673 |
-
"pass through untouched (only the timing changes downstream). 2-16 = FORCE this "
|
| 674 |
-
"multiplier, ignoring the multiplier input (e.g. from GIF Plan Interpolation). Use the "
|
| 675 |
-
"SAME value on the [last, first] loop-pair interpolation, and keep allow_longer ON in "
|
| 676 |
-
"GIF Delay-Aware Interpolation so none of the frames is dropped."}),
|
| 677 |
-
"output_device": (["auto", "ram", "vram"], {"default": "auto", "tooltip":
|
| 678 |
-
"Where the output batch lives.\n"
|
| 679 |
-
"auto: in VRAM when it fits with head-room (the model is loaded first, so the free VRAM is known), "
|
| 680 |
-
"otherwise in RAM.\n"
|
| 681 |
-
"ram: always RAM (ComfyUI offload device).\n"
|
| 682 |
-
"vram: always the GPU (falls back to RAM if it does not fit). Saves a lot of RAM; the batch "
|
| 683 |
-
"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."}),
|
| 684 |
-
},
|
| 685 |
-
}
|
| 686 |
-
|
| 687 |
-
RETURN_TYPES = ("IMAGE",)
|
| 688 |
-
RETURN_NAMES = ("images",)
|
| 689 |
-
FUNCTION = "interpolate"
|
| 690 |
-
CATEGORY = CATEGORY
|
| 691 |
-
|
| 692 |
-
def interpolate(self, interp_model, images, multiplier, batch_size=10, force_custom_multiplier=0,
|
| 693 |
-
output_device="auto"):
|
| 694 |
-
# 0 = off, 1 = forced x1 (no interpolation: the frames are returned as they are), 2-16 = forced
|
| 695 |
-
if int(force_custom_multiplier) >= 1:
|
| 696 |
-
multiplier = int(force_custom_multiplier)
|
| 697 |
-
from comfy import model_management
|
| 698 |
-
import comfy.utils
|
| 699 |
-
from tqdm import tqdm
|
| 700 |
-
|
| 701 |
-
offload_device = model_management.intermediate_device()
|
| 702 |
-
num_frames = images.shape[0]
|
| 703 |
-
if num_frames < 2 or multiplier < 2:
|
| 704 |
-
return (images,)
|
| 705 |
-
|
| 706 |
-
device = interp_model.load_device
|
| 707 |
-
dtype = interp_model.model_dtype()
|
| 708 |
-
inference_model = interp_model.model
|
| 709 |
-
activation_mem = inference_model.memory_used_forward(images.shape, dtype)
|
| 710 |
-
model_management.load_models_gpu([interp_model], memory_required=activation_mem)
|
| 711 |
-
align = getattr(inference_model, "pad_align", 1)
|
| 712 |
-
H, W = images.shape[1], images.shape[2]
|
| 713 |
-
|
| 714 |
-
def prepare_frame(idx):
|
| 715 |
-
frame = images[idx:idx + 1].movedim(-1, 1).to(dtype=dtype, device=device)
|
| 716 |
-
if align > 1:
|
| 717 |
-
from comfy.ldm.common_dit import pad_to_patch_size
|
| 718 |
-
frame = pad_to_patch_size(frame, (align, align), padding_mode="reflect")
|
| 719 |
-
return frame
|
| 720 |
-
|
| 721 |
-
total_pairs = num_frames - 1
|
| 722 |
-
num_interp = multiplier - 1
|
| 723 |
-
total_steps = total_pairs * num_interp
|
| 724 |
-
pbar = comfy.utils.ProgressBar(total_steps)
|
| 725 |
-
tqdm_bar = tqdm(total=total_steps, desc="GIF Batch Interpolate")
|
| 726 |
-
|
| 727 |
-
# Key difference from FrameInterpolate: force float16 accumulator.
|
| 728 |
-
# This halves peak RAM: 57.4 GB (float32) -> 28.7 GB (float16), fits in 64 GB.
|
| 729 |
-
out_dtype = torch.float16
|
| 730 |
-
total_out_frames = total_pairs * multiplier + 1
|
| 731 |
-
out_dev = _pick_output_device(output_device, total_out_frames * H * W * 3 * 2, device,
|
| 732 |
-
offload_device, activation_mem)
|
| 733 |
-
# BHWC and contiguous from the start: downstream nodes never need a second full copy
|
| 734 |
-
result = _alloc_output((total_out_frames, H, W, 3), out_dtype, out_dev, offload_device,
|
| 735 |
-
"GIF Batch Interpolate")
|
| 736 |
-
result[0] = images[0][..., :3].to(out_dtype)
|
| 737 |
-
out_idx = 1
|
| 738 |
-
|
| 739 |
-
# Pre-compute timestep tensor on device (padded dimensions needed)
|
| 740 |
-
sample = prepare_frame(0)
|
| 741 |
-
pH, pW = sample.shape[2], sample.shape[3]
|
| 742 |
-
t_values = [t / multiplier for t in range(1, multiplier)]
|
| 743 |
-
ts_full = torch.tensor(t_values, device=device, dtype=dtype).reshape(num_interp, 1, 1, 1)
|
| 744 |
-
ts_full = ts_full.expand(-1, 1, pH, pW)
|
| 745 |
-
del sample
|
| 746 |
-
|
| 747 |
-
multi_fn = getattr(inference_model, "forward_multi_timestep", None)
|
| 748 |
-
feat_cache = {}
|
| 749 |
-
prev_frame = None
|
| 750 |
-
batch = num_interp # per-pair timestep batch, reduced on OOM
|
| 751 |
-
|
| 752 |
-
try:
|
| 753 |
-
for i in range(total_pairs):
|
| 754 |
-
img0_single = prev_frame if prev_frame is not None else prepare_frame(i)
|
| 755 |
-
img1_single = prepare_frame(i + 1)
|
| 756 |
-
prev_frame = img1_single
|
| 757 |
-
|
| 758 |
-
# Cache features: img1 of pair N becomes img0 of pair N+1
|
| 759 |
-
feat_cache["img0"] = (feat_cache.pop("next") if "next" in feat_cache
|
| 760 |
-
else inference_model.extract_features(img0_single))
|
| 761 |
-
feat_cache["img1"] = inference_model.extract_features(img1_single)
|
| 762 |
-
feat_cache["next"] = feat_cache["img1"]
|
| 763 |
-
|
| 764 |
-
used_multi = False
|
| 765 |
-
if multi_fn is not None:
|
| 766 |
-
try:
|
| 767 |
-
mids = multi_fn(img0_single, img1_single, t_values, cache=feat_cache)
|
| 768 |
-
result[out_idx:out_idx + num_interp] = mids[:, :, :H, :W].permute(0, 2, 3, 1).clamp(0.0, 1.0).to(out_dtype)
|
| 769 |
-
out_idx += num_interp
|
| 770 |
-
pbar.update(num_interp)
|
| 771 |
-
tqdm_bar.update(num_interp)
|
| 772 |
-
used_multi = True
|
| 773 |
-
except model_management.OOM_EXCEPTION:
|
| 774 |
-
model_management.soft_empty_cache()
|
| 775 |
-
multi_fn = None # fall through to single-timestep path
|
| 776 |
-
|
| 777 |
-
if not used_multi:
|
| 778 |
-
j = 0
|
| 779 |
-
while j < num_interp:
|
| 780 |
-
b = min(batch, num_interp - j)
|
| 781 |
-
try:
|
| 782 |
-
img0 = img0_single.expand(b, -1, -1, -1)
|
| 783 |
-
img1 = img1_single.expand(b, -1, -1, -1)
|
| 784 |
-
mids = inference_model(img0, img1, timestep=ts_full[j:j + b], cache=feat_cache)
|
| 785 |
-
result[out_idx:out_idx + b] = mids[:, :, :H, :W].permute(0, 2, 3, 1).clamp(0.0, 1.0).to(out_dtype)
|
| 786 |
-
out_idx += b
|
| 787 |
-
pbar.update(b)
|
| 788 |
-
tqdm_bar.update(b)
|
| 789 |
-
j += b
|
| 790 |
-
except model_management.OOM_EXCEPTION:
|
| 791 |
-
if batch <= 1:
|
| 792 |
-
raise
|
| 793 |
-
batch = max(1, batch // 2)
|
| 794 |
-
model_management.soft_empty_cache()
|
| 795 |
-
|
| 796 |
-
result[out_idx] = images[i + 1][..., :3].to(out_dtype)
|
| 797 |
-
out_idx += 1
|
| 798 |
-
|
| 799 |
-
# Clear GPU caches every batch_size pairs to free intermediate tensors
|
| 800 |
-
if batch_size > 0 and (i + 1) % batch_size == 0 and i + 1 < total_pairs:
|
| 801 |
-
if torch.cuda.is_available():
|
| 802 |
-
torch.cuda.empty_cache()
|
| 803 |
-
model_management.soft_empty_cache()
|
| 804 |
-
finally:
|
| 805 |
-
tqdm_bar.close()
|
| 806 |
-
|
| 807 |
-
return (result,)
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
class GIFFusedInterpolate:
|
| 811 |
-
"""
|
| 812 |
-
Delay-aware interpolation in ONE step (RIFE + timeline).
|
| 813 |
-
|
| 814 |
-
The separate pipeline (Batch Interpolate -> Delay-Aware Interpolation) first creates
|
| 815 |
-
EVERY in-between frame (original x multiplier) and only afterwards throws away the ones
|
| 816 |
-
that do not fit the timing. This node plans the timeline first and asks RIFE only for the
|
| 817 |
-
frames that will really be in the final gif, so RAM scales with the FINAL frame count.
|
| 818 |
-
The loop transition (last -> first) is computed here too: no GIF Loop Pair needed.
|
| 819 |
-
"""
|
| 820 |
-
@classmethod
|
| 821 |
-
def INPUT_TYPES(cls):
|
| 822 |
-
return {
|
| 823 |
-
"required": {
|
| 824 |
-
"interp_model": ("INTERP_MODEL",),
|
| 825 |
-
"images": ("IMAGE", {"tooltip": "The ORIGINAL frames (e.g. after GIF Deduplicate)."}),
|
| 826 |
-
"original_delays": (GIF_DELAYS,),
|
| 827 |
-
"multiplier": ("INT", {"default": 4, "min": 1, "max": 64, "tooltip":
|
| 828 |
-
"Can be wired from GIF Plan Interpolation. Frames that do not fit the timing "
|
| 829 |
-
"are never computed, so a high multiplier no longer costs RAM."}),
|
| 830 |
-
"timing_mode": (core.TIMING_MODES,),
|
| 831 |
-
"deduce_from_original": (core.DEDUCE_MODES, {"default": "deduce", "tooltip":
|
| 832 |
-
"deduce: the time of the new frames comes out of the original frame's delay.\n"
|
| 833 |
-
"deduce - not held frame: same, but frames with a delay of 2x the average or more "
|
| 834 |
-
"keep their full delay (still interpolated, new frames added on top).\n"
|
| 835 |
-
"don't deduce: originals keep their full delay, the gif gets longer."}),
|
| 836 |
-
"allow_longer": ("BOOLEAN", {"default": True}),
|
| 837 |
-
"max_fps": ("FLOAT", {"default": 50.0, "min": 1.0, "max": 100.0, "step": 1.0}),
|
| 838 |
-
"interp_delay_ms": ("INT", {"default": 0, "min": 0, "max": 5000, "step": 10}),
|
| 839 |
-
"looping": ("BOOLEAN", {"default": True, "tooltip":
|
| 840 |
-
"Insert the interpolated last->first transition (seamless loop)."}),
|
| 841 |
-
"output_dtype": (["float16", "float32"], {"default": "float16", "tooltip":
|
| 842 |
-
"float16 halves RAM. GIF/WebP Save handles both."}),
|
| 843 |
-
"clear_cache_every": ("INT", {"default": 10, "min": 0, "max": 1000, "tooltip":
|
| 844 |
-
"Free GPU caches every N frame pairs (0 = never)."}),
|
| 845 |
-
"held_frame_factor": ("FLOAT", {"default": 2.0, "min": 1.1, "max": 10.0, "step": 0.1, "tooltip":
|
| 846 |
-
"A frame is 'held' when its delay is at least this many times the AVERAGE delay "
|
| 847 |
-
"(2.0 = twice the average). Used by 'deduce - not held frame' and by the hold cap of "
|
| 848 |
-
"'smart_delays'. Lower = more frames count as held."}),
|
| 849 |
-
"force_custom_multiplier": ("INT", {"default": 0, "min": 0, "max": 16, "step": 1, "tooltip":
|
| 850 |
-
"0 = off (use the multiplier input).\n"
|
| 851 |
-
"1 = FORCE x1: NO interpolation at all (RIFE is not even loaded). The original frames "
|
| 852 |
-
"are kept and only the timing settings are applied - use it to change the speed or just "
|
| 853 |
-
"convert to WebP/GIF.\n"
|
| 854 |
-
"2-16 = FORCE this multiplier, ignoring the multiplier input (e.g. from GIF Plan "
|
| 855 |
-
"Interpolation).\n"
|
| 856 |
-
"All other settings are respected, except 'allow_longer': with it OFF the frames that do "
|
| 857 |
-
"not fit would be dropped, so it is switched ON while a multiplier of 2 or more is forced "
|
| 858 |
-
"(not needed for uniform_delays, nor for x1)."}),
|
| 859 |
-
},
|
| 860 |
-
"optional": {
|
| 861 |
-
"output_device": (["auto", "ram", "vram"], {"default": "auto", "tooltip":
|
| 862 |
-
"Where the output batch lives.\n"
|
| 863 |
-
"auto: in VRAM when it fits with head-room (the model is loaded first, so the free VRAM is known), "
|
| 864 |
-
"otherwise in RAM.\n"
|
| 865 |
-
"ram: always RAM (ComfyUI offload device).\n"
|
| 866 |
-
"vram: always the GPU (falls back to RAM if it does not fit). Saves a lot of RAM; the batch "
|
| 867 |
-
"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."}),
|
| 868 |
-
},
|
| 869 |
-
}
|
| 870 |
-
|
| 871 |
-
RETURN_TYPES = ("IMAGE", GIF_DELAYS, "STRING", "STRING")
|
| 872 |
-
RETURN_NAMES = ("images", "delays", "multiplier", "gif_info")
|
| 873 |
-
FUNCTION = "run"
|
| 874 |
-
CATEGORY = CATEGORY
|
| 875 |
-
|
| 876 |
-
def run(self, interp_model, images, original_delays, multiplier, timing_mode,
|
| 877 |
-
deduce_from_original, allow_longer, max_fps, interp_delay_ms, looping,
|
| 878 |
-
output_dtype, clear_cache_every, held_frame_factor=2.0,
|
| 879 |
-
force_custom_multiplier=0, output_device="auto"):
|
| 880 |
-
from comfy import model_management
|
| 881 |
-
import comfy.utils
|
| 882 |
-
from tqdm import tqdm
|
| 883 |
-
|
| 884 |
-
n = int(images.shape[0])
|
| 885 |
-
if len(original_delays) != n:
|
| 886 |
-
raise ValueError(f"{n} images but {len(original_delays)} delays. They must match.")
|
| 887 |
-
m, allow_longer, force_note = core.apply_forced_multiplier(
|
| 888 |
-
multiplier, force_custom_multiplier, timing_mode, allow_longer)
|
| 889 |
-
if force_note:
|
| 890 |
-
print(f"[GIF Delay Tools] {force_note}")
|
| 891 |
-
min_ms = core.min_delay_cs_for_fps(max_fps) * 10
|
| 892 |
-
interp_ms = max(min_ms, int(interp_delay_ms) if interp_delay_ms > 0 else min_ms)
|
| 893 |
-
|
| 894 |
-
idx, delays, originals, jobs = core.plan_fused(
|
| 895 |
-
list(original_delays), m, timing_mode, deduce_from_original, allow_longer,
|
| 896 |
-
interp_ms, min_ms, looping=looping, held_factor=held_frame_factor)
|
| 897 |
-
|
| 898 |
-
H, W = int(images.shape[1]), int(images.shape[2])
|
| 899 |
-
out_dtype = torch.float16 if output_dtype == "float16" else torch.float32
|
| 900 |
-
offload_device = model_management.intermediate_device()
|
| 901 |
-
out_shape = (len(idx), H, W, 3)
|
| 902 |
-
out_bytes = len(idx) * H * W * 3 * (2 if output_dtype == "float16" else 4)
|
| 903 |
-
what = "GIF Delay-Aware Interpolate (fused)"
|
| 904 |
-
|
| 905 |
-
def fill_originals(out):
|
| 906 |
-
for o, i in originals:
|
| 907 |
-
out[o] = images[i][..., :3].to(out_dtype)
|
| 908 |
-
|
| 909 |
-
n_new = sum(len(j[3]) for j in jobs)
|
| 910 |
-
print(f"[GIF Delay Tools] fused: {n} originals x{m} -> {len(idx)} output frames "
|
| 911 |
-
f"({len(originals)} copied, {n_new} interpolated)")
|
| 912 |
-
if not jobs:
|
| 913 |
-
# nothing to interpolate (e.g. forced x1): plain copy, the model is not even loaded
|
| 914 |
-
out = _alloc_output(out_shape, out_dtype, offload_device, offload_device, what)
|
| 915 |
-
fill_originals(out)
|
| 916 |
-
return (out, delays, f"x{m}", _gif_info(delays))
|
| 917 |
-
|
| 918 |
-
device = interp_model.load_device
|
| 919 |
-
dtype = interp_model.model_dtype()
|
| 920 |
-
inference_model = interp_model.model
|
| 921 |
-
activation_mem = inference_model.memory_used_forward((1,) + tuple(images.shape[1:]), dtype)
|
| 922 |
-
model_management.load_models_gpu([interp_model], memory_required=activation_mem)
|
| 923 |
-
# the model is loaded now, so the free VRAM is known: decide where the output batch goes
|
| 924 |
-
out_dev = _pick_output_device(output_device, out_bytes, device, offload_device, activation_mem)
|
| 925 |
-
out = _alloc_output(out_shape, out_dtype, out_dev, offload_device, what)
|
| 926 |
-
fill_originals(out)
|
| 927 |
-
align = getattr(inference_model, "pad_align", 1)
|
| 928 |
-
|
| 929 |
-
def prepare_frame(i):
|
| 930 |
-
frame = images[i:i + 1].movedim(-1, 1).to(dtype=dtype, device=device)
|
| 931 |
-
if align > 1:
|
| 932 |
-
from comfy.ldm.common_dit import pad_to_patch_size
|
| 933 |
-
frame = pad_to_patch_size(frame, (align, align), padding_mode="reflect")
|
| 934 |
-
return frame
|
| 935 |
-
|
| 936 |
-
def store(pos, mids):
|
| 937 |
-
res = mids[:, :, :H, :W].permute(0, 2, 3, 1).clamp(0.0, 1.0).to(out_dtype)
|
| 938 |
-
out[pos:pos + res.shape[0]] = res
|
| 939 |
-
|
| 940 |
-
probe = prepare_frame(0)
|
| 941 |
-
pH, pW = probe.shape[2], probe.shape[3]
|
| 942 |
-
del probe
|
| 943 |
-
|
| 944 |
-
pbar = comfy.utils.ProgressBar(n_new)
|
| 945 |
-
tqdm_bar = tqdm(total=n_new, desc="GIF Fused Interpolate")
|
| 946 |
-
multi_fn = getattr(inference_model, "forward_multi_timestep", None)
|
| 947 |
-
batch = max(1, m - 1) # timesteps per forward call, halved on OOM
|
| 948 |
-
prev_b = prev_img1 = prev_f1 = None
|
| 949 |
-
try:
|
| 950 |
-
for ji, (a, b, o0, ts) in enumerate(jobs):
|
| 951 |
-
if prev_b == a: # previous pair ended on this frame: reuse its features
|
| 952 |
-
img0, f0 = prev_img1, prev_f1
|
| 953 |
-
else:
|
| 954 |
-
img0 = prepare_frame(a)
|
| 955 |
-
f0 = inference_model.extract_features(img0)
|
| 956 |
-
img1 = prepare_frame(b)
|
| 957 |
-
f1 = inference_model.extract_features(img1)
|
| 958 |
-
prev_b, prev_img1, prev_f1 = b, img1, f1
|
| 959 |
-
cache = {"img0": f0, "img1": f1}
|
| 960 |
-
|
| 961 |
-
done = False
|
| 962 |
-
if multi_fn is not None:
|
| 963 |
-
try:
|
| 964 |
-
store(o0, multi_fn(img0, img1, ts, cache=cache))
|
| 965 |
-
done = True
|
| 966 |
-
except model_management.OOM_EXCEPTION:
|
| 967 |
-
model_management.soft_empty_cache()
|
| 968 |
-
multi_fn = None # fall back to the single-timestep path
|
| 969 |
-
if not done:
|
| 970 |
-
j = 0
|
| 971 |
-
while j < len(ts):
|
| 972 |
-
bs = min(batch, len(ts) - j)
|
| 973 |
-
try:
|
| 974 |
-
tt = (torch.tensor(ts[j:j + bs], device=device, dtype=dtype)
|
| 975 |
-
.reshape(bs, 1, 1, 1).expand(-1, 1, pH, pW))
|
| 976 |
-
mids = inference_model(img0.expand(bs, -1, -1, -1),
|
| 977 |
-
img1.expand(bs, -1, -1, -1),
|
| 978 |
-
timestep=tt, cache=cache)
|
| 979 |
-
store(o0 + j, mids)
|
| 980 |
-
j += bs
|
| 981 |
-
except model_management.OOM_EXCEPTION:
|
| 982 |
-
if batch <= 1:
|
| 983 |
-
raise
|
| 984 |
-
batch = max(1, batch // 2)
|
| 985 |
-
model_management.soft_empty_cache()
|
| 986 |
-
pbar.update(len(ts))
|
| 987 |
-
tqdm_bar.update(len(ts))
|
| 988 |
-
|
| 989 |
-
if clear_cache_every > 0 and (ji + 1) % clear_cache_every == 0 and ji + 1 < len(jobs):
|
| 990 |
-
if torch.cuda.is_available():
|
| 991 |
-
torch.cuda.empty_cache()
|
| 992 |
-
model_management.soft_empty_cache()
|
| 993 |
-
finally:
|
| 994 |
-
tqdm_bar.close()
|
| 995 |
-
|
| 996 |
-
return (out, delays, f"x{m}", _gif_info(delays))
|
| 997 |
-
|
| 998 |
-
|
| 999 |
-
NODE_CLASS_MAPPINGS = {
|
| 1000 |
-
"GIFLoadWithDelays": GIFLoadWithDelays,
|
| 1001 |
-
"GIFSaveWithDelays": GIFSaveWithDelays,
|
| 1002 |
-
"GIFDelaysInfo": GIFDelaysInfo,
|
| 1003 |
-
"GIFDelaysFromFPS": GIFDelaysFromFPS,
|
| 1004 |
-
"GIFPlanInterpolation": GIFPlanInterpolation,
|
| 1005 |
-
"GIFLoopPair": GIFLoopPair,
|
| 1006 |
-
"GIFDeduplicate": GIFDeduplicate,
|
| 1007 |
-
"GIFDelayAwareInterpolation": GIFDelayAwareInterpolation,
|
| 1008 |
-
"GIFBatchInterpolate": GIFBatchInterpolate,
|
| 1009 |
-
"GIFFusedInterpolate": GIFFusedInterpolate,
|
| 1010 |
-
}
|
| 1011 |
-
NODE_DISPLAY_NAME_MAPPINGS = {
|
| 1012 |
-
"GIFLoadWithDelays": "GIF/WebP Load (with delays)",
|
| 1013 |
-
"GIFSaveWithDelays": "GIF/WebP Save (delays + FFmpeg palette)",
|
| 1014 |
-
"GIFDelaysInfo": "GIF Delays Info",
|
| 1015 |
-
"GIFDelaysFromFPS": "GIF Delays From FPS",
|
| 1016 |
-
"GIFPlanInterpolation": "GIF Plan Interpolation (multiplier)",
|
| 1017 |
-
"GIFLoopPair": "GIF Loop Pair (last + first)",
|
| 1018 |
-
"GIFDeduplicate": "GIF Deduplicate (merge delays)",
|
| 1019 |
-
"GIFDelayAwareInterpolation": "GIF Delay-Aware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