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
feat(video): let LTX-2 soundtrack conditioning keep first and last frames
Lincoln Stein97c0adaa8019
diff --git a/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdx b/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdxindex 31c4889c38..f375d78efe 100644--- a/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdx+++ b/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdx@@ -61,6 +61,7 @@ There is no mode switch. The panel infers what to generate from **which inputs y| Initial Video | Extends the clip | — | ✓ | ✓ | ✓ | ✓ || Initial Video + Last Frame | Extends toward a destination image | — | ✓ | — | ✓ | ✓ || Conditioning Clip, *its soundtrack* | Generates a picture for the audio (audio-to-video) | — | — | — | — | ✓ |+| Conditioning Clip, *its soundtrack* + First and/or Last Frame | Generates a picture for the audio that starts and/or ends on your images | — | — | — | — | ✓ || Conditioning Clip, *its picture* | Generates a soundtrack for the video (video-to-audio) | — | — | — | — | ✓ |MiniMax H3's **Ref2VA** transformer has a mode of its own — reference-conditioned generation — covered [with the model](/users-guide/video-generation/minimax-h3/).diff --git a/docs/src/content/docs/Users Guide/05.Video Generation/ltx-2.mdx b/docs/src/content/docs/Users Guide/05.Video Generation/ltx-2.mdxindex e6052884e3..b183838c8a 100644--- a/docs/src/content/docs/Users Guide/05.Video Generation/ltx-2.mdx+++ b/docs/src/content/docs/Users Guide/05.Video Generation/ltx-2.mdx@@ -59,7 +59,8 @@ The clip decides the run's length: in the soundtrack role the Frames control locA few rules follow from how it works:-* The clip excludes every other conditioning input — clear the first frame, last frame and initial video to use one.+* In the soundtrack role, a **First Frame** and **Last Frame** can be combined with the clip: the picture generated for the audio starts or ends on your images. This is how to animate a particular character speaking or singing the soundtrack — set their portrait as the first frame. The aspect ratio then comes from the first frame, or from the last frame when only that is set.+* The picture role already supplies every frame, so it can't be combined with a first or last frame. While either is set, that role is unavailable and a dropped clip arrives in the soundtrack role; setting a frame while a clip is held for its picture removes the clip, and the frame fields say so beforehand. Neither role combines with an initial video.* Only the single-pass resolutions (512p, 704p, 768p) can run; with 1024p or 1536p selected, the Invoke button says to pick another. A [two-stage](#two-stage-presets) refine pass re-noises everything, which would undo the held stream.* In the picture role, the output carries **your original footage** at its own resolution with the new soundtrack. The model itself sees the clip resized to the generation canvas, whose aspect ratio the panel takes from the clip, so the soundtrack is generated for the whole frame.* To give LTX-2 a bare soundtrack — a song, a voice recording — upload the audio file to the gallery. It becomes a clip whose frames draw the waveform, and dropping it here selects the soundtrack role automatically.@@ -106,7 +107,7 @@ Context Frames steps along the same 8·n + 1 grid as Frames (9, 17, 25, 33 …).LTX-2 generates picture and soundtrack as one sequence, so it can hold either stream fixed and generate only the other — the same mechanism a first frame uses to hold one image fixed, applied to a whole stream. The panel exposes this as the [Conditioning Clip](#conditioning-clip):-* **Audio-to-video** encodes the clip's soundtrack and keeps it fixed at every step. Because the model has always learned picture and sound together, it lines the video up with the audio — a face speaking or singing to camera gets matching lip movement. The output contains the original recording, so nothing is lost from the audio. The two modes are mirror images: each returns the stream you supplied untouched.+* **Audio-to-video** encodes the clip's soundtrack and keeps it fixed at every step. Because the model has always learned picture and sound together, it lines the video up with the audio — a face speaking or singing to camera gets matching lip movement. The output contains the original recording, so nothing is lost from the audio. The two modes are mirror images: each returns the stream you supplied untouched. A first or last frame holds part of the *picture* stream, so it composes with a held soundtrack the same way it does with a generated one.* **Video-to-audio** keeps the clip's frames fixed and generates a soundtrack. The output is your original footage, frame for frame, with the generated soundtrack muxed in.Both run on the single-pass canvases only. Guidance applies as usual on Dev; in particular **Audio CFG** is the one that steers a video-to-audio soundtrack toward the prompt.diff --git a/docs/src/content/docs/development/Guides/video-recall-api.mdx b/docs/src/content/docs/development/Guides/video-recall-api.mdxindex 8f189c3412..318df30e5f 100644--- a/docs/src/content/docs/development/Guides/video-recall-api.mdx+++ b/docs/src/content/docs/development/Guides/video-recall-api.mdx@@ -68,7 +68,8 @@ Unknown fields, and values outside the bounds below, are rejected with `422`.Media fields in one request are read in the Video panel's precedence, highest first:1. `ltx2_conditioning_video` — a whole-generation conditioning clip excludes every- other medium.+ other medium, except that in the `audio` role `first_frame_image` and+ `last_frame_image` ride alongside it to anchor the generated picture.2. `minimax_h3_references` (non-empty) — references replace the frame slots; a`source_video` rides alongside them.3. `source_video` — an initial video replaces `first_frame_image`, which extend@@ -145,10 +146,12 @@ in a text field; the notification still reports the change.otherwise video and audio from a short sample of the clip. It is declined whenthe panel's model takes no reference videos or all its video slots are taken.- **Use as Conditioning Clip** sets the panel's *Conditioning Clip* in the requested- role; the whole clip is used. A conditioning clip excludes every other medium, so- where the panel's own field waits for you to clear them, this action clears the- first and last frames, the initial video and the references itself, and the- notification says so when there were any. It replaces a conditioning clip the+ role; the whole clip is used. A conditioning clip excludes the initial video and+ the references, and in the `video` role the first and last frames as well, so+ where the panel's own field waits for you to clear them, this action clears them+ itself, and the notification says so when there were any. In the `audio` role the+ first and last frames are kept: they anchor the picture generated for the+ soundtrack. It replaces a conditioning clip thepanel already holds. It is declined, leaving the panel alone, when the panel'smodel cannot generate in that role, and in the `video` role for an uploaded audiofile, whose picture is only a placeholder. Other settings are not changed to fitdiff --git a/invokeai/app/api/routers/video_recall.py b/invokeai/app/api/routers/video_recall.pyindex daa74b4f6f..c95ab1e3e1 100644--- a/invokeai/app/api/routers/video_recall.py+++ b/invokeai/app/api/routers/video_recall.py@@ -366,15 +366,18 @@ MEDIA_QUALIFIERS: dict[str, tuple[str, ...]] = {def apply_media_precedence(resolved: dict[str, Any]) -> dict[str, str]:"""Drop media a higher-precedence medium in the same request excludes; returns {dropped field: winner}.- Mirrors the Video panel's reading of a record: a whole-generation conditioning clip excludes every other slot;- Ref2VA references replace the frame slots (an initial video rides alongside them); an initial video replaces- the first frame, which extend mode extracts from the clip itself.+ Mirrors the Video panel's reading of a record: a whole-generation conditioning clip excludes every other slot,+ except that a held soundtrack keeps the frames that anchor the picture generated for it; Ref2VA references+ replace the frame slots (an initial video rides alongside them); an initial video replaces the first frame,+ which extend mode extracts from the clip itself."""+ clip_holds_picture = resolved.get("ltx2_conditioning_role") == "video"rules: list[tuple[str, bool, tuple[str, ...]]] = [("ltx2_conditioning_video","ltx2_conditioning_video" in resolved,- ("minimax_h3_references", "source_video", "first_frame_image", "last_frame_image"),+ ("minimax_h3_references", "source_video")+ + (("first_frame_image", "last_frame_image") if clip_holds_picture else ()),),("minimax_h3_references",@@ -684,7 +687,8 @@ def recall_conditioning_video() -> VideoRecallMediaResponse:"""Set a gallery video as the current user's conditioning clip (models that take one, e.g. LTX-2).- The clip replaces the panel's other conditioning media: frames, initial video and references.+ The clip replaces the panel's initial video and references, and in the `video` role its first and last frames;+ in the `audio` role the frames stay, anchoring the picture generated for the soundtrack."""return _place_gallery_video(queue_id, "conditioning_video", video_name, current_user, role)diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 6a3c8162b4..d0eb22b2a3 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -16214,7 +16214,7 @@"post": {"tags": ["recall"],"summary": "Recall Conditioning Video",- "description": "Set a gallery video as the current user's conditioning clip (models that take one, e.g. LTX-2).\n\nThe clip replaces the panel's other conditioning media: frames, initial video and references.",+ "description": "Set a gallery video as the current user's conditioning clip (models that take one, e.g. LTX-2).\n\nThe clip replaces the panel's initial video and references, and in the `video` role its first and last frames;\nin the `audio` role the frames stay, anchoring the picture generated for the soundtrack.","operationId": "recall_conditioning_video","security": [{diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex fddf71a271..3c09c5b56d 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -4155,7 +4155,8 @@ export type paths = {* Recall Conditioning Video* @description Set a gallery video as the current user's conditioning clip (models that take one, e.g. LTX-2).*- * The clip replaces the panel's other conditioning media: frames, initial video and references.+ * The clip replaces the panel's initial video and references, and in the `video` role its first and last frames;+ * in the `audio` role the frames stay, anchoring the picture generated for the soundtrack.*/post: operations["recall_conditioning_video"];delete?: never;diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex d1a64e162d..e91e6f0f45 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -4109,11 +4109,13 @@"dimensionSourceValue": {"first-frame": "From the first frame","last-frame": "From the last frame",- "source-video": "From the initial video"+ "source-video": "From the initial video",+ "conditioning-clip": "From the conditioning clip"},"firstFrame": "First Frame","firstFrameBlocked": "Clear the initial video to start from a frame instead.","firstFrameHelp": "The video starts on this image.",+ "frameClearsConditioningClip": "Setting a frame removes the conditioning clip, whose picture supplies every frame. Use its soundtrack instead to keep both.","fpsExtendLocked": "The extension inherits the source clip's frame rate.","initialFrames": "Start & End Images","initialVideo": "Initial Video",@@ -4185,7 +4187,7 @@"referenceExtendCapFull": "Initial video not set","referenceExtendCapFullDescription": "All 3 video reference slots are in use, so there is no room for the continuity reference this clip needs. Remove a video reference, then drop the clip again.","placement": {- "conditioningClipDisplaced": "A conditioning clip is used on its own, so the panel's other conditioning media was cleared.",+ "conditioningClipDisplaced": "The panel's conditioning media that can't be combined with this clip was cleared.","conditioningClipNoPicture": "This is an uploaded audio file, so it has no picture to generate a soundtrack for. Use its soundtrack instead.","conditioningClipNotSet": "Conditioning clip not set","conditioningClipSet": "Conditioning clip set",@@ -4213,12 +4215,13 @@"staleReferences": "References are set but the selected model cannot use them.","staleConditioningClip": "A conditioning clip is set, but this model cannot generate from one.","conditioningClip": "Conditioning Clip",- "conditioningClipHelp": "Drop a clip to generate the other half of it: a picture for its soundtrack, or a soundtrack for its picture.",- "conditioningClipBlocked": "Clear the First Frame, Last Frame, Initial Video and References to use a conditioning clip.",+ "conditioningClipHelp": "Drop a clip to generate the other half of it: a picture for its soundtrack, or a soundtrack for its picture. A soundtrack can be combined with a First Frame and Last Frame.",+ "conditioningClipBlocked": "Clear the Initial Video and References to use a conditioning clip.","twoStageConditioningBlocked": "A conditioning clip cannot run a two-stage resolution. Pick a single-stage one.","conditioningRole": "Use from this clip","conditioningRoleAudio": "Its soundtrack \u2014 generate the picture","conditioningRoleVideo": "Its picture \u2014 generate the soundtrack",+ "conditioningRoleVideoBlocked": "Clear the First Frame and Last Frame to use this clip's picture.","conditioningRoleVideoHelp": "The clip is re-encoded at the generation's canvas, so the picture comes back cropped and recompressed.","conditioningDerivedAudio": "{{frames}} frames at {{fps}} FPS, from the soundtrack's length.","conditioningDerivedVideo": "{{frames}} frames at {{fps}} FPS, from the clip itself.",diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts b/invokeai/frontend/webv2/src/features/video/core/graph.test.tsindex df903c274c..28bcad6a92 100644--- a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/graph.test.ts@@ -946,6 +946,43 @@ describe('compileVideoGraph — LTX-2', () => {expect(hasEdge(backendGraph, conditioning.id, 'audio_conditioning', output.id, 'source_audio')).toBe(true);});+ it('anchors the picture generated for a soundtrack on first and last frames', () => {+ const model = ltx2Model('ltx2_dev');+ const first = { height: 704, image_name: 'first.png', width: 1248 };+ const last = { height: 704, image_name: 'last.png', width: 1248 };+ const { backendGraph } = compileVideoGraph(+ ltx2SettingsFor(model, {+ conditioningClip: { clip: LTX2_CLIP, fpsKnown: true, role: 'audio' },+ firstFrameImage: first,+ lastFrameImage: last,+ numFrames: 121,+ }),+ model+ );+ const audio = nodeOfType(backendGraph, 'ltx2_audio_conditioning');++ expect(backendGraph.nodes.image_conditioning).toMatchObject({ frame_index: 0, image: { image_name: 'first.png' } });+ expect(backendGraph.nodes.last_frame_conditioning).toMatchObject({+ frame_index: -1,+ image: { image_name: 'last.png' },+ });+ expect(+ hasEdge(backendGraph, 'image_conditioning', 'video_conditioning', 'denoise_latents', 'video_conditioning')+ ).toBe(true);+ expect(+ hasEdge(backendGraph, 'last_frame_conditioning', 'video_conditioning', 'denoise_latents', 'keyframe_conditioning')+ ).toBe(true);+ // The soundtrack is still held and still decides the length the last frame's -1 resolves against.+ expect(hasEdge(backendGraph, audio.id, 'audio_conditioning', 'denoise_latents', 'audio_conditioning')).toBe(true);+ expect(hasEdge(backendGraph, audio.id, 'num_frames', 'denoise_latents', 'num_frames')).toBe(true);+ expect(backendGraph.nodes.core_metadata).toMatchObject({+ first_frame_image: { image_name: 'first.png' },+ generation_mode: 'ltx2_a2v',+ last_frame_image: { image_name: 'last.png' },+ ltx2_conditioning_role: 'audio',+ });+ });+it("conditions on a clip's picture at the canvas its own ratio resolves to", () => {const model = ltx2Model('ltx2_dev');const { backendGraph } = compileVideoGraph(diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.ts b/invokeai/frontend/webv2/src/features/video/core/graph.tsindex ba6fa8e153..052926c14e 100644--- a/invokeai/frontend/webv2/src/features/video/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/video/core/graph.ts@@ -882,15 +882,19 @@ const buildLtx2VideoGraph = (settings: VideoSettings, model: MainModelConfig): B// The generation opens either from a still or from the tail of the clip being continued; a last// frame rides on top of either as a keyframe. `-1` is resolved against the run's own frame count- // by the denoise node, so the encode does not go stale when the length changes.+ // by the denoise node, so the encode does not go stale when the length changes -- including the+ // length a held soundtrack wires in, since audio-to-video holds the other stream and leaves both+ // frame slots free to anchor the picture generated for it.// Keyed on the MODE rather than on whichever slot still holds something. Validation refuses every// bad combination before a graph is built, so this is the second line rather than the first -- but// a held frame reaching the graph unasked is both a silent change of output and, beside a// whole-clip conditioning, a shape failure inside the transformer, and the sibling MiniMax builder// guards the same way.- const holdsFirstFrame = (mode === 'first-frame' || mode === 'first-last') && settings.firstFrameImage;+ const holdsFirstFrame =+ (mode === 'first-frame' || mode === 'first-last' || mode === 'audio-to-video') && settings.firstFrameImage;const holdsLastFrame =- (mode === 'last-frame' || mode === 'first-last' || mode === 'extend') && settings.lastFrameImage;+ (mode === 'last-frame' || mode === 'first-last' || mode === 'extend' || mode === 'audio-to-video') &&+ settings.lastFrameImage;if (holdsFirstFrame) {addHeldFrame('image_conditioning', holdsFirstFrame, stages.base, denoise, 0);diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.tsindex 55a0c4165b..e96c487e57 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts@@ -26,6 +26,7 @@ import {getReferencesPatch,isVideoSettings,createVideoConditioningClip,+ getFrameImagePatch,isVideoSourceClip,normalizeVideoSettings,normalizeVideoWidgetValues,@@ -98,6 +99,12 @@ describe('createVideoConditioningClip', () => {expect(createVideoConditioningClip(item).role).toBe('video');});+ it('takes a clip for its soundtrack while start or end images are held, so they are not cleared', () => {+ const item = { durationSeconds: 4, fps: 24, height: 704, name: 'clip.mp4', width: 1248 };++ expect(createVideoConditioningClip(item, { framesHeld: true }).role).toBe('audio');+ });+it('carries no trim bounds, which the conditioning nodes would not honour', () => {const clip = createVideoConditioningClip({ durationSeconds: 4, fps: 24, height: 704, name: 'c.mp4', width: 1248 });@@ -502,14 +509,45 @@ describe('getDefaultReferenceImageDetail', () => {});});+describe('getFrameImagePatch', () => {+ const soundtrack = { clip: CONDITIONING_CLIP, fpsKnown: true, role: 'audio' as const };+ const picture = { ...soundtrack, role: 'video' as const };++ it('displaces a clip held for its picture, which already supplies every frame', () => {+ expect(getFrameImagePatch('firstFrameImage', FIRST_FRAME, picture)).toEqual({+ conditioningClip: null,+ firstFrameImage: FIRST_FRAME,+ sourceVideo: null,+ });+ expect(getFrameImagePatch('lastFrameImage', FIRST_FRAME, picture)).toEqual({+ conditioningClip: null,+ lastFrameImage: FIRST_FRAME,+ });+ });++ it('keeps a soundtrack, whose generated picture the frame anchors', () => {+ expect(getFrameImagePatch('firstFrameImage', FIRST_FRAME, soundtrack)).toEqual({+ firstFrameImage: FIRST_FRAME,+ sourceVideo: null,+ });+ expect(getFrameImagePatch('lastFrameImage', FIRST_FRAME, soundtrack)).toEqual({ lastFrameImage: FIRST_FRAME });+ });++ it('clears only its own slot', () => {+ expect(getFrameImagePatch('firstFrameImage', null, picture)).toEqual({ firstFrameImage: null });+ });+});+describe('normalizeVideoSettings — the conditioning clip', () => {const clip = { clip: CONDITIONING_CLIP, fpsKnown: true, role: 'audio' as const };it('drops a clip stored beside a slot that claims the same conditioning mask', () => {// A rolled-back or hand-edited project can hold both. Keeping them would resolve to a mode// whose graph silently ignores one of the two.+ const picture = { ...clip, role: 'video' as const };+expect(- normalizeVideoSettings({ ...createSettings({ firstFrameImage: FIRST_FRAME }), conditioningClip: clip })+ normalizeVideoSettings({ ...createSettings({ firstFrameImage: FIRST_FRAME }), conditioningClip: picture })?.conditioningClip).toBeNull();expect(@@ -519,6 +557,16 @@ describe('normalizeVideoSettings — the conditioning clip', () => {expect(normalizeVideoSettings(createSettings({ conditioningClip: clip }))?.conditioningClip).toEqual(clip);});+ it('keeps a soundtrack beside the first frame that anchors the picture generated for it', () => {+ const normalized = normalizeVideoSettings({+ ...createSettings({ firstFrameImage: FIRST_FRAME }),+ conditioningClip: clip,+ });++ expect(normalized?.conditioningClip).toEqual(clip);+ expect(normalized?.firstFrameImage).toEqual(FIRST_FRAME);+ });+it('drops a malformed clip rather than passing it to the graph builder', () => {for (const malformed of [{ clip: CONDITIONING_CLIP },diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.tsindex 1287f92d66..2c2eb5bbd9 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts@@ -285,8 +285,9 @@ export const resolveVideoMode = (return 'reference';}- // Ahead of the frame and clip slots because a conditioning clip excludes them all: it holds one- // whole modality clean, which is the same mask the other conditioning modes write into.+ // Ahead of the frame and clip slots because a conditioning clip decides the mode: it holds one+ // whole modality clean. A soundtrack leaves the picture to be generated, so first and last frames+ // ride along inside audio-to-video rather than naming a mode of their own.if (settings.conditioningClip) {return settings.conditioningClip.role === 'audio' ? 'audio-to-video' : 'video-to-audio';}@@ -340,10 +341,13 @@ export const normalizeVideoSettings = (values: unknown): VideoSettings | null =>// A first frame and a source video are mutually exclusive; if a stale// project somehow holds both, the first frame wins deterministically.const sourceVideo = !firstFrameImage && isVideoSourceClip(values.sourceVideo) ? values.sourceVideo : null;- // One conditioning clip at a time, and never alongside a first frame or an initial video: those- // condition the same stream this one would hold, and the model samples exactly one modality.+ // One conditioning clip at a time, and never alongside an initial video. A first frame excludes it+ // only in the picture role, where both would hold the same frames; a soundtrack holds the other+ // stream, so a first frame can anchor the picture generated for it.const conditioningClip =- !firstFrameImage && !sourceVideo && isVideoConditioningClip(values.conditioningClip)+ !sourceVideo &&+ isVideoConditioningClip(values.conditioningClip) &&+ (!firstFrameImage || !isConditioningClipExcludingFrames(values.conditioningClip))? values.conditioningClip: null;const loras = Array.isArray(values.loras) ? values.loras.filter(isVideoLora) : [];@@ -585,20 +589,27 @@ export const getDefaultReferenceConditioning = (mediaOrigin: string | null | undexport const getDefaultConditioningRole = (mediaOrigin: string | null | undefined): VideoConditioningRole =>mediaOrigin === 'audio_upload' ? 'audio' : 'video';-export const createVideoConditioningClip = (item: {- durationSeconds: number;- fps?: number;- height: number;- mediaOrigin?: string;- name: string;- width: number;-}): VideoConditioningClip => {+/**+ * A clip in its default role. `framesHeld` puts it in the soundtrack role instead, the only one that can join start+ * and end images already set: the picture role would clear them.+ */+export const createVideoConditioningClip = (+ item: {+ durationSeconds: number;+ fps?: number;+ height: number;+ mediaOrigin?: string;+ name: string;+ width: number;+ },+ { framesHeld = false }: { framesHeld?: boolean } = {}+): VideoConditioningClip => {const { endFrame: _endFrame, startFrame: _startFrame, ...clip } = createVideoSourceClip(item);return {clip,fpsKnown: typeof item.fps === 'number' && Number.isFinite(item.fps) && item.fps > 0,- role: getDefaultConditioningRole(item.mediaOrigin),+ role: framesHeld ? 'audio' : getDefaultConditioningRole(item.mediaOrigin),};};@@ -958,14 +969,38 @@ export const getInitialVideoPatch = ({};/**- * The panel patch that sets the conditioning clip, or clears it. A clip claims a whole modality, so it displaces- * every other conditioning slot: the frames, the initial video and the references.+ * Whether a conditioning clip holds the picture, and so excludes the first and last frames. A clip in the soundtrack+ * role holds only the audio stream: frames anchor the picture generated for it.+ */+export const isConditioningClipExcludingFrames = (+ conditioningClip: Pick<VideoConditioningClip, 'role'> | null+): boolean => conditioningClip?.role === 'video';++/**+ * The panel patch that sets a first or last frame, or clears it. A first frame displaces the initial video, and either+ * frame displaces a conditioning clip that holds the picture; a soundtrack stays, since the frame anchors the picture+ * generated for it.+ */+export const getFrameImagePatch = (+ slot: 'firstFrameImage' | 'lastFrameImage',+ image: ImageWithDims | null,+ conditioningClip: VideoConditioningClip | null+): Partial<VideoWidgetValues> => ({+ [slot]: image,+ ...(image && slot === 'firstFrameImage' ? { sourceVideo: null } : {}),+ ...(image && isConditioningClipExcludingFrames(conditioningClip) ? { conditioningClip: null } : {}),+});++/**+ * The panel patch that sets the conditioning clip, or clears it. A clip claims a whole modality, so it displaces the+ * initial video and the references, and in the picture role the frames as well.*/export const getConditioningClipPatch = (conditioningClip: VideoConditioningClip | null): Partial<VideoWidgetValues> => ({conditioningClip,- ...(conditioningClip ? { firstFrameImage: null, lastFrameImage: null, references: [], sourceVideo: null } : {}),+ ...(conditioningClip ? { references: [], sourceVideo: null } : {}),+ ...(isConditioningClipExcludingFrames(conditioningClip) ? { firstFrameImage: null, lastFrameImage: null } : {}),});/**diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.tsindex d684cef57f..7488485936 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts@@ -6,7 +6,7 @@ import {LTX2_DEFAULT_NEGATIVE_PROMPT,LTX2_EXTEND_CONTEXT_FRAMES,} from '@features/video/core/dimensions';-import { isVideoTargetResolution, normalizeVideoSettings } from '@features/video/core/settings';+import { isVideoTargetResolution, normalizeVideoSettings, resolveVideoMode } from '@features/video/core/settings';import { describe, expect, it } from 'vitest';import type { Ltx2TargetResolution, VideoSettings } from './types';@@ -2048,15 +2048,38 @@ describe('LTX-2 policy', () => {expect(getVideoDimensions(model, conditioned('audio'))?.source).toBe('aspect-ratio');});- it('refuses a clip beside any other conditioning slot', () => {- expect(- getVideoValidationReasons(- model,- conditioned('audio', { firstFrameImage: { height: 704, image_name: 'first.png', width: 1248 } })- )- ).toContain(- 'A conditioning clip cannot be combined with first/last frames, an initial video or references. Clear one side.'+ it('refuses a clip beside an initial video, and its picture beside frames', () => {+ const frame = { height: 704, image_name: 'frame.png', width: 1248 };+ const source = {+ endFrame: 94,+ fps: 24,+ height: 704,+ numFrames: 96,+ startFrame: 0,+ video_name: 's.mp4',+ width: 1248,+ };++ expect(getVideoValidationReasons(model, conditioned('audio', { sourceVideo: source }))).toContain(+ 'A conditioning clip cannot be combined with an initial video or references. Clear one side.');+ for (const slot of ['firstFrameImage', 'lastFrameImage'] as const) {+ expect(getVideoValidationReasons(model, conditioned('video', { [slot]: frame })), slot).toContain(+ "A conditioning clip's picture cannot be combined with first/last frames. Clear one side."+ );+ }+ });++ it('lets first and last frames anchor the picture generated for a soundtrack', () => {+ const first = { height: 704, image_name: 'first.png', width: 1248 };+ const last = { height: 704, image_name: 'last.png', width: 1248 };+ const settings = conditioned('audio', { firstFrameImage: first, lastFrameImage: last });++ expect(resolveVideoMode(settings)).toBe('audio-to-video');+ expect(getVideoValidationReasons(model, settings)).toEqual([]);+ // The soundtrack still decides the length; the first frame decides the canvas.+ expect(getEffectiveVideoTiming(model, settings).numFramesFromClip).toBe(true);+ expect(getVideoDimensions(model, settings)?.source).toBe('first-frame');});it('refuses a two-stage preset, which the denoise node cannot combine with a held modality', () => {diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.tsindex 885c532160..d4aa7a6c43 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts@@ -65,6 +65,7 @@ import {import {applyReferenceExtendSourceVideo,applyReferenceExtendNumFrames,+ isConditioningClipExcludingFrames,MIN_VIDEO_TRIM_FRAMES,MINIMAX_H3_HYBRID_BLOCK_RANGE,resolveVideoMode,@@ -2223,15 +2224,19 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Videreasons.push('A first frame and an initial video cannot be combined. Clear one of them.');}+ if (settings.conditioningClip && (settings.sourceVideo || settings.references.length > 0)) {+ // Both claim the run's conditioning wholesale, and `resolveVideoMode` would silently drop one+ // rather than run something it cannot express.+ reasons.push('A conditioning clip cannot be combined with an initial video or references. Clear one side.');+ }+if (- settings.conditioningClip &&- (settings.firstFrameImage || settings.lastFrameImage || settings.sourceVideo || settings.references.length > 0)+ isConditioningClipExcludingFrames(settings.conditioningClip) &&+ (settings.firstFrameImage || settings.lastFrameImage)) {- // Every one of these writes into the same conditioning mask the clip fills wholesale, and- // `resolveVideoMode` would silently drop the clip rather than run something it cannot express.- reasons.push(- 'A conditioning clip cannot be combined with first/last frames, an initial video or references. Clear one side.'- );+ // A clip's picture already fills every frame these would hold. Its soundtrack does not, which is+ // why the frames stay available in that role.+ reasons.push("A conditioning clip's picture cannot be combined with first/last frames. Clear one side.");}if (settings.references.length > 0 && (settings.firstFrameImage || settings.lastFrameImage)) {diff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.tsindex 15af94b652..dcc03db109 100644--- a/invokeai/frontend/webv2/src/features/video/index.ts+++ b/invokeai/frontend/webv2/src/features/video/index.ts@@ -23,8 +23,10 @@ export {getDefaultConditioningRole,getDefaultReferenceConditioning,getConditioningClipPatch,+ getFrameImagePatch,getInitialVideoPatch,getReferencesPatch,+ isConditioningClipExcludingFrames,isImageWithDims,isVideoAspectRatioId,isVideoReferenceConditioning,diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoConditioningClipField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoConditioningClipField.tsxindex 6ffa35de47..d19b81b52a 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoConditioningClipField.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoConditioningClipField.tsx@@ -13,7 +13,8 @@ import { useVideoUiActions } from './VideoUiContext';/*** The whole-modality conditioning slot: a clip whose soundtrack the model generates a picture for,* or whose picture it generates a soundtrack for. One slot with a role, not two slots, because- * LTX-2 holds exactly one modality clean and samples the other.+ * LTX-2 holds exactly one modality clean and samples the other. Start and end images can anchor the+ * generated picture in the soundtrack role only, so while they are set the picture role is closed.** No trim bounds: the conditioning nodes consume the whole recording.*/@@ -27,6 +28,7 @@ export const VideoConditioningClipField = memo(disabled = false,disabledReason,derivedText,+ pictureRoleDisabledReason,onChange,}: {conditioningClip: VideoConditioningClip | null;@@ -35,6 +37,8 @@ export const VideoConditioningClipField = memo(disabledReason?: string;/** What the clip works out to — length, and the rate it will run at. */derivedText?: string;+ /** Set while the picture role is unavailable; a dropped clip then arrives in the soundtrack role. */+ pictureRoleDisabledReason?: string;onChange: (conditioning: VideoConditioningClip | null) => void;}) {const { t } = useTranslation();@@ -60,10 +64,14 @@ export const VideoConditioningClipField = memo(createListCollection({items: [{ label: t('widgets.video.conditioningRoleAudio'), value: 'audio' },- { label: t('widgets.video.conditioningRoleVideo'), value: 'video' },+ {+ disabled: pictureRoleDisabledReason !== undefined,+ label: t('widgets.video.conditioningRoleVideo'),+ value: 'video',+ },],}),- [t]+ [pictureRoleDisabledReason, t]);const roleValue = useMemo(() => (conditioningClip ? [conditioningClip.role] : []), [conditioningClip]);@@ -72,10 +80,10 @@ export const VideoConditioningClipField = memo(if (item === null) {onChange(null);} else if (item.kind === 'video') {- onChange(createVideoConditioningClip(item));+ onChange(createVideoConditioningClip(item, { framesHeld: pictureRoleDisabledReason !== undefined }));}},- [onChange]+ [onChange, pictureRoleDisabledReason]);// The whole premise of this field is what is inside the clip, so it gets the same way back to// the gallery record that every other media slot has.@@ -113,7 +121,7 @@ export const VideoConditioningClipField = memo(helpText={conditioningClip.role === 'video'? `${t('widgets.video.conditioningRoleVideoHelp')}${derivedText ? ` ${derivedText}` : ''}`- : derivedText+ : [derivedText, pictureRoleDisabledReason].filter(Boolean).join(' ') || undefined}label={t('widgets.video.conditioningRole')}>@@ -138,6 +146,7 @@ export const VideoConditioningClipField = memo(previous.disabled === next.disabled &&previous.disabledReason === next.disabledReason &&previous.derivedText === next.derivedText &&+ previous.pictureRoleDisabledReason === next.pictureRoleDisabledReason &&previous.conditioningClip?.clip.video_name === next.conditioningClip?.clip.video_name &&previous.conditioningClip?.role === next.conditioningClip?.role);diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsxindex 43e1b2b760..6f2fec856e 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx@@ -23,8 +23,10 @@ import {applyReferenceExtendNumFrames,canPlaceReferenceExtendAnchor,getConditioningClipPatch,+ getFrameImagePatch,getInitialVideoPatch,getReferencesPatch,+ isConditioningClipExcludingFrames,isVideoTargetResolution,normalizeVideoWidgetValues,resolveVideoMode,@@ -280,19 +282,24 @@ export const VideoWidgetView = () => {// extension also keeps the linked tail reference synchronized.const referenceExtend = Boolean(policy.references?.extend);const maxVideoReferences = policy.references?.maxVideos ?? 3;+ const conditioningClip = values.conditioningClip;const setFirstFrame = useCallback((firstFrameImage: ImageWithDims | null) =>- patch({ firstFrameImage, ...(firstFrameImage ? { conditioningClip: null, sourceVideo: null } : {}) }),- [patch]+ patch(getFrameImagePatch('firstFrameImage', firstFrameImage, conditioningClip)),+ [conditioningClip, patch]);const setLastFrame = useCallback((lastFrameImage: ImageWithDims | null) =>- patch({ lastFrameImage, ...(lastFrameImage ? { conditioningClip: null } : {}) }),- [patch]+ patch(getFrameImagePatch('lastFrameImage', lastFrameImage, conditioningClip)),+ [conditioningClip, patch]);- // A conditioning clip claims a whole modality, so it excludes every other conditioning slot --- // and each of those clears it in turn. The role a dropped clip arrives in comes from the gallery- // record: an uploaded soundtrack has no picture to condition on.+ // Setting a frame is what clears a clip held for its picture, so the frame fields say so beforehand.+ const frameClearsClipText = isConditioningClipExcludingFrames(conditioningClip)+ ? t('widgets.video.frameClearsConditioningClip')+ : undefined;+ // A conditioning clip claims a whole modality, so it excludes the initial video and references, and in the picture+ // role the frames too -- and each of those clears it in turn. The role a dropped clip arrives in comes from the+ // gallery record: an uploaded soundtrack has no picture to condition on.const setConditioningClip = useCallback((conditioningClip: VideoConditioningClip | null) => patch(getConditioningClipPatch(conditioningClip)),[patch]@@ -460,9 +467,9 @@ export const VideoWidgetView = () => {const hasConditioningMedia = Boolean(values.firstFrameImage || values.lastFrameImage || values.sourceVideo || values.conditioningClip?.role === 'video');- const otherMediaSet = Boolean(- values.firstFrameImage || values.lastFrameImage || values.sourceVideo || values.references.length > 0- );+ const otherMediaSet = Boolean(values.sourceVideo || values.references.length > 0);+ // Frames block only the clip's picture role; its soundtrack is what they can be combined with.+ const framesSet = Boolean(values.firstFrameImage || values.lastFrameImage);const conditioningDerivedText = values.conditioningClip? t(values.conditioningClip.role === 'audio'@@ -543,7 +550,11 @@ export const VideoWidgetView = () => {<Stack gap="3" p="2">{supportsFirstFrame ? (<Field- helpText={values.sourceVideo ? undefined : t('widgets.video.firstFrameHelp')}+ helpText={+ values.sourceVideo+ ? undefined+ : [t('widgets.video.firstFrameHelp'), frameClearsClipText].filter(Boolean).join(' ')+ }label={t('widgets.video.firstFrame')}><VideoFrameImageField@@ -558,9 +569,12 @@ export const VideoWidgetView = () => {) : null}{supportsLastFrame ? (<Field- helpText={- values.sourceVideo ? t('widgets.video.lastFrameExtendHelp') : t('widgets.video.lastFrameHelp')- }+ helpText={[+ values.sourceVideo ? t('widgets.video.lastFrameExtendHelp') : t('widgets.video.lastFrameHelp'),+ frameClearsClipText,+ ]+ .filter(Boolean)+ .join(' ')}label={t('widgets.video.lastFrame')}><VideoFrameImageField@@ -659,6 +673,7 @@ export const VideoWidgetView = () => {derivedText={conditioningDerivedText}disabled={otherMediaSet}disabledReason={otherMediaSet ? t('widgets.video.conditioningClipBlocked') : undefined}+ pictureRoleDisabledReason={framesSet ? t('widgets.video.conditioningRoleVideoBlocked') : undefined}onChange={setConditioningClip}/></Stack>diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsxindex 216ebafdb0..3d78d4a099 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsx@@ -79,6 +79,7 @@ void i18n.use(initReactI18next).init({conditioningRole: 'Use from this clip',conditioningRoleAudio: 'Its soundtrack',conditioningRoleVideo: 'Its picture',+ conditioningRoleVideoBlocked: 'Clear the start and end images to use its picture.',conditioningRoleVideoHelp: 'The clip is re-encoded at the canvas.',},},@@ -93,7 +94,11 @@ describe('the conditioning clip role control', () => {let host: HTMLDivElement;let root: Root;const onChange = vi.fn();- const mount = (conditioningClip: VideoConditioningClip | null, disabled?: { reason: string }) =>+ const mount = (+ conditioningClip: VideoConditioningClip | null,+ disabled?: { reason: string },+ pictureRoleDisabledReason?: string+ ) =>act(() => {root.render(<I18nextProvider i18n={i18n}>@@ -105,6 +110,7 @@ describe('the conditioning clip role control', () => {conditioningClip={conditioningClip}disabled={Boolean(disabled)}disabledReason={disabled?.reason}+ pictureRoleDisabledReason={pictureRoleDisabledReason}onChange={onChange}/></DndContext>@@ -175,4 +181,21 @@ describe('the conditioning clip role control', () => {expect(onChange).toHaveBeenCalledWith({ ...CLIP, role: 'video' });});++ it('closes the picture role while start or end images are held, and says why', async () => {+ const reason = 'Clear the start and end images to use its picture.';++ await mount(CLIP, undefined, reason);+ expect(host.textContent).toContain(reason);+ await act(() => trigger()!.click());+ await expect.poll(() => document.querySelectorAll('[role="option"]').length).toBe(2);++ const picture = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find((option) =>+ option.textContent?.includes('Its picture')+ );++ expect(picture?.getAttribute('aria-disabled')).toBe('true');+ await act(() => picture!.click());+ expect(onChange).not.toHaveBeenCalled();+ });});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.tsindex 9cd13ab5ac..310c52046c 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.ts@@ -161,23 +161,19 @@ describe('appendReferenceVideo', () => {});describe('placeConditioningClip', () => {- it('sets the clip in the requested role and clears every other conditioning slot', () => {- const placement = placeConditioningClip({- models: [LTX2],- role: 'audio',- video: clip,- videoValues: panel(LTX2, {- firstFrameImage: { height: 480, image_name: 'first.png', width: 832 },- sourceVideo: { ...videoReference('source.mp4').clip },- }),+ it('sets the clip in the requested role and clears the conditioning slots that role conflicts with', () => {+ const framed = panel(LTX2, {+ firstFrameImage: { height: 480, image_name: 'first.png', width: 832 },+ lastFrameImage: { height: 480, image_name: 'last.png', width: 832 },});- expect(placement).toEqual({+ // The picture role holds every frame, so the start and end images go.+ expect(placeConditioningClip({ models: [LTX2], role: 'video', video: clip, videoValues: framed })).toEqual({displaced: true,patch: {conditioningClip: expect.objectContaining({clip: expect.objectContaining({ video_name: 'clip.mp4' }),- role: 'audio',+ role: 'video',}),firstFrameImage: null,lastFrameImage: null,@@ -186,6 +182,25 @@ describe('placeConditioningClip', () => {},status: 'placed',});+ // A soundtrack leaves them to anchor the picture generated for it.+ expect(placeConditioningClip({ models: [LTX2], role: 'audio', video: clip, videoValues: framed })).toEqual({+ displaced: false,+ patch: {+ conditioningClip: expect.objectContaining({ role: 'audio' }),+ references: [],+ sourceVideo: null,+ },+ status: 'placed',+ });+ // An initial video conflicts with either role.+ expect(+ placeConditioningClip({+ models: [LTX2],+ role: 'audio',+ video: clip,+ videoValues: panel(LTX2, { sourceVideo: { ...videoReference('source.mp4').clip } }),+ })+ ).toMatchObject({ displaced: true, patch: { sourceVideo: null }, status: 'placed' });});it('replacing a clip on an otherwise empty panel displaces nothing', () => {diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.tsindex 865f89e811..d54848de23 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts@@ -153,11 +153,15 @@ const ltx2ConditioningMetadata = (role: unknown, videoName: unknown | null = 'so/** Recalls an LTX-2 conditioned run onto a panel that starts with `startingValues`. */const recallConditioningClip = async (role: unknown,- { startingValues, videoName }: { startingValues?: Record<string, unknown>; videoName?: unknown | null } = {}+ {+ recorded,+ startingValues,+ videoName,+ }: { recorded?: Record<string, unknown>; startingValues?: Record<string, unknown>; videoName?: unknown | null } = {}) => {recallSeq += 1;- galleryApi.galleryVideos.metadata.mockResolvedValue(ltx2ConditioningMetadata(role, videoName));+ galleryApi.galleryVideos.metadata.mockResolvedValue({ ...ltx2ConditioningMetadata(role, videoName), ...recorded });// An ordinary gallery clip: `getDefaultConditioningRole` would take it for the VIDEO role, so a// recalled `audio` role can only come from the metadata.galleryApi.galleryItems.resolve.mockResolvedValue({ ...item, durationSeconds: 4, fps: 24, name: 'song.mp4' });@@ -307,6 +311,7 @@ describe('the LTX-2 conditioning clip on recall', () => {accountLifecycle.activate('test-account');galleryApi.galleryVideos.metadata.mockReset();galleryApi.galleryItems.resolve.mockReset();+ galleryApi.galleryImages.resolveMany.mockReset();});// The role IS the mode: recalling an audio-to-video run as video-to-audio reproduces the@@ -340,6 +345,29 @@ describe('the LTX-2 conditioning clip on recall', () => {expect(written).toMatchObject({ firstFrameImage: null, references: [], sourceVideo: null });});+ it("restores the frames that anchored a soundtrack's picture, and only for a soundtrack", async () => {+ const recorded = {+ first_frame_image: { image_name: 'first.png' },+ last_frame_image: { image_name: 'last.png' },+ };+ galleryApi.galleryImages.resolveMany.mockResolvedValue([+ { height: 704, imageName: 'first.png', width: 1248 },+ { height: 704, imageName: 'last.png', width: 1248 },+ ]);++ expect(await recallConditioningClip('audio', { recorded })).toMatchObject({+ conditioningClip: { role: 'audio' },+ firstFrameImage: { image_name: 'first.png' },+ lastFrameImage: { image_name: 'last.png' },+ });+ // A picture-role run cannot have held frames; a record claiming both keeps the clip, not them.+ expect(await recallConditioningClip('video', { recorded })).toMatchObject({+ conditioningClip: { role: 'video' },+ firstFrameImage: null,+ lastFrameImage: null,+ });+ });+it('clears a clip the panel is holding when the recalled run used none', async () => {galleryApi.galleryVideos.metadata.mockResolvedValue({...ltx2ConditioningMetadata('audio'),diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.tsindex ccc3c7d53e..346533ec72 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts@@ -18,9 +18,11 @@ import {createVideoSourceClip,getConditioningClipPatch,getDefaultReferenceConditioning,+ getFrameImagePatch,getInitialVideoPatch,getReferencesPatch,getVideoModelPolicy,+ isConditioningClipExcludingFrames,isVideoReferenceConditioning,normalizeVideoWidgetValues,syncVideoWidgetValuesWithModels,@@ -248,18 +250,27 @@ export const applyVideoRecallMetadata = async ({const firstFrame = firstFrameName ? framesByName.get(firstFrameName) : undefined;const lastFrame = lastFrameName ? framesByName.get(lastFrameName) : undefined;+ // Through the panel's own frame patch: a partial recall can land a frame beside a clip the panel holds for its+ // picture, which the frame displaces exactly as setting it by hand would.if (firstFrame) {result.values = {...result.values,- firstFrameImage: { height: firstFrame.height, image_name: firstFrame.imageName, width: firstFrame.width },- sourceVideo: null,+ ...getFrameImagePatch(+ 'firstFrameImage',+ { height: firstFrame.height, image_name: firstFrame.imageName, width: firstFrame.width },+ result.values.conditioningClip+ ),};recalledMedia = true;}if (lastFrame) {result.values = {...result.values,- lastFrameImage: { height: lastFrame.height, image_name: lastFrame.imageName, width: lastFrame.width },+ ...getFrameImagePatch(+ 'lastFrameImage',+ { height: lastFrame.height, image_name: lastFrame.imageName, width: lastFrame.width },+ result.values.conditioningClip+ ),};recalledMedia = true;}@@ -286,8 +297,10 @@ export const applyVideoRecallMetadata = async ({}),role: conditioningClip.role,},- firstFrameImage: null,- lastFrameImage: null,+ // A soundtrack keeps the frames hydrated above: they anchored the picture made for it.+ ...(isConditioningClipExcludingFrames(conditioningClip)+ ? { firstFrameImage: null, lastFrameImage: null }+ : {}),references: [],sourceVideo: null,};@@ -609,7 +622,7 @@ const CONDITIONING_ROLE_MODE = {export type ConditioningClipPlacement =| {- /** Whether the clip cleared other conditioning media: frames, the initial video or references. */+ /** Whether the clip cleared other conditioning media: the initial video, references, or frames for its picture. */displaced: boolean;patch: Partial<VideoWidgetValues>;status: 'placed';@@ -621,9 +634,9 @@ const canConditionInRole = (policy: VideoModelPolicy | null, role: VideoConditioBoolean(policy?.modes.includes(CONDITIONING_ROLE_MODE[role]));/**- * Set the video as the Video panel's conditioning clip in `role`. The panel's own field refuses a clip while other- * conditioning media is set; this explicit action clears that media instead, as Extend in Video displaces a first- * frame, and reports it. Unlike the Initial Video, a clip the panel's model cannot use is declined: it would clear+ * Set the video as the Video panel's conditioning clip in `role`. The panel's own field refuses a clip while+ * conflicting conditioning media is set; this explicit action clears that media instead, as Extend in Video displaces+ * a first frame, and reports it. Frames conflict only with the picture role. Unlike the Initial Video, a clip the panel's model cannot use is declined: it would clear* the other media for nothing.*/export const placeConditioningClip = ({@@ -647,11 +660,15 @@ export const placeConditioningClip = ({return { status: 'unsupported' };}+ const clip = { ...createVideoConditioningClip(video), role };+return {displaced: Boolean(- values.firstFrameImage || values.lastFrameImage || values.sourceVideo || values.references.length > 0+ values.sourceVideo ||+ values.references.length > 0 ||+ (isConditioningClipExcludingFrames(clip) && (values.firstFrameImage || values.lastFrameImage))),- patch: getConditioningClipPatch({ ...createVideoConditioningClip(video), role }),+ patch: getConditioningClipPatch(clip),status: 'placed',};};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.tsindex 55f50b25cb..f19d369a2e 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts@@ -21,6 +21,7 @@ import {getVideoModelPolicy,getVideoModelSelectionResult,getVideoTargetResolutionOptions,+ isConditioningClipExcludingFrames,isSupportedVideoModel,isValidVideoNumFrames,LTX2_NUM_FRAMES_STEP,@@ -413,7 +414,10 @@ export interface VideoRecallConditioningClip {}export interface VideoRecallMediaNames {- /** The LTX-2 whole-modality conditioning clip, which excludes every other slot below. */+ /**+ * The LTX-2 whole-modality conditioning clip. It excludes every other slot below, except that a soundtrack+ * recalls alongside the first and last frames that anchored the picture generated for it.+ */conditioningClip: VideoRecallConditioningClip | null;firstFrameName: string | null;lastFrameName: string | null;@@ -788,9 +792,13 @@ export const buildVideoRecallSettings = ({}if (conditioningClip) {- // First, and alone: the clip holds a whole modality clean, so no other slot could have been- // filled on the run being recalled.+ // First, and alone but for frames: the clip holds a whole modality clean, so no other slot could+ // have been filled on the run being recalled -- except a held soundtrack's first and last frames.mediaNames.conditioningClip = conditioningClip;+ if (!isConditioningClipExcludingFrames(conditioningClip)) {+ mediaNames.firstFrameName = media.firstFrameName;+ mediaNames.lastFrameName = media.lastFrameName;+ }fields.push('media');} else if (references.length > 0) {// References replace the frame slots, but a recorded source video ridesdiff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.tsindex 6d832590b6..5db1da509a 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts@@ -185,6 +185,49 @@ describe('createVideoRecallRuntime', () => {runtime.dispose();});+ describe('frames beside an LTX-2 conditioning clip', () => {+ const pictureClip = {+ clip: { fps: 24, height: 480, numFrames: 96, video_name: 'held.mp4', width: 832 },+ fpsKnown: true,+ role: 'video',+ };+ const recalledClip = (role: 'audio' | 'video') => ({+ ltx2_conditioning_role: role,+ ltx2_conditioning_video: { video_name: 'song.mp4' },+ });++ it('lets a recalled frame displace a clip the panel holds for its picture, as setting it would', async () => {+ const { projectId, runtime, socket, store, videoValues } = setup(LTX2);+ store.commands.widgets.patchValues('video', { conditioningClip: pictureClip }, projectId);+ // The record's own clip is gone, so only its frame lands.+ galleryApi.galleryItems.resolve.mockRejectedValue(new Error('gone'));++ socket.emit(parametersEvent({ last_frame_image: { image_name: 'last.png' }, ...recalledClip('audio') }));+ await flush();++ expect(videoValues()).toMatchObject({ conditioningClip: null, lastFrameImage: { image_name: 'last.png' } });++ runtime.dispose();+ });++ it("keeps the panel's frames beside a recalled soundtrack and clears them for a recalled picture", async () => {+ for (const [role, frame] of [+ ['audio', heldFrame],+ ['video', null],+ ] as const) {+ const { projectId, runtime, socket, store, videoValues } = setup(LTX2);+ store.commands.widgets.patchValues('video', { firstFrameImage: heldFrame }, projectId);++ socket.emit(parametersEvent(recalledClip(role)));+ await flush();++ expect(videoValues(), role).toMatchObject({ conditioningClip: { role }, firstFrameImage: frame });++ runtime.dispose();+ }+ });+ });+it('clears media a strict recall does not name', async () => {const { runtime, socket, videoValues } = setup();@@ -490,11 +533,11 @@ describe('createVideoRecallRuntime', () => {const { lastNotice, projectId, runtime, socket, store, videoShown, videoValues } = setup(LTX2);store.commands.widgets.patchValues('video', { firstFrameImage: heldFrame }, projectId);- socket.emit({ ...placementEvent('conditioning_video'), conditioning_role: 'audio' });+ socket.emit({ ...placementEvent('conditioning_video'), conditioning_role: 'video' });await flush();expect(videoValues()).toMatchObject({- conditioningClip: { clip: { video_name: 'clip.mp4' }, fpsKnown: true, role: 'audio' },+ conditioningClip: { clip: { video_name: 'clip.mp4' }, fpsKnown: true, role: 'video' },firstFrameImage: null,});expect(lastNotice()).toEqual(@@ -509,6 +552,19 @@ describe('createVideoRecallRuntime', () => {runtime.dispose();});+ it('keeps the first frame beside a soundtrack, which it anchors the picture of', async () => {+ const { lastNotice, projectId, runtime, socket, store, videoValues } = setup(LTX2);+ store.commands.widgets.patchValues('video', { firstFrameImage: heldFrame }, projectId);++ socket.emit({ ...placementEvent('conditioning_video'), conditioning_role: 'audio' });+ await flush();++ expect(videoValues()).toMatchObject({ conditioningClip: { role: 'audio' }, firstFrameImage: heldFrame });+ expect(lastNotice()).toMatchObject({ kind: 'success', title: 'widgets.video.placement.conditioningClipSet' });++ runtime.dispose();+ });+it('sets a conditioning clip on an otherwise empty panel with a plain success notice', async () => {const { lastNotice, runtime, socket, videoValues } = setup(LTX2);diff --git a/tests/app/routers/test_video_recall.py b/tests/app/routers/test_video_recall.pyindex cbc017b251..5b63fa7ec9 100644--- a/tests/app/routers/test_video_recall.py+++ b/tests/app/routers/test_video_recall.py@@ -466,15 +466,24 @@ class TestParameterRecall:"ltx2_conditioning_video": {"video_name": "song.mp4"},"ltx2_conditioning_role": "audio",},- {"ltx2_conditioning_video", "ltx2_conditioning_role"},+ {"ltx2_conditioning_video", "ltx2_conditioning_role", "first_frame_image"},{- "first_frame_image": "ltx2_conditioning_video","source_video": "ltx2_conditioning_video","source_video_start_frame": "ltx2_conditioning_video","source_video_end_frame": "ltx2_conditioning_video","minimax_h3_references": "ltx2_conditioning_video",},),+ (+ {+ "first_frame_image": {"image_name": "first.png"},+ "last_frame_image": {"image_name": "last.png"},+ "ltx2_conditioning_video": {"video_name": "clip.mp4"},+ "ltx2_conditioning_role": "video",+ },+ {"ltx2_conditioning_video", "ltx2_conditioning_role"},+ {"first_frame_image": "ltx2_conditioning_video", "last_frame_image": "ltx2_conditioning_video"},+ ),({"first_frame_image": {"image_name": "first.png"}, "minimax_h3_references": []},{"first_frame_image", "minimax_h3_references"},@@ -493,7 +502,8 @@ class TestParameterRecall:ids=["initial-video-over-first-frame","references-over-frames",- "conditioning-clip-over-all",+ "soundtrack-clip-over-all-but-frames",+ "picture-clip-over-frames","empty-list-beside-a-frame","empty-list-beside-a-clip",],diff --git a/tests/backend/ltx2/test_ltx2_denoise.py b/tests/backend/ltx2/test_ltx2_denoise.pyindex 6046cd861b..054bf0486b 100644--- a/tests/backend/ltx2/test_ltx2_denoise.py+++ b/tests/backend/ltx2/test_ltx2_denoise.py@@ -413,6 +413,33 @@ def test_a_first_frame_and_a_keyframe_compose_into_first_to_last_interpolation()assert torch.allclose(unpack_video_latents(video, *LATENT)[:, :, :1], image_latents, atol=1e-5)+def test_first_and_last_frames_anchor_the_picture_generated_for_a_held_soundtrack() -> None:+ """Frames and a soundtrack hold different streams, so all three compose: the appended keyframe+ must not disturb the audio rows, nor the held audio the keyframe's."""+ image_latents = torch.randn(1, LTX2_LATENT_CHANNELS, 1, LATENT[1], LATENT[2])+ keyframe = _keyframe()+ soundtrack = _soundtrack()+ state = _state(+ image_latents=image_latents,+ keyframe_latents=keyframe,+ keyframe_latent_index=LATENT[0] - 1,+ frozen_audio_latents=soundtrack,+ )+ # An audio target the soundtrack is not at, so it drifts unless the mask holds it.+ transformer = TransformerStub(+ target=torch.randn(1, ROWS, LTX2_LATENT_CHANNELS), audio_target=torch.randn_like(soundtrack)+ )++ video, audio = _denoise(transformer, state, LTX2Guidance(**OFF))++ for call in transformer.calls:+ assert torch.allclose(call["hidden_states"].float()[:, ROWS:], pack_video_latents(keyframe), atol=1e-5)+ assert torch.equal(call["timestep"][0, ROWS:], torch.zeros(state.keyframe_tokens))+ assert torch.allclose(call["audio_hidden_states"].float(), soundtrack, atol=1e-5)+ assert torch.allclose(unpack_video_latents(video, *LATENT)[:, :, :1], image_latents, atol=1e-5)+ assert torch.allclose(audio, soundtrack, atol=1e-5)++def test_a_partially_held_keyframe_is_noised_to_its_share_of_the_step() -> None:state = _state(keyframe_latents=_keyframe(), keyframe_latent_index=LATENT[0] - 1, keyframe_strength=0.5)transformer = TransformerStub()