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(ltx2): let auto duration size an extension's continuation
Lincoln Stein2a3e0c20d4d0
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 cc8bef7a0d..566510b677 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@@ -85,7 +85,8 @@ LTX-2.5 ships with a small **duration head** that reads your prompt, as the mode* With it on, the head chooses the clip's length, and **Frames becomes Max frames** — the longest clip it may choose. That number still sizes the run's memory, so it stays editable, and its help text shows the range in seconds. Raise it to allow longer shots.* The head chooses between one second (or the shortest clip LTX-2 makes) and Max frames, at the panel's FPS, and lands on the 8·n + 1 frame grid. If Max frames is too short to leave it a choice, the clip simply runs at that length.-* It is off for audio-to-video, video-to-audio and extensions, where the source clip decides the length.+* For an [extension](#extending-with-ltx-2) the prompt describes the continuation, so the head chooses the length of the new material, at the source clip's frame rate, and the Context Frames are added in front of it. Max frames still counts the whole generated clip, context included.+* It is off for audio-to-video and video-to-audio, where the conditioning clip decides the length.* The length that ran is what the video records, so recalling it reproduces that exact clip; recall turns Auto duration off for that reason.The duration head is a separate, optional 3.6 MB install (**LTX-2.5 Duration Head** in the starter models). It is fetched from Lightricks' own repository, which is license-gated: the install needs a Hugging Face token from an account that has accepted the LTX-2.5 license. Once installed it is selected automatically; the switch stays off until you turn it on.diff --git a/invokeai/app/invocations/ltx2/ltx2_duration.py b/invokeai/app/invocations/ltx2/ltx2_duration.pyindex 2e4b34d74a..2cf10e0b80 100644--- a/invokeai/app/invocations/ltx2/ltx2_duration.py+++ b/invokeai/app/invocations/ltx2/ltx2_duration.py@@ -12,7 +12,8 @@ from invokeai.app.invocations.baseinvocation import (from invokeai.app.invocations.fields import Input, InputField, LTX2ConditioningField, OutputFieldfrom invokeai.app.invocations.model import ModelIdentifierFieldfrom invokeai.app.services.shared.invocation_context import InvocationContext-from invokeai.backend.ltx2.constants import LTX2_DEFAULT_FPS, LTX2_TEMPORAL_COMPRESSION+from invokeai.backend.ltx2.constants import LTX2_DEFAULT_FPS, LTX2_FRAME_MODULUS, LTX2_TEMPORAL_COMPRESSION+from invokeai.backend.ltx2.packing import snap_num_frames_downfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType# The range the head was trained to regress over. Outside it the prediction is extrapolation, so@@ -26,7 +27,8 @@ class LTX2DurationOutput(BaseInvocationOutput):"""A predicted shot length, as both a frame count and the seconds it came from."""num_frames: int = OutputField(- description="Frame count on LTX-2's 8k+1 grid. Wire into the denoise node's `num_frames`."+ description="Frame count on LTX-2's 8k+1 grid, including any context frames. Wire into the denoise "+ "node's `num_frames`.")# The frame count is what a graph consumes, but it has been clamped and snapped, so on its own# it cannot tell a user whether the model wanted 3 seconds or 30. This is the raw regression.@@ -38,7 +40,7 @@ class LTX2DurationOutput(BaseInvocationOutput):title="Duration - LTX-2",tags=["ltx", "ltx2", "video", "duration", "frames"],category="video",- version="1.0.0",+ version="1.1.0",classification=Classification.Prototype,)class LTX2DurationInvocation(BaseInvocation):@@ -49,8 +51,10 @@ class LTX2DurationInvocation(BaseInvocation):prediction is clamped to `min_seconds`/`max_seconds` and then snapped down onto the VAE'scausal temporal grid (`8k + 1`), which is the only frame count a generation can run at.- Conditioning clips and video extension fix the frame count by construction -- the source- footage decides it -- so this node has nothing to say about those graphs.+ For an extension, the prompt describes the continuation rather than the frames it opens with,+ so the prediction sizes the new material and `context_frames` is added in front of it.+ Conditioning clips fix the frame count by construction -- the clip decides it -- so this node+ has nothing to say about those graphs."""conditioning: LTX2ConditioningField = InputField(@@ -83,6 +87,18 @@ class LTX2DurationInvocation(BaseInvocation):le=LTX2_DURATION_MAX_SECONDS,description="Longest clip to allow.",)+ context_frames: int = InputField(+ default=0,+ ge=0,+ description="Source frames the run opens with, as an extension's `context_frames`. The prediction "+ "covers what follows them, so they are added to it. 0 when nothing is held.",+ )+ max_num_frames: int | None = InputField(+ default=None,+ ge=1,+ description="Longest total frame count the run was sized for. The result never exceeds it, whatever "+ "frame rate the seconds bounds turn out to be read at.",+ )@torch.no_grad()def invoke(self, context: InvocationContext) -> LTX2DurationOutput:@@ -93,6 +109,15 @@ class LTX2DurationInvocation(BaseInvocation):f"min_seconds ({self.min_seconds}) must be less than max_seconds ({self.max_seconds}) ""for the duration head to have a range to choose from.")+ # Context comes off the extend node, which only ever holds whole frame groups. Anything else+ # would put the sum below off the grid.+ if self.context_frames and (self.context_frames - 1) % LTX2_FRAME_MODULUS:+ raise ValueError(f"context_frames ({self.context_frames}) must be 0 or on the 8k+1 grid.")+ ceiling = snap_num_frames_down(self.max_num_frames) if self.max_num_frames is not None else None+ if ceiling is not None and self.context_frames and ceiling <= self.context_frames:+ raise ValueError(+ f"max_num_frames ({self.max_num_frames}) leaves no room after {self.context_frames} context frames."+ )conditioning = context.conditioning.load(self.conditioning.conditioning_name)# The text encoder emits one conditioning per prompt; the head reads a single prompt's@@ -120,5 +145,16 @@ class LTX2DurationInvocation(BaseInvocation):max_seconds=float(self.max_seconds),)- context.logger.info(f"LTX-2 duration: predicted {seconds:.2f}s -> {num_frames} frames at {self.fps} fps")+ if self.context_frames:+ # The prediction is 8k + 1; its k whole groups are the new material, appended to a context+ # that is itself 8k + 1, so the total stays on the grid. At least one group, or the+ # continuation would be all replay.+ num_frames = self.context_frames + max(num_frames - 1, LTX2_FRAME_MODULUS)+ if ceiling is not None:+ num_frames = min(num_frames, ceiling)++ context.logger.info(+ f"LTX-2 duration: predicted {seconds:.2f}s -> {num_frames} frames at {self.fps} fps"+ + (f" (including {self.context_frames} context frames)" if self.context_frames else "")+ )return LTX2DurationOutput(num_frames=int(num_frames), seconds=seconds)diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 6fe218373b..82fc7f321a 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -62132,7 +62132,7 @@"category": "video","class": "invocation","classification": "prototype",- "description": "Predicts the natural length of the shot a prompt describes, as an LTX-2 frame count.\n\nThe duration head reads the same connector outputs the transformer's prompt cross-attention\nconsumes, so it judges the prompt the model will actually see rather than its raw text. The\nprediction is clamped to `min_seconds`/`max_seconds` and then snapped down onto the VAE's\ncausal temporal grid (`8k + 1`), which is the only frame count a generation can run at.\n\nConditioning clips and video extension fix the frame count by construction -- the source\nfootage decides it -- so this node has nothing to say about those graphs.",+ "description": "Predicts the natural length of the shot a prompt describes, as an LTX-2 frame count.\n\nThe duration head reads the same connector outputs the transformer's prompt cross-attention\nconsumes, so it judges the prompt the model will actually see rather than its raw text. The\nprediction is clamped to `min_seconds`/`max_seconds` and then snapped down onto the VAE's\ncausal temporal grid (`8k + 1`), which is the only frame count a generation can run at.\n\nFor an extension, the prompt describes the continuation rather than the frames it opens with,\nso the prediction sizes the new material and `context_frames` is added in front of it.\nConditioning clips fix the frame count by construction -- the clip decides it -- so this node\nhas nothing to say about those graphs.","node_pack": "invokeai","properties": {"id": {@@ -62229,6 +62229,35 @@"title": "Max Seconds","type": "number"},+ "context_frames": {+ "default": 0,+ "description": "Source frames the run opens with, as an extension's `context_frames`. The prediction covers what follows them, so they are added to it. 0 when nothing is held.",+ "field_kind": "input",+ "input": "any",+ "minimum": 0,+ "orig_default": 0,+ "orig_required": false,+ "title": "Context Frames",+ "type": "integer"+ },+ "max_num_frames": {+ "anyOf": [+ {+ "minimum": 1,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Longest total frame count the run was sized for. The result never exceeds it, whatever frame rate the seconds bounds turn out to be read at.",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false,+ "title": "Max Num Frames"+ },"type": {"const": "ltx2_duration","default": "ltx2_duration",@@ -62241,7 +62270,7 @@"tags": ["ltx", "ltx2", "video", "duration", "frames"],"title": "Duration - LTX-2","type": "object",- "version": "1.0.0",+ "version": "1.1.0","output": {"$ref": "#/components/schemas/LTX2DurationOutput"}@@ -62251,7 +62280,7 @@"description": "A predicted shot length, as both a frame count and the seconds it came from.","properties": {"num_frames": {- "description": "Frame count on LTX-2's 8k+1 grid. Wire into the denoise node's `num_frames`.",+ "description": "Frame count on LTX-2's 8k+1 grid, including any context frames. Wire into the denoise node's `num_frames`.","field_kind": "output","title": "Num Frames","type": "integer",diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex ff8b7a5bd4..ef08ffc459 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -24788,8 +24788,10 @@ export type components = {* prediction is clamped to `min_seconds`/`max_seconds` and then snapped down onto the VAE's* causal temporal grid (`8k + 1`), which is the only frame count a generation can run at.*- * Conditioning clips and video extension fix the frame count by construction -- the source- * footage decides it -- so this node has nothing to say about those graphs.+ * For an extension, the prompt describes the continuation rather than the frames it opens with,+ * so the prediction sizes the new material and `context_frames` is added in front of it.+ * Conditioning clips fix the frame count by construction -- the clip decides it -- so this node+ * has nothing to say about those graphs.*/LTX2DurationInvocation: {/**@@ -24839,6 +24841,18 @@ export type components = {* @default 20*/max_seconds?: number;+ /**+ * Context Frames+ * @description Source frames the run opens with, as an extension's `context_frames`. The prediction covers what follows them, so they are added to it. 0 when nothing is held.+ * @default 0+ */+ context_frames?: number;+ /**+ * Max Num Frames+ * @description Longest total frame count the run was sized for. The result never exceeds it, whatever frame rate the seconds bounds turn out to be read at.+ * @default null+ */+ max_num_frames?: number | null;/*** type* @default ltx2_duration@@ -24853,7 +24867,7 @@ export type components = {LTX2DurationOutput: {/*** Num Frames- * @description Frame count on LTX-2's 8k+1 grid. Wire into the denoise node's `num_frames`.+ * @description Frame count on LTX-2's 8k+1 grid, including any context frames. Wire into the denoise node's `num_frames`.*/num_frames: number;/**diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 67f22a4585..31e5408c1f 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -4120,6 +4120,7 @@"fps": "FPS","extendContext": "Context Frames","extendContextHelp": "Frames of the initial video carried in. Adds {{frames}} new frames ({{seconds}}s).",+ "extendContextHelpAuto": "Frames of the initial video carried in. Adds up to {{frames}} new frames ({{seconds}}s).","frames": "Frames","maxFrames": "Max frames","framesDuration": "{{seconds}} s at the current frame rate",diff --git a/invokeai/frontend/webv2/src/features/video/core/__snapshots__/videoGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/video/core/__snapshots__/videoGraphNodeTypes.jsonindex d9b5ea4458..eb0b955a07 100644--- a/invokeai/frontend/webv2/src/features/video/core/__snapshots__/videoGraphNodeTypes.json+++ b/invokeai/frontend/webv2/src/features/video/core/__snapshots__/videoGraphNodeTypes.json@@ -10,6 +10,7 @@"core_metadata metadata wan_l2v metadata","extract_video_range fps float_to_int value","extract_video_range fps ltx2_denoise fps",+ "extract_video_range fps ltx2_duration fps","extract_video_range fps ltx2_extend_conditioning fps","extract_video_range fps ltx2_latents_to_video fps","extract_video_range video collect item",@@ -31,6 +32,7 @@"ltx2_duration num_frames core_metadata num_frames","ltx2_duration num_frames ltx2_denoise num_frames","ltx2_extend_conditioning audio_conditioning ltx2_denoise audio_prefix_conditioning",+ "ltx2_extend_conditioning context_frames ltx2_duration context_frames","ltx2_extend_conditioning context_frames video_concat transition_frames","ltx2_extend_conditioning video_conditioning ltx2_denoise video_conditioning","ltx2_image_conditioning video_conditioning ltx2_denoise keyframe_conditioning",@@ -470,7 +472,9 @@},"ltx2_duration": {"inputs": [- "conditioning"+ "conditioning",+ "context_frames",+ "fps"],"literalInputs": {"duration_head": [],@@ -480,7 +484,11 @@"is_intermediate": [true],+ "max_num_frames": [+ 121+ ],"max_seconds": [+ 4.375,5.041666666666667],"min_seconds": [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..3c7f04a9ab 100644--- a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/graph.test.ts@@ -1384,13 +1384,30 @@ describe('compileVideoGraph — LTX-2 auto duration', () => {expect(hasEdge(backendGraph, encoder.id, 'conditioning', duration.id, 'conditioning')).toBe(true);});- it('stays out of a continuation, whose length the source clip already fixes', () => {+ it('sizes a continuation from its prompt, at the source rate, behind the context it holds', () => {const model = ltx2Model('ltx2_dev');- const settings = autoSettings(model, { sourceVideo: LTX2_SOURCE_CLIP });+ // The source plays at 30 fps against a 24 fps panel, so a head reading the panel's rate is caught.+ const settings = autoSettings(model, { fps: 24, numFrames: 121, sourceVideo: { ...LTX2_SOURCE_CLIP, fps: 30 } });const { backendGraph } = compileVideoGraph(settings, model);-- // Two edges into one `num_frames` is a malformed graph, not a preference that loses.- expect(nodesOfType(backendGraph, 'ltx2_duration')).toHaveLength(0);+ const duration = nodeOfType(backendGraph, 'ltx2_duration');+ const denoise = nodeOfType(backendGraph, 'ltx2_denoise');+ const extend = nodeOfType(backendGraph, 'ltx2_extend_conditioning');+ const rateSource = backendGraph.edges.find(+ (edge) => edge.destination.node_id === denoise.id && edge.destination.field === 'fps'+ )?.source;++ // The context actually held, and the rate the run actually plays at, both known only at run time.+ expect(hasEdge(backendGraph, extend.id, 'context_frames', duration.id, 'context_frames')).toBe(true);+ expect(rateSource).toBeDefined();+ expect(hasEdge(backendGraph, rateSource!.node_id, rateSource!.field, duration.id, 'fps')).toBe(true);+ // 17 context frames leave 121 - 16 = 105 for the prediction, read at the source's 30 fps.+ expect(duration.max_seconds).toBe(105 / 30);+ expect(duration.max_num_frames).toBe(121);+ expect(+ backendGraph.edges.filter(+ (edge) => edge.destination.node_id === denoise.id && edge.destination.field === 'num_frames'+ )+ ).toEqual([expect.objectContaining({ source: { field: 'num_frames', node_id: duration.id } })]);});it('runs both passes of a two-stage preset at the length it chose', () => {diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.ts b/invokeai/frontend/webv2/src/features/video/core/graph.tsindex ba6fa8e153..c350349000 100644--- a/invokeai/frontend/webv2/src/features/video/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/video/core/graph.ts@@ -776,17 +776,19 @@ const buildLtx2VideoGraph = (settings: VideoSettings, model: MainModelConfig): B//// Only in the modes whose length is still open. A conditioning clip drives `num_frames` by its// own edge further down, and a second edge into one input is a malformed graph rather than a- // fallback; an extension has no such edge, but its length is the continuation the user asked- // for, measured against the source it joins. The head chooses at most the Frames value, which- // under auto duration is the ceiling the run's memory was sized for.+ // fallback. An extension's prompt sizes the continuation; its rate and held context arrive over+ // edges once the join is laid out. The head chooses at most the Frames value, which under auto+ // duration is the ceiling the run's memory was sized for -- passed in frames as well, because a+ // continuation's seconds are read at a rate only the run knows.const durationBounds = getAutoDurationBounds(model, settings);const durationHead =durationBounds && settings.ltx2DurationHeadModel? addNode(graph, {duration_head: settings.ltx2DurationHeadModel,- fps: timing.fps,+ ...(durationBounds.contextFrames ? {} : { fps: durationBounds.fps }),id: 'duration',type: 'ltx2_duration',+ max_num_frames: timing.numFrames,max_seconds: durationBounds.maxSeconds,min_seconds: durationBounds.minSeconds,})@@ -1068,6 +1070,10 @@ const buildLtx2VideoGraph = (settings: VideoSettings, model: MainModelConfig): B}addEdge(graph, extendConditioning, 'context_frames', join.concat, 'transition_frames');+ if (durationHead) {+ addEdge(graph, extendConditioning, 'context_frames', durationHead, 'context_frames');+ addEdge(graph, join.extract, 'fps', durationHead, 'fps');+ }// The continuation inherits the source's own frame rate, read off the trimmed clip at run time// rather than from the gallery's record of it -- a video row's fps is nullable, and a guess// here would play the two halves at different speeds and mistime the generated soundtrack.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..9b33d91a4f 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts@@ -29,6 +29,7 @@ import {getVideoModes,getVideoPromptPolicy,getVideoValidationReasons,+ getAutoDurationBounds,isAutoDurationActive,isAutoDurationSupportedForMode,getWanExpertWiringWarning,@@ -2531,11 +2532,14 @@ describe('auto duration', () => {});- it('has none for a continuation: its length is the new material the user asked for', () => {+ it('sizes a continuation at the source rate, with the context counted against the ceiling', () => {const extending = settings({+ fps: 24,+ ltx2ExtendContextFrames: 25,+ numFrames: 121,sourceVideo: {endFrame: 48,- fps: 24,+ fps: 30,height: 704,numFrames: 49,startFrame: 0,@@ -2544,8 +2548,15 @@ describe('auto duration', () => {},} as Partial<VideoSettings>);- expect(isAutoDurationSupportedForMode(extending)).toBe(false);- expect(isAutoDurationActive(extending)).toBe(false);+ expect(isAutoDurationSupportedForMode(extending)).toBe(true);+ // 25 held frames leave 121 - 24 = 97 for the prediction, at 30 fps; the total is back at 121.+ expect(getAutoDurationBounds(ltx2('ltx2_dev'), extending)).toEqual({+ contextFrames: 25,+ fps: 30,+ maxFrames: 121,+ maxSeconds: 97 / 30,+ minSeconds: 1,+ });});it('is inactive without a head, however the flag is stored', () => {diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.tsindex 885c532160..1a19832f1c 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts@@ -46,6 +46,7 @@ import {resolveLtx2Canvas,resolveMiniMaxH3Canvas,scaleAndSnapWanDimensions,+ snapLtx2FramesDown,snapNumFramesToChoices,snapNumFramesToGrid,WAN_A14B_PIXEL_MULTIPLE,@@ -637,8 +638,8 @@ export interface EffectiveVideoTiming {* Whether this mode has a length left for the duration head to decide.** A conditioning clip drives `num_frames` by its own edge, and a second edge into one input is a- * malformed graph. An extension has no such edge, but its frame count is the new material the user- * asked for, measured against the source it joins -- a prompt's natural length is not that number.+ * malformed graph. An extension has no such edge: its prompt describes the continuation, so the+ * head sizes the new material and the held context is added in front of it.** Separate from `isAutoDurationActive` because the panel needs to say *why* the control is* unavailable, which "not active" alone cannot tell it.@@ -651,7 +652,7 @@ export const isAutoDurationSupportedForMode = (): boolean => {const mode = resolveVideoMode(settings);- return mode !== 'audio-to-video' && mode !== 'video-to-audio' && mode !== 'extend';+ return mode !== 'audio-to-video' && mode !== 'video-to-audio';};/**@@ -837,6 +838,17 @@ export interface VideoModelPolicy {};}+export interface AutoDurationBounds {+ maxSeconds: number;+ minSeconds: number;+ /** Frames held in front of the prediction: an extension's context, else 0. */+ contextFrames: number;+ /** The longest total the head can hand the run, context included, at `fps`. */+ maxFrames: number;+ /** The rate the seconds are read at; a continuation's is the source's. */+ fps: number;+}+/*** The range the duration head chooses this run's length from, or null when it does not run.*@@ -845,11 +857,15 @@ export interface VideoModelPolicy {* sized the run for. A ceiling at or under that floor leaves nothing to choose: the head is skipped* and the run uses the Frames value as set. The graph and the panel both read this, so the panel's* description of the run is the run.+ *+ * A continuation plays at its source's rate, and its prompt describes only what follows the held+ * context, so the head chooses the new material: from the family's shortest clip up to whatever of+ * the Frames ceiling the context leaves.*/export const getAutoDurationBounds = (model: MainModelConfig | undefined,settings: VideoSettings-): { maxSeconds: number; minSeconds: number } | null => {+): AutoDurationBounds | null => {if (!isAutoDurationActive(settings)) {return null;}@@ -858,8 +874,23 @@ export const getAutoDurationBounds = (return null;}const timing = getEffectiveVideoTiming(model, settings);+ const source = resolveVideoMode(settings) === 'extend' ? settings.sourceVideo : null;+ const fps = source?.fps ?? timing.fps;+ const contextFrames = source ? settings.ltx2ExtendContextFrames : 0;+ // Both 8k + 1, so their difference plus one is too: the longest prediction that still fits.+ const bounds = ltx2AutoDurationBounds(fps, frames.min, timing.numFrames - Math.max(0, contextFrames - 1));+ if (!bounds) {+ return null;+ }+ // The head converts seconds at the run's rate and floors onto the grid, the same as here.+ const predicted = snapLtx2FramesDown(Math.round(bounds.maxSeconds * fps));- return ltx2AutoDurationBounds(timing.fps, frames.min, timing.numFrames);+ return {+ ...bounds,+ contextFrames,+ fps,+ maxFrames: contextFrames ? contextFrames + predicted - 1 : predicted,+ };};export const getVideoModelPolicy = (model: MainModelConfig | undefined, settings: VideoSettings): VideoModelPolicy => {diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsxindex bf044f786b..6e2cee5d08 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx@@ -156,14 +156,16 @@ export const VideoWidgetView = () => {() =>autoDurationBounds? {- // The head converts seconds at the run's rate and floors onto the grid, the same as here.- frames: snapLtx2FramesDown(Math.round(autoDurationBounds.maxSeconds * timing.fps)),- seconds: autoDurationBounds.maxSeconds,+ frames: autoDurationBounds.maxFrames,+ seconds: autoDurationBounds.maxFrames / autoDurationBounds.fps,}: null,- [autoDurationBounds, timing.fps]+ [autoDurationBounds]);const autoDurationSupported = useMemo(() => isAutoDurationSupportedForMode(values), [values]);+ const extendNewFrames = autoDurationBounds+ ? autoDurationBounds.maxFrames - autoDurationBounds.contextFrames+ : (policy.ui.extendContext?.newFrames ?? 0);const durationSeconds = getVideoDurationSeconds(timing.numFrames,// In extend mode the extension inherits the SOURCE clip's frame rate.@@ -642,10 +644,15 @@ export const VideoWidgetView = () => {defaultValue={LTX2_EXTEND_CONTEXT_FRAMES}// The trade this control makes, which Frames alone does not show: the join consumes// the context from both halves, so every frame held is a frame of new video given up.- helpText={t('widgets.video.extendContextHelp', {- frames: policy.ui.extendContext.newFrames,- seconds: (policy.ui.extendContext.newFrames / Math.max(1, values.fps)).toFixed(1),- })}+ // Under auto duration Frames is only a ceiling, so the new material is too.+ helpText={t(+ autoDurationBounds ? 'widgets.video.extendContextHelpAuto' : 'widgets.video.extendContextHelp',+ {+ frames: extendNewFrames,+ // The continuation plays at the source's rate, not the panel's.+ seconds: (extendNewFrames / Math.max(1, values.sourceVideo?.fps ?? values.fps)).toFixed(1),+ }+ )}inputMax={policy.ui.extendContext.max}label={t('widgets.video.extendContext')}max={policy.ui.extendContext.max}diff --git a/tests/app/invocations/test_ltx2_duration.py b/tests/app/invocations/test_ltx2_duration.pyindex 2561f9653a..fe66a7bf88 100644--- a/tests/app/invocations/test_ltx2_duration.py+++ b/tests/app/invocations/test_ltx2_duration.py@@ -134,3 +134,45 @@ def test_it_refuses_a_batch_of_prompts(monkeypatch: pytest.MonkeyPatch) -> None:head = _head(monkeypatch, seconds=5.0)with pytest.raises(ValueError, match="exactly one conditioning"):_node().invoke(_context(head, conditioning_count=2))+++def test_an_extension_s_context_is_added_in_front_of_the_predicted_continuation(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The prompt sizes the new material: 5s at 24 fps is 113 frames, i.e. 112 after the first, behind 17 held ones."""+ head = _head(monkeypatch, seconds=5.0)+ output = _node(fps=24.0, context_frames=17).invoke(_context(head))++ assert output.num_frames == 17 + 112+ assert (output.num_frames - 1) % 8 == 0+++def test_an_extension_always_keeps_one_group_of_new_material(monkeypatch: pytest.MonkeyPatch) -> None:+ """At 1 fps a 1s floor is one frame; added naively that is the context alone, a continuation of nothing."""+ head = _head(monkeypatch, seconds=0.3)+ output = _node(fps=1.0, min_seconds=1.0, max_seconds=5.0, context_frames=17).invoke(_context(head))++ assert output.num_frames == 17 + 8++[email protected]("context_frames", [0, 17])+def test_the_frame_ceiling_holds_when_the_rate_is_higher_than_the_bounds_assumed(+ monkeypatch: pytest.MonkeyPatch, context_frames: int+) -> None:+ """Bounds sized at a guessed 24 fps, read at a real 48: the seconds clamp alone would double the run."""+ head = _head(monkeypatch, seconds=30.0)+ output = _node(fps=48.0, max_seconds=5.0, context_frames=context_frames, max_num_frames=124).invoke(_context(head))++ assert output.num_frames == 121 # 124 snapped down onto the grid+++ ("context_frames", "max_num_frames", "match"),+ [(16, None, "8k\\+1 grid"), (17, 20, "leaves no room")],+)+def test_it_refuses_a_context_it_cannot_continue_from(+ monkeypatch: pytest.MonkeyPatch, context_frames: int, max_num_frames: int | None, match: str+) -> None:+ head = _head(monkeypatch, seconds=5.0)+ with pytest.raises(ValueError, match=match):+ _node(context_frames=context_frames, max_num_frames=max_num_frames).invoke(_context(head))