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
fix(video): keep whole-range copies to the video's duration
Lincoln Stein4b52ab11ab70
diff --git a/invokeai/app/invocations/video_frame_extract_range.py b/invokeai/app/invocations/video_frame_extract_range.pyindex c14a8189ee..545f2dd557 100644--- a/invokeai/app/invocations/video_frame_extract_range.py+++ b/invokeai/app/invocations/video_frame_extract_range.py@@ -231,8 +231,15 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):layout = read_h264_layout(video_path)if layout is not None and layout.sample_count != exact_frame_count:layout = None- # The whole clip is the source itself; copying it avoids another lossy generation.- if layout is not None and start == 0 and end == layout.sample_count - 1:+ # The whole clip is the source itself; copying it avoids another lossy generation. Unless+ # some stream plays past the last frame — audio that outlasts the video or starts late+ # (the probed duration is the longest stream's, end trims applied) — which a trim must cut.+ if (+ layout is not None+ and start == 0+ and end == layout.sample_count - 1+ and duration <= n_frames / output_fps + 0.5 / output_fps + 0.01+ ):return self._save_unchanged(context, video_path, width, height, n_frames, output_fps)context.util.signal_progress(f"Transcoding frames {start}-{end} of {n_frames} @ {output_fps:.2f} fps")@@ -452,7 +459,8 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):copy_path = Path(work) / "source.mp4"# A stream-copy remux that drops the source's keyed metadata: save() writes this# node's record, and if that rewrite fails the source's must not be read back as it.- write_mp4_tags(video_path, copy_path, {}, context.util.is_canceled)+ # Only the first soundtrack: the ordinary path carries no other.+ write_mp4_tags(video_path, copy_path, {}, context.util.is_canceled, first_audio_only=True)# A cancellation that arrived during an uninterruptible stage must not be saved.if context.util.is_canceled():raise CanceledExceptiondiff --git a/invokeai/app/util/mp4_metadata.py b/invokeai/app/util/mp4_metadata.pyindex 1074ff6b75..b5a8c9f43e 100644--- a/invokeai/app/util/mp4_metadata.py+++ b/invokeai/app/util/mp4_metadata.py@@ -215,11 +215,17 @@ def _escape_ffmetadata(value: str) -> str:def write_mp4_tags(- src: Path, dst: Path, tags: Mapping[str, str], is_canceled: Optional[Callable[[], bool]] = None+ src: Path,+ dst: Path,+ tags: Mapping[str, str],+ is_canceled: Optional[Callable[[], bool]] = None,+ *,+ first_audio_only: bool = False,) -> None:- """Write ``dst`` = ``src``'s first video stream and every audio stream, stream-copied, with- ``tags`` as the file's keyed metadata (replacing any global tags ``src`` had). An empty- mapping therefore strips ``src``'s global tags.+ """Write ``dst`` = ``src``'s first video stream and every audio stream (or only the first,+ with ``first_audio_only``), stream-copied, with ``tags`` as the file's keyed metadata+ (replacing any global tags ``src`` had). An empty mapping therefore strips ``src``'s+ global tags.Subtitle, data and further video tracks are not carried: InvokeAI stores only what itserves, and the ingest path already narrows uploads the same way. ``dst`` is written with@@ -251,7 +257,7 @@ def write_mp4_tags("-map","0:v:0","-map",- "0:a?",+ "0:a:0?" if first_audio_only else "0:a?","-map_metadata","1","-c",diff --git a/tests/app/invocations/test_video_frame_extract_range_audio_splice.py b/tests/app/invocations/test_video_frame_extract_range_audio_splice.pyindex d33d649ab8..9cbad042c1 100644--- a/tests/app/invocations/test_video_frame_extract_range_audio_splice.py+++ b/tests/app/invocations/test_video_frame_extract_range_audio_splice.py@@ -12,10 +12,12 @@ Real ffmpeg (the imageio-ffmpeg bundled binary) encodes and decodes throughout."""import struct+import subprocessfrom pathlib import Pathfrom unittest.mock import MagicMock, patchimport imageio.v2 as iio2+import imageio_ffmpegimport numpy as npimport pytest@@ -220,3 +222,65 @@ def test_trim_splices_when_frames_hold_fractional_samples(tmp_path):want = decoded[0][:, round(7 * rate / fps) : round(101 * rate / fps)]interior = slice(LEAD_IN_LIMIT, want.shape[1] - TAIL_LIMIT)assert np.array_equal(got[0][:, interior], want[:, interior])++[email protected]("n_frames,fps,rate", [(40, 16.0, 32000), (97, 24.0, 32000), (81, 16.0, 16000)])+def test_whole_clip_copy_keeps_a_soundtrack_that_ends_with_the_video(tmp_path, n_frames, fps, rate):+ """The app's own soundtracks decode up to a packet past their end (the decoder does not+ apply the end trim); that must not cost them the copy. 97 frames at 24 fps and 32 kHz is+ a MiniMax H3 clip, 81 at 16 fps and 16 kHz a 16 kHz Wan-length one."""+ n = round(n_frames / fps * rate)+ wav, source = tmp_path / "source.wav", tmp_path / "source.mp4"+ write_stereo_wav(wav, np.stack([np.sin(np.arange(n) / 7.0)] * 2).astype(np.float32) * 0.4, rate)+ writer = make_mp4_writer(source, fps, audio_path=wav)+ for i in range(n_frames):+ writer.append_data(np.full((SIZE, SIZE, 3), i, dtype=np.uint8))+ writer.close()++ saved, context = _trim(tmp_path, source, 0, -1)+ assert "the whole of the source, copied" in _logged(context)+ want, got = extract_audio_pcm(source), extract_audio_pcm(saved)+ assert want is not None and got is not None+ assert np.array_equal(got[0], want[0])+++ "audio_args,audio_frames,copied",+ [+ ([], 80, "Stream-copied frames 0-39"),+ (["-itsoffset", "1.0"], 39, "Stream-copied frames 0-39"),+ ([], 40, "the whole of the source, copied"),+ ],+ ids=["longer-audio", "delayed-audio", "second-audio-track"],+)+def test_whole_clip_copy_carries_only_the_soundtrack_a_trim_would(tmp_path, audio_args, audio_frames, copied):+ """An uploaded H.264 MP4 is stored as-is, so its audio can outlast its video, start late,+ or come as several tracks. Copying the file whole would keep audio past the last frame+ (or every track) where any other range is cut to the frames it keeps (and the first track)."""+ video = tmp_path / "video.mp4"+ writer = make_mp4_writer(video, FPS)+ rng = np.random.default_rng(0)+ for _ in range(40):+ writer.append_data(rng.integers(0, 256, (SIZE, SIZE, 3), dtype=np.uint8))+ writer.close()+ audio = tmp_path / "audio.wav"+ write_stereo_wav(audio, _signal("tone", audio_frames, 0), RATE)+ extra_track = copied.startswith("the whole")+ inputs = ["-i", str(video), *audio_args, "-i", str(audio)] + (["-i", str(audio)] if extra_track else [])+ maps = ["-map", "0:v", "-map", "1:a"] + (["-map", "2:a"] if extra_track else [])+ source = tmp_path / "source.mp4"+ subprocess.run(+ [imageio_ffmpeg.get_ffmpeg_exe(), "-y", "-loglevel", "error", *inputs, *maps]+ + ["-c:v", "copy", "-c:a", "aac", "-aac_pns", "0", str(source)],+ check=True,+ )++ saved, context = _trim(tmp_path, source, 0, -1)+ # Nothing plays past the last frame (the probe reports to the hundredth of a second).+ assert _movie_duration(saved) <= 40 / FPS + 0.5 / FPS+ banner = subprocess.run(+ [imageio_ffmpeg.get_ffmpeg_exe(), "-hide_banner", "-i", str(saved)], capture_output=True, text=True+ ).stderr+ assert banner.count("Audio:") == 1+ # The video is still copied, not re-encoded.+ assert copied in _logged(context)diff --git a/tests/app/util/test_h264_splice.py b/tests/app/util/test_h264_splice.pyindex 3a4aa1daae..1ad8ae2575 100644--- a/tests/app/util/test_h264_splice.py+++ b/tests/app/util/test_h264_splice.py@@ -118,7 +118,9 @@ def _patch_box(data: bytearray, box: bytes, offset: int, value: bytes) -> None:data[at + 4 + offset : at + 4 + offset + len(value)] = value[email protected](sys.platform == "win32", reason="bounds the child's address space with RLIMIT_AS")+ sys.platform != "linux", reason="bounds the child's address space with RLIMIT_AS, which only Linux enforces"+)@pytest.mark.parametrize("uniform_size", [0, 1], ids=["size-table", "uniform-size"])def test_oversized_sample_count_is_refused_without_allocating(tmp_path: Path, uniform_size: int) -> None:"""Uploads that are already H.264 MP4s are stored as-is, so the sample tables are the