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.

fix(video): a long clip no longer grows brighter section by section (P5 box run)

purpleb2e05759fbb6
diff --git a/src-tauri/src/commands/video_settle.py b/src-tauri/src/commands/video_settle.py
index 7de9cdcf..fee0c6b0 100644
--- a/src-tauri/src/commands/video_settle.py
+++ b/src-tauri/src/commands/video_settle.py
@@ -31,6 +31,19 @@ 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.
+``--base`` (P5 box run, 30 s): the file this step wrote last time. ComfyUI
+hands back the WHOLE clip with every section, and its copy of the frames
+already there went through its own RGB round trip: +1.3 to +1.6 levels of Y
+and 3 to 4 % more saturation per section, the first section included. Matched
+to the first section, every section looked even while the whole clip grew
+brighter (Y 74.8 -> 83.8 over six sections). With ``--base`` the frames before
+the newest boundary come from that file instead, so only the new section is
+ComfyUI's. When the base does not have exactly that many frames of the same
+size, it is left out and the report says why.
+
+The output carries the colour tags of the input (range, matrix, primaries,
+transfer). Without them ComfyUI read the next clip with another matrix.
+
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.
@@ -51,11 +64,13 @@ import numpy as np
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.
+# scene that really changed from being forced back. Chroma is wider (P5 box
+# run, 30 s): a short last section of A14B + lightx2v came out with U and V
+# 20 to 27 levels off the anchor and needed gains near 0.35.
Y_GAIN = (0.75, 1.25)
-C_GAIN = (0.5, 1.5)
+C_GAIN = (0.35, 1.5)
Y_SHIFT = 30.0
-C_SHIFT = 15.0
+C_SHIFT = 30.0
SOFTEN_MAX = 0.85
# Every 2nd pixel in each direction is enough for the statistics.
STEP = 2
@@ -123,6 +138,36 @@ def sharpness(y):
return float(np.abs(lap).mean())
+COLOR_FIELDS = ("color_range", "colorspace", "color_primaries", "color_trc")
+
+
+def read_color(source):
+ """The colour tags of a codec context or frame that PyAV exposes."""
+ tags = {}
+ for name in COLOR_FIELDS:
+ try:
+ tags[name] = getattr(source, name)
+ except Exception:
+ pass
+ return tags
+
+
+def apply_color(tags, target):
+ """Set the tags on a codec context or frame; older PyAV lacks some."""
+ for name, value in tags.items():
+ try:
+ setattr(target, name, value)
+ except Exception:
+ pass
+
+
+def frame_count_and_size(path):
+ with av.open(path) as c:
+ s = c.streams.video[0]
+ n = sum(1 for _ in c.decode(s))
+ return n, s.codec_context.width, s.codec_context.height
+
+
def frame_stats(y, u, v, with_blur):
sub = [p[::STEP, ::STEP].astype(np.float64) for p in (y, u, v)]
row = {
@@ -232,6 +277,7 @@ def main():
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)
+ parser.add_argument("--base", default="")
args = parser.parse_args()
window = args.window
@@ -255,17 +301,52 @@ def main():
# yuv420p needs even sides; an odd one loses its last row or column.
out_w, out_h = width - (width % 2), height - (height % 2)
+ color = read_color(in_video.codec_context)
+ # The input's frame count first: whether the base fits depends on it.
+ try:
+ total = sum(1 for _ in source.decode(in_video))
+ except Exception as exc:
+ fail("Reading failed: %s" % exc)
+ source.close()
+
+ inside = [b for b in requested if 0 < b < total]
+ base_frames, base_note = 0, None
+ if args.base:
+ newest = inside[-1] if inside else 0
+ try:
+ n, bw, bh = frame_count_and_size(args.base)
+ except Exception as exc:
+ n, bw, bh = -1, 0, 0
+ base_note = "base not read: %s" % exc
+ if base_note is None:
+ if newest < 1 or n != newest or (bw - bw % 2, bh - bh % 2) != (out_w, out_h):
+ base_note = "base left out: %d frames of %dx%d, the clip needs %d of %dx%d" % (n, bw, bh, newest, out_w, out_h)
+ else:
+ base_frames = newest
+
+ def frames_in_order():
+ """Planes of every frame: the first base_frames from the base, the
+ rest from the input."""
+ if base_frames:
+ with av.open(args.base) as b:
+ for i, frame in enumerate(b.decode(b.streams.video[0])):
+ if i >= base_frames:
+ break
+ yield planes(frame, out_w, out_h)
+ with av.open(args.input) as c:
+ for i, frame in enumerate(c.decode(c.streams.video[0])):
+ if i >= base_frames:
+ yield planes(frame, out_w, out_h)
+
# 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))
+ for p in frames_in_order():
+ stats.append(frame_stats(*p, 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]
@@ -282,6 +363,7 @@ def main():
out_video.width = out_w
out_video.height = out_h
out_video.pix_fmt = "yuv420p"
+ apply_color(color, out_video.codec_context)
try:
out_video.options = {"crf": str(args.crf)}
except Exception:
@@ -295,17 +377,16 @@ def main():
# Pass 2: write.
index = 0
try:
- 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 y, u, v in frames_in_order():
+ if index >= start:
+ y, u, v = apply_plan(y, u, v, plan[index - start])
+ vf = to_frame(y, u, v)
+ apply_color(color, vf)
+ 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 Exception as exc:
@@ -352,6 +433,8 @@ def main():
"ignoredBoundaries": sorted(ignored),
"audio": audio_copied,
"note": audio_note,
+ "base": base_frames,
+ "baseNote": base_note,
}))
diff --git a/src-tauri/src/commands/video_settle.rs b/src-tauri/src/commands/video_settle.rs
index e498c2f1..5a1a4397 100644
--- a/src-tauri/src/commands/video_settle.rs
+++ b/src-tauri/src/commands/video_settle.rs
@@ -101,6 +101,10 @@ struct ScriptReport {
audio: bool,
#[serde(default)]
note: Option<String>,
+ #[serde(default)]
+ base: u32,
+ #[serde(default)]
+ base_note: Option<String>,
}
/// What the command returns.
@@ -123,6 +127,10 @@ pub struct SettleReport {
/// The source's audio track was copied over unchanged.
pub audio: bool,
pub note: Option<String>,
+ /// Frames taken from the base (the last settled clip) instead of the input.
+ pub base: u32,
+ /// Why the base was left out, when it was.
+ pub base_note: Option<String>,
}
/// The ComfyUI folder a file triple names: `output` or `input`.
@@ -211,7 +219,15 @@ 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, anchor_end: Option<u32>) -> Vec<OsString> {
+pub(crate) fn script_args(
+ script: &Path,
+ input: &Path,
+ output: &Path,
+ boundaries: &[u32],
+ window: u32,
+ anchor_end: Option<u32>,
+ base: Option<&Path>,
+) -> Vec<OsString> {
let list = boundaries.iter().map(u32::to_string).collect::<Vec<_>>().join(",");
let mut args: Vec<OsString> = vec![
"-I".into(),
@@ -229,6 +245,10 @@ pub(crate) fn script_args(script: &Path, input: &Path, output: &Path, boundaries
args.push("--anchor-end".into());
args.push(end.to_string().into());
}
+ if let Some(b) = base {
+ args.push("--base".into());
+ args.push(b.as_os_str().to_owned());
+ }
args
}
@@ -299,6 +319,7 @@ fn run_with_timeout(python: &str, args: &[OsString], timeout: Duration) -> Resul
Ok((status.success(), out.join().unwrap_or_default(), err.join().unwrap_or_default()))
}
+#[allow(clippy::too_many_arguments)]
fn settle_blocking(
state: &AppState,
filename: &str,
@@ -307,6 +328,7 @@ fn settle_blocking(
boundaries: Vec<u32>,
window: Option<u32>,
anchor_end: Option<u32>,
+ base_filename: Option<&str>,
) -> Result<SettleReport, String> {
let folder = ComfyFolder::parse(folder_type)?;
let window = effective_window(window)?;
@@ -318,6 +340,12 @@ fn settle_blocking(
ComfyFolder::Input => paths.input_dir_or(&comfy_dir),
};
let input = resolve_source(&base, filename, subfolder)?;
+ // The last settled clip, in the same folder: its frames stand in for
+ // ComfyUI's re-encoded copy of them (see --base in video_settle.py).
+ let base_file = match base_filename.filter(|b| !b.is_empty()) {
+ Some(b) => Some(resolve_source(&base, b, subfolder)?),
+ None => None,
+ };
let python = crate::commands::process::comfy_tool_python(state, &comfy_dir)
.map_err(|e| format!("{NOT_AVAILABLE}: {e}"))?;
@@ -326,7 +354,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, anchor_end);
+ let args = script_args(&script, &input, &partial, &boundaries, window, anchor_end, base_file.as_deref());
let run = run_with_timeout(&python, &args, RUN_TIMEOUT);
let finish = || {
@@ -364,6 +392,8 @@ fn settle_blocking(
ignored_boundaries: report.ignored_boundaries,
audio: report.audio,
note: report.note,
+ base: report.base,
+ base_note: report.base_note,
})
}
@@ -375,6 +405,7 @@ fn settle_blocking(
// ASYNC + spawn_blocking, like start_comfyui: the run takes seconds to
// minutes and must not sit on the main thread.
#[tauri::command]
+#[allow(clippy::too_many_arguments)]
pub async fn video_color_settle(
app: tauri::AppHandle,
filename: String,
@@ -383,10 +414,11 @@ pub async fn video_color_settle(
boundaries: Vec<u32>,
window: Option<u32>,
anchor_end: Option<u32>,
+ base_filename: Option<String>,
) -> Result<SettleReport, String> {
tokio::task::spawn_blocking(move || {
let state = app.state::<AppState>();
- settle_blocking(&state, &filename, &subfolder, &folder_type, boundaries, window, anchor_end)
+ settle_blocking(&state, &filename, &subfolder, &folder_type, boundaries, window, anchor_end, base_filename.as_deref())
})
.await
.map_err(|e| format!("video_color_settle task: {e}"))?
@@ -487,6 +519,7 @@ mod tests {
&[81, 157],
5,
None,
+ None,
);
let text: Vec<String> = args.iter().map(|a| a.to_string_lossy().to_string()).collect();
assert_eq!(
@@ -509,7 +542,7 @@ 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)
+ script_args(Path::new("/s.py"), Path::new("/i.mp4"), Path::new("/o.mp4"), &[157], 8, anchor, None)
.iter()
.map(|a| a.to_string_lossy().to_string())
.collect::<Vec<_>>()
@@ -519,6 +552,31 @@ mod tests {
assert_eq!(args(Some(0)).len(), 10);
}
+ #[test]
+ fn the_base_goes_to_the_script_as_its_own_argument() {
+ let args = script_args(
+ Path::new("/s.py"),
+ Path::new("/i.mp4"),
+ Path::new("/o.mp4"),
+ &[233],
+ 8,
+ Some(81),
+ Some(Path::new("/c/out/clip 1; x_settled.mp4")),
+ );
+ let text: Vec<String> = args.iter().map(|a| a.to_string_lossy().to_string()).collect();
+ assert_eq!(text[10..], ["--anchor-end", "81", "--base", "/c/out/clip 1; x_settled.mp4"]);
+ }
+
+ #[test]
+ fn a_report_says_how_many_frames_came_from_the_base() {
+ let r = parse_script_output("{\"ok\": true, \"frames\": 309, \"seams\": [], \"base\": 233, \"baseNote\": null}").unwrap();
+ assert_eq!(r.base, 233);
+ let r = parse_script_output("{\"ok\": true, \"frames\": 309, \"seams\": [], \"base\": 0, \"baseNote\": \"base left out\"}").unwrap();
+ assert_eq!((r.base, r.base_note.as_deref()), (0, Some("base left out")));
+ // An older script without the field still reads.
+ assert_eq!(parse_script_output("{\"ok\": true, \"frames\": 1, \"seams\": []}").unwrap().base, 0);
+ }
+
#[test]
fn a_report_with_the_anchor_numbers_reads() {
let out = "{\"ok\": true, \"frames\": 233, \"seams\": [{\"frame\": 157, \"space\": \"yuv\", \"refMean\": [1,2,3], \
diff --git a/src/api/__tests__/video-settle-base.test.ts b/src/api/__tests__/video-settle-base.test.ts
new file mode 100644
index 00000000..7c68b8f9
--- /dev/null
+++ b/src/api/__tests__/video-settle-base.test.ts
@@ -0,0 +1,35 @@
+// The settle takes the frames already there from the clip it settled last
+// time (P5 box run, 30 s): ComfyUI's copy of them came out brighter with
+// every section. The base only goes along when it lies next to the item,
+// since the command looks for it in the item's own folder.
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const calls: Array<Record<string, unknown>> = []
+vi.mock('../backend', () => ({
+ isTauri: () => true,
+ backendCall: async (_cmd: string, args: Record<string, unknown>) => {
+ calls.push(args)
+ return { filename: 'clip_settled.mp4', subfolder: String(args.subfolder ?? '') }
+ },
+}))
+
+import { settleSeams } from '../video-settle'
+
+describe('settleSeams and its base', () => {
+ beforeEach(() => { calls.length = 0 })
+
+ it('sends the base file name with the call', async () => {
+ await settleSeams({ filename: 'vid_00008_.mp4', subfolder: '' }, [157], 81, { filename: 'vid_00007__settled.mp4', subfolder: '' })
+ expect(calls[0]).toMatchObject({ filename: 'vid_00008_.mp4', boundaries: [157], anchorEnd: 81, baseFilename: 'vid_00007__settled.mp4' })
+ })
+
+ it('leaves the base out when it lies in another subfolder', async () => {
+ await settleSeams({ filename: 'a.mp4', subfolder: 'video' }, [157], 81, { filename: 'b.mp4', subfolder: '' })
+ expect(calls[0]).not.toHaveProperty('baseFilename')
+ })
+
+ it('works as before without a base', async () => {
+ await settleSeams({ filename: 'a.mp4' }, [81], 81)
+ expect(calls[0]).not.toHaveProperty('baseFilename')
+ })
+})
diff --git a/src/api/video-settle.ts b/src/api/video-settle.ts
index 2ee1f69b..3a0e2106 100644
--- a/src/api/video-settle.ts
+++ b/src/api/video-settle.ts
@@ -22,6 +22,9 @@ export async function settleSeams(
boundaries: number[],
/** Frames of the anchor, the clip's first section. */
anchorEnd?: number,
+ /** The clip this step settled last time, in the same folder: its frames
+ * stand in for ComfyUI's re-encoded copy of them. */
+ base?: { filename?: string; subfolder?: string },
): Promise<SettleReport | null> {
if (!isTauri() || !item.filename || boundaries.length === 0) return null
try {
@@ -32,6 +35,7 @@ export async function settleSeams(
boundaries,
window: 8,
...(anchorEnd && anchorEnd > 0 ? { anchorEnd } : {}),
+ ...(base?.filename && (base.subfolder ?? '') === (item.subfolder ?? '') ? { baseFilename: base.filename } : {}),
})
return report?.filename ? report : null
} catch (e) {
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index c66cc9ab..b45ac757 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -2533,8 +2533,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, anchorEnd) => {
- const settled = await settleSeams(item, seams, anchorEnd)
+ settle: async (item: ClipItem, seams, anchorEnd, base) => {
+ const settled = await settleSeams(item, seams, anchorEnd, base)
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.test.ts b/src/lib/__tests__/long-video.test.ts
index 03c49256..653682df 100644
--- a/src/lib/__tests__/long-video.test.ts
+++ b/src/lib/__tests__/long-video.test.ts
@@ -200,6 +200,52 @@ describe('runLongVideo: section after section, one clip in the gallery', () => {
})
expect(new Set(anchors)).toEqual(new Set([161]))
})
+
+ // P5 box run, 30 s: ComfyUI hands back the whole clip with every section,
+ // and its copy of the frames already there came out brighter each time
+ // (Y 74.8 -> 83.8 over six sections, the first one included). The settle
+ // takes those frames from the clip the section continued instead.
+ it('gives the settle the clip each section continued as its base', async () => {
+ const f = fakeDeps()
+ const calls: Array<{ item: string; base?: string }> = []
+ await runLongVideo(planLongVideo('wan', 15, 16)!, { firstModel: 'T', continueModel: 'I' }, {
+ ...f.deps,
+ settle: async (item, _seams, _anchorEnd, base) => {
+ calls.push({ item: item.id, base: base?.id })
+ return { ...item, id: `${item.id}-settled` }
+ },
+ })
+ expect(calls).toHaveLength(2)
+ // Section 2 continued section 1 as it came out; section 3 continued the
+ // settled clip of the step before, never ComfyUI's newest copy.
+ expect(calls[0].base).toBeDefined()
+ expect(calls[0].base).not.toBe(calls[0].item)
+ expect(calls[1].base).toBe(`${calls[0].item}-settled`)
+ })
+
+ it('a settle that fails leaves the next base on the clip that was continued', async () => {
+ const f = fakeDeps()
+ const calls: Array<{ item: string; base?: string }> = []
+ await runLongVideo(planLongVideo('wan', 15, 16)!, { firstModel: 'T', continueModel: 'I' }, {
+ ...f.deps,
+ settle: async (item, _seams, _anchorEnd, base) => {
+ calls.push({ item: item.id, base: base?.id })
+ return null
+ },
+ })
+ expect(calls[1].base).toBe(calls[0].item)
+ })
+
+ it('a brought clip is never a base: it is not in ComfyUI\'s output', async () => {
+ const f = fakeDeps()
+ const bases: Array<string | undefined> = []
+ await runLongVideo(planExtension('wan', 10, 16)!, { firstModel: 'I', continueModel: 'I', clip: new Blob(['x']), clipFrames: 161 }, {
+ ...f.deps,
+ settle: async (item, _seams, _anchorEnd, base) => { bases.push(base?.id); return { ...item, id: `${item.id}-settled` } },
+ })
+ expect(bases[0]).toBeUndefined()
+ if (bases.length > 1) expect(bases[1]).toMatch(/-settled$/)
+ })
})
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 b7d897c3..2ad0ecdd 100644
--- a/src/lib/long-video-run.ts
+++ b/src/lib/long-video-run.ts
@@ -39,8 +39,9 @@ export interface LongRunDeps {
remove: (id: string) => void
/** 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[], anchorEnd: number) => Promise<ClipItem | null>
+ * backend cannot. `base` is the clip settled the step before: the frames
+ * before the newest boundary are taken from it, not from ComfyUI's copy. */
+ settle?: (item: ClipItem, boundaries: number[], anchorEnd: number, base?: ClipItem) => Promise<ClipItem | null>
aborted: () => boolean
}
@@ -148,6 +149,12 @@ export async function runLongVideo(plan: LongVideoPlan, start: LongRunStart, dep
{ videoModel: start.continueModel, frames: sectionFrames, cloudOp: 'extend', mode: 'video' },
{ stepLabel: `Section ${index + 1} of ${total}`, continueFrom: { video: name, overlap: plan.overlap } },
)
+ // The clip this section continued, when it is our own (not a brought
+ // one): ComfyUI hands back the whole clip, and its copy of these frames
+ // went through its own RGB round trip (P5 box run, 30 s: +1.3 to +1.6
+ // levels of Y per section, the first section included). The settle takes
+ // them from here instead.
+ const continued = current
// Only our own in-between clips are taken out of the gallery.
if (current) deps.remove(current.id)
current = made
@@ -160,7 +167,7 @@ export async function runLongVideo(plan: LongVideoPlan, start: LongRunStart, dep
// 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), seams[0]).catch(() => null)
+ const settled = await deps.settle(current, seams.slice(-1), seams[0], continued ?? undefined).catch(() => null)
if (settled) current = settled
}
}