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.

feat(nodes): preserve audio in Frame Range from Video

Lincoln Stein0db3ae8e3bb4
diff --git a/invokeai/app/invocations/video_frame_extract_range.py b/invokeai/app/invocations/video_frame_extract_range.py
index b9449e5201..2c85698044 100644
--- a/invokeai/app/invocations/video_frame_extract_range.py
+++ b/invokeai/app/invocations/video_frame_extract_range.py
@@ -5,6 +5,13 @@ Companion to ``video_frame_extract`` (single frame → image) and
video and emits a new MP4, so the output can be fed straight into
Concatenate Videos to splice clips together — e.g. trim a generated clip
to a usable middle section before chaining it to another shot.
+
+If the source carries an audio track, the matching slice of it is carried
+through (and retimed alongside the video when the output fps differs from
+the source's). Like ``video_concat``, the audio path buffers the source
+soundtrack in full — float32 stereo PCM, ~3 orders of magnitude smaller
+per second than decoded frames — and audio failures fail the node loudly
+rather than emit a silently-stripped clip.
"""
import tempfile
@@ -32,7 +39,8 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.primitives import VideoOutput
from invokeai.app.services.session_processor.session_processor_common import CanceledException
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.app.util.video_encoding import make_mp4_writer
+from invokeai.app.util.video_audio import extract_audio_pcm, mux_audio_into_video, resample_linear
+from invokeai.app.util.video_encoding import make_mp4_writer, write_stereo_wav
from invokeai.app.util.video_thumbnails import decoder_frame_count, iter_video_frames, probe_video
@@ -104,7 +112,7 @@ class ExtractVideoRangeOutput(BaseInvocationOutput):
title="Frame Range from Video",
tags=["video", "trim", "range", "frames"],
category="video",
- version="1.1.0",
+ version="1.2.0",
classification=Classification.Prototype,
)
class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
@@ -114,7 +122,10 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
emits 41 frames. Negative indices count from the end (``end_frame=-1``
is the final frame), matching ``video_frame_extract``. The output frame
rate defaults to the source video's frame rate; set ``fps=0`` to inherit
- it (or 16 fps if the source rate can't be probed).
+ it (or 16 fps if the source rate can't be probed). If the source has an
+ audio track, the same range of it is carried into the output (retimed
+ with the video when the output fps changes playback speed); silent
+ sources stay silent.
The resolved (positive) ``start_frame`` and ``end_frame`` are also emitted as
outputs, so chained workflows can re-use the boundary indices — e.g. feeding
@@ -183,6 +194,8 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
tmp = tempfile.NamedTemporaryFile(prefix="invokeai_video_range_", suffix=".mp4", delete=False)
tmp.close()
tmp_path = Path(tmp.name)
+ wav_path: Optional[Path] = None
+ muxed_path: Optional[Path] = None
try:
# imageio's iter_index isn't exposed by iio.imiter, so we enumerate and skip.
# Frames stream straight from the decoder into the encoder; see _write_frame_range.
@@ -206,13 +219,40 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
f"(probed {n_frames} frames). The container's metadata may be inaccurate."
)
+ # Carry the source's audio (if any) through: slice the matching span of
+ # its soundtrack and map it onto the output timeline. Silent sources
+ # keep the old behavior (no audio stream).
+ source_path = tmp_path
+ audio = self._build_audio_track(
+ context=context,
+ video_path=video_path,
+ start=start,
+ end=end,
+ n_frames=n_frames,
+ source_fps=source_fps,
+ source_duration=duration,
+ output_fps=output_fps,
+ )
+ if audio is not None:
+ pcm, rate = audio
+ context.util.signal_progress("Muxing audio")
+ wav_tmp = tempfile.NamedTemporaryFile(prefix="invokeai_video_range_", suffix=".wav", delete=False)
+ wav_tmp.close()
+ wav_path = Path(wav_tmp.name)
+ write_stereo_wav(wav_path, pcm, rate)
+ mux_tmp = tempfile.NamedTemporaryFile(prefix="invokeai_video_range_", suffix=".mp4", delete=False)
+ mux_tmp.close()
+ muxed_path = Path(mux_tmp.name)
+ mux_audio_into_video(tmp_path, wav_path, muxed_path)
+ source_path = muxed_path
+
out_duration = num_frames / output_fps
context.logger.info(
f"Encoded trimmed MP4: {num_frames} frames @ {output_fps:.2f} fps "
- f"({out_duration:.2f}s) at {width}x{height}"
+ f"({out_duration:.2f}s) at {width}x{height}" + (", with AAC audio" if audio is not None else ", silent")
)
video_dto = context.videos.save(
- source_path=tmp_path,
+ source_path=source_path,
width=width,
height=height,
duration=out_duration,
@@ -231,10 +271,61 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
end_frame=end,
)
finally:
- try:
- tmp_path.unlink(missing_ok=True)
- except Exception:
- pass
+ for cleanup in (tmp_path, wav_path, muxed_path):
+ if cleanup is None:
+ continue
+ try:
+ cleanup.unlink(missing_ok=True)
+ except Exception:
+ pass
+
+ def _build_audio_track(
+ self,
+ context: InvocationContext,
+ video_path: Path,
+ start: int,
+ end: int,
+ n_frames: int,
+ source_fps: Optional[float],
+ source_duration: Optional[float],
+ output_fps: float,
+ ) -> Optional[tuple[np.ndarray, int]]:
+ """Slice the source soundtrack to frames [start, end] and map it onto the output timeline.
+
+ Returns ``(pcm, sample_rate)`` — ``pcm`` shaped ``(2, n)``, float32 in [-1, 1] —
+ or ``None`` when the source has no audio track.
+
+ Frame-to-sample mapping needs the source's effective frame rate. Preference
+ order (mirroring ``video_concat``): the probed fps; the probed duration (fps can
+ be None for VFR-flagged containers); the extracted length itself, which
+ approximates the native span to within the codec padding. The final resample
+ maps the sliced window onto the span the trimmed video occupies in the output —
+ a no-op at matching fps, a deliberate speed/pitch retime under an fps override
+ (matching what the retime does to the video).
+ """
+ context.util.signal_progress("Extracting audio")
+ extracted = extract_audio_pcm(video_path)
+ if extracted is None:
+ return None
+ if context.util.is_canceled():
+ raise CanceledException
+ pcm, rate = extracted
+ if source_fps is not None and source_fps > 0:
+ eff_fps = float(source_fps)
+ elif source_duration is not None and source_duration > 0:
+ eff_fps = n_frames / float(source_duration)
+ else:
+ # extract_audio_pcm returns None for zero-sample tracks, so pcm is non-empty.
+ eff_fps = n_frames * rate / pcm.shape[1]
+ window_start = round(start * rate / eff_fps)
+ window_end = round((end + 1) * rate / eff_fps)
+ window = pcm[:, window_start:window_end]
+ if window.shape[1] < window_end - window_start:
+ # Audio track shorter than the video (or the range lies past its end):
+ # keep temporal alignment by padding the shortfall with silence.
+ window = np.pad(window, ((0, 0), (0, (window_end - window_start) - window.shape[1])))
+ target = round((end - start + 1) / output_fps * rate)
+ return resample_linear(window, target), rate
@staticmethod
def _resolve_index(value: int, n_frames: int, field_name: str) -> int:
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 8fd4a282e0..dd56cb8256 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -27749,7 +27749,7 @@
"category": "video",
"class": "invocation",
"classification": "prototype",
- "description": "Trim a video to a contiguous frame range and re-encode as MP4.\n\nBoth bounds are inclusive and 0-based \u2014 ``start_frame=10, end_frame=50``\nemits 41 frames. Negative indices count from the end (``end_frame=-1``\nis the final frame), matching ``video_frame_extract``. The output frame\nrate defaults to the source video's frame rate; set ``fps=0`` to inherit\nit (or 16 fps if the source rate can't be probed).\n\nThe resolved (positive) ``start_frame`` and ``end_frame`` are also emitted as\noutputs, so chained workflows can re-use the boundary indices \u2014 e.g. feeding\nthem into a downstream Frame from Video to extract the same boundary frame.",
+ "description": "Trim a video to a contiguous frame range and re-encode as MP4.\n\nBoth bounds are inclusive and 0-based \u2014 ``start_frame=10, end_frame=50``\nemits 41 frames. Negative indices count from the end (``end_frame=-1``\nis the final frame), matching ``video_frame_extract``. The output frame\nrate defaults to the source video's frame rate; set ``fps=0`` to inherit\nit (or 16 fps if the source rate can't be probed). If the source has an\naudio track, the same range of it is carried into the output (retimed\nwith the video when the output fps changes playback speed); silent\nsources stay silent.\n\nThe resolved (positive) ``start_frame`` and ``end_frame`` are also emitted as\noutputs, so chained workflows can re-use the boundary indices \u2014 e.g. feeding\nthem into a downstream Frame from Video to extract the same boundary frame.",
"node_pack": "invokeai",
"properties": {
"board": {
@@ -27869,7 +27869,7 @@
"tags": ["video", "trim", "range", "frames"],
"title": "Frame Range from Video",
"type": "object",
- "version": "1.1.0",
+ "version": "1.2.0",
"output": {
"$ref": "#/components/schemas/ExtractVideoRangeOutput"
}
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index ba4b9cb88b..138f258443 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -10843,7 +10843,10 @@ export type components = {
* emits 41 frames. Negative indices count from the end (``end_frame=-1``
* is the final frame), matching ``video_frame_extract``. The output frame
* rate defaults to the source video's frame rate; set ``fps=0`` to inherit
- * it (or 16 fps if the source rate can't be probed).
+ * it (or 16 fps if the source rate can't be probed). If the source has an
+ * audio track, the same range of it is carried into the output (retimed
+ * with the video when the output fps changes playback speed); silent
+ * sources stay silent.
*
* The resolved (positive) ``start_frame`` and ``end_frame`` are also emitted as
* outputs, so chained workflows can re-use the boundary indices — e.g. feeding
diff --git a/tests/app/invocations/test_video_frame_extract_range.py b/tests/app/invocations/test_video_frame_extract_range.py
index 52945ca7d1..a62590ec81 100644
--- a/tests/app/invocations/test_video_frame_extract_range.py
+++ b/tests/app/invocations/test_video_frame_extract_range.py
@@ -101,6 +101,7 @@ def test_invocation_only_saves_complete_requested_range(written: int, should_rai
patch("invokeai.app.invocations.video_frame_extract_range.decoder_frame_count", return_value=5),
patch("invokeai.app.invocations.video_frame_extract_range.make_mp4_writer", return_value=MagicMock()),
patch("invokeai.app.invocations.video_frame_extract_range._write_frame_range", return_value=written),
+ patch("invokeai.app.invocations.video_frame_extract_range.extract_audio_pcm", return_value=None),
patch("invokeai.app.invocations.video_frame_extract_range.VideoOutput.build", return_value=base_output),
):
if should_raise:
diff --git a/tests/app/invocations/test_video_frame_extract_range_audio.py b/tests/app/invocations/test_video_frame_extract_range_audio.py
new file mode 100644
index 0000000000..fe754366da
--- /dev/null
+++ b/tests/app/invocations/test_video_frame_extract_range_audio.py
@@ -0,0 +1,183 @@
+"""Audio-preservation tests for ExtractVideoRangeInvocation.
+
+The node originally re-encoded video frames only, so trimming a clip silently stripped
+its soundtrack — feeding a trimmed clip into Concatenate Videos then produced correct
+silence for its span (the "extend video" workflow lost the source's audio). These tests
+pin the carried-through audio: slice alignment against the frame range, fps-override
+retiming, the frame-rate fallback chain, and silent-source passthrough.
+
+Real ffmpeg (the imageio-ffmpeg bundled binary) encodes and decodes throughout — tone
+clips are tiny (64x64) so the suite stays fast.
+"""
+
+import shutil
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import numpy as np
+
+from invokeai.app.invocations.fields import VideoField
+from invokeai.app.invocations.video_frame_extract_range import ExtractVideoRangeInvocation
+from invokeai.app.util.video_audio import extract_audio_pcm
+from invokeai.app.util.video_encoding import make_mp4_writer, write_stereo_wav
+
+RATE = 32000
+FPS = 16.0
+SIZE = 64
+
+
+class _Util:
+ def signal_progress(self, *args, **kwargs) -> None:
+ pass
+
+ def is_canceled(self) -> bool:
+ return False
+
+
+class _Ctx:
+ util = _Util()
+
+
+def _tone(freq: float, seconds: float, rate: int = RATE) -> np.ndarray:
+ t = np.arange(round(seconds * rate)) / rate
+ mono = (0.5 * np.sin(2 * np.pi * freq * t)).astype(np.float32)
+ return np.stack([mono, mono])
+
+
+def _dominant_freq(pcm: np.ndarray, rate: int) -> float:
+ spectrum = np.abs(np.fft.rfft(pcm[0]))
+ spectrum[0] = 0.0 # ignore DC
+ return float(np.fft.rfftfreq(pcm.shape[1], 1.0 / rate)[int(np.argmax(spectrum))])
+
+
+def _make_clip(dirpath: Path, name: str, n_frames: int, audio: np.ndarray | None, fps: float = FPS) -> Path:
+ path = dirpath / f"{name}.mp4"
+ audio_path = None
+ if audio is not None:
+ audio_path = dirpath / f"{name}.wav"
+ write_stereo_wav(audio_path, audio, RATE)
+ writer = make_mp4_writer(path, fps, audio_path=audio_path)
+ frame = np.full((SIZE, SIZE, 3), 128, dtype=np.uint8)
+ for _ in range(n_frames):
+ writer.append_data(frame)
+ writer.close()
+ return path
+
+
+def _invoke_and_capture(invocation: ExtractVideoRangeInvocation, clip_path: Path, out_dir: Path) -> Path:
+ """Runs invoke() with a mocked context and returns a copy of the saved MP4.
+
+ The node unlinks its temp files in a finally block, so ``videos.save`` copies the
+ file out before returning.
+ """
+ saved = out_dir / "saved.mp4"
+
+ def _save(source_path: Path, **kwargs) -> MagicMock:
+ shutil.copyfile(source_path, saved)
+ return MagicMock()
+
+ context = MagicMock()
+ context.videos.get_path.return_value = clip_path
+ context.util.is_canceled.return_value = False
+ context.videos.save.side_effect = _save
+ base_output = MagicMock(
+ video=VideoField(video_name="saved.mp4"), width=SIZE, height=SIZE, num_frames=1, fps=FPS, duration=1.0
+ )
+ with patch("invokeai.app.invocations.video_frame_extract_range.VideoOutput.build", return_value=base_output):
+ invocation.invoke(context)
+ assert saved.exists()
+ return saved
+
+
+class TestRangeAudio:
+ def test_trim_keeps_the_matching_audio_slice(self, tmp_path):
+ # 2 s clip: first second 440 Hz, second second 880 Hz. Trimming the back half
+ # must carry the 880 Hz second, not the 440 Hz one (slice offset correctness).
+ audio = np.concatenate([_tone(440.0, 1.0), _tone(880.0, 1.0)], axis=1)
+ clip = _make_clip(tmp_path, "twotone", n_frames=32, audio=audio)
+ node = ExtractVideoRangeInvocation(video=VideoField(video_name="twotone"), start_frame=16, end_frame=31)
+ saved = _invoke_and_capture(node, clip, tmp_path)
+
+ extracted = extract_audio_pcm(saved)
+ assert extracted is not None
+ pcm, rate = extracted
+ assert abs(pcm.shape[1] / rate - 1.0) < 0.05 # ~1 s of audio for 16 frames @ 16 fps
+ assert abs(_dominant_freq(pcm, rate) - 880.0) < 20.0
+
+ def test_full_range_round_trips_audio(self, tmp_path):
+ clip = _make_clip(tmp_path, "tone", n_frames=32, audio=_tone(440.0, 2.0))
+ node = ExtractVideoRangeInvocation(video=VideoField(video_name="tone"), start_frame=0, end_frame=-1)
+ saved = _invoke_and_capture(node, clip, tmp_path)
+
+ extracted = extract_audio_pcm(saved)
+ assert extracted is not None
+ pcm, rate = extracted
+ assert abs(pcm.shape[1] / rate - 2.0) < 0.05
+ assert abs(_dominant_freq(pcm, rate) - 440.0) < 20.0
+
+ def test_silent_source_stays_silent(self, tmp_path):
+ clip = _make_clip(tmp_path, "silent", n_frames=16, audio=None)
+ node = ExtractVideoRangeInvocation(video=VideoField(video_name="silent"), start_frame=0, end_frame=7)
+ saved = _invoke_and_capture(node, clip, tmp_path)
+ assert extract_audio_pcm(saved) is None
+
+ def test_fps_override_retimes_audio_with_video(self, tmp_path):
+ # Doubling the frame rate halves the duration; the audio must follow the video's
+ # retime (half the samples, pitch doubled) rather than play at original speed.
+ clip = _make_clip(tmp_path, "tone", n_frames=32, audio=_tone(440.0, 2.0))
+ node = ExtractVideoRangeInvocation(video=VideoField(video_name="tone"), start_frame=0, end_frame=-1, fps=32)
+ saved = _invoke_and_capture(node, clip, tmp_path)
+
+ extracted = extract_audio_pcm(saved)
+ assert extracted is not None
+ pcm, rate = extracted
+ assert abs(pcm.shape[1] / rate - 1.0) < 0.05
+ assert abs(_dominant_freq(pcm, rate) - 880.0) < 25.0
+
+
+class TestBuildAudioTrackFallbacks:
+ """The frame->sample mapping's frame-rate fallback chain, with synthetic extraction."""
+
+ def _build(self, node, source_fps, source_duration, pcm, start, end, n_frames, output_fps=FPS):
+ with patch(
+ "invokeai.app.invocations.video_frame_extract_range.extract_audio_pcm",
+ return_value=(pcm, RATE),
+ ):
+ return node._build_audio_track(
+ context=_Ctx(), # type: ignore[arg-type]
+ video_path=Path("unused.mp4"),
+ start=start,
+ end=end,
+ n_frames=n_frames,
+ source_fps=source_fps,
+ source_duration=source_duration,
+ output_fps=output_fps,
+ )
+
+ def test_unknown_fps_uses_probed_duration(self):
+ node = ExtractVideoRangeInvocation(video=VideoField(video_name="x"))
+ pcm = np.concatenate([_tone(440.0, 1.0), _tone(880.0, 1.0)], axis=1)
+ result = self._build(node, source_fps=None, source_duration=2.0, pcm=pcm, start=16, end=31, n_frames=32)
+ assert result is not None
+ out, rate = result
+ assert out.shape[1] == round(16 / FPS * RATE)
+ assert abs(_dominant_freq(out, rate) - 880.0) < 20.0
+
+ def test_unknown_fps_and_duration_falls_back_to_extracted_length(self):
+ node = ExtractVideoRangeInvocation(video=VideoField(video_name="x"))
+ pcm = np.concatenate([_tone(440.0, 1.0), _tone(880.0, 1.0)], axis=1)
+ result = self._build(node, source_fps=None, source_duration=None, pcm=pcm, start=16, end=31, n_frames=32)
+ assert result is not None
+ out, rate = result
+ assert abs(_dominant_freq(out, rate) - 880.0) < 20.0
+
+ def test_short_audio_track_is_padded_not_stretched(self):
+ # Audio covers only the first second of a 2 s video; trimming the back half must
+ # yield silence (aligned), not the front half's audio stretched over the range.
+ node = ExtractVideoRangeInvocation(video=VideoField(video_name="x"))
+ pcm = _tone(440.0, 1.0)
+ result = self._build(node, source_fps=FPS, source_duration=2.0, pcm=pcm, start=16, end=31, n_frames=32)
+ assert result is not None
+ out, _rate = result
+ assert out.shape[1] == round(16 / FPS * RATE)
+ assert float(np.abs(out).max()) < 1e-6