Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(video): decouple reference start frame from sample length
Lincoln Steinbc14e62b47a7
diff --git a/invokeai/app/invocations/minimax_h3_reference.py b/invokeai/app/invocations/minimax_h3_reference.pyindex 3194c0f00f..b5f3aeb47f 100644--- a/invokeai/app/invocations/minimax_h3_reference.py+++ b/invokeai/app/invocations/minimax_h3_reference.py@@ -199,16 +199,24 @@ class _ResolvedVideoRange:else:raise ValueError(f"Could not determine the frame rate of reference video {reference.video.video_name}.")- def resolve(value: int, name: str) -> int:- resolved = value + n_frames if value < 0 else value- if resolved < 0 or resolved >= n_frames:- raise ValueError(f"{name}={value} is out of range for a {n_frames}-frame reference video.")- return resolved-- self.start = resolve(reference.start_frame, "start_frame")- self.end = resolve(reference.end_frame, "end_frame")- if self.start > self.end:- raise ValueError(f"start_frame ({self.start}) must not be after end_frame ({self.end}).")+ start = reference.start_frame + n_frames if reference.start_frame < 0 else reference.start_frame+ if start < 0 or start >= n_frames:+ raise ValueError(+ f"start_frame={reference.start_frame} is out of range for a {n_frames}-frame reference video."+ )+ self.start = start+ # The sample LENGTH is pinned to what the clip can actually supply rather than+ # rejected: "start here and take N frames" past the last frame reads as "take the+ # rest of the clip", and the panel's frame count is an estimate the real count can+ # undershoot. A start frame that is itself off the end has no such reading, and an+ # end before the start is an inverted range, so both still raise.+ end = reference.end_frame + n_frames if reference.end_frame < 0 else reference.end_frame+ if end < self.start:+ raise ValueError(+ f"end_frame ({reference.end_frame} -> {end}) must not be before start_frame "+ f"({reference.start_frame} -> {self.start})."+ )+ self.end = min(end, n_frames - 1)def load_reference_video_frames(diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.ts b/invokeai/frontend/webv2/src/features/video/core/graph.tsindex 6334b7ecd2..8a228edb86 100644--- a/invokeai/frontend/webv2/src/features/video/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/video/core/graph.ts@@ -131,9 +131,10 @@ const addReferenceNode = (* bounds on the estimate already. And a start within `TAIL_INDEX_SLOP` of the* clip's own beginning stays absolute because the relative form resolves to* `startFrame + (real - estimate)`, which goes NEGATIVE once the estimate- * overshoots by more than `startFrame` — and `_ResolvedVideoRange.resolve`- * rejects an out-of-range index outright rather than clamping, failing the- * whole generation. That can only arise when the window fills nearly the entire+ * overshoots by more than `startFrame` — and `_ResolvedVideoRange` rejects an+ * out-of-range START index outright rather than clamping, failing the whole+ * generation. (Only the END bound is clamped there, pinning the sample length+ * to the frames the clip can supply.) That can only arise when the window fills nearly the entire* clip, where its length cannot be honoured anyway; below the slop the absolute* form is always in range, and the drift it costs is the estimate error itself,* a frame or two.diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.tsindex 70b35d9194..64448d2c23 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts@@ -931,12 +931,17 @@ describe('reference sample window', () => {expect([next.startFrame, next.endFrame]).toEqual([50, 249]);});- it('stops at the clip end instead of shrinking (no overshoot ratchet)', () => {- // Drag far past the wall, then back to 0: the length must survive the round trip.- const overshot = slideReferenceSampleWindow(clip(0, 199), 299, false);- expect([overshot.startFrame, overshot.endFrame]).toEqual([100, 299]);- const back = slideReferenceSampleWindow(overshot, 0, false);- expect([back.startFrame, back.endFrame]).toEqual([0, 199]);+ it('keeps the length while the clip can still supply it', () => {+ const next = slideReferenceSampleWindow(clip(0, 199), 100, false);+ expect([next.startFrame, next.endFrame]).toEqual([100, 299]);+ });++ it('pins the length to the frames left instead of blocking the start', () => {+ // The start reaches the frame the user picked; the sample is what gives way.+ const shortened = slideReferenceSampleWindow(clip(0, 199), 250, false);+ expect([shortened.startFrame, shortened.endFrame]).toEqual([250, 299]);+ const lastFrame = slideReferenceSampleWindow(clip(0, 199), 299, false);+ expect([lastFrame.startFrame, lastFrame.endFrame]).toEqual([299, 299]);});it('keeps the extend anchor end pinned to the cutpoint', () => {@@ -959,7 +964,7 @@ describe('reference sample window', () => {expect(inverted.endFrame).toBeGreaterThanOrEqual(inverted.startFrame);expect(inverted.endFrame).toBeLessThanOrEqual(19);const oversized = slideReferenceSampleWindow(clip(0, 999, 20), 5, false);- expect([oversized.startFrame, oversized.endFrame]).toEqual([0, 19]);+ expect([oversized.startFrame, oversized.endFrame]).toEqual([5, 19]);});it('handles a single-frame clip', () => {diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.tsindex 67ff8bd225..15c3e7006b 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts@@ -92,11 +92,14 @@ export const DEFAULT_REFERENCE_SAMPLE_FRAMES = 200;/*** Move a reference clip's sample window to a new start frame.*- * Ordinary references slide at CONSTANT length, stopping at the clip's end rather than- * shrinking — a transient overshoot during a drag must not ratchet the sample down. The- * reference-extend anchor (`pinEnd`) instead keeps its end frame pinned to the Initial- * Video cutpoint (seam continuity depends on the frames adjacent to it; see- * deriveReferenceExtendClip), so moving its start only adjusts the lead-in length.+ * The two controls are independent: an ordinary reference's start frame reaches every+ * frame of the clip, and the sample length is what gives way — it keeps its value while+ * there is clip left to fill it and is pinned to the remaining frames past that, so+ * `start + length` never runs beyond the last frame. (The length slider's ceiling in the+ * panel is the same `numFrames - startFrame`, so the control tracks what the window can+ * actually hold.) The reference-extend anchor (`pinEnd`) instead keeps its end frame+ * pinned to the Initial Video cutpoint (seam continuity depends on the frames adjacent to+ * it; see deriveReferenceExtendClip), so moving its start only adjusts the lead-in length.** Self-healing by construction: the returned window always satisfies* 0 <= start <= end <= numFrames - 1, even from a corrupt persisted trim.@@ -116,9 +119,9 @@ export const slideReferenceSampleWindow = (}const sampleFrames = Math.min(Math.max(1, clip.endFrame - clip.startFrame + 1), maxFrame + 1);- const startFrame = Math.min(Math.max(0, Math.round(rawStart)), maxFrame - (sampleFrames - 1));+ const startFrame = Math.min(Math.max(0, Math.round(rawStart)), maxFrame);- return { ...clip, endFrame: startFrame + sampleFrames - 1, startFrame };+ return { ...clip, endFrame: Math.min(startFrame + sampleFrames - 1, maxFrame), startFrame };};/**diff --git a/tests/app/invocations/test_minimax_h3_reference_nodes.py b/tests/app/invocations/test_minimax_h3_reference_nodes.pyindex e0282c0cc1..011ee57c69 100644--- a/tests/app/invocations/test_minimax_h3_reference_nodes.py+++ b/tests/app/invocations/test_minimax_h3_reference_nodes.py@@ -5,7 +5,7 @@ prompt-vs-conditioning signature cross-checks in the denoise node, and the task-guard. The numerics live in tests/backend/minimax_h3/."""-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patchimport pytestimport torch@@ -20,6 +20,7 @@ from invokeai.app.invocations.fields import ()from invokeai.app.invocations.minimax_h3_denoise import MiniMaxH3DenoiseInvocationfrom invokeai.app.invocations.minimax_h3_reference import (+ _ResolvedVideoRange,normalize_reference_list,reference_has_audio,reference_kind,@@ -86,6 +87,48 @@ class TestMediaField:assert reference_signature_entry(_image_ref(), (1024, 1024), 124) != image+class TestResolvedVideoRange:+ """The reference range's start/length enforcement. No decoding: the probe is stubbed."""++ @staticmethod+ def _resolve(start: int, end: int, n_frames: int = 300) -> _ResolvedVideoRange:+ context = MagicMock()+ context.videos.get_path.return_value = "clip.mp4"+ reference = _video_ref()+ reference.start_frame = start+ reference.end_frame = end+ with (+ patch(+ "invokeai.app.invocations.minimax_h3_reference.probe_video",+ return_value=(640, 480, n_frames / 24.0, 24.0),+ ),+ patch("invokeai.app.invocations.minimax_h3_reference.decoder_frame_count", return_value=n_frames),+ ):+ return _ResolvedVideoRange(context, reference)++ def test_resolves_positive_and_negative_bounds(self):+ span = self._resolve(10, 49)+ assert (span.start, span.end) == (10, 49)+ tail = self._resolve(-24, -1)+ assert (tail.start, tail.end) == (276, 299)++ def test_pins_the_length_to_the_last_frame(self):+ # A start frame plus a length that runs past the end takes the rest of the clip+ # rather than failing the generation.+ span = self._resolve(250, 449)+ assert (span.start, span.end) == (250, 299)++ def test_rejects_a_start_frame_past_the_end(self):+ with pytest.raises(ValueError, match="start_frame=300 is out of range"):+ self._resolve(300, 400)+ with pytest.raises(ValueError, match="start_frame=-301 is out of range"):+ self._resolve(-301, -1)++ def test_rejects_an_inverted_range(self):+ with pytest.raises(ValueError, match="must not be before start_frame"):+ self._resolve(100, 50)++def _transformer_field(variant: str | None) -> MiniMaxH3TransformerField:return MiniMaxH3TransformerField(transformer=ModelIdentifierField(