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): guard whole-range copy with movie duration
JPPhoto17d06e9d2117
diff --git a/invokeai/app/invocations/video_frame_extract_range.py b/invokeai/app/invocations/video_frame_extract_range.pyindex 545f2dd557..c04c23090e 100644--- a/invokeai/app/invocations/video_frame_extract_range.py+++ b/invokeai/app/invocations/video_frame_extract_range.py@@ -65,7 +65,7 @@ from invokeai.app.util.h264_splice import (probes_as,read_h264_layout,)-from invokeai.app.util.mp4_metadata import write_mp4_tags+from invokeai.app.util.mp4_metadata import read_mp4_movie_duration, write_mp4_tagsfrom invokeai.app.util.video_audio import extract_audio_pcm, mux_audio_into_video, resample_linearfrom invokeai.app.util.video_encoding import make_mp4_writer, write_stereo_wav, writer_sample_entryfrom invokeai.app.util.video_thumbnails import decoder_frame_count, iter_video_frames, probe_video@@ -231,14 +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. 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.+ # The whole clip is the source itself; copying it avoids another lossy generation. The+ # OpenCV probe fallback knows only the video duration, so also require the MP4 movie header+ # to fit the selected frames before bypassing the ordinary path that trims the soundtrack.+ whole_range = layout is not None and start == 0 and end == layout.sample_count - 1+ movie_duration = read_mp4_movie_duration(video_path) if whole_range else Noneif (- 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+ whole_range+ and movie_duration is not None+ and max(duration, movie_duration) <= n_frames / output_fps + 0.5 / output_fps + 0.01):return self._save_unchanged(context, video_path, width, height, n_frames, output_fps)diff --git a/invokeai/app/util/mp4_metadata.py b/invokeai/app/util/mp4_metadata.pyindex b5a8c9f43e..d836485073 100644--- a/invokeai/app/util/mp4_metadata.py+++ b/invokeai/app/util/mp4_metadata.py@@ -38,6 +38,8 @@ _MAX_KEY_NAME_BYTES = 1024# fragmented file, so a raw upload padded with tiny top-level boxes is given up on rather than# walked. Children of ``moov`` are bounded by ``moov``'s own size._MAX_TOP_LEVEL_BOXES = 1024+# Movie headers are near the start of ``moov``; bound this walk for uploaded files.+_MAX_MOVIE_HEADER_CHILDREN = 64# Same wall-clock bound as the audio mux: a stream copy of a 1 GB upload is disk-bound and# finishes in seconds, so this only stops a wedged child from holding the save forever.REMUX_TIMEOUT_SECONDS = 600@@ -92,6 +94,43 @@ def find_box(return None+def read_mp4_movie_duration(path: Path) -> Optional[float]:+ """Return the MP4 movie-header duration in seconds, or None if it is unavailable or invalid.++ Unlike OpenCV's video-only fallback probe, ``mvhd`` covers the movie timeline across tracks.+ The bounded box walks and fixed-size reads keep this safe for uploaded containers.+ """+ with open(path, "rb") as fh:+ fh.seek(0, 2)+ moov = find_box(fh, 0, fh.tell(), b"moov", max_boxes=_MAX_TOP_LEVEL_BOXES)+ if moov is None:+ return None+ mvhd = find_box(fh, *moov, b"mvhd", max_boxes=_MAX_MOVIE_HEADER_CHILDREN)+ if mvhd is None or mvhd[0] >= mvhd[1]:+ return None+ fh.seek(mvhd[0])+ version = fh.read(1)+ if not version or version[0] not in (0, 1):+ return None+ if version[0] == 0:+ timescale_offset, duration_offset, duration_size = 12, 16, 4+ else:+ timescale_offset, duration_offset, duration_size = 20, 24, 8+ if mvhd[0] + duration_offset + duration_size > mvhd[1]:+ return None+ fh.seek(mvhd[0] + timescale_offset)+ timescale_raw = fh.read(4)+ fh.seek(mvhd[0] + duration_offset)+ duration_raw = fh.read(duration_size)+ if len(timescale_raw) != 4 or len(duration_raw) != duration_size:+ return None+ timescale = struct.unpack(">I", timescale_raw)[0]+ duration = int.from_bytes(duration_raw, "big")+ if timescale == 0 or duration == (1 << (duration_size * 8)) - 1:+ return None+ return duration / timescale++def _meta_payload_start(fh: BinaryIO, start: int, end: int) -> int:"""``meta`` is a FullBox (4 bytes of version/flags) in ISO BMFF but a plain box inQuickTime files. Disambiguate the way ffmpeg does: if the bytes right after the headerdiff --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 9cbad042c1..0cb344d522 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@@ -245,17 +245,21 @@ def test_whole_clip_copy_keeps_a_soundtrack_that_ends_with_the_video(tmp_path, n@pytest.mark.parametrize(- "audio_args,audio_frames,copied",+ "audio_args,audio_frames,copied,video_only_probe",[- ([], 80, "Stream-copied frames 0-39"),- (["-itsoffset", "1.0"], 39, "Stream-copied frames 0-39"),- ([], 40, "the whole of the source, copied"),+ ([], 80, "Stream-copied frames 0-39", False),+ (["-itsoffset", "1.0"], 39, "Stream-copied frames 0-39", False),+ ([], 40, "the whole of the source, copied", False),+ ([], 80, "Stream-copied frames 0-39", True),],- ids=["longer-audio", "delayed-audio", "second-audio-track"],+ ids=["longer-audio", "delayed-audio", "second-audio-track", "longer-audio-opencv-probe"],)-def test_whole_clip_copy_carries_only_the_soundtrack_a_trim_would(tmp_path, audio_args, audio_frames, copied):+def test_whole_clip_copy_carries_only_the_soundtrack_a_trim_would(+ tmp_path, monkeypatch, audio_args, audio_frames, copied, video_only_probe+):"""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 come as several tracks. The OpenCV probe fallback knows only the video duration, so the+ MP4 movie duration must also guard a whole-file copy that would keep audio past its 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)@@ -275,6 +279,13 @@ def test_whole_clip_copy_carries_only_the_soundtrack_a_trim_would(tmp_path, audicheck=True,)+ if video_only_probe:+ # video_decode_worker._probe() returns frame_count / fps when it falls back to OpenCV.+ monkeypatch.setattr(+ "invokeai.app.invocations.video_frame_extract_range.probe_video",+ lambda _path: (SIZE, SIZE, 40 / FPS, FPS),+ )+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