Skip to content

The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface. The fastest local inference engine in the world.

Support prores and using different chroma subsampling for video saving. (#17463)

comfyanonymous6d352802d8f8
diff --git a/comfy_api/latest/_input/video_types.py b/comfy_api/latest/_input/video_types.py
index 8b4936a47..71ce4615f 100644
--- a/comfy_api/latest/_input/video_types.py
+++ b/comfy_api/latest/_input/video_types.py
@@ -32,14 +32,20 @@ class VideoInput(ABC):
crf: float | None = None,
color_space: str | None = None,
preset: str | None = None,
+ chroma_subsampling: str | None = None,
):
"""
Abstract method to save the video input to a file.
- bit_depth selects the encoded bit depth; None keeps the video's native depth.
+ bit_depth requests the encoded bit depth; unsupported depths use the encoder's highest
+ supported depth with a warning. None keeps the video's native depth where supported.
crf selects the H.264 or AV1 constant rate factor; None uses 18 for H.264 or 24 for AV1 when encoding.
preset selects the H.264 encoder speed/compression trade-off (e.g. "ultrafast");
None uses the encoder default. Ignored for other codecs.
+ chroma_subsampling selects 444, 422, or 420. None keeps the video's requested or native
+ subsampling; unspecified tensor inputs use 444 for ProRes and 420 for H.264/AV1.
+ An explicit choice forces re-encoding. Unsupported choices use the closest supported mode
+ with a warning.
color_space="sRGB" selects SDR BT.709/sRGB, "HDR" selects BT.2020/HLG, and "HDR PQ"
selects BT.2020/PQ. Bit depth is selected independently.
Tensor-created videos default to sRGB when color_space is None. Loaded videos keep matching recognized native color
@@ -51,6 +57,10 @@ class VideoInput(ABC):
"""Return the video's color space as sRGB, HDR, HDR PQ, or auto when unspecified."""
return "auto"
+ def get_chroma_subsampling(self) -> str | None:
+ """Return requested or native chroma subsampling, or None for codec defaults."""
+ return None
+
@abstractmethod
def as_trimmed(
self,
@@ -103,6 +113,7 @@ class VideoInput(ABC):
else None,
),
bit_depth=self.get_bit_depth(),
+ chroma_subsampling=self.get_chroma_subsampling(),
)
def get_stream_source(self) -> Union[str, io.BytesIO]:
diff --git a/comfy_api/latest/_input_impl/video_types.py b/comfy_api/latest/_input_impl/video_types.py
index 91d147ed4..3f681f526 100644
--- a/comfy_api/latest/_input_impl/video_types.py
+++ b/comfy_api/latest/_input_impl/video_types.py
@@ -21,11 +21,13 @@ import logging
VIDEO_ENCODERS = {
VideoCodec.H264: "h264",
VideoCodec.AV1: "libsvtav1",
+ VideoCodec.PRORES: "prores_ks",
}
VIDEO_CONTAINER_FORMATS = {
VideoContainer.MP4: "mp4",
VideoContainer.MKV: "matroska",
VideoContainer.WEBM: "webm",
+ VideoContainer.MOV: "mov",
}
WEBM_STREAM_CODECS = {
"video": {"av1", "vp8", "vp9"},
@@ -98,6 +100,12 @@ def video_stream_bit_depth(stream) -> int:
return max(component.bits for component in stream.format.components)
+def video_stream_chroma_subsampling(stream) -> str | None:
+ if stream is None or stream.format is None or stream.format.is_rgb or len(stream.format.components) < 3:
+ return None
+ return {(2, 2): "444", (1, 2): "422", (1, 1): "420"}.get((stream.format.chroma_width(2), stream.format.chroma_height(2)))
+
+
def isobmff_hevc_filter(output_container, stream, out_stream):
"""Apple players need the 'hvc1' sample entry, not FFmpeg's default 'hev1'. Annex B input without
extradata makes the muxer build hvcC from the first packet and strip in-band parameter sets;
@@ -170,17 +178,21 @@ def video_output_config(path: str | io.BytesIO, format: VideoContainer, codec: V
if format == VideoContainer.AUTO:
extension = os.path.splitext(os.fspath(path))[1].lower() if isinstance(path, (str, os.PathLike)) else ""
format = {
+ ".mp4": VideoContainer.MP4,
".mkv": VideoContainer.MKV,
".webm": VideoContainer.WEBM,
- }.get(extension, VideoContainer.MP4)
+ ".mov": VideoContainer.MOV,
+ }.get(extension, VideoContainer.MOV if codec == VideoCodec.PRORES else VideoContainer.MP4)
if codec == VideoCodec.AUTO:
codec = VideoCodec.AV1 if format == VideoContainer.WEBM else VideoCodec.H264
if format == VideoContainer.WEBM and codec != VideoCodec.AV1:
raise ValueError("WebM output requires the AV1 codec")
+ if codec == VideoCodec.PRORES and format not in (VideoContainer.MOV, VideoContainer.MKV):
+ raise ValueError("ProRes output requires a MOV or MKV container")
# FFmpeg's faststart pass reopens the output by filename, so it cannot be used with file-like objects.
open_kwargs = {"mode": "w", "format": VIDEO_CONTAINER_FORMATS[format]}
- if format == VideoContainer.MP4:
+ if format in (VideoContainer.MP4, VideoContainer.MOV):
movflags = "use_metadata_tags+faststart" if isinstance(path, (str, os.PathLike)) else "use_metadata_tags"
open_kwargs["options"] = {"movflags": movflags}
return open_kwargs, format, codec
@@ -208,8 +220,10 @@ def video_stream_color_space(stream) -> str | None:
def video_encoder_options(
- codec: VideoCodec, crf: float | None, preset: str | None = None
+ codec: VideoCodec, crf: float | None, preset: str | None = None, pix_fmt: str | None = None
) -> dict[str, str]:
+ if codec == VideoCodec.PRORES:
+ return {"profile": "hq" if pix_fmt is not None and pix_fmt.startswith("yuv422p") else "4444", "alpha_bits": "16"}
if crf is None:
crf = 24 if codec == VideoCodec.AV1 else 18
options = {}
@@ -222,6 +236,43 @@ def video_encoder_options(
return options
+def video_pixel_format(codec: VideoCodec, bit_depth: int, chroma_subsampling: str | None = None, has_alpha: bool = False) -> str:
+ subsampling_order = ("444", "422", "420")
+ default_subsampling = "444" if codec == VideoCodec.PRORES else "420"
+ if chroma_subsampling is None:
+ chroma_subsampling = default_subsampling
+ if chroma_subsampling not in subsampling_order:
+ raise ValueError(f"Unsupported chroma subsampling: {chroma_subsampling}")
+ encoder_formats = av.codec.Codec(VIDEO_ENCODERS[codec], "w").video_formats
+ supported_formats = {}
+ for subsampling in subsampling_order:
+ candidates = [
+ pixel_format for pixel_format in encoder_formats
+ if pixel_format.name.startswith((f"yuv{subsampling}p", f"yuva{subsampling}p"))
+ and pixel_format.name.endswith(("p", "le"))
+ ]
+ if candidates:
+ supported_formats[subsampling] = candidates
+ if chroma_subsampling not in supported_formats:
+ requested_index = subsampling_order.index(chroma_subsampling)
+ fallback = min(supported_formats, key=lambda subsampling: abs(subsampling_order.index(subsampling) - requested_index))
+ logging.warning("%s does not support %s chroma subsampling; saving as %s instead.", VIDEO_ENCODERS[codec], chroma_subsampling, fallback)
+ chroma_subsampling = fallback
+ candidates = supported_formats[chroma_subsampling]
+ save_alpha = has_alpha and any(pixel_format.name.startswith("yuva") for pixel_format in candidates)
+ formats = {
+ pixel_format.components[0].bits: pixel_format.name
+ for pixel_format in candidates
+ if pixel_format.name.startswith("yuva") == save_alpha
+ }
+ depth = max((depth for depth in formats if depth <= bit_depth), default=min(formats))
+ if depth < bit_depth:
+ logging.warning("%s does not support %d-bit color; saving at %d-bit instead.", VIDEO_ENCODERS[codec], bit_depth, depth)
+ if has_alpha and not save_alpha:
+ logging.warning("%s output does not support alpha; the alpha channel will be discarded.", codec.value.upper())
+ return formats[depth]
+
+
def webm_streams_compatible(streams) -> bool:
for stream in streams:
allowed_codecs = WEBM_STREAM_CODECS.get(stream.type)
@@ -319,6 +370,13 @@ class VideoFromFile(VideoInput):
video_stream = container.streams.video[0] if len(container.streams.video) > 0 else None
return video_stream_color_space(video_stream) or "sRGB"
+ def get_chroma_subsampling(self) -> str | None:
+ if isinstance(self.__file, io.BytesIO):
+ self.__file.seek(0)
+ with av.open(self.__file, mode="r") as container:
+ video_stream = container.streams.video[0] if len(container.streams.video) > 0 else None
+ return video_stream_chroma_subsampling(video_stream)
+
def get_duration(self) -> float:
"""
Returns the duration of the video in seconds.
@@ -646,6 +704,7 @@ class VideoFromFile(VideoInput):
crf: float | None = None,
color_space: str | None = None,
preset: str | None = None,
+ chroma_subsampling: str | None = None,
):
if color_space is not None and color_space not in VIDEO_COLOR_TRANSFERS:
raise ValueError(f"Unsupported video color space: {color_space}")
@@ -668,12 +727,16 @@ class VideoFromFile(VideoInput):
reuse_streams = False
if output_format == VideoContainer.WEBM and not webm_streams_compatible(container.streams):
reuse_streams = False
+ if output_format == VideoContainer.MP4 and video_encoding == "prores":
+ reuse_streams = False
if codec != VideoCodec.AUTO and codec != video_encoding and video_encoding is not None:
reuse_streams = False
if bit_depth is not None and video_encoding is not None and bit_depth != source_bit_depth:
reuse_streams = False
if crf is not None:
reuse_streams = False
+ if chroma_subsampling is not None:
+ reuse_streams = False
if color_space is not None:
reuse_streams = False
if self.__start_time or self.__duration:
@@ -684,7 +747,7 @@ class VideoFromFile(VideoInput):
if not reuse_streams:
if bit_depth is None:
bit_depth = source_bit_depth
- return self._save_transcoded(container, path, format=format, codec=codec, metadata=metadata, bit_depth=bit_depth, crf=crf, color_space=color_space, preset=preset)
+ return self._save_transcoded(container, path, format=format, codec=codec, metadata=metadata, bit_depth=bit_depth, crf=crf, color_space=color_space, preset=preset, chroma_subsampling=chroma_subsampling)
streams = container.streams
@@ -702,6 +765,8 @@ class VideoFromFile(VideoInput):
logging.warning("Skipping %s stream %d with unsupported codec", stream.type, stream.index)
continue
out_stream = output_container.add_stream_from_template(template=stream, opaque=True)
+ if stream.codec.canonical_name == "prores":
+ out_stream.codec_context.codec_tag = stream.codec_context.codec_tag
hevc_filter = isobmff_hevc_filter(output_container, stream, out_stream)
if hevc_filter is not None:
hevc_filters[stream] = hevc_filter
@@ -731,11 +796,14 @@ class VideoFromFile(VideoInput):
frame_rate: Fraction | None = None,
audio_sample_rate: int | None = None,
audio_layout: str | None = None,
+ chroma_subsampling: str | None = None,
):
"""Re-encode one frame at a time; peak memory does not scale with video length."""
open_kwargs, output_format, output_codec = video_output_config(path, format, codec)
video_stream = self._get_first_video_stream(container)
video_stream.thread_type = "AUTO"
+ if chroma_subsampling is None:
+ chroma_subsampling = video_stream_chroma_subsampling(video_stream)
start_time, duration = self.get_active_trim_window()
start_pts = int(start_time / video_stream.time_base)
end_pts = int((start_time + duration) / video_stream.time_base) if duration else None
@@ -751,7 +819,6 @@ class VideoFromFile(VideoInput):
audio_stream = last_decodable_audio_stream(container)
source_color_space = video_stream_color_space(video_stream)
preserve_source_color = source_color_space is not None
- pix_fmt = "yuv420p10le" if bit_depth >= 10 else "yuv420p"
rate = frame_rate or (Fraction(video_stream.average_rate) if video_stream.average_rate else Fraction(1))
resampler = None
@@ -874,6 +941,8 @@ 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:
+ has_alpha = any(component.is_alpha for component in frame.format.components)
+ pix_fmt = video_pixel_format(output_codec, bit_depth, chroma_subsampling, has_alpha)
rotation_k = _rotation_quadrant(frame)
if rotation_k % 2:
out_width, out_height = frame.height, frame.width
@@ -883,18 +952,16 @@ class VideoFromFile(VideoInput):
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) and crop_rect is None:
- even_width = out_width - out_width % 2
- even_height = out_height - out_height % 2
- if even_width > 0 and even_height > 0:
- crop_rect = (0, 0, even_width, even_height)
- out_width, out_height = even_width, even_height
- if out_width % 2 or out_height % 2:
- raise ValueError(f"{output_codec.value.upper()} output requires even dimensions, got {out_width}x{out_height}")
- if any(component.is_alpha for component in frame.format.components):
- logging.warning(
- "Transcoded video output does not support alpha; the alpha channel will be discarded."
- )
+ width_alignment = 2 if output_codec != VideoCodec.PRORES and pix_fmt.startswith(("yuv420p", "yuv422p")) else 1
+ height_alignment = 2 if output_codec != VideoCodec.PRORES and pix_fmt.startswith("yuv420p") else 1
+ if (out_width % width_alignment or out_height % height_alignment) and crop_rect is None:
+ aligned_width = out_width - out_width % width_alignment
+ aligned_height = out_height - out_height % height_alignment
+ if aligned_width > 0 and aligned_height > 0:
+ crop_rect = (0, 0, aligned_width, aligned_height)
+ out_width, out_height = aligned_width, aligned_height
+ if out_width % width_alignment or out_height % height_alignment:
+ raise ValueError(f"{output_codec.value.upper()} {pix_fmt} output requires dimensions divisible by {width_alignment}x{height_alignment}, got {out_width}x{out_height}")
source_size = (frame.width, frame.height)
output = av.open(path, **open_kwargs)
# Add metadata before writing any streams
@@ -903,7 +970,7 @@ class VideoFromFile(VideoInput):
out_video.width = out_width
out_video.height = out_height
out_video.pix_fmt = pix_fmt
- out_video.options = video_encoder_options(output_codec, crf, preset)
+ out_video.options = video_encoder_options(output_codec, crf, preset, pix_fmt)
if preserve_source_color:
copy_color_properties(video_stream, out_video.codec_context)
elif color_space is not None:
@@ -1106,13 +1173,14 @@ class VideoFromComponents(VideoInput):
Class representing video input from tensors.
"""
- def __init__(self, components: VideoComponents, bit_depth: int = 8, color_space: str = "sRGB"):
+ def __init__(self, components: VideoComponents, bit_depth: int = 8, color_space: str = "sRGB", chroma_subsampling: str | None = None):
if color_space not in VIDEO_COLOR_TRANSFERS:
raise ValueError(f"Unsupported video color space: {color_space}")
self.__components = components
# Tensor components have no inherent bit depth; this is the depth used when encoding.
self.__bit_depth = bit_depth
self.__color_space = color_space
+ self.__chroma_subsampling = chroma_subsampling
def get_components(self) -> VideoComponents:
return VideoComponents(
@@ -1129,6 +1197,9 @@ class VideoFromComponents(VideoInput):
def get_color_space(self) -> str:
return self.__color_space
+ def get_chroma_subsampling(self) -> str | None:
+ return self.__chroma_subsampling
+
def save_to(
self,
path: str,
@@ -1139,17 +1210,23 @@ class VideoFromComponents(VideoInput):
crf: float | None = None,
color_space: str | None = None,
preset: str | None = None,
+ chroma_subsampling: str | None = None,
):
"""Save the video to a file path or BytesIO buffer."""
if color_space is None:
color_space = self.__color_space
if color_space is not None and color_space not in VIDEO_COLOR_TRANSFERS:
raise ValueError(f"Unsupported video color space: {color_space}")
- open_kwargs, output_format, output_codec = video_output_config(path, format, codec)
# None means "use the depth this video was created with" (CreateVideo's choice).
if bit_depth is None:
bit_depth = self.__bit_depth
- is_10bit = bit_depth >= 10
+ if chroma_subsampling is None:
+ chroma_subsampling = self.__chroma_subsampling
+ open_kwargs, output_format, output_codec = video_output_config(path, format, codec)
+ has_alpha = self.__components.alpha is not None or self.__components.images.shape[-1] == 4
+ pix_fmt = video_pixel_format(output_codec, bit_depth, chroma_subsampling, has_alpha)
+ save_alpha = pix_fmt.startswith("yuva")
+ high_bit_depth = av.VideoFormat(pix_fmt).components[0].bits > 8
with av.open(path, **open_kwargs) as output:
# Add metadata before writing any streams
if metadata is not None:
@@ -1158,12 +1235,11 @@ class VideoFromComponents(VideoInput):
frame_rate = Fraction(round(self.__components.frame_rate * 1000), 1000)
# Create a video stream
- pix_fmt = "yuv420p10le" if is_10bit else "yuv420p"
video_stream = output.add_stream(VIDEO_ENCODERS[output_codec], rate=frame_rate)
video_stream.width = self.__components.images.shape[2]
video_stream.height = self.__components.images.shape[1]
video_stream.pix_fmt = pix_fmt
- video_stream.options = video_encoder_options(output_codec, crf, preset)
+ video_stream.options = video_encoder_options(output_codec, crf, preset, pix_fmt)
if color_space is not None:
set_video_color_properties(video_stream.codec_context, color_space)
@@ -1184,13 +1260,17 @@ class VideoFromComponents(VideoInput):
# Encode video
for i, frame in enumerate(self.__components.images):
- if is_10bit:
- # 16-bit RGB keeps float precision through the conversion to 10-bit YUV.
- img = (frame.float() * 65535).clamp(0, 65535).cpu().numpy().astype(np.uint16) # shape: (H, W, 3)
- frame = av.VideoFrame.from_ndarray(img, format="rgb48le")
+ if save_alpha and self.__components.alpha is not None:
+ frame = torch.cat((frame[..., :3], self.__components.alpha[i].reshape(*frame.shape[:2], 1).to(frame)), dim=-1)
+ elif not save_alpha:
+ frame = frame[..., :3]
+ if high_bit_depth:
+ # Keep 16-bit precision until conversion to the encoder's pixel format.
+ img = (frame.float() * 65535).clamp(0, 65535).cpu().numpy().astype(np.uint16)
+ frame = av.VideoFrame.from_ndarray(img, format="rgba64le" if save_alpha else "rgb48le")
else:
- img = (frame * 255).clamp(0, 255).byte().cpu().numpy() # shape: (H, W, 3)
- frame = av.VideoFrame.from_ndarray(img, format='rgb24')
+ img = (frame * 255).clamp(0, 255).byte().cpu().numpy()
+ frame = av.VideoFrame.from_ndarray(img, format='rgba' if save_alpha else 'rgb24')
dst_colorspace = None
if color_space == "sRGB":
dst_colorspace = BT709_NCL
@@ -1324,6 +1404,9 @@ class VideoFromList(VideoInput):
def get_color_space(self):
return self.videos[0].get_color_space()
+ def get_chroma_subsampling(self):
+ return self.videos[0].get_chroma_subsampling()
+
def get_duration(self):
return sum(video.get_duration() for video in self.videos)
@@ -1334,7 +1417,7 @@ class VideoFromList(VideoInput):
return self.videos[0].get_frame_rate()
def save_to(self, path, format=VideoContainer.AUTO, codec=VideoCodec.AUTO, metadata=None,
- bit_depth=None, crf=None, color_space=None, preset=None):
+ bit_depth=None, crf=None, color_space=None, preset=None, chroma_subsampling=None):
open_kwargs, output_format, output_codec = video_output_config(path, format, codec)
requested_codec = VideoCodec(codec)
output = None
@@ -1403,10 +1486,11 @@ class VideoFromList(VideoInput):
video_stream_color_space(video_stream),
audio_stream.sample_rate if audio_stream else None,
audio_stream.layout.name if audio_stream else None,
+ video_stream_chroma_subsampling(video_stream),
)
source_signatures = []
- shared_encode = crf is not None or color_space is not None
+ shared_encode = crf is not None or color_space is not None or chroma_subsampling is not None
for video in self.videos:
with av.open(video.get_stream_source()) as container:
current_signature = encoded_signature(container)
@@ -1416,6 +1500,7 @@ class VideoFromList(VideoInput):
(requested_codec != VideoCodec.AUTO and current_signature[0] != requested_codec.value)
or (bit_depth is not None and current_signature[4] != bit_depth)
or (output_format == VideoContainer.WEBM and video_stream.codec.canonical_name not in WEBM_STREAM_CODECS["video"])
+ or (output_format == VideoContainer.MP4 and video_stream.codec.canonical_name == "prores")
or video.get_active_trim_window() != (0.0, 0.0)
or video.get_dimensions() != (video_stream.width, video_stream.height)
)
@@ -1429,6 +1514,7 @@ class VideoFromList(VideoInput):
target_frame_rate = Fraction(self.videos[0].get_frame_rate())
target_audio_rate = source_signatures[0][6]
target_audio_layout = source_signatures[0][7]
+ target_chroma_subsampling = chroma_subsampling if chroma_subsampling is not None else source_signatures[0][8]
try:
for index, video in enumerate(self.videos):
@@ -1447,6 +1533,7 @@ class VideoFromList(VideoInput):
crf=crf,
color_space=target_color_space,
preset=preset,
+ chroma_subsampling=target_chroma_subsampling,
preserve_source_timestamps=False,
frame_rate=target_frame_rate,
audio_sample_rate=target_audio_rate,
@@ -1459,7 +1546,7 @@ class VideoFromList(VideoInput):
current_signature = encoded_signature(container)
if signature is not None and current_signature != signature:
container.close()
- fields = ("codec", "extradata", "width", "height", "bit depth", "color space", "audio rate", "audio layout")
+ fields = ("codec", "extradata", "width", "height", "bit depth", "color space", "audio rate", "audio layout", "chroma subsampling")
differences = "; ".join(
f"{field}: expected {expected!r}, got {actual!r}"
for field, expected, actual in zip(fields, signature, current_signature)
@@ -1474,6 +1561,8 @@ class VideoFromList(VideoInput):
output = av.open(path, **open_kwargs)
write_output_metadata(container, output, metadata)
output_video = output.add_stream_from_template(video_stream, opaque=True)
+ if video_stream.codec.canonical_name == "prores":
+ output_video.codec_context.codec_tag = video_stream.codec_context.codec_tag
if self.complete_audio is not None:
source_rate = int(self.complete_audio["sample_rate"])
channels = self.complete_audio["waveform"].shape[1]
@@ -1538,8 +1627,10 @@ class VideoFromList(VideoInput):
def get_stream_source(self):
if self.__buffer is None:
+ with av.open(self.videos[0].get_stream_source()) as container:
+ output_format = VideoContainer.MOV if container.streams.video[0].codec.canonical_name == "prores" else VideoContainer.MP4
self.__buffer = io.BytesIO()
- self.save_to(self.__buffer, format=VideoContainer.MP4)
+ self.save_to(self.__buffer, format=output_format)
self.__buffer.seek(0)
return self.__buffer
diff --git a/comfy_api/latest/_util/video_types.py b/comfy_api/latest/_util/video_types.py
index 3451034ac..db5f17339 100644
--- a/comfy_api/latest/_util/video_types.py
+++ b/comfy_api/latest/_util/video_types.py
@@ -8,6 +8,7 @@ class VideoCodec(str, Enum):
AUTO = "auto"
H264 = "h264"
AV1 = "av1"
+ PRORES = "prores"
@classmethod
def as_input(cls) -> list[str]:
@@ -21,6 +22,7 @@ class VideoContainer(str, Enum):
MP4 = "mp4"
MKV = "mkv"
WEBM = "webm"
+ MOV = "mov"
@classmethod
def as_input(cls) -> list[str]:
@@ -42,6 +44,8 @@ class VideoContainer(str, Enum):
return "mkv"
if value == VideoContainer.WEBM:
return "webm"
+ if value == VideoContainer.MOV:
+ return "mov"
return ""
@dataclass
diff --git a/comfy_extras/nodes_video.py b/comfy_extras/nodes_video.py
index a753211ed..afb7d6927 100644
--- a/comfy_extras/nodes_video.py
+++ b/comfy_extras/nodes_video.py
@@ -123,6 +123,8 @@ def _save_video_codec_input(supported_codecs: list[str], *, optional=False, hidd
],
)
)
+ if "prores" in supported_codecs:
+ codec_options.append(io.DynamicCombo.Option("prores", []))
return io.DynamicCombo.Input(
"codec",
options=codec_options,
@@ -148,14 +150,15 @@ class SaveVideo(io.ComfyNode):
io.DynamicCombo.Input(
"format",
options=[
- io.DynamicCombo.Option("auto", [_save_video_codec_input(["auto", "h264", "av1"])]),
+ io.DynamicCombo.Option("auto", [_save_video_codec_input(["auto", "h264", "av1", "prores"])]),
io.DynamicCombo.Option("mp4", [_save_video_codec_input(["auto", "h264", "av1"])]),
- io.DynamicCombo.Option("mkv", [_save_video_codec_input(["auto", "h264", "av1"])]),
+ io.DynamicCombo.Option("mkv", [_save_video_codec_input(["auto", "h264", "av1", "prores"])]),
io.DynamicCombo.Option("webm", [_save_video_codec_input(["auto", "av1"])]),
+ io.DynamicCombo.Option("mov", [_save_video_codec_input(["prores"])]),
],
- tooltip="The output container. Auto uses MP4 for Auto/H.264 and WebM for AV1. MP4, MKV, and WebM select a specific container.",
+ tooltip="Auto uses MOV for ProRes, WebM for AV1, and MP4 otherwise.",
),
- _save_video_codec_input(["auto", "h264", "av1"], optional=True, hidden=True),
+ _save_video_codec_input(["auto", "h264", "av1", "prores"], optional=True, hidden=True),
],
hidden=[io.Hidden.prompt, io.Hidden.extra_pnginfo],
is_output_node=True,
@@ -170,10 +173,10 @@ class SaveVideo(io.ComfyNode):
else:
format_name = format
if codec is None:
- codec = {"codec": "auto"}
+ codec = {"codec": "prores" if format_name == "mov" else "auto"}
codec_name = codec["codec"]
if format_name == "auto":
- format_name = "webm" if codec_name == "av1" else "mp4"
+ format_name = {"av1": "webm", "prores": "mov"}.get(codec_name, "mp4")
encoding = codec.get("encoding") or {}
width, height = video.get_dimensions()
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(
@@ -231,6 +234,13 @@ class CreateVideo(io.ComfyNode):
optional=True,
tooltip="Colorspace of the input images. HDR selects BT.2020/HLG and HDR PQ selects BT.2020/PQ.",
),
+ io.Combo.Input(
+ "chroma_subsampling",
+ options=["auto", "444", "422", "420"],
+ default="auto",
+ optional=True,
+ tooltip="444 keeps full color resolution, 422 halves horizontal color resolution, and 420 halves both axes. Auto uses the codec default. Unsupported choices use the closest supported mode and print a console warning.",
+ ),
io.Combo.Input(
"codec",
options=["none", *Types.VideoCodec.as_input()],
@@ -247,7 +257,7 @@ class CreateVideo(io.ComfyNode):
@classmethod
def execute(
- cls, images: Input.Image, fps: float, audio: Optional[Input.Audio] = None, bit_depth: int | str = "auto", color_space: str = "sRGB", codec: str = "none",
+ cls, images: Input.Image, fps: float, audio: Optional[Input.Audio] = None, bit_depth: int | str = "auto", color_space: str = "sRGB", codec: str = "none", chroma_subsampling: str = "auto",
) -> io.NodeOutput:
if bit_depth == "auto":
bit_depth = 10 if color_space in ("HDR", "HDR PQ") else 8
@@ -255,6 +265,7 @@ class CreateVideo(io.ComfyNode):
Types.VideoComponents(images=images, audio=audio, frame_rate=Fraction(fps)),
bit_depth=bit_depth,
color_space=color_space,
+ chroma_subsampling=None if chroma_subsampling == "auto" else chroma_subsampling,
)
if codec != "none":
video = InputImpl.VideoFromList([video], codec=Types.VideoCodec(codec))
diff --git a/tests-unit/comfy_api_test/video_accumulation_test.py b/tests-unit/comfy_api_test/video_accumulation_test.py
index dcb26dc3e..c61246e0b 100644
--- a/tests-unit/comfy_api_test/video_accumulation_test.py
+++ b/tests-unit/comfy_api_test/video_accumulation_test.py
@@ -84,7 +84,7 @@ def test_create_video_optional_eager_encoding(monkeypatch):
codec_input = next(input for input in CreateVideo.define_schema().inputs if input.id == "codec")
assert isinstance(video, VideoFromList)
assert encoded_codecs == [VideoCodec.AV1]
- assert codec_input.options == ["none", "auto", "h264", "av1"]
+ assert codec_input.options == ["none", "auto", "h264", "av1", "prores"]
assert codec_input.default == "none"
assert codec_input.advanced and codec_input.optional
diff --git a/tests-unit/comfy_api_test/video_bit_depth_test.py b/tests-unit/comfy_api_test/video_bit_depth_test.py
index 715a09129..97d7e0299 100644
--- a/tests-unit/comfy_api_test/video_bit_depth_test.py
+++ b/tests-unit/comfy_api_test/video_bit_depth_test.py
@@ -2,11 +2,13 @@ import pytest
import torch
import av
import numpy as np
+import io
+import json
from fractions import Fraction
from types import SimpleNamespace
-from comfy_api.latest._input_impl.video_types import VideoFromFile, VideoFromComponents
+from comfy_api.latest._input_impl.video_types import VideoFromFile, VideoFromComponents, VideoFromList
from comfy_api.latest._util.video_types import VideoComponents
-from comfy_extras.nodes_video import CreateVideo, SaveVideo
+from comfy_extras.nodes_video import CreateVideo, LoadVideo, SaveVideo
@pytest.fixture(scope="module")
@@ -37,7 +39,7 @@ def probe(path):
"""(codec, pix_fmt, bit_depth) of the first video stream"""
with av.open(path) as container:
stream = container.streams.video[0]
- return (stream.codec.name, stream.format.name, max(c.bits for c in stream.format.components))
+ return (stream.codec.canonical_name, stream.format.name, max(c.bits for c in stream.format.components))
def decoded_levels(path):
@@ -93,6 +95,7 @@ def test_create_video_node_bit_depth_options():
("auto", "mp4", "h264"),
("h264", "mp4", "h264"),
("av1", "webm", "av1"),
+ ("prores", "mov", "prores"),
],
)
def test_save_video_auto_format(gradient_components, tmp_path, monkeypatch, codec, expected_suffix, expected_codec):
@@ -153,3 +156,271 @@ def test_get_bit_depth(gradient_components, src8, src10):
assert VideoFromFile(src10).get_bit_depth() == 10
assert VideoFromComponents(gradient_components, bit_depth=10).get_bit_depth() == 10
assert VideoFromComponents(gradient_components).get_bit_depth() == 8
+
+
[email protected]("source_kind", ["components", "file", "list"])
[email protected]("codec,extension", [("h264", "mp4"), ("av1", "webm")])
+def test_12bit_falls_back_with_warning(gradient_components, src10, tmp_path, caplog, source_kind, codec, extension):
+ video = VideoFromComponents(gradient_components, bit_depth=12)
+ options = {}
+ if source_kind == "file":
+ video = VideoFromFile(src10)
+ options["bit_depth"] = 12
+ elif source_kind == "list":
+ video = VideoFromList([VideoFromFile(src10), VideoFromFile(src10)])
+ options["bit_depth"] = 12
+ path = str(tmp_path / f"fallback.{extension}")
+ video.save_to(path, codec=codec, **options)
+
+ assert probe(path) == (codec, "yuv420p10le", 10)
+ assert "does not support 12-bit color; saving at 10-bit instead" in caplog.text
+ assert decoded_levels(path) > 20
+
+
[email protected]("source_kind", ["components", "file", "list"])
[email protected]("chroma,encoded_profile", [
+ ("444", "4444"),
+ ("422", "HQ"),
+])
+def test_prores_chroma_subsampling(gradient_components, src10, tmp_path, caplog, source_kind, chroma, encoded_profile):
+ video = VideoFromComponents(gradient_components)
+ if source_kind == "file":
+ video = VideoFromFile(src10)
+ elif source_kind == "list":
+ video = VideoFromList([VideoFromFile(src10), VideoFromFile(src10)])
+ path = str(tmp_path / "prores.mov")
+ video.save_to(path, codec="prores", chroma_subsampling=chroma, bit_depth=12)
+
+ with av.open(path) as container:
+ stream = container.streams.video[0]
+ assert stream.codec.canonical_name == "prores"
+ assert stream.profile == encoded_profile
+ assert stream.format.name.startswith(f"yuv{chroma}p")
+ assert len(list(container.decode(stream))) == (6 if source_kind == "list" else 3)
+ assert "prores_ks does not support 12-bit color; saving at 10-bit instead" in caplog.text
+ assert decoded_levels(path) > 20
+
+
[email protected]("alpha_source", ["rgba", "mask"])
+def test_prores_alpha_roundtrip(gradient_components, tmp_path, caplog, alpha_source):
+ images = gradient_components.images
+ alpha = torch.linspace(0, 1, images.shape[2]).expand(images.shape[:3]).contiguous()
+ components = VideoComponents(
+ images=torch.cat((images, alpha.unsqueeze(-1)), dim=-1) if alpha_source == "rgba" else images,
+ alpha=alpha if alpha_source == "mask" else None,
+ frame_rate=gradient_components.frame_rate,
+ )
+ source = str(tmp_path / "alpha.mov")
+ VideoFromComponents(components, bit_depth=10).save_to(source, codec="prores", chroma_subsampling="444")
+ output = str(tmp_path / "alpha-transcoded.mov")
+ VideoFromFile(source).save_to(output, codec="prores", chroma_subsampling="444", bit_depth=10)
+
+ for path in (source, output):
+ decoded = VideoFromFile(path).get_components()
+ assert decoded.alpha is not None
+ torch.testing.assert_close(decoded.alpha.squeeze(-1), alpha, atol=0.003, rtol=0)
+ assert "alpha channel will be discarded" not in caplog.text
+
+
+def test_prores_chroma_change_reencodes(gradient_components, tmp_path):
+ source = str(tmp_path / "444.mov")
+ VideoFromComponents(gradient_components).save_to(source, codec="prores", chroma_subsampling="444")
+ output = str(tmp_path / "422.mov")
+ VideoFromFile(source).save_to(output, codec="prores", chroma_subsampling="422", bit_depth=10)
+ with av.open(output) as container:
+ assert container.streams.video[0].profile == "HQ"
+ assert container.streams.video[0].format.name == "yuv422p10le"
+ assert video_packet_bytes(output) != video_packet_bytes(source)
+
+
[email protected]("output_kind", ["file", "buffer"])
+def test_prores_audio_and_metadata(gradient_components, tmp_path, output_kind):
+ components = VideoComponents(
+ images=gradient_components.images,
+ frame_rate=gradient_components.frame_rate,
+ audio={"waveform": torch.zeros(1, 2, 4800), "sample_rate": 48000},
+ )
+ path = io.BytesIO() if output_kind == "buffer" else str(tmp_path / "metadata.mov")
+ VideoFromComponents(components, bit_depth=10).save_to(path, codec="prores", metadata={"prompt": {"test": True}})
+ if output_kind == "buffer":
+ path.seek(0)
+ with av.open(path) as container:
+ assert container.format.name.startswith("mov")
+ assert json.loads(container.metadata["prompt"]) == {"test": True}
+ assert container.streams.video[0].profile == "4444"
+ assert container.streams.audio[0].sample_rate == 48000
+ assert sum(frame.samples for frame in container.decode(audio=0)) >= 4800
+
+
+def test_save_video_prores_defaults(gradient_components, tmp_path, monkeypatch, caplog):
+ schema = SaveVideo.define_schema()
+ assert all("chroma_subsampling" not in str(input.as_dict()) for input in schema.inputs)
+ format_input = next(input for input in schema.inputs if input.id == "format")
+ mov_option = next(option for option in format_input.options if option.key == "mov")
+ prores_option = mov_option.inputs[0].options[0]
+ assert prores_option.key == "prores"
+ assert prores_option.inputs == []
+ chroma_input = next(input for input in CreateVideo.define_schema().inputs if input.id == "chroma_subsampling")
+ assert chroma_input.options == ["auto", "444", "422", "420"]
+ assert chroma_input.default == "auto"
+ monkeypatch.setattr(SaveVideo, "hidden", SimpleNamespace(prompt=None, extra_pnginfo=None))
+ monkeypatch.setattr("comfy_extras.nodes_video.folder_paths.get_output_directory", lambda: str(tmp_path))
+ monkeypatch.setattr(
+ "comfy_extras.nodes_video.folder_paths.get_save_image_path",
+ lambda *args: (str(tmp_path), "prores", 1, "", "prores"),
+ )
+ SaveVideo.execute(VideoFromComponents(gradient_components), "prores", "mov")
+ with av.open(str(tmp_path / "prores_00001_.mov")) as container:
+ assert container.streams.video[0].profile == "4444"
+ assert container.streams.video[0].format.name.startswith("yuv444p")
+ assert "does not support" not in caplog.text
+
+
+def test_prores_rejects_mp4(gradient_components, tmp_path):
+ with pytest.raises(ValueError, match="ProRes output requires a MOV or MKV container"):
+ VideoFromComponents(gradient_components).save_to(str(tmp_path / "bad.mp4"), format="mp4", codec="prores")
+
+
[email protected]("codec,extension", [("prores", "mov"), ("h264", "mp4")])
+def test_444_transcode_preserves_odd_dimensions(tmp_path, codec, extension):
+ video = VideoFromComponents(
+ VideoComponents(images=torch.rand(2, 65, 63, 3), frame_rate=Fraction(30)), bit_depth=10,
+ )
+ source = str(tmp_path / f"source.{extension}")
+ output = str(tmp_path / f"transcoded.{extension}")
+ video.save_to(source, codec=codec, chroma_subsampling="444")
+ VideoFromFile(source).save_to(output, codec=codec, bit_depth=10, chroma_subsampling="444")
+ with av.open(output) as container:
+ frames = list(container.decode(video=0))
+ assert [(frame.width, frame.height) for frame in frames] == [(63, 65)] * 2
+
+
[email protected]("chroma", ["444", "422"])
+def test_prores_remux_preserves_profile(gradient_components, tmp_path, chroma):
+ source = str(tmp_path / "source.mov")
+ output = str(tmp_path / "remux.mov")
+ VideoFromComponents(gradient_components).save_to(source, codec="prores", chroma_subsampling=chroma)
+ VideoFromFile(source).save_to(output, format="mov", codec="prores")
+ with av.open(source) as original, av.open(output) as remuxed:
+ assert remuxed.streams.video[0].profile == original.streams.video[0].profile
+ assert remuxed.streams.video[0].codec_context.codec_tag == original.streams.video[0].codec_context.codec_tag
+ assert video_packet_bytes(output) == video_packet_bytes(source)
+
+
[email protected]("source_kind", ["components", "file", "list"])
[email protected]("chroma", ["444", "422", "420"])
[email protected]("bit_depth", [8, 10])
+def test_h264_chroma_subsampling(gradient_components, src10, tmp_path, source_kind, chroma, bit_depth):
+ video = VideoFromComponents(gradient_components)
+ if source_kind == "file":
+ video = VideoFromFile(src10)
+ elif source_kind == "list":
+ video = VideoFromList([VideoFromFile(src10), VideoFromFile(src10)])
+ path = str(tmp_path / "chroma.mp4")
+ video.save_to(path, codec="h264", bit_depth=bit_depth, chroma_subsampling=chroma)
+ assert probe(path) == ("h264", f"yuv{chroma}p" + ("10le" if bit_depth == 10 else ""), bit_depth)
+ with av.open(path) as container:
+ assert len(list(container.decode(video=0))) == (6 if source_kind == "list" else 3)
+
+
[email protected]("codec,extension,requested,actual", [("av1", "webm", "444", "420"), ("prores", "mov", "420", "422")])
+def test_unsupported_chroma_falls_back(gradient_components, tmp_path, caplog, codec, extension, requested, actual):
+ path = str(tmp_path / f"fallback.{extension}")
+ VideoFromComponents(gradient_components).save_to(path, codec=codec, chroma_subsampling=requested)
+ with av.open(path) as container:
+ assert container.streams.video[0].format.name.startswith(f"yuv{actual}p")
+ assert f"does not support {requested} chroma subsampling; saving as {actual} instead" in caplog.text
+
+
[email protected]("eager", [False, True])
[email protected]("codec,extension,requested,actual", [
+ ("h264", "mp4", "444", "444"),
+ ("h264", "mp4", "422", "422"),
+ ("h264", "mp4", "420", "420"),
+ ("av1", "webm", "444", "420"),
+ ("av1", "webm", "422", "420"),
+ ("av1", "webm", "420", "420"),
+ ("prores", "mov", "444", "444"),
+ ("prores", "mov", "422", "422"),
+ ("prores", "mov", "420", "422"),
+ ("auto", "mp4", "444", "444"),
+])
+def test_create_video_chroma_control(gradient_components, tmp_path, monkeypatch, caplog, eager, codec, extension, requested, actual):
+ monkeypatch.setattr(SaveVideo, "hidden", SimpleNamespace(prompt=None, extra_pnginfo=None))
+ monkeypatch.setattr("comfy_extras.nodes_video.folder_paths.get_output_directory", lambda: str(tmp_path))
+ monkeypatch.setattr(
+ "comfy_extras.nodes_video.folder_paths.get_save_image_path",
+ lambda *args: (str(tmp_path), "chroma", 1, "", "chroma"),
+ )
+ video = CreateVideo.execute(
+ gradient_components.images, 30, bit_depth=10, chroma_subsampling=requested,
+ codec=codec if eager else "none",
+ ).args[0]
+ assert video.get_chroma_subsampling() == (actual if eager else requested)
+ SaveVideo.execute(video, "chroma", {"format": extension, "codec": {"codec": codec}})
+ with av.open(str(tmp_path / f"chroma_00001_.{extension}")) as container:
+ assert container.streams.video[0].format.name.startswith(f"yuv{actual}p")
+ assert len(list(container.decode(video=0))) == 3
+ if requested != actual:
+ assert f"does not support {requested} chroma subsampling; saving as {actual} instead" in caplog.text
+ else:
+ assert "chroma subsampling; saving" not in caplog.text
+
+
[email protected]("source_chroma,has_alpha", [("444", False), ("444", True), ("422", False)])
[email protected]("format_name,codec,extension", [("mov", "prores", "mov"), ("auto", "prores", "mov"), ("auto", "auto", "mp4"), ("mp4", "auto", "mp4")])
+def test_load_and_save_prores_nodes(gradient_components, tmp_path, monkeypatch, source_chroma, has_alpha, format_name, codec, extension):
+ monkeypatch.setattr(SaveVideo, "hidden", SimpleNamespace(prompt=None, extra_pnginfo=None))
+ monkeypatch.setattr("comfy_extras.nodes_video.folder_paths.get_input_directory", lambda: str(tmp_path))
+ monkeypatch.setattr("comfy_extras.nodes_video.folder_paths.get_output_directory", lambda: str(tmp_path))
+ images = gradient_components.images
+ alpha = torch.linspace(0, 1, images.shape[2]).expand(images.shape[:3]).contiguous() if has_alpha else None
+ components = VideoComponents(
+ images=images, alpha=alpha, frame_rate=gradient_components.frame_rate,
+ audio={"waveform": (torch.sin(torch.arange(4800) * (2 * torch.pi * 440 / 48000)) * 0.1).reshape(1, 1, -1), "sample_rate": 48000},
+ )
+ VideoFromComponents(components, bit_depth=10).save_to(str(tmp_path / "source.mov"), codec="prores", chroma_subsampling=source_chroma)
+ assert "source.mov" in LoadVideo.define_schema().inputs[0].options
+ loaded = LoadVideo.execute("source.mov").args[0]
+ decoded = loaded.get_components()
+ assert decoded.images.shape == images.shape
+ assert decoded.audio is not None
+ assert (decoded.alpha is not None) == has_alpha
+
+ options = {"codec": codec}
+ SaveVideo.execute(loaded, "roundtrip", {"format": format_name, "codec": options})
+ path = next(tmp_path.glob(f"roundtrip_*.{extension}"))
+ saved = VideoFromFile(str(path)).get_components()
+ assert saved.images.shape == images.shape
+ assert saved.audio is not None
+ expected_samples = images.shape[0] * 48000 // int(components.frame_rate)
+ # AAC pads the final frame to a block of 1024 samples.
+ assert expected_samples <= saved.audio["waveform"].shape[-1] < expected_samples + 1024
+ assert saved.audio["waveform"].abs().mean() > 0.01
+ with av.open(str(path)) as container:
+ assert container.streams.video[0].codec.canonical_name == ("prores" if codec == "prores" else "h264")
+ if codec == "prores" and has_alpha:
+ torch.testing.assert_close(saved.alpha.squeeze(-1), alpha, atol=0.003, rtol=0)
+ else:
+ assert saved.alpha is None
+
+
[email protected]("chroma", ["444", "422"])
[email protected]("operation", ["crop", "trim", "transcode", "concatenate"])
+def test_created_chroma_survives_video_operations(gradient_components, tmp_path, chroma, operation):
+ video = CreateVideo.execute(gradient_components.images, 30, bit_depth=10, chroma_subsampling=chroma).args[0]
+ save_options = {}
+ if operation == "crop":
+ video = video.as_cropped(0, 0, 32, 32)
+ elif operation == "trim":
+ video = video.as_trimmed(0, 1 / 30)
+ elif operation == "transcode":
+ video = VideoFromFile(video.get_stream_source())
+ save_options["crf"] = 20
+ else:
+ second = CreateVideo.execute(gradient_components.images, 30, bit_depth=8, chroma_subsampling=chroma).args[0]
+ video = VideoFromList([video, second])
+ path = str(tmp_path / "preserved.mp4")
+ video.save_to(path, **save_options)
+ assert video.get_chroma_subsampling() == chroma
+ assert probe(path) == ("h264", f"yuv{chroma}p10le", 10)