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(webv2): give an audio-only reference its whole clip, not 8 seconds of it

Lincoln Steind60b889be0a0
diff --git a/invokeai/app/invocations/minimax_h3_reference.py b/invokeai/app/invocations/minimax_h3_reference.py
index 3194c0f00f..5bf4bded17 100644
--- a/invokeai/app/invocations/minimax_h3_reference.py
+++ b/invokeai/app/invocations/minimax_h3_reference.py
@@ -47,6 +47,7 @@ from invokeai.backend.minimax_h3.autoencoder_kl_minimax_h3 import AutoencoderKLM
from invokeai.backend.minimax_h3.autoencoder_kl_minimax_h3_audio import AutoencoderKLMiniMaxH3Audio
from invokeai.backend.minimax_h3.packing import (
MINIMAX_H3_CANVAS_MULTIPLE,
+ MINIMAX_H3_FPS,
validate_reference_kinds,
)
from invokeai.backend.minimax_h3.presets import MINIMAX_H3_MIN_VIDEO_FRAMES
@@ -251,6 +252,12 @@ def load_reference_audio(
pcm, rate = extracted
window_start = round(span.start * rate / span.fps)
window_end = round((span.end + 1) * rate / span.fps)
+ # Only the generated duration ever survives normalize_reference_audio, so bound the
+ # window here rather than carrying samples that are about to be dropped. This is what
+ # keeps the silence-pad below cheap: np.pad allocates the WHOLE window, and an
+ # audio-only reference defaults to its entire clip, so padding an unbounded window
+ # would copy a full-length track to preserve an alignment truncation then discards.
+ window_end = min(window_end, window_start + int(num_frames / MINIMAX_H3_FPS * rate))
window = pcm[:, window_start:window_end]
if window.shape[1] == 0:
raise ValueError(
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 70b35d9194..829fed814d 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,7 @@ import type { VideoReferenceItem, VideoSettings } from './types';
import { MINIMAX_H3_NUM_FRAMES_CHOICES } from './dimensions';
import {
+ DEFAULT_REFERENCE_SAMPLE_FRAMES,
resizeReferenceSampleWindow,
slideReferenceSampleWindow,
applyReferenceExtendSourceVideo,
@@ -14,6 +15,7 @@ import {
cloneVideoWidgetValues,
createVideoSourceClip,
deriveReferenceExtendClip,
+ getDefaultReferenceClip,
getDefaultReferenceConditioning,
getDefaultReferenceImageDetail,
isVideoSettings,
@@ -281,6 +283,89 @@ describe('getDefaultReferenceConditioning', () => {
});
});
+describe('getDefaultReferenceClip', () => {
+ // A wrapped audio upload: the server renders it at AUDIO_WRAP_FPS (24), so
+ // DEFAULT_REFERENCE_SAMPLE_FRAMES lands at a little over 8 seconds of the track.
+ // Deliberately handed in with a narrow, offset window: were the helper to pass its clip
+ // through unchanged, the audio expectation below would still be satisfied by a fixture
+ // that already held the whole clip.
+ const wrappedAudio = {
+ endFrame: 199,
+ fps: 24,
+ height: 512,
+ numFrames: 4320,
+ startFrame: 120,
+ video_name: 'song.mp4',
+ width: 512,
+ };
+
+ // Long enough that the sample window actually bites: SOURCE_VIDEO's 81 frames are
+ // shorter than DEFAULT_REFERENCE_SAMPLE_FRAMES, so it can only exercise the clamp.
+ const footage = { ...SOURCE_VIDEO, endFrame: 599, numFrames: 600 };
+
+ it('samples footage from the head of the clip', () => {
+ expect(getDefaultReferenceClip(footage, 'video_audio')).toEqual({
+ ...footage,
+ endFrame: DEFAULT_REFERENCE_SAMPLE_FRAMES - 1,
+ startFrame: 0,
+ });
+ expect(getDefaultReferenceClip(footage, 'video')).toEqual({
+ ...footage,
+ endFrame: DEFAULT_REFERENCE_SAMPLE_FRAMES - 1,
+ startFrame: 0,
+ });
+ });
+
+ it('gives the same long clip its whole length once it is audio-only', () => {
+ expect(getDefaultReferenceClip(footage, 'audio').endFrame).toBe(599);
+ });
+
+ it('gives an audio-only reference the whole clip', () => {
+ // 3 minutes of audio, not the first 8 seconds of it: an audio reference is encoded as
+ // a soundtrack and no visual rows, and the window is what the generation gets to hear.
+ expect(getDefaultReferenceClip(wrappedAudio, 'audio')).toEqual({
+ ...wrappedAudio,
+ endFrame: 4319,
+ startFrame: 0,
+ });
+ });
+
+ it('still samples the head of that same clip when it carries video', () => {
+ expect(getDefaultReferenceClip(wrappedAudio, 'video_audio')).toEqual({
+ ...wrappedAudio,
+ endFrame: DEFAULT_REFERENCE_SAMPLE_FRAMES - 1,
+ startFrame: 0,
+ });
+ });
+
+ it('never samples past the end of a clip shorter than the window', () => {
+ // SOURCE_VIDEO is 81 frames; both conditionings collapse to the whole clip.
+ expect(getDefaultReferenceClip(SOURCE_VIDEO, 'video_audio').endFrame).toBe(80);
+ expect(getDefaultReferenceClip(SOURCE_VIDEO, 'audio').endFrame).toBe(80);
+
+ const short = { ...SOURCE_VIDEO, endFrame: 11, numFrames: 12 };
+
+ expect(getDefaultReferenceClip(short, 'video_audio').endFrame).toBe(11);
+ expect(getDefaultReferenceClip(short, 'audio').endFrame).toBe(11);
+ });
+
+ it('keeps the shortest real clip on its single frame', () => {
+ // createVideoSourceClip floors numFrames at 1, so this is the smallest clip either
+ // branch can be handed; both must land on frame 0, not on -1.
+ const single = { ...SOURCE_VIDEO, endFrame: 0, numFrames: 1 };
+
+ expect(getDefaultReferenceClip(single, 'video_audio').endFrame).toBe(0);
+ expect(getDefaultReferenceClip(single, 'audio').endFrame).toBe(0);
+ });
+
+ it('resets the start frame, so a trimmed source clip does not carry its trim in', () => {
+ const trimmed = { ...SOURCE_VIDEO, endFrame: 70, startFrame: 40 };
+
+ expect(getDefaultReferenceClip(trimmed, 'video_audio').startFrame).toBe(0);
+ expect(getDefaultReferenceClip(trimmed, 'audio').startFrame).toBe(0);
+ });
+});
+
describe('getDefaultReferenceImageDetail', () => {
const imageReference = {
detail: 'max',
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.ts
index 67ff8bd225..e3170bce9f 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts
@@ -553,6 +553,36 @@ export const getDefaultReferenceConditioning = (
metadata: Record<string, unknown> | null | undefined
): VideoReferenceConditioning => (metadata?.media_origin === 'audio_upload' ? 'audio' : 'video_audio');
+/**
+ * The sample window a newly added video reference starts on.
+ *
+ * Footage starts on {@link DEFAULT_REFERENCE_SAMPLE_FRAMES} from the clip's head, because
+ * every reference frame is VAE-encoded into rows the denoiser re-attends at every step.
+ *
+ * An AUDIO-ONLY reference starts on the whole clip. It pays none of that cost: the backend
+ * decodes a reference's frames only when its packed kind is `video` (`reference_kind`), so
+ * an 'audio' reference contributes soundtrack rows and no visual rows at all — and those
+ * rows are bounded by the GENERATED duration, not by how long the window is. What the
+ * window decides is which audio the model hears: the track is sliced to the window and only
+ * THEN truncated to the generated duration, so a window shorter than the generation cuts
+ * the soundtrack off early. At 8s that is every frame count above 200 — over half of the
+ * ones the panel offers.
+ *
+ * Only the starting value — the card's sample-length control still trims either kind, and
+ * changing a card's conditioning afterwards leaves the window the user can see alone.
+ */
+export const getDefaultReferenceClip = (
+ clip: VideoSourceClip,
+ conditioning: VideoReferenceConditioning
+): VideoSourceClip => ({
+ ...clip,
+ endFrame:
+ conditioning === 'audio'
+ ? Math.max(0, clip.numFrames - 1)
+ : Math.max(0, Math.min(DEFAULT_REFERENCE_SAMPLE_FRAMES, clip.numFrames) - 1),
+ startFrame: 0,
+});
+
/**
* The detail a newly added image reference starts on.
*
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
index 3f0f03b12a..b74ffa537f 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
@@ -16,7 +16,7 @@ import { galleryImageUrls, galleryVideoUrls, isGalleryItemDragData } from '@feat
import { resolveMiniMaxH3ReferenceImage } from '@features/video/core/dimensions';
import {
createVideoSourceClip,
- DEFAULT_REFERENCE_SAMPLE_FRAMES,
+ getDefaultReferenceClip,
getDefaultReferenceConditioning,
getDefaultReferenceImageDetail,
resizeReferenceSampleWindow,
@@ -476,15 +476,10 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({
// Built outside the updater so the caller holds the same object the list does: it is
// the only durable handle on this entry once reordering moves it.
const entry: Extract<VideoReferenceItem, { kind: 'video' }> = {
- // Default to a short sample window from the clip's start, not the whole
- // clip: reference frames cost denoise VRAM every step, and a few seconds
- // captures the wanted features. (Not the extend-mode 2-frame-tail trim
- // either -- references are truncated to the generated duration, not joined.)
- clip: {
- ...clip,
- endFrame: Math.max(0, Math.min(DEFAULT_REFERENCE_SAMPLE_FRAMES, clip.numFrames) - 1),
- startFrame: 0,
- },
+ // The window depends on the conditioning -- a short sample of footage, the whole
+ // clip of a soundtrack. (Neither is the extend-mode 2-frame-tail trim: references
+ // are truncated to the generated duration, not joined.)
+ clip: getDefaultReferenceClip(clip, conditioning),
conditioning,
kind: 'video',
};
@@ -655,10 +650,20 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({
if (conditioning === entry.conditioning) {
return;
}
+ // The window is re-derived with the conditioning, not carried over: this path adds
+ // BEFORE it knows the answer, so the card is holding the footage default, and
+ // leaving it would give a picked soundtrack a shorter window than the same clip
+ // dropped or uploaded. Safe to recompute -- the identity match below already
+ // establishes that the window is still the one this code chose.
+ //
// Matched by identity, not index: a card the user has since edited is a different
// object and keeps their choice, and a removed one is simply no longer there.
onChange((current) =>
- current.map((existing) => (existing === entry ? { ...entry, conditioning } : existing))
+ current.map((existing) =>
+ existing === entry
+ ? { ...entry, clip: getDefaultReferenceClip(entry.clip, conditioning), conditioning }
+ : existing
+ )
);
})
.catch(() => undefined);
diff --git a/tests/app/invocations/test_minimax_h3_reference_nodes.py b/tests/app/invocations/test_minimax_h3_reference_nodes.py
index e0282c0cc1..92a467f04c 100644
--- a/tests/app/invocations/test_minimax_h3_reference_nodes.py
+++ b/tests/app/invocations/test_minimax_h3_reference_nodes.py
@@ -7,6 +7,7 @@ guard. The numerics live in tests/backend/minimax_h3/.
from unittest.mock import MagicMock
+import numpy as np
import pytest
import torch
@@ -20,6 +21,7 @@ from invokeai.app.invocations.fields import (
)
from invokeai.app.invocations.minimax_h3_denoise import MiniMaxH3DenoiseInvocation
from invokeai.app.invocations.minimax_h3_reference import (
+ load_reference_audio,
normalize_reference_list,
reference_has_audio,
reference_kind,
@@ -227,3 +229,85 @@ class TestTextEncoderGuards:
node = self._node(references=_image_ref())
with pytest.raises(ValueError, match="num_frames is required"):
node.invoke(MagicMock())
+
+
+class _Span:
+ """The parts of `_ResolvedVideoRange` that `load_reference_audio` reads."""
+
+ def __init__(self, start: int, end: int, fps: float, path: str = "clip.mp4") -> None:
+ self.start = start
+ self.end = end
+ self.fps = fps
+ self.path = path
+
+
+class TestReferenceAudioWindow:
+ """The soundtrack window is bounded by the GENERATED duration before anything copies it.
+
+ An audio-only reference defaults to its whole clip (the frontend's
+ `getDefaultReferenceClip`), which for an uploaded song is minutes of PCM. Only
+ `num_frames / 24` seconds of it ever survive normalization, so the window has to be
+ clamped before the silence-pad -- `np.pad` allocates the whole window, however few
+ samples it actually adds.
+ """
+
+ RATE = 32_000 # the audio VAE's own rate, so normalization is a pass-through
+ FPS = 24.0 # AUDIO_WRAP_FPS: what the ingest wrapper renders an audio upload at
+
+ def _patch_pcm(self, monkeypatch, pcm):
+ monkeypatch.setattr(
+ "invokeai.app.invocations.minimax_h3_reference.extract_audio_pcm",
+ lambda path, float_pcm=False: (pcm, self.RATE),
+ )
+
+ def test_whole_clip_window_keeps_only_the_generated_duration(self, monkeypatch):
+ # A 60 s track behind a 14.375 s (345-frame) generation.
+ pcm = np.linspace(-1, 1, 60 * self.RATE, dtype=np.float32)[None].repeat(2, axis=0)
+ self._patch_pcm(monkeypatch, pcm)
+ out = load_reference_audio(_video_ref(conditioning="audio"), _Span(0, 60 * 24 - 1, self.FPS), 345)
+
+ kept = int(345 / self.FPS * self.RATE)
+ assert out.shape == (2, kept)
+ assert torch.equal(out, torch.from_numpy(pcm[:, :kept]))
+
+ def test_short_track_pads_to_the_generated_duration_not_the_clip(self, monkeypatch):
+ # The track ends long before the video does: the silence-pad must fill the
+ # generated duration, NOT the 60 s the whole-clip window nominally spans.
+ pcm = np.ones((2, 5 * self.RATE), dtype=np.float32)
+ self._patch_pcm(monkeypatch, pcm)
+ out = load_reference_audio(_video_ref(conditioning="audio"), _Span(0, 60 * 24 - 1, self.FPS), 345)
+
+ kept = int(345 / self.FPS * self.RATE)
+ assert out.shape == (2, kept)
+ assert torch.equal(out[:, : 5 * self.RATE], torch.ones(2, 5 * self.RATE))
+ assert torch.equal(out[:, 5 * self.RATE :], torch.zeros(2, kept - 5 * self.RATE))
+
+ def test_does_not_pad_beyond_the_generated_duration(self, monkeypatch):
+ # The actual regression guard. The two tests above only prove the OUTPUT is
+ # unchanged -- normalization truncates either way, so they pass with or without the
+ # clamp. This one watches the allocation: unclamped, np.pad is asked to build the
+ # whole 60 s window (a full-length copy of an uploaded song) to preserve an
+ # alignment that is discarded on the next line.
+ pcm = np.ones((2, 5 * self.RATE), dtype=np.float32)
+ self._patch_pcm(monkeypatch, pcm)
+ widths: list[int] = []
+ real_pad = np.pad
+
+ def spy(array, pad_width, *args, **kwargs):
+ widths.append(array.shape[1] + pad_width[1][1])
+
+ return real_pad(array, pad_width, *args, **kwargs)
+
+ monkeypatch.setattr(np, "pad", spy)
+ load_reference_audio(_video_ref(conditioning="audio"), _Span(0, 60 * 24 - 1, self.FPS), 345)
+
+ assert widths == [int(345 / self.FPS * self.RATE)]
+
+ def test_window_shorter_than_the_generation_is_left_alone(self, monkeypatch):
+ # The clamp must not lengthen a deliberately short window: 200 frames of a
+ # 345-frame generation still yields 200 frames' worth of audio, cut short.
+ pcm = np.linspace(-1, 1, 60 * self.RATE, dtype=np.float32)[None].repeat(2, axis=0)
+ self._patch_pcm(monkeypatch, pcm)
+ out = load_reference_audio(_video_ref(conditioning="audio"), _Span(0, 199, self.FPS), 345)
+
+ assert out.shape == (2, round(200 * self.RATE / self.FPS))