Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(video): Length up to 15 s for now, every section held to the first one (P5)

purple4a361b96d9e7
diff --git a/src-tauri/src/commands/video_settle.py b/src-tauri/src/commands/video_settle.py
index 8bc31ee8..7de9cdcf 100644
--- a/src-tauri/src/commands/video_settle.py
+++ b/src-tauri/src/commands/video_settle.py
@@ -1,24 +1,38 @@
"""Colour settle for a video made of several sections laid end to end.
LU writes this file into a private temp folder and runs it with ComfyUI's own
-Python (``python -I video_settle.py --input A --output B --boundaries 81,157
---window 5``). Only numpy and PyAV (``av``) are imported besides the standard
-library; both are in ComfyUI's requirements.txt.
-
-Every boundary is the index of the first frame of a new section. Each section
-is matched to the one before it, as that one looks AFTER its own correction:
-the last ``window`` corrected frames before the boundary are the reference,
-the first ``window`` frames of the new section the sample. Per channel
-
- gain = clamp(std_ref / std_cur, 0.8, 1.25)
- f' = (f - mean_cur) * gain + mean_ref
-
-is applied to every frame from the boundary to the next one (or the end).
-Chained like this, every section hangs on the first one and the corrections
-do not add up their own errors.
-
-The video is streamed: at most ``window`` corrected frames and ``window``
-uncorrected ones are held at a time, so the length of the video does not
+Python (``python -I video_settle.py --input A --output B --boundaries 157
+--anchor-end 81 --window 8``). Only numpy and PyAV (``av``) are imported
+besides the standard library; both are in ComfyUI's requirements.txt.
+
+Every boundary is the index of the first frame of a new section. The frames
+before the first boundary pass through as they are; from it on every frame is
+matched to the anchor, frames 0..anchor_end-1 (without ``--anchor-end``: all
+frames before the first boundary). The anchor is the clip's first section, so
+every later one hangs on it and no correction builds on another.
+
+Why per frame and not once per seam (P5, 3.0.9): in the B18 box runs a Wan
+section continued from frames came out about a fifth more saturated and half
+again as sharp within its first 15 frames, then stayed there, and the next
+section started from that and added its own step. Matching the first frames
+of a section to the last ones of the section before only carried every step
+over. Here, per frame and per plane of the video's own YUV,
+
+ f' = (f - mean_t) * clamp(std_anchor / std_t) + mean_t + clamp(mean_anchor - mean_t)
+
+where mean_t and std_t are smoothed over ``window`` frames on each side
+(never across a boundary), so a quick change in the picture stays and only
+the slow drift goes. U and V carry the saturation. Sharpness is the mean
+absolute Laplacian of Y; a frame sharper than the anchor is blended towards a
+slightly blurred copy of itself by just enough to meet it (softened only,
+never sharpened).
+
+Everything stays in YUV 4:2:0, the format the h264 file has anyway. A detour
+through RGB lost about 1.2 levels of brightness on every pass with PyAV, and
+a long clip passes through here once per section.
+
+Two passes over the video: statistics first, then the corrected frames. Only
+per-frame numbers are kept between them, so the length of the video does not
decide the memory it needs. Frames above MAX_PIXELS are refused outright.
The result goes to stdout as one JSON line, the last line printed. An error
@@ -28,18 +42,23 @@ is the same shape with ``ok: false`` and exit code 2.
import argparse
import json
import sys
-from collections import deque
from fractions import Fraction
import av
import numpy as np
-GAIN_MIN = 0.8
-GAIN_MAX = 1.25
-# 4096 x 2304: far above anything LU renders, low enough that 2 x window
-# frames in float stay well under a gigabyte.
+# 4096 x 2304: far above anything LU renders.
MAX_PIXELS = 4096 * 2304
MAX_WINDOW = 60
+# The drift this takes out builds up over sections; the clamp only stops a
+# scene that really changed from being forced back.
+Y_GAIN = (0.75, 1.25)
+C_GAIN = (0.5, 1.5)
+Y_SHIFT = 30.0
+C_SHIFT = 15.0
+SOFTEN_MAX = 0.85
+# Every 2nd pixel in each direction is enough for the statistics.
+STEP = 2
def fail(message):
@@ -60,41 +79,124 @@ def parse_boundaries(text):
return sorted(out)
-def channel_stats(frames):
- """Mean and standard deviation per channel over a list of HxWx3 uint8."""
- stack = np.stack(frames).astype(np.float64)
- flat = stack.reshape(-1, 3)
- return flat.mean(axis=0), flat.std(axis=0)
-
-
-def make_transform(ref_frames, cur_frames):
- ref_mean, ref_std = channel_stats(ref_frames)
- cur_mean, cur_std = channel_stats(cur_frames)
- gain = np.ones(3)
- for c in range(3):
- if cur_std[c] > 1e-6:
- gain[c] = ref_std[c] / cur_std[c]
- gain = np.clip(gain, GAIN_MIN, GAIN_MAX)
- seam = {
- "refMean": [round(float(v), 3) for v in ref_mean],
- "curMean": [round(float(v), 3) for v in cur_mean],
- "refStd": [round(float(v), 3) for v in ref_std],
- "curStd": [round(float(v), 3) for v in cur_std],
- "gain": [round(float(v), 4) for v in gain],
- "refFrames": len(ref_frames),
- "curFrames": len(cur_frames),
+def planes(frame, w, h):
+ """Y (h x w), U and V (h/2 x w/2) of a decoded frame, as uint8."""
+ if frame.format.name != "yuv420p":
+ frame = frame.reformat(format="yuv420p")
+ a = frame.to_ndarray(format="yuv420p")
+ fw = frame.width
+ fh = frame.height
+ y = a[:fh, :fw]
+ qw, qh = fw // 2, fh // 2
+ u = a[fh:fh + fh // 4].reshape(-1)[: qw * qh].reshape(qh, qw)
+ v = a[fh + fh // 4:].reshape(-1)[: qw * qh].reshape(qh, qw)
+ return y[:h, :w], u[: h // 2, : w // 2], v[: h // 2, : w // 2]
+
+
+def to_frame(y, u, v):
+ h, w = y.shape
+ a = np.empty((h * 3 // 2, w), dtype=np.uint8)
+ a[:h] = y
+ a[h:h + h // 4] = u.reshape(h // 4, w)
+ a[h + h // 4:] = v.reshape(h // 4, w)
+ return av.VideoFrame.from_ndarray(a, format="yuv420p")
+
+
+def blur(img):
+ """5-tap binomial blur along both axes, edges repeated."""
+ out = img.astype(np.float32)
+ for axis in (0, 1):
+ pad = [(0, 0), (0, 0)]
+ pad[axis] = (2, 2)
+ p = np.pad(out, pad, mode="edge")
+ n = out.shape[axis]
+ acc = np.zeros_like(out)
+ for i, w in enumerate((1.0, 4.0, 6.0, 4.0, 1.0)):
+ acc += w * np.take(p, range(i, i + n), axis=axis)
+ out = acc / 16.0
+ return out
+
+
+def sharpness(y):
+ y = y.astype(np.float32)
+ lap = 4 * y[1:-1, 1:-1] - y[:-2, 1:-1] - y[2:, 1:-1] - y[1:-1, :-2] - y[1:-1, 2:]
+ return float(np.abs(lap).mean())
+
+
+def frame_stats(y, u, v, with_blur):
+ sub = [p[::STEP, ::STEP].astype(np.float64) for p in (y, u, v)]
+ row = {
+ "mean": np.array([p.mean() for p in sub]),
+ "std": np.array([p.std() for p in sub]),
+ "sharp": sharpness(y),
}
- return (cur_mean, gain, ref_mean), seam
+ if with_blur:
+ row["sharpBlur"] = sharpness(blur(y))
+ return row
+
+
+def smooth(values, window, cuts):
+ """Centred moving average over `window` frames each side, never across a
+ cut (indices where a new section starts)."""
+ arr = np.asarray(values, dtype=np.float64)
+ out = np.empty_like(arr)
+ edges = [0] + [c for c in cuts if 0 < c < len(arr)] + [len(arr)]
+ for lo_seg, hi_seg in zip(edges, edges[1:]):
+ for i in range(lo_seg, hi_seg):
+ lo, hi = max(lo_seg, i - window), min(hi_seg, i + window + 1)
+ out[i] = arr[lo:hi].mean(axis=0)
+ return out
+
+
+def plan_frames(stats, anchor_end, start, window, boundaries):
+ """Per frame from `start` on: (mean_t, gain, target, soften), and the
+ anchor's numbers."""
+ anchor = stats[:anchor_end]
+ a_mean = np.mean([r["mean"] for r in anchor], axis=0)
+ a_std = np.mean([r["std"] for r in anchor], axis=0)
+ a_sharp = float(np.mean([r["sharp"] for r in anchor]))
+ rest = stats[start:]
+ cuts = [b - start for b in boundaries if b > start]
+ m = smooth([r["mean"] for r in rest], window, cuts)
+ sd = smooth([r["std"] for r in rest], window, cuts)
+ sh = smooth([r["sharp"] for r in rest], window, cuts)
+ sb = smooth([r["sharpBlur"] for r in rest], window, cuts)
+ plan = []
+ for i in range(len(rest)):
+ gain = np.ones(3)
+ for c in range(3):
+ if sd[i][c] > 1e-6:
+ gain[c] = a_std[c] / sd[i][c]
+ gain[0] = min(max(gain[0], Y_GAIN[0]), Y_GAIN[1])
+ gain[1:] = np.clip(gain[1:], C_GAIN[0], C_GAIN[1])
+ target = m[i].copy()
+ target[0] += float(np.clip(a_mean[0] - m[i][0], -Y_SHIFT, Y_SHIFT))
+ target[1:] += np.clip(a_mean[1:] - m[i][1:], -C_SHIFT, C_SHIFT)
+ # The Laplacian scales with the Y gain; blending towards the blurred
+ # copy moves it linearly between the two.
+ s_now, s_soft = gain[0] * sh[i], gain[0] * sb[i]
+ soften = 0.0
+ if s_now > a_sharp and s_now - s_soft > 1e-6:
+ soften = min(SOFTEN_MAX, (s_now - a_sharp) / (s_now - s_soft))
+ plan.append((m[i], gain, target, soften))
+ anchor_info = {
+ "mean": [round(float(x), 3) for x in a_mean],
+ "std": [round(float(x), 3) for x in a_std],
+ "sharp": round(a_sharp, 3),
+ }
+ return plan, anchor_info
-def apply_transform(frame, transform):
- if transform is None:
- return frame
- cur_mean, gain, ref_mean = transform
- out = (frame.astype(np.float32) - cur_mean.astype(np.float32)) * gain.astype(np.float32)
- out += ref_mean.astype(np.float32)
- np.clip(out, 0.0, 255.0, out=out)
- return np.rint(out).astype(np.uint8)
+def apply_plan(y, u, v, step):
+ mean_t, gain, target, soften = step
+ out = []
+ for c, p in enumerate((y, u, v)):
+ f = (p.astype(np.float32) - np.float32(mean_t[c])) * np.float32(gain[c]) + np.float32(target[c])
+ if soften > 0:
+ f += np.float32(soften) * (blur(f) - f)
+ np.clip(f, 0.0, 255.0, out=f)
+ out.append(np.rint(f).astype(np.uint8))
+ return out
def add_audio_stream(output, in_audio):
@@ -107,12 +209,28 @@ def add_audio_stream(output, in_audio):
return None, "audio not copied: %s" % exc
+def copy_audio(input_path, output, out_audio):
+ """Remux the source's audio behind the video. Returns (copied, note)."""
+ try:
+ with av.open(input_path) as again:
+ stream = again.streams.audio[0]
+ for packet in again.demux(stream):
+ if packet.dts is None:
+ continue
+ packet.stream = out_audio
+ output.mux(packet)
+ return True, None
+ except Exception as exc:
+ return False, "audio not copied: %s" % exc
+
+
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True)
parser.add_argument("--output", required=True)
parser.add_argument("--boundaries", default="")
- parser.add_argument("--window", type=int, default=5)
+ parser.add_argument("--anchor-end", type=int, default=0)
+ parser.add_argument("--window", type=int, default=8)
parser.add_argument("--crf", type=int, default=18)
args = parser.parse_args()
@@ -128,16 +246,37 @@ def main():
if not source.streams.video:
fail("The file has no video stream.")
in_video = source.streams.video[0]
- in_audio = source.streams.audio[0] if source.streams.audio else None
+ has_audio = bool(source.streams.audio)
width = in_video.codec_context.width
height = in_video.codec_context.height
if width * height > MAX_PIXELS:
fail("Frames of %dx%d are larger than this step handles." % (width, height))
- rate = in_video.average_rate or in_video.guessed_rate or Fraction(24, 1)
- rate = Fraction(rate)
+ rate = Fraction(in_video.average_rate or in_video.guessed_rate or Fraction(24, 1))
# yuv420p needs even sides; an odd one loses its last row or column.
out_w, out_h = width - (width % 2), height - (height % 2)
+ # Pass 1: numbers per frame.
+ stats = []
+ try:
+ for frame in source.decode(in_video):
+ stats.append(frame_stats(*planes(frame, out_w, out_h), with_blur=True))
+ except Exception as exc:
+ fail("Reading failed at frame %d: %s" % (len(stats), exc))
+ source.close()
+ total = len(stats)
+
+ inside = [b for b in requested if 0 < b < total]
+ ignored = [b for b in requested if b not in inside]
+ anchor_end = args.anchor_end if args.anchor_end > 0 else (inside[0] if inside else 0)
+ after = [b for b in inside if b >= anchor_end]
+ ignored.extend(b for b in inside if b < anchor_end)
+ start = after[0] if after else None
+ if start is None or anchor_end < 1 or anchor_end >= total:
+ start = total # nothing to correct: a plain copy
+ plan, anchor_info = [], None
+ else:
+ plan, anchor_info = plan_frames(stats, anchor_end, start, window, after)
+
output = av.open(args.output, mode="w")
out_video = output.add_stream("h264", rate=rate)
out_video.width = out_w
@@ -149,103 +288,68 @@ def main():
pass
time_base = Fraction(1, 1) / rate
out_audio, audio_note = (None, None)
- if in_audio is not None:
- out_audio, audio_note = add_audio_stream(output, in_audio)
-
- written = 0
-
- def write(frame_array):
- nonlocal written
- if frame_array.shape[1] != out_w or frame_array.shape[0] != out_h:
- frame_array = frame_array[:out_h, :out_w]
- vf = av.VideoFrame.from_ndarray(np.ascontiguousarray(frame_array), format="rgb24")
- vf.pts = written
- vf.time_base = time_base
- for packet in out_video.encode(vf):
- output.mux(packet)
- written += 1
+ if has_audio:
+ with av.open(args.input) as probe:
+ out_audio, audio_note = add_audio_stream(output, probe.streams.audio[0])
- pending = deque(requested)
- while pending and pending[0] <= 0:
- pending.popleft()
- ignored = [b for b in requested if b <= 0]
- seams = []
- recent = deque(maxlen=window) # last corrected frames
- transform = None
- sample = None # raw frames collected after a boundary
- sample_start = None
- sample_end = None
+ # Pass 2: write.
index = 0
-
- def close_sample():
- nonlocal transform, sample, sample_start
- new_transform, seam = make_transform(list(recent), sample)
- seam["frame"] = sample_start
- seams.append(seam)
- transform = new_transform
- for raw in sample:
- fixed = apply_transform(raw, transform)
- write(fixed)
- recent.append(fixed)
- sample = None
- sample_start = None
-
try:
- for frame in source.decode(in_video):
- raw = frame.to_ndarray(format="rgb24")
- if pending and index == pending[0]:
- if sample is not None:
- close_sample()
- pending.popleft()
- sample, sample_start = [], index
- # The sample stays inside its own section.
- sample_end = min(index + window, pending[0] if pending else index + window)
- if sample is not None:
- sample.append(raw)
- if index + 1 >= sample_end:
- close_sample()
- else:
- fixed = apply_transform(raw, transform)
- write(fixed)
- recent.append(fixed)
- index += 1
- if sample is not None:
- close_sample()
+ with av.open(args.input) as again:
+ for frame in again.decode(again.streams.video[0]):
+ y, u, v = planes(frame, out_w, out_h)
+ if index >= start:
+ y, u, v = apply_plan(y, u, v, plan[index - start])
+ vf = to_frame(y, u, v)
+ vf.pts = index
+ vf.time_base = time_base
+ for packet in out_video.encode(vf):
+ output.mux(packet)
+ index += 1
for packet in out_video.encode():
output.mux(packet)
- except SystemExit:
- raise
except Exception as exc:
output.close()
fail("Processing failed at frame %d: %s" % (index, exc))
- ignored.extend(pending)
- source.close()
-
audio_copied = False
if out_audio is not None:
- try:
- with av.open(args.input) as again:
- stream = again.streams.audio[0]
- for packet in again.demux(stream):
- if packet.dts is None:
- continue
- packet.stream = out_audio
- output.mux(packet)
- audio_copied = True
- except Exception as exc:
- audio_note = "audio not copied: %s" % exc
+ audio_copied, note = copy_audio(args.input, output, out_audio)
+ audio_note = note or audio_note
output.close()
+ seams = []
+ if anchor_info is not None:
+ cuts = after + [total]
+ for lo, hi in zip(cuts, cuts[1:]):
+ part = plan[lo - start:hi - start]
+ raw = stats[lo:hi]
+ softens = [p[3] for p in part]
+ seams.append({
+ "frame": lo,
+ "space": "yuv",
+ "refMean": anchor_info["mean"],
+ "refStd": anchor_info["std"],
+ "curMean": [round(float(x), 3) for x in np.mean([r["mean"] for r in raw], axis=0)],
+ "curStd": [round(float(x), 3) for x in np.mean([r["std"] for r in raw], axis=0)],
+ "gain": [round(float(x), 4) for x in np.mean([p[1] for p in part], axis=0)],
+ "refFrames": anchor_end,
+ "curFrames": hi - lo,
+ "refSharp": anchor_info["sharp"],
+ "curSharp": round(float(np.mean([r["sharp"] for r in raw])), 3),
+ "soften": round(float(np.mean(softens)), 4),
+ "softenMax": round(float(np.max(softens)), 4),
+ })
+
print(json.dumps({
"ok": True,
- "frames": written,
+ "frames": index,
"width": out_w,
"height": out_h,
"fps": float(rate),
"window": window,
"seams": seams,
- "ignoredBoundaries": ignored,
+ "ignoredBoundaries": sorted(ignored),
"audio": audio_copied,
"note": audio_note,
}))
diff --git a/src-tauri/src/commands/video_settle.rs b/src-tauri/src/commands/video_settle.rs
index 5b0f99cc..e498c2f1 100644
--- a/src-tauri/src/commands/video_settle.rs
+++ b/src-tauri/src/commands/video_settle.rs
@@ -1,12 +1,12 @@
//! Colour settle for a long video made of several sections (3.0.9).
//!
-//! A 30 second clip is rendered as sections that each continue from the last
-//! frame of the one before. Every section drifts a little in brightness,
-//! contrast and tint, and over five or six sections that adds up to a visible
-//! jump at every seam. `video_color_settle` takes the finished, already
-//! concatenated clip and matches each section to the corrected one before it
-//! (the rule is in video_settle.py, which runs on ComfyUI's own Python with
-//! numpy and PyAV, both in ComfyUI's requirements).
+//! A long clip is rendered as sections that each continue from the last
+//! frames of the one before. Every section comes out more saturated and
+//! sharper than the one it continues, and over a few sections that adds up.
+//! `video_color_settle` takes the finished, already concatenated clip and
+//! matches every frame from the newest seam on to the clip's first section,
+//! the anchor (the rule is in video_settle.py, which runs on ComfyUI's own
+//! Python with numpy and PyAV, both in ComfyUI's requirements).
//!
//! The frontend only knows ComfyUI's own file names (filename, subfolder,
//! type), the same triple the gallery shows. The file is resolved here inside
@@ -38,8 +38,8 @@ const SCRIPT: &str = include_str!("video_settle.py");
/// the frontend can skip the step without showing an error.
pub const NOT_AVAILABLE: &str = "not available";
-/// Default frames on each side of a seam that the statistics are taken over.
-pub(crate) const DEFAULT_WINDOW: u32 = 5;
+/// Default frames on each side that a frame's statistics are smoothed over.
+pub(crate) const DEFAULT_WINDOW: u32 = 8;
/// Upper bound, the same as the script's own.
pub(crate) const MAX_WINDOW: u32 = 60;
/// A 30 second 832x480 clip takes well under a minute; ten minutes covers a
@@ -48,8 +48,9 @@ const RUN_TIMEOUT: Duration = Duration::from_secs(600);
/// Video containers a section render can come out as.
const VIDEO_EXTENSIONS: &[&str] = &["mp4", "webm", "mov", "mkv"];
-/// One seam as the script measured it. Means and deviations are per RGB
-/// channel on the 0..255 scale.
+/// One corrected section as the script measured it. Means and deviations are
+/// per plane of the video's YUV (`space`), on the 0..255 scale; `ref*` is the
+/// anchor, `cur*` the section as it came out.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SettleSeam {
@@ -59,10 +60,22 @@ pub struct SettleSeam {
pub cur_mean: [f64; 3],
pub ref_std: [f64; 3],
pub cur_std: [f64; 3],
- /// The contrast factor applied, already clamped to 0.8..1.25.
+ /// The mean contrast factor applied per plane, already clamped.
pub gain: [f64; 3],
pub ref_frames: u32,
pub cur_frames: u32,
+ #[serde(default)]
+ pub space: Option<String>,
+ /// Sharpness (mean absolute Laplacian of Y) of the anchor and the section.
+ #[serde(default)]
+ pub ref_sharp: Option<f64>,
+ #[serde(default)]
+ pub cur_sharp: Option<f64>,
+ /// How far frames were blended towards a blurred copy, mean and most.
+ #[serde(default)]
+ pub soften: Option<f64>,
+ #[serde(default)]
+ pub soften_max: Option<f64>,
}
/// What the script prints as its last line.
@@ -198,9 +211,9 @@ pub(crate) fn effective_window(window: Option<u32>) -> Result<u32, String> {
/// The interpreter's argument list: isolated mode, the script, then every
/// path as its own argument. No shell ever sees these.
-pub(crate) fn script_args(script: &Path, input: &Path, output: &Path, boundaries: &[u32], window: u32) -> Vec<OsString> {
+pub(crate) fn script_args(script: &Path, input: &Path, output: &Path, boundaries: &[u32], window: u32, anchor_end: Option<u32>) -> Vec<OsString> {
let list = boundaries.iter().map(u32::to_string).collect::<Vec<_>>().join(",");
- vec![
+ let mut args: Vec<OsString> = vec![
"-I".into(),
script.as_os_str().to_owned(),
"--input".into(),
@@ -211,7 +224,12 @@ pub(crate) fn script_args(script: &Path, input: &Path, output: &Path, boundaries
list.into(),
"--window".into(),
window.to_string().into(),
- ]
+ ];
+ if let Some(end) = anchor_end.filter(|e| *e > 0) {
+ args.push("--anchor-end".into());
+ args.push(end.to_string().into());
+ }
+ args
}
/// The report out of the script's stdout: the last line that is JSON. Lines
@@ -288,6 +306,7 @@ fn settle_blocking(
folder_type: &str,
boundaries: Vec<u32>,
window: Option<u32>,
+ anchor_end: Option<u32>,
) -> Result<SettleReport, String> {
let folder = ComfyFolder::parse(folder_type)?;
let window = effective_window(window)?;
@@ -307,7 +326,7 @@ fn settle_blocking(
// stopped run never leaves a half file under the name the gallery shows.
let partial = out_dir.join(format!(".lu-settle-{}-{}.mp4", std::process::id(), uuid::Uuid::new_v4().simple()));
let (_script_dir, script) = crate::private_tmp::write_private_temp("lu-settle-", "video_settle.py", SCRIPT.as_bytes())?;
- let args = script_args(&script, &input, &partial, &boundaries, window);
+ let args = script_args(&script, &input, &partial, &boundaries, window, anchor_end);
let run = run_with_timeout(&python, &args, RUN_TIMEOUT);
let finish = || {
@@ -350,7 +369,9 @@ fn settle_blocking(
/// Settle the colour across the seams of a long video in ComfyUI's output
/// (or input) folder. `boundaries` are the frame indices where a new section
-/// starts, `window` the frames per side the statistics use (default 5).
+/// starts; frames from the first of them on are matched to the anchor, frames
+/// `0..anchor_end` (default: all before the first boundary). `window` is the
+/// frames per side the statistics are smoothed over (default 8).
// ASYNC + spawn_blocking, like start_comfyui: the run takes seconds to
// minutes and must not sit on the main thread.
#[tauri::command]
@@ -361,10 +382,11 @@ pub async fn video_color_settle(
folder_type: String,
boundaries: Vec<u32>,
window: Option<u32>,
+ anchor_end: Option<u32>,
) -> Result<SettleReport, String> {
tokio::task::spawn_blocking(move || {
let state = app.state::<AppState>();
- settle_blocking(&state, &filename, &subfolder, &folder_type, boundaries, window)
+ settle_blocking(&state, &filename, &subfolder, &folder_type, boundaries, window, anchor_end)
})
.await
.map_err(|e| format!("video_color_settle task: {e}"))?
@@ -449,7 +471,7 @@ mod tests {
assert_eq!(ComfyFolder::parse("input").unwrap(), ComfyFolder::Input);
assert!(ComfyFolder::parse("temp").is_err());
assert!(ComfyFolder::parse("../output").is_err());
- assert_eq!(effective_window(None).unwrap(), 5);
+ assert_eq!(effective_window(None).unwrap(), 8);
assert_eq!(effective_window(Some(12)).unwrap(), 12);
assert!(effective_window(Some(0)).is_err());
assert!(effective_window(Some(MAX_WINDOW + 1)).is_err());
@@ -464,6 +486,7 @@ mod tests {
Path::new("/c/out/.lu-settle-1.mp4"),
&[81, 157],
5,
+ None,
);
let text: Vec<String> = args.iter().map(|a| a.to_string_lossy().to_string()).collect();
assert_eq!(
@@ -483,6 +506,30 @@ mod tests {
);
}
+ #[test]
+ fn the_anchor_goes_to_the_script_only_when_given() {
+ let args = |anchor| {
+ script_args(Path::new("/s.py"), Path::new("/i.mp4"), Path::new("/o.mp4"), &[157], 8, anchor)
+ .iter()
+ .map(|a| a.to_string_lossy().to_string())
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(args(Some(81))[9..], ["8", "--anchor-end", "81"]);
+ assert_eq!(args(None).len(), 10);
+ assert_eq!(args(Some(0)).len(), 10);
+ }
+
+ #[test]
+ fn a_report_with_the_anchor_numbers_reads() {
+ let out = "{\"ok\": true, \"frames\": 233, \"seams\": [{\"frame\": 157, \"space\": \"yuv\", \"refMean\": [1,2,3], \
+ \"curMean\": [1,2,3], \"refStd\": [1,1,1], \"curStd\": [1,1,1], \"gain\": [1,0.8,0.8], \"refFrames\": 81, \
+ \"curFrames\": 76, \"refSharp\": 6.9, \"curSharp\": 10.0, \"soften\": 0.4, \"softenMax\": 0.5}]}";
+ let r = parse_script_output(out).unwrap();
+ assert_eq!(r.seams[0].space.as_deref(), Some("yuv"));
+ assert_eq!(r.seams[0].soften_max, Some(0.5));
+ assert_eq!(r.seams[0].ref_frames, 81);
+ }
+
#[test]
fn the_report_is_the_last_json_line() {
let out = "some warning\n{\"ok\": true, \"frames\": 240, \"width\": 832, \"height\": 480, \"fps\": 16.0, \"window\": 5, \
@@ -516,6 +563,15 @@ mod tests {
}
}
+ /// P5: PyAV's yuv420p -> rgb24 -> yuv420p round trip lost about 1.2
+ /// levels of brightness per pass, and a long clip passes through here
+ /// once per section. The script works on the YUV planes only.
+ #[test]
+ fn the_script_never_takes_a_detour_through_rgb() {
+ assert!(!SCRIPT.contains("rgb24"), "video_settle.py converts to RGB");
+ assert!(SCRIPT.contains("format=\"yuv420p\""));
+ }
+
#[test]
fn the_command_is_registered_for_the_desktop_only() {
const LIB: &str = include_str!("../lib.rs");
diff --git a/src/api/video-settle.ts b/src/api/video-settle.ts
index 9e5c33ba..2ee1f69b 100644
--- a/src/api/video-settle.ts
+++ b/src/api/video-settle.ts
@@ -1,8 +1,9 @@
// The colour settle at the seams of a long clip (B18, 3.0.9). The work is a
// numpy step in ComfyUI's own Python, started by the Rust command
-// video_color_settle (src-tauri/src/commands/video_settle.rs): each section
-// is matched to the settled one before it, so the whole clip keeps the
-// colours of its first section. The command only reaches a ComfyUI LU manages
+// video_color_settle (src-tauri/src/commands/video_settle.rs): every frame
+// from the newest seam on is matched to the clip's first section (colour,
+// saturation, sharpness), so the drift of one section never carries into the
+// next. The command only reaches a ComfyUI LU manages
// on this machine; anywhere else this returns null and the clip stays as it
// came out.
@@ -19,6 +20,8 @@ export interface SettleReport {
export async function settleSeams(
item: { filename?: string; subfolder?: string; comfyType?: string },
boundaries: number[],
+ /** Frames of the anchor, the clip's first section. */
+ anchorEnd?: number,
): Promise<SettleReport | null> {
if (!isTauri() || !item.filename || boundaries.length === 0) return null
try {
@@ -27,7 +30,8 @@ export async function settleSeams(
subfolder: item.subfolder ?? '',
folderType: item.comfyType === 'input' ? 'input' : 'output',
boundaries,
- window: 5,
+ window: 8,
+ ...(anchorEnd && anchorEnd > 0 ? { anchorEnd } : {}),
})
return report?.filename ? report : null
} catch (e) {
diff --git a/src/components/create/experimental/LongVideoControls.tsx b/src/components/create/experimental/LongVideoControls.tsx
index 5af7cd93..55ea74c5 100644
--- a/src/components/create/experimental/LongVideoControls.tsx
+++ b/src/components/create/experimental/LongVideoControls.tsx
@@ -139,7 +139,7 @@ export function LongVideoControls({ model, intent }: { model: string; intent: st
? 'Continues from the last frames of the clip, the result is the whole clip, longer.'
: s.longVideoMode === 'one-pass'
? 'One run past the native length. Keeps the scene even; motion may repeat.'
- : `Past ${nativeSeconds} s the clip is made in sections. Each one continues from the last frames, colours are matched at every seam.`}
+ : `Past ${nativeSeconds} s the clip is made in sections. Each one continues from the last frames and is held to the colours and sharpness of the first.`}
</p>
)}
{estimate && (
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 883c16ad..848a4fe8 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -2538,8 +2538,8 @@ export function useCreate() {
fetchBlob: (item) => fetchGalleryItemBlob(item as GalleryItem),
upload: (blob, name) => uploadMediaFile(blob, name),
remove: (id) => useCreateStore.getState().removeFromGallery(id),
- settle: async (item: ClipItem, seams) => {
- const settled = await settleSeams(item, seams)
+ settle: async (item: ClipItem, seams, anchorEnd) => {
+ const settled = await settleSeams(item, seams, anchorEnd)
if (!settled) return null
const st = useCreateStore.getState()
const old = st.gallery.find((g) => g.id === item.id)
diff --git a/src/lib/__tests__/long-video-offers-fifteen-seconds.test.ts b/src/lib/__tests__/long-video-offers-fifteen-seconds.test.ts
new file mode 100644
index 00000000..6958a066
--- /dev/null
+++ b/src/lib/__tests__/long-video-offers-fifteen-seconds.test.ts
@@ -0,0 +1,53 @@
+/**
+ * P5 (3.0.9): the Length control stops at 15 s. The B18 box runs made 30 s
+ * with clean seams, but every section came out more saturated and sharper
+ * than the one before, clearly so past 10–15 s. Until David decides (D2) the
+ * control offers 15 s; one constant opens it to 30 s.
+ *
+ * Run: npx vitest run src/lib/__tests__/long-video-offers-fifteen-seconds.test.ts
+ */
+import { describe, expect, it } from 'vitest'
+import { LONG_SECONDS_CAP, MAX_LONG_SECONDS, planLongVideo } from '../long-video'
+import { longVideoRequest, type LongVideoAsk } from '../long-video-run'
+import { useCreateStore } from '../../stores/createStore'
+
+const ask = (over: Partial<LongVideoAsk>): LongVideoAsk => ({
+ mode: 'video', intent: 'video',
+ model: 'wan2.2_i2v_high_noise_14B_Q4_K_S.gguf', type: 'wan',
+ installed: ['wan2.2_i2v_high_noise_14B_Q4_K_S.gguf'],
+ longVideoSeconds: 15, longVideoMode: 'sections', fps: 16, frames: 81, extendClip: null,
+ ...over,
+})
+
+describe('the Length control offers 15 s for now', () => {
+ it('the limit is 15 s, the sections themselves still reach 30 s', () => {
+ expect(MAX_LONG_SECONDS).toBe(15)
+ expect(LONG_SECONDS_CAP).toBe(30)
+ expect(planLongVideo('wan', 30, 16)!.seconds).toBeGreaterThanOrEqual(30)
+ })
+
+ it('the store keeps a longer ask at 15 s', () => {
+ useCreateStore.getState().setLongVideoSeconds(30)
+ expect(useCreateStore.getState().longVideoSeconds).toBe(15)
+ useCreateStore.getState().setLongVideoSeconds(12)
+ expect(useCreateStore.getState().longVideoSeconds).toBe(12)
+ })
+
+ it('a saved 30 s from before makes a 15 s clip, not 30', () => {
+ const r = longVideoRequest(ask({ longVideoSeconds: 30 }))
+ expect(r?.kind).toBe('sections')
+ if (r?.kind !== 'sections') return
+ // 81 + 76 + 76 = 233 frames, 14.6 s: a fourth section would add 0.4 s
+ // for a whole run.
+ expect(r.plan.seconds).toBeGreaterThan(14.5)
+ expect(r.plan.seconds).toBeLessThan(15.3)
+ expect(r.plan.sections).toEqual([81, 81, 81])
+ })
+
+ it('Extend Video adds at most 15 s in one go', () => {
+ const r = longVideoRequest(ask({ intent: 'extend', longVideoSeconds: 30, extendClip: new Blob(['x']) }))
+ expect(r?.kind).toBe('sections')
+ if (r?.kind !== 'sections') return
+ expect(r.plan.seconds).toBeLessThan(15.3)
+ })
+})
diff --git a/src/lib/__tests__/long-video.test.ts b/src/lib/__tests__/long-video.test.ts
index 9dc4c364..03c49256 100644
--- a/src/lib/__tests__/long-video.test.ts
+++ b/src/lib/__tests__/long-video.test.ts
@@ -178,6 +178,28 @@ describe('runLongVideo: section after section, one clip in the gallery', () => {
expect(seen[0]).toEqual([81])
expect(seen[1]).toEqual([157])
})
+
+ it('matches every new section to the first one, not to the one before (P5)', async () => {
+ const f = fakeDeps()
+ const anchors: number[] = []
+ await runLongVideo(planLongVideo('wan', 30, 16)!, { firstModel: 'T', continueModel: 'I' }, {
+ ...f.deps,
+ settle: async (item, _seams, anchorEnd) => { anchors.push(anchorEnd); return item },
+ })
+ expect(anchors).toHaveLength(6)
+ expect(new Set(anchors)).toEqual(new Set([81]))
+ })
+
+ it('an extended clip is its own anchor', async () => {
+ const f = fakeDeps()
+ const anchors: number[] = []
+ const plan = planExtension('wan', 10, 16)!
+ await runLongVideo(plan, { firstModel: 'I', continueModel: 'I', clip: new Blob(['x']), clipFrames: 161 }, {
+ ...f.deps,
+ settle: async (item, _seams, anchorEnd) => { anchors.push(anchorEnd); return item },
+ })
+ expect(new Set(anchors)).toEqual(new Set([161]))
+ })
})
describe('Fast mode for the Wan 14B models', () => {
diff --git a/src/lib/long-video-run.ts b/src/lib/long-video-run.ts
index ca1b5647..b7d897c3 100644
--- a/src/lib/long-video-run.ts
+++ b/src/lib/long-video-run.ts
@@ -8,14 +8,14 @@
// gallery: the hook's run adds each one, this removes the one before it.
// A clip the user brought (Extend Video) is never removed.
//
-// After each section the seam gets a colour settle when the backend can do it
-// (a numpy step in ComfyUI's own Python, Rust command video_color_settle):
-// the next section then starts from settled frames, so a drift cannot carry
-// over and add up. Without it (a ComfyUI LU does not manage) the run goes on
+// After each section the new frames are matched to the first section when the
+// backend can do it (a numpy step in ComfyUI's own Python, Rust command
+// video_color_settle): the next section then starts from settled frames, so a
+// drift cannot carry over and add up. Without it (a ComfyUI LU does not manage) the run goes on
// unsettled.
import type { ModelType } from '../api/comfyui'
-import { planLongVideo, sectionSpec, type LongVideoPlan } from './long-video'
+import { MAX_LONG_SECONDS, planLongVideo, sectionSpec, type LongVideoPlan } from './long-video'
/** What the chain needs to know about a gallery entry. */
export interface ClipItem {
@@ -37,9 +37,10 @@ export interface LongRunDeps {
/** Into ComfyUI's input folder; returns the name LoadVideo lists. */
upload: (blob: Blob, name: string) => Promise<string>
remove: (id: string) => void
- /** Settle the colours at the seams, in place of the item; null when the
+ /** Match everything from the boundaries on to the anchor (frames
+ * 0..anchorEnd, the first section), in place of the item; null when the
* backend cannot. */
- settle?: (item: ClipItem, boundaries: number[]) => Promise<ClipItem | null>
+ settle?: (item: ClipItem, boundaries: number[], anchorEnd: number) => Promise<ClipItem | null>
aborted: () => boolean
}
@@ -154,11 +155,12 @@ export async function runLongVideo(plan: LongVideoPlan, start: LongRunStart, dep
seams.push(frames)
frames += sectionFrames - plan.overlap
}
- // Only the newest seam: everything before it was settled in the step
- // before, and this section was made from those settled frames. Passing
- // every seam would only re-encode the old ones again.
+ // Only the newest section, matched to the first one (the anchor):
+ // everything before it was settled in the step before, and this section
+ // was made from those settled frames, so its drift is one step, never the
+ // sum of all before it.
if (deps.settle && seams.length > 0) {
- const settled = await deps.settle(current, seams.slice(-1)).catch(() => null)
+ const settled = await deps.settle(current, seams.slice(-1), seams[0]).catch(() => null)
if (settled) current = settled
}
}
@@ -198,6 +200,9 @@ export function longVideoRequest(ask: LongVideoAsk): LongVideoRequest | null {
const spec = sectionSpec(ask.type)
if (!spec) return null
const fps = ask.fps > 0 ? ask.fps : spec.fps
+ // A value saved before the limit came down never asks for more than the
+ // control offers now.
+ const seconds = Math.min(MAX_LONG_SECONDS, ask.longVideoSeconds)
const continueModel = continueModelFor(ask.model, ask.type, ask.installed)
const noI2v = (): LongVideoRequest => ({
kind: 'error',
@@ -205,14 +210,14 @@ export function longVideoRequest(ask: LongVideoAsk): LongVideoRequest | null {
})
if (ask.intent === 'extend') {
if (!ask.extendClip) return null
- const add = ask.longVideoSeconds > 0 ? ask.longVideoSeconds : (spec.native - spec.overlap) / spec.fps
+ const add = seconds > 0 ? seconds : (spec.native - spec.overlap) / spec.fps
const plan = planExtension(ask.type, add, fps)
if (!plan) return null
if (!continueModel) return noI2v()
return { kind: 'sections', plan, start: { firstModel: continueModel, continueModel, clip: ask.extendClip } }
}
- if (!(ask.longVideoSeconds > 0) || ask.longVideoSeconds * fps <= spec.native) return null
- const plan = planLongVideo(ask.type, ask.longVideoSeconds, fps)
+ if (!(seconds > 0) || seconds * fps <= spec.native) return null
+ const plan = planLongVideo(ask.type, seconds, fps)
if (!plan || plan.sections.length < 2) return null
if (ask.longVideoMode === 'one-pass') return { kind: 'one-pass', frames: plan.totalFrames }
if (!continueModel) return noI2v()
diff --git a/src/lib/long-video.ts b/src/lib/long-video.ts
index b33898e1..7d94d53e 100644
--- a/src/lib/long-video.ts
+++ b/src/lib/long-video.ts
@@ -22,8 +22,15 @@
import type { ModelType } from '../api/comfyui'
-/** The longest clip the Seconds control offers. */
-export const MAX_LONG_SECONDS = 30
+/** The longest clip sections can make. The box run of 3.0.9 made 30 s with
+ * clean seams, so the plan itself goes this far. */
+export const LONG_SECONDS_CAP = 30
+
+/** The longest clip the Length control offers (and the most Extend Video
+ * adds in one go). 15 s for 3.0.9: past that the box runs drifted towards
+ * a saturated, oversharpened picture (B18). Set it to LONG_SECONDS_CAP to
+ * offer the full 30 s; nothing else needs to change. */
+export const MAX_LONG_SECONDS = 15
export interface SectionSpec {
/** Frames of one section at the model's native length. */
@@ -71,19 +78,21 @@ export interface LongVideoPlan {
* the native length (or shorter for a short clip), each later one adds up to
* `native - overlap` new frames, and the last one is cut to what is left,
* on the family's grid and never shorter than its overlap plus one grid step.
- * The clip never comes out shorter than asked; it may run up to one grid step
- * longer.
+ * The clip may run up to one grid step longer than asked, or up to half a
+ * second shorter where one more section would only add those few frames.
*/
export function planLongVideo(type: ModelType | string, seconds: number, fps?: number): LongVideoPlan | null {
const spec = sectionSpec(type)
if (!spec) return null
const rate = fps && fps > 0 ? fps : spec.fps
- const want = snapUp(Math.round(Math.min(MAX_LONG_SECONDS, Math.max(1, seconds)) * rate), spec.grid)
+ const want = snapUp(Math.round(Math.min(LONG_SECONDS_CAP, Math.max(1, seconds)) * rate), spec.grid)
const first = Math.min(spec.native, want)
const sections = [first]
let total = first
const step = spec.native - spec.overlap
- while (total < want) {
+ // A last section that would add half a second or less costs a whole run
+ // (model load, decode) for almost nothing: the clip ends that much short.
+ while (want - total > Math.max(spec.grid, rate / 2)) {
const add = Math.min(step, want - total)
const frames = Math.max(spec.overlap + spec.grid, snapUp(spec.overlap + add, spec.grid))
sections.push(frames)