Skip to content

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.

fix(video): repair three defects found in adversarial review

Lincoln Stein5c7fd9a000a2
diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts b/invokeai/frontend/webv2/src/features/video/core/graph.test.ts
index 0467666892..257240085b 100644
--- a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/graph.test.ts
@@ -557,7 +557,7 @@ describe('compileVideoGraph — MiniMax H3 Ref2VA', () => {
);
});
- it('reference-extend: only the linked tail window is anchored to the clip end', () => {
+ it('a window ending in the tail anchors BOTH bounds to the clip end', () => {
const linked = (clip: Record<string, unknown>, flag = true) => ({
clip: { fps: 24, height: 480, numFrames: 402, video_name: 'long.mp4', width: 832, ...clip },
conditioning: 'video_audio' as const,
@@ -570,9 +570,15 @@ describe('compileVideoGraph — MiniMax H3 Ref2VA', () => {
'minimax_h3_video_reference'
).start_frame;
- // A user's own reference keeps an absolute start: their trim is a position,
- // not a length, and re-anchoring it would drift with the estimate.
- expect(startOf(linked({ endFrame: 400, startFrame: 260 }, false))).toBe(260);
+ // Both bounds convert together, flagged or not. Mixing an absolute start
+ // with a tail-relative end splits the window across two index spaces: the
+ // backend then extracts `length + (real - estimate)` frames, or -- on a
+ // window short enough for the error to swallow -- resolves the end BEFORE
+ // the start and fails the generation.
+ expect(startOf(linked({ endFrame: 400, startFrame: 260 }, false))).toBe(-142);
+ // The inversion that mixing produced: [398,399] of an estimated 402 emitted
+ // `398 / -3`, which against a real 400 is start 398, end 397.
+ expect(startOf(linked({ endFrame: 399, startFrame: 398 }, false))).toBe(-4);
// A start at or inside the estimate's slop stays ABSOLUTE: the relative
// form resolves to `startFrame + (real - estimate)`, and the backend
// rejects a negative index rather than clamping, so an estimate that
@@ -584,7 +590,7 @@ describe('compileVideoGraph — MiniMax H3 Ref2VA', () => {
expect(startOf(linked({ endFrame: 400, startFrame: 4 }))).toBe(-398);
// A cutpoint far enough from the end that BOTH bounds keep the estimate.
expect(startOf(linked({ endFrame: 300, startFrame: 160 }))).toBe(160);
- // The tail case: end went negative, so the start follows it.
+ // The anchor's tail window: end went negative, so the start follows it.
expect(startOf(linked({ endFrame: 400, startFrame: 260 }))).toBe(-142);
});
diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.ts b/invokeai/frontend/webv2/src/features/video/core/graph.ts
index bbc01ee552..52488fb670 100644
--- a/invokeai/frontend/webv2/src/features/video/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/graph.ts
@@ -16,7 +16,7 @@ import {
} from '@features/generation/graph';
import { getCompatibleDiffusersComponentSource } from '@features/generation/settings';
-import type { VideoGenerationMode, VideoReferenceItem, VideoSettings } from './types';
+import type { VideoGenerationMode, VideoReferenceItem, VideoSettings, VideoSourceClip } from './types';
import { resolveVideoMode } from './settings';
import { getVideoDimensions, getVideoModelPolicy, getVideoValidationReasons } from './videoPolicies';
@@ -104,7 +104,7 @@ const addReferenceNode = (
conditioning: reference.conditioning,
end_frame: endFrame,
id: `reference_${index + 1}`,
- start_frame: toReferenceStartIndex(reference, endFrame),
+ start_frame: toReferenceStartIndex(reference.clip, endFrame),
type: 'minimax_h3_video_reference',
video: { video_name: reference.clip.video_name },
});
@@ -115,31 +115,31 @@ const addReferenceNode = (
*
* `toTailAwareIndex` sends a near-the-end bound out NEGATIVE, resolved against
* the clip's REAL frame count, and leaves anything further back POSITIVE, taken
- * from the panel's ESTIMATE. That split is right for a hand-picked trim, whose
- * start is an absolute position the estimate must not drift — but the linked
- * tail window straddles it: the cutpoint end goes negative while the start,
- * ~124 frames back, stays positive, so what the backend extracts is
- * `tail + (real - estimate)` frames rather than `tail`. That length is a budget
- * the backend enforces by discarding the overrun at the SEAM (see
- * `deriveReferenceExtendClip`), so it has to survive an inexact estimate.
+ * from the panel's ESTIMATE. Applied to each bound independently that splits a
+ * window across two index spaces: a window ENDING in the tail but starting
+ * further back emits a negative end beside a positive start, so the backend
+ * extracts `length + (real - estimate)` frames — or, when the window is short
+ * enough for the estimate error to swallow it, resolves the end BEFORE the
+ * start and fails the generation outright. (`[295,296]` of an estimated 300
+ * emits `295 / -4`; against a real 298 that is start 295, end 294.)
*
- * The linked entry's start is not an absolute pick — it is defined as
- * `tail - 1` frames before the cutpoint — so it rides the same negative anchor
- * and the window keeps its length whatever the real count turns out to be.
+ * So the two bounds are converted TOGETHER. Once the end has gone tail-relative
+ * the window is anchored to the real end anyway, and what is worth preserving
+ * is its LENGTH — which is also the budget the backend enforces by discarding
+ * the overrun from the window's end (see `deriveReferenceExtendClip`), so it
+ * has to survive an inexact estimate. The start rides the same anchor.
*
- * Three cases stay absolute. A window the user moved off the derived default
- * (`trimOverridden`) is a hand-picked trim like any other, so it takes the
- * hand-picked treatment. A cutpoint far enough from the end leaves both
- * 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
+ * Two cases stay absolute. A window far enough from the end leaves both 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` 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.
+ * 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.
*
* DECIDED: the slop is not widened beyond 3. An estimate error past the slop
* can still fail the relative form, but only on a clip barely longer than the
@@ -148,15 +148,8 @@ const addReferenceNode = (
* remove the cliff — it would move it, and pay for the move with silent length
* drift on every clip inside the wider margin.
*/
-const toReferenceStartIndex = (reference: Extract<VideoReferenceItem, { kind: 'video' }>, endIndex: number): number => {
- const { clip } = reference;
-
- if (
- reference.fromSourceVideo !== true ||
- reference.trimOverridden === true ||
- endIndex >= 0 ||
- clip.startFrame <= TAIL_INDEX_SLOP
- ) {
+const toReferenceStartIndex = (clip: VideoSourceClip, endIndex: number): number => {
+ if (endIndex >= 0 || clip.startFrame <= TAIL_INDEX_SLOP) {
return toTailAwareIndex(clip.startFrame, clip.numFrames);
}
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
index 2eb743d10c..27b44e841b 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
@@ -4,6 +4,8 @@ import type { VideoReferenceItem, VideoSettings } from './types';
import { MINIMAX_H3_NUM_FRAMES_CHOICES } from './dimensions';
import {
+ clampReferenceSampleFrames,
+ referenceSampleFrames,
resizeReferenceSampleWindow,
slideReferenceSampleWindow,
applyReferenceExtendSourceVideo,
@@ -796,6 +798,31 @@ describe('reference-extend linkage', () => {
expect(deriveReferenceExtendClip({ ...highRate, fps: 1e17 }, 141)).toMatchObject({ startFrame: 49860 });
});
+ it('a demoted anchor loses its override, so re-setting the clip re-derives', () => {
+ // The corrupt-record shape the flag canonicalization exists to heal: two
+ // flagged entries for the same clip. The demoted one kept `trimOverridden`,
+ // and adopt-by-name then honoured that stale window on the next Initial
+ // Video set -- the help text's "clear and re-set to get the default back"
+ // silently did nothing.
+ const overriddenNamed = (video_name: string) => ({
+ ...VIDEO_REFERENCE,
+ clip: { ...VIDEO_REFERENCE.clip, endFrame: 60, startFrame: 40, video_name },
+ fromSourceVideo: true,
+ trimOverridden: true,
+ });
+ const healed = normalizeVideoSettings(
+ createSettings({ references: [overriddenNamed('long.mp4'), overriddenNamed('b.mp4')] })
+ );
+
+ expect(healed?.references[0]).toMatchObject({ fromSourceVideo: false, trimOverridden: false });
+
+ // Setting that clip as the Initial Video adopts the demoted entry by name
+ // and must derive the default window, not resurrect the stale one.
+ const adopted = applyReferenceExtendSourceVideo(healed!.references.slice(0, 1), source24, 3, FRAMES);
+
+ expect(adopted[0]).toMatchObject({ clip: { endFrame: 400, startFrame: 260 }, fromSourceVideo: true });
+ });
+
it('adopts an unflagged reference for the same clip instead of duplicating it (recall shape)', () => {
const recalled = { ...VIDEO_REFERENCE, clip: { ...VIDEO_REFERENCE.clip, video_name: 'long.mp4' } };
const result = applyReferenceExtendSourceVideo([IMAGE_REFERENCE, recalled], source24, 3, FRAMES);
@@ -1010,6 +1037,61 @@ describe('reference sample window', () => {
const next = slideReferenceSampleWindow(clip(0, 0, 1), 5);
expect([next.startFrame, next.endFrame]).toEqual([0, 0]);
});
+
+ it('a drag past the clip end comes back with its length intact', () => {
+ // A slider commits a value per pointer step, so the round trip is the
+ // test: without the recorded request each step would take its length from
+ // the already-clamped window it was handed, and one overshoot-and-back
+ // would leave a 200-frame sample at 1 frame.
+ let reference: Extract<VideoReferenceItem, { kind: 'video' }> = {
+ clip: clip(0, 199),
+ conditioning: 'video_audio',
+ kind: 'video',
+ };
+ const drag = (rawStart: number) => {
+ const sampleFrames = referenceSampleFrames(reference);
+
+ reference = {
+ ...reference,
+ clip: slideReferenceSampleWindow(reference.clip, rawStart, sampleFrames),
+ sampleFrames,
+ };
+
+ return [reference.clip.startFrame, reference.clip.endFrame];
+ };
+
+ expect([40, 140, 240, 299, 240, 0].map(drag)).toEqual([
+ [40, 239],
+ // Pinned at the clip's end on the way out ...
+ [140, 299],
+ [240, 299],
+ [299, 299],
+ // ... and restored on the way back.
+ [240, 299],
+ [0, 199],
+ ]);
+ });
+
+ it('the length control replaces the recorded request', () => {
+ // Shortening the sample WHILE clamped is a deliberate choice, so sliding
+ // back must restore that length and not the one it replaced.
+ const shortened = resizeReferenceSampleWindow(clip(250, 299), 30);
+ expect([shortened.startFrame, shortened.endFrame]).toEqual([250, 279]);
+ expect(clampReferenceSampleFrames(shortened, 30)).toBe(30);
+ expect(slideReferenceSampleWindow(shortened, 0, 30)).toMatchObject({ endFrame: 29, startFrame: 0 });
+ });
+
+ it('referenceSampleFrames falls back to the window until a control is touched', () => {
+ const untouched: Extract<VideoReferenceItem, { kind: 'video' }> = {
+ clip: clip(10, 29),
+ conditioning: 'video_audio',
+ kind: 'video',
+ };
+ expect(referenceSampleFrames(untouched)).toBe(20);
+ expect(referenceSampleFrames({ ...untouched, sampleFrames: 200 })).toBe(200);
+ // A recorded request larger than the clip could ever hold still clamps.
+ expect(referenceSampleFrames({ ...untouched, sampleFrames: 9999 })).toBe(300);
+ });
});
describe('resizeReferenceSampleWindow', () => {
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.ts
index 4efccbe7ee..fdac44c6cb 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts
@@ -89,14 +89,37 @@ export const VIDEO_REFERENCE_MAX_IMAGES = 9;
*/
export const DEFAULT_REFERENCE_SAMPLE_FRAMES = 200;
+/** A sample length clamped to what the clip could ever hold, whatever a control emitted. */
+export const clampReferenceSampleFrames = (clip: VideoSourceClip, rawSampleFrames: number): number =>
+ Math.min(Math.max(1, Math.round(rawSampleFrames)), Math.max(0, clip.numFrames - 1) + 1);
+
+/**
+ * The sample length a reference is asking for: its recorded intent, else its own window.
+ *
+ * The intent is what makes the two controls independent under a DRAG. A slider emits a
+ * value per pointer step, and each one is committed, so a window that took its length
+ * from the state it was handed would shrink at the clip's end and stay short on the way
+ * back — one overshoot and back would leave a 200-frame sample at 1 frame. The requested
+ * length is therefore carried on the reference (`sampleFrames`) and only the EFFECTIVE
+ * window is clamped.
+ */
+export const referenceSampleFrames = (reference: Extract<VideoReferenceItem, { kind: 'video' }>): number =>
+ clampReferenceSampleFrames(
+ reference.clip,
+ reference.sampleFrames ?? reference.clip.endFrame - reference.clip.startFrame + 1
+ );
+
/**
* Move a reference clip's sample window to a new start frame.
*
* The two controls are independent: the 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 sample length is what gives way — the window keeps the requested length 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.) Pass `requestedSampleFrames` — `referenceSampleFrames` of the reference
+ * BEFORE the drag — to keep a clamped window recoverable; it defaults to the window's own
+ * length, which is the identity only while the window still fits.
*
* Every video reference trims this way, the reference-extend anchor included: Ref2VA has
* no frame-exact seam to protect (see deriveReferenceExtendClip), so the anchor's window
@@ -105,9 +128,13 @@ export const DEFAULT_REFERENCE_SAMPLE_FRAMES = 200;
* Self-healing by construction: the returned window always satisfies
* 0 <= start <= end <= numFrames - 1, even from a corrupt persisted trim.
*/
-export const slideReferenceSampleWindow = (clip: VideoSourceClip, rawStart: number): VideoSourceClip => {
+export const slideReferenceSampleWindow = (
+ clip: VideoSourceClip,
+ rawStart: number,
+ requestedSampleFrames?: number
+): VideoSourceClip => {
const maxFrame = Math.max(0, clip.numFrames - 1);
- const sampleFrames = Math.min(Math.max(1, clip.endFrame - clip.startFrame + 1), maxFrame + 1);
+ const sampleFrames = clampReferenceSampleFrames(clip, requestedSampleFrames ?? clip.endFrame - clip.startFrame + 1);
const startFrame = Math.min(Math.max(0, Math.round(rawStart)), maxFrame);
return { ...clip, endFrame: Math.min(startFrame + sampleFrames - 1, maxFrame), startFrame };
@@ -117,11 +144,12 @@ export const slideReferenceSampleWindow = (clip: VideoSourceClip, rawStart: numb
* Resize a reference clip's sample window to a new length in frames.
*
* The window grows forward from its start frame, with the end clamped to the clip. Same
- * self-healing bounds as slideReferenceSampleWindow.
+ * self-healing bounds as slideReferenceSampleWindow. The caller records the requested
+ * length on the reference as `sampleFrames`; this returns only the window it produces.
*/
export const resizeReferenceSampleWindow = (clip: VideoSourceClip, rawSampleFrames: number): VideoSourceClip => {
const maxFrame = Math.max(0, clip.numFrames - 1);
- const sampleFrames = Math.min(Math.max(1, Math.round(rawSampleFrames)), maxFrame + 1);
+ const sampleFrames = clampReferenceSampleFrames(clip, rawSampleFrames);
const startFrame = Math.min(Math.max(0, clip.startFrame), maxFrame);
return { ...clip, endFrame: Math.min(startFrame + sampleFrames - 1, maxFrame), startFrame };
@@ -188,7 +216,13 @@ const sanitizeVideoReferences = (value: unknown, sourceVideoName?: string): Vide
}
valid = valid.map((entry, index) =>
index !== flagged && entry.kind === 'video' && entry.fromSourceVideo === true
- ? { ...entry, fromSourceVideo: false }
+ ? // `trimOverridden` goes with the flag: it only ever means "this ANCHOR's window
+ // is the user's". Left behind on a demoted entry it would be honoured again the
+ // next time adopt-by-name picked that entry up as the anchor, and the clip's
+ // default window would never be derived. The recorded sample length goes with
+ // it — a request kept beside a window it did not produce would spring the window
+ // back to it on the next drag.
+ { ...entry, fromSourceVideo: false, sampleFrames: undefined, trimOverridden: false }
: entry
);
@@ -711,7 +745,8 @@ export const applyReferenceExtendNumFrames = (
}
changed = true;
- return { ...entry, clip: { ...entry.clip, startFrame } };
+ // Re-derived, so the user's recorded sample length no longer describes it.
+ return { ...entry, clip: { ...entry.clip, startFrame }, sampleFrames: undefined };
});
return changed ? next : references;
@@ -831,7 +866,14 @@ export const applyReferenceExtendSourceVideo = (
if (index !== linkedIndex || entry.kind !== 'video') {
return entry;
}
- if (entry.trimOverridden !== true || entry.clip.video_name !== sourceVideo.video_name) {
+ // `fromSourceVideo` is required, not implied by `linkedIndex`: the adopt-by-name
+ // fallback below reaches UNFLAGGED entries (recall restores the pair without the
+ // flag), and those have never been an anchor, so they get the derived default.
+ if (
+ entry.fromSourceVideo !== true ||
+ entry.trimOverridden !== true ||
+ entry.clip.video_name !== sourceVideo.video_name
+ ) {
return { ...linked, conditioning: entry.conditioning };
}
@@ -845,6 +887,7 @@ export const applyReferenceExtendSourceVideo = (
entry.clip.startFrame
),
conditioning: entry.conditioning,
+ sampleFrames: entry.sampleFrames,
trimOverridden: true,
};
})
diff --git a/invokeai/frontend/webv2/src/features/video/core/types.ts b/invokeai/frontend/webv2/src/features/video/core/types.ts
index e030ecf04a..d1793520b5 100644
--- a/invokeai/frontend/webv2/src/features/video/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/types.ts
@@ -66,6 +66,15 @@ export type VideoReferenceItem =
* never in metadata; meaningless without `fromSourceVideo`.
*/
trimOverridden?: boolean;
+ /**
+ * The sample length the user last asked for, in frames. The window stored in
+ * `clip` is this clamped to the frames the clip has left from its start frame —
+ * keeping the request separate is what lets a start-frame drag run into the end
+ * of the clip and come back with the length intact. Absent until a control is
+ * touched, where the window's own length is the request. Panel state only, never
+ * in metadata; read it through `referenceSampleFrames`.
+ */
+ sampleFrames?: number;
}
| { kind: 'image'; image: ImageWithDims; detail: VideoReferenceImageDetail };
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
index 8ad7d23eca..184169c658 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
@@ -15,10 +15,12 @@ import { GalleryPickerPopover } from '@features/gallery/picker';
import { galleryImageUrls, galleryVideoUrls, isGalleryItemDragData } from '@features/gallery/utility';
import { resolveMiniMaxH3ReferenceImage } from '@features/video/core/dimensions';
import {
+ clampReferenceSampleFrames,
createVideoSourceClip,
DEFAULT_REFERENCE_SAMPLE_FRAMES,
getDefaultReferenceConditioning,
getDefaultReferenceImageDetail,
+ referenceSampleFrames,
resizeReferenceSampleWindow,
slideReferenceSampleWindow,
} from '@features/video/core/settings';
@@ -164,9 +166,15 @@ const ReferenceCard = memo(function ReferenceCard({
const handleStartFrame = useCallback(
(rawStart: number) => {
if (reference.kind === 'video') {
+ // Recording the length here as well as reading it is what makes a drag
+ // reversible: the first pointer step of the drag captures the pre-drag window's
+ // length, and every step after it slides that same length.
+ const sampleFrames = referenceSampleFrames(reference);
+
onUpdate(index, {
...reference,
- clip: slideReferenceSampleWindow(reference.clip, rawStart),
+ clip: slideReferenceSampleWindow(reference.clip, rawStart, sampleFrames),
+ sampleFrames,
...(reference.fromSourceVideo === true ? { trimOverridden: true } : {}),
});
}
@@ -179,6 +187,7 @@ const ReferenceCard = memo(function ReferenceCard({
onUpdate(index, {
...reference,
clip: resizeReferenceSampleWindow(reference.clip, rawSampleFrames),
+ sampleFrames: clampReferenceSampleFrames(reference.clip, rawSampleFrames),
...(reference.fromSourceVideo === true ? { trimOverridden: true } : {}),
});
}