From f561f5682684d727375f1b92af53f2077d991309 Mon Sep 17 00:00:00 2001 From: Terry Jia Date: Tue, 28 Jul 2026 15:17:11 -0400 Subject: [PATCH] feat: VIDEO_EDIT input type with asset-backed video metadata --- app/assets/scanner.py | 9 +- app/assets/services/ingest.py | 48 +++--- app/assets/services/media_metadata.py | 31 ++++ app/assets/services/video_metadata.py | 81 ++++++++++ comfy_api/latest/_input/video_types.py | 35 ++++- comfy_api/latest/_input_impl/video_types.py | 120 +++++++++++++-- comfy_api/latest/_io.py | 36 +++++ comfy_api/latest/_util/__init__.py | 3 +- comfy_api/latest/_util/video_types.py | 20 +++ comfy_extras/nodes_video.py | 135 ++++++++++++++++- .../services/test_video_metadata.py | 138 ++++++++++++++++++ 11 files changed, 613 insertions(+), 43 deletions(-) create mode 100644 app/assets/services/media_metadata.py create mode 100644 app/assets/services/video_metadata.py create mode 100644 tests-unit/assets_test/services/test_video_metadata.py diff --git a/app/assets/scanner.py b/app/assets/scanner.py index 42c4c1e9d..17a445d56 100644 --- a/app/assets/scanner.py +++ b/app/assets/scanner.py @@ -33,7 +33,7 @@ from app.assets.services.file_utils import ( verify_file_unchanged, ) from app.assets.services.hashing import HashCheckpoint, compute_blake3_hash -from app.assets.services.image_dimensions import extract_image_dimensions +from app.assets.services.media_metadata import extract_media_metadata from app.assets.services.metadata_extract import extract_file_metadata from app.assets.services.path_utils import ( compute_loader_path, @@ -507,10 +507,9 @@ def enrich_asset( if extract_metadata and metadata: system_metadata = metadata.to_user_metadata() - if mime_type and mime_type.startswith("image/"): - dims = extract_image_dimensions(file_path, mime_type=mime_type) - if dims: - system_metadata.update(dims) + dims = extract_media_metadata(file_path, mime_type=mime_type) + if dims: + system_metadata.update(dims) set_reference_system_metadata(session, reference_id, system_metadata) if full_hash: diff --git a/app/assets/services/ingest.py b/app/assets/services/ingest.py index 1ffb3d634..bbdfe9f1e 100644 --- a/app/assets/services/ingest.py +++ b/app/assets/services/ingest.py @@ -31,7 +31,10 @@ from app.assets.database.queries import ( from app.assets.helpers import get_utc_now, normalize_tags from app.assets.services.bulk_ingest import batch_insert_seed_assets from app.assets.services.file_utils import get_size_and_mtime_ns -from app.assets.services.image_dimensions import extract_image_dimensions +from app.assets.services.media_metadata import ( + MEDIA_METADATA_KEYS, + extract_media_metadata, +) from app.assets.services.path_utils import ( compute_loader_path, get_name_and_tags_from_asset_path, @@ -138,7 +141,7 @@ def _ingest_file_from_path( user_metadata=user_metadata, ) - _maybe_store_image_dimensions( + _maybe_store_media_metadata( session, reference_id=reference_id, file_path=locator, @@ -316,7 +319,7 @@ def _register_existing_asset( user_metadata=new_meta, ) - _backfill_image_dimensions_from_siblings( + _backfill_media_metadata_from_siblings( session, asset_id=asset.id, new_reference_id=ref.id, @@ -369,25 +372,22 @@ def _update_metadata_with_filename( ) -_IMAGE_DIMENSION_KEYS = ("kind", "width", "height") +_MEDIA_KINDS = ("image", "video") -def _maybe_store_image_dimensions( +def _maybe_store_media_metadata( session: Session, reference_id: str, file_path: str, mime_type: str | None, current_system_metadata: dict | None, ) -> None: - """Populate ``kind``/``width``/``height`` on system_metadata for image refs. + """Populate media keys on system_metadata for image and video refs. - Non-image MIME types are a no-op. Pre-existing keys (e.g. enricher-written + Non-media MIME types are a no-op. Pre-existing keys (e.g. enricher-written safetensors metadata, download provenance) are preserved by merge. """ - if not mime_type or not mime_type.startswith("image/"): - return - - dims = extract_image_dimensions(file_path, mime_type=mime_type) + dims = extract_media_metadata(file_path, mime_type=mime_type) if not dims: return @@ -402,31 +402,35 @@ def _maybe_store_image_dimensions( ) -def _backfill_image_dimensions_from_siblings( +def _backfill_media_metadata_from_siblings( session: Session, asset_id: str, new_reference_id: str, current_system_metadata: dict | None, ) -> None: - """Copy image dimension keys from any sibling reference of the same asset. + """Copy media metadata keys from any sibling reference of the same asset. - The from-hash path doesn't read the file bytes, so dimensions can't be + The from-hash path doesn't read the file bytes, so metadata can't be extracted there directly. When another reference of the same asset already - carries image dimensions, copy them onto the new reference so consumers - see consistent metadata regardless of how the asset was registered. + carries media metadata, copy it onto the new reference so consumers see + consistent metadata regardless of how the asset was registered. - Best-effort: missing siblings, non-image siblings, or absent dimension + Best-effort: missing siblings, non-media siblings, or absent metadata keys leave the target reference unchanged. """ current = current_system_metadata or {} - if current.get("kind") == "image" and "width" in current and "height" in current: + if ( + current.get("kind") in _MEDIA_KINDS + and "width" in current + and "height" in current + ): return for sibling in list_references_by_asset_id(session, asset_id): if sibling.id == new_reference_id: continue meta = sibling.system_metadata or {} - if meta.get("kind") != "image": + if meta.get("kind") not in _MEDIA_KINDS: continue width = meta.get("width") height = meta.get("height") @@ -438,9 +442,9 @@ def _backfill_image_dimensions_from_siblings( ): continue merged = dict(current) - merged["kind"] = "image" - merged["width"] = width - merged["height"] = height + for key in MEDIA_METADATA_KEYS: + if key in meta: + merged[key] = meta[key] if merged != current: set_reference_system_metadata( session, diff --git a/app/assets/services/media_metadata.py b/app/assets/services/media_metadata.py new file mode 100644 index 000000000..ca0ddd539 --- /dev/null +++ b/app/assets/services/media_metadata.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from typing import Any + +from app.assets.services.image_dimensions import extract_image_dimensions +from app.assets.services.video_metadata import extract_video_metadata + +MEDIA_METADATA_KEYS = ( + "kind", + "width", + "height", + "duration", + "fps", + "frame_count", +) + + +def extract_media_metadata( + file_path: str, mime_type: str | None = None +) -> dict[str, Any] | None: + """Extract media metadata for the file, dispatched on the MIME prefix. + + Returns ``None`` for non-media MIME types or unreadable files. + """ + if not mime_type: + return None + if mime_type.startswith("image/"): + return extract_image_dimensions(file_path, mime_type=mime_type) + if mime_type.startswith("video/"): + return extract_video_metadata(file_path, mime_type=mime_type) + return None diff --git a/app/assets/services/video_metadata.py b/app/assets/services/video_metadata.py new file mode 100644 index 000000000..603b503c0 --- /dev/null +++ b/app/assets/services/video_metadata.py @@ -0,0 +1,81 @@ +"""Video metadata extraction for asset ingest. + +Reads only the container/stream headers via PyAV to capture dimensions, +duration, fps and frame count cheaply, without decoding frames. Returns a +metadata dict suitable for merging into ``AssetReference.system_metadata``. +""" +from __future__ import annotations + +import logging +from typing import Any + +logger = logging.getLogger(__name__) + + +def extract_video_metadata( + file_path: str, mime_type: str | None = None +) -> dict[str, Any] | None: + """Extract video stream metadata for the file at ``file_path``. + + Args: + file_path: Absolute path to a file on disk. + mime_type: Optional MIME type hint. When provided and not prefixed + with ``video/``, extraction is skipped without touching the file. + + Returns: + ``{"kind": "video", "width": W, "height": H, ...}`` with optional + ``duration`` (seconds), ``fps`` and ``frame_count`` keys when the + file has a recognizable video stream, otherwise ``None``. + """ + if mime_type is not None and not mime_type.startswith("video/"): + return None + + try: + import av + except ImportError: + logger.debug( + "PyAV not available; skipping video metadata extraction for %s", + file_path, + ) + return None + + try: + with av.open(file_path) as container: + stream = next( + (s for s in container.streams if s.type == "video"), None + ) + if stream is None: + return None + + fps = float(stream.average_rate) if stream.average_rate else None + duration = None + if stream.duration is not None and stream.time_base is not None: + duration = float(stream.duration * stream.time_base) + elif container.duration is not None: + duration = float(container.duration * av.time_base) + frame_count = stream.frames or None + if frame_count is None and duration is not None and fps is not None: + frame_count = round(duration * fps) + + width = stream.codec_context.width + height = stream.codec_context.height + except (OSError, ValueError, av.error.FFmpegError) as exc: + logger.debug("Failed to read video metadata from %s: %s", file_path, exc) + return None + + if ( + not isinstance(width, int) + or not isinstance(height, int) + or width <= 0 + or height <= 0 + ): + return None + + metadata: dict[str, Any] = {"kind": "video", "width": width, "height": height} + if duration is not None: + metadata["duration"] = duration + if fps is not None: + metadata["fps"] = fps + if frame_count is not None: + metadata["frame_count"] = frame_count + return metadata diff --git a/comfy_api/latest/_input/video_types.py b/comfy_api/latest/_input/video_types.py index e2e99521f..d034279de 100644 --- a/comfy_api/latest/_input/video_types.py +++ b/comfy_api/latest/_input/video_types.py @@ -4,7 +4,7 @@ from fractions import Fraction from typing import Optional, Union, IO import io import av -from .._util import VideoContainer, VideoCodec, VideoComponents +from .._util import VideoContainer, VideoCodec, VideoComponents, normalize_crop_rect class VideoInput(ABC): """ @@ -52,6 +52,39 @@ class VideoInput(ABC): """ pass + def as_cropped( + self, + x: int = 0, + y: int = 0, + width: int = 0, + height: int = 0, + ) -> VideoInput: + """ + Create a new VideoInput spatially cropped to the given pixel rectangle. + + """ + components = self.get_components() + rect = normalize_crop_rect( + x, y, width, height, components.images.shape[2], components.images.shape[1] + ) + if rect is None: + return self + from .._input_impl.video_types import VideoFromComponents + + cx, cy, cw, ch = rect + return VideoFromComponents( + VideoComponents( + images=components.images[:, cy:cy + ch, cx:cx + cw, :], + audio=components.audio, + frame_rate=components.frame_rate, + metadata=components.metadata, + alpha=components.alpha[:, cy:cy + ch, cx:cx + cw] + if components.alpha is not None + else None, + ), + bit_depth=self.get_bit_depth(), + ) + def get_stream_source(self) -> Union[str, io.BytesIO]: """ Get a streamable source for the video. This allows processing without diff --git a/comfy_api/latest/_input_impl/video_types.py b/comfy_api/latest/_input_impl/video_types.py index f5af41973..f8fc0e8b4 100644 --- a/comfy_api/latest/_input_impl/video_types.py +++ b/comfy_api/latest/_input_impl/video_types.py @@ -12,7 +12,7 @@ import numpy as np import math import os import torch -from .._util import VideoContainer, VideoCodec, VideoComponents +from .._util import VideoContainer, VideoCodec, VideoComponents, normalize_crop_rect import logging @@ -111,12 +111,17 @@ def mp4_output_open_kwargs(path: str | io.BytesIO, format: VideoContainer, codec return open_kwargs +def _rotation_quadrant(frame: av.VideoFrame) -> int: + return int(round(frame.rotation // 90)) % 4 if frame.rotation else 0 + + class VideoFromFile(VideoInput): """ Class representing video input from a file. """ - def __init__(self, file: str | io.BytesIO, *, start_time: float=0, duration: float=0): + def __init__(self, file: str | io.BytesIO, *, start_time: float=0, duration: float=0, + crop: tuple[int, int, int, int] | None = None): """ Initialize the VideoFromFile object based off of either a path on disk or a BytesIO object containing the file contents. @@ -124,6 +129,7 @@ class VideoFromFile(VideoInput): self.__file = file self.__start_time = start_time self.__duration = duration + self.__crop = crop def get_stream_source(self) -> str | io.BytesIO: """ @@ -153,7 +159,31 @@ class VideoFromFile(VideoInput): for stream in container.streams: if stream.type == 'video': assert isinstance(stream, av.VideoStream) - return stream.width, stream.height + if self.__crop is None: + return stream.width, stream.height + + display_width, display_height = self._get_display_dimensions() + rect = normalize_crop_rect(*self.__crop, display_width, display_height) + if rect is not None: + return rect[2], rect[3] + return display_width, display_height + raise ValueError(f"No video stream found in file '{self.__file}'") + + def _get_display_dimensions(self) -> tuple[int, int]: + if isinstance(self.__file, io.BytesIO): + self.__file.seek(0) + with av.open(self.__file, mode='r') as container: + for stream in container.streams: + if stream.type == 'video': + assert isinstance(stream, av.VideoStream) + width, height = stream.width, stream.height + try: + frame = next(container.decode(stream), None) + except av.error.FFmpegError: + frame = None + if frame is not None and _rotation_quadrant(frame) % 2: + width, height = height, width + return width, height raise ValueError(f"No video stream found in file '{self.__file}'") def get_bit_depth(self) -> int: @@ -323,6 +353,8 @@ class VideoFromFile(VideoInput): streams = [video_stream] has_first_audio_frame = False checked_alpha = False + crop_rect = None + crop_resolved = False # Default to False so we decode until EOF if duration is 0 video_done = False @@ -393,9 +425,16 @@ class VideoFromFile(VideoInput): img = np.ascontiguousarray(align_graph[2].pull().to_ndarray(format=image_format)[:frame.height, :frame.width]) else: img = frame.to_ndarray(format=image_format) - if frame.rotation != 0: - k = int(round(frame.rotation // 90)) - img = np.rot90(img, k=k, axes=(0, 1)).copy() + rotation_quadrant = _rotation_quadrant(frame) + if rotation_quadrant: + img = np.rot90(img, k=rotation_quadrant, axes=(0, 1)).copy() + if self.__crop is not None: + if not crop_resolved: + crop_rect = normalize_crop_rect(*self.__crop, img.shape[1], img.shape[0]) + crop_resolved = True + if crop_rect is not None: + cx, cy, cw, ch = crop_rect + img = np.ascontiguousarray(img[cy:cy + ch, cx:cx + cw]) if alphas is None: frames.append(torch.from_numpy(img)) else: @@ -477,6 +516,8 @@ class VideoFromFile(VideoInput): reuse_streams = False if self.__start_time or self.__duration: reuse_streams = False + if self.__crop is not None: + reuse_streams = False if not reuse_streams: if bit_depth is None: @@ -556,6 +597,12 @@ class VideoFromFile(VideoInput): if duration: duration_cap = math.ceil(duration * sample_rate) + import comfy.utils + raw_duration = self._get_raw_duration() + window_seconds = duration if duration else max(raw_duration - start_time, 0.0) + progress_total = max(1, int(round(window_seconds * float(rate)))) + pbar = comfy.utils.ProgressBar(progress_total) + streams = [video_stream] if audio_stream is None else [video_stream, audio_stream] pts_step = max(1, int(round((1 / rate) / video_stream.time_base))) video_done = False @@ -568,6 +615,8 @@ class VideoFromFile(VideoInput): source_size = None rotation_k = 0 rotation_filter = None + crop_rect = None + crop_filter = None audio_started = False samples_written = 0 pending_audio = [] @@ -641,11 +690,15 @@ class VideoFromFile(VideoInput): if end_pts is not None and frame.pts is not None: frame_duration = min(frame_duration, end_pts - frame.pts) if output is None: - rotation_k = int(round(frame.rotation // 90)) % 4 if frame.rotation else 0 + rotation_k = _rotation_quadrant(frame) if rotation_k % 2: out_width, out_height = frame.height, frame.width else: out_width, out_height = frame.width, frame.height + if self.__crop is not None: + crop_rect = normalize_crop_rect(*self.__crop, out_width, out_height) + if crop_rect is not None: + out_width, out_height = crop_rect[2], crop_rect[3] if out_width % 2 or out_height % 2: raise ValueError(f"H.264 output requires even dimensions, got {out_width}x{out_height}") source_size = (frame.width, frame.height) @@ -684,9 +737,22 @@ class VideoFromFile(VideoInput): g_sink = g.add("buffersink") tail.link_to(g_sink) g.configure() - rotation_filter = (g_src, g_sink) - rotation_filter[0].push(frame) - frame = rotation_filter[1].pull() + rotation_filter = (g, g_src, g_sink) + rotation_filter[1].push(frame) + frame = rotation_filter[2].pull() + if crop_rect is not None: + if crop_filter is None: + g = av.filter.Graph() + g_src = g.add_buffer(width=frame.width, height=frame.height, + format=frame.format.name, time_base=video_stream.time_base) + g_crop = g.add("crop", f"{crop_rect[2]}:{crop_rect[3]}:{crop_rect[0]}:{crop_rect[1]}") + g_sink = g.add("buffersink") + g_src.link_to(g_crop) + g_crop.link_to(g_sink) + g.configure() + crop_filter = (g, g_src, g_sink) + crop_filter[1].push(frame) + frame = crop_filter[2].pull() if frame.color_range == ColorRange.JPEG: # compress full-range sources (yuvj/MJPEG) to limited range frame = frame.reformat(format=pix_fmt, src_color_range="JPEG", dst_color_range="MPEG") @@ -725,6 +791,7 @@ class VideoFromFile(VideoInput): out_packet.duration = video_frame_durations.pop(out_packet.pts, 0) output.mux(out_packet) drain_audio() + pbar.update(1) elif packet.stream == audio_stream and not audio_done: for resampled in itertools.chain.from_iterable(map(resampler.resample, packet.decode())): @@ -794,11 +861,42 @@ class VideoFromFile(VideoInput): self.get_stream_source(), start_time=start_time + self.__start_time, duration=duration, + crop=self.__crop, ) if trimmed.get_duration() < duration and strict_duration: return None return trimmed + def as_cropped( + self, x: int = 0, y: int = 0, width: int = 0, height: int = 0 + ) -> VideoInput: + if int(width) <= 0 or int(height) <= 0: + return self + + display_width, display_height = self._get_display_dimensions() + outer = ( + normalize_crop_rect(*self.__crop, display_width, display_height) + if self.__crop is not None + else None + ) + if outer is None: + rect = normalize_crop_rect(x, y, width, height, display_width, display_height) + else: + inner = normalize_crop_rect(x, y, width, height, outer[2], outer[3]) + rect = ( + (outer[0] + inner[0], outer[1] + inner[1], inner[2], inner[3]) + if inner is not None + else None + ) + if rect is None: + return self + return VideoFromFile( + self.get_stream_source(), + start_time=self.__start_time, + duration=self.__duration, + crop=rect, + ) + class VideoFromComponents(VideoInput): """ @@ -815,6 +913,8 @@ class VideoFromComponents(VideoInput): images=self.__components.images, audio=self.__components.audio, frame_rate=self.__components.frame_rate, + metadata=self.__components.metadata, + alpha=self.__components.alpha, ) def get_bit_depth(self) -> int: diff --git a/comfy_api/latest/_io.py b/comfy_api/latest/_io.py index 58e49d8e2..defa6ffc5 100644 --- a/comfy_api/latest/_io.py +++ b/comfy_api/latest/_io.py @@ -1361,6 +1361,41 @@ class BoundingBoxes(ComfyTypeIO): self.default = [] +@comfytype(io_type="VIDEO_EDIT") +class VideoEdit(ComfyTypeIO): + class VideoTrimSection(TypedDict): + start_time: float + duration: float + + class VideoCropSection(TypedDict): + x: int + y: int + width: int + height: int + + class VideoEditDict(TypedDict, total=False): + trim: 'VideoEdit.VideoTrimSection' + crop: 'VideoEdit.VideoCropSection' + Type = VideoEditDict + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, default: dict=None, features: list[str]=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, None, default, socketless, None, None, None, None, advanced) + self.features = features if features is not None else ["trim", "crop"] + if default is None: + self.default = {} + if "trim" in self.features: + self.default["trim"] = {"start_time": 0.0, "duration": 0.0} + if "crop" in self.features: + self.default["crop"] = {"x": 0, "y": 0, "width": 0, "height": 0} + + def as_dict(self): + return super().as_dict() | prune_dict({ + "features": self.features, + }) + + @comfytype(io_type="HISTOGRAM") class Histogram(ComfyTypeIO): """A histogram represented as a list of bin counts.""" @@ -2436,5 +2471,6 @@ __all__ = [ "Curve", "Histogram", "Range", + "VideoEdit", "NodeReplace", ] diff --git a/comfy_api/latest/_util/__init__.py b/comfy_api/latest/_util/__init__.py index b27f5a97e..c3c9f0183 100644 --- a/comfy_api/latest/_util/__init__.py +++ b/comfy_api/latest/_util/__init__.py @@ -1,4 +1,4 @@ -from .video_types import VideoContainer, VideoCodec, VideoComponents +from .video_types import VideoContainer, VideoCodec, VideoComponents, normalize_crop_rect from .geometry_types import VOXEL, MESH, SPLAT, File3D from .image_types import SVG @@ -7,6 +7,7 @@ __all__ = [ "VideoContainer", "VideoCodec", "VideoComponents", + "normalize_crop_rect", "VOXEL", "MESH", "SPLAT", diff --git a/comfy_api/latest/_util/video_types.py b/comfy_api/latest/_util/video_types.py index 6c9d6a526..2f8ae887d 100644 --- a/comfy_api/latest/_util/video_types.py +++ b/comfy_api/latest/_util/video_types.py @@ -48,3 +48,23 @@ class VideoComponents: audio: Optional[AudioInput] = None metadata: Optional[dict] = None alpha: Optional[MaskInput] = None + + +def normalize_crop_rect( + x: int, y: int, width: int, height: int, source_width: int, source_height: int +) -> Optional[tuple[int, int, int, int]]: + width = int(width) + height = int(height) + if width <= 0 or height <= 0: + return None + x = max(0, min(int(x), source_width - 1)) + y = max(0, min(int(y), source_height - 1)) + width = min(width, source_width - x) + height = min(height, source_height - y) + if x == 0 and y == 0 and width == source_width and height == source_height: + return None + width -= width % 2 + height -= height % 2 + if width <= 0 or height <= 0: + return None + return x, y, width, height diff --git a/comfy_extras/nodes_video.py b/comfy_extras/nodes_video.py index 3bfd00be4..9647c11ea 100644 --- a/comfy_extras/nodes_video.py +++ b/comfy_extras/nodes_video.py @@ -202,8 +202,14 @@ class LoadVideo(io.ComfyNode): display_name="Load Video", category="video", essentials_category="Basics", + has_intermediate_output=True, inputs=[ io.Combo.Input("file", options=sorted(files), upload=io.UploadType.video), + io.VideoEdit.Input( + "edit", + optional=True, + tooltip="Trim (seconds) and crop (pixels) applied on load. Zero values leave the video unchanged.", + ), ], outputs=[ io.Video.Output(), @@ -211,12 +217,17 @@ class LoadVideo(io.ComfyNode): ) @classmethod - def execute(cls, file) -> io.NodeOutput: + def execute(cls, file, edit=None) -> io.NodeOutput: video_path = folder_paths.get_annotated_filepath(file) - return io.NodeOutput(InputImpl.VideoFromFile(video_path)) + source = InputImpl.VideoFromFile(video_path) + video = apply_video_trim(source, (edit or {}).get("trim")) + video = apply_video_crop(video, (edit or {}).get("crop")) + if video is source: + return io.NodeOutput(video, ui=preview_input_video(file)) + return io.NodeOutput(video, ui=save_video_preview(video)) @classmethod - def fingerprint_inputs(s, file): + def fingerprint_inputs(s, file, edit=None): video_path = folder_paths.get_annotated_filepath(file) mod_time = os.path.getmtime(video_path) # Instead of hashing the file, we can just use the modification time to avoid @@ -224,12 +235,60 @@ class LoadVideo(io.ComfyNode): return mod_time @classmethod - def validate_inputs(s, file): + def validate_inputs(s, file, edit=None): if not folder_paths.exists_annotated_filepath(file): return "Invalid video file: {}".format(file) return True +def preview_input_video(file: str) -> ui.PreviewVideo: + name, _ = folder_paths.annotated_filepath(file) + subfolder, _, filename = name.replace("\\", "/").rpartition("/") + return ui.PreviewVideo([ui.SavedResult(filename, subfolder, io.FolderType.input)]) + + +def save_video_preview(video: Input.Video) -> ui.PreviewVideo: + width, height = video.get_dimensions() + full_output_folder, filename, counter, subfolder, _ = folder_paths.get_save_image_path( + "ComfyUI_temp_video", folder_paths.get_temp_directory(), width, height + ) + preview_format = Types.VideoContainer.MP4 + file = f"{filename}_{counter:05}_.{Types.VideoContainer.get_extension(preview_format)}" + video.save_to( + os.path.join(full_output_folder, file), + format=preview_format, + codec="auto", + ) + return ui.PreviewVideo([ui.SavedResult(file, subfolder, io.FolderType.temp)]) + + +def apply_video_trim(video: Input.Video, trim, strict_duration: bool = False) -> Input.Video: + trim = trim or {} + start_time = float(trim.get("start_time", 0.0)) + duration = float(trim.get("duration", 0.0)) + if duration < 0: + raise ValueError(f"Trim duration must be >= 0, got {duration}") + if start_time == 0.0 and duration == 0.0: + return video + + trimmed = video.as_trimmed(start_time, duration, strict_duration=strict_duration) + if trimmed is None: + raise ValueError( + f"Failed to trim video:\nSource duration: {video.get_duration()}\nStart time: {start_time}\nTarget duration: {duration}" + ) + return trimmed + + +def apply_video_crop(video: Input.Video, crop) -> Input.Video: + crop = crop or {} + return video.as_cropped( + int(crop.get("x", 0)), + int(crop.get("y", 0)), + int(crop.get("width", 0)), + int(crop.get("height", 0)), + ) + + class VideoSlice(io.ComfyNode): @classmethod def define_schema(cls): @@ -277,6 +336,72 @@ class VideoSlice(io.ComfyNode): ) +class VideoTrim(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="VideoTrim", + display_name="Trim Video", + search_aliases=["trim video duration", "skip first frames", "cut video", "start time"], + category="video", + is_experimental=True, + essentials_category="Video Tools", + has_intermediate_output=True, + inputs=[ + io.Video.Input("video"), + io.VideoEdit.Input( + "trim", + features=["trim"], + tooltip="Trim window in seconds. Duration 0 keeps the video until the end.", + ), + io.Boolean.Input( + "strict_duration", + default=False, + advanced=True, + tooltip="If True, when the specified duration is not possible, an error will be raised.", + ), + ], + outputs=[ + io.Video.Output(), + ], + ) + + @classmethod + def execute(cls, video: io.Video.Type, trim: io.VideoEdit.Type, strict_duration: bool) -> io.NodeOutput: + trimmed = apply_video_trim(video, (trim or {}).get("trim"), strict_duration=strict_duration) + return io.NodeOutput(trimmed, ui=save_video_preview(trimmed)) + + +class VideoCrop(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="VideoCrop", + display_name="Crop Video", + search_aliases=["crop video", "cut region", "spatial crop"], + category="video", + is_experimental=True, + essentials_category="Video Tools", + has_intermediate_output=True, + inputs=[ + io.Video.Input("video"), + io.VideoEdit.Input( + "crop", + features=["crop"], + tooltip="Crop region in pixels. Zero width/height keeps the full frame.", + ), + ], + outputs=[ + io.Video.Output(), + ], + ) + + @classmethod + def execute(cls, video: io.Video.Type, crop: io.VideoEdit.Type) -> io.NodeOutput: + cropped = apply_video_crop(video, (crop or {}).get("crop")) + return io.NodeOutput(cropped, ui=save_video_preview(cropped)) + + class VideoExtension(ComfyExtension): @override async def get_node_list(self) -> list[type[io.ComfyNode]]: @@ -287,6 +412,8 @@ class VideoExtension(ComfyExtension): GetVideoComponents, LoadVideo, VideoSlice, + VideoTrim, + VideoCrop, ] async def comfy_entrypoint() -> VideoExtension: diff --git a/tests-unit/assets_test/services/test_video_metadata.py b/tests-unit/assets_test/services/test_video_metadata.py new file mode 100644 index 000000000..cb9be0038 --- /dev/null +++ b/tests-unit/assets_test/services/test_video_metadata.py @@ -0,0 +1,138 @@ +"""Tests for the video_metadata service.""" +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pytest + +from app.assets.services.media_metadata import extract_media_metadata +from app.assets.services.video_metadata import extract_video_metadata + +av = pytest.importorskip("av") + + +def _make_mp4( + path: Path, width: int = 64, height: int = 48, frames: int = 12, fps: int = 8 +) -> Path: + with av.open(str(path), "w") as container: + stream = container.add_stream("libx264", rate=fps) + stream.width = width + stream.height = height + stream.pix_fmt = "yuv420p" + for _ in range(frames): + frame = av.VideoFrame.from_ndarray( + np.zeros((height, width, 3), dtype=np.uint8), format="rgb24" + ) + for packet in stream.encode(frame): + container.mux(packet) + for packet in stream.encode(): + container.mux(packet) + return path + + +class TestExtractVideoMetadata: + def test_extracts_stream_metadata(self, tmp_path: Path): + f = _make_mp4(tmp_path / "clip.mp4", width=64, height=48, frames=12, fps=8) + + result = extract_video_metadata(str(f), mime_type="video/mp4") + + assert result is not None + assert result["kind"] == "video" + assert result["width"] == 64 + assert result["height"] == 48 + assert result["frame_count"] == 12 + assert result["fps"] == pytest.approx(8.0) + assert result["duration"] == pytest.approx(12 / 8, abs=0.1) + + def test_works_when_mime_type_is_none(self, tmp_path: Path): + f = _make_mp4(tmp_path / "no_mime.mp4") + + result = extract_video_metadata(str(f), mime_type=None) + + assert result is not None + assert result["kind"] == "video" + + @pytest.mark.parametrize( + "mime", + ["application/json", "text/plain", "image/png", "audio/mpeg"], + ) + def test_skips_non_video_mime_types(self, tmp_path: Path, mime: str): + result = extract_video_metadata( + str(tmp_path / "untouched.mp4"), mime_type=mime + ) + + assert result is None + + def test_returns_none_for_missing_file(self, tmp_path: Path): + result = extract_video_metadata( + str(tmp_path / "does_not_exist.mp4"), mime_type="video/mp4" + ) + + assert result is None + + def test_returns_none_for_corrupt_video(self, tmp_path: Path): + f = tmp_path / "corrupt.mp4" + f.write_bytes(b"not actually an mp4 file") + + result = extract_video_metadata(str(f), mime_type="video/mp4") + + assert result is None + + +class TestExtractMediaMetadata: + def test_dispatches_video_mime_to_video_extractor(self, tmp_path: Path): + f = _make_mp4(tmp_path / "clip.mp4") + + result = extract_media_metadata(str(f), mime_type="video/mp4") + + assert result is not None + assert result["kind"] == "video" + + def test_dispatches_image_mime_to_image_extractor(self, tmp_path: Path): + from PIL import Image + + f = tmp_path / "img.png" + Image.new("RGB", (32, 16)).save(f, format="PNG") + + result = extract_media_metadata(str(f), mime_type="image/png") + + assert result == {"kind": "image", "width": 32, "height": 16} + + def test_returns_none_without_mime_type(self, tmp_path: Path): + f = _make_mp4(tmp_path / "clip.mp4") + + assert extract_media_metadata(str(f), mime_type=None) is None + + def test_returns_none_for_non_media_mime(self, tmp_path: Path): + f = tmp_path / "file.bin" + f.write_bytes(b"\x00") + + assert extract_media_metadata(str(f), mime_type="text/plain") is None + + +class TestIngestStoresVideoMetadata: + def test_register_file_in_place_stores_video_metadata( + self, mock_create_session, temp_dir: Path, session + ): + from app.assets.database.models import AssetReference + from app.assets.services.ingest import _ingest_file_from_path + + f = _make_mp4(temp_dir / "clip.mp4", width=64, height=48) + + result = _ingest_file_from_path( + abs_path=str(f), + asset_hash="blake3:video123", + size_bytes=f.stat().st_size, + mtime_ns=1234567890000000000, + mime_type="video/mp4", + ) + + assert result.reference_id is not None + ref = session.query(AssetReference).one() + meta = ref.system_metadata or {} + assert meta["kind"] == "video" + assert meta["width"] == 64 + assert meta["height"] == 48 + assert meta["frame_count"] == 12 + assert meta["fps"] == pytest.approx(8.0)