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(videos): normalize uploads to MP4 (remux/transcode/audio-wrap); land uploads in Assets on the selected board

Lincoln Stein8fc0366b241b
diff --git a/docs/src/content/docs/features/gallery.mdx b/docs/src/content/docs/features/gallery.mdx
index c3c0fde13c..376f35d9d9 100644
--- a/docs/src/content/docs/features/gallery.mdx
+++ b/docs/src/content/docs/features/gallery.mdx
@@ -144,9 +144,13 @@ Additionally, each image has a context menu (right-click or Ctrl+click) with pow
Videos generated by InvokeAI (currently from the Wan 2.2 model family) appear alongside images in the same gallery view. Each video item displays a first-frame still as its thumbnail with a play badge in the corner; selecting it opens the video in the viewer where you can play it back inline.
-### Uploading Videos
+### Uploading Videos and Audio
-You can upload existing videos to a board via the standard drop-or-upload affordance. The upload pipeline accepts **MP4 files encoded with H.264/AVC only** so uploaded videos can play in supported browsers. Other containers (`.mov`, `.webm`, `.mkv`) and codecs such as HEVC/H.265 are not transcoded on upload and are rejected at the API boundary. Re-encode them before uploading, for example with `ffmpeg -i input.mov -c:v libx264 output.mp4`.
+You can upload existing videos to a board via the standard drop-or-upload affordance. Everything is stored and served as **H.264/AAC MP4** so it plays in supported browsers, but the upload pipeline now converts on ingest rather than rejecting:
+
+- **H.264 in another container** (an iPhone `.mov` recorded with "Most Compatible", `.m4v`, most screen recordings) is losslessly remuxed — near-instant, no quality change.
+- **Other codecs** (iPhone "High Efficiency" HEVC, ProRes, VP9, and anything else FFmpeg can decode) are transcoded to H.264. Expect the upload to take roughly the clip's duration on a typical CPU. 10-bit HDR footage is converted to 8-bit without tonemapping, so HDR clips will look flatter than the original — pre-convert those yourself if color fidelity matters.
+- **Audio files** (`.mp3`, `.m4a`, `.wav`, `.flac`, `.ogg`, and friends) are wrapped into a video whose frames render the waveform. The clip behaves like any other gallery video — it can be trimmed, played, and used wherever audio-only conditioning accepts a video — without audio being a separate media type.
The **Concatenate Videos** and **Extract Video Range** nodes encode video frames only; audio tracks are not preserved. Concatenation requires matching source frame rates unless an explicit output FPS is selected, which retimes the source frames.
diff --git a/invokeai/app/api/routers/videos.py b/invokeai/app/api/routers/videos.py
index 5d0cf6adfa..7b729de951 100644
--- a/invokeai/app/api/routers/videos.py
+++ b/invokeai/app/api/routers/videos.py
@@ -1,3 +1,4 @@
+import json
import os
import re
import tempfile
@@ -48,6 +49,7 @@ from invokeai.app.services.videos.videos_common import (
VideoDTO,
VideoUrlsDTO,
)
+from invokeai.app.util.video_ingest import VideoIngestError, ingest_media_to_mp4, probe_media_streams
from invokeai.app.util.video_thumbnails import VideoDecodeTimeoutError, extract_video_frame, probe_video_with_codec
videos_router = APIRouter(prefix="/v1/videos", tags=["videos"])
@@ -55,12 +57,18 @@ videos_router = APIRouter(prefix="/v1/videos", tags=["videos"])
# Videos are immutable; set a high max-age (1 year)
VIDEO_MAX_AGE = 31536000
-# MP4 only — the names service emits `{uuid}.mp4` unconditionally and we don't transcode on
-# upload. Accepting .mov/.webm/.mkv here previously caused those containers to be stored
-# under a .mp4 name and served with the .mp4 MIME type, which silently broke playback in
-# browsers when the container did not match.
-ACCEPTED_VIDEO_MIME_PREFIXES = ("video/mp4",)
-ACCEPTED_VIDEO_EXTENSIONS = (".mp4",)
+# The names service emits `{uuid}.mp4` unconditionally and files are served as video/mp4,
+# so everything *stored* must genuinely be H.264 MP4 — storing foreign containers under a
+# .mp4 name silently broke browser playback, which is why uploads were historically
+# restricted to already-compliant files. Uploads are now normalized at ingest instead
+# (see invokeai.app.util.video_ingest): H.264 in a foreign container is losslessly
+# remuxed, other codecs (iPhone HEVC, ProRes, VP9) are transcoded, and audio-only files
+# are wrapped into waveform videos so audio clips flow through the video pipeline
+# (gallery, trim, audio-only reference conditioning) without a first-class audio type.
+ACCEPTED_VIDEO_MIME_PREFIXES = ("video/",)
+ACCEPTED_VIDEO_EXTENSIONS = (".mp4", ".mov", ".m4v", ".webm", ".mkv", ".avi", ".mpg", ".mpeg", ".3gp")
+ACCEPTED_AUDIO_MIME_PREFIXES = ("audio/",)
+ACCEPTED_AUDIO_EXTENSIONS = (".mp3", ".m4a", ".aac", ".wav", ".flac", ".ogg", ".oga", ".opus", ".aiff", ".aif")
# Per-chunk size for HTTP Range responses (1 MB)
RANGE_CHUNK_SIZE = 1024 * 1024
@@ -113,12 +121,32 @@ def _assert_video_direct_owner(video_name: str, current_user: CurrentUserOrDefau
raise HTTPException(status_code=403, detail="Not authorized to move this video")
-def _is_accepted_video_upload(file: UploadFile) -> bool:
- if file.content_type and file.content_type.startswith(ACCEPTED_VIDEO_MIME_PREFIXES):
- return True
+def _classify_upload(file: UploadFile) -> Optional[str]:
+ """Returns 'video' or 'audio' for an accepted upload, None for a rejected one.
+
+ The classification is advisory (it picks the 415 message and nothing else): the
+ ingest path probes actual stream content, so a mislabeled file still converts
+ correctly or fails with a clear error.
+ """
+ if file.content_type:
+ if file.content_type.startswith(ACCEPTED_VIDEO_MIME_PREFIXES):
+ return "video"
+ if file.content_type.startswith(ACCEPTED_AUDIO_MIME_PREFIXES):
+ return "audio"
if file.filename:
- return file.filename.lower().endswith(ACCEPTED_VIDEO_EXTENSIONS)
- return False
+ name = file.filename.lower()
+ if name.endswith(ACCEPTED_VIDEO_EXTENSIONS):
+ return "video"
+ if name.endswith(ACCEPTED_AUDIO_EXTENSIONS):
+ return "audio"
+ return None
+
+
+def _with_media_origin(metadata: Optional[str], origin: str) -> str:
+ """Merges a `media_origin` marker into the upload's (already-validated) metadata JSON."""
+ parsed = json.loads(metadata) if metadata else {}
+ parsed.setdefault("media_origin", origin)
+ return json.dumps(parsed)
def _is_mp4_file(path: Path) -> bool:
@@ -206,8 +234,9 @@ async def upload_video(
# Check board access for uploads to a specific board.
await run_in_threadpool(_assert_board_write_access, board_id, current_user)
- if not _is_accepted_video_upload(file):
- raise HTTPException(status_code=415, detail="Not a supported video file")
+ upload_kind = _classify_upload(file)
+ if upload_kind is None:
+ raise HTTPException(status_code=415, detail="Not a supported video or audio file")
# Stream the upload to a tmp file so we can probe and then hand its path to the service.
# Reading the full body into memory first risked exhausting RAM on multi-GB uploads;
@@ -236,8 +265,37 @@ async def upload_video(
# window to the copy loop itself.
await file.close()
- if not await run_in_threadpool(_is_mp4_file, tmp_path):
- raise HTTPException(status_code=415, detail="Not an MP4 video file")
+ # Already-compliant H.264 MP4s pass through byte-identical (the historical path);
+ # everything else — foreign containers, foreign codecs, audio-only files — is
+ # normalized by the ingest converter. The conversion runs inside this upload's
+ # concurrency slot: a long HEVC transcode holds one of MAX_CONCURRENT_VIDEO_UPLOADS
+ # slots for its duration, which is the intended backpressure.
+ needs_ingest = True
+ if upload_kind == "video" and await run_in_threadpool(_is_mp4_file, tmp_path):
+ try:
+ 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"
+
+ if needs_ingest:
+ converted = tempfile.NamedTemporaryFile(prefix="invokeai_ingest_", suffix=".mp4", delete=False)
+ converted_path = Path(converted.name)
+ converted.close()
+ try:
+ ingest_action = await run_in_threadpool(
+ ingest_media_to_mp4, tmp_path, converted_path, max_output_bytes=MAX_UPLOAD_SIZE
+ )
+ await run_in_threadpool(os.replace, converted_path, tmp_path)
+ except VideoIngestError as e:
+ ApiDependencies.invoker.services.logger.info(f"Video upload ingest failed: {e}")
+ raise HTTPException(status_code=415, detail=str(e))
+ finally:
+ converted_path.unlink(missing_ok=True)
+ if ingest_action == "audio_wrap":
+ # Mark wrapped audio uploads so clients can treat them as audio clips
+ # (e.g. defaulting an audio-only reference conditioning mode).
+ metadata = _with_media_origin(metadata, "audio_upload")
try:
(width, height, duration, fps), first_frame = await run_in_threadpool(_probe_decodable_video, tmp_path)
diff --git a/invokeai/app/services/board_video_records/board_video_records_base.py b/invokeai/app/services/board_video_records/board_video_records_base.py
index 244b781492..f7e9fcdee7 100644
--- a/invokeai/app/services/board_video_records/board_video_records_base.py
+++ b/invokeai/app/services/board_video_records/board_video_records_base.py
@@ -41,3 +41,8 @@ class BoardVideoRecordStorageBase(ABC):
def get_video_count_for_board(self, board_id: str) -> int:
"""Gets the number of videos for a board."""
pass
+
+ @abstractmethod
+ def get_asset_video_count_for_board(self, board_id: str) -> int:
+ """Gets the number of asset-category (non-'general') videos for a board."""
+ pass
diff --git a/invokeai/app/services/board_video_records/board_video_records_sqlite.py b/invokeai/app/services/board_video_records/board_video_records_sqlite.py
index 6b780f8eaa..449796ad42 100644
--- a/invokeai/app/services/board_video_records/board_video_records_sqlite.py
+++ b/invokeai/app/services/board_video_records/board_video_records_sqlite.py
@@ -95,3 +95,19 @@ class SqliteBoardVideoRecordStorage(BoardVideoRecordStorageBase):
)
count = cast(int, cursor.fetchone()[0])
return count
+
+ def get_asset_video_count_for_board(self, board_id: str) -> int:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ SELECT COUNT(*)
+ FROM board_videos
+ INNER JOIN videos ON board_videos.video_name = videos.video_name
+ WHERE videos.is_intermediate = FALSE
+ AND videos.video_category != 'general'
+ AND board_videos.board_id = ?;
+ """,
+ (board_id,),
+ )
+ count = cast(int, cursor.fetchone()[0])
+ return count
diff --git a/invokeai/app/services/boards/boards_common.py b/invokeai/app/services/boards/boards_common.py
index 87d8f322a9..2e1babc6a2 100644
--- a/invokeai/app/services/boards/boards_common.py
+++ b/invokeai/app/services/boards/boards_common.py
@@ -20,6 +20,12 @@ class BoardDTO(BoardRecord):
"""The number of videos in the board."""
asset_count: int = Field(description="The number of assets in the board.")
"""The number of assets in the board."""
+ asset_video_count: int = Field(
+ default=0, description="The number of asset-category (non-'general') videos in the board."
+ )
+ """Uploaded videos are assets ('user' category) while generated videos are 'general', mirroring
+ images. `video_count` stays the total so "delete board with N videos" copy remains honest; this
+ field lets clients split the total across the Media/Assets views."""
owner_username: Optional[str] = Field(default=None, description="The username of the board owner (for admin view).")
"""The username of the board owner (for admin view)."""
project_id: Optional[str] = Field(default=None, description="The id of the project that owns this board, if any.")
@@ -39,6 +45,7 @@ def board_record_to_dto(
owner_username: Optional[str] = None,
cover_video_name: Optional[str] = None,
video_count: int = 0,
+ asset_video_count: int = 0,
project_id: Optional[str] = None,
) -> BoardDTO:
"""Converts a board record to a board DTO."""
@@ -49,6 +56,7 @@ def board_record_to_dto(
image_count=image_count,
video_count=video_count,
asset_count=asset_count,
+ asset_video_count=asset_video_count,
owner_username=owner_username,
project_id=project_id,
)
diff --git a/invokeai/app/services/boards/boards_default.py b/invokeai/app/services/boards/boards_default.py
index e7bfe4b887..d8b6a18b69 100644
--- a/invokeai/app/services/boards/boards_default.py
+++ b/invokeai/app/services/boards/boards_default.py
@@ -39,12 +39,13 @@ class BoardService(BoardServiceABC):
return None, cover_video.video_name
return cover_image.image_name, None
- def _get_counts(self, board_id: str) -> tuple[int, int, int]:
- """Return ``(image_count, video_count, asset_count)`` for a board."""
+ def _get_counts(self, board_id: str) -> tuple[int, int, int, int]:
+ """Return ``(image_count, video_count, asset_count, asset_video_count)`` for a board."""
image_count = self.__invoker.services.board_image_records.get_image_count_for_board(board_id)
asset_count = self.__invoker.services.board_image_records.get_asset_count_for_board(board_id)
video_count = self.__invoker.services.board_video_records.get_video_count_for_board(board_id)
- return image_count, video_count, asset_count
+ asset_video_count = self.__invoker.services.board_video_records.get_asset_video_count_for_board(board_id)
+ return image_count, video_count, asset_count, asset_video_count
def create(
self,
@@ -60,7 +61,7 @@ class BoardService(BoardServiceABC):
# takes — on the most-travelled read in the API.
board_record, project_id = self.__invoker.services.board_records.get_with_project_id(board_id)
cover_image_name, cover_video_name = self._resolve_cover(board_record.board_id)
- image_count, video_count, asset_count = self._get_counts(board_id)
+ image_count, video_count, asset_count, asset_video_count = self._get_counts(board_id)
return board_record_to_dto(
board_record,
cover_image_name,
@@ -68,6 +69,7 @@ class BoardService(BoardServiceABC):
asset_count,
cover_video_name=cover_video_name,
video_count=video_count,
+ asset_video_count=asset_video_count,
project_id=project_id,
)
@@ -150,6 +152,7 @@ class BoardService(BoardServiceABC):
owner_username,
cover_video_name=summary.cover_video_name,
video_count=summary.video_count,
+ asset_video_count=summary.asset_video_count,
project_id=project_ids.get(r.board_id),
)
)
diff --git a/invokeai/app/services/gallery/gallery_common.py b/invokeai/app/services/gallery/gallery_common.py
index 00a3befdb8..473c497953 100644
--- a/invokeai/app/services/gallery/gallery_common.py
+++ b/invokeai/app/services/gallery/gallery_common.py
@@ -81,3 +81,4 @@ class BoardMediaSummary:
image_count: int = 0
video_count: int = 0
asset_count: int = 0
+ asset_video_count: int = 0
diff --git a/invokeai/app/services/gallery/gallery_default.py b/invokeai/app/services/gallery/gallery_default.py
index 6f7c475587..19837dba29 100644
--- a/invokeai/app/services/gallery/gallery_default.py
+++ b/invokeai/app/services/gallery/gallery_default.py
@@ -283,7 +283,8 @@ class SqliteGalleryService(GalleryServiceABC):
DATE(created_at) AS date,
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
+ SUM(CASE WHEN kind = 'video' THEN 1 ELSE 0 END) AS video_count,
+ SUM(CASE WHEN kind = 'video' AND category != 'general' THEN 1 ELSE 0 END) AS asset_video_count
FROM ({union})
GROUP BY DATE(created_at)
ORDER BY date DESC;
@@ -328,6 +329,7 @@ class SqliteGalleryService(GalleryServiceABC):
image_count=row["image_count"],
asset_count=row["asset_count"],
video_count=row["video_count"],
+ asset_video_count=row["asset_video_count"],
cover_image_name=cover_name if cover_kind == "image" else None,
cover_video_name=cover_name if cover_kind == "video" else None,
)
@@ -346,6 +348,7 @@ 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,
+ SUM(CASE WHEN kind = 'video' AND category != 'general' THEN 1 ELSE 0 END) AS asset_video_count,
MAX(CASE WHEN rank = 1 AND kind = 'image' THEN name END) AS cover_image_name,
MAX(CASE WHEN rank = 1 AND kind = 'video' THEN name END) AS cover_video_name
FROM (
@@ -396,6 +399,7 @@ class SqliteGalleryService(GalleryServiceABC):
image_count=row["image_count"],
video_count=row["video_count"],
asset_count=row["asset_count"],
+ asset_video_count=row["asset_video_count"],
)
return summaries
diff --git a/invokeai/app/services/virtual_boards/virtual_boards_common.py b/invokeai/app/services/virtual_boards/virtual_boards_common.py
index 9b396ecf80..0a401c7657 100644
--- a/invokeai/app/services/virtual_boards/virtual_boards_common.py
+++ b/invokeai/app/services/virtual_boards/virtual_boards_common.py
@@ -12,6 +12,9 @@ class VirtualSubBoardDTO(BaseModel):
image_count: int = Field(description="The number of general images for this date.")
asset_count: int = Field(description="The number of asset images for this date.")
video_count: int = Field(default=0, description="The number of videos for this date.")
+ asset_video_count: int = Field(
+ default=0, description="The number of asset-category (non-'general') videos for this date."
+ )
cover_image_name: Optional[str] = Field(default=None, description="The most recent image name for this date.")
cover_video_name: Optional[str] = Field(
default=None,
diff --git a/invokeai/app/util/video_ingest.py b/invokeai/app/util/video_ingest.py
new file mode 100644
index 0000000000..f7aaa9a67b
--- /dev/null
+++ b/invokeai/app/util/video_ingest.py
@@ -0,0 +1,234 @@
+"""Upload-time normalization of video and audio files into browser-safe H.264/AAC MP4.
+
+Uploaded videos are stored under a ``{uuid}.mp4`` name and served with the ``video/mp4``
+MIME type unconditionally, so everything in the store must genuinely be H.264/AAC MP4 —
+anything else silently breaks browser playback (the reason uploads were historically
+restricted to already-compliant files). This module widens what users may *upload* by
+converting at ingest time instead of widening what is *stored*:
+
+- H.264 video in a foreign container (iPhone ``.mov`` in "Most Compatible" mode, ``.m4v``,
+ screen recordings): lossless **remux** — stream-copy the video, seconds even for large
+ files.
+- Any other decodable video codec (HEVC from iPhone "High Efficiency" mode, ProRes, VP9):
+ **transcode** to H.264. 10-bit/HDR sources are converted to 8-bit yuv420p without
+ tonemapping — HDR footage will look flatter than the original; the bundled ffmpeg has
+ no zscale/tonemap support.
+- Audio-only files (voice memos, music): **wrap** into a video whose frames are a rendered
+ waveform. The result flows through every existing video path — gallery, thumbnails,
+ trim, and audio-only reference conditioning — without audio becoming a first-class
+ media type. The waveform (rather than black frames) keeps the clip recognizable in a
+ gallery of thumbnails and makes trim positions legible.
+
+Audio is normalized to AAC in every branch except when the source track is already AAC,
+which is stream-copied to avoid a needless lossy generation.
+
+The ffmpeg child gets the same hostile-input discipline as the decode worker: a hard
+wall-clock timeout (``subprocess.run`` kills the child on expiry) and a post-hoc output
+size cap. The bundled binary ships without ffprobe, so stream layout is read from the
+banner ffmpeg prints for a probe-only invocation — the established fallback used by
+``video_audio._probe_audio_sample_rate``.
+"""
+
+import re
+import subprocess
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Literal, Optional
+
+# Hard wall-clock bound for a single ffmpeg child (probe or convert). Matches the bound
+# used for audio extraction: generous enough for a worst-case ~1 GB 4K transcode on a
+# modest CPU, small enough that a hostile file cannot camp an upload slot forever.
+INGEST_TIMEOUT_SECONDS = 600
+PROBE_TIMEOUT_SECONDS = 60
+
+# The waveform canvas for wrapped audio uploads. 24 fps matches the video models' native
+# rate so frame-based trims map to 1/24 s of audio.
+AUDIO_WRAP_SIZE = "640x360"
+AUDIO_WRAP_FPS = 24
+
+IngestAction = Literal["remux", "transcode", "audio_wrap"]
+
+
+class VideoIngestError(RuntimeError):
+ """The upload could not be converted to a browser-safe MP4. Message is user-safe."""
+
+
+@dataclass(frozen=True)
+class MediaProbe:
+ """Stream layout parsed from ffmpeg's probe banner."""
+
+ video_codec: Optional[str]
+ audio_codec: Optional[str]
+
+ @property
+ def has_video(self) -> bool:
+ return self.video_codec is not None
+
+ @property
+ def has_audio(self) -> bool:
+ return self.audio_codec is not None
+
+
+def _ffmpeg_exe() -> str:
+ import imageio_ffmpeg
+
+ return imageio_ffmpeg.get_ffmpeg_exe()
+
+
+# ffmpeg banner lines look like:
+# Stream #0:0[0x1](und): Video: hevc (Main 10) (hvc1 / 0x31637668), yuv420p10le(tv, ...
+# Stream #0:1[0x2](und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp
+# The codec token is the first word after the stream-type label. "Attached pictures"
+# (album art in audio files) are video streams flagged "(attached pic)" — they are cover
+# art, not video content, and must not make an audio file look like a video.
+_STREAM_RE = re.compile(r"Stream #\d+:\d+.*?: (Video|Audio): (\w+)")
+_ATTACHED_PIC_RE = re.compile(r"\(attached pic\)")
+
+
+def probe_media_streams(path: Path) -> MediaProbe:
+ """Returns the first real video stream's codec and the first audio stream's codec.
+
+ Raises VideoIngestError when ffmpeg cannot read the file at all.
+ """
+ try:
+ proc = subprocess.run(
+ [_ffmpeg_exe(), "-hide_banner", "-i", str(path)],
+ capture_output=True,
+ timeout=PROBE_TIMEOUT_SECONDS,
+ )
+ except subprocess.TimeoutExpired as e:
+ raise VideoIngestError("Timed out reading the uploaded file") from e
+ # A probe-only invocation always exits non-zero; the banner is on stderr.
+ banner = proc.stderr.decode("utf-8", errors="replace")
+ if "Invalid data found" in banner or "Stream #" not in banner:
+ raise VideoIngestError("The uploaded file is not a readable video or audio file")
+
+ video_codec: Optional[str] = None
+ audio_codec: Optional[str] = None
+ for line in banner.splitlines():
+ match = _STREAM_RE.search(line)
+ if match is None:
+ continue
+ kind, codec = match.group(1), match.group(2).lower()
+ if kind == "Video" and video_codec is None and not _ATTACHED_PIC_RE.search(line):
+ video_codec = codec
+ elif kind == "Audio" and audio_codec is None:
+ audio_codec = codec
+ return MediaProbe(video_codec=video_codec, audio_codec=audio_codec)
+
+
+def _audio_args(probe: MediaProbe) -> list[str]:
+ """Copy an already-AAC track; encode anything else (PCM, MP3, ALAC, …) to AAC."""
+ if not probe.has_audio:
+ return []
+ if probe.audio_codec == "aac":
+ return ["-c:a", "copy"]
+ return ["-c:a", "aac", "-b:a", "192k"]
+
+
+def plan_ingest(probe: MediaProbe) -> IngestAction:
+ """Decides how ``ingest_media_to_mp4`` will convert a probed upload."""
+ if probe.has_video:
+ return "remux" if probe.video_codec == "h264" else "transcode"
+ if probe.has_audio:
+ return "audio_wrap"
+ raise VideoIngestError("The uploaded file contains no video or audio stream")
+
+
+def ingest_media_to_mp4(src: Path, dst: Path, *, max_output_bytes: int) -> IngestAction:
+ """Converts ``src`` into a browser-safe H.264/AAC MP4 at ``dst``.
+
+ Returns the action taken. Raises VideoIngestError (user-safe message) on any
+ failure; ``dst`` is left absent or partial on failure and the caller owns cleanup.
+ """
+ probe = probe_media_streams(src)
+ action = plan_ingest(probe)
+
+ common_output = ["-movflags", "+faststart", "-f", "mp4", str(dst)]
+ if action == "remux":
+ args = [
+ "-i",
+ str(src),
+ "-map",
+ "0:v:0",
+ "-map",
+ "0:a:0?",
+ "-c:v",
+ "copy",
+ *_audio_args(probe),
+ *common_output,
+ ]
+ elif action == "transcode":
+ args = [
+ "-i",
+ str(src),
+ "-map",
+ "0:v:0",
+ "-map",
+ "0:a:0?",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "veryfast",
+ "-crf",
+ "18",
+ # x264 yuv420p needs even dimensions; also folds 10-bit/HDR sources to 8-bit.
+ "-vf",
+ "scale=trunc(iw/2)*2:trunc(ih/2)*2",
+ "-pix_fmt",
+ "yuv420p",
+ *_audio_args(probe),
+ *common_output,
+ ]
+ else: # audio_wrap
+ args = [
+ "-i",
+ str(src),
+ "-f",
+ "lavfi",
+ "-i",
+ f"color=c=0x101418:s={AUDIO_WRAP_SIZE}:r={AUDIO_WRAP_FPS}",
+ "-filter_complex",
+ # Waveform over a dark background. `shortest=1` ends the wrap at the
+ # waveform stream's end, i.e. the audio duration — the color source is
+ # infinite. aformat guarantees showwaves a stereo layout for odd sources;
+ # colors covers both channels (an uncovered channel falls back to ffmpeg's
+ # default green) and sqrt scaling keeps quiet recordings visible.
+ (
+ f"[0:a]aformat=channel_layouts=stereo,"
+ f"showwaves=s={AUDIO_WRAP_SIZE}:mode=cline:rate={AUDIO_WRAP_FPS}"
+ f":colors=0x4FA8FF|0x2E7CD6:scale=sqrt[w];"
+ f"[1:v][w]overlay=shortest=1,format=yuv420p[v]"
+ ),
+ "-map",
+ "[v]",
+ "-map",
+ "0:a:0",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "veryfast",
+ "-crf",
+ "23",
+ *_audio_args(probe),
+ *common_output,
+ ]
+
+ try:
+ proc = subprocess.run(
+ [_ffmpeg_exe(), "-y", "-loglevel", "error", *args],
+ capture_output=True,
+ timeout=INGEST_TIMEOUT_SECONDS,
+ )
+ except subprocess.TimeoutExpired as e:
+ 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()
+ 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:
+ raise VideoIngestError("The converted video exceeds the maximum upload size")
+ return action
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index f690af1494..7d0d9e7a03 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -17544,6 +17544,12 @@
"title": "Asset Count",
"description": "The number of assets in the board."
},
+ "asset_video_count": {
+ "type": "integer",
+ "title": "Asset Video Count",
+ "description": "The number of asset-category (non-'general') videos in the board.",
+ "default": 0
+ },
"owner_username": {
"anyOf": [
{
@@ -95312,6 +95318,12 @@
"description": "The number of videos for this date.",
"default": 0
},
+ "asset_video_count": {
+ "type": "integer",
+ "title": "Asset Video Count",
+ "description": "The number of asset-category (non-'general') videos for this date.",
+ "default": 0
+ },
"cover_image_name": {
"anyOf": [
{
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 46ce894691..30c5d0585d 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -5306,6 +5306,12 @@ export type components = {
* @description The number of assets in the board.
*/
asset_count: number;
+ /**
+ * Asset Video Count
+ * @description The number of asset-category (non-'general') videos in the board.
+ * @default 0
+ */
+ asset_video_count?: number;
/**
* Owner Username
* @description The username of the board owner (for admin view).
@@ -42507,6 +42513,12 @@ export type components = {
* @default 0
*/
video_count?: number;
+ /**
+ * Asset Video Count
+ * @description The number of asset-category (non-'general') videos for this date.
+ * @default 0
+ */
+ asset_video_count?: number;
/**
* Cover Image Name
* @description The most recent image name for this date.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 157925522d..89ee1f03f7 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3041,7 +3041,7 @@
"uploadSuccessTitle_other": "Uploaded {{count}} files",
"uploadSummary": "{{images}} and {{videos}} uploaded to {{board}}. {{failed}} failed.",
"uploadsUnavailableForDateBoards": "Uploads are unavailable for date boards",
- "uploadUnsupported": "No supported media files to upload (PNG, JPEG, WebP, or MP4).",
+ "uploadUnsupported": "No supported media files to upload (PNG, JPEG, or WebP images; video files; or audio files).",
"videoCount_one": "{{count}} video",
"videoCount_other": "{{count}} videos",
"windowAnchored": "Showing this board from item {{index}}.",
diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
index f678f90540..6cef6f8088 100644
--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
@@ -5,6 +5,7 @@ import { invalidateGallery } from '@features/gallery/queries';
import { VideoUiProvider } from '@features/video';
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';
@@ -31,6 +32,13 @@ 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).
+ const uploadBoardId = useActiveProjectSelector((activeProject) => {
+ const selectedBoardId = getProjectWidgetValues(activeProject, 'gallery').selectedBoardId;
+
+ return typeof selectedBoardId === 'string' ? selectedBoardId : 'none';
+ });
const commands = useWorkbenchCommands();
const queryClient = useQueryClient();
// The port's callbacks are keyed to the project, not to its contents: rebuilding
@@ -46,15 +54,17 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>
[commands]
);
const touchGalleryImages = useCallback(() => void invalidateGallery(queryClient), [queryClient]);
+ const getUploadBoardId = useCallback(() => uploadBoardId, [uploadBoardId]);
const adapter = useMemo<VideoUiAdapter>(
() => ({
...project,
+ getUploadBoardId,
patchValues,
reportError,
showPromptSyntaxHighlighting,
touchGalleryImages,
}),
- [patchValues, project, reportError, showPromptSyntaxHighlighting, touchGalleryImages]
+ [getUploadBoardId, patchValues, project, reportError, showPromptSyntaxHighlighting, touchGalleryImages]
);
return <VideoUiProvider adapter={adapter}>{children}</VideoUiProvider>;
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts
index 3a730dec23..07ce251c7c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts
@@ -7,6 +7,7 @@ import { getGalleryBoardLabel } from './boardLabels';
const createBoard = (overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({
archived: false,
assetCount: 3,
+ assetVideoCount: 0,
id: 'dogs',
imageCount: 50,
kind: 'board',
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/types.ts b/invokeai/frontend/webv2/src/features/gallery/core/types.ts
index c0856c6b70..a76db9e156 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/types.ts
@@ -24,6 +24,8 @@ export interface GalleryBoard {
assetCount: number;
/** Videos on the board, counted separately from `imageCount` by the backend. */
videoCount: number;
+ /** Asset-category (non-'general') videos on the board; uploaded videos are assets. */
+ assetVideoCount: number;
archived: boolean;
coverImageName?: string | null;
/** Set instead of `coverImageName` when the board's most recent item is a video. */
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
index 9a166654b4..8add269e04 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
@@ -771,8 +771,15 @@ describe('classifyGalleryUpload', () => {
['image/jpg', 'photo.bin', 'image'],
['image/webp', 'photo.bin', 'image'],
['video/mp4', 'clip.bin', 'video'],
+ ['video/quicktime', 'clip.bin', 'video'],
+ ['video/webm', 'clip.webm', 'video'],
+ ['audio/mpeg', 'song.bin', 'video'],
+ ['audio/wav', 'memo.bin', 'video'],
['', 'photo.PNG', 'image'],
+ ['', 'clip.MOV', 'video'],
+ ['', 'memo.m4a', 'video'],
['application/octet-stream', 'photo.jpeg', 'image'],
+ ['application/octet-stream', 'song.mp3', 'video'],
['binary/octet-stream', 'clip.MP4', 'video'],
['application/pdf', 'photo.png', 'image'],
] as const)('classifies MIME %s and name %s as %s', (type, name, kind) => {
@@ -782,7 +789,6 @@ describe('classifyGalleryUpload', () => {
it.each([
['application/pdf', 'document.pdf'],
['', 'archive.zip'],
- ['video/webm', 'clip.webm'],
['image/gif', 'animation.gif'],
] as const)('rejects unsupported MIME %s and name %s', (type, name) => {
expect(classifyGalleryUpload(new File(['media'], name, { type }))).toBeNull();
@@ -827,7 +833,7 @@ describe('gallery uploads', () => {
expect(init.body).toBeInstanceOf(FormData);
});
- it('uploads videos as durable general media to a real board', async () => {
+ it('uploads videos as durable user assets to a real board', async () => {
const controller = new AbortController();
mocks.apiFetchJson.mockResolvedValue({
board_id: 'board-1',
@@ -859,7 +865,7 @@ describe('gallery uploads', () => {
const [url, init] = mocks.apiFetchJson.mock.calls[0] as [string, RequestInit];
const query = new URLSearchParams(url.split('?')[1]);
expect(url.split('?')[0]).toBe('/api/v1/videos/upload');
- expect(query.get('video_category')).toBe('general');
+ expect(query.get('video_category')).toBe('user');
expect(query.get('is_intermediate')).toBe('false');
expect(query.get('board_id')).toBe('board-1');
expect(init).toMatchObject({ method: 'POST', signal: controller.signal });
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index a60ef02c90..446b6e70b1 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -45,6 +45,8 @@ interface BackendBoardDTO {
asset_count: number;
/** Videos on the board. Counted separately from `image_count` by the backend. */
video_count?: number;
+ /** Asset-category (non-'general') videos on the board; uploaded videos are assets. */
+ asset_video_count?: number;
archived: boolean;
cover_image_name?: string | null;
/** Set instead of `cover_image_name` when the board's most recent item is a video. */
@@ -81,24 +83,49 @@ const GALLERY_UPLOAD_KIND_BY_MIME = new Map<string, GalleryUploadKind>([
['image/jpg', 'image'],
['image/png', 'image'],
['image/webp', 'image'],
- ['video/mp4', 'video'],
]);
+// The server normalizes every accepted upload to H.264 MP4 at ingest — foreign
+// containers/codecs (.mov, HEVC, …) are remuxed or transcoded, and audio files are
+// wrapped into waveform videos — so both video/* and audio/* upload as 'video'.
const GALLERY_UPLOAD_KIND_BY_EXTENSION = new Map<string, GalleryUploadKind>([
['.jpeg', 'image'],
['.jpg', 'image'],
['.png', 'image'],
['.webp', 'image'],
['.mp4', 'video'],
+ ['.mov', 'video'],
+ ['.m4v', 'video'],
+ ['.webm', 'video'],
+ ['.mkv', 'video'],
+ ['.avi', 'video'],
+ ['.mpg', 'video'],
+ ['.mpeg', 'video'],
+ ['.3gp', 'video'],
+ ['.mp3', 'video'],
+ ['.m4a', 'video'],
+ ['.aac', 'video'],
+ ['.wav', 'video'],
+ ['.flac', 'video'],
+ ['.ogg', 'video'],
+ ['.oga', 'video'],
+ ['.opus', 'video'],
+ ['.aiff', 'video'],
+ ['.aif', 'video'],
]);
export const classifyGalleryUpload = (file: Pick<File, 'name' | 'type'>): { kind: GalleryUploadKind } | null => {
- const mimeKind = GALLERY_UPLOAD_KIND_BY_MIME.get(file.type.toLowerCase());
+ const mimeType = file.type.toLowerCase();
+ const mimeKind = GALLERY_UPLOAD_KIND_BY_MIME.get(mimeType);
if (mimeKind) {
return { kind: mimeKind };
}
+ if (mimeType.startsWith('video/') || mimeType.startsWith('audio/')) {
+ return { kind: 'video' };
+ }
+
const lowerName = file.name.toLowerCase();
for (const [extension, kind] of GALLERY_UPLOAD_KIND_BY_EXTENSION) {
@@ -209,6 +236,7 @@ const getBoardCoverThumbnailUrl = (
const mapBoard = (board: BackendBoardDTO): GalleryBoard => ({
archived: board.archived,
assetCount: board.asset_count,
+ assetVideoCount: board.asset_video_count ?? 0,
coverImageName: board.cover_image_name,
coverThumbnailUrl: getBoardCoverThumbnailUrl(board),
coverVideoName: board.cover_video_name,
@@ -244,17 +272,20 @@ const getGalleryTotal = async ({
};
/**
- * Videos carry no category split — the gallery's Images/Assets views are an image-only
- * distinction — so this counts every non-intermediate video on the board.
+ * Counts non-intermediate videos on a board, optionally restricted to a category set —
+ * the same general/asset split the images use (uploaded videos are 'user', generated
+ * are 'general').
*/
const getGalleryVideoTotal = async ({
boardId,
+ categories,
signal,
}: {
boardId: string;
+ categories?: string[];
signal?: AbortSignal;
}): Promise<number> => {
- const query = toSearchParams({ board_id: boardId, is_intermediate: false, limit: 0, offset: 0 });
+ const query = toSearchParams({ board_id: boardId, categories, is_intermediate: false, limit: 0, offset: 0 });
const body = await apiFetchJson<{ total: number }>(`/api/v1/videos/?${query}`, { signal });
return body.total;
@@ -369,13 +400,20 @@ export const listGalleryBoards = async ({
{ signal }
);
- const [body, uncategorizedImageCount, uncategorizedAssetCount, uncategorizedVideoCount] = await Promise.all([
+ const [
+ body,
+ uncategorizedImageCount,
+ uncategorizedAssetCount,
+ uncategorizedVideoCount,
+ uncategorizedAssetVideoCount,
+ ] = await Promise.all([
boardsBodyPromise,
getGalleryTotal({ boardId: 'none', categories: imageCategories, signal }),
getGalleryTotal({ boardId: 'none', categories: assetCategories, signal }),
// Real boards carry `video_count` in their DTO, but the uncategorized pseudo-board is
- // assembled here, so its video total needs its own request.
+ // assembled here, so its video totals need their own requests.
getGalleryVideoTotal({ boardId: 'none', signal }),
+ getGalleryVideoTotal({ boardId: 'none', categories: assetCategories, signal }),
]);
const boards = Array.isArray(body) ? body : (body.items ?? []);
@@ -383,6 +421,7 @@ export const listGalleryBoards = async ({
{
archived: false,
assetCount: uncategorizedAssetCount,
+ assetVideoCount: uncategorizedAssetVideoCount,
id: 'none',
imageCount: uncategorizedImageCount,
kind: 'uncategorized',
@@ -408,6 +447,7 @@ interface VirtualDateBoardDTO {
image_count: number;
asset_count: number;
video_count?: number;
+ asset_video_count?: number;
cover_image_name?: string | null;
cover_video_name?: string | null;
}
@@ -418,6 +458,7 @@ export const listGalleryDateBoards = async (signal?: AbortSignal): Promise<Galle
return body.map((board) => ({
archived: false,
assetCount: board.asset_count,
+ assetVideoCount: board.asset_video_count ?? 0,
coverImageName: board.cover_image_name,
coverThumbnailUrl: getBoardCoverThumbnailUrl(board),
coverVideoName: board.cover_video_name,
@@ -1494,7 +1535,9 @@ export const uploadGalleryVideo = async (
const query = toSearchParams({
board_id: getUploadBoardId(boardId),
is_intermediate: false,
- video_category: 'general',
+ // Uploads are user assets (the Assets view), mirroring `image_category: 'user'` on
+ // image uploads; generated videos save as 'general' (the Media view).
+ video_category: 'user',
});
const body = new FormData();
body.append('file', file);
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
index 00d6d00128..c4ddb33649 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
@@ -312,6 +312,7 @@ describe('getGalleryItemBoardIdsFromCaches', () => {
const createBoard = (id: string, overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id,
imageCount: 1,
kind: 'board',
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
index a202eb07c4..fa15d37244 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
@@ -38,6 +38,7 @@ vi.mock('react-i18next', () => ({
const board = {
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'board-1',
imageCount: 2,
kind: 'board',
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
index a1382aa6be..d8a45d0428 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
@@ -51,9 +51,9 @@ export const GalleryBoardRow = ({
});
const counts = getBoardCounts(board);
- const mediaCount = counts.imageCount + counts.videoCount;
+ const mediaCount = counts.imageCount + counts.videoCount - counts.assetVideoCount;
const countsBreakdown = t('widgets.gallery.boardCountsBreakdown', {
- assets: counts.assetCount,
+ assets: counts.assetCount + counts.assetVideoCount,
media: mediaCount,
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx
index 2d52cd930c..e6ec3f6f03 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx
@@ -52,6 +52,7 @@ const itemActions = { moveItemsToBoard: vi.fn(async () => {}) };
const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id' | 'name'>): GalleryBoard => ({
archived: false,
assetCount: 3,
+ assetVideoCount: 0,
imageCount: 50,
kind: 'board',
projectId: null,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
index 4c9fa7f3c2..cd654cb767 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
@@ -177,6 +177,7 @@ const previewSource: StreamingImageSource = {
const board = {
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'board-a',
imageCount: 3,
kind: 'board',
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx
index f1f86149e2..a6850374d5 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx
@@ -35,6 +35,7 @@ vi.mock('react-i18next', () => ({
const board: GalleryBoard = {
archived: false,
assetCount: 3,
+ assetVideoCount: 0,
id: 'dogs',
imageCount: 50,
kind: 'board',
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx
index db84fbf585..477d6ecc9a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx
@@ -44,6 +44,7 @@ const itemActions = {
const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id' | 'name'>): GalleryBoard => ({
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
imageCount: 0,
kind: 'board',
projectId: null,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.browser.test.tsx
index 31c52a5f50..f744b40e24 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.browser.test.tsx
@@ -34,7 +34,7 @@ const renderViewTabs = async (): Promise<{
const value = {
actions: { setView: vi.fn() },
gallery: {
- boards: [{ assetCount: 7, id: 'board-1', imageCount: 148, videoCount: 0 }],
+ boards: [{ assetCount: 7, assetVideoCount: 0, id: 'board-1', imageCount: 148, videoCount: 0 }],
galleryView: 'images',
selectedBoardId: 'board-1',
},
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts
index 753ab804d1..f06f7b3cf2 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts
@@ -7,6 +7,7 @@ import { getGalleryBoardGroups } from './galleryBoardGroups';
const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id' | 'name'>): GalleryBoard => ({
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
imageCount: 0,
kind: 'board',
projectId: null,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts
index 02272bad03..3755775166 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts
@@ -7,6 +7,7 @@ import { getGalleryCountForView } from './galleryBoardLabels';
const createBoard = (overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({
archived: false,
assetCount: 3,
+ assetVideoCount: 0,
id: 'dogs',
imageCount: 50,
kind: 'board',
@@ -24,4 +25,13 @@ describe('getGalleryCountForView', () => {
it('counts assets alone for the assets view', () => {
expect(getGalleryCountForView(createBoard(), 'assets')).toBe(3);
});
+
+ it('splits asset-category videos out of media and into assets', () => {
+ // 4 videos total, 1 uploaded (asset): media shows 50 images + 3 media videos,
+ // assets shows 3 asset images + 1 asset video.
+ const board = createBoard({ assetVideoCount: 1 });
+
+ expect(getGalleryCountForView(board, 'images')).toBe(53);
+ expect(getGalleryCountForView(board, 'assets')).toBe(4);
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts
index 42ab71ffe5..c238d4610a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts
@@ -9,5 +9,9 @@ import { getBoardCounts } from './galleryStateView';
export const getGalleryCountForView = (board: GalleryBoard, galleryView: GalleryView): number => {
const counts = getBoardCounts(board);
- return galleryView === 'assets' ? counts.assetCount : counts.imageCount + counts.videoCount;
+ // Videos split across the views the same way images do: uploaded ('user') videos are
+ // assets, generated ('general') videos are media.
+ return galleryView === 'assets'
+ ? counts.assetCount + counts.assetVideoCount
+ : counts.imageCount + counts.videoCount - counts.assetVideoCount;
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
index 9c7c8c0db6..1be595a318 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
@@ -19,6 +19,7 @@ const boards: GalleryBoard[] = [
{
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'none',
imageCount: 1,
kind: 'uncategorized',
@@ -29,6 +30,7 @@ const boards: GalleryBoard[] = [
{
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'board-1',
imageCount: 2,
kind: 'board',
@@ -175,6 +177,7 @@ describe('gallery state view', () => {
it('exposes image, video, and asset counts for board labels', () => {
expect(getBoardCounts({ ...boards[1], videoCount: 3 })).toEqual({
assetCount: 0,
+ assetVideoCount: 0,
imageCount: 2,
videoCount: 3,
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
index 048d538ccc..7ab6ff5783 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
@@ -28,6 +28,7 @@ import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '
const UNCATEGORIZED_BOARD: GalleryBoard = {
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'none',
imageCount: 0,
kind: 'uncategorized',
@@ -404,6 +405,7 @@ export const getGalleryStateView = (
: [
{
...UNCATEGORIZED_BOARD,
+ assetVideoCount: items.filter((item) => item.kind === 'video' && item.category !== 'general').length,
imageCount: items.filter((item) => item.kind === 'image' && item.category === 'general').length,
projectId: null,
videoCount: items.filter((item) => item.kind === 'video').length,
@@ -474,8 +476,9 @@ export const getGalleryStateView = (
export const getBoardCounts = (
board: GalleryBoard
-): { assetCount: number; imageCount: number; videoCount: number } => ({
+): { assetCount: number; assetVideoCount: number; imageCount: number; videoCount: number } => ({
assetCount: board.assetCount,
+ assetVideoCount: board.assetVideoCount,
imageCount: board.imageCount,
videoCount: board.videoCount,
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
index caa1876bbb..58d57c3f2a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
@@ -121,6 +121,7 @@ const Probe = ({
{
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'board-1',
imageCount: 2,
kind: 'board',
@@ -131,6 +132,7 @@ const Probe = ({
{
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'none',
imageCount: 0,
kind: 'uncategorized',
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx
index 244d9a536b..1fcf99e91c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx
@@ -127,6 +127,7 @@ const Probe = ({
{
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'board-1',
imageCount: 2,
kind: 'board',
@@ -137,6 +138,7 @@ const Probe = ({
{
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'none',
imageCount: 0,
kind: 'uncategorized',
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx
index 6754c29b71..9752a2935e 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx
@@ -67,7 +67,7 @@ export const VideoFrameImageField = memo(
onChange: (image: ImageWithDims | null) => void;
}) {
const { t } = useTranslation();
- const { reportError, touchGalleryImages } = useVideoUiActions();
+ const { getUploadBoardId, reportError, touchGalleryImages } = useVideoUiActions();
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
@@ -134,7 +134,7 @@ export const VideoFrameImageField = memo(
setIsLoading(true);
try {
- const uploaded = await galleryTransfers.upload(file, 'none', { signal: owner.signal });
+ const uploaded = await galleryTransfers.upload(file, getUploadBoardId(), { signal: owner.signal });
assertAccountScopeCurrent(owner);
onChange({ height: uploaded.height, image_name: uploaded.imageName, width: uploaded.width });
@@ -151,7 +151,7 @@ export const VideoFrameImageField = memo(
setIsLoading(false);
}
},
- [onChange, reportError, t, touchGalleryImages]
+ [getUploadBoardId, onChange, reportError, t, touchGalleryImages]
);
const handleFileChange = useCallback(
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
index 3fa8294261..363ab78a5f 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
@@ -143,7 +143,7 @@ export const VideoSourceClipField = memo(
sourceVideo: VideoSourceClip | null;
}) {
const { t } = useTranslation();
- const { reportError, touchGalleryImages } = useVideoUiActions();
+ const { getUploadBoardId, reportError, touchGalleryImages } = useVideoUiActions();
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
@@ -213,7 +213,7 @@ export const VideoSourceClipField = memo(
setIsLoading(true);
try {
- const uploaded = await galleryTransfers.uploadVideo(file, 'none', { signal: owner.signal });
+ const uploaded = await galleryTransfers.uploadVideo(file, getUploadBoardId(), { signal: owner.signal });
assertAccountScopeCurrent(owner);
onChange(
@@ -238,7 +238,7 @@ export const VideoSourceClipField = memo(
setIsLoading(false);
}
},
- [onChange, reportError, t, touchGalleryImages]
+ [getUploadBoardId, onChange, reportError, t, touchGalleryImages]
);
const handleFileChange = useCallback(
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx
index 5064418e2d..e00b50f810 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx
@@ -8,6 +8,12 @@ import { createContext, use, useMemo } from 'react';
* may not import workbench), not a test seam; no second adapter is expected.
*/
export interface VideoUiAdapter {
+ /**
+ * The board a file upload from the video panel should land on — the gallery's
+ * currently selected board. A callback rather than a value so upload handlers
+ * read it at upload time without subscribing to board-selection changes.
+ */
+ getUploadBoardId(): string;
patchValues(values: Partial<VideoWidgetValues>, origin?: 'user' | 'system'): void;
projectId: string;
rawValues: Record<string, unknown>;
@@ -17,7 +23,10 @@ export interface VideoUiAdapter {
}
/** The adapter's callbacks, which are stable for the lifetime of a project. */
-export type VideoUiActions = Pick<VideoUiAdapter, 'patchValues' | 'reportError' | 'touchGalleryImages'>;
+export type VideoUiActions = Pick<
+ VideoUiAdapter,
+ 'getUploadBoardId' | 'patchValues' | 'reportError' | 'touchGalleryImages'
+>;
const VideoUiContext = createContext<VideoUiAdapter | null>(null);
/**
@@ -29,10 +38,10 @@ const VideoUiContext = createContext<VideoUiAdapter | null>(null);
const VideoUiActionsContext = createContext<VideoUiActions | null>(null);
export const VideoUiProvider = ({ adapter, children }: { adapter: VideoUiAdapter; children: ReactNode }) => {
- const { patchValues, reportError, touchGalleryImages } = adapter;
+ const { getUploadBoardId, patchValues, reportError, touchGalleryImages } = adapter;
const actions = useMemo<VideoUiActions>(
- () => ({ patchValues, reportError, touchGalleryImages }),
- [patchValues, reportError, touchGalleryImages]
+ () => ({ getUploadBoardId, patchValues, reportError, touchGalleryImages }),
+ [getUploadBoardId, patchValues, reportError, touchGalleryImages]
);
return (
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
index 4030fcd365..420c1f3890 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
@@ -248,7 +248,7 @@ describe('WorkflowFieldInput media inputs', () => {
expect(host.textContent).toContain('Drop a video here');
expect(findButton('Use gallery selection').disabled).toBe(true);
expect(findButton('Upload').disabled).toBe(false);
- expect(host.querySelector<HTMLInputElement>('input[type="file"]')?.accept).toBe('video/*');
+ expect(host.querySelector<HTMLInputElement>('input[type="file"]')?.accept).toBe('video/*,audio/*');
});
it('adopts a selected gallery video and clears it', async () => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index c154fd0f3f..59cc01d9ca 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -437,7 +437,7 @@ const MEDIA_FIELD_CONFIG = {
noun: 'image',
},
video: {
- fileAccept: 'video/*',
+ fileAccept: 'video/*,audio/*',
getThumbnailUrl: (name: string) => galleryVideoUrls.thumbnail(name),
nameKey: 'video_name',
noun: 'video',
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
index 219cdbaa57..5571607998 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
@@ -204,6 +204,7 @@ const Probe = ({ modelKey = 'sd-1-model', ref }: { modelKey?: string; ref: Ref<I
{
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'none',
imageCount: 0,
kind: 'uncategorized',
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
index 87b30d22d6..d6a1ca943c 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
@@ -40,6 +40,7 @@ const searchContext = () => ({ signal: new AbortController().signal });
const uncategorized: GalleryBoard = {
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'none',
imageCount: 1,
kind: 'uncategorized',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index a4f36b4800..bd163cd3c2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -114,6 +114,7 @@ const fallbackBoards: GalleryBoard[] = [
{
archived: false,
assetCount: 0,
+ assetVideoCount: 0,
id: 'none',
imageCount: 0,
kind: 'uncategorized',
diff --git a/tests/app/routers/test_videos_multiuser.py b/tests/app/routers/test_videos_multiuser.py
index 6fcddf11a1..34c20aa5d9 100644
--- a/tests/app/routers/test_videos_multiuser.py
+++ b/tests/app/routers/test_videos_multiuser.py
@@ -12,6 +12,7 @@ filter is covered separately in tests/app/services/video_records.
"""
import inspect
+import json
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock, patch
@@ -38,6 +39,7 @@ from invokeai.app.api_app import app
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.users.users_common import UserCreateRequest
from invokeai.app.services.videos.videos_common import VideoDTO
+from invokeai.app.util.video_ingest import MediaProbe
class MockApiDependencies(ApiDependencies):
@@ -531,17 +533,18 @@ def test_upload_video_malformed_mp4_returns_415_and_cleans_up_tmp(
client: TestClient, mock_invoker: Invoker, user1_token: str, tmp_path: Path
):
"""An upload that looks like an MP4 on the surface (``.mp4`` extension or video MIME
- type) but contains bytes ``probe_video`` can't decode must:
+ type) but contains bytes no probe can decode must:
- 1. Reach ``probe_video`` (the extension/MIME gate is intentionally permissive — the
- real validation is the decode probe).
+ 1. Reach the content probes (the extension/MIME gate is intentionally permissive —
+ the real validation is stream content).
2. Surface a 415 to the caller.
- 3. Unlink the streamed-to-disk temp file so the server doesn't leak storage on every
- garbage upload.
+ 3. Unlink every temp file the route created (the streamed upload spool and, for
+ non-compliant uploads, the ingest converter's output) so the server doesn't
+ leak storage on garbage uploads.
"""
- # Capture the tmp path the route created so we can prove it was unlinked after the
- # 415 response. ``tempfile.NamedTemporaryFile(..., delete=False)`` is invoked inside
- # the route, so we wrap the real call and stash the resulting path.
+ # Capture the tmp paths the route created so we can prove they were unlinked after
+ # the 415 response. ``tempfile.NamedTemporaryFile(..., delete=False)`` is invoked
+ # inside the route, so we wrap the real call and stash the resulting paths.
captured_paths: list[Path] = []
import tempfile as _tempfile
@@ -574,10 +577,11 @@ def test_upload_video_malformed_mp4_returns_415_and_cleans_up_tmp(
)
assert response.status_code == status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
- # The route should have allocated exactly one tmp file and then unlinked it.
- assert len(captured_paths) == 1, f"expected one tmp file, got {captured_paths}"
- tmp_file = captured_paths[0]
- assert not tmp_file.exists(), f"tmp file leaked after 415: {tmp_file}"
+ # The route allocates the upload spool plus (for a non-compliant container) the
+ # ingest converter's output file; every one of them must be unlinked on rejection.
+ assert len(captured_paths) == 2, f"expected upload + ingest tmp files, got {captured_paths}"
+ leaked = [p for p in captured_paths if p.exists()]
+ assert not leaked, f"tmp files leaked after 415: {leaked}"
def test_upload_video_rejects_non_mp4_container_with_spoofed_mime(
@@ -643,7 +647,13 @@ def test_upload_video_accepts_object_metadata(client: TestClient, mock_invoker:
mp4 = b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 12
metadata = '{"seed": 123}'
- with patch("invokeai.app.api.routers.videos._probe_decodable_video", return_value=((64, 64, 1.0, 8.0), None)):
+ with (
+ patch(
+ "invokeai.app.api.routers.videos.probe_media_streams",
+ return_value=MediaProbe(video_codec="h264", audio_codec="aac"),
+ ),
+ patch("invokeai.app.api.routers.videos._probe_decodable_video", return_value=((64, 64, 1.0, 8.0), None)),
+ ):
response = client.post(
"/api/v1/videos/upload",
params={"video_category": "general", "is_intermediate": False},
@@ -656,6 +666,95 @@ def test_upload_video_accepts_object_metadata(client: TestClient, mock_invoker:
assert mock_invoker.services.videos.create.call_args.kwargs["metadata"] == metadata
+def _make_fixture_media(path: Path, *args: str) -> Path:
+ import subprocess
+
+ import imageio_ffmpeg
+
+ subprocess.run(
+ [imageio_ffmpeg.get_ffmpeg_exe(), "-y", "-loglevel", "error", *args, str(path)],
+ check=True,
+ capture_output=True,
+ )
+ return path
+
+
+def test_upload_h264_mov_is_remuxed_and_created(
+ client: TestClient, mock_invoker: Invoker, user1_token: str, tmp_path: Path
+):
+ """A QuickTime container with H.264 inside (the iPhone 'Most Compatible' shape) must
+ upload end-to-end: ingest remuxes it to MP4 and the full decode probe then accepts
+ it. No probes are patched — this exercises the real conversion."""
+ mov = _make_fixture_media(
+ tmp_path / "clip.mov",
+ *("-f", "lavfi", "-i", "testsrc2=s=64x48:r=8:d=1"),
+ *("-c:v", "libx264", "-pix_fmt", "yuv420p"),
+ )
+ # The route unlinks its tmp file after create() returns, so the container check
+ # must happen while the file still exists — inside the mocked create call.
+ stored_was_mp4: list[bool] = []
+
+ def create(**kwargs: Any) -> VideoDTO:
+ stored_was_mp4.append(_is_mp4_file(Path(kwargs["source_path"])))
+ 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.mov", mov.read_bytes(), "video/quicktime")},
+ headers={"Authorization": f"Bearer {user1_token}"},
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ create_kwargs = mock_invoker.services.videos.create.call_args.kwargs
+ assert (create_kwargs["width"], create_kwargs["height"]) == (64, 48)
+ # The created file is the converted MP4, not the original QuickTime bytes.
+ assert stored_was_mp4 == [True]
+
+
+def test_upload_audio_file_is_wrapped_and_marked(
+ client: TestClient, mock_invoker: Invoker, user1_token: str, tmp_path: Path
+):
+ """An audio-only upload becomes a waveform video, and its metadata is stamped with
+ `media_origin: audio_upload` so clients can recognize wrapped audio clips."""
+ wav = _make_fixture_media(
+ tmp_path / "tone.wav",
+ *("-f", "lavfi", "-i", "anoisesrc=a=0.3:d=1"),
+ *("-c:a", "pcm_s16le"),
+ )
+ mock_invoker.services.videos.create.return_value = _uploaded_video_dto()
+
+ response = client.post(
+ "/api/v1/videos/upload",
+ params={"video_category": "user", "is_intermediate": False},
+ files={"file": ("tone.wav", wav.read_bytes(), "audio/wav")},
+ data={"metadata": '{"note": "kept"}'},
+ headers={"Authorization": f"Bearer {user1_token}"},
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ create_kwargs = mock_invoker.services.videos.create.call_args.kwargs
+ stored_metadata = json.loads(create_kwargs["metadata"])
+ assert stored_metadata["media_origin"] == "audio_upload"
+ assert stored_metadata["note"] == "kept", "user-supplied metadata must survive the stamp"
+ assert (create_kwargs["width"], create_kwargs["height"]) == (640, 360)
+
+
+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")
+
+ response = client.post(
+ "/api/v1/videos/upload",
+ params={"video_category": "user", "is_intermediate": False},
+ files={"file": ("notes.txt", b"just text", "text/plain")},
+ headers={"Authorization": f"Bearer {user1_token}"},
+ )
+
+ assert response.status_code == status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
+
+
def test_mp4_validation_allows_boxes_before_file_type(tmp_path: Path) -> None:
path = tmp_path / "valid.mp4"
path.write_bytes(b"\x00\x00\x00\x08free" + b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 12)
diff --git a/tests/app/services/boards/test_boards_default.py b/tests/app/services/boards/test_boards_default.py
index 87d6fb9b95..d2ee6b7c21 100644
--- a/tests/app/services/boards/test_boards_default.py
+++ b/tests/app/services/boards/test_boards_default.py
@@ -28,6 +28,7 @@ def test_board_listing_fetches_media_summaries_once(mock_invoker: Invoker) -> No
image_count=1,
video_count=2,
asset_count=3,
+ asset_video_count=1,
)
for board_id in board_ids
}
@@ -74,6 +75,7 @@ def test_admin_board_listing_batches_owner_lookup(mock_invoker: Invoker) -> None
image_count=0,
video_count=0,
asset_count=0,
+ asset_video_count=0,
)
for board_id in board_ids
}
@@ -105,7 +107,12 @@ def test_non_admin_board_listing_skips_owner_lookup(mock_invoker: Invoker) -> No
mock_invoker.services.gallery.get_board_media_summaries = MagicMock( # type: ignore[attr-defined]
return_value={
board_id: SimpleNamespace(
- cover_image_name=None, cover_video_name=None, image_count=0, video_count=0, asset_count=0
+ cover_image_name=None,
+ cover_video_name=None,
+ image_count=0,
+ video_count=0,
+ asset_count=0,
+ asset_video_count=0,
)
}
)
diff --git a/tests/app/services/gallery/test_gallery_default.py b/tests/app/services/gallery/test_gallery_default.py
index 5764f5b474..8f4c5d2788 100644
--- a/tests/app/services/gallery/test_gallery_default.py
+++ b/tests/app/services/gallery/test_gallery_default.py
@@ -358,9 +358,13 @@ class TestGetBoardMediaSummaries:
_save_image(services["images"], "cover.png", user_id="alice")
_save_video(services["videos"], "cover.mp4", user_id="alice")
_save_video(services["videos"], "intermediate.mp4", user_id="alice")
+ # An uploaded (user-category) video is an asset: counted in video_count AND
+ # asset_video_count, so clients can split the Media/Assets views.
+ _save_video(services["videos"], "uploaded.mp4", user_id="alice", category=ImageCategory.USER)
services["board_images"].add_image_to_board(populated.board_id, "cover.png")
services["board_videos"].add_video_to_board(populated.board_id, "cover.mp4")
services["board_videos"].add_video_to_board(populated.board_id, "intermediate.mp4")
+ services["board_videos"].add_video_to_board(populated.board_id, "uploaded.mp4")
with services["images"]._db.transaction() as cursor:
cursor.execute(
"UPDATE images SET starred = 1, created_at = ? WHERE image_name = ?",
@@ -382,12 +386,14 @@ class TestGetBoardMediaSummaries:
)
assert summaries[populated.board_id].image_count == 1
- assert summaries[populated.board_id].video_count == 1
+ assert summaries[populated.board_id].video_count == 2
assert summaries[populated.board_id].asset_count == 0
+ assert summaries[populated.board_id].asset_video_count == 1
assert summaries[populated.board_id].cover_image_name is None
assert summaries[populated.board_id].cover_video_name == "cover.mp4"
assert summaries[empty.board_id].image_count == 0
assert summaries[empty.board_id].video_count == 0
+ assert summaries[empty.board_id].asset_video_count == 0
assert summaries[empty.board_id].cover_image_name is None
assert summaries[empty.board_id].cover_video_name is None
assert next(i for i, detail in enumerate(details) if "board_images" in detail) < next(
diff --git a/tests/app/util/test_video_ingest.py b/tests/app/util/test_video_ingest.py
new file mode 100644
index 0000000000..0258297514
--- /dev/null
+++ b/tests/app/util/test_video_ingest.py
@@ -0,0 +1,194 @@
+"""Tests for upload-time media normalization (video_ingest).
+
+Fixtures are generated with the same bundled ffmpeg the module invokes, using codecs
+that binary can *encode* (h264/mpeg4/aac/pcm) — HEVC and ProRes can only be decoded,
+so the "foreign codec" transcode branch is exercised with mpeg4, which takes the same
+code path.
+"""
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from invokeai.app.util.video_audio import extract_audio_pcm
+from invokeai.app.util.video_ingest import (
+ MediaProbe,
+ VideoIngestError,
+ ingest_media_to_mp4,
+ plan_ingest,
+ probe_media_streams,
+)
+from invokeai.app.util.video_thumbnails import probe_video_with_codec
+
+GB = 1 << 30
+
+
+def _ffmpeg_exe() -> str:
+ import imageio_ffmpeg
+
+ return imageio_ffmpeg.get_ffmpeg_exe()
+
+
+def _make_media(path: Path, *args: str) -> Path:
+ subprocess.run([_ffmpeg_exe(), "-y", "-loglevel", "error", *args, str(path)], check=True, capture_output=True)
+ return path
+
+
[email protected](scope="session")
+def fixture_dir(tmp_path_factory: pytest.TempPathFactory) -> Path:
+ return tmp_path_factory.mktemp("ingest_fixtures")
+
+
[email protected](scope="session")
+def h264_mov(fixture_dir: Path) -> Path:
+ """H.264 + AAC in a QuickTime container — the iPhone 'Most Compatible' shape."""
+ return _make_media(
+ fixture_dir / "clip.mov",
+ *("-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", "aac"),
+ )
+
+
[email protected](scope="session")
+def mpeg4_avi(fixture_dir: Path) -> Path:
+ """A decodable-but-foreign video codec, standing in for HEVC/ProRes."""
+ return _make_media(
+ fixture_dir / "clip.avi",
+ *("-f", "lavfi", "-i", "testsrc2=s=64x48:r=8:d=1"),
+ *("-c:v", "mpeg4"),
+ )
+
+
[email protected](scope="session")
+def wav_audio(fixture_dir: Path) -> Path:
+ return _make_media(
+ fixture_dir / "tone.wav",
+ *("-f", "lavfi", "-i", "anoisesrc=a=0.3:d=1"),
+ *("-c:a", "pcm_s16le"),
+ )
+
+
[email protected](scope="session")
+def m4a_audio(fixture_dir: Path) -> Path:
+ return _make_media(
+ fixture_dir / "tone.m4a",
+ *("-f", "lavfi", "-i", "sine=frequency=550:d=1"),
+ *("-c:a", "aac"),
+ )
+
+
+def test_probe_reports_video_and_audio_codecs(h264_mov: Path, wav_audio: Path) -> None:
+ probe = probe_media_streams(h264_mov)
+ assert probe.video_codec == "h264"
+ assert probe.audio_codec == "aac"
+
+ probe = probe_media_streams(wav_audio)
+ assert probe.video_codec is None
+ assert probe.audio_codec is not None
+
+
+def test_probe_rejects_unreadable_bytes(tmp_path: Path) -> None:
+ garbage = tmp_path / "garbage.mov"
+ garbage.write_bytes(b"this is not media" * 64)
+ with pytest.raises(VideoIngestError):
+ probe_media_streams(garbage)
+
+
+def test_plan_covers_each_stream_layout() -> None:
+ assert plan_ingest(MediaProbe(video_codec="h264", audio_codec=None)) == "remux"
+ assert plan_ingest(MediaProbe(video_codec="hevc", audio_codec="aac")) == "transcode"
+ assert plan_ingest(MediaProbe(video_codec=None, audio_codec="mp3")) == "audio_wrap"
+ with pytest.raises(VideoIngestError):
+ plan_ingest(MediaProbe(video_codec=None, audio_codec=None))
+
+
+def test_h264_foreign_container_is_remuxed(h264_mov: Path, tmp_path: Path) -> None:
+ dst = tmp_path / "out.mp4"
+ assert ingest_media_to_mp4(h264_mov, dst, max_output_bytes=GB) == "remux"
+ width, height, _duration, _fps, codec = probe_video_with_codec(dst)
+ assert (width, height, codec) == (64, 48, "h264")
+ pcm = extract_audio_pcm(dst)
+ assert pcm is not None, "the AAC track must survive the remux"
+
+
+def test_foreign_codec_is_transcoded_to_h264(mpeg4_avi: Path, tmp_path: Path) -> None:
+ dst = tmp_path / "out.mp4"
+ assert ingest_media_to_mp4(mpeg4_avi, dst, max_output_bytes=GB) == "transcode"
+ width, height, _duration, _fps, codec = probe_video_with_codec(dst)
+ assert (width, height, codec) == (64, 48, "h264")
+
+
+def test_odd_dimensions_are_evened_for_yuv420p(fixture_dir: Path, tmp_path: Path) -> None:
+ src = _make_media(
+ fixture_dir / "odd.avi",
+ *("-f", "lavfi", "-i", "testsrc2=s=63x47:r=8:d=1"),
+ *("-c:v", "mpeg4"),
+ )
+ dst = tmp_path / "out.mp4"
+ assert ingest_media_to_mp4(src, dst, max_output_bytes=GB) == "transcode"
+ width, height, _duration, _fps, codec = probe_video_with_codec(dst)
+ assert (width, height, codec) == (62, 46, "h264")
+
+
[email protected]("fixture_name", ["wav_audio", "m4a_audio"])
+def test_audio_only_uploads_are_wrapped_into_waveform_videos(
+ fixture_name: str, tmp_path: Path, request: pytest.FixtureRequest
+) -> None:
+ src: Path = request.getfixturevalue(fixture_name)
+ dst = tmp_path / "out.mp4"
+ assert ingest_media_to_mp4(src, dst, max_output_bytes=GB) == "audio_wrap"
+ width, height, duration, fps, codec = probe_video_with_codec(dst)
+ assert (width, height, codec) == (640, 360, "h264")
+ assert fps == 24.0
+ # The video track must span the audio (AAC priming may pad slightly past it).
+ assert 0.9 <= duration <= 1.5
+ pcm = extract_audio_pcm(dst)
+ assert pcm is not None
+
+
+def test_album_art_does_not_make_an_audio_file_a_video(fixture_dir: Path, tmp_path: Path) -> None:
+ """An m4a with embedded cover art carries a real (attached-pic) video stream; it must
+ still be classified audio-only and wrapped, not 'transcoded' into a still image."""
+ cover = _make_media(
+ fixture_dir / "cover_src.mp4",
+ *("-f", "lavfi", "-i", "testsrc2=s=64x48:r=1:d=1"),
+ *("-frames:v", "1", "-c:v", "mjpeg"),
+ )
+ src = fixture_dir / "with_art.m4a"
+ subprocess.run(
+ [
+ _ffmpeg_exe(),
+ *("-y", "-loglevel", "error"),
+ *("-f", "lavfi", "-i", "sine=frequency=330:d=1"),
+ *("-i", str(cover)),
+ *("-map", "0:a", "-map", "1:v"),
+ *("-c:a", "aac", "-c:v", "copy"),
+ *("-disposition:v:0", "attached_pic"),
+ # The ipod/m4a muxer refuses mjpeg streams; the plain mp4 muxer takes them,
+ # and readers sniff content rather than trusting the .m4a name.
+ *("-f", "mp4"),
+ str(src),
+ ],
+ check=True,
+ capture_output=True,
+ )
+ probe = probe_media_streams(src)
+ assert probe.video_codec is None, "attached cover art must not count as a video stream"
+
+ dst = tmp_path / "out.mp4"
+ assert ingest_media_to_mp4(src, dst, max_output_bytes=GB) == "audio_wrap"
+
+
+def test_unreadable_input_raises_user_safe_error(tmp_path: Path) -> None:
+ garbage = tmp_path / "garbage.mp3"
+ garbage.write_bytes(b"\x00" * 1024)
+ with pytest.raises(VideoIngestError):
+ ingest_media_to_mp4(garbage, tmp_path / "out.mp4", max_output_bytes=GB)
+ assert not (tmp_path / "out.mp4").exists() or (tmp_path / "out.mp4").stat().st_size == 0
+
+
+def test_output_size_cap_is_enforced(h264_mov: Path, tmp_path: Path) -> None:
+ with pytest.raises(VideoIngestError, match="maximum upload size"):
+ ingest_media_to_mp4(h264_mov, tmp_path / "out.mp4", max_output_bytes=64)