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(videos): harden ingest after adversarial review

Lincoln Steinf117706c6935
diff --git a/invokeai/app/api/routers/videos.py b/invokeai/app/api/routers/videos.py
index 7b729de951..446a4aa300 100644
--- a/invokeai/app/api/routers/videos.py
+++ b/invokeai/app/api/routers/videos.py
@@ -276,7 +276,11 @@ async def upload_video(
container_probe = await run_in_threadpool(probe_media_streams, tmp_path)
except VideoIngestError as e:
raise HTTPException(status_code=415, detail=str(e))
- needs_ingest = container_probe.video_codec != "h264"
+ # Both codecs must already be browser-safe to skip ingest: an mp4-family
+ # container can legally carry h264 video with AMR/opus/mp3/ac3 audio (e.g.
+ # older Android .3gp camera files), which browsers render as silent video.
+ # The remux branch stream-copies the h264 and normalizes only the audio.
+ needs_ingest = container_probe.video_codec != "h264" or container_probe.audio_codec not in (None, "aac")
if needs_ingest:
converted = tempfile.NamedTemporaryFile(prefix="invokeai_ingest_", suffix=".mp4", delete=False)
diff --git a/invokeai/app/services/gallery/gallery_default.py b/invokeai/app/services/gallery/gallery_default.py
index 19837dba29..c73489a201 100644
--- a/invokeai/app/services/gallery/gallery_default.py
+++ b/invokeai/app/services/gallery/gallery_default.py
@@ -284,6 +284,9 @@ class SqliteGalleryService(GalleryServiceABC):
SUM(CASE WHEN kind = 'image' AND category = 'general' THEN 1 ELSE 0 END) AS image_count,
SUM(CASE WHEN kind = 'image' AND category != 'general' THEN 1 ELSE 0 END) AS asset_count,
SUM(CASE WHEN kind = 'video' THEN 1 ELSE 0 END) AS video_count,
+ -- Same not-'general' predicate as the image asset_count above (rather than the
+ -- listing services' explicit asset-category allowlist), so image and video
+ -- counts stay consistent within this query.
SUM(CASE WHEN kind = 'video' AND category != 'general' THEN 1 ELSE 0 END) AS asset_video_count
FROM ({union})
GROUP BY DATE(created_at)
diff --git a/invokeai/app/util/video_ingest.py b/invokeai/app/util/video_ingest.py
index f7aaa9a67b..29b51c4c35 100644
--- a/invokeai/app/util/video_ingest.py
+++ b/invokeai/app/util/video_ingest.py
@@ -144,7 +144,12 @@ def ingest_media_to_mp4(src: Path, dst: Path, *, max_output_bytes: int) -> Inges
probe = probe_media_streams(src)
action = plan_ingest(probe)
- common_output = ["-movflags", "+faststart", "-f", "mp4", str(dst)]
+ # `-fs` bounds the output *during* the encode, so a long audio wrap or a
+ # high-entropy transcode cannot grow the temp file past the upload cap before the
+ # post-hoc check runs. ffmpeg stops once the size is exceeded (the final file lands
+ # at or slightly above the cap) and exits 0, so the >= check below is what turns a
+ # truncated-at-cap file into an error.
+ common_output = ["-fs", str(max_output_bytes), "-movflags", "+faststart", "-f", "mp4", str(dst)]
if action == "remux":
args = [
"-i",
@@ -224,11 +229,13 @@ def ingest_media_to_mp4(src: Path, dst: Path, *, max_output_bytes: int) -> Inges
raise VideoIngestError("Timed out converting the uploaded file to MP4") from e
if proc.returncode != 0:
stderr = proc.stderr.decode("utf-8", errors="replace").strip()
+ # The message reaches API clients; server temp paths are not theirs to see.
+ stderr = stderr.replace(str(src), src.name).replace(str(dst), dst.name)
raise VideoIngestError(f"Could not convert the uploaded file to MP4: {stderr[-500:]}")
try:
output_bytes = dst.stat().st_size
except OSError as e:
raise VideoIngestError("Could not convert the uploaded file to MP4") from e
- if output_bytes > max_output_bytes:
+ if output_bytes >= max_output_bytes:
raise VideoIngestError("The converted video exceeds the maximum upload size")
return action
diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
index 6cef6f8088..a710c7de54 100644
--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
@@ -7,7 +7,7 @@ import { useQueryClient } from '@tanstack/react-query';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
-import { useCallback, useMemo } from 'react';
+import { useCallback, useEffect, useMemo, useRef } from 'react';
/**
* Production binding of Video's UI port: maps the video widget instance out of
@@ -32,13 +32,21 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>
const showPromptSyntaxHighlighting = useWorkbenchPreferenceSelector(
(preferences) => preferences.showPromptSyntaxHighlighting
);
- // Uploads from the video panel land on the gallery's currently selected board,
- // matching where the user is looking (and where generation results go).
+ // Uploads from the video panel land on the gallery's currently selected board. This
+ // deliberately reads the RAW selectedBoardId — the same value the queue snapshots as
+ // galleryBoardId for generation results — so uploads and generations land on the same
+ // board, rather than replicating the gallery view's display-side fallbacks.
const uploadBoardId = useActiveProjectSelector((activeProject) => {
const selectedBoardId = getProjectWidgetValues(activeProject, 'gallery').selectedBoardId;
return typeof selectedBoardId === 'string' ? selectedBoardId : 'none';
});
+ // Ref-backed so the port's actions keep their stable-for-the-project identity: a
+ // board click must not re-render every useVideoUiActions consumer in the panel.
+ const uploadBoardIdRef = useRef(uploadBoardId);
+ useEffect(() => {
+ uploadBoardIdRef.current = uploadBoardId;
+ }, [uploadBoardId]);
const commands = useWorkbenchCommands();
const queryClient = useQueryClient();
// The port's callbacks are keyed to the project, not to its contents: rebuilding
@@ -54,7 +62,7 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>
[commands]
);
const touchGalleryImages = useCallback(() => void invalidateGallery(queryClient), [queryClient]);
- const getUploadBoardId = useCallback(() => uploadBoardId, [uploadBoardId]);
+ const getUploadBoardId = useCallback(() => uploadBoardIdRef.current, []);
const adapter = useMemo<VideoUiAdapter>(
() => ({
...project,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
index d8a45d0428..daf5d530c1 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
@@ -51,7 +51,7 @@ export const GalleryBoardRow = ({
});
const counts = getBoardCounts(board);
- const mediaCount = counts.imageCount + counts.videoCount - counts.assetVideoCount;
+ const mediaCount = Math.max(0, counts.imageCount + counts.videoCount - counts.assetVideoCount);
const countsBreakdown = t('widgets.gallery.boardCountsBreakdown', {
assets: counts.assetCount + counts.assetVideoCount,
media: mediaCount,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts
index c238d4610a..9dedc92fdb 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts
@@ -10,8 +10,10 @@ export const getGalleryCountForView = (board: GalleryBoard, galleryView: Gallery
const counts = getBoardCounts(board);
// Videos split across the views the same way images do: uploaded ('user') videos are
- // assets, generated ('general') videos are media.
+ // assets, generated ('general') videos are media. Clamped: the uncategorized
+ // pseudo-board's counts come from parallel requests, so a delete landing between
+ // them can transiently report more asset videos than videos.
return galleryView === 'assets'
? counts.assetCount + counts.assetVideoCount
- : counts.imageCount + counts.videoCount - counts.assetVideoCount;
+ : Math.max(0, counts.imageCount + counts.videoCount - counts.assetVideoCount);
};
diff --git a/tests/app/routers/test_videos_multiuser.py b/tests/app/routers/test_videos_multiuser.py
index 34c20aa5d9..f2411e9987 100644
--- a/tests/app/routers/test_videos_multiuser.py
+++ b/tests/app/routers/test_videos_multiuser.py
@@ -742,6 +742,39 @@ def test_upload_audio_file_is_wrapped_and_marked(
assert (create_kwargs["width"], create_kwargs["height"]) == (640, 360)
+def test_upload_mp4_with_non_aac_audio_gets_audio_normalized(
+ client: TestClient, mock_invoker: Invoker, user1_token: str, tmp_path: Path
+):
+ """An MP4 whose video is already h264 but whose audio track is not browser-safe
+ (mp3 here; AMR in older Android .3gp files) must NOT take the byte-identical fast
+ path — the audio is re-encoded to AAC while the h264 stream is copied."""
+ from invokeai.app.util.video_ingest import probe_media_streams
+
+ src = _make_fixture_media(
+ tmp_path / "clip.mp4",
+ *("-f", "lavfi", "-i", "testsrc2=s=64x48:r=8:d=1"),
+ *("-f", "lavfi", "-i", "sine=frequency=440:d=1"),
+ *("-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "libmp3lame", "-shortest"),
+ )
+ stored_audio_codecs: list[str | None] = []
+
+ def create(**kwargs: Any) -> VideoDTO:
+ stored_audio_codecs.append(probe_media_streams(Path(kwargs["source_path"])).audio_codec)
+ return _uploaded_video_dto()
+
+ mock_invoker.services.videos.create.side_effect = create
+
+ response = client.post(
+ "/api/v1/videos/upload",
+ params={"video_category": "user", "is_intermediate": False},
+ files={"file": ("clip.mp4", src.read_bytes(), "video/mp4")},
+ headers={"Authorization": f"Bearer {user1_token}"},
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert stored_audio_codecs == ["aac"]
+
+
def test_upload_rejects_unrecognized_file_kind(client: TestClient, mock_invoker: Invoker, user1_token: str):
mock_invoker.services.videos.create.side_effect = AssertionError("unrecognized upload reached creation")