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
feat(video): embed generation metadata in MP4 files
Lincoln Stein70329866b0ce
diff --git a/docs/src/content/docs/concepts/video-generation.mdx b/docs/src/content/docs/concepts/video-generation.mdxindex 337b2b182b..32b78312d3 100644--- a/docs/src/content/docs/concepts/video-generation.mdx+++ b/docs/src/content/docs/concepts/video-generation.mdx@@ -1,7 +1,7 @@---title: Video Generationdescription: Generate short videos — with audio on MiniMax H3 — from the Video panel. Covers the panel's controls, the Wan 2.2 and MiniMax H3 model families, and how to make longer videos.-lastUpdated: 2026-09-16+lastUpdated: 2026-09-19---import { Card, CardGrid, Steps } from '@astrojs/starlight/components';@@ -128,6 +128,8 @@ If a Wan A14B pairing looks mis-wired — for example a low-noise-tagged file inVideo generations record their parameters as metadata. Select a video in the gallery and use **Recall parameters** (in the viewer's header or the context menu) to load its prompt, model, dimensions, frames, LoRAs, and conditioning back into the Video panel — the same round-trip the image panel offers. Media that no longer exists is cleared rather than silently substituted. The MiniMax H3 hybrid is part of the record too: recalling a hybrid video restores its base and start block, and recalling a video made without the hybrid clears the slot.+The record travels **inside the MP4**, the way an image's does inside its PNG. Download a video, upload it to any Invoke install — yours or someone else's — and **Recall parameters** works there too: models are matched by content hash when the other install's model keys differ, and conditioning media that only existed in the original gallery is simply left empty. The [Media Metadata](/development/architecture/media-metadata/) reference documents the record's fields and versioning.+---## The modelsdiff --git a/docs/src/content/docs/development/Architecture/media-metadata.mdx b/docs/src/content/docs/development/Architecture/media-metadata.mdxnew file mode 100644index 0000000000..63fbf494ff--- /dev/null+++ b/docs/src/content/docs/development/Architecture/media-metadata.mdx@@ -0,0 +1,137 @@+---+title: Media Metadata+description: How generation metadata travels inside PNG and MP4 files, the versioned record schema, and what a recall can restore on another install.+lastUpdated: 2026-09-19+---++Every image and video InvokeAI produces carries its generation record **inside the file**, so a+download dropped into any Invoke instance is recallable and remixable without access to the+database that produced it. This page is the reference for that contract: where the record lives+in each container, the record's fields, and how the format evolves.++## Envelope: three keys, two containers++The same three strings are written to every media file. Each value is compact UTF-8 JSON.++| Key | Content | Required |+|---|---|---|+| `invokeai_metadata` | The generation record (schema below) | when the graph produced one |+| `invokeai_workflow` | The `WorkflowWithoutID` the session ran, verbatim | only when a workflow was run |+| `invokeai_graph` | The executed `Graph`, verbatim | when available |++| Container | Where the keys live | Writer | Reader |+|---|---|---|---|+| PNG | `tEXt` chunks, one per key | `DiskImageFileStorage.save` via Pillow's `PngInfo` | `extract_metadata_from_image` reads `Image.info` |+| MP4 | QuickTime keyed metadata: `moov/udta/meta` with an `mdta` `keys` table and `ilst` UTF-8 `data` atoms | `DiskVideoFileStorage.save` remuxes through the bundled ffmpeg (`-movflags use_metadata_tags`, stream copy, `+faststart`) | `invokeai.app.util.mp4_metadata.read_mp4_tags`, a pure-Python box walk |++Both readers feed `extract_metadata` in `invokeai/app/api/extract_metadata.py`, which owns the+validation rules: the metadata must parse to a JSON object, the workflow must validate as a+`WorkflowWithoutID`, and the graph must be an object with a `nodes` object and an `edges` list.+Anything else degrades to "absent". On upload, a client-supplied `metadata` form field wins over+the embedded copy; workflow and graph are never client-overridable.++The MP4 layout is the one `ffprobe`, `exiftool` and `mediainfo` display. Like PNG chunks it+survives a container-aware copy — for ffmpeg that is a remux with `-movflags use_metadata_tags`;+a plain `-c copy` or a re-encode drops it.++:::note[Videos stored before embedding]+Videos saved by earlier releases keep their record in a JSON sidecar under+`outputs/videos/sidecars/`. The reader consults the MP4 first and the sidecar second; the sidecar+is also the fallback written when the remux fails, so a record is never lost to ffmpeg.+:::++## The record: `invokeai_metadata`++A flat JSON object, the output of the `core_metadata` node. Video is a *profile* of the same+record as images, discriminated by `generation_mode`, not a second format. Every key is+optional; readers ignore keys they do not know and never reject a record for having them.++Common shapes:++```+ModelIdentifier = { key, hash, name, base, type, submodel_type? }+ImageRef = { image_name }+VideoRef = { video_name }+LoRA = { model: ModelIdentifier, weight }+H3Reference = { kind: "image" | "video", image_name?, video_name?, detail?, conditioning?, start_frame?, end_frame? }+```++### Versioning++| Key | Type | Meaning |+|---|---|---|+| `metadata_version` | semver string | The record schema version, currently `1.0.0`. Absent on records written before versioning; they are read with the same rules plus the aliases listed below. |+| `app_version` | string | The InvokeAI release that wrote the record. Informational. |++The version is over the **record**, not the node that writes it. A **minor** bump adds keys or+widens a value set: any 1.x reader parses any other 1.x. A **major** bump renames, removes or+retypes a key. Readers are tolerant by construction: they read the keys they know, ignore the+rest, and never reject a record for its version, so a newer record still recalls what it can.+The current value is `CORE_METADATA_VERSION` in `invokeai/app/invocations/metadata.py`.++### Shared with images++| Key | Type |+|---|---|+| `generation_mode` | string. Video values: `wan_t2v`, `wan_i2v`, `wan_interpolate`, `wan_extend_video`, `minimax_h3_t2v`, `minimax_h3_i2v`, `minimax_h3_lf2v`, `minimax_h3_flf2v`, `minimax_h3_extend_video`, `minimax_h3_ref2v`. A record is video metadata iff this is one of them. |+| `positive_prompt`, `negative_prompt` | string; `negative_prompt` is absent for MiniMax H3, which has no CFG |+| `seed`, `steps` | integer |+| `cfg_scale` | number (Wan only) |+| `width`, `height` | integer |+| `model` | `ModelIdentifier`: the main (transformer) model |+| `vae` | `ModelIdentifier`: a standalone VAE override |+| `loras` | `LoRA[]` |++### Video profile++| Key | Type | Notes |+|---|---|---|+| `num_frames` | integer | |+| `fps` | integer | The delivered frame rate. MiniMax H3 records its fixed 24. |+| `first_frame_image`, `last_frame_image` | `ImageRef` | In extend mode the first frame is the one *extracted* from the source clip, so recall ignores it when `source_video` is set. |+| `source_video` | `VideoRef` | The clip an extension continues |+| `source_video_start_frame`, `source_video_end_frame` | integer | Inclusive trim bounds of the source clip |+| `wan_guidance_scale_low_noise` | number | The low-noise expert's CFG when it differed from `cfg_scale` |+| `wan_t5_encoder_model` | `ModelIdentifier` | Standalone UMT5-XXL used with a single-file Wan main |+| `wan_transformer_low_noise` | `ModelIdentifier` | Standalone low-noise expert used with a single-file Wan main |+| `wan_component_source` | `ModelIdentifier` | Wan Diffusers install that supplied VAE and encoder to a single-file main |+| `minimax_h3_transformer_model` | `ModelIdentifier` | Legacy: single-file transformer recorded as an override of a Diffusers `model` |+| `minimax_h3_text_encoder_model` | `ModelIdentifier` | Standalone Qwen3-VL text encoder |+| `minimax_h3_component_source` | `ModelIdentifier` | H3 Diffusers install that supplied VAEs and tokenizer to a single-file transformer |+| `minimax_h3_hybrid_base_model` | `ModelIdentifier` | The FL2VA transformer overlaid on a Ref2VA main |+| `minimax_h3_hybrid_start_block` | integer | First block taken from the hybrid base |+| `minimax_h3_references` | `H3Reference[]` | Ref2VA references in conditioning order |+| `media_origin` | string | Set by the upload route, not the graph: `audio_upload` marks an audio file wrapped into a video |++### Aliases read for pre-1.0 records++Earlier writers spelled three Wan keys differently. Readers accept both spellings; the current+graph builders write only the canonical ones.++| Canonical | Also read as |+|---|---|+| `wan_guidance_scale_low_noise` | `guidance_scale_low_noise` |+| `wan_t5_encoder_model` | `wan_t5_encoder` |+| `wan_transformer_low_noise` | `transformer_low_noise` |++## What a recall can restore elsewhere++- **Models** in a video record resolve against the local catalog by `key`, then by `hash`, then+ by `name` + `base` + `type`. Keys are minted per install, so a record that travelled with a file+ names keys the receiving catalog has never seen; the BLAKE3 hash is the content identity and+ resolves the same weights wherever they are installed. The name step is the last resort and the+ only one that can pick a different file of the same model. Image recall still resolves by key+ only.+- **Media references** (`image_name`, `video_name`) are names in the originating gallery, exactly+ as an image record's `init_image` is. Recall restores everything else and clears media it+ cannot find rather than substituting.+- **Workflow and graph** load into the editor on any install, subject to the same model and+ media resolution.++## Evolving the record++1. Add a typed `Optional` field to `CoreMetadataInvocation` under its canonical name, stamp it from+ the graph builder, and read it in the recall mappers.+2. Bump `CORE_METADATA_VERSION`'s minor component. Bump the major only for a rename, removal or+ type change, and add the old spelling to the readers' alias table.+3. Update the tables on this page.diff --git a/invokeai/app/api/extract_metadata.py b/invokeai/app/api/extract_metadata.pynew file mode 100644index 0000000000..04cc7579ea--- /dev/null+++ b/invokeai/app/api/extract_metadata.py@@ -0,0 +1,165 @@+"""Recovers the ``invokeai_metadata`` / ``invokeai_workflow`` / ``invokeai_graph`` strings a media+file carries, so an uploaded PNG or MP4 is recallable without the database that produced it.++PNGs hold the three keys as text chunks; MP4s hold them as QuickTime keyed metadata (see+``invokeai.app.util.mp4_metadata``). Both are stringified JSON written by this application,+so the validation is the same for either source and lives in ``extract_metadata``.+"""++import json+import logging+from collections.abc import Mapping+from dataclasses import dataclass+from pathlib import Path++from PIL import Image++from invokeai.app.services.video_files.video_files_common import (+ EMBEDDED_METADATA_KEYS,+ GRAPH_KEY,+ METADATA_KEY,+ WORKFLOW_KEY,+)+from invokeai.app.services.workflow_records.workflow_records_common import WorkflowWithoutIDValidator+from invokeai.app.util.mp4_metadata import read_mp4_tags+++@dataclass+class ExtractedMetadata:+ invokeai_metadata: str | None+ invokeai_workflow: str | None+ invokeai_graph: str | None+++def extract_metadata(+ embedded: Mapping[str, object],+ invokeai_metadata_override: str | None,+ invokeai_workflow_override: str | None,+ invokeai_graph_override: str | None,+ logger: logging.Logger,+) -> ExtractedMetadata:+ """+ Validates the "invokeai_metadata", "invokeai_workflow", and "invokeai_graph" strings found in a media file.++ ``embedded`` maps those keys to whatever the file carried. Each value is expected to be stringified JSON; a value+ that is missing, not a string, or fails validation is returned as None. Values are returned as they came (as+ strings), never re-serialized.++ In some situations, we may prefer to override the values extracted from the file with some other values. For+ example, when uploading via API, the client can optionally provide the metadata directly in the request, as+ opposed to embedding it in the file. In this case, the client-provided metadata will be used instead of the+ embedded metadata.+ """++ # The fallback value for metadata is None.+ stringified_metadata: str | None = None++ metadata_raw = invokeai_metadata_override if invokeai_metadata_override is not None else embedded.get(METADATA_KEY)++ # When we create media, we always store metadata as a stringified JSON dict. So, we expect it to be a string here.+ if isinstance(metadata_raw, str):+ try:+ # Must be a JSON string+ metadata_parsed = json.loads(metadata_raw)+ # Must be a dict+ if isinstance(metadata_parsed, dict):+ # Looks good, overwrite the fallback value+ stringified_metadata = metadata_raw+ except Exception as e:+ logger.debug(f"Failed to parse metadata for uploaded media, {e}")+ pass++ # We expect the workflow, if embedded, to be a JSON-stringified WorkflowWithoutID. We will store it as a string.+ workflow_raw = invokeai_workflow_override if invokeai_workflow_override is not None else embedded.get(WORKFLOW_KEY)++ # The fallback value for workflow is None.+ stringified_workflow: str | None = None++ if isinstance(workflow_raw, str):+ try:+ # Validate the workflow JSON before storing it+ WorkflowWithoutIDValidator.validate_json(workflow_raw)+ # Looks good, overwrite the fallback value+ stringified_workflow = workflow_raw+ except Exception:+ logger.debug("Failed to parse workflow for uploaded media")+ pass++ # We expect the graph, if embedded, to be a JSON-stringified Graph. We will store it as a string.+ graph_raw = invokeai_graph_override if invokeai_graph_override is not None else embedded.get(GRAPH_KEY)++ # The fallback value for graph is None.+ stringified_graph: str | None = None++ if isinstance(graph_raw, str):+ try:+ # TODO(psyche): Due to pydantic's handling of None values, it is possible for the graph to fail validation,+ # even if it is a direct dump of a valid graph. Node fields in the graph are allowed to have be unset if+ # they have incoming connections, but something about the ser/de process cannot adequately handle this.+ #+ # In lieu of fixing the graph validation, we will just do a simple check here to see if the graph is dict+ # with the correct keys. This is not a perfect solution, but it should be good enough for now.++ # FIX ME: Validate the graph JSON before storing it+ # Graph.model_validate_json(graph_raw)++ # Crappy workaround to validate JSON+ graph_parsed = json.loads(graph_raw)+ if not isinstance(graph_parsed, dict):+ raise ValueError("Not a dict")+ if not isinstance(graph_parsed.get("nodes", None), dict):+ raise ValueError("'nodes' is not a dict")+ if not isinstance(graph_parsed.get("edges", None), list):+ raise ValueError("'edges' is not a list")++ # Looks good, overwrite the fallback value+ stringified_graph = graph_raw+ except Exception as e:+ logger.debug(f"Failed to parse graph for uploaded media, {e}")+ pass++ return ExtractedMetadata(+ invokeai_metadata=stringified_metadata, invokeai_workflow=stringified_workflow, invokeai_graph=stringified_graph+ )+++def extract_metadata_from_image(+ pil_image: Image.Image,+ invokeai_metadata_override: str | None,+ invokeai_workflow_override: str | None,+ invokeai_graph_override: str | None,+ logger: logging.Logger,+) -> ExtractedMetadata:+ """Extracts and validates the metadata, workflow and graph embedded in a PIL Image's text chunks."""+ return extract_metadata(+ pil_image.info,+ invokeai_metadata_override,+ invokeai_workflow_override,+ invokeai_graph_override,+ logger,+ )+++def extract_metadata_from_video(+ video_path: Path,+ invokeai_metadata_override: str | None,+ invokeai_workflow_override: str | None,+ invokeai_graph_override: str | None,+ logger: logging.Logger,+) -> ExtractedMetadata:+ """Extracts and validates the metadata, workflow and graph embedded in an MP4's keyed metadata.++ A file that is not an MP4 or carries no tags simply yields all-None (or the overrides).+ """+ try:+ embedded = read_mp4_tags(video_path, keys=EMBEDDED_METADATA_KEYS)+ except OSError as e:+ logger.debug(f"Could not read embedded metadata from uploaded video, {e}")+ embedded = {}+ return extract_metadata(+ embedded,+ invokeai_metadata_override,+ invokeai_workflow_override,+ invokeai_graph_override,+ logger,+ )diff --git a/invokeai/app/api/extract_metadata_from_image.py b/invokeai/app/api/extract_metadata_from_image.pydeleted file mode 100644index 642a4b1bce..0000000000--- a/invokeai/app/api/extract_metadata_from_image.py+++ /dev/null@@ -1,134 +0,0 @@-import json-import logging-from dataclasses import dataclass--from PIL import Image--from invokeai.app.services.workflow_records.workflow_records_common import WorkflowWithoutIDValidator---@dataclass-class ExtractedMetadata:- invokeai_metadata: str | None- invokeai_workflow: str | None- invokeai_graph: str | None---def extract_metadata_from_image(- pil_image: Image.Image,- invokeai_metadata_override: str | None,- invokeai_workflow_override: str | None,- invokeai_graph_override: str | None,- logger: logging.Logger,-) -> ExtractedMetadata:- """- Extracts the "invokeai_metadata", "invokeai_workflow", and "invokeai_graph" data embedded in the PIL Image.-- These items are stored as stringified JSON in the image file's metadata, so we need to do some parsing to validate- them. Once parsed, the values are returned as they came (as strings), or None if they are not present or invalid.-- In some situations, we may prefer to override the values extracted from the image file with some other values.-- For example, when uploading an image via API, the client can optionally provide the metadata directly in the request,- as opposed to embedding it in the image file. In this case, the client-provided metadata will be used instead of the- metadata embedded in the image file.-- Args:- pil_image: The PIL Image object.- invokeai_metadata_override: The metadata override provided by the client.- invokeai_workflow_override: The workflow override provided by the client.- invokeai_graph_override: The graph override provided by the client.- logger: The logger to use for debug logging.-- Returns:- ExtractedMetadata: The extracted metadata, workflow, and graph.- """-- # The fallback value for metadata is None.- stringified_metadata: str | None = None-- # Use the metadata override if provided, else attempt to extract it from the image file.- metadata_raw = (- invokeai_metadata_override- if invokeai_metadata_override is not None- else pil_image.info.get("invokeai_metadata", None)- )-- # If the metadata is present in the image file, we will attempt to parse it as JSON. When we create images,- # we always store metadata as a stringified JSON dict. So, we expect it to be a string here.- if isinstance(metadata_raw, str):- try:- # Must be a JSON string- metadata_parsed = json.loads(metadata_raw)- # Must be a dict- if isinstance(metadata_parsed, dict):- # Looks good, overwrite the fallback value- stringified_metadata = metadata_raw- except Exception as e:- logger.debug(f"Failed to parse metadata for uploaded image, {e}")- pass-- # We expect the workflow, if embedded in the image, to be a JSON-stringified WorkflowWithoutID. We will store it- # as a string.- workflow_raw: str | None = (- invokeai_workflow_override- if invokeai_workflow_override is not None- else pil_image.info.get("invokeai_workflow", None)- )-- # The fallback value for workflow is None.- stringified_workflow: str | None = None-- # If the workflow is present in the image file, we will attempt to parse it as JSON. When we create images, we- # always store workflows as a stringified JSON WorkflowWithoutID. So, we expect it to be a string here.- if isinstance(workflow_raw, str):- try:- # Validate the workflow JSON before storing it- WorkflowWithoutIDValidator.validate_json(workflow_raw)- # Looks good, overwrite the fallback value- stringified_workflow = workflow_raw- except Exception:- logger.debug("Failed to parse workflow for uploaded image")- pass-- # We expect the workflow, if embedded in the image, to be a JSON-stringified Graph. We will store it as a- # string.- graph_raw: str | None = (- invokeai_graph_override if invokeai_graph_override is not None else pil_image.info.get("invokeai_graph", None)- )-- # The fallback value for graph is None.- stringified_graph: str | None = None-- # If the graph is present in the image file, we will attempt to parse it as JSON. When we create images, we- # always store graphs as a stringified JSON Graph. So, we expect it to be a string here.- if isinstance(graph_raw, str):- try:- # TODO(psyche): Due to pydantic's handling of None values, it is possible for the graph to fail validation,- # even if it is a direct dump of a valid graph. Node fields in the graph are allowed to have be unset if- # they have incoming connections, but something about the ser/de process cannot adequately handle this.- #- # In lieu of fixing the graph validation, we will just do a simple check here to see if the graph is dict- # with the correct keys. This is not a perfect solution, but it should be good enough for now.-- # FIX ME: Validate the graph JSON before storing it- # Graph.model_validate_json(graph_raw)-- # Crappy workaround to validate JSON- graph_parsed = json.loads(graph_raw)- if not isinstance(graph_parsed, dict):- raise ValueError("Not a dict")- if not isinstance(graph_parsed.get("nodes", None), dict):- raise ValueError("'nodes' is not a dict")- if not isinstance(graph_parsed.get("edges", None), list):- raise ValueError("'edges' is not a list")-- # Looks good, overwrite the fallback value- stringified_graph = graph_raw- except Exception as e:- logger.debug(f"Failed to parse graph for uploaded image, {e}")- pass-- return ExtractedMetadata(- invokeai_metadata=stringified_metadata, invokeai_workflow=stringified_workflow, invokeai_graph=stringified_graph- )diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.pyindex cda754164b..c7ce34e49c 100644--- a/invokeai/app/api/routers/images.py+++ b/invokeai/app/api/routers/images.py@@ -13,7 +13,7 @@ from pydantic import BaseModel, Field, StringConstraints, model_validatorfrom invokeai.app.api.auth_dependencies import CurrentMediaUserOrDefault, CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependencies-from invokeai.app.api.extract_metadata_from_image import extract_metadata_from_image+from invokeai.app.api.extract_metadata import extract_metadata_from_imagefrom invokeai.app.api.routers._access import (assert_board_read_access as _assert_board_read_access,)diff --git a/invokeai/app/api/routers/videos.py b/invokeai/app/api/routers/videos.pyindex b830f396fa..5ec8ddfe32 100644--- a/invokeai/app/api/routers/videos.py+++ b/invokeai/app/api/routers/videos.py@@ -20,6 +20,7 @@ from starlette.requests import ClientDisconnectfrom invokeai.app.api.auth_dependencies import CurrentMediaUserOrDefault, CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.api.extract_metadata import extract_metadata_from_videofrom invokeai.app.api.routers._access import (assert_board_read_access as _assert_board_read_access,)@@ -52,6 +53,7 @@ from invokeai.app.services.videos.videos_common import (VideoDTO,VideoUrlsDTO,)+from invokeai.app.util.mp4_metadata import read_ftyp_major_brandfrom invokeai.app.util.video_ingest import VideoIngestError, ingest_media_to_mp4, probe_media_streamsfrom invokeai.app.util.video_thumbnails import (VideoDecodeTimeoutError,@@ -121,7 +123,8 @@ MAX_UPLOAD_REQUEST_SIZE = MAX_UPLOAD_SIZE + 10 * 1024 * 1024MAX_UPLOAD_METADATA_SIZE = 1024 * 1024# Global bound on concurrent video uploads — each in-flight upload holds one full-size copy# of the file in temp storage until probe/thumbnail/create finish with it, and a second (also-# capped at MAX_UPLOAD_SIZE) while the ingest converter is writing its output.+# capped at MAX_UPLOAD_SIZE) while the ingest converter is writing its output or, inside+# create(), while the metadata remux writes its replacement next to the stored file.MAX_CONCURRENT_VIDEO_UPLOADS = 2# Per-user bound (multiuser mode only): keeps one tenant's slow uploads from holding# every global slot and starving the other users into 429s.@@ -353,30 +356,10 @@ async def _stream_video_upload(request: Request, destination: BinaryIO) -> _Videdef _is_mp4_file(path: Path) -> bool:try:- with open(path, "rb") as video_file:- search_limit = min(path.stat().st_size, 64 * 1024)- position = 0- while position + 8 <= search_limit:- video_file.seek(position)- header = video_file.read(8)- box_size = int.from_bytes(header[:4], byteorder="big")- box_type = header[4:8]- header_size = 8- if box_size == 1:- extended_size = video_file.read(8)- if len(extended_size) != 8:- return False- box_size = int.from_bytes(extended_size, byteorder="big")- header_size = 16- if box_size < header_size:- return False- if box_type == b"ftyp":- major_brand = video_file.read(4)- return len(major_brand) == 4 and major_brand != b"qt "- position += box_size+ major_brand = read_ftyp_major_brand(path)except OSError:return False- return False+ return major_brand is not None and major_brand != b"qt "def _probe_decodable_video(path: Path) -> tuple[tuple[int, int, float, Optional[float]], Optional[PILImage.Image]]:@@ -474,14 +457,33 @@ async def upload_video(tmp.close()upload_kind = upload.upload_kind- metadata = upload.metadata- if metadata is not None:+ if upload.metadata is not None:try:- MetadataFieldValidator.validate_json(metadata)+ MetadataFieldValidator.validate_json(upload.metadata)except ValidationError as e:raise HTTPException(status_code=422, detail="Metadata must be a JSON object") from e- # Already-compliant H.264 MP4s pass through byte-identical (the historical path);+ # An MP4 that InvokeAI produced carries its metadata, workflow and graph as keyed metadata, the way a+ # PNG carries text chunks. Read them from the file as uploaded: the ingest remux below does not+ # preserve keyed metadata. As for images, client-supplied metadata wins over the embedded copy, while+ # workflow and graph are never client-overridable.+ extracted = await run_in_threadpool(+ extract_metadata_from_video,+ tmp_path,+ upload.metadata,+ None,+ None,+ ApiDependencies.invoker.services.logger,+ )+ metadata = extracted.invokeai_metadata+ if metadata is not None and len(metadata.encode("utf-8")) > MAX_UPLOAD_METADATA_SIZE:+ # The form field is capped while it streams; an embedded record gets the same bound+ # before it reaches the database. Workflow and graph legitimately run larger.+ ApiDependencies.invoker.services.logger.info("Ignoring oversized metadata embedded in uploaded video")+ metadata = None++ # Already-compliant H.264 MP4s skip conversion (their only rewrite is the metadata+ # remux inside create(), and only when there is a record to embed);# 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@@ -537,8 +539,8 @@ async def upload_video(session_id=session_id,board_id=board_id,metadata=metadata,- workflow=None,- graph=None,+ workflow=extracted.invokeai_workflow,+ graph=extracted.invokeai_graph,is_intermediate=is_intermediate,user_id=current_user.user_id,)diff --git a/invokeai/app/invocations/metadata.py b/invokeai/app/invocations/metadata.pyindex 139243dc88..5c172d6d8d 100644--- a/invokeai/app/invocations/metadata.py+++ b/invokeai/app/invocations/metadata.py@@ -213,12 +213,20 @@ class MiniMaxH3ReferenceMetadataField(BaseModel):end_frame: Optional[int] = Field(default=None, description="A video reference's trim end (inclusive).")+# The version of the metadata record `core_metadata` emits, stamped as `metadata_version`. It is+# semver over the *record*, not this node: a minor bump adds keys (any 1.x reader parses any+# other 1.x, ignoring unknown keys); a major bump renames, removes or retypes one. A record+# without the key predates versioning and is read with the same rules. Documented, with the+# field table, in docs/development/Architecture/media-metadata.+CORE_METADATA_VERSION = "1.0.0"++@invocation("core_metadata",title="Core Metadata",tags=["metadata"],category="metadata",- version="2.5.0",+ version="2.6.0",classification=Classification.Internal,)class CoreMetadataInvocation(BaseInvocation):@@ -306,6 +314,34 @@ class CoreMetadataInvocation(BaseInvocation):default=None,description="The video this generation was derived from, e.g. the clip an extend workflow continues",)+ source_video_start_frame: Optional[int] = InputField(+ default=None,+ description="The first frame (inclusive) of the source video that was kept",+ )+ source_video_end_frame: Optional[int] = InputField(+ default=None,+ description="The last frame (inclusive) of the source video that was kept",+ )+ fps: Optional[int] = InputField(+ default=None,+ description="The frame rate of the generated video",+ )+ wan_guidance_scale_low_noise: Optional[float] = InputField(+ default=None,+ description="The classifier-free guidance scale used by the Wan low-noise expert, when it differed",+ )+ wan_t5_encoder_model: Optional[ModelIdentifierField] = InputField(+ default=None,+ description="The standalone UMT5-XXL encoder used with a single-file Wan main model",+ )+ wan_transformer_low_noise: Optional[ModelIdentifierField] = InputField(+ default=None,+ description="The standalone low-noise expert used with a single-file Wan main model",+ )+ wan_component_source: Optional[ModelIdentifierField] = InputField(+ default=None,+ description="The Wan Diffusers install whose VAE and encoder served a single-file main model",+ )minimax_h3_transformer_model: Optional[ModelIdentifierField] = InputField(default=None,description="The single-file MiniMax H3 transformer used in place of the main model's transformer",@@ -314,6 +350,18 @@ class CoreMetadataInvocation(BaseInvocation):default=None,description="The single-file MiniMax H3 Qwen3-VL text encoder used in place of the main model's",)+ minimax_h3_component_source: Optional[ModelIdentifierField] = InputField(+ default=None,+ description="The MiniMax H3 Diffusers install whose VAEs and encoder served a single-file transformer",+ )+ minimax_h3_hybrid_base_model: Optional[ModelIdentifierField] = InputField(+ default=None,+ description="The FL2VA transformer whose later blocks overlaid the Ref2VA transformer (the hybrid)",+ )+ minimax_h3_hybrid_start_block: Optional[int] = InputField(+ default=None,+ description="The first transformer block taken from the hybrid base",+ )minimax_h3_references: Optional[list[MiniMaxH3ReferenceMetadataField]] = InputField(default=None,description="The ordered Ref2VA references this generation was conditioned on (names and options only; "@@ -380,6 +428,7 @@ class CoreMetadataInvocation(BaseInvocation):as_dict = self.model_dump(exclude_none=True, exclude={"id", "type", "is_intermediate", "use_cache"})as_dict["app_version"] = __version__+ as_dict["metadata_version"] = CORE_METADATA_VERSIONreturn MetadataOutput(metadata=MetadataField.model_validate(as_dict))diff --git a/invokeai/app/services/video_files/video_files_base.py b/invokeai/app/services/video_files/video_files_base.pyindex f9570aa267..287430995d 100644--- a/invokeai/app/services/video_files/video_files_base.py+++ b/invokeai/app/services/video_files/video_files_base.py@@ -64,12 +64,12 @@ class VideoFileStorageBase(ABC):@abstractmethoddef get_workflow(self, video_name: str, video_subfolder: str = "") -> Optional[str]:- """Gets the workflow JSON sidecar of a video, if any."""+ """Gets the workflow JSON embedded in (or stored beside) a video, if any."""pass@abstractmethoddef get_graph(self, video_name: str, video_subfolder: str = "") -> Optional[str]:- """Gets the graph JSON sidecar of a video, if any."""+ """Gets the graph JSON embedded in (or stored beside) a video, if any."""pass@abstractmethoddiff --git a/invokeai/app/services/video_files/video_files_common.py b/invokeai/app/services/video_files/video_files_common.pyindex 4743d8a7cc..dd084242df 100644--- a/invokeai/app/services/video_files/video_files_common.py+++ b/invokeai/app/services/video_files/video_files_common.py@@ -17,3 +17,11 @@ class VideoFileDeleteException(Exception):def __init__(self, message="Video file not deleted"):super().__init__(message)+++# The three keys a media file carries its generation record under — PNG text chunks, MP4 keyed+# metadata and the legacy JSON sidecar all use the same names.+METADATA_KEY = "invokeai_metadata"+WORKFLOW_KEY = "invokeai_workflow"+GRAPH_KEY = "invokeai_graph"+EMBEDDED_METADATA_KEYS = (METADATA_KEY, WORKFLOW_KEY, GRAPH_KEY)diff --git a/invokeai/app/services/video_files/video_files_disk.py b/invokeai/app/services/video_files/video_files_disk.pyindex 66b32b8644..e9ff34236c 100644--- a/invokeai/app/services/video_files/video_files_disk.py+++ b/invokeai/app/services/video_files/video_files_disk.py@@ -11,10 +11,15 @@ from PIL import Imagefrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.video_files.video_files_base import VideoFileStorageBasefrom invokeai.app.services.video_files.video_files_common import (+ EMBEDDED_METADATA_KEYS,+ GRAPH_KEY,+ METADATA_KEY,+ WORKFLOW_KEY,VideoFileDeleteException,VideoFileNotFoundException,VideoFileSaveException,)+from invokeai.app.util.mp4_metadata import read_mp4_tags, write_mp4_tagsfrom invokeai.app.util.thumbnails import make_thumbnailfrom invokeai.app.util.video_thumbnails import extract_representative_video_frame, get_video_thumbnail_namefrom invokeai.backend.util.logging import InvokeAILogger@@ -26,10 +31,18 @@ class _StagedDelete:files: list[tuple[Path, Path]]+# Prefix of the same-directory temp file a metadata remux writes before replacing the video.+_EMBED_TEMP_PREFIX = ".embed_"++class DiskVideoFileStorage(VideoFileStorageBase):"""Stores video files on disk under {outputs}/videos/, with representative-frame WebP thumbnails under- {outputs}/videos/thumbnails/ and optional JSON sidecars for metadata/workflow/graph under- {outputs}/videos/sidecars/."""+ {outputs}/videos/thumbnails/.++ Metadata, workflow and graph are embedded in the MP4 itself as keyed metadata (the same three keys a PNG+ carries as text chunks), so a downloaded video stays recallable anywhere. A JSON sidecar under+ {outputs}/videos/sidecars/ is written only when embedding fails, and is still read for videos stored before+ embedding existed."""def __init__(self, output_folder: Union[str, Path]):self.__output_folder = output_folder if isinstance(output_folder, Path) else Path(output_folder)@@ -40,6 +53,7 @@ class DiskVideoFileStorage(VideoFileStorageBase):def start(self, invoker: Invoker) -> None:self.__invoker = invokerself.__recover_staged_deletes()+ self.__sweep_embed_temps()def save(self,@@ -75,6 +89,13 @@ class DiskVideoFileStorage(VideoFileStorageBase):shutil.copy2(str(source_path), str(video_path))logger.info(f"Video file written: {video_path}")+ tags = {+ key: value+ for key, value in ((METADATA_KEY, metadata), (WORKFLOW_KEY, workflow), (GRAPH_KEY, graph))+ if value is not None+ }+ embedded = self.__embed_tags(video_path, tags)+thumbnail_name = get_video_thumbnail_name(video_name)thumbnail_path = self.get_path(thumbnail_name, thumbnail=True, video_subfolder=video_subfolder)thumbnail_path.parent.mkdir(parents=True, exist_ok=True)@@ -101,13 +122,15 @@ class DiskVideoFileStorage(VideoFileStorageBase):f"Could not extract a thumbnail frame for {video_name}; gallery thumbnail will be missing.")- if metadata is not None or workflow is not None or graph is not None:+ if tags and not embedded:+ # Nothing recallable may be lost to a remux failure: fall back to the sidecar the reader+ # still understands.sidecar_path = self.__get_sidecar_path(video_name, video_subfolder=video_subfolder)sidecar_path.parent.mkdir(parents=True, exist_ok=True)sidecar = {- "invokeai_metadata": metadata,- "invokeai_workflow": workflow,- "invokeai_graph": graph,+ METADATA_KEY: metadata,+ WORKFLOW_KEY: workflow,+ GRAPH_KEY: graph,}with open(sidecar_path, "w", encoding="utf-8") as f:json.dump(sidecar, f)@@ -192,18 +215,60 @@ class DiskVideoFileStorage(VideoFileStorageBase):return resolved_video_pathdef get_workflow(self, video_name: str, video_subfolder: str = "") -> Optional[str]:- sidecar = self.__read_sidecar(video_name, video_subfolder)- if sidecar is None:- return None- workflow = sidecar.get("invokeai_workflow")- return workflow if isinstance(workflow, str) else None+ return self.__read_embedded_or_sidecar(video_name, WORKFLOW_KEY, video_subfolder)def get_graph(self, video_name: str, video_subfolder: str = "") -> Optional[str]:+ return self.__read_embedded_or_sidecar(video_name, GRAPH_KEY, video_subfolder)++ def __embed_tags(self, video_path: Path, tags: dict[str, str]) -> bool:+ """Make ``video_path``'s keyed metadata carry exactly ``tags`` — the record being saved, which+ may be empty. False (and a warning) on any failure, leaving the original file untouched so the+ caller can fall back to a sidecar."""+ logger = InvokeAILogger.get_logger()+ tmp_path: Optional[Path] = None+ try:+ # A file that already carries exactly this record (a re-uploaded InvokeAI download, or an+ # untagged file saved without one) needs no rewrite. A file carrying a key the record lacks+ # — an upload whose embedded workflow failed validation — is rewritten so the rejected value+ # cannot be read back as the record.+ if read_mp4_tags(video_path, keys=EMBEDDED_METADATA_KEYS) == tags:+ return True+ # Same directory, so the final os.replace is an atomic rename and never a cross-device copy.+ fd, tmp_name = tempfile.mkstemp(prefix=_EMBED_TEMP_PREFIX, suffix=".mp4", dir=video_path.parent)+ os.close(fd)+ tmp_path = Path(tmp_name)+ write_mp4_tags(video_path, tmp_path, tags)+ os.replace(tmp_path, video_path)+ return True+ except Exception as e:+ logger.warning(f"Could not embed metadata in {video_path.name}; writing a sidecar instead: {e}")+ return False+ finally:+ if tmp_path is not None:+ tmp_path.unlink(missing_ok=True)++ def __sweep_embed_temps(self) -> None:+ """Remove remux temp files a crash left behind: they are never referenced by a record."""+ for stale in self.__output_folder.rglob(f"{_EMBED_TEMP_PREFIX}*.mp4"):+ try:+ stale.unlink()+ except OSError as e:+ InvokeAILogger.get_logger().warning(f"Could not remove stale metadata temp file {stale}: {e}")++ def __read_embedded_or_sidecar(self, video_name: str, key: str, video_subfolder: str) -> Optional[str]:+ video_path = self.get_path(video_name, video_subfolder=video_subfolder)+ if video_path.exists():+ try:+ value = read_mp4_tags(video_path, keys=(key,)).get(key)+ except OSError as e:+ raise VideoFileNotFoundException from e+ if value is not None:+ return valuesidecar = self.__read_sidecar(video_name, video_subfolder)if sidecar is None:return None- graph = sidecar.get("invokeai_graph")- return graph if isinstance(graph, str) else None+ value = sidecar.get(key)+ return value if isinstance(value, str) else Nonedef validate_path(self, path: Union[str, Path]) -> bool:path = path if isinstance(path, Path) else Path(path)diff --git a/invokeai/app/services/workflow_records/default_workflows/Extend Video - MiniMax H3.json b/invokeai/app/services/workflow_records/default_workflows/Extend Video - MiniMax H3.jsonindex 1a3dc29ec7..c8c7b7bb31 100644--- a/invokeai/app/services/workflow_records/default_workflows/Extend Video - MiniMax H3.json+++ b/invokeai/app/services/workflow_records/default_workflows/Extend Video - MiniMax H3.json@@ -338,7 +338,7 @@"type": "invocation","data": {"id": "9e2b5033-4c5d-4e7f-a081-9c0d1e2f3a04",- "version": "2.5.0",+ "version": "2.6.0","nodePack": "invokeai","label": "Core Metadata","notes": "Everything except the generation mode arrives over an edge from the node that used the value, so the record cannot go stale.",diff --git a/invokeai/app/services/workflow_records/default_workflows/First Frame to Video - MiniMax H3.json b/invokeai/app/services/workflow_records/default_workflows/First Frame to Video - MiniMax H3.jsonindex 3acda8b4df..c9103c3a32 100644--- a/invokeai/app/services/workflow_records/default_workflows/First Frame to Video - MiniMax H3.json+++ b/invokeai/app/services/workflow_records/default_workflows/First Frame to Video - MiniMax H3.json@@ -330,7 +330,7 @@"type": "invocation","data": {"id": "9e2b5033-4c5d-4e7f-a081-9c0d1e2f3a04",- "version": "2.5.0",+ "version": "2.6.0","nodePack": "invokeai","label": "Core Metadata","notes": "Everything except the generation mode arrives over an edge from the node that used the value, so the record cannot go stale.",diff --git a/invokeai/app/services/workflow_records/default_workflows/First and Last Frame to Video - MiniMax H3.json b/invokeai/app/services/workflow_records/default_workflows/First and Last Frame to Video - MiniMax H3.jsonindex 76b7d50d6c..c8899368e0 100644--- a/invokeai/app/services/workflow_records/default_workflows/First and Last Frame to Video - MiniMax H3.json+++ b/invokeai/app/services/workflow_records/default_workflows/First and Last Frame to Video - MiniMax H3.json@@ -334,7 +334,7 @@"type": "invocation","data": {"id": "9e2b5033-4c5d-4e7f-a081-9c0d1e2f3a04",- "version": "2.5.0",+ "version": "2.6.0","nodePack": "invokeai","label": "Core Metadata","notes": "Everything except the generation mode arrives over an edge from the node that used the value, so the record cannot go stale.",diff --git a/invokeai/app/services/workflow_records/default_workflows/Last Frame to Video - MiniMax H3.json b/invokeai/app/services/workflow_records/default_workflows/Last Frame to Video - MiniMax H3.jsonindex dccbe2cc61..404bde6e2c 100644--- a/invokeai/app/services/workflow_records/default_workflows/Last Frame to Video - MiniMax H3.json+++ b/invokeai/app/services/workflow_records/default_workflows/Last Frame to Video - MiniMax H3.json@@ -330,7 +330,7 @@"type": "invocation","data": {"id": "9e2b5033-4c5d-4e7f-a081-9c0d1e2f3a04",- "version": "2.5.0",+ "version": "2.6.0","nodePack": "invokeai","label": "Core Metadata","notes": "Everything except the generation mode arrives over an edge from the node that used the value, so the record cannot go stale.",diff --git a/invokeai/app/services/workflow_records/default_workflows/Reference to Video - MiniMax H3.json b/invokeai/app/services/workflow_records/default_workflows/Reference to Video - MiniMax H3.jsonindex cfadad69a7..ef12672bc2 100644--- a/invokeai/app/services/workflow_records/default_workflows/Reference to Video - MiniMax H3.json+++ b/invokeai/app/services/workflow_records/default_workflows/Reference to Video - MiniMax H3.json@@ -380,7 +380,7 @@"type": "invocation","data": {"id": "9e2b5033-4c5d-4e7f-a081-9c0d1e2f3a04",- "version": "2.5.0",+ "version": "2.6.0","nodePack": "invokeai","label": "Core Metadata","notes": "Everything except the generation mode arrives over an edge from the node that used the value, so the record cannot go stale.",diff --git a/invokeai/app/services/workflow_records/default_workflows/Text to Video - MiniMax H3.json b/invokeai/app/services/workflow_records/default_workflows/Text to Video - MiniMax H3.jsonindex 8fc404b8cb..b9e62cf832 100644--- a/invokeai/app/services/workflow_records/default_workflows/Text to Video - MiniMax H3.json+++ b/invokeai/app/services/workflow_records/default_workflows/Text to Video - MiniMax H3.json@@ -334,7 +334,7 @@"type": "invocation","data": {"id": "9e2b5033-4c5d-4e7f-a081-9c0d1e2f3a04",- "version": "2.5.0",+ "version": "2.6.0","nodePack": "invokeai","label": "Core Metadata","notes": "Everything except the generation mode arrives over an edge from the node that used the value, so the record cannot go stale.",diff --git a/invokeai/app/util/mp4_metadata.py b/invokeai/app/util/mp4_metadata.pynew file mode 100644index 0000000000..1b1b6e32d4--- /dev/null+++ b/invokeai/app/util/mp4_metadata.py@@ -0,0 +1,286 @@+"""Generation metadata carried inside MP4 files.++Images carry their ``invokeai_metadata`` / ``invokeai_workflow`` / ``invokeai_graph`` JSON as+PNG text chunks, so a file dragged into any Invoke instance is recallable. This module gives+MP4s the same property: the three strings are stored as QuickTime *keyed metadata* — the+``moov/udta/meta`` box with an ``mdta`` ``keys`` table and an ``ilst`` of UTF-8 ``data``+atoms. That is the layout ffmpeg writes for ``-movflags use_metadata_tags`` and the one+ffprobe, exiftool and mediainfo display, so the tags are inspectable with ordinary tools. Like+PNG text chunks they survive a container-aware copy — an ffmpeg remux that passes+``-movflags use_metadata_tags`` — and not a plain ``-c copy`` or a re-encode.++Writing goes through the bundled ffmpeg as a stream-copy remux: hand-inserting a box into+``moov`` would mean re-pointing every chunk offset table when ``moov`` precedes ``mdat``.+The file's own global tags are replaced by ours (``-map_metadata``); per-stream metadata is+kept. The values travel in an *ffmetadata* file rather than ``-metadata`` arguments because+a graph JSON routinely exceeds the per-argument (Linux, 128 KiB) and whole-command-line+(Windows, 32 K) limits.++Reading is a pure-Python box walk: the bundled ffmpeg ships without ffprobe, and walking by+box sizes costs a handful of seeks regardless of file size (``mdat`` is skipped, never read).+"""++import struct+import subprocess+import tempfile+from collections.abc import Collection, Iterator, Mapping+from pathlib import Path+from typing import BinaryIO, Optional++import imageio_ffmpeg++# A single tag is a JSON string the app itself produced; a graph JSON is the largest and+# runs to a few hundred KiB. The cap exists only so a hostile file cannot make the reader+# allocate its declared box size.+MAX_TAG_BYTES = 8 * 1024 * 1024+# ``keys`` is a table of short names; a hostile count or name length is refused, not read.+_MAX_KEYS = 4096+_MAX_KEY_NAME_BYTES = 1024+# A real file has a dozen top-level boxes at most, and ``moov`` precedes every fragment in a+# 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+# 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++_UTF8_TYPE_INDICATOR = 1+_FFMETADATA_HEADER = ";FFMETADATA1\n"+++class Mp4MetadataError(RuntimeError):+ """The MP4 could not be rewritten with the requested tags."""+++def _ffmpeg_exe() -> str:+ return imageio_ffmpeg.get_ffmpeg_exe()+++def _iter_boxes(+ fh: BinaryIO, start: int, end: int, max_boxes: Optional[int] = None+) -> Iterator[tuple[bytes, int, int]]:+ """Yield ``(type, payload_start, payload_end)`` for each box in ``[start, end)``.++ Stops silently at the first structurally impossible box (size smaller than its own+ header, or one that overruns ``end``), which is how a truncated or non-MP4 file reads as+ "no tags" rather than raising. ``max_boxes`` stops the walk after that many boxes.+ """+ position = start+ seen = 0+ while position + 8 <= end and (max_boxes is None or seen < max_boxes):+ seen += 1+ fh.seek(position)+ header = fh.read(8)+ if len(header) < 8:+ return+ size = int.from_bytes(header[:4], "big")+ box_type = header[4:8]+ header_size = 8+ if size == 1:+ extended = fh.read(8)+ if len(extended) < 8:+ return+ size = int.from_bytes(extended, "big")+ header_size = 16+ elif size == 0:+ # "Extends to end of file" — legal only for the last top-level box.+ size = end - position+ if size < header_size or position + size > end:+ return+ yield box_type, position + header_size, position + size+ position += size+++def _find_box(+ fh: BinaryIO, start: int, end: int, box_type: bytes, max_boxes: Optional[int] = None+) -> Optional[tuple[int, int]]:+ for found_type, payload_start, payload_end in _iter_boxes(fh, start, end, max_boxes):+ if found_type == box_type:+ return payload_start, payload_end+ return None+++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 in+ QuickTime files. Disambiguate the way ffmpeg does: if the bytes right after the header+ already spell a child box type, there is no version/flags word."""+ if start + 8 > end:+ return start+ fh.seek(start + 4)+ if fh.read(4) in (b"hdlr", b"keys", b"ilst", b"mhdr"):+ return start+ return start + 4+++def _read_keys(fh: BinaryIO, start: int, end: int) -> dict[int, str]:+ """The ``keys`` table: 1-based index → key name, ``mdta`` namespace only."""+ if start + 8 > end:+ return {}+ fh.seek(start)+ _version_flags, count = struct.unpack(">II", fh.read(8))+ if count > _MAX_KEYS:+ return {}+ keys: dict[int, str] = {}+ position = start + 8+ for index in range(1, count + 1):+ if position + 8 > end:+ break+ fh.seek(position)+ size, namespace = struct.unpack(">I4s", fh.read(8))+ if size < 8 or position + size > end:+ break+ if namespace == b"mdta" and size - 8 <= _MAX_KEY_NAME_BYTES:+ name = fh.read(size - 8)+ try:+ keys[index] = name.decode("utf-8")+ except UnicodeDecodeError:+ pass+ position += size+ return keys+++def _read_utf8_data(fh: BinaryIO, start: int, end: int) -> Optional[str]:+ """The first UTF-8 ``data`` atom of an ``ilst`` item, or None."""+ for box_type, payload_start, payload_end in _iter_boxes(fh, start, end):+ if box_type != b"data" or payload_end - payload_start < 8:+ continue+ fh.seek(payload_start)+ type_indicator, _locale = struct.unpack(">II", fh.read(8))+ if type_indicator != _UTF8_TYPE_INDICATOR:+ continue+ length = payload_end - payload_start - 8+ if length > MAX_TAG_BYTES:+ return None+ try:+ return fh.read(length).decode("utf-8")+ except UnicodeDecodeError:+ return None+ return None+++def read_mp4_tags(path: Path, keys: Optional[Collection[str]] = None) -> dict[str, str]:+ """Return the file's ``mdta`` keyed metadata as ``{key: value}`` for UTF-8 values.++ ``keys`` restricts the result (and the bytes read) to the named tags. A file that is not+ an MP4, has no keyed metadata, or is truncated yields ``{}``; only I/O errors propagate.+ """+ wanted = set(keys) if keys is not None else None+ result: dict[str, str] = {}+ with open(path, "rb") as fh:+ fh.seek(0, 2)+ file_size = fh.tell()+ moov = _find_box(fh, 0, file_size, b"moov", max_boxes=_MAX_TOP_LEVEL_BOXES)+ if moov is None:+ return result+ udta = _find_box(fh, *moov, b"udta")+ if udta is None:+ return result+ meta = _find_box(fh, *udta, b"meta")+ if meta is None:+ return result+ meta_start = _meta_payload_start(fh, *meta)+ keys_box = _find_box(fh, meta_start, meta[1], b"keys")+ ilst = _find_box(fh, meta_start, meta[1], b"ilst")+ if keys_box is None or ilst is None:+ return result+ names = _read_keys(fh, *keys_box)+ for item_type, item_start, item_end in _iter_boxes(fh, *ilst):+ name = names.get(int.from_bytes(item_type, "big"))+ if name is None or (wanted is not None and name not in wanted):+ continue+ value = _read_utf8_data(fh, item_start, item_end)+ if value is not None:+ result[name] = value+ return result+++def read_ftyp_major_brand(path: Path, search_limit: int = 64 * 1024) -> Optional[bytes]:+ """The ``ftyp`` major brand if a well-formed one appears within the first ``search_limit``+ bytes, else None."""+ with open(path, "rb") as fh:+ fh.seek(0, 2)+ end = min(fh.tell(), search_limit)+ for box_type, payload_start, payload_end in _iter_boxes(fh, 0, end):+ if box_type == b"ftyp":+ if payload_end - payload_start < 4:+ return None+ fh.seek(payload_start)+ return fh.read(4)+ return None+++def _escape_ffmetadata(value: str) -> str:+ # The ffmetadata grammar: '=', ';', '#', '\\' and line breaks are special in keys and+ # values; a backslash before a CR or LF continues the line, which is how both are carried.+ return (+ value.replace("\\", "\\\\")+ .replace("=", "\\=")+ .replace(";", "\\;")+ .replace("#", "\\#")+ .replace("\n", "\\\n")+ .replace("\r", "\\\r")+ )+++def write_mp4_tags(src: Path, dst: Path, tags: Mapping[str, str]) -> None:+ """Write ``dst`` = ``src``'s first video stream and every audio stream, stream-copied, with+ ``tags`` as the file's keyed metadata (replacing any global tags ``src`` had). An empty+ mapping therefore strips ``src``'s global tags.++ Subtitle, data and further video tracks are not carried: InvokeAI stores only what it+ serves, and the ingest path already narrows uploads the same way. ``dst`` is written with+ ``+faststart`` so progressive playback is preserved. Raises Mp4MetadataError when ffmpeg+ fails and ValueError for a tag the format cannot carry; ``dst`` may then be absent or+ partial and the caller owns cleanup.+ """+ if any(not key or "\r" in key or "\n" in key or value.endswith("\\") for key, value in tags.items()):+ # ffmpeg's ffmetadata reader treats any backslash right before the line break as a+ # continuation, escaped or not, so a value ending in a backslash would swallow the+ # next tag. JSON text never ends that way; the caller falls back to a sidecar.+ raise ValueError("MP4 tag keys must be single-line and non-empty; values may not end in a backslash")+ body = "".join(f"{_escape_ffmetadata(key)}={_escape_ffmetadata(value)}\n" for key, value in tags.items())+ # newline="\n": the escaped line breaks must reach ffmpeg byte-for-byte, never as CRLF.+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="\n", suffix=".ffmeta", delete=False) as ffmeta:+ ffmeta.write(_FFMETADATA_HEADER + body)+ ffmeta_path = Path(ffmeta.name)+ try:+ try:+ proc = subprocess.run(+ [+ _ffmpeg_exe(),+ "-y",+ "-loglevel",+ "error",+ "-i",+ str(src),+ "-i",+ str(ffmeta_path),+ "-map",+ "0:v:0",+ "-map",+ "0:a?",+ "-map_metadata",+ "1",+ "-c",+ "copy",+ "-movflags",+ "+faststart+use_metadata_tags",+ "-f",+ "mp4",+ str(dst),+ ],+ capture_output=True,+ timeout=REMUX_TIMEOUT_SECONDS,+ )+ except subprocess.TimeoutExpired as e:+ raise Mp4MetadataError(f"ffmpeg timed out writing metadata into {dst.name}") from e+ if proc.returncode != 0:+ stderr = proc.stderr.decode("utf-8", errors="replace").strip()+ raise Mp4MetadataError(f"ffmpeg could not write metadata into {dst.name}: {stderr[-500:]}")+ try:+ if dst.stat().st_size == 0:+ raise Mp4MetadataError(f"ffmpeg wrote an empty file for {dst.name}")+ except OSError as e:+ raise Mp4MetadataError(f"ffmpeg produced no output for {dst.name}") from e+ finally:+ ffmeta_path.unlink(missing_ok=True)diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex e201350b90..fdb5ab8b6f 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -26331,6 +26331,122 @@"orig_default": null,"orig_required": false},+ "source_video_start_frame": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "The first frame (inclusive) of the source video that was kept",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false,+ "title": "Source Video Start Frame"+ },+ "source_video_end_frame": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "The last frame (inclusive) of the source video that was kept",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false,+ "title": "Source Video End Frame"+ },+ "fps": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "The frame rate of the generated video",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false,+ "title": "Fps"+ },+ "wan_guidance_scale_low_noise": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "The classifier-free guidance scale used by the Wan low-noise expert, when it differed",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false,+ "title": "Wan Guidance Scale Low Noise"+ },+ "wan_t5_encoder_model": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ModelIdentifierField"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "The standalone UMT5-XXL encoder used with a single-file Wan main model",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false+ },+ "wan_transformer_low_noise": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ModelIdentifierField"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "The standalone low-noise expert used with a single-file Wan main model",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false+ },+ "wan_component_source": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ModelIdentifierField"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "The Wan Diffusers install whose VAE and encoder served a single-file main model",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false+ },"minimax_h3_transformer_model": {"anyOf": [{@@ -26363,6 +26479,55 @@"orig_default": null,"orig_required": false},+ "minimax_h3_component_source": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ModelIdentifierField"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "The MiniMax H3 Diffusers install whose VAEs and encoder served a single-file transformer",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false+ },+ "minimax_h3_hybrid_base_model": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ModelIdentifierField"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "The FL2VA transformer whose later blocks overlaid the Ref2VA transformer (the hybrid)",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false+ },+ "minimax_h3_hybrid_start_block": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "The first transformer block taken from the hybrid base",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false,+ "title": "Minimax H3 Hybrid Start Block"+ },"minimax_h3_references": {"anyOf": [{@@ -26598,7 +26763,7 @@"tags": ["metadata"],"title": "Core Metadata","type": "object",- "version": "2.5.0",+ "version": "2.6.0","output": {"$ref": "#/components/schemas/MetadataOutput"}diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex dba84b8414..bf068ba398 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -9768,6 +9768,45 @@ export type components = {* @default null*/source_video?: components["schemas"]["VideoField"] | null;+ /**+ * Source Video Start Frame+ * @description The first frame (inclusive) of the source video that was kept+ * @default null+ */+ source_video_start_frame?: number | null;+ /**+ * Source Video End Frame+ * @description The last frame (inclusive) of the source video that was kept+ * @default null+ */+ source_video_end_frame?: number | null;+ /**+ * Fps+ * @description The frame rate of the generated video+ * @default null+ */+ fps?: number | null;+ /**+ * Wan Guidance Scale Low Noise+ * @description The classifier-free guidance scale used by the Wan low-noise expert, when it differed+ * @default null+ */+ wan_guidance_scale_low_noise?: number | null;+ /**+ * @description The standalone UMT5-XXL encoder used with a single-file Wan main model+ * @default null+ */+ wan_t5_encoder_model?: components["schemas"]["ModelIdentifierField"] | null;+ /**+ * @description The standalone low-noise expert used with a single-file Wan main model+ * @default null+ */+ wan_transformer_low_noise?: components["schemas"]["ModelIdentifierField"] | null;+ /**+ * @description The Wan Diffusers install whose VAE and encoder served a single-file main model+ * @default null+ */+ wan_component_source?: components["schemas"]["ModelIdentifierField"] | null;/*** @description The single-file MiniMax H3 transformer used in place of the main model's transformer* @default null@@ -9778,6 +9817,22 @@ export type components = {* @default null*/minimax_h3_text_encoder_model?: components["schemas"]["ModelIdentifierField"] | null;+ /**+ * @description The MiniMax H3 Diffusers install whose VAEs and encoder served a single-file transformer+ * @default null+ */+ minimax_h3_component_source?: components["schemas"]["ModelIdentifierField"] | null;+ /**+ * @description The FL2VA transformer whose later blocks overlaid the Ref2VA transformer (the hybrid)+ * @default null+ */+ minimax_h3_hybrid_base_model?: components["schemas"]["ModelIdentifierField"] | null;+ /**+ * Minimax H3 Hybrid Start Block+ * @description The first transformer block taken from the hybrid base+ * @default null+ */+ minimax_h3_hybrid_start_block?: number | null;/*** Minimax H3 References* @description The ordered Ref2VA references this generation was conditioned on (names and options only; the media is re-resolved from the gallery at recall time)diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.jsonindex 82dbf42709..7fbb082203 100644--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json@@ -616,7 +616,7 @@],"vae": [],"wan_component_source": [],- "wan_t5_encoder": [],+ "wan_t5_encoder_model": [],"width": [1024,512,diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tsindex e0c1c294ca..9f184a0b03 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -1434,11 +1434,11 @@ const buildWanGraph = (addEdge(graph, seed, 'value', denoise, 'seed');addEdge(graph, denoise, 'latents', output, 'latents');addMetadata(graph, output, settings, model, 'wan_txt2img', projectSettings, {- guidance_scale_low_noise: settings.wanGuidanceScaleLowNoise ?? undefined,- transformer_low_noise: settings.wanLowNoiseModel ?? undefined,vae: vaeModel ?? undefined,wan_component_source: sourceModel,- wan_t5_encoder: wanT5EncoderModel ?? undefined,+ wan_guidance_scale_low_noise: settings.wanGuidanceScaleLowNoise ?? undefined,+ wan_t5_encoder_model: wanT5EncoderModel ?? undefined,+ wan_transformer_low_noise: settings.wanLowNoiseModel ?? undefined,});return graph;diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts b/invokeai/frontend/webv2/src/features/video/core/graph.test.tsindex 98888c573b..ecc40757fc 100644--- a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/graph.test.ts@@ -318,9 +318,9 @@ describe('compileVideoGraph — Wan 2.2', () => {wan_t5_encoder_model: { key: 'umt5' },});expect(nodeOfType(backendGraph, 'core_metadata')).toMatchObject({- transformer_low_noise: { key: 'low-expert' },vae: { key: 'wan-vae' },- wan_t5_encoder: { key: 'umt5' },+ wan_t5_encoder_model: { key: 'umt5' },+ wan_transformer_low_noise: { key: 'low-expert' },});const diffusers = wanModel('i2v_a14b', 'diffusers');@@ -376,7 +376,7 @@ describe('compileVideoGraph — MiniMax H3', () => {expect(hasEdge(backendGraph, 'model_loader', 'audio_vae', 'video_output', 'audio_vae')).toBe(true);expect(nodesOfType(backendGraph, 'minimax_h3_frame_conditioning')).toHaveLength(0);- expect(nodeOfType(backendGraph, 'core_metadata').generation_mode).toBe('minimax_h3_t2v');+ expect(nodeOfType(backendGraph, 'core_metadata')).toMatchObject({ fps: 24, generation_mode: 'minimax_h3_t2v' });// H3 has no negative prompt; the metadata must not claim one.expect(hasEdge(backendGraph, 'negative_prompt', 'value', 'core_metadata', 'negative_prompt')).toBe(false);});diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.ts b/invokeai/frontend/webv2/src/features/video/core/graph.tsindex 5d60519451..d71aeadc8b 100644--- a/invokeai/frontend/webv2/src/features/video/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/video/core/graph.ts@@ -18,6 +18,7 @@ import { getCompatibleDiffusersComponentSource } from '@features/generation/settimport type { VideoGenerationMode, VideoReferenceItem, VideoSettings, VideoSourceClip } from './types';+import { MINIMAX_H3_FPS } from './dimensions';import { MINIMAX_H3_HYBRID_BLOCK_RANGE, resolveVideoMode } from './settings';import { getVideoDimensions, getVideoModelPolicy, getVideoValidationReasons } from './videoPolicies';@@ -460,12 +461,14 @@ const buildWanVideoGraph = (settings: VideoSettings, model: MainModelConfig): Ba// the one user-settable Wan parameter recall could never restore.fps: extendParts && settings.sourceVideo ? Math.round(settings.sourceVideo.fps) : settings.fps,...(policy.ui.cfgLowNoiseVisible && settings.cfgScaleLowNoise !== null- ? { guidance_scale_low_noise: settings.cfgScaleLowNoise }+ ? { wan_guidance_scale_low_noise: settings.cfgScaleLowNoise }: {}),...(settings.vae ? { vae: settings.vae } : {}),- ...(settings.wanT5EncoderModel ? { wan_t5_encoder: settings.wanT5EncoderModel } : {}),+ ...(settings.wanT5EncoderModel ? { wan_t5_encoder_model: settings.wanT5EncoderModel } : {}),...(sourceModel ? { wan_component_source: sourceModel } : {}),- ...(isSingleFileMain && settings.wanLowNoiseModel ? { transformer_low_noise: settings.wanLowNoiseModel } : {}),+ ...(isSingleFileMain && settings.wanLowNoiseModel+ ? { wan_transformer_low_noise: settings.wanLowNoiseModel }+ : {}),},generationMode: WAN_GENERATION_MODES[mode] ?? 'wan_t2v',graph,@@ -662,6 +665,8 @@ const buildMiniMaxH3VideoGraph = (settings: VideoSettings, model: MainModelConficonst metadata = addVideoMetadata({extras: {+ // H3 always delivers its fixed rate; recording it keeps the record self-describing.+ fps: MINIMAX_H3_FPS,...(componentSource ? { minimax_h3_component_source: componentSource } : {}),...(settings.h3TextEncoderModel ? { minimax_h3_text_encoder_model: settings.h3TextEncoderModel } : {}),...(hybridBasediff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.tsindex 743a836e00..07c0276de7 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts@@ -719,3 +719,106 @@ describe('model-position recall shapes', () => {expect(result?.mediaNames.sourceVideoTrim).toEqual({ endFrame: 400, startFrame: 10 });});});++describe('portable records (metadata_version 1.0.0)', () => {+ const catalog = [WAN_T2V, WAN_I2V, h3Model(), LIGHTNING_HIGH, LIGHTNING_LOW];+ const currentValues = { ...createDefaultVideoWidgetValues([h3Model()]) };++ it('reads the canonical low-noise CFG key and its pre-1.0 alias alike', () => {+ const withLow = { ...createDefaultVideoWidgetValues([WAN_T2V]), cfgScaleLowNoise: 2 };+ const canonical = buildVideoRecallSettings({+ currentValues: withLow,+ kind: 'all',+ metadata: wanMetadata({ wan_guidance_scale_low_noise: 3.5 }),+ models: catalog,+ });+ const legacy = buildVideoRecallSettings({+ currentValues: withLow,+ kind: 'all',+ metadata: wanMetadata({ guidance_scale_low_noise: 3.5 }),+ models: catalog,+ });++ expect(canonical?.values.cfgScaleLowNoise).toBe(3.5);+ expect(legacy?.values.cfgScaleLowNoise).toBe(3.5);+ });++ it('resolves a model recorded on another install by hash when its key is unknown here', () => {+ const hashed = { ...WAN_T2V, hash: 'blake3:abc' };+ const result = buildVideoRecallSettings({+ currentValues,+ kind: 'all',+ metadata: wanMetadata({+ model: { base: 'wan', hash: 'blake3:abc', key: 'foreign-key', name: 'Other name', type: 'main' },+ }),+ models: [hashed, h3Model()],+ });++ expect(result?.fields).toContain('model');+ expect(result?.values.model?.key).toBe(WAN_T2V.key);+ });++ it('falls back to name, base and type when neither key nor hash matches', () => {+ const result = buildVideoRecallSettings({+ currentValues,+ kind: 'all',+ metadata: wanMetadata({+ model: { base: 'wan', hash: 'blake3:nope', key: 'foreign-key', name: WAN_T2V.name, type: 'main' },+ }),+ models: catalog,+ });++ expect(result?.values.model?.key).toBe(WAN_T2V.key);++ const wrongType = buildVideoRecallSettings({+ currentValues,+ kind: 'all',+ metadata: wanMetadata({ model: { base: 'wan', key: 'foreign-key', name: WAN_T2V.name, type: 'lora' } }),+ models: catalog,+ });++ expect(wrongType?.fields).not.toContain('model');+ });++ it('resolves LoRAs and Wan components through the same ladder', () => {+ const hashedLora = { ...LIGHTNING_HIGH, hash: 'blake3:high' };+ const umt5 = { base: 'any', hash: 'blake3:umt5', key: 'local-umt5', name: 'UMT5-XXL', type: 'wan_t5_encoder' };+ const result = buildVideoRecallSettings({+ currentValues,+ kind: 'all',+ metadata: wanMetadata({+ loras: [{ model: { hash: 'blake3:high', key: 'foreign-lora' }, weight: 0.8 }],+ // The canonical key for the standalone encoder; a record may also spell it `wan_t5_encoder`.+ wan_t5_encoder_model: {+ base: 'any',+ hash: 'blake3:umt5',+ key: 'foreign-umt5',+ name: 'UMT5-XXL',+ type: 'wan_t5_encoder',+ },+ }),+ models: [WAN_T2V, hashedLora, umt5],+ });++ expect(result?.values.loras).toEqual([{ isEnabled: true, model: hashedLora, weight: 0.8 }]);+ expect(result?.values.wanT5EncoderModel).toEqual(umt5);++ const lowExpert = wanModel('t2v_a14b', 'checkpoint', 'low-expert');+ const aliased = buildVideoRecallSettings({+ currentValues,+ kind: 'all',+ metadata: wanMetadata({ transformer_low_noise: { key: lowExpert.key }, wan_t5_encoder: { key: 'local-umt5' } }),+ models: [WAN_T2V, umt5, lowExpert],+ });++ expect(aliased?.values.wanT5EncoderModel).toEqual(umt5);+ expect(aliased?.values.wanLowNoiseModel).toEqual(lowExpert);+ });++ it('does not advertise a recall for a model reference nothing can resolve', () => {+ expect(getVideoRecallCapabilities({ generation_mode: 'wan_t2v', model: { name: 'only a name' } })).toEqual(+ EMPTY_VIDEO_RECALL_CAPABILITIES+ );+ expect(getVideoRecallCapabilities({ generation_mode: 'wan_t2v', model: { hash: 'blake3:x' } }).remix).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.tsindex 11f85dcd37..eb38974617 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts@@ -24,14 +24,26 @@ import { SEED_MAX } from '@platform/core/seed';/*** Pure mapping from a video's recorded `core_metadata` to a Video-panel- * patch — the sibling of `imageRecall.ts`. Model resolution is by KEY against- * the installed catalog; an uninstalled model skips the model field and+ * patch — the sibling of `imageRecall.ts`. Models resolve against the+ * installed catalog by key, then hash, then name+base+type (see+ * `resolveRecordedModel`); an unresolvable model skips the model field and* everything downstream validates against the current model instead. The* conditioning mode is never recalled directly: the panel derives it from* which media fields are filled, so recall restores the media and lets the* mode fall out.*/+/**+ * Canonical record key → the names earlier writers used for the same value.+ * The record format is versioned (`metadata_version`); these are read-only+ * aliases for pre-1.0 records and are never written again.+ */+const METADATA_KEY_ALIASES: Readonly<Record<string, readonly string[]>> = {+ wan_guidance_scale_low_noise: ['guidance_scale_low_noise'],+ wan_t5_encoder_model: ['wan_t5_encoder'],+ wan_transformer_low_noise: ['transformer_low_noise'],+};+/** The generation_mode strings the video graphs stamp; anything else is not video metadata. */const VIDEO_GENERATION_MODE_IDS: ReadonlySet<string> = new Set(['wan_t2v',@@ -83,32 +95,35 @@ export interface VideoRecallResult {const isRecord = (value: unknown): value is Record<string, unknown> =>Boolean(value) && typeof value === 'object' && !Array.isArray(value);-const getRecord = (value: unknown, key: string): Record<string, unknown> | null => {- if (!isRecord(value)) {- return null;+/** The recorded value under `key`, or under the first present alias of it; `undefined` when absent. */+const readKey = (metadata: unknown, key: string): unknown => {+ if (!isRecord(metadata)) {+ return undefined;+ }++ for (const candidate of [key, ...(METADATA_KEY_ALIASES[key] ?? [])]) {+ if (candidate in metadata) {+ return metadata[candidate];+ }}- const child = value[key];+ return undefined;+};++const getRecord = (value: unknown, key: string): Record<string, unknown> | null => {+ const child = readKey(value, key);return isRecord(child) ? child : null;};const getString = (metadata: unknown, key: string): string | null => {- if (!isRecord(metadata)) {- return null;- }-- const value = metadata[key];+ const value = readKey(metadata, key);return typeof value === 'string' ? value : null;};const getNullableString = (metadata: unknown, key: string): string | null | undefined => {- if (!isRecord(metadata)) {- return undefined;- }-- const value = metadata[key];+ const value = readKey(metadata, key);if (value === null) {return null;@@ -118,11 +133,7 @@ const getNullableString = (metadata: unknown, key: string): string | null | unde};const getNumber = (metadata: unknown, key: string): number | null => {- if (!isRecord(metadata)) {- return null;- }-- const value = metadata[key];+ const value = readKey(metadata, key);return typeof value === 'number' && Number.isFinite(value) ? value : null;};@@ -145,20 +156,71 @@ export const isVideoGenerationMetadata = (metadata: unknown): boolean => {return mode !== null && VIDEO_GENERATION_MODE_IDS.has(mode);};-const getMetadataModelKey = (metadata: unknown, key: string): string | null => {- const model = getRecord(metadata, key);+/** A recorded `ModelIdentifier` — `{ key, hash, name, base, type }` — with every field optional on read. */+interface RecordedModelRef {+ key: string | null;+ hash: string | null;+ name: string | null;+ base: string | null;+ type: string | null;+}- return typeof model?.key === 'string' ? model.key : null;+const toRecordedModelRef = (value: unknown): RecordedModelRef | null => {+ if (!isRecord(value)) {+ return null;+ }++ const field = (name: string) => (typeof value[name] === 'string' ? (value[name] as string) : null);+ const ref: RecordedModelRef = {+ base: field('base'),+ hash: field('hash'),+ key: field('key'),+ name: field('name'),+ type: field('type'),+ };++ // Only a ref that at least one rung of `resolveRecordedModel` can act on counts as recorded;+ // anything less would advertise a recall that can never resolve.+ return ref.key || ref.hash || (ref.name && ref.base && ref.type) ? ref : null;};-const getSupportedVideoMetadataModel = (metadata: unknown, models: readonly ModelConfig[]): MainModelConfig | null => {- const modelKey = getMetadataModelKey(metadata, 'model');+const getMetadataModelRef = (metadata: unknown, key: string): RecordedModelRef | null =>+ toRecordedModelRef(getRecord(metadata, key));- if (!modelKey) {+/**+ * The installed catalog entry a recorded model refers to. Keys are minted per+ * install, so a record that travelled with a downloaded file names keys this+ * catalog has never seen; the hash is the content identity and resolves the+ * same weights wherever they are installed. Name+base+type is the last+ * resort for records without a hash (or a re-quantized copy), and the only+ * step that can pick a different file of the same model.+ */+const resolveRecordedModel = <T extends ModelConfig>(ref: RecordedModelRef | null, models: readonly T[]): T | null => {+ if (!ref) {return null;}- const installed = models.find((model) => model.key === modelKey);+ const byKey = ref.key ? models.find((model) => model.key === ref.key) : undefined;+ if (byKey) {+ return byKey;+ }++ const byHash = ref.hash ? models.find((model) => model.hash === ref.hash) : undefined;+ if (byHash) {+ return byHash;+ }++ if (ref.name && ref.base && ref.type) {+ return (+ models.find((model) => model.name === ref.name && model.base === ref.base && model.type === ref.type) ?? null+ );+ }++ return null;+};++const getSupportedVideoMetadataModel = (metadata: unknown, models: readonly ModelConfig[]): MainModelConfig | null => {+ const installed = resolveRecordedModel(getMetadataModelRef(metadata, 'model'), models);return installed && isSupportedVideoModel(installed) ? (installed as MainModelConfig) : null;};@@ -207,28 +269,30 @@ export const getRecallableMediaNames = (};};-const getMetadataLoras = (metadata: unknown): { key: string; weight: number }[] => {+const getMetadataLoras = (metadata: unknown): { model: RecordedModelRef; weight: number }[] => {if (!isRecord(metadata) || !Array.isArray(metadata.loras)) {return [];}return metadata.loras.flatMap((entry) => {- if (!isRecord(entry) || !isRecord(entry.model) || typeof entry.model.key !== 'string') {+ const model = isRecord(entry) ? toRecordedModelRef(entry.model) : null;++ if (!model) {return [];}const weight = typeof entry.weight === 'number' && Number.isFinite(entry.weight) ? entry.weight : 1;- return [{ key: entry.model.key, weight }];+ return [{ model, weight }];});};-/** Metadata component slot → widget-values key, with the recorded value's key resolved against the catalog. */+/** Metadata component slot → widget-values key, with the recorded model resolved against the catalog. */const VIDEO_COMPONENT_METADATA_KEYS = [['vae', 'vae'],- ['wan_t5_encoder', 'wanT5EncoderModel'],+ ['wan_t5_encoder_model', 'wanT5EncoderModel'],['wan_component_source', 'componentSourceModel'],- ['transformer_low_noise', 'wanLowNoiseModel'],+ ['wan_transformer_low_noise', 'wanLowNoiseModel'],['minimax_h3_transformer_model', 'h3TransformerModel'],['minimax_h3_component_source', 'componentSourceModel'],['minimax_h3_text_encoder_model', 'h3TextEncoderModel'],@@ -311,7 +375,7 @@ export const getVideoRecallCapabilities = (metadata: unknown): VideoRecallCapabiconst media = getRecallableMediaNames(metadata);const hasNonSeed =prompts ||- getMetadataModelKey(metadata, 'model') !== null ||+ getMetadataModelRef(metadata, 'model') !== null ||getInteger(metadata, 'num_frames') !== null ||getInteger(metadata, 'steps') !== null ||getNumber(metadata, 'cfg_scale') !== null ||@@ -496,7 +560,7 @@ export const buildVideoRecallSettings = ({}const cfgScale = getNumber(metadata, 'cfg_scale');- const cfgScaleLowNoise = getNumber(metadata, 'guidance_scale_low_noise');+ const cfgScaleLowNoise = getNumber(metadata, 'wan_guidance_scale_low_noise');const policy = getVideoModelPolicy(model, values);if (policy.ui.cfgVisible && cfgScale !== null && cfgScale >= 1) {@@ -514,8 +578,8 @@ export const buildVideoRecallSettings = ({const fps = getInteger(metadata, 'fps');- // Wan records the delivered frame rate (H3 is fixed at 24 and records- // none). Recalling it into an extend-mode panel is harmless: the fps field+ // Wan records the delivered frame rate (H3 records its fixed 24, which its+ // policy never lets the panel edit). Recalling it into an extend-mode panel is harmless: the fps field// is display-only there and the compiled graph re-inherits the clip's rate.if (policy.fps.editable && fps !== null && fps >= 1 && fps <= 120) {if (fps !== values.fps) {@@ -537,13 +601,7 @@ export const buildVideoRecallSettings = ({let hybridBaseRecalled = false;for (const [metadataKey, valuesKey] of VIDEO_COMPONENT_METADATA_KEYS) {- const recordedKey = getMetadataModelKey(metadata, metadataKey);-- if (!recordedKey) {- continue;- }-- const installed = models.find((candidate) => candidate.key === recordedKey);+ const installed = resolveRecordedModel(getMetadataModelRef(metadata, metadataKey), models);if (installed) {values = { ...values, [valuesKey]: installed };@@ -620,7 +678,7 @@ export const buildVideoRecallSettings = ({const recordedLoras = getMetadataLoras(metadata);const resolvedLoras = recordedLoras.flatMap((entry) => {- const installed = models.find((candidate) => candidate.key === entry.key);+ const installed = resolveRecordedModel(entry.model, models);return installed && isLoraModelConfig(installed) && isLoraCompatibleWithModel(installed, model)? [{ isEnabled: true, model: installed as LoraModelConfig, weight: entry.weight }]diff --git a/tests/app/invocations/test_core_metadata.py b/tests/app/invocations/test_core_metadata.pynew file mode 100644index 0000000000..079e5835a5--- /dev/null+++ b/tests/app/invocations/test_core_metadata.py@@ -0,0 +1,41 @@+from unittest.mock import MagicMock++from invokeai.app.invocations.fields import ImageField, VideoField+from invokeai.app.invocations.metadata import CORE_METADATA_VERSION, CoreMetadataInvocation+from invokeai.app.invocations.model import ModelIdentifierField+from invokeai.version import __version__+++def test_core_metadata_stamps_the_record_version_beside_the_app_version() -> None:+ output = CoreMetadataInvocation(id="m", positive_prompt="a fox", seed=3).invoke(MagicMock())++ record = output.metadata.root+ assert record["metadata_version"] == CORE_METADATA_VERSION+ assert record["app_version"] == __version__+ assert record["positive_prompt"] == "a fox"+ assert "negative_prompt" not in record # unset fields are omitted, not written as null+++def test_core_metadata_records_the_video_profile_fields_by_their_canonical_names() -> None:+ encoder = ModelIdentifierField(key="k", hash="h", name="UMT5", base="any", type="wan_t5_encoder")+ output = CoreMetadataInvocation(+ id="m",+ generation_mode="wan_extend_video",+ num_frames=81,+ fps=16,+ wan_guidance_scale_low_noise=3.5,+ wan_t5_encoder_model=encoder,+ source_video=VideoField(video_name="clip.mp4"),+ source_video_start_frame=0,+ source_video_end_frame=40,+ last_frame_image=ImageField(image_name="end.png"),+ minimax_h3_hybrid_start_block=12,+ ).invoke(MagicMock())++ record = output.metadata.root+ assert record["fps"] == 16+ assert record["wan_guidance_scale_low_noise"] == 3.5+ assert record["wan_t5_encoder_model"]["hash"] == "h"+ assert record["source_video"] == {"video_name": "clip.mp4"}+ assert (record["source_video_start_frame"], record["source_video_end_frame"]) == (0, 40)+ assert record["minimax_h3_hybrid_start_block"] == 12diff --git a/tests/app/routers/test_videos_multiuser.py b/tests/app/routers/test_videos_multiuser.pyindex e965388e0f..77a1029bd6 100644--- a/tests/app/routers/test_videos_multiuser.py+++ b/tests/app/routers/test_videos_multiuser.py@@ -1208,3 +1208,161 @@ def test_single_video_mutations_are_offloaded_by_fastapi(handler: Any) -> None:every other request and socket event until the delete/update finished."""assert not inspect.iscoroutinefunction(handler)+++# --- Embedded metadata on upload -----------------------------------------------------------------+++def _tagged_upload(tmp_path: Path, tags: dict[str, str]) -> bytes:+ """A real H.264 MP4 carrying ``tags`` as keyed metadata, as an InvokeAI download would."""+ import numpy as np++ from invokeai.app.util.mp4_metadata import write_mp4_tags+ from invokeai.app.util.video_encoding import make_mp4_writer++ plain = tmp_path / "plain.mp4"+ writer = make_mp4_writer(plain, fps=8.0)+ try:+ for _ in range(2):+ writer.append_data(np.zeros((16, 16, 3), dtype=np.uint8))+ finally:+ writer.close()+ tagged = tmp_path / "tagged.mp4"+ write_mp4_tags(plain, tagged, tags)+ return tagged.read_bytes()+++def _upload(client: TestClient, token: str, body: bytes, metadata: str | None = None):+ with (+ patch(+ "invokeai.app.api.routers.videos.probe_media_streams",+ return_value=MediaProbe(video_codec="h264", audio_codec=None),+ ),+ patch("invokeai.app.api.routers.videos._probe_decodable_video", return_value=((16, 16, 0.25, 8.0), None)),+ ):+ return client.post(+ "/api/v1/videos/upload",+ params={"video_category": "general", "is_intermediate": False},+ files={"file": ("video.mp4", body, "video/mp4")},+ data={} if metadata is None else {"metadata": metadata},+ headers={"Authorization": f"Bearer {token}"},+ )+++def test_upload_video_recovers_metadata_workflow_and_graph_embedded_in_the_file(+ client: TestClient, mock_invoker: Invoker, user1_token: str, tmp_path: Path+):+ mock_invoker.services.videos.create.return_value = _uploaded_video_dto()+ tags = {+ "invokeai_metadata": json.dumps({"seed": 42, "generation_mode": "wan_t2v", "metadata_version": "1.0.0"}),+ "invokeai_workflow": json.dumps(+ {+ "name": "wf",+ "author": "",+ "description": "",+ "version": "",+ "contact": "",+ "tags": "",+ "notes": "",+ "exposedFields": [],+ "meta": {"version": "3.0.0", "category": "user"},+ "nodes": [],+ "edges": [],+ "form": {"elements": {}, "rootElementId": "root"},+ }+ ),+ "invokeai_graph": json.dumps({"nodes": {}, "edges": []}),+ }++ response = _upload(client, user1_token, _tagged_upload(tmp_path, tags))++ assert response.status_code == status.HTTP_201_CREATED+ kwargs = mock_invoker.services.videos.create.call_args.kwargs+ assert kwargs["metadata"] == tags["invokeai_metadata"]+ assert kwargs["workflow"] == tags["invokeai_workflow"]+ assert kwargs["graph"] == tags["invokeai_graph"]+++def test_upload_video_client_metadata_wins_over_the_embedded_copy(+ client: TestClient, mock_invoker: Invoker, user1_token: str, tmp_path: Path+):+ mock_invoker.services.videos.create.return_value = _uploaded_video_dto()+ tags = {"invokeai_metadata": '{"seed": 42}', "invokeai_graph": '{"nodes": {}, "edges": []}'}++ response = _upload(client, user1_token, _tagged_upload(tmp_path, tags), metadata='{"seed": 7}')++ assert response.status_code == status.HTTP_201_CREATED+ kwargs = mock_invoker.services.videos.create.call_args.kwargs+ assert kwargs["metadata"] == '{"seed": 7}'+ assert kwargs["workflow"] is None+ assert kwargs["graph"] == tags["invokeai_graph"]+++def test_upload_video_without_embedded_tags_stores_no_metadata(+ client: TestClient, mock_invoker: Invoker, user1_token: str+):+ mock_invoker.services.videos.create.return_value = _uploaded_video_dto()+ mp4 = b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 12++ response = _upload(client, user1_token, mp4)++ assert response.status_code == status.HTTP_201_CREATED+ kwargs = mock_invoker.services.videos.create.call_args.kwargs+ assert (kwargs["metadata"], kwargs["workflow"], kwargs["graph"]) == (None, None, None)+++def test_upload_recovers_embedded_tags_from_a_file_the_ingest_path_rewrites(+ client: TestClient, mock_invoker: Invoker, user1_token: str, tmp_path: Path+):+ """The ingest remux does not carry keyed metadata, so extraction must happen on the file as+ uploaded. An h264 MP4 with mp3 audio takes the real ingest path (no probes patched)."""+ from invokeai.app.util.mp4_metadata import read_mp4_tags, write_mp4_tags++ plain = _make_fixture_media(+ tmp_path / "plain.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"),+ )+ tags = {+ "invokeai_metadata": '{"seed": 5, "generation_mode": "wan_t2v"}',+ "invokeai_graph": '{"nodes": {}, "edges": []}',+ }+ tagged = tmp_path / "tagged.mp4"+ write_mp4_tags(plain, tagged, tags)+ stored_tags: list[dict[str, str]] = []++ def create(**kwargs: Any) -> VideoDTO:+ stored_tags.append(read_mp4_tags(Path(kwargs["source_path"]), keys=tags))+ 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", tagged.read_bytes(), "video/mp4")},+ headers={"Authorization": f"Bearer {user1_token}"},+ )++ assert response.status_code == status.HTTP_201_CREATED+ kwargs = mock_invoker.services.videos.create.call_args.kwargs+ assert kwargs["metadata"] == tags["invokeai_metadata"]+ assert kwargs["graph"] == tags["invokeai_graph"]+ # The converted file reaching create() has lost the tags — which is why extraction ran first.+ assert stored_tags == [{}]+++def test_upload_ignores_an_embedded_metadata_record_over_the_form_field_cap(+ client: TestClient, mock_invoker: Invoker, user1_token: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ mock_invoker.services.videos.create.return_value = _uploaded_video_dto()+ monkeypatch.setattr(videos_router_module, "MAX_UPLOAD_METADATA_SIZE", 64)+ tags = {"invokeai_metadata": json.dumps({"pad": "x" * 100}), "invokeai_graph": '{"nodes": {}, "edges": []}'}++ response = _upload(client, user1_token, _tagged_upload(tmp_path, tags))++ assert response.status_code == status.HTTP_201_CREATED+ kwargs = mock_invoker.services.videos.create.call_args.kwargs+ assert kwargs["metadata"] is None+ assert kwargs["graph"] == tags["invokeai_graph"]diff --git a/tests/app/services/image_files/test_image_files_disk.py b/tests/app/services/image_files/test_image_files_disk.pyindex d7b8892ec6..435f382ff9 100644--- a/tests/app/services/image_files/test_image_files_disk.py+++ b/tests/app/services/image_files/test_image_files_disk.py@@ -11,7 +11,7 @@ from unittest.mock import MagicMock, patchimport pytestfrom PIL import Image-from invokeai.app.api.extract_metadata_from_image import extract_metadata_from_image+from invokeai.app.api.extract_metadata import extract_metadata_from_imagefrom invokeai.app.services.image_files.image_files_common import ImageFileDeleteException, ImageFileSaveExceptionfrom invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage, _should_use_png_rlefrom invokeai.app.util.thumbnails import get_thumbnail_namediff --git a/tests/app/services/video_files/test_video_files_disk.py b/tests/app/services/video_files/test_video_files_disk.pyindex e6b2cf54ec..de941b295d 100644--- a/tests/app/services/video_files/test_video_files_disk.py+++ b/tests/app/services/video_files/test_video_files_disk.py@@ -236,3 +236,206 @@ def test_start_purges_staged_delete_when_record_is_gone(storage: DiskVideoFileStassert _all_files(tmp_path / "videos") == []assert not list((tmp_path / "videos").glob(".delete_*"))+++# --- Embedded metadata -------------------------------------------------------------------------+#+# Metadata, workflow and graph live inside the MP4 as keyed metadata; the JSON sidecar is only+# the fallback when the remux fails, and the read path for videos stored before embedding.+++def real_source(tmp_path: Path) -> Path:+ import numpy as np++ from invokeai.app.util.video_encoding import make_mp4_writer++ source = tmp_path / "real.mp4"+ writer = make_mp4_writer(source, fps=8.0)+ try:+ for _ in range(2):+ writer.append_data(np.zeros((16, 16, 3), dtype=np.uint8))+ finally:+ writer.close()+ return source+++def _sidecars(storage: DiskVideoFileStorage) -> list[Path]:+ return [p for p in _all_files(storage.get_path(VIDEO_NAME).parent) if p.suffix == ".json"]+++def test_save_embeds_metadata_workflow_and_graph_in_the_mp4_and_writes_no_sidecar(+ storage: DiskVideoFileStorage, real_source: Path+):+ from invokeai.app.util.mp4_metadata import read_mp4_tags++ storage.save(+ source_path=real_source,+ video_name=VIDEO_NAME,+ metadata='{"seed": 1}',+ workflow='{"name": "wf"}',+ graph='{"nodes": {}, "edges": []}',+ )++ embedded = read_mp4_tags(storage.get_path(VIDEO_NAME))+ assert {key: value for key, value in embedded.items() if key.startswith("invokeai_")} == {+ "invokeai_metadata": '{"seed": 1}',+ "invokeai_workflow": '{"name": "wf"}',+ "invokeai_graph": '{"nodes": {}, "edges": []}',+ }+ assert storage.get_workflow(VIDEO_NAME) == '{"name": "wf"}'+ assert storage.get_graph(VIDEO_NAME) == '{"nodes": {}, "edges": []}'+ assert _sidecars(storage) == []+ # The thumbnail was taken from the rewritten file, which still decodes.+ assert storage.get_path(VIDEO_NAME, thumbnail=True).exists()+++def test_save_without_any_metadata_leaves_the_file_byte_identical(storage: DiskVideoFileStorage, real_source: Path):+ original = real_source.read_bytes()++ storage.save(source_path=real_source, video_name=VIDEO_NAME)++ assert storage.get_path(VIDEO_NAME).read_bytes() == original+ assert _sidecars(storage) == []+++def test_save_falls_back_to_a_sidecar_when_embedding_fails(+ storage: DiskVideoFileStorage, real_source: Path, monkeypatch: pytest.MonkeyPatch+):+ from invokeai.app.util.mp4_metadata import Mp4MetadataError++ original = real_source.read_bytes()++ def broken_write(*args, **kwargs):+ raise Mp4MetadataError("ffmpeg exploded")++ monkeypatch.setattr("invokeai.app.services.video_files.video_files_disk.write_mp4_tags", broken_write)++ storage.save(source_path=real_source, video_name=VIDEO_NAME, workflow='{"name": "wf"}')++ assert storage.get_path(VIDEO_NAME).read_bytes() == original+ assert len(_sidecars(storage)) == 1+ assert storage.get_workflow(VIDEO_NAME) == '{"name": "wf"}'+ assert storage.get_graph(VIDEO_NAME) is None+ # No stray remux temp file survives the failure.+ assert [p.name for p in _all_files(storage.get_path(VIDEO_NAME).parent) if p.name.startswith(".embed_")] == []+++def test_legacy_sidecar_is_still_read_for_an_untagged_video(storage: DiskVideoFileStorage, real_source: Path):+ storage.save(source_path=real_source, video_name=VIDEO_NAME)+ sidecar_dir = storage.get_path(VIDEO_NAME).parent / "sidecars"+ sidecar_dir.mkdir(exist_ok=True)+ (sidecar_dir / "abc123.json").write_text(+ '{"invokeai_metadata": null, "invokeai_workflow": "{\\"name\\": \\"old\\"}", "invokeai_graph": null}'+ )++ assert storage.get_workflow(VIDEO_NAME) == '{"name": "old"}'+ assert storage.get_graph(VIDEO_NAME) is None+++def test_embedded_tags_win_over_a_stale_sidecar(storage: DiskVideoFileStorage, real_source: Path):+ storage.save(source_path=real_source, video_name=VIDEO_NAME, workflow='{"name": "embedded"}')+ sidecar_dir = storage.get_path(VIDEO_NAME).parent / "sidecars"+ sidecar_dir.mkdir(exist_ok=True)+ (sidecar_dir / "abc123.json").write_text('{"invokeai_workflow": "{\\"name\\": \\"stale\\"}"}')++ assert storage.get_workflow(VIDEO_NAME) == '{"name": "embedded"}'+++def test_save_of_an_already_tagged_file_skips_the_rewrite(+ storage: DiskVideoFileStorage, real_source: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ """A re-uploaded InvokeAI download carries exactly the tags being saved; a 1 GB rewrite for+ an identical result is wasted I/O."""+ from invokeai.app.util.mp4_metadata import write_mp4_tags++ tags = {"invokeai_metadata": '{"seed": 9}', "invokeai_graph": '{"nodes": {}, "edges": []}'}+ tagged = tmp_path / "tagged.mp4"+ write_mp4_tags(real_source, tagged, tags)+ original = tagged.read_bytes()+ monkeypatch.setattr(+ "invokeai.app.services.video_files.video_files_disk.write_mp4_tags",+ lambda *args, **kwargs: pytest.fail("remux ran for identical tags"),+ )++ storage.save(+ source_path=tagged, video_name=VIDEO_NAME, metadata=tags["invokeai_metadata"], graph=tags["invokeai_graph"]+ )++ assert storage.get_path(VIDEO_NAME).read_bytes() == original+ assert _sidecars(storage) == []+++def test_crlf_metadata_is_embedded_not_rejected(storage: DiskVideoFileStorage, real_source: Path):+ """CRLF-formatted JSON from an API client must neither fail the save nor lose the record."""+ from invokeai.app.util.mp4_metadata import read_mp4_tags++ metadata = '{\r\n "seed": 1\r\n}'++ storage.save(source_path=real_source, video_name=VIDEO_NAME, metadata=metadata)++ assert read_mp4_tags(storage.get_path(VIDEO_NAME), keys=["invokeai_metadata"]) == {"invokeai_metadata": metadata}+ assert _sidecars(storage) == []+++def test_a_tag_the_writer_refuses_falls_back_to_a_sidecar_without_leaking(+ storage: DiskVideoFileStorage, real_source: Path+):+ original = real_source.read_bytes()++ storage.save(source_path=real_source, video_name=VIDEO_NAME, metadata="ends in a backslash \\")++ assert storage.get_path(VIDEO_NAME).read_bytes() == original+ assert len(_sidecars(storage)) == 1+ assert [p.name for p in _all_files(storage.get_path(VIDEO_NAME).parent) if p.name.startswith(".embed_")] == []+++def test_start_sweeps_remux_temp_files_left_by_a_crash(tmp_path: Path):+ storage = DiskVideoFileStorage(tmp_path / "videos")+ stale = tmp_path / "videos" / ".embed_abc.mp4"+ stale.write_bytes(b"partial")+ invoker = MagicMock()++ storage.start(invoker)++ assert not stale.exists()+++def test_a_file_carrying_a_tag_the_caller_dropped_is_rewritten_without_it(+ storage: DiskVideoFileStorage, real_source: Path, tmp_path: Path+):+ """An upload whose embedded workflow failed validation arrives with metadata and graph only;+ the stored file must not keep serving the rejected workflow through get_workflow."""+ from invokeai.app.util.mp4_metadata import read_mp4_tags, write_mp4_tags++ tagged = tmp_path / "tagged.mp4"+ write_mp4_tags(+ real_source,+ tagged,+ {"invokeai_metadata": '{"seed": 1}', "invokeai_workflow": '{"not": "a workflow"}', "invokeai_graph": "{}"},+ )++ storage.save(source_path=tagged, video_name=VIDEO_NAME, metadata='{"seed": 1}', graph="{}")++ embedded = read_mp4_tags(storage.get_path(VIDEO_NAME))+ assert "invokeai_workflow" not in embedded+ assert embedded["invokeai_metadata"] == '{"seed": 1}'+ assert storage.get_workflow(VIDEO_NAME) is None+ assert storage.get_graph(VIDEO_NAME) == "{}"+++def test_a_file_whose_only_tag_was_rejected_is_stored_without_it(+ storage: DiskVideoFileStorage, real_source: Path, tmp_path: Path+):+ """No record to save, but the upload carried an invalid workflow: the stored file must not keep it,+ or get_workflow (and a later copy) would launder the rejected value back into a record."""+ from invokeai.app.util.mp4_metadata import read_mp4_tags, write_mp4_tags++ tagged = tmp_path / "tagged.mp4"+ write_mp4_tags(real_source, tagged, {"invokeai_workflow": '{"not": "a workflow"}'})++ storage.save(source_path=tagged, video_name=VIDEO_NAME)++ assert "invokeai_workflow" not in read_mp4_tags(storage.get_path(VIDEO_NAME))+ assert storage.get_workflow(VIDEO_NAME) is None+ assert _sidecars(storage) == []diff --git a/tests/app/test_extract_metadata_from_image.py b/tests/app/test_extract_metadata.pysimilarity index 71%rename from tests/app/test_extract_metadata_from_image.pyrename to tests/app/test_extract_metadata.pyindex 7a299a57b3..6ff6eed3b5 100644--- a/tests/app/test_extract_metadata_from_image.py+++ b/tests/app/test_extract_metadata.py@@ -5,7 +5,7 @@ from unittest.mock import MagicMock, patchimport pytestfrom PIL import Image-from invokeai.app.api.extract_metadata_from_image import ExtractedMetadata, extract_metadata_from_image+from invokeai.app.api.extract_metadata import ExtractedMetadata, extract_metadata_from_image@pytest.fixture@@ -46,7 +46,7 @@ def test_extract_valid_metadata_from_image(mock_logger, valid_metadata, valid_wo# Assert correct calls to validatorsmock_workflow_validate.assert_called_once_with(valid_workflow)- # TODO(psyche): The extract_metadata_from_image does not validate the graph correctly. See note in `extract_metadata_from_image.py`.+ # TODO(psyche): The extract_metadata_from_image does not validate the graph correctly. See note in `extract_metadata.py`.# Skipping this.# _mock_graph_validate.assert_called_once_with(valid_graph)@@ -221,3 +221,89 @@ def test_empty_string_overrides_do_not_fall_back_to_image_metadata(assert result.invokeai_metadata is Noneassert result.invokeai_workflow is Noneassert result.invokeai_graph is None+++# --- MP4 sources -----------------------------------------------------------------------------++[email protected](scope="module")+def tagged_mp4(tmp_path_factory: pytest.TempPathFactory):+ """A real MP4 carrying the three keys the way DiskVideoFileStorage writes them."""+ import numpy as np++ from invokeai.app.util.mp4_metadata import write_mp4_tags+ from invokeai.app.util.video_encoding import make_mp4_writer++ folder = tmp_path_factory.mktemp("tagged")+ plain = folder / "plain.mp4"+ writer = make_mp4_writer(plain, fps=8.0)+ try:+ for _ in range(2):+ writer.append_data(np.zeros((16, 16, 3), dtype=np.uint8))+ finally:+ writer.close()+ tagged = folder / "tagged.mp4"+ tags = {+ "invokeai_metadata": json.dumps({"seed": 42, "generation_mode": "wan_t2v"}),+ "invokeai_workflow": json.dumps(MINIMAL_WORKFLOW),+ "invokeai_graph": json.dumps({"nodes": {}, "edges": []}),+ }+ write_mp4_tags(plain, tagged, tags)+ return tagged, plain, tags+++MINIMAL_WORKFLOW = {+ "name": "wf",+ "author": "",+ "description": "",+ "version": "",+ "contact": "",+ "tags": "",+ "notes": "",+ "exposedFields": [],+ "meta": {"version": "3.0.0", "category": "user"},+ "nodes": [],+ "edges": [],+ "form": {"elements": {}, "rootElementId": "root"},+}+++def test_extract_from_tagged_video_returns_the_embedded_strings(mock_logger, tagged_mp4):+ """Through the real workflow validator: the video entry point is not mocked."""+ from invokeai.app.api.extract_metadata import extract_metadata_from_video++ tagged, _plain, tags = tagged_mp4+ result = extract_metadata_from_video(tagged, None, None, None, mock_logger)++ assert result == ExtractedMetadata(+ invokeai_metadata=tags["invokeai_metadata"],+ invokeai_workflow=tags["invokeai_workflow"],+ invokeai_graph=tags["invokeai_graph"],+ )+++def test_extract_from_video_prefers_the_client_metadata_over_the_embedded_copy(mock_logger, tagged_mp4):+ from invokeai.app.api.extract_metadata import extract_metadata_from_video++ tagged, _plain, tags = tagged_mp4+ override = '{"seed": 7}'+ result = extract_metadata_from_video(tagged, override, None, None, mock_logger)++ assert result.invokeai_metadata == override+ # Workflow and graph still come from the file.+ assert result.invokeai_workflow == tags["invokeai_workflow"]+ assert result.invokeai_graph == tags["invokeai_graph"]+++def test_extract_from_untagged_or_non_mp4_video_is_all_none(mock_logger, tagged_mp4, tmp_path):+ from invokeai.app.api.extract_metadata import extract_metadata_from_video++ _tagged, plain, _tags = tagged_mp4+ assert extract_metadata_from_video(plain, None, None, None, mock_logger) == ExtractedMetadata(None, None, None)++ garbage = tmp_path / "garbage.mp4"+ garbage.write_bytes(b"\x00\x00\x00\x18ftypmp42 not a real mp4")+ assert extract_metadata_from_video(garbage, None, None, None, mock_logger) == ExtractedMetadata(None, None, None)++ missing = tmp_path / "missing.mp4"+ assert extract_metadata_from_video(missing, "{}", None, None, mock_logger) == ExtractedMetadata("{}", None, None)diff --git a/tests/app/util/test_mp4_metadata.py b/tests/app/util/test_mp4_metadata.pynew file mode 100644index 0000000000..62ad714a8f--- /dev/null+++ b/tests/app/util/test_mp4_metadata.py@@ -0,0 +1,212 @@+"""Tests for the MP4 keyed-metadata reader/writer (mp4_metadata.py)."""++import json+import struct+from pathlib import Path++import imageio.v2 as iio2+import numpy as np+import pytest++from invokeai.app.util.mp4_metadata import (+ Mp4MetadataError,+ read_ftyp_major_brand,+ read_mp4_tags,+ write_mp4_tags,+)+from invokeai.app.util.video_encoding import make_mp4_writer++[email protected](scope="module")+def tiny_mp4(tmp_path_factory: pytest.TempPathFactory) -> Path:+ path = tmp_path_factory.mktemp("mp4") / "tiny.mp4"+ writer = make_mp4_writer(path, fps=8.0)+ try:+ for i in range(4):+ writer.append_data(np.full((32, 48, 3), i * 40, dtype=np.uint8))+ finally:+ writer.close()+ return path+++def _box(box_type: bytes, payload: bytes) -> bytes:+ return struct.pack(">I4s", 8 + len(payload), box_type) + payload+++def _keyed_metadata_boxes(tags: dict[str, str], *, full_meta_box: bool) -> bytes:+ """A hand-built ``udta/meta`` carrying ``tags`` in either ``meta`` layout."""+ keys_payload = struct.pack(">II", 0, len(tags))+ ilst_payload = b""+ for index, (key, value) in enumerate(tags.items(), start=1):+ name = key.encode("utf-8")+ keys_payload += struct.pack(">I4s", 8 + len(name), b"mdta") + name+ data = _box(b"data", struct.pack(">II", 1, 0) + value.encode("utf-8"))+ ilst_payload += _box(index.to_bytes(4, "big"), data)+ hdlr = _box(b"hdlr", struct.pack(">II4s4s", 0, 0, b"", b"mdta") + b"\x00" * 12)+ meta_payload = (b"\x00\x00\x00\x00" if full_meta_box else b"") + hdlr + _box(b"keys", keys_payload)+ meta_payload += _box(b"ilst", ilst_payload)+ return _box(b"udta", _box(b"meta", meta_payload))+++def _fake_mp4(path: Path, udta: bytes, *, moov_first: bool = True) -> Path:+ ftyp = _box(b"ftyp", b"isom" + struct.pack(">I", 512) + b"isomiso2avc1mp41")+ moov = _box(b"moov", _box(b"mvhd", b"\x00" * 100) + udta)+ mdat = _box(b"mdat", b"\xff" * 64)+ path.write_bytes(ftyp + (moov + mdat if moov_first else mdat + moov))+ return path+++def test_round_trip_through_ffmpeg_preserves_every_special_character(tiny_mp4: Path, tmp_path: Path) -> None:+ metadata = json.dumps({"positive_prompt": "a=b;c#d\\e\nf", "seed": 7, "nested": {"k": [1, 2]}})+ graph = json.dumps({"nodes": {}, "edges": []})+ out = tmp_path / "tagged.mp4"++ write_mp4_tags(tiny_mp4, out, {"invokeai_metadata": metadata, "invokeai_graph": graph})++ tags = read_mp4_tags(out)+ assert tags["invokeai_metadata"] == metadata+ assert tags["invokeai_graph"] == graph+ # The remux must leave a playable H.264 stream behind and keep moov in front (faststart).+ reader = iio2.get_reader(str(out))+ try:+ assert reader.get_data(0).shape[:2] == (32, 48)+ finally:+ reader.close()+ with open(out, "rb") as fh:+ head = fh.read(4096)+ assert b"moov" in head+++def test_round_trip_of_a_payload_larger_than_a_megabyte(tiny_mp4: Path, tmp_path: Path) -> None:+ graph = json.dumps({"nodes": {"x": "y" * 1_500_000}, "edges": []})+ out = tmp_path / "big.mp4"++ write_mp4_tags(tiny_mp4, out, {"invokeai_graph": graph})++ assert read_mp4_tags(out, keys=["invokeai_graph"]) == {"invokeai_graph": graph}+++def test_keys_filter_returns_only_the_requested_tags(tiny_mp4: Path, tmp_path: Path) -> None:+ out = tmp_path / "filtered.mp4"+ write_mp4_tags(tiny_mp4, out, {"invokeai_metadata": "{}", "invokeai_workflow": "{}"})++ assert read_mp4_tags(out, keys=["invokeai_workflow"]) == {"invokeai_workflow": "{}"}+ assert read_mp4_tags(out, keys=["absent"]) == {}+++def test_untagged_mp4_and_non_mp4_read_as_no_tags(tiny_mp4: Path, tmp_path: Path) -> None:+ assert read_mp4_tags(tiny_mp4) == {}+ garbage = tmp_path / "garbage.mp4"+ garbage.write_bytes(b"\x00\x00\x00\x18ftypmp42 not a real mp4")+ assert read_mp4_tags(garbage) == {}+ empty = tmp_path / "empty.mp4"+ empty.write_bytes(b"")+ assert read_mp4_tags(empty) == {}++[email protected]("full_meta_box", [True, False], ids=["iso-fullbox-meta", "quicktime-plain-meta"])[email protected]("moov_first", [True, False], ids=["moov-first", "moov-last"])+def test_reads_both_meta_layouts_in_either_box_order(tmp_path: Path, full_meta_box: bool, moov_first: bool) -> None:+ tags = {"invokeai_metadata": '{"seed": 3}', "com.apple.quicktime.make": "Apple"}+ path = _fake_mp4(+ tmp_path / "fake.mp4", _keyed_metadata_boxes(tags, full_meta_box=full_meta_box), moov_first=moov_first+ )++ assert read_mp4_tags(path) == tags+++def test_truncated_box_size_reads_as_no_tags(tmp_path: Path) -> None:+ path = _fake_mp4(tmp_path / "trunc.mp4", _keyed_metadata_boxes({"invokeai_metadata": "{}"}, full_meta_box=True))+ data = bytearray(path.read_bytes())+ # Claim the moov box is far larger than the file: the walker must not trust it.+ moov_at = data.index(b"moov") - 4+ data[moov_at : moov_at + 4] = struct.pack(">I", 1 << 30)+ path.write_bytes(bytes(data))++ assert read_mp4_tags(path) == {}+++def test_oversized_tag_is_skipped_without_allocating_it(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ tags = {"invokeai_metadata": "x" * 64, "invokeai_workflow": "{}"}+ path = _fake_mp4(tmp_path / "oversized.mp4", _keyed_metadata_boxes(tags, full_meta_box=True))+ monkeypatch.setattr("invokeai.app.util.mp4_metadata.MAX_TAG_BYTES", 32)++ assert read_mp4_tags(path) == {"invokeai_workflow": "{}"}+++def test_non_utf8_data_atom_is_skipped(tmp_path: Path) -> None:+ boxes = bytearray(_keyed_metadata_boxes({"invokeai_metadata": "{}"}, full_meta_box=True))+ at = boxes.index(b"data" + struct.pack(">I", 1)) + 4 # the atom, not the "metadata" key text+ boxes[at : at + 4] = struct.pack(">I", 0) # type indicator 0 = binary, not UTF-8 text+ path = _fake_mp4(tmp_path / "binary.mp4", bytes(boxes))++ assert read_mp4_tags(path) == {}+++def test_carriage_returns_round_trip(tiny_mp4: Path, tmp_path: Path) -> None:+ # CRLF-formatted JSON from an API client reaches the writer verbatim.+ value = '{\r\n "seed": 1\r\n}'+ out = tmp_path / "crlf.mp4"++ write_mp4_tags(tiny_mp4, out, {"invokeai_metadata": value, "invokeai_graph": "{}"})++ assert read_mp4_tags(out, keys=["invokeai_metadata", "invokeai_graph"]) == {+ "invokeai_metadata": value,+ "invokeai_graph": "{}",+ }+++def test_an_empty_mapping_strips_existing_tags(tiny_mp4: Path, tmp_path: Path) -> None:+ tagged = tmp_path / "tagged.mp4"+ write_mp4_tags(tiny_mp4, tagged, {"invokeai_workflow": "{}"})++ write_mp4_tags(tagged, tmp_path / "stripped.mp4", {})++ assert read_mp4_tags(tmp_path / "stripped.mp4", keys=["invokeai_workflow"]) == {}+++def test_write_rejects_tags_the_ffmetadata_grammar_cannot_carry(tiny_mp4: Path, tmp_path: Path) -> None:+ # ffmpeg reads a backslash before the line break as a continuation even when escaped, so a+ # value ending in one would swallow the following tag.+ with pytest.raises(ValueError):+ write_mp4_tags(tiny_mp4, tmp_path / "out.mp4", {"invokeai_metadata": "abc\\", "invokeai_graph": "{}"})+ with pytest.raises(ValueError):+ write_mp4_tags(tiny_mp4, tmp_path / "out.mp4", {"bad\nkey": "{}"})+++def test_oversized_key_name_is_skipped(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ tags = {"x" * 64: "long", "invokeai_workflow": "{}"}+ path = _fake_mp4(tmp_path / "longkey.mp4", _keyed_metadata_boxes(tags, full_meta_box=True))+ monkeypatch.setattr("invokeai.app.util.mp4_metadata._MAX_KEY_NAME_BYTES", 32)++ assert read_mp4_tags(path) == {"invokeai_workflow": "{}"}+++def test_top_level_walk_is_bounded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ udta = _keyed_metadata_boxes({"invokeai_metadata": "{}"}, full_meta_box=True)+ path = tmp_path / "junk.mp4"+ junk = _box(b"free", b"") * 100+ path.write_bytes(junk + _box(b"moov", udta) + _box(b"mdat", b""))+ monkeypatch.setattr("invokeai.app.util.mp4_metadata._MAX_TOP_LEVEL_BOXES", 50)++ assert read_mp4_tags(path) == {}+++def test_write_raises_on_an_undecodable_source(tmp_path: Path) -> None:+ garbage = tmp_path / "garbage.mp4"+ garbage.write_bytes(b"\x00\x00\x00\x18ftypmp42 not a real mp4")++ with pytest.raises(Mp4MetadataError):+ write_mp4_tags(garbage, tmp_path / "out.mp4", {"invokeai_metadata": "{}"})+++def test_read_ftyp_major_brand(tiny_mp4: Path, tmp_path: Path) -> None:+ assert read_ftyp_major_brand(tiny_mp4) == b"isom"+ qt = tmp_path / "qt.mov"+ qt.write_bytes(_box(b"ftyp", b"qt " + b"\x00" * 8) + _box(b"mdat", b""))+ assert read_ftyp_major_brand(qt) == b"qt "+ late = tmp_path / "late.mp4"+ late.write_bytes(_box(b"free", b"\x00" * (70 * 1024)) + _box(b"ftyp", b"isom" + b"\x00" * 8))+ assert read_ftyp_major_brand(late) is None+ (tmp_path / "none.bin").write_bytes(b"not boxes at all")+ assert read_ftyp_major_brand(tmp_path / "none.bin") is None