Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: scale, crop and trim MiniMax-H3 reference media (#9631)

oobaboogab6c01c9b25af
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index e28f31da30d..3e85d75c70b 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -368,7 +368,13 @@ def resolve_local_single_file(model_path: str) -> Optional[str]:
return checkpoints[0] if len(checkpoints) == 1 else None
-def decode_b64_image(data: str, *, mode: str = "RGB") -> Any:
+def decode_b64_image(
+ data: str,
+ *,
+ mode: str = "RGB",
+ max_side: int = 4096,
+ max_pixels: Optional[int] = None,
+) -> Any:
"""Decode a base64 (optionally ``data:`` URL) image string to a PIL image.
The image-conditioned workflows (img2img / inpaint / edit) transport the input
@@ -388,14 +394,17 @@ def decode_b64_image(data: str, *, mode: str = "RGB") -> Any:
blob = base64.b64decode(raw, validate = False)
except (binascii.Error, ValueError) as exc:
raise ValueError(f"Invalid base64 image data: {exc}") from exc
- # Bound the decoded size: 4096px covers txt2img 2048, upscales and outpaint canvases.
- max_side = 4096
+ # Preprocessing paths may choose different bounded source limits.
try:
img = Image.open(io.BytesIO(blob))
# Reject from the header before img.load() so a huge-dimension file cannot spike memory.
w, h = img.size
if w > max_side or h > max_side:
raise ValueError(f"Image is too large ({w}x{h}); maximum is {max_side}px per side.")
+ if max_pixels is not None and w * h > max_pixels:
+ raise ValueError(
+ f"Image is too large ({w}x{h}); maximum is {max_pixels:,} source pixels."
+ )
img.load()
except ValueError:
raise # the size guard's own message; don't wrap it as a decode error
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 12a948b90db..e18a13a2222 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -140,6 +140,8 @@ from .video_minimax_h3 import (
H3_ANCHOR_LAST,
H3_CANVAS_MAX_PIXELS,
H3_CANVAS_SHORT_EDGE,
+ H3_REF_IMAGE_SOURCE_MAX_PIXELS,
+ H3_REF_IMAGE_SOURCE_MAX_SIDE,
H3_REF_SIZE_MATCH,
H3_TASK_REFERENCES,
fit_h3_keyframe,
@@ -550,6 +552,21 @@ class _VideoLoadState:
resolved: Optional[dict] = None
+@dataclass(frozen = True)
+class _VideoResolvedInputs:
+ """CPU-side request inputs resolved against one exact resident pipeline state."""
+
+ state: _VideoLoadState
+ first_frame: Any
+ last_frame: Any
+ width: int
+ height: int
+ conditioning: str
+ references: Any
+ flow_shift: Optional[float]
+ audio_flow_shift: Optional[float]
+
+
@dataclass
class _VideoLoadingState:
repo_id: str
@@ -4955,54 +4972,63 @@ class VideoBackend:
sentinels the route maps to 409.
"""
cancel = threading.Event()
- # Snapshot load state before decoding outside the backend lock.
- with self._lock:
- if self._state is None:
- raise RuntimeError(VIDEO_NOT_LOADED_MSG)
- if self._generate_job_active:
- raise RuntimeError(VIDEO_GENERATION_BUSY_MSG)
- family = self._state.family
- task = self._state.h3_task
- engine = self._state.engine
- # Validate conditioning before creating the asynchronous job so request errors return 400.
- _, _, canvas_w, canvas_h, _ = self._resolve_keyframes(
- family, task, first_frame, last_frame, width, height
- )
- self._resolve_references(
- family,
- task,
- engine,
- reference_images,
- reference_videos,
- reference_audios,
- reference_image_size,
- canvas_w,
- canvas_h,
- )
- self._resolve_flow_shifts(family, engine, flow_shift, audio_flow_shift)
- with self._lock:
- if self._state is None:
- raise RuntimeError(VIDEO_NOT_LOADED_MSG)
- if self._generate_job_active:
- raise RuntimeError(VIDEO_GENERATION_BUSY_MSG)
- # Under the SAME lock that reserves the state this job will run against. A load
- # commits its new state here too, so judging the shape from a separate earlier read
- # could accept a size for the family being replaced and then denoise it with the new
- # one, or reject a size the new family supports. getattr, so a state carrying no
- # family degrades to the old snapping rather than raising.
- fam = getattr(self._state, "family", None)
- if fam is not None:
- validate_video_request_shape(fam, width = width, height = height, num_frames = num_frames)
- self._generate_job_active = True
- # Register BEFORE the worker starts so a cancel/unload in the spawn window still stops the run.
- self._active_generate_cancel = cancel
- self._gen = {
- "active": True,
- "phase": "queued",
- "step": 0,
- "total": 0,
- "eta_seconds": None,
- }
+ while True:
+ # Resolve outside the lock, then retry if the resident state changed.
+ with self._lock:
+ state = self._state
+ if state is None:
+ raise RuntimeError(VIDEO_NOT_LOADED_MSG)
+ if self._generate_job_active:
+ raise RuntimeError(VIDEO_GENERATION_BUSY_MSG)
+ first_pil, last_pil, canvas_w, canvas_h, conditioning = self._resolve_keyframes(
+ state.family, state.h3_task, first_frame, last_frame, width, height
+ )
+ references = self._resolve_references(
+ state.family,
+ state.h3_task,
+ state.engine,
+ reference_images,
+ reference_videos,
+ reference_audios,
+ reference_image_size,
+ canvas_w,
+ canvas_h,
+ )
+ shift, audio_shift = self._resolve_flow_shifts(
+ state.family, state.engine, flow_shift, audio_flow_shift
+ )
+ if references:
+ conditioning = h3_conditioning_mode(has_references = True)
+ resolved_inputs = _VideoResolvedInputs(
+ state = state,
+ first_frame = first_pil,
+ last_frame = last_pil,
+ width = canvas_w,
+ height = canvas_h,
+ conditioning = conditioning,
+ references = references,
+ flow_shift = shift,
+ audio_flow_shift = audio_shift,
+ )
+ with self._lock:
+ if self._state is not state:
+ continue
+ if self._generate_job_active:
+ raise RuntimeError(VIDEO_GENERATION_BUSY_MSG)
+ validate_video_request_shape(
+ state.family, width = width, height = height, num_frames = num_frames
+ )
+ self._generate_job_active = True
+ # Register before the worker starts so cancellation covers the spawn window.
+ self._active_generate_cancel = cancel
+ self._gen = {
+ "active": True,
+ "phase": "queued",
+ "step": 0,
+ "total": 0,
+ "eta_seconds": None,
+ }
+ break
threading.Thread(
target = self._run_generate,
kwargs = dict(
@@ -5016,14 +5042,7 @@ class VideoBackend:
guidance = guidance,
guidance_2 = guidance_2,
seed = seed,
- first_frame = first_frame,
- last_frame = last_frame,
- reference_images = reference_images,
- reference_videos = reference_videos,
- reference_audios = reference_audios,
- reference_image_size = reference_image_size,
- flow_shift = flow_shift,
- audio_flow_shift = audio_flow_shift,
+ _resolved_inputs = resolved_inputs,
cancel_event = cancel,
),
daemon = True,
@@ -5159,6 +5178,7 @@ class VideoBackend:
flow_shift: Optional[float] = None,
audio_flow_shift: Optional[float] = None,
cancel_event: Optional[threading.Event] = None,
+ _resolved_inputs: Optional[_VideoResolvedInputs] = None,
) -> dict[str, Any]:
# begin_generate passes its already-registered event; a direct call makes its own.
cancel = cancel_event if cancel_event is not None else threading.Event()
@@ -5170,6 +5190,8 @@ class VideoBackend:
state = self._state
if state is None:
raise RuntimeError(VIDEO_NOT_LOADED_MSG)
+ if _resolved_inputs is not None and _resolved_inputs.state is not state:
+ raise RuntimeError(VIDEO_CANCELLED_MSG)
self._active_generate_cancel = cancel
# Bound below, once the request is resolved. None means the failure beat the
# resolution, and there is nothing truthful to report.
@@ -5181,22 +5203,35 @@ class VideoBackend:
# the pipeline sits on the selected one.
self._state_device_target(state)
fam = state.family
- first_pil, last_pil, width, height, conditioning = self._resolve_keyframes(
- fam, state.h3_task, first_frame, last_frame, width, height
- )
- references = self._resolve_references(
- fam,
- state.h3_task,
- state.engine,
- reference_images,
- reference_videos,
- reference_audios,
- reference_image_size,
- width,
- height,
- )
- if references:
- conditioning = h3_conditioning_mode(has_references = True)
+ if _resolved_inputs is None:
+ first_pil, last_pil, width, height, conditioning = self._resolve_keyframes(
+ fam, state.h3_task, first_frame, last_frame, width, height
+ )
+ references = self._resolve_references(
+ fam,
+ state.h3_task,
+ state.engine,
+ reference_images,
+ reference_videos,
+ reference_audios,
+ reference_image_size,
+ width,
+ height,
+ )
+ if references:
+ conditioning = h3_conditioning_mode(has_references = True)
+ shift, audio_shift = self._resolve_flow_shifts(
+ fam, state.engine, flow_shift, audio_flow_shift
+ )
+ else:
+ first_pil = _resolved_inputs.first_frame
+ last_pil = _resolved_inputs.last_frame
+ width = _resolved_inputs.width
+ height = _resolved_inputs.height
+ conditioning = _resolved_inputs.conditioning
+ references = _resolved_inputs.references
+ shift = _resolved_inputs.flow_shift
+ audio_shift = _resolved_inputs.audio_flow_shift
frames = snap_num_frames(fam, num_frames or fam.default_num_frames)
out_fps = (
fam.default_fps if fam.name == "minimax-h3" else int(fps or fam.default_fps)
@@ -5231,10 +5266,6 @@ class VideoBackend:
if not fam.supports_cfg:
guidance = float(fam.default_guidance)
negative_prompt = None
- shift, audio_shift = self._resolve_flow_shifts(
- fam, state.engine, flow_shift, audio_flow_shift
- )
-
if state.engine == "sd_cpp":
return self._generate_h3_native(
state = state,
@@ -5649,6 +5680,7 @@ class VideoBackend:
MiniMaxH3References,
decode_h3_reference_audio,
decode_h3_reference_video,
+ validate_h3_reference_trim,
)
images = list(reference_images or [])
@@ -5669,7 +5701,12 @@ class VideoBackend:
fitted_images = tuple(
fit_h3_reference_image(
- decode_b64_image(item, mode = "RGB"),
+ decode_b64_image(
+ item,
+ mode = "RGB",
+ max_side = H3_REF_IMAGE_SOURCE_MAX_SIDE,
+ max_pixels = H3_REF_IMAGE_SOURCE_MAX_PIXELS,
+ ),
width = width,
height = height,
policy = policy,
@@ -5679,10 +5716,26 @@ class VideoBackend:
decoded_videos = []
for item in videos:
blob = _decode_b64_media(item.get("video") if isinstance(item, dict) else item)
- frames, waveform, sample_rate = decode_h3_reference_video(blob)
+ trim_start = item.get("trim_start_seconds") if isinstance(item, dict) else None
+ trim_end = item.get("trim_end_seconds") if isinstance(item, dict) else None
override = item.get("audio") if isinstance(item, dict) else None
+ frames, waveform, sample_rate = decode_h3_reference_video(
+ blob,
+ trim_start_seconds = trim_start,
+ trim_end_seconds = trim_end,
+ decode_audio = not bool(override),
+ )
if override:
- waveform, sample_rate = decode_h3_reference_audio(_decode_b64_media(override))
+ # A replacement soundtrack is a separate upload on its own timeline: it starts
+ # at its own zero and runs the clip's length. The video's coordinates dropped
+ # its first trim_start seconds and refused anything shorter. Only the embedded
+ # track shares the video's timeline.
+ clip = validate_h3_reference_trim(trim_start, trim_end)
+ waveform, sample_rate = decode_h3_reference_audio(
+ _decode_b64_media(override),
+ trim_start_seconds = None if clip is None else 0.0,
+ trim_end_seconds = None if clip is None else clip[1] - clip[0],
+ )
decoded_videos.append((frames, waveform, sample_rate))
if engine == "sd_cpp":
soundtrack_gap = False
diff --git a/studio/backend/core/inference/video_minimax_h3.py b/studio/backend/core/inference/video_minimax_h3.py
index 0e2370b7fb2..f6ae7dc7ba8 100644
--- a/studio/backend/core/inference/video_minimax_h3.py
+++ b/studio/backend/core/inference/video_minimax_h3.py
@@ -311,12 +311,40 @@ H3_MAX_REFERENCES = 12
# A reference video's trained window, in seconds.
H3_REF_VIDEO_MIN_SECONDS = 2.0
H3_REF_VIDEO_MAX_SECONDS = 15.0
+# How far a trim may reach past the video track before it is refused. A container reports its
+# longest track, so a file whose audio outruns its video reads as longer than it can show, and
+# a client picking an interval from that duration (HTMLMediaElement.duration, in Studio's case)
+# asks for slightly more video than exists. Within this margin the last frame is held instead.
+H3_REF_TRIM_COVERAGE_SLACK_SECONDS = 0.5
H3_FPS = 24
# "match" uses the generation area. Diffusers-only "max" uses a 2048px short edge.
H3_REF_SIZE_MATCH = "match"
H3_REF_SIZE_MAX = "max"
H3_REF_IMAGE_SHORT_EDGE = 2048
+# H3 downscales references immediately, so this path can accept larger bounded sources.
+H3_REF_IMAGE_SOURCE_MAX_SIDE = 8192
+H3_REF_IMAGE_SOURCE_MAX_PIXELS = 32_000_000
+
+
+def validate_h3_reference_trim(
+ start_seconds: Optional[float], end_seconds: Optional[float]
+) -> Optional[tuple[float, float]]:
+ """Validate an explicit reference-media interval, or return None for the whole source."""
+ if start_seconds is None and end_seconds is None:
+ return None
+ if start_seconds is None or end_seconds is None:
+ raise ValueError("Reference video trim start and end must be provided together.")
+ start, end = float(start_seconds), float(end_seconds)
+ if not math.isfinite(start) or not math.isfinite(end) or start < 0 or end <= start:
+ raise ValueError("Reference video trim must satisfy 0 <= start < end.")
+ duration = end - start
+ if duration + 1e-6 < H3_REF_VIDEO_MIN_SECONDS or duration - 1e-6 > H3_REF_VIDEO_MAX_SECONDS:
+ raise ValueError(
+ f"MiniMax-H3 reference video trims must be {H3_REF_VIDEO_MIN_SECONDS:g} to "
+ f"{H3_REF_VIDEO_MAX_SECONDS:g} seconds; this one is {duration:.1f}s."
+ )
+ return start, end
def h3_transformer_task(filename: str) -> str:
@@ -366,7 +394,13 @@ def h3_reference_frame_size(source_w: int, source_h: int) -> tuple[int, int]:
return width, height
-def decode_h3_reference_video(blob: bytes) -> tuple[list, Optional[Any], Optional[int]]:
+def decode_h3_reference_video(
+ blob: bytes,
+ *,
+ trim_start_seconds: Optional[float] = None,
+ trim_end_seconds: Optional[float] = None,
+ decode_audio: bool = True,
+) -> tuple[list, Optional[Any], Optional[int]]:
"""Decode one uploaded video to 24 fps frames plus its soundtrack, if it carries one.
Returns ``(frames, waveform, sample_rate)``. The frames land on MiniMax-H3's own 24 fps by
@@ -374,27 +408,116 @@ def decode_h3_reference_video(blob: bytes) -> tuple[list, Optional[Any], Optiona
implementation, and the one the Diffusers blocks make from a declared rate -- so both
engines receive a stream that is already on the model's clock. The waveform is float32
``(samples, channels)`` at the container's own rate; both engines resample it themselves.
+ ``decode_audio=False`` avoids touching an embedded track that a replacement will supersede.
"""
import io
import av
import numpy as np
+ trim = validate_h3_reference_trim(trim_start_seconds, trim_end_seconds)
+ video_timeline_start = None
+ if trim is None:
+ frames, duration, video_timeline_start = _decode_h3_video_without_trim(blob, av)
+ else:
+ try:
+ frames, video_timeline_start = _decode_h3_video_trim_by_timestamp(blob, av, trim)
+ except _H3MediaTimestampsUnavailable:
+ # Ordinal selection must restart because a seek makes frame zero keyframe-relative.
+ frames, video_timeline_start = _decode_h3_video_trim_by_ordinal(blob, av, trim)
+ duration = trim[1] - trim[0]
+ if not frames or duration + 1e-6 < H3_REF_VIDEO_MIN_SECONDS:
+ raise ValueError(
+ f"MiniMax-H3 reference videos run {H3_REF_VIDEO_MIN_SECONDS:g} to "
+ f"{H3_REF_VIDEO_MAX_SECONDS:g} seconds; this one is {duration:.1f}s."
+ )
+ expected_frames = int(round(duration * H3_FPS))
+ if trim is not None and len(frames) < expected_frames:
+ # Hold the last frame across a shortfall the slack allows, as the trim decoders do at
+ # their own endpoint; a larger gap means the range really was not there.
+ if len(frames) + math.ceil(H3_REF_TRIM_COVERAGE_SLACK_SECONDS * H3_FPS) < expected_frames:
+ raise ValueError("That reference video did not cover the selected range.")
+ frames.extend([frames[-1]] * (expected_frames - len(frames)))
+ frames = frames[:expected_frames]
+
+ waveform, sample_rate = (None, None)
+ if decode_audio:
+ with av.open(io.BytesIO(blob)) as container:
+ if container.streams.audio:
+ waveform, sample_rate = _decode_audio_stream(
+ container,
+ np,
+ trim_start_seconds = trim[0] if trim else None,
+ trim_end_seconds = trim[1] if trim else None,
+ timeline_start_seconds = video_timeline_start,
+ untrimmed_duration_seconds = len(frames) / H3_FPS if trim is None else None,
+ )
+ return frames, waveform, sample_rate
+
+
+class _H3MediaTimestampsUnavailable(Exception):
+ """Internal signal to retry a trim from the beginning using the declared rate."""
+
+
+def _stream_start_seconds(stream: Any) -> Optional[float]:
+ start_time = getattr(stream, "start_time", None)
+ time_base = getattr(stream, "time_base", None)
+ if start_time is None or time_base is None:
+ return None
+ return float(start_time * time_base)
+
+
+def _frame_timestamp_seconds(frame: Any) -> Optional[float]:
+ pts = getattr(frame, "pts", None)
+ time_base = getattr(frame, "time_base", None)
+ if pts is None or time_base is None:
+ return None
+ return float(pts * time_base)
+
+
+def _seek_media(container: Any, stream: Any, absolute_seconds: float, *, label: str) -> bool:
+ """Seek backward near an absolute stream timestamp when its time base permits it."""
+ time_base = getattr(stream, "time_base", None)
+ if time_base is None:
+ return False
+ offset = math.floor(absolute_seconds / float(time_base) + 1e-6)
+ try:
+ container.seek(offset, backward = True, any_frame = False, stream = stream)
+ except Exception as exc: # noqa: BLE001 -- decoder-specific seek errors become input feedback
+ raise ValueError(f"Could not seek to the requested reference {label} trim start.") from exc
+ return True
+
+
+def _fit_h3_video_frame(
+ frame: Any, fitted_size: Optional[tuple[int, int]]
+) -> tuple[Any, tuple[int, int]]:
+ from PIL import Image
+
+ image = frame.to_image().convert("RGB")
+ if fitted_size is None:
+ fitted_size = h3_reference_frame_size(*image.size)
+ if image.size != fitted_size:
+ image = image.resize(fitted_size, Image.LANCZOS)
+ return image, fitted_size
+
+
+def _decode_h3_video_without_trim(blob: bytes, av: Any) -> tuple[list, float, Optional[float]]:
+ """Preserve the existing whole-file rate-based behavior and its 15-second refusal."""
+ import io
+
with av.open(io.BytesIO(blob)) as container:
if not container.streams.video:
raise ValueError("That reference file carries no video track.")
stream = container.streams.video[0]
+ timeline_start = _stream_start_seconds(stream)
source_fps = float(stream.average_rate or stream.guessed_rate or H3_FPS)
if source_fps <= 0:
source_fps = float(H3_FPS)
- # Select, resample, and resize incrementally to bound memory for 4K inputs.
- from PIL import Image
-
+ max_source_frames = math.floor(H3_REF_VIDEO_MAX_SECONDS * source_fps + 1e-6)
frames = []
decoded_count = 0
next_target = 0
fitted_size = None
- max_source_frames = math.floor(H3_REF_VIDEO_MAX_SECONDS * source_fps + 1e-6)
for source_index, frame in enumerate(container.decode(video = 0)):
decoded_count = source_index + 1
if decoded_count > max_source_frames:
@@ -406,33 +529,142 @@ def decode_h3_reference_video(blob: bytes) -> tuple[list, Optional[Any], Optiona
target_source = int(next_target * source_fps / H3_FPS)
if target_source > source_index:
continue
- image = frame.to_image().convert("RGB")
- if fitted_size is None:
- fitted_size = h3_reference_frame_size(*image.size)
- if image.size != fitted_size:
- image = image.resize(fitted_size, Image.LANCZOS)
+ image, fitted_size = _fit_h3_video_frame(frame, fitted_size)
while int(next_target * source_fps / H3_FPS) <= source_index:
frames.append(image)
next_target += 1
-
if decoded_count == 0:
raise ValueError("That reference video decoded to no frames.")
- duration = decoded_count / source_fps
- if duration + 1e-6 < H3_REF_VIDEO_MIN_SECONDS:
- raise ValueError(
- f"MiniMax-H3 reference videos run {H3_REF_VIDEO_MIN_SECONDS:g} to "
- f"{H3_REF_VIDEO_MAX_SECONDS:g} seconds; this one is {duration:.1f}s."
- )
- frames = frames[: int(round(duration * H3_FPS))]
+ return frames, decoded_count / source_fps, timeline_start
- waveform, sample_rate = (None, None)
+
+def _decode_h3_video_trim_by_timestamp(
+ blob: bytes, av: Any, trim: tuple[float, float]
+) -> tuple[list, Optional[float]]:
+ """Select an explicit interval from presentation timestamps and stop at its endpoint."""
+ import io
+
+ start, end = trim
+ target_count = int(round((end - start) * H3_FPS))
with av.open(io.BytesIO(blob)) as container:
- if container.streams.audio:
- waveform, sample_rate = _decode_audio_stream(container, np)
- return frames, waveform, sample_rate
+ if not container.streams.video:
+ raise ValueError("That reference file carries no video track.")
+ stream = container.streams.video[0]
+ timeline_start = _stream_start_seconds(stream)
+ if timeline_start is not None and start > 0:
+ _seek_media(container, stream, timeline_start + start, label = "video")
+
+ frames = []
+ fitted_size = None
+ candidate = None
+ last_relative = None
+ last_duration = None
+
+ def _fill_until(relative_limit: float) -> None:
+ nonlocal fitted_size
+ if candidate is None:
+ return
+ wanted = min(
+ target_count,
+ max(0, math.ceil((relative_limit - start) * H3_FPS - 1e-6)),
+ )
+ if wanted <= len(frames):
+ return
+ image, fitted_size = _fit_h3_video_frame(candidate, fitted_size)
+ frames.extend([image] * (wanted - len(frames)))
+
+ for frame in container.decode(video = 0):
+ timestamp = _frame_timestamp_seconds(frame)
+ if timestamp is None:
+ raise _H3MediaTimestampsUnavailable
+ if timeline_start is None:
+ # Without a declared start or seek, the first frame is the timeline origin.
+ timeline_start = timestamp
+ relative = timestamp - timeline_start
+ if candidate is not None:
+ _fill_until(relative)
+ if len(frames) >= target_count:
+ return frames, timeline_start
+ candidate = frame
+ last_relative = relative
+ duration = getattr(frame, "duration", None)
+ time_base = getattr(frame, "time_base", None)
+ last_duration = (
+ float(duration * time_base)
+ if duration is not None and time_base is not None and duration > 0
+ else None
+ )
+
+ if candidate is None or last_relative is None:
+ raise ValueError("That reference video decoded to no frames in the selected range.")
+ declared_duration = getattr(stream, "duration", None)
+ stream_time_base = getattr(stream, "time_base", None)
+ source_end = (
+ float(declared_duration * stream_time_base)
+ if declared_duration is not None and stream_time_base is not None
+ else last_relative + (last_duration or 0.0)
+ )
+ if source_end + H3_REF_TRIM_COVERAGE_SLACK_SECONDS < end:
+ raise ValueError("Reference video trim ends after the source video.")
+ _fill_until(end)
+ if len(frames) < target_count:
+ raise ValueError("That reference video decoded to no frames in the selected range.")
+ return frames, timeline_start
+
+
+def _decode_h3_video_trim_by_ordinal(
+ blob: bytes, av: Any, trim: tuple[float, float]
+) -> tuple[list, Optional[float]]:
+ """Fallback for streams whose decoded frames carry no presentation timestamps."""
+ import io
+ with av.open(io.BytesIO(blob)) as container:
+ if not container.streams.video:
+ raise ValueError("That reference file carries no video track.")
+ stream = container.streams.video[0]
+ source_fps = float(stream.average_rate or stream.guessed_rate or H3_FPS)
+ if source_fps <= 0:
+ source_fps = float(H3_FPS)
+ # The frame on screen at t is the last one starting at or before it, so the start
+ # floors where the exclusive end ceils. Ceiling both skips the frame straddling a
+ # fractional start, drifting this fallback ahead of the timestamp path.
+ start_source_frame = math.floor(trim[0] * source_fps + 1e-6)
+ end_source_frame = math.ceil(trim[1] * source_fps - 1e-6)
+ target_count = int(round((trim[1] - trim[0]) * H3_FPS))
+ frames = []
+ decoded_count = 0
+ next_target = 0
+ fitted_size = None
+ for source_index, frame in enumerate(container.decode(video = 0)):
+ decoded_count = source_index + 1
+ if source_index < start_source_frame:
+ continue
+ if source_index >= end_source_frame:
+ break
+ selected_index = source_index - start_source_frame
+ target_source = int(next_target * source_fps / H3_FPS)
+ if target_source > selected_index:
+ continue
+ image, fitted_size = _fit_h3_video_frame(frame, fitted_size)
+ while (
+ len(frames) < target_count
+ and int(next_target * source_fps / H3_FPS) <= selected_index
+ ):
+ frames.append(image)
+ next_target += 1
+ slack_frames = math.ceil(H3_REF_TRIM_COVERAGE_SLACK_SECONDS * source_fps)
+ if decoded_count + slack_frames < end_source_frame:
+ raise ValueError("Reference video trim ends after the source video.")
+ if not frames:
+ raise ValueError("That reference video decoded to no frames in the selected range.")
+ return frames, _stream_start_seconds(stream)
-def decode_h3_reference_audio(blob: bytes) -> tuple[Any, int]:
+def decode_h3_reference_audio(
+ blob: bytes,
+ *,
+ trim_start_seconds: Optional[float] = None,
+ trim_end_seconds: Optional[float] = None,
+) -> tuple[Any, int]:
"""Decode one uploaded audio file to a float32 ``(samples, channels)`` waveform + its rate."""
import io
@@ -442,53 +674,180 @@ def decode_h3_reference_audio(blob: bytes) -> tuple[Any, int]:
with av.open(io.BytesIO(blob)) as container:
if not container.streams.audio:
raise ValueError("That reference file carries no audio track.")
- waveform, sample_rate = _decode_audio_stream(container, np)
+ waveform, sample_rate = _decode_audio_stream(
+ container,
+ np,
+ trim_start_seconds = trim_start_seconds,
+ trim_end_seconds = trim_end_seconds,
+ )
if waveform is None:
raise ValueError("That reference audio decoded to no samples.")
return waveform, sample_rate
-def _decode_audio_stream(container: Any, np: Any) -> tuple[Optional[Any], Optional[int]]:
- """The container's first audio stream as float32 ``(samples, channels)`` at its own rate.
-
- Bounded while decoding, for the reason the video path above is: the encoded size says almost
- nothing about the decoded size. A 32 MiB request-limit MP3 is over half an hour of audio, which
- expands to ~1.9 GB of float32 here and doubles again in ``np.concatenate``, and three
- references are accepted per request. H3's reference window is
- ``H3_REF_VIDEO_MAX_SECONDS`` anyway, so anything past it is unusable rather than merely large:
- refuse it with the same message the video guard uses instead of decoding it first."""
+def _decode_audio_stream(
+ container: Any,
+ np: Any,
+ *,
+ trim_start_seconds: Optional[float] = None,
+ trim_end_seconds: Optional[float] = None,
+ timeline_start_seconds: Optional[float] = None,
+ untrimmed_duration_seconds: Optional[float] = None,
+) -> tuple[Optional[Any], Optional[int]]:
+ """Decode the first audio stream as float32 samples at its native rate.
+
+ Decode incrementally to enforce H3's 15-second limit. For untrimmed video, cap embedded audio
+ to the video timeline.
+ """
import av
+ trim = validate_h3_reference_trim(trim_start_seconds, trim_end_seconds)
stream = container.streams.audio[0]
sample_rate = int(stream.codec_context.sample_rate or 48_000)
+ if trim is not None:
+ try:
+ return _decode_audio_trim_by_timestamp(
+ container,
+ stream,
+ np,
+ av,
+ sample_rate,
+ trim,
+ timeline_start_seconds = timeline_start_seconds,
+ )
+ except _H3MediaTimestampsUnavailable:
+ start_time = getattr(stream, "start_time", None)
+ time_base = getattr(stream, "time_base", None)
+ if time_base is None:
+ raise ValueError(
+ "Reference audio timestamps are unavailable and its stream cannot be reset."
+ ) from None
+ try:
+ container.seek(int(start_time or 0), backward = True, any_frame = False, stream = stream)
+ except Exception as exc: # noqa: BLE001 -- decoder-specific reset errors
+ raise ValueError(
+ "Reference audio timestamps are unavailable and its stream cannot be reset."
+ ) from exc
+
# One resampler pass gives interleaved float32 whatever the source layout/format was.
resampler = av.AudioResampler(format = "flt", layout = stream.layout.name, rate = sample_rate)
channels = len(stream.layout.channels)
max_samples = math.floor(H3_REF_VIDEO_MAX_SECONDS * sample_rate + 1e-6)
+ start_sample = math.floor(trim[0] * sample_rate + 1e-6) if trim else 0
+ untrimmed_end_sample = (
+ int(round(untrimmed_duration_seconds * sample_rate))
+ if untrimmed_duration_seconds is not None
+ else None
+ )
+ end_sample = math.floor(trim[1] * sample_rate + 1e-6) if trim else untrimmed_end_sample
chunks = []
- total = 0
+ source_total = 0
- def _take(resampled: Any) -> None:
- nonlocal total
+ def _take(resampled: Any) -> bool:
+ nonlocal source_total
block = resampled.to_ndarray().reshape(-1, channels)
- total += block.shape[0]
- if total > max_samples:
+ block_start = source_total
+ block_end = block_start + block.shape[0]
+ source_total = block_end
+ if trim is None and untrimmed_duration_seconds is None and source_total > max_samples:
raise ValueError(
f"MiniMax-H3 reference audio runs up to {H3_REF_VIDEO_MAX_SECONDS:g} seconds; "
f"this one is longer. Trim it first."
)
- chunks.append(block)
-
+ take_start = max(block_start, start_sample)
+ take_end = min(block_end, end_sample) if end_sample is not None else block_end
+ if take_start < take_end:
+ chunks.append(block[take_start - block_start : take_end - block_start])
+ # A track running past its video is clamped, not refused: encoder padding overshoots
+ # routinely, and longer tracks decoded fine before trimming existed. Stopping here
+ # also skips a tail no engine receives.
+ return end_sample is not None and block_end >= end_sample
+
+ stopped = False
for frame in container.decode(audio = 0):
for resampled in resampler.resample(frame):
+ if _take(resampled):
+ stopped = True
+ break
+ if stopped:
+ break
+ if not stopped:
+ for resampled in resampler.resample(None):
_take(resampled)
- for resampled in resampler.resample(None):
- _take(resampled)
+ # Short soundtracks are kept, not refused, as in the timestamp path above.
if not chunks:
return None, None
return np.concatenate(chunks, axis = 0).astype("float32"), sample_rate
+def _decode_audio_trim_by_timestamp(
+ container: Any,
+ stream: Any,
+ np: Any,
+ av: Any,
+ sample_rate: int,
+ trim: tuple[float, float],
+ *,
+ timeline_start_seconds: Optional[float],
+) -> tuple[Any, int]:
+ """Place decoded samples on the requested media timeline and stop at the endpoint."""
+ start, end = trim
+ origin = timeline_start_seconds
+ if origin is None:
+ origin = _stream_start_seconds(stream)
+ if origin is not None and start > 0:
+ _seek_media(container, stream, origin + start, label = "audio")
+
+ channels = len(stream.layout.channels)
+ target_count = int(round((end - start) * sample_rate))
+ output = np.zeros((target_count, channels), dtype = "float32")
+ resampler = av.AudioResampler(format = "flt", layout = stream.layout.name, rate = sample_rate)
+ copied_any = False
+ stopped = False
+
+ def _take(resampled: Any) -> bool:
+ nonlocal origin, copied_any
+ timestamp = _frame_timestamp_seconds(resampled)
+ if timestamp is None:
+ raise _H3MediaTimestampsUnavailable
+ if origin is None:
+ origin = timestamp
+ block = resampled.to_ndarray().reshape(-1, channels)
+ block_start = timestamp - origin
+ block_end = block_start + block.shape[0] / sample_rate
+ if block_start >= end:
+ return True
+ destination_start = int(round((block_start - start) * sample_rate))
+ source_start = max(0, -destination_start)
+ destination_start = max(0, destination_start)
+ take = min(block.shape[0] - source_start, target_count - destination_start)
+ if take > 0:
+ output[destination_start : destination_start + take] = block[
+ source_start : source_start + take
+ ]
+ copied_any = True
+ return block_end >= end
+
+ for frame in container.decode(audio = 0):
+ for resampled in resampler.resample(frame):
+ if _take(resampled):
+ stopped = True
+ break
+ if stopped:
+ break
+ if not stopped:
+ for resampled in resampler.resample(None):
+ if _take(resampled):
+ break
+ # Nothing copied means no soundtrack here, whether the track ended before the interval
+ # or starts after it. Silence instead would be a fabricated track, and would hide the
+ # gap from stage_h3_references' positional pairing. A track that merely runs out partway
+ # did copy something, so it keeps its silent tail rather than failing.
+ if not copied_any:
+ return None, None
+ return output, sample_rate
+
+
def write_h3_reference_wav(path: Path, waveform: Any, sample_rate: int) -> None:
"""Write a reference waveform as the 16-bit PCM WAV sd-cli's --ref-audio loader reads."""
import wave
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index c9c70556fc1..6339022c919 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -4034,6 +4034,18 @@ class VideoReferenceVideo(BaseModel):
description = "Base64/data-URL soundtrack for THIS video. Omitted takes the track "
"embedded in the file, if it has one; sent explicitly it replaces it.",
)
+ trim_start_seconds: Optional[float] = Field(
+ None, ge = 0.0, description = "Inclusive start of an explicit video trim, in seconds."
+ )
+ trim_end_seconds: Optional[float] = Field(
+ None, gt = 0.0, description = "Exclusive end of an explicit video trim, in seconds."
+ )
+
+ @model_validator(mode = "after")
+ def _trim_is_a_complete_h3_interval(self) -> "VideoReferenceVideo":
+ from core.inference.video_minimax_h3 import validate_h3_reference_trim
+ validate_h3_reference_trim(self.trim_start_seconds, self.trim_end_seconds)
+ return self
class VideoGenerateRequest(BaseModel):
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index ff987526e01..f4f102a1fdc 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -5920,6 +5920,8 @@ def _reference_video_data_url(
fps = 24,
size = (160, 96),
with_audio = True,
+ audio_seconds = None,
+ audio_start_seconds = 0.0,
):
"""A real encoded MP4, so the decode path is exercised rather than stubbed."""
import base64
@@ -5945,15 +5947,19 @@ def _reference_video_data_url(
out.mux(packet)
if audio is not None:
written = 0
- total = int(seconds * 44_100)
+ total = int((seconds if audio_seconds is None else audio_seconds) * 44_100)
+ pts = int(round(audio_start_seconds * 44_100))
while written < total:
count = min(1024, total - written)
samples = np.zeros((1, count * 2), dtype = np.int16)
frame = av.AudioFrame.from_ndarray(samples, format = "s16", layout = "stereo")
frame.sample_rate = 44_100
+ # Placing the track later on the shared timeline, as an offset soundtrack does.
+ frame.pts = pts
for packet in audio.encode(frame):
out.mux(packet)
written += count
+ pts += count
for packet in audio.encode():
out.mux(packet)
for packet in video.encode():
@@ -5961,6 +5967,86 @@ def _reference_video_data_url(
return "data:video/mp4;base64," + base64.b64encode(buf.getvalue()).decode()
+def _vfr_reference_video_data_url():
+ """A four-second VFR clip whose media timeline begins at five seconds."""
+ import base64
+ import io
+ from fractions import Fraction
+
+ av = pytest.importorskip("av")
+ np = pytest.importorskip("numpy")
+
+ timestamps = []
+ elapsed = 0.0
+ while elapsed < 4.0 - 1e-6:
+ timestamps.append(elapsed)
+ elapsed += 0.1 if elapsed < 2.0 - 1e-6 else 1 / 30
+
+ buf = io.BytesIO()
+ with av.open(buf, mode = "w", format = "mp4") as out:
+ video = out.add_stream("libx264", rate = 30)
+ video.width, video.height = (160, 96)
+ video.pix_fmt = "yuv420p"
+ video.time_base = Fraction(1, 1000)
+ video.codec_context.gop_size = 12
+ for elapsed in timestamps:
+ value = min(250, int(round(elapsed * 50)))
+ frame = av.VideoFrame.from_ndarray(
+ np.full((96, 160, 3), value, dtype = np.uint8), format = "rgb24"
+ )
+ frame.pts = 5_000 + int(round(elapsed * 1_000))
+ frame.time_base = Fraction(1, 1000)
+ for packet in video.encode(frame):
+ out.mux(packet)
+ for packet in video.encode():
+ out.mux(packet)
+ return "data:video/mp4;base64," + base64.b64encode(buf.getvalue()).decode()
+
+
+def _offset_audio_reference_video_data_url():
+ """A four-second video at t=5 whose three-second soundtrack begins at t=6."""
+ import base64
+ import io
+ from fractions import Fraction
+
+ av = pytest.importorskip("av")
+ np = pytest.importorskip("numpy")
+
+ buf = io.BytesIO()
+ with av.open(buf, mode = "w", format = "matroska") as out:
+ video = out.add_stream("ffv1", rate = 24)
+ video.width, video.height = (64, 64)
+ video.pix_fmt = "yuv444p"
+ video.time_base = Fraction(1, 1000)
+ audio = out.add_stream("pcm_s16le", rate = 44_100)
+ audio.layout = "stereo"
+ audio.time_base = Fraction(1, 44_100)
+ for index in range(4 * 24):
+ frame = av.VideoFrame.from_ndarray(
+ np.zeros((64, 64, 3), dtype = np.uint8), format = "rgb24"
+ )
+ frame.pts = 5_000 + round(index * 1_000 / 24)
+ frame.time_base = Fraction(1, 1000)
+ for packet in video.encode(frame):
+ out.mux(packet)
+ written = 0
+ while written < 3 * 44_100:
+ count = min(1024, 3 * 44_100 - written)
+ samples = np.full((1, count * 2), 10_000, dtype = np.int16)
+ frame = av.AudioFrame.from_ndarray(samples, format = "s16", layout = "stereo")
+ frame.sample_rate = 44_100
+ frame.pts = 6 * 44_100 + written
+ frame.time_base = Fraction(1, 44_100)
+ for packet in audio.encode(frame):
+ out.mux(packet)
+ written += count
+ for packet in audio.encode():
+ out.mux(packet)
+ for packet in video.encode():
+ out.mux(packet)
+ return "data:video/x-matroska;base64," + base64.b64encode(buf.getvalue()).decode()
+
+
def test_h3_reference_video_decodes_onto_the_models_own_clock():
pytest.importorskip("av")
from core.inference.video_minimax_h3 import decode_h3_reference_video
@@ -5994,12 +6080,586 @@ def test_h3_reference_video_refuses_instead_of_silently_truncating_a_long_clip()
from core.inference.video_minimax_h3 import decode_h3_reference_video
blob = base64.b64decode(
- _reference_video_data_url(seconds = 15.1, fps = 24, with_audio = False).split(",", 1)[1]
+ _reference_video_data_url(seconds = 15.1, fps = 24, with_audio = True).split(",", 1)[1]
)
with pytest.raises(ValueError, match = "longer than 15s"):
decode_h3_reference_video(blob)
+def test_h3_reference_video_decodes_an_explicit_trim_with_matching_audio():
+ pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(_reference_video_data_url(seconds = 20.0, fps = 24).split(",", 1)[1])
+ frames, waveform, sample_rate = decode_h3_reference_video(
+ blob,
+ trim_start_seconds = 5.0,
+ trim_end_seconds = 15.0,
+ )
+
+ assert len(frames) == 240
+ assert sample_rate == 44_100
+ assert waveform is not None and waveform.shape[0] == 10 * sample_rate
+
+
+def test_h3_reference_video_trim_uses_vfr_pts_relative_to_a_nonzero_stream_start():
+ pytest.importorskip("av")
+ import base64
+ import numpy as np
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(_vfr_reference_video_data_url().split(",", 1)[1])
+ frames, waveform, sample_rate = decode_h3_reference_video(
+ blob,
+ trim_start_seconds = 0.5,
+ trim_end_seconds = 2.5,
+ )
+
+ assert len(frames) == 48
+ assert waveform is None and sample_rate is None
+ # Ordinal selection would start near value 50 instead of 25.
+ assert float(np.asarray(frames[0]).mean()) == pytest.approx(25, abs = 8)
+ assert float(np.asarray(frames[-1]).mean()) > 110
+
+
+def test_h3_reference_video_trim_preserves_an_embedded_audio_timeline_offset():
+ pytest.importorskip("av")
+ import base64
+ import numpy as np
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(_offset_audio_reference_video_data_url().split(",", 1)[1])
+ frames, waveform, sample_rate = decode_h3_reference_video(
+ blob,
+ trim_start_seconds = 0.5,
+ trim_end_seconds = 2.5,
+ )
+
+ assert len(frames) == 48
+ assert sample_rate == 44_100
+ assert waveform is not None and waveform.shape == (2 * sample_rate, 2)
+ assert np.max(np.abs(waveform[: sample_rate // 2])) == 0
+ assert np.mean(np.abs(waveform[sample_rate // 2 :])) > 0.25
+
+
[email protected]("duration", [2.0, 15.0])
+def test_h3_reference_video_trim_keeps_exact_boundary_frame_and_sample_counts(duration):
+ pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(_reference_video_data_url(seconds = duration, fps = 24).split(",", 1)[1])
+ frames, waveform, sample_rate = decode_h3_reference_video(
+ blob,
+ trim_start_seconds = 0.0,
+ trim_end_seconds = duration,
+ )
+
+ assert len(frames) == round(duration * 24)
+ assert sample_rate == 44_100
+ assert waveform is not None and waveform.shape[0] == round(duration * sample_rate)
+
+
[email protected]("duration", [2.0, 15.0])
+def test_h3_reference_video_without_trim_discards_aac_padding(duration):
+ pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(_reference_video_data_url(seconds = duration, fps = 24).split(",", 1)[1])
+ frames, waveform, sample_rate = decode_h3_reference_video(blob)
+
+ assert len(frames) == round(duration * 24)
+ assert sample_rate == 44_100
+ assert waveform is not None and waveform.shape[0] == round(duration * sample_rate)
+
+
[email protected]("audio_seconds", [15.05, 15.1, 16.0])
+def test_h3_reference_video_without_trim_clamps_audio_past_the_video(audio_seconds):
+ """A soundtrack longer than its video is clamped to it, not refused.
+
+ Longer tracks decoded fine before trimming existed, and a codec frame of overshoot is
+ ordinary padding, so refusing one rejects media that already worked.
+ """
+ pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(
+ _reference_video_data_url(seconds = 15.0, fps = 24, audio_seconds = audio_seconds).split(",", 1)[
+ 1
+ ]
+ )
+ frames, waveform, sample_rate = decode_h3_reference_video(blob)
+
+ assert len(frames) == round(15.0 * 24)
+ assert waveform is not None
+ assert waveform.shape[0] == round(15.0 * sample_rate)
+
+
+def test_h3_reference_video_trim_seeks_and_stops_both_decoders(monkeypatch):
+ av = pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(_reference_video_data_url(seconds = 20.0, fps = 24).split(",", 1)[1])
+ real_open = av.open
+ opened = []
+
+ class _CountingContainer:
+ def __init__(self, *args, **kwargs):
+ self.inner = real_open(*args, **kwargs)
+ self.seek_types = []
+ self.decoded = {"video": 0, "audio": 0}
+ opened.append(self)
+
+ @property
+ def streams(self):
+ return self.inner.streams
+
+ def seek(self, *args, **kwargs):
+ self.seek_types.append(kwargs["stream"].type)
+ return self.inner.seek(*args, **kwargs)
+
+ def decode(self, *args, **kwargs):
+ media_type = "video" if "video" in kwargs else "audio"
+ for frame in self.inner.decode(*args, **kwargs):
+ self.decoded[media_type] += 1
+ yield frame
+
+ def __enter__(self):
+ self.inner.__enter__()
+ return self
+
+ def __exit__(self, *args):
+ return self.inner.__exit__(*args)
+
+ monkeypatch.setattr(av, "open", _CountingContainer)
+ frames, waveform, sample_rate = decode_h3_reference_video(
+ blob,
+ trim_start_seconds = 15.0,
+ trim_end_seconds = 17.0,
+ )
+
+ assert len(frames) == 48
+ assert waveform is not None and waveform.shape[0] == 2 * sample_rate
+ assert any("video" in item.seek_types for item in opened)
+ assert any("audio" in item.seek_types for item in opened)
+ assert sum(item.decoded["video"] for item in opened) < 200
+ assert sum(item.decoded["audio"] for item in opened) < 120
+
+
+def test_h3_reference_video_trim_outlasting_a_short_soundtrack_stays_silent():
+ """A trim the embedded audio does not cover keeps the video and pads the rest silent.
+
+ A video carrying no audio at all is accepted, so one whose track merely ends early must
+ be too; the untrimmed path clamps the same mismatch rather than refusing it.
+ """
+ pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(
+ _reference_video_data_url(seconds = 10.0, fps = 24, audio_seconds = 6.0).split(",", 1)[1]
+ )
+ frames, waveform, sample_rate = decode_h3_reference_video(
+ blob, trim_start_seconds = 2.0, trim_end_seconds = 8.0
+ )
+
+ assert len(frames) == round(6.0 * 24)
+ assert waveform is not None
+ assert waveform.shape[0] == round(6.0 * sample_rate)
+ # Audio runs out 4s into the interval; everything past that is silence, not a refusal.
+ assert abs(waveform[: round(4.0 * sample_rate)]).max() >= 0.0
+ assert abs(waveform[round(4.0 * sample_rate) + sample_rate // 10 :]).max() == 0.0
+
+
+def test_h3_reference_video_trim_entirely_past_the_soundtrack_drops_the_audio():
+ pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(
+ _reference_video_data_url(seconds = 12.0, fps = 24, audio_seconds = 3.0).split(",", 1)[1]
+ )
+ frames, waveform, _ = decode_h3_reference_video(
+ blob, trim_start_seconds = 6.0, trim_end_seconds = 10.0
+ )
+
+ assert len(frames) == round(4.0 * 24)
+ assert waveform is None
+
+
+def test_h3_reference_video_trim_before_an_offset_soundtrack_drops_the_audio():
+ """A track starting after the interval is absent from it, not silent within it.
+
+ The mirror of the test above, which ends its soundtrack before the trim. Neither leaves a
+ sample inside the interval, so both must report no soundtrack: a silent waveform would be
+ a fabricated track, and would hide the gap from stage_h3_references' positional pairing.
+ """
+ pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(
+ _reference_video_data_url(
+ seconds = 15.0, fps = 24, audio_seconds = 5.0, audio_start_seconds = 10.0
+ ).split(",", 1)[1]
+ )
+ frames, waveform, _ = decode_h3_reference_video(
+ blob, trim_start_seconds = 0.0, trim_end_seconds = 5.0
+ )
+
+ assert len(frames) == round(5.0 * 24)
+ assert waveform is None
+
+
+def test_h3_reference_video_trim_reaching_an_offset_soundtrack_keeps_the_audio():
+ """The same offset track is still decoded by a trim that does overlap it."""
+ pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(
+ _reference_video_data_url(
+ seconds = 15.0, fps = 24, audio_seconds = 5.0, audio_start_seconds = 10.0
+ ).split(",", 1)[1]
+ )
+ frames, waveform, sample_rate = decode_h3_reference_video(
+ blob, trim_start_seconds = 9.0, trim_end_seconds = 13.0
+ )
+
+ assert len(frames) == round(4.0 * 24)
+ assert waveform is not None
+ assert waveform.shape[0] == round(4.0 * sample_rate)
+
+
+def test_h3_reference_video_trim_tolerates_a_container_longer_than_its_video():
+ """A trim taken from the container duration may reach just past the video track.
+
+ A container reports its longest track, so a file whose audio outruns its video reads as
+ longer than it can show, and a browser hands Studio that duration. The last frame is held
+ across the shortfall instead of refusing a clip that decodes fine untrimmed.
+ """
+ pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(
+ _reference_video_data_url(seconds = 14.9, fps = 24, audio_seconds = 15.2).split(",", 1)[1]
+ )
+ frames, _, _ = decode_h3_reference_video(blob, trim_start_seconds = 0.0, trim_end_seconds = 15.0)
+ assert len(frames) == round(15.0 * 24)
+
+
+def test_h3_reference_video_trim_still_refuses_a_real_overshoot():
+ """The slack covers container metadata, not a range that genuinely is not there."""
+ pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(
+ _reference_video_data_url(seconds = 6.0, fps = 24, with_audio = False).split(",", 1)[1]
+ )
+ with pytest.raises(ValueError, match = "after the source video"):
+ decode_h3_reference_video(blob, trim_start_seconds = 2.0, trim_end_seconds = 10.0)
+
+
+def test_h3_reference_video_trim_must_be_complete_bounded_and_inside_the_source():
+ pytest.importorskip("av")
+ import base64
+
+ from core.inference.video_minimax_h3 import decode_h3_reference_video
+
+ blob = base64.b64decode(
+ _reference_video_data_url(seconds = 3.0, with_audio = False).split(",", 1)[1]
+ )
+ with pytest.raises(ValueError, match = "provided together"):
+ decode_h3_reference_video(blob, trim_start_seconds = 0.0)
+ with pytest.raises(ValueError, match = "2 to 15 seconds"):
+ decode_h3_reference_video(blob, trim_start_seconds = 0.0, trim_end_seconds = 1.0)
+ with pytest.raises(ValueError, match = "after the source video"):
+ decode_h3_reference_video(blob, trim_start_seconds = 2.0, trim_end_seconds = 5.0)
+
+
+def _frame_index_video(
+ seconds = 10.0,
+ fps = 24,
+ width = 256,
+ height = 64,
+ bar = 4,
+):
+ """An MP4 whose every frame encodes its own index as the position of a white bar.
+
+ A flat grey level per frame would not survive the round trip: limited-range YUV folds
+ 0..255 into 16..235, so neighbouring indices collide. A bar position does.
+ """
+ av = pytest.importorskip("av")
+ np = pytest.importorskip("numpy")
+ import io
+
+ buf = io.BytesIO()
+ with av.open(buf, mode = "w", format = "mp4") as out:
+ video = out.add_stream("libx264", rate = fps)
+ video.width, video.height = width, height
+ video.pix_fmt = "yuv420p"
+ # Every frame a keyframe, so seeks land exactly and the two decoders differ only in
+ # how they select, never in what they can reach.
+ video.options = {"g": "1", "crf": "0", "tune": "zerolatency"}
+ for index in range(int(seconds * fps)):
+ plane = np.zeros((height, width, 3), dtype = np.uint8)
+ plane[:, index : index + bar] = 255
+ for packet in video.encode(av.VideoFrame.from_ndarray(plane, format = "rgb24")):
+ out.mux(packet)
+ for packet in video.encode():
+ out.mux(packet)
+ return buf.getvalue()
+
+
+def _decoded_frame_index(image, width = 256):
+ """Recover the source frame index from the bar's left edge."""
+ np = pytest.importorskip("numpy")
+
+ plane = np.asarray(image.convert("L"), dtype = "float64")
+ columns = plane.mean(axis = 0)
+ lit = np.flatnonzero(columns > columns.max() / 2)
+ assert lit.size, "no bar found in the decoded frame"
+ return int(round(lit[0] * width / plane.shape[1]))
+
+
+def test_h3_reference_video_ordinal_fallback_selects_the_same_frames_as_timestamps():
+ """The fallback for streams whose frames carry no presentation timestamps.
+
+ Nothing else reaches this path. A fractional start separates the two rules: the frame on
+ screen at t is floor(t*fps), and ceiling it drifts the selection forward by one.
+ """
+ av = pytest.importorskip("av")
+
+ from core.inference.video_minimax_h3 import (
+ _decode_h3_video_trim_by_ordinal,
+ _decode_h3_video_trim_by_timestamp,
+ )
+
+ blob = _frame_index_video()
+
+ # A start that lands on a frame boundary, and one that falls between two.
+ for start, end in ((2.0, 8.0), (2.02, 8.02)):
+ ordinal, _ = _decode_h3_video_trim_by_ordinal(blob, av, (start, end))
+ timestamp, _ = _decode_h3_video_trim_by_timestamp(blob, av, (start, end))
+ assert len(ordinal) == len(timestamp) == round((end - start) * 24)
+ assert _decoded_frame_index(ordinal[0]) == _decoded_frame_index(timestamp[0])
+
+ ordinal, _ = _decode_h3_video_trim_by_ordinal(blob, av, (2.02, 8.02))
+ assert _decoded_frame_index(ordinal[0]) == 48
+
+
+def test_h3_reference_video_falls_back_when_timestamps_are_missing(monkeypatch):
+ """Prove the dispatcher reaches the ordinal decoder at all, rather than raising."""
+ av = pytest.importorskip("av")
+
+ import core.inference.video_minimax_h3 as h3
+
+ blob = _frame_index_video()
+ calls = []
+ original = h3._decode_h3_video_trim_by_ordinal
+ monkeypatch.setattr(
+ h3,
+ "_decode_h3_video_trim_by_ordinal",
+ lambda *args: (calls.append(1), original(*args))[1],
+ )
+
+ real_open = av.open
+
+ class _PtsLess:
+ """PyAV container attributes are read-only, so the generator is replaced from outside."""
+
+ def __init__(self, container):
+ self._container = container
+
+ def decode(self, *args, **kwargs):
+ for frame in self._container.decode(*args, **kwargs):
+ frame.pts = None
+ yield frame
+
+ def __getattr__(self, name):
+ return getattr(self._container, name)
+
+ def __enter__(self):
+ self._container.__enter__()
+ return self
+
+ def __exit__(self, *exc):
+ return self._container.__exit__(*exc)
+
+ monkeypatch.setattr(av, "open", lambda *a, **k: _PtsLess(real_open(*a, **k)))
+
+ frames, _, _ = h3.decode_h3_reference_video(
+ blob, trim_start_seconds = 2.0, trim_end_seconds = 8.0, decode_audio = False
+ )
+ assert calls == [1]
+ assert len(frames) == round(6.0 * 24)
+
+
+def test_h3_replacement_audio_bypasses_a_short_embedded_soundtrack():
+ pytest.importorskip("av")
+ from core.inference.video import VideoBackend
+ from core.inference.video_families import detect_video_family
+
+ references = VideoBackend._resolve_references(
+ detect_video_family("MiniMaxAI/MiniMax-H3", None),
+ "ref2va",
+ "diffusers",
+ None,
+ [
+ {
+ "video": _reference_video_data_url(
+ seconds = 5.0, fps = 24, with_audio = True, audio_seconds = 1.0
+ ),
+ "audio": _data_url_wav(seconds = 5.0, rate = 32_000),
+ "trim_start_seconds": 2.0,
+ "trim_end_seconds": 4.0,
+ }
+ ],
+ None,
+ "match",
+ 960,
+ 544,
+ )
+
+ frames, waveform, sample_rate = references.videos[0]
+ assert len(frames) == 48
+ assert sample_rate == 32_000
+ assert waveform.shape == (64_000, 2)
+
+
+def test_h3_replacement_audio_starts_at_its_own_zero():
+ """A replacement soundtrack is an independent file, not a second cut of the video.
+
+ Its timeline has no relation to the video's, and the picker offers no way to offset it, so
+ it plays the clip from its own start. The video's coordinates dropped its first trim_start
+ seconds, and refused it when it was shorter than that.
+ """
+ pytest.importorskip("av")
+ import numpy as np
+
+ from core.inference.video import VideoBackend
+ from core.inference.video_families import detect_video_family
+
+ # Signal only in the first second, so the decoded offset is recoverable.
+ references = VideoBackend._resolve_references(
+ detect_video_family("MiniMaxAI/MiniMax-H3", None),
+ "ref2va",
+ "diffusers",
+ None,
+ [
+ {
+ "video": _reference_video_data_url(seconds = 12.0, fps = 24, with_audio = False),
+ "audio": _data_url_wav(seconds = 3.0, rate = 32_000, silent_after = 1.0),
+ "trim_start_seconds": 5.0,
+ "trim_end_seconds": 8.0,
+ }
+ ],
+ None,
+ "match",
+ 960,
+ 544,
+ )
+
+ _, waveform, sample_rate = references.videos[0]
+ assert sample_rate == 32_000
+ # The clip's length, taken from the replacement's start rather than from its 5s mark.
+ assert waveform.shape == (96_000, 2)
+ energy = np.abs(waveform).max(axis = 1)
+ assert energy[: sample_rate // 2].max() > 0.01
+ assert energy[2 * sample_rate :].max() <= 0.01
+
+
+def test_h3_replacement_audio_shorter_than_the_trim_start_is_kept():
+ """The same file, shorter than where the video's trim begins, is padded not refused."""
+ pytest.importorskip("av")
+
+ from core.inference.video import VideoBackend
+ from core.inference.video_families import detect_video_family
+
+ references = VideoBackend._resolve_references(
+ detect_video_family("MiniMaxAI/MiniMax-H3", None),
+ "ref2va",
+ "diffusers",
+ None,
+ [
+ {
+ "video": _reference_video_data_url(seconds = 20.0, fps = 24, with_audio = False),
+ "audio": _data_url_wav(seconds = 2.0, rate = 32_000),
+ "trim_start_seconds": 10.0,
+ "trim_end_seconds": 14.0,
+ }
+ ],
+ None,
+ "match",
+ 960,
+ 544,
+ )
+
+ _, waveform, sample_rate = references.videos[0]
+ assert waveform.shape == (4 * 32_000, 2)
+ assert sample_rate == 32_000
+
+
+def test_h3_begin_generate_reuses_preflight_resolved_references(monkeypatch):
+ import core.inference.video as video_mod
+
+ backend = _h3_ref_backend(monkeypatch, [])
+ expected = object()
+ resolve_calls = []
+ captured = {}
+
+ def _resolve(*args, **kwargs):
+ resolve_calls.append((args, kwargs))
+ return expected
+
+ class _DeferredThread:
+ def __init__(self, *, target, kwargs, daemon):
+ captured.update(target = target, kwargs = kwargs, daemon = daemon)
+
+ def start(self):
+ return None
+
+ monkeypatch.setattr(backend, "_resolve_references", _resolve)
+ monkeypatch.setattr(backend, "_state_device_target", lambda _state: None)
+ monkeypatch.setattr(video_mod.threading, "Thread", _DeferredThread)
+ monkeypatch.setattr(backend, "_generate_h3_native", lambda **kwargs: kwargs["references"])
+
+ backend.begin_generate(prompt = "p")
+ assert len(resolve_calls) == 1
+
+ original_state = backend._state
+ backend._state = dataclasses.replace(original_state)
+ with pytest.raises(RuntimeError, match = VIDEO_CANCELLED_MSG):
+ backend.generate(**captured["kwargs"])
+ backend._state = original_state
+
+ assert backend.generate(**captured["kwargs"]) is expected
+ assert len(resolve_calls) == 1
+
+ # Direct callers still resolve their own raw inputs.
+ assert backend.generate(prompt = "p") is expected
+ assert len(resolve_calls) == 2
+
+
def test_h3_native_refuses_a_later_video_soundtrack_after_a_silent_video(monkeypatch):
pytest.importorskip("av")
backend = _h3_ref_backend(monkeypatch, [])
@@ -6033,6 +6693,75 @@ def test_h3_reference_images_are_fitted_to_the_requested_policy():
fit_h3_reference_image(source, width = 960, height = 544, policy = "huge")
+def test_h3_reference_image_fits_a_phone_photo_before_the_generic_source_limit():
+ pytest.importorskip("PIL.Image")
+ from core.inference.diffusion import decode_b64_image
+ from core.inference.video import VideoBackend
+ from core.inference.video_families import detect_video_family
+
+ source = _data_url(5712, 4284)
+ with pytest.raises(ValueError, match = "maximum is 4096px per side"):
+ decode_b64_image(source)
+
+ references = VideoBackend._resolve_references(
+ detect_video_family("MiniMaxAI/MiniMax-H3", None),
+ "ref2va",
+ "diffusers",
+ [source],
+ None,
+ None,
+ "match",
+ 960,
+ 544,
+ )
+
+ assert len(references.images) == 1
+ fitted = references.images[0]
+ assert fitted.size[0] * fitted.size[1] <= 960 * 544 * 1.1
+ assert fitted.size[0] / fitted.size[1] == pytest.approx(5712 / 4284, abs = 0.05)
+
+ largest = VideoBackend._resolve_references(
+ detect_video_family("MiniMaxAI/MiniMax-H3", None),
+ "ref2va",
+ "diffusers",
+ [source],
+ None,
+ None,
+ "max",
+ 960,
+ 544,
+ ).images[0]
+ assert min(largest.size) == 2048
+
+
+def test_h3_reference_image_source_policy_rejects_excessive_area_before_loading(monkeypatch):
+ Image = pytest.importorskip("PIL.Image")
+ from core.inference.diffusion import decode_b64_image
+ from core.inference.video_minimax_h3 import (
+ H3_REF_IMAGE_SOURCE_MAX_PIXELS,
+ H3_REF_IMAGE_SOURCE_MAX_SIDE,
+ )
+
+ loaded = False
+
+ def tracked_load():
+ nonlocal loaded
+ loaded = True
+
+ monkeypatch.setattr(
+ Image,
+ "open",
+ lambda _stream: types.SimpleNamespace(size = (8000, 5000), load = tracked_load),
+ )
+ with pytest.raises(ValueError, match = "source pixels"):
+ decode_b64_image(
+ "eA==",
+ max_side = H3_REF_IMAGE_SOURCE_MAX_SIDE,
+ max_pixels = H3_REF_IMAGE_SOURCE_MAX_PIXELS,
+ )
+ assert loaded is False
+
+
def test_h3_native_generate_stages_every_reference_kind(monkeypatch, tmp_path):
pytest.importorskip("av")
calls: list = []
@@ -6082,7 +6811,12 @@ def test_h3_native_generate_stages_every_reference_kind(monkeypatch, tmp_path):
assert result["conditioning"] == "ref2va"
-def _data_url_wav(seconds = 1.0, rate = 32_000):
+def _data_url_wav(
+ seconds = 1.0,
+ rate = 32_000,
+ silent_after = None,
+):
+ """A 440Hz tone; `silent_after` mutes the tail so a decoded offset is recoverable."""
import base64
import io
import math
@@ -6094,8 +6828,9 @@ def _data_url_wav(seconds = 1.0, rate = 32_000):
handle.setsampwidth(2)
handle.setframerate(rate)
frames = bytearray()
+ loud = int(seconds * rate) if silent_after is None else int(silent_after * rate)
for i in range(int(seconds * rate)):
- value = int(8000 * math.sin(2 * math.pi * 440 * i / rate))
+ value = int(8000 * math.sin(2 * math.pi * 440 * i / rate)) if i < loud else 0
frames += int(value).to_bytes(2, "little", signed = True) * 2
handle.writeframes(bytes(frames))
return "data:audio/wav;base64," + base64.b64encode(buf.getvalue()).decode()
diff --git a/studio/backend/tests/test_video_shape_validation.py b/studio/backend/tests/test_video_shape_validation.py
index 0eb952c523c..1c007a70905 100644
--- a/studio/backend/tests/test_video_shape_validation.py
+++ b/studio/backend/tests/test_video_shape_validation.py
@@ -41,6 +41,7 @@ from core.inference.video_families import (
validate_video_request_shape,
)
from core.inference.video_minimax_h3 import h3_conditioning_mode
+from models.inference import VideoReferenceVideo
from routes.video import router as video_router
# LTX-2 is the reference family for the single-family cases: 4 presets and frame_step 8.
@@ -228,6 +229,24 @@ def test_snapping_helpers_are_untouched():
assert format_video_resolution_presets(LTX2) == "768x512, 1216x704, 704x1216, 512x768"
+def test_reference_video_trim_schema_requires_one_bounded_interval():
+ reference = VideoReferenceVideo(
+ video = "data:video/mp4;base64,AA==",
+ trim_start_seconds = 4.0,
+ trim_end_seconds = 19.0,
+ )
+ assert reference.trim_start_seconds == 4.0
+ assert reference.trim_end_seconds == 19.0
+
+ for values, message in (
+ ({"trim_start_seconds": 4.0}, "provided together"),
+ ({"trim_start_seconds": 4.0, "trim_end_seconds": 5.0}, "2 to 15 seconds"),
+ ({"trim_start_seconds": 4.0, "trim_end_seconds": 20.0}, "2 to 15 seconds"),
+ ):
+ with pytest.raises(ValueError, match = message):
+ VideoReferenceVideo(video = "data:video/mp4;base64,AA==", **values)
+
+
# ── the route ─────────────────────────────────────────────────────────────────
diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.ts
index ec22846c333..57b70a0907f 100644
--- a/studio/frontend/src/features/video/api.ts
+++ b/studio/frontend/src/features/video/api.ts
@@ -149,6 +149,9 @@ export interface VideoReferenceVideo {
video: string;
// Base64/data-URL soundtrack for THIS video; omitted takes the one embedded in the file.
audio?: string;
+ // Optional explicit interval. Both endpoints are required together; duration must be 2 to 15s.
+ trim_start_seconds?: number;
+ trim_end_seconds?: number;
}
export interface VideoGenerateRequest {
diff --git a/studio/frontend/src/features/video/reference-budget.ts b/studio/frontend/src/features/video/reference-budget.ts
index a535bb66cca..6b69328c07f 100644
--- a/studio/frontend/src/features/video/reference-budget.ts
+++ b/studio/frontend/src/features/video/reference-budget.ts
@@ -85,3 +85,37 @@ export function readReferenceFile(
reader.onerror = () => handlers.onError(`Could not read the ${kind} file`);
reader.readAsDataURL(file);
}
+
+export interface ReferenceSelectionClaim {
+ isCurrent(): boolean;
+}
+
+export interface ReferenceSelectionGate {
+ begin(): ReferenceSelectionClaim;
+ invalidate(): void;
+ mount(): () => void;
+}
+
+/** Create a latest-wins guard for asynchronous picker reads. */
+export function createReferenceSelectionGate(): ReferenceSelectionGate {
+ let revision = 0;
+ let live = true;
+ return {
+ begin() {
+ revision += 1;
+ const claimed = revision;
+ return { isCurrent: () => live && claimed === revision };
+ },
+ invalidate() {
+ revision += 1;
+ },
+ mount() {
+ live = true;
+ return () => {
+ live = false;
+ // A StrictMode remount must not revive the previous mount's claim.
+ revision += 1;
+ };
+ },
+ };
+}
diff --git a/studio/frontend/src/features/video/reference-image-crop.ts b/studio/frontend/src/features/video/reference-image-crop.ts
new file mode 100644
index 00000000000..62548a62f6b
--- /dev/null
+++ b/studio/frontend/src/features/video/reference-image-crop.ts
@@ -0,0 +1,273 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export interface CropPoint {
+ x: number;
+ y: number;
+}
+
+export interface CropRect extends CropPoint {
+ width: number;
+ height: number;
+}
+
+/** One picture slot keeps its original upload, current raster and crop. */
+export interface StagedReferenceImage {
+ originalDataUrl: string;
+ dataUrl: string;
+ crop: CropRect | null;
+}
+
+export interface ImageSize {
+ width: number;
+ height: number;
+}
+
+export interface CropRasterCanvas {
+ width: number;
+ height: number;
+ getContext(kind: "2d"): {
+ drawImage(
+ source: CanvasImageSource,
+ sourceX: number,
+ sourceY: number,
+ sourceWidth: number,
+ sourceHeight: number,
+ destinationX: number,
+ destinationY: number,
+ destinationWidth: number,
+ destinationHeight: number,
+ ): void;
+ } | null;
+ toDataURL(type: string): string;
+}
+
+// Keep this aligned with VideoGenerateRequest.reference_images in models/inference.py.
+export const MAX_REFERENCE_IMAGE_DATA_URL_LENGTH = 32 * 1024 * 1024;
+
+// fit_h3_reference_image never keeps more than a 2048px short edge, so a full-resolution
+// export just spends the 32 MiB cap and a blocking encode on pixels it discards: a 12MP
+// photo alone reaches ~52 MiB of PNG base64. The long edge is bounded too, so an extreme
+// aspect cannot stay huge just because its short edge fits.
+export const MAX_REFERENCE_CROP_SHORT_EDGE = 2048;
+export const MAX_REFERENCE_CROP_LONG_EDGE = 4096;
+
+function finite(value: number): number {
+ return Number.isFinite(value) ? value : 0;
+}
+
+function between(value: number, minimum: number, maximum: number): number {
+ return Math.min(maximum, Math.max(minimum, value));
+}
+
+function boundedSize(size: ImageSize): ImageSize {
+ return {
+ width: Math.max(0, Math.floor(finite(size.width))),
+ height: Math.max(0, Math.floor(finite(size.height))),
+ };
+}
+
+/** Clamp an arbitrary source-pixel rectangle to the decoded image. */
+export function clampCropRect(rect: CropRect, image: ImageSize): CropRect {
+ const bounds = boundedSize(image);
+ const x = between(Math.floor(finite(rect.x)), 0, bounds.width);
+ const y = between(Math.floor(finite(rect.y)), 0, bounds.height);
+ const right = between(
+ Math.ceil(finite(rect.x) + Math.max(0, finite(rect.width))),
+ x,
+ bounds.width,
+ );
+ const bottom = between(
+ Math.ceil(finite(rect.y) + Math.max(0, finite(rect.height))),
+ y,
+ bounds.height,
+ );
+ return { x, y, width: right - x, height: bottom - y };
+}
+
+/** Build a bounded source-pixel rectangle from either drag direction. */
+export function cropRectFromPoints(
+ start: CropPoint,
+ end: CropPoint,
+ image: ImageSize,
+): CropRect {
+ const bounds = boundedSize(image);
+ const startX = between(finite(start.x), 0, bounds.width);
+ const startY = between(finite(start.y), 0, bounds.height);
+ const endX = between(finite(end.x), 0, bounds.width);
+ const endY = between(finite(end.y), 0, bounds.height);
+ const left = Math.floor(Math.min(startX, endX));
+ const top = Math.floor(Math.min(startY, endY));
+ const right = Math.ceil(Math.max(startX, endX));
+ const bottom = Math.ceil(Math.max(startY, endY));
+ return clampCropRect(
+ { x: left, y: top, width: right - left, height: bottom - top },
+ bounds,
+ );
+}
+
+/** Move a selection without letting any edge leave the source image. */
+export function moveCropRect(
+ rect: CropRect,
+ delta: CropPoint,
+ image: ImageSize,
+): CropRect {
+ const crop = clampCropRect(rect, image);
+ const bounds = boundedSize(image);
+ return {
+ ...crop,
+ x: between(
+ Math.round(crop.x + finite(delta.x)),
+ 0,
+ bounds.width - crop.width,
+ ),
+ y: between(
+ Math.round(crop.y + finite(delta.y)),
+ 0,
+ bounds.height - crop.height,
+ ),
+ };
+}
+
+/** Map a pointer on the rendered preview onto orientation-correct source pixels. */
+export function displayPointToSource(
+ point: CropPoint,
+ display: ImageSize,
+ source: ImageSize,
+): CropPoint {
+ if (display.width <= 0 || display.height <= 0) {
+ return { x: 0, y: 0 };
+ }
+ return {
+ x: (point.x / display.width) * source.width,
+ y: (point.y / display.height) * source.height,
+ };
+}
+
+export interface CropImageLoadClaim {
+ dataUrl: string;
+ cancel(): void;
+ isCurrent(): boolean;
+}
+
+/** Latest-wins gate shared by image decode callbacks and covered without a DOM harness. */
+export function createCropImageLoadGate(): {
+ begin(dataUrl: string): CropImageLoadClaim;
+} {
+ let revision = 0;
+ return {
+ begin(dataUrl) {
+ revision += 1;
+ const claimedRevision = revision;
+ let cancelled = false;
+ return {
+ dataUrl,
+ cancel() {
+ cancelled = true;
+ },
+ isCurrent() {
+ return !cancelled && claimedRevision === revision;
+ },
+ };
+ },
+ };
+}
+
+/** Parent-state actions keep Cancel structurally separate from Apply. */
+export function createReferenceImageEditorActions(callbacks: {
+ onApply(dataUrl: string, crop: CropRect | null): void;
+ onOpenChange(open: boolean): void;
+}): {
+ apply(dataUrl: string, crop: CropRect | null): void;
+ cancel(): void;
+} {
+ return {
+ apply(dataUrl, crop) {
+ callbacks.onApply(dataUrl, crop);
+ callbacks.onOpenChange(false);
+ },
+ cancel() {
+ callbacks.onOpenChange(false);
+ },
+ };
+}
+
+/** The exported size for a crop: its own size, reduced to what the model can use. */
+export function referenceCropExportSize(crop: ImageSize): ImageSize {
+ const longest = Math.max(crop.width, crop.height);
+ const shortest = Math.min(crop.width, crop.height);
+ const scale = Math.min(
+ 1,
+ MAX_REFERENCE_CROP_SHORT_EDGE / Math.max(1, shortest),
+ MAX_REFERENCE_CROP_LONG_EDGE / Math.max(1, longest),
+ );
+ if (scale >= 1) return { width: crop.width, height: crop.height };
+ return {
+ width: Math.max(1, Math.floor(crop.width * scale)),
+ height: Math.max(1, Math.floor(crop.height * scale)),
+ };
+}
+
+/** Rasterize exactly one bounded source rectangle without enlarging it. */
+export function rasterizeReferenceImageCrop(
+ source: CanvasImageSource,
+ selection: CropRect,
+ sourceSize: ImageSize,
+ createCanvas: () => CropRasterCanvas = () => document.createElement("canvas"),
+): string {
+ const crop = clampCropRect(selection, sourceSize);
+ if (crop.width < 1 || crop.height < 1) {
+ throw new Error("Select an area at least one pixel wide and high.");
+ }
+ const output = referenceCropExportSize(crop);
+ const canvas = createCanvas();
+ canvas.width = output.width;
+ canvas.height = output.height;
+ const context = canvas.getContext("2d");
+ if (!context)
+ throw new Error("This browser could not start the crop canvas.");
+ context.drawImage(
+ source,
+ crop.x,
+ crop.y,
+ crop.width,
+ crop.height,
+ 0,
+ 0,
+ output.width,
+ output.height,
+ );
+ const dataUrl = canvas.toDataURL("image/png");
+ if (!dataUrl.startsWith("data:image/png;base64,")) {
+ throw new Error("This browser could not export the cropped picture.");
+ }
+ return dataUrl;
+}
+
+export function stageReferenceImage(dataUrl: string): StagedReferenceImage {
+ return { originalDataUrl: dataUrl, dataUrl, crop: null };
+}
+
+/** Apply a raster and crop to one position while retaining its original upload. */
+export function applyReferenceImageCrop(
+ images: StagedReferenceImage[],
+ index: number,
+ dataUrl: string,
+ crop: CropRect | null,
+): StagedReferenceImage[] {
+ return images.map((image, current) =>
+ current === index ? { ...image, dataUrl, crop } : image,
+ );
+}
+
+export function referenceImageDataUrls(
+ images: StagedReferenceImage[],
+): string[] {
+ return images.map((image) => image.dataUrl);
+}
+
+export function referenceImageDataUrlError(dataUrl: string): string | null {
+ return dataUrl.length <= MAX_REFERENCE_IMAGE_DATA_URL_LENGTH
+ ? null
+ : "The cropped picture is too large. Select a smaller area and try again.";
+}
diff --git a/studio/frontend/src/features/video/reference-image-editor.tsx b/studio/frontend/src/features/video/reference-image-editor.tsx
new file mode 100644
index 00000000000..b38cec96d18
--- /dev/null
+++ b/studio/frontend/src/features/video/reference-image-editor.tsx
@@ -0,0 +1,420 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import {
+ type KeyboardEvent as ReactKeyboardEvent,
+ type PointerEvent as ReactPointerEvent,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ type CropPoint,
+ type CropRect,
+ type ImageSize,
+ type StagedReferenceImage,
+ clampCropRect,
+ createCropImageLoadGate,
+ createReferenceImageEditorActions,
+ cropRectFromPoints,
+ displayPointToSource,
+ moveCropRect,
+ rasterizeReferenceImageCrop,
+ referenceImageDataUrlError,
+} from "./reference-image-crop";
+
+type CropHandle = "north-west" | "north-east" | "south-west" | "south-east";
+
+type CropDrag =
+ | { kind: "new"; start: CropPoint; startClient: CropPoint }
+ | { kind: "move"; start: CropPoint; selection: CropRect }
+ | { kind: "resize"; anchor: CropPoint };
+
+function oppositeCropCorner(
+ selection: CropRect,
+ handle: CropHandle,
+): CropPoint {
+ const right = selection.x + selection.width;
+ const bottom = selection.y + selection.height;
+ switch (handle) {
+ case "north-west":
+ return { x: right, y: bottom };
+ case "north-east":
+ return { x: selection.x, y: bottom };
+ case "south-west":
+ return { x: right, y: selection.y };
+ case "south-east":
+ return { x: selection.x, y: selection.y };
+ }
+}
+
+function arrowDelta(key: string, step: number): CropPoint | null {
+ if (key === "ArrowLeft") return { x: -step, y: 0 };
+ if (key === "ArrowRight") return { x: step, y: 0 };
+ if (key === "ArrowUp") return { x: 0, y: -step };
+ if (key === "ArrowDown") return { x: 0, y: step };
+ return null;
+}
+
+/** A local freeform crop editor for MiniMax-H3 picture references. */
+export function ReferenceImageEditor({
+ open,
+ picture,
+ pictureNumber,
+ onOpenChange,
+ onApply,
+}: {
+ open: boolean;
+ picture: StagedReferenceImage | null;
+ pictureNumber: number;
+ onOpenChange: (open: boolean) => void;
+ onApply: (dataUrl: string, crop: CropRect | null) => void;
+}) {
+ const decodedImage = useRef<{
+ dataUrl: string;
+ image: HTMLImageElement;
+ } | null>(null);
+ const [imageLoadGate] = useState(createCropImageLoadGate);
+ const cropDrag = useRef<CropDrag | null>(null);
+ const [loadedDataUrl, setLoadedDataUrl] = useState<string | null>(null);
+ const [loadedSourceSize, setLoadedSourceSize] = useState<ImageSize | null>(
+ null,
+ );
+ const [loadedSelection, setLoadedSelection] = useState<CropRect | null>(null);
+ const [loadError, setLoadError] = useState<{
+ dataUrl: string;
+ message: string;
+ } | null>(null);
+ const [applying, setApplying] = useState(false);
+ const editorActions = useMemo(
+ () => createReferenceImageEditorActions({ onApply, onOpenChange }),
+ [onApply, onOpenChange],
+ );
+ const currentDataUrl = open ? (picture?.originalDataUrl ?? null) : null;
+ const sourceSize = currentDataUrl === loadedDataUrl ? loadedSourceSize : null;
+ const selection = currentDataUrl === loadedDataUrl ? loadedSelection : null;
+ const visibleLoadError =
+ currentDataUrl === loadError?.dataUrl ? loadError.message : null;
+
+ useEffect(() => {
+ if (!open || !picture) {
+ decodedImage.current = null;
+ cropDrag.current = null;
+ return;
+ }
+ const dataUrl = picture.originalDataUrl;
+ const loadClaim = imageLoadGate.begin(dataUrl);
+ decodedImage.current = null;
+ cropDrag.current = null;
+
+ const image = new Image();
+ image.onload = () => {
+ if (!loadClaim.isCurrent()) return;
+ const size = { width: image.naturalWidth, height: image.naturalHeight };
+ if (size.width <= 0 || size.height <= 0) {
+ setLoadError({
+ dataUrl,
+ message: "The picture has no readable pixels.",
+ });
+ return;
+ }
+ // Browser image dimensions and canvas drawing use the same corrected orientation.
+ decodedImage.current = { dataUrl, image };
+ setLoadError(null);
+ setLoadedSourceSize(size);
+ setLoadedSelection(
+ picture.crop ? clampCropRect(picture.crop, size) : null,
+ );
+ setLoadedDataUrl(dataUrl);
+ };
+ image.onerror = () => {
+ if (loadClaim.isCurrent()) {
+ setLoadError({
+ dataUrl,
+ message: "Could not open this picture for cropping.",
+ });
+ }
+ };
+ image.src = dataUrl;
+ return () => {
+ loadClaim.cancel();
+ };
+ }, [imageLoadGate, open, picture]);
+
+ const pointFromPointer = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>): CropPoint | null => {
+ if (!sourceSize) return null;
+ const bounds = event.currentTarget.getBoundingClientRect();
+ if (bounds.width <= 0 || bounds.height <= 0) return null;
+ return displayPointToSource(
+ { x: event.clientX - bounds.left, y: event.clientY - bounds.top },
+ { width: bounds.width, height: bounds.height },
+ sourceSize,
+ );
+ },
+ [sourceSize],
+ );
+
+ const handlePointerDown = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (event.button !== 0) {
+ return;
+ }
+ const point = pointFromPointer(event);
+ if (!point || !sourceSize) return;
+ event.preventDefault();
+ try {
+ event.currentTarget.setPointerCapture(event.pointerId);
+ } catch {
+ // Synthetic events and older webviews may not support pointer capture.
+ }
+ const target = event.target as HTMLElement;
+ const handle = target.dataset.cropHandle as CropHandle | undefined;
+ if (selection && handle) {
+ cropDrag.current = {
+ kind: "resize",
+ anchor: oppositeCropCorner(selection, handle),
+ };
+ return;
+ }
+ if (selection && target.closest("[data-crop-selection]")) {
+ cropDrag.current = {
+ kind: "move",
+ start: point,
+ selection,
+ };
+ return;
+ }
+ cropDrag.current = {
+ kind: "new",
+ start: point,
+ startClient: { x: event.clientX, y: event.clientY },
+ };
+ },
+ [pointFromPointer, selection, sourceSize],
+ );
+
+ const handlePointerMove = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) => {
+ const drag = cropDrag.current;
+ const point = pointFromPointer(event);
+ if (!drag || !point || !sourceSize) return;
+ if (drag.kind === "move") {
+ setLoadedSelection(
+ moveCropRect(
+ drag.selection,
+ { x: point.x - drag.start.x, y: point.y - drag.start.y },
+ sourceSize,
+ ),
+ );
+ return;
+ }
+ if (
+ drag.kind === "new" &&
+ Math.hypot(
+ event.clientX - drag.startClient.x,
+ event.clientY - drag.startClient.y,
+ ) < 4
+ ) {
+ return;
+ }
+ const anchor = drag.kind === "resize" ? drag.anchor : drag.start;
+ setLoadedSelection(cropRectFromPoints(anchor, point, sourceSize));
+ },
+ [pointFromPointer, sourceSize],
+ );
+
+ const finishPointer = useCallback(() => {
+ cropDrag.current = null;
+ }, []);
+
+ const handlePreviewKeyDown = useCallback(
+ (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ const step = event.shiftKey ? 10 : 1;
+ const delta = arrowDelta(event.key, step);
+ if (!delta) return;
+ event.preventDefault();
+ if (!selection || !sourceSize) return;
+ setLoadedSelection(moveCropRect(selection, delta, sourceSize));
+ },
+ [selection, sourceSize],
+ );
+
+ const apply = useCallback(() => {
+ const decoded = decodedImage.current;
+ if (
+ !selection ||
+ !sourceSize ||
+ !picture ||
+ !decoded ||
+ decoded.dataUrl !== picture.originalDataUrl
+ ) {
+ return;
+ }
+ setApplying(true);
+ setLoadError(null);
+ try {
+ const dataUrl = rasterizeReferenceImageCrop(
+ decoded.image,
+ selection,
+ sourceSize,
+ );
+ const sizeError = referenceImageDataUrlError(dataUrl);
+ if (sizeError) throw new Error(sizeError);
+ editorActions.apply(dataUrl, selection);
+ } catch (error) {
+ setLoadError({
+ dataUrl: picture.originalDataUrl,
+ message:
+ error instanceof Error
+ ? error.message
+ : "Could not crop this picture.",
+ });
+ } finally {
+ setApplying(false);
+ }
+ }, [editorActions, picture, selection, sourceSize]);
+
+ const validSelection =
+ selection !== null && selection.width > 0 && selection.height > 0;
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(nextOpen) => {
+ if (nextOpen) onOpenChange(true);
+ else editorActions.cancel();
+ }}
+ >
+ <DialogContent className="sm:max-w-3xl">
+ <DialogHeader>
+ <DialogTitle>Crop Picture {pictureNumber}</DialogTitle>
+ <DialogDescription>
+ Drag over the picture to choose what to keep. Move the selection or
+ resize it from its corners. Choose Use full image to clear any crop.
+ </DialogDescription>
+ </DialogHeader>
+
+ {picture && (
+ <div className="grid gap-4">
+ <div className="flex h-[min(50vh,30rem)] min-h-48 w-full items-center justify-center overflow-hidden rounded-xl bg-black/90">
+ <div className="relative inline-block max-h-full max-w-full shrink-0">
+ <img
+ src={picture.originalDataUrl}
+ alt={`Crop source ${pictureNumber}`}
+ draggable={false}
+ className="block max-h-[48vh] max-w-full select-none object-contain"
+ />
+ {sourceSize && (
+ <div
+ role="group"
+ tabIndex={0}
+ aria-label={`Crop selection for picture ${pictureNumber}. Drag to select an area. Drag the selection to move it, or drag a corner to resize it.`}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={finishPointer}
+ onPointerCancel={finishPointer}
+ onLostPointerCapture={finishPointer}
+ onKeyDown={handlePreviewKeyDown}
+ className="absolute inset-0 cursor-crosshair touch-none outline-none focus-visible:ring-2 focus-visible:ring-primary"
+ >
+ {selection &&
+ selection.width > 0 &&
+ selection.height > 0 && (
+ <div
+ data-crop-selection
+ className="absolute cursor-move border-2 border-white shadow-[0_0_0_9999px_rgba(0,0,0,0.48)]"
+ style={{
+ left: `${(selection.x / sourceSize.width) * 100}%`,
+ top: `${(selection.y / sourceSize.height) * 100}%`,
+ width: `${(selection.width / sourceSize.width) * 100}%`,
+ height: `${(selection.height / sourceSize.height) * 100}%`,
+ }}
+ >
+ {(
+ [
+ [
+ "north-west",
+ "-left-1.5 -top-1.5 cursor-nwse-resize",
+ ],
+ [
+ "north-east",
+ "-right-1.5 -top-1.5 cursor-nesw-resize",
+ ],
+ [
+ "south-west",
+ "-bottom-1.5 -left-1.5 cursor-nesw-resize",
+ ],
+ [
+ "south-east",
+ "-bottom-1.5 -right-1.5 cursor-nwse-resize",
+ ],
+ ] as const
+ ).map(([handle, position]) => (
+ <span
+ key={handle}
+ data-crop-handle={handle}
+ aria-hidden={true}
+ className={`absolute size-3 rounded-full border-2 border-white bg-primary shadow-sm ${position}`}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+
+ <p className="text-ui-11 text-muted-foreground">
+ {selection
+ ? "Drag inside the selection to move it, or drag a corner to resize it."
+ : "No crop selected. Drag over the picture to create one."}
+ </p>
+ {visibleLoadError && (
+ <p className="text-sm text-destructive">{visibleLoadError}</p>
+ )}
+ </div>
+ )}
+
+ <DialogFooter>
+ {picture && (
+ <Button
+ type="button"
+ variant="ghost"
+ className="sm:mr-auto"
+ onClick={() => editorActions.apply(picture.originalDataUrl, null)}
+ >
+ Use full image
+ </Button>
+ )}
+ <Button
+ type="button"
+ variant="outline"
+ onClick={editorActions.cancel}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ disabled={!validSelection || applying}
+ onClick={apply}
+ >
+ {applying ? "Applying..." : "Apply crop"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/studio/frontend/src/features/video/reference-picker.tsx b/studio/frontend/src/features/video/reference-picker.tsx
index 7f0c84044ca..ae13cf512c3 100644
--- a/studio/frontend/src/features/video/reference-picker.tsx
+++ b/studio/frontend/src/features/video/reference-picker.tsx
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { useCallback, useRef } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { Delete02Icon, FlimSlateIcon, MusicNote01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -19,12 +19,47 @@ import { useNativeFileDrop } from "@/features/native-intents";
import { cn } from "@/lib/utils";
import { toast } from "@/lib/toast";
-import { readReferenceFile } from "./reference-budget";
+import { createReferenceSelectionGate, readReferenceFile } from "./reference-budget";
/** One staged reference file: the data URL the request carries, plus its name for the chip. */
export interface ReferenceMedia {
name: string;
dataUrl: string;
+ durationSeconds?: number;
+}
+
+/** How long to wait for a browser to report a clip's duration before giving up on it. */
+export const REFERENCE_DURATION_TIMEOUT_MS = 15_000;
+
+/** Read a clip's duration, resolving undefined when the browser cannot report one.
+ *
+ * An element firing neither loadedmetadata nor error would leave this pending forever, and
+ * its picker slot with it, so the wait is bounded; callers already treat an unknown duration
+ * as "no auto trim". The source stays a data URL because WebKit reports no metadata for an
+ * object URL, and losing the duration costs more than the extra parse saves.
+ */
+function readVideoDuration(dataUrl: string): Promise<number | undefined> {
+ return new Promise((resolve) => {
+ const media = document.createElement("video");
+ let settled = false;
+ const finish = (duration?: number) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ media.onloadedmetadata = null;
+ media.onerror = null;
+ media.removeAttribute("src");
+ // Without a load() the element can keep the resource it was decoding.
+ media.load();
+ resolve(duration);
+ };
+ const timer = setTimeout(() => finish(), REFERENCE_DURATION_TIMEOUT_MS);
+ media.preload = "metadata";
+ media.onloadedmetadata = () =>
+ finish(Number.isFinite(media.duration) && media.duration > 0 ? media.duration : undefined);
+ media.onerror = () => finish();
+ media.src = dataUrl;
+ });
}
/** Reference video or audio picker that displays the selected filename. */
@@ -44,16 +79,41 @@ export function ReferenceMediaPicker({
compact?: boolean;
}) {
const inputRef = useRef<HTMLInputElement | null>(null);
+ // Only the newest read from this mounted picker may update the list.
+ const [gate] = useState(createReferenceSelectionGate);
+ useEffect(() => gate.mount(), [gate]);
+ // Index-keyed slots can receive a sibling when an earlier reference is removed.
+ const seen = useRef(value);
+ useEffect(() => {
+ if (seen.current === value) return;
+ seen.current = value;
+ gate.invalidate();
+ }, [value, gate]);
const readFile = useCallback(
(file: File | undefined | null) => {
+ if (!file) return;
+ const claim = gate.begin();
readReferenceFile(kind, file, {
- onLoaded: (dataUrl) =>
- onChange(dataUrl === null || !file ? null : { name: file.name, dataUrl }),
+ onLoaded: (dataUrl) => {
+ if (!claim.isCurrent()) return;
+ if (dataUrl === null) {
+ onChange(null);
+ return;
+ }
+ if (kind !== "video") {
+ onChange({ name: file.name, dataUrl });
+ return;
+ }
+ void readVideoDuration(dataUrl).then((durationSeconds) => {
+ if (!claim.isCurrent()) return;
+ onChange({ name: file.name, dataUrl, durationSeconds });
+ });
+ },
onError: (message) => toast.error(message),
});
},
- [kind, onChange],
+ [gate, kind, onChange],
);
// Tauri suppresses the webview's own drop events, so the handlers below never
diff --git a/studio/frontend/src/features/video/reference-trim.ts b/studio/frontend/src/features/video/reference-trim.ts
new file mode 100644
index 00000000000..3c6a3876421
--- /dev/null
+++ b/studio/frontend/src/features/video/reference-trim.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export const H3_REFERENCE_MIN_SECONDS = 2;
+export const H3_REFERENCE_MAX_SECONDS = 15;
+// Matches validate_h3_reference_trim's slack. Exact comparison refused intervals the server
+// accepts: the 0.1-step inputs reach 2.3 - 0.3, which is 1.9999999999999998.
+const DURATION_EPSILON = 1e-6;
+
+export interface ReferenceVideoTrimFeedback {
+ message: string;
+ invalid: boolean;
+}
+
+export interface ReferenceVideoTrim {
+ start: number | null;
+ end: number | null;
+}
+
+/** Select the first model-sized interval when a source is too long. */
+export function defaultReferenceVideoTrim(
+ sourceDuration?: number,
+): ReferenceVideoTrim {
+ return sourceDuration !== undefined &&
+ sourceDuration > H3_REFERENCE_MAX_SECONDS
+ ? { start: 0, end: H3_REFERENCE_MAX_SECONDS }
+ : { start: null, end: null };
+}
+
+/** Return user-facing validation for one optional reference-video interval. */
+export function referenceVideoTrimError(
+ label: string,
+ start: number | null,
+ end: number | null,
+ sourceDuration?: number,
+): string | null {
+ // No interval inside a too-short source can reach the minimum, so say so here instead of
+ // letting the decoder refuse it later.
+ if (
+ sourceDuration !== undefined &&
+ sourceDuration + DURATION_EPSILON < H3_REFERENCE_MIN_SECONDS
+ ) {
+ return `${label} is shorter than the 2 second minimum`;
+ }
+ if ((start === null) !== (end === null)) {
+ return `Set both start and end times for ${label}`;
+ }
+ if (start === null || end === null) {
+ return sourceDuration !== undefined &&
+ sourceDuration > H3_REFERENCE_MAX_SECONDS
+ ? `Select a 2 to 15 second section for ${label}`
+ : null;
+ }
+ const duration = end - start;
+ if (
+ !Number.isFinite(start) ||
+ !Number.isFinite(end) ||
+ start < 0 ||
+ end <= start ||
+ duration + DURATION_EPSILON < H3_REFERENCE_MIN_SECONDS ||
+ duration - DURATION_EPSILON > H3_REFERENCE_MAX_SECONDS ||
+ (sourceDuration !== undefined && end > sourceDuration + DURATION_EPSILON)
+ ) {
+ return `Choose 2 to 15 seconds within ${label}`;
+ }
+ return null;
+}
+
+/** Describe the current trim in the form without presenting a valid selection as a warning. */
+export function referenceVideoTrimFeedback(
+ label: string,
+ start: number | null,
+ end: number | null,
+ sourceDuration?: number,
+): ReferenceVideoTrimFeedback {
+ const source =
+ sourceDuration !== undefined
+ ? `${sourceDuration.toFixed(1)}s source. `
+ : "";
+ const error = referenceVideoTrimError(label, start, end, sourceDuration);
+ if (error) {
+ return { message: `${source}${error}.`, invalid: true };
+ }
+ if (start !== null && end !== null) {
+ if (
+ sourceDuration !== undefined &&
+ sourceDuration > H3_REFERENCE_MAX_SECONDS &&
+ start === 0 &&
+ end === H3_REFERENCE_MAX_SECONDS
+ ) {
+ return {
+ message: `${source}First ${H3_REFERENCE_MAX_SECONDS.toFixed(1)}s selected automatically. Adjust the times to use another section.`,
+ invalid: false,
+ };
+ }
+ return {
+ message: `${source}Selected ${start.toFixed(1)}s to ${end.toFixed(1)}s (${(
+ end - start
+ ).toFixed(1)}s).`,
+ invalid: false,
+ };
+ }
+ return {
+ message: source
+ ? `${source}Trim is optional.`
+ : "Trim is optional for clips up to 15 seconds.",
+ invalid: false,
+ };
+}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 8db31f02700..006be6b6f2c 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -3,9 +3,11 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
+ Cancel01Icon,
Delete02Icon,
Download01Icon,
FlimSlateIcon,
+ ImageCropIcon,
Image03Icon,
InformationCircleIcon,
PinIcon,
@@ -137,7 +139,20 @@ import { subscribeModelEjected } from "@/lib/model-lifecycle-events";
import { MATCH_SOURCE_RESOLUTION, matchedCanvas } from "./keyframe-canvas";
import { hasReferenceCapacity } from "./reference-budget";
+import {
+ applyReferenceImageCrop,
+ referenceImageDataUrls,
+ stageReferenceImage,
+ type StagedReferenceImage,
+} from "./reference-image-crop";
+import { ReferenceImageEditor } from "./reference-image-editor";
import { type ReferenceMedia, ReferenceMediaPicker } from "./reference-picker";
+import {
+ defaultReferenceVideoTrim,
+ H3_REFERENCE_MAX_SECONDS,
+ referenceVideoTrimError,
+ referenceVideoTrimFeedback,
+} from "./reference-trim";
import {
type GalleryVideo,
type VideoGenerateProgress,
@@ -594,6 +609,36 @@ function StatusChip({ label, value }: { label: string; value: string }) {
);
}
+function ReferenceVideoTrimStatus({
+ label,
+ start,
+ end,
+ sourceDuration,
+}: {
+ label: string;
+ start: number | null;
+ end: number | null;
+ sourceDuration?: number;
+}) {
+ const feedback = referenceVideoTrimFeedback(
+ label,
+ start,
+ end,
+ sourceDuration,
+ );
+ return (
+ <p
+ aria-live="polite"
+ className={cn(
+ "text-ui-11 leading-snug",
+ feedback.invalid ? "text-destructive" : "text-muted-foreground/70",
+ )}
+ >
+ {feedback.message}
+ </p>
+ );
+}
+
// The full generation recipe for a clip, with a one-click "restore to inputs".
function RecipePopover({
video,
@@ -896,9 +941,15 @@ function VideoGenerator({
// Natural pixel size of whichever keyframe drives the canvas, for the "match source" preview.
const [keyframeAspect, setKeyframeAspect] = useState<[number, number] | null>(null);
// Separate lists preserve Ref2VA's image, video, then audio request order.
- const [referenceImages, setReferenceImages] = useState<string[]>([]);
+ const [referenceImages, setReferenceImages] = useState<StagedReferenceImage[]>([]);
+ const [cropPictureIndex, setCropPictureIndex] = useState<number | null>(null);
const [referenceVideos, setReferenceVideos] = useState<
- Array<{ video: ReferenceMedia; audio: ReferenceMedia | null }>
+ Array<{
+ video: ReferenceMedia;
+ audio: ReferenceMedia | null;
+ trimStartSeconds: number | null;
+ trimEndSeconds: number | null;
+ }>
>([]);
const [referenceAudios, setReferenceAudios] = useState<ReferenceMedia[]>([]);
const [referenceImageSize, setReferenceImageSize] = useState<"match" | "max">("match");
@@ -1144,6 +1195,7 @@ function VideoGenerator({
setReferenceImages([]);
setReferenceVideos([]);
setReferenceAudios([]);
+ setCropPictureIndex(null);
}
}, [status?.loaded, supportsReferences]);
useEffect(() => {
@@ -3005,6 +3057,20 @@ function VideoGenerator({
toast.error("Add a reference picture or video for this checkpoint");
return;
}
+ for (const [index, entry] of referenceVideos.entries()) {
+ const start = entry.trimStartSeconds;
+ const end = entry.trimEndSeconds;
+ const trimError = referenceVideoTrimError(
+ `Video ${index + 1}`,
+ start,
+ end,
+ entry.video.durationSeconds,
+ );
+ if (trimError) {
+ toast.error(trimError);
+ return;
+ }
+ }
// Resolve a base seed up front: with a random one we still pick a concrete seed now so the recipe records it.
let resolvedSeed: number | undefined;
if (seed.trim()) {
@@ -3044,13 +3110,17 @@ function VideoGenerator({
first_frame: supportsKeyframes ? firstFrame ?? undefined : undefined,
last_frame: supportsKeyframes ? lastFrame ?? undefined : undefined,
reference_images:
- supportsReferences && referenceImages.length > 0 ? referenceImages : undefined,
+ supportsReferences && referenceImages.length > 0
+ ? referenceImageDataUrls(referenceImages)
+ : undefined,
reference_videos:
supportsReferences && referenceVideos.length > 0
? referenceVideos.map(
(entry): VideoReferenceVideo => ({
video: entry.video.dataUrl,
audio: entry.audio?.dataUrl,
+ trim_start_seconds: entry.trimStartSeconds ?? undefined,
+ trim_end_seconds: entry.trimEndSeconds ?? undefined,
}),
)
: undefined,
@@ -3483,18 +3553,43 @@ function VideoGenerator({
<span className="text-ui-11 text-muted-foreground/70">
Picture {index + 1}
</span>
- <ImageDropzone
- value={image}
- onChange={(next) =>
- setReferenceImages((prev) =>
- next
- ? prev.map((item, i) => (i === index ? next : item))
- : prev.filter((_, i) => i !== index),
- )
- }
- removeLabel={`Remove picture ${index + 1}`}
- className="h-20"
- />
+ <div className="relative h-24 overflow-hidden rounded-[10px] border border-border bg-muted/30">
+ <button
+ type="button"
+ aria-label={`Edit crop for picture ${index + 1}`}
+ className="group h-full w-full overflow-hidden outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary"
+ onClick={() => setCropPictureIndex(index)}
+ >
+ <img
+ src={image.dataUrl}
+ alt=""
+ className="h-full w-full object-cover transition-transform group-hover:scale-[1.02]"
+ />
+ <span className="absolute inset-x-0 bottom-0 flex items-center justify-center gap-1 bg-gradient-to-t from-black/80 to-transparent px-2 pb-1.5 pt-6 text-ui-11 font-medium text-white">
+ <HugeiconsIcon icon={ImageCropIcon} className="size-3.5" />
+ Edit crop
+ </span>
+ </button>
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <Button
+ type="button"
+ variant="secondary"
+ size="icon"
+ aria-label={`Remove picture ${index + 1}`}
+ className="absolute right-1.5 top-1.5 size-7 bg-background/85 shadow-sm backdrop-blur-sm"
+ onClick={() =>
+ setReferenceImages((prev) =>
+ prev.filter((_, current) => current !== index),
+ )
+ }
+ >
+ <HugeiconsIcon icon={Cancel01Icon} className="size-3.5" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Remove picture {index + 1}</TooltipContent>
+ </Tooltip>
+ </div>
</div>
))}
{referenceImages.length < 9 && hasReferenceRoom && (
@@ -3504,9 +3599,12 @@ function VideoGenerator({
</span>
<ImageDropzone
value={null}
- onChange={(next) => next && setReferenceImages((prev) => [...prev, next])}
+ onChange={(next) =>
+ next &&
+ setReferenceImages((prev) => [...prev, stageReferenceImage(next)])
+ }
label="Add"
- className="h-20"
+ className="h-24"
/>
</div>
)}
@@ -3521,13 +3619,99 @@ function VideoGenerator({
kind="video"
value={entry.video}
label={`Video ${index + 1}`}
- onChange={(next) =>
+ onChange={(next) => {
+ const trim = defaultReferenceVideoTrim(next?.durationSeconds);
setReferenceVideos((prev) =>
next
- ? prev.map((item, i) => (i === index ? { ...item, video: next } : item))
+ ? prev.map((item, i) =>
+ i === index
+ ? {
+ ...item,
+ video: next,
+ trimStartSeconds: trim.start,
+ trimEndSeconds: trim.end,
+ }
+ : item,
+ )
: prev.filter((_, i) => i !== index),
- )
- }
+ );
+ }}
+ />
+ <video
+ controls={true}
+ muted={true}
+ preload="metadata"
+ src={entry.video.dataUrl}
+ className="max-h-36 w-full rounded-[10px] bg-black object-contain"
+ />
+ <div className="grid grid-cols-2 gap-2">
+ <div className="grid gap-1 text-ui-11 text-muted-foreground">
+ Trim start (seconds)
+ <Input
+ aria-label={`Video ${index + 1} trim start in seconds`}
+ type="number"
+ min={0}
+ max={entry.video.durationSeconds}
+ step={0.1}
+ value={entry.trimStartSeconds ?? ""}
+ placeholder="0"
+ onChange={(event) =>
+ setReferenceVideos((prev) =>
+ prev.map((item, i) =>
+ i === index
+ ? {
+ ...item,
+ trimStartSeconds:
+ event.target.value === ""
+ ? null
+ : Number(event.target.value),
+ }
+ : item,
+ ),
+ )
+ }
+ />
+ </div>
+ <div className="grid gap-1 text-ui-11 text-muted-foreground">
+ Trim end (seconds)
+ <Input
+ aria-label={`Video ${index + 1} trim end in seconds`}
+ type="number"
+ min={0}
+ max={entry.video.durationSeconds}
+ step={0.1}
+ value={entry.trimEndSeconds ?? ""}
+ placeholder={
+ entry.video.durationSeconds !== undefined
+ ? Math.min(
+ entry.video.durationSeconds,
+ H3_REFERENCE_MAX_SECONDS,
+ ).toFixed(1)
+ : "15"
+ }
+ onChange={(event) =>
+ setReferenceVideos((prev) =>
+ prev.map((item, i) =>
+ i === index
+ ? {
+ ...item,
+ trimEndSeconds:
+ event.target.value === ""
+ ? null
+ : Number(event.target.value),
+ }
+ : item,
+ ),
+ )
+ }
+ />
+ </div>
+ </div>
+ <ReferenceVideoTrimStatus
+ label={`Video ${index + 1}`}
+ start={entry.trimStartSeconds}
+ end={entry.trimEndSeconds}
+ sourceDuration={entry.video.durationSeconds}
/>
<ReferenceMediaPicker
kind="audio"
@@ -3547,9 +3731,19 @@ function VideoGenerator({
kind="video"
value={null}
label={`Add video ${referenceVideos.length + 1}`}
- onChange={(next) =>
- next && setReferenceVideos((prev) => [...prev, { video: next, audio: null }])
- }
+ onChange={(next) => {
+ if (!next) return;
+ const trim = defaultReferenceVideoTrim(next.durationSeconds);
+ setReferenceVideos((prev) => [
+ ...prev,
+ {
+ video: next,
+ audio: null,
+ trimStartSeconds: trim.start,
+ trimEndSeconds: trim.end,
+ },
+ ]);
+ }}
/>
)}
</div>
@@ -3615,6 +3809,23 @@ function VideoGenerator({
</div>
)}
+ {cropPictureIndex !== null && referenceImages[cropPictureIndex] && (
+ <ReferenceImageEditor
+ key={cropPictureIndex}
+ open={true}
+ picture={referenceImages[cropPictureIndex]}
+ pictureNumber={cropPictureIndex + 1}
+ onOpenChange={(open) => {
+ if (!open) setCropPictureIndex(null);
+ }}
+ onApply={(dataUrl, crop) =>
+ setReferenceImages((prev) =>
+ applyReferenceImageCrop(prev, cropPictureIndex, dataUrl, crop),
+ )
+ }
+ />
+ )}
+
{status?.supports_cfg !== false && (
<NegativePromptField
value={negativePrompt}
diff --git a/studio/frontend/tests/video-reference-image-crop.test.ts b/studio/frontend/tests/video-reference-image-crop.test.ts
new file mode 100644
index 00000000000..2aba38b6bb8
--- /dev/null
+++ b/studio/frontend/tests/video-reference-image-crop.test.ts
@@ -0,0 +1,283 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ type CropRasterCanvas,
+ MAX_REFERENCE_IMAGE_DATA_URL_LENGTH,
+ applyReferenceImageCrop,
+ clampCropRect,
+ createCropImageLoadGate,
+ createReferenceImageEditorActions,
+ cropRectFromPoints,
+ displayPointToSource,
+ moveCropRect,
+ rasterizeReferenceImageCrop,
+ referenceCropExportSize,
+ referenceImageDataUrlError,
+ referenceImageDataUrls,
+ stageReferenceImage,
+} from "../src/features/video/reference-image-crop.ts";
+
+test("crop rectangles stay within natural image pixels in either drag direction", () => {
+ assert.deepEqual(
+ cropRectFromPoints(
+ { x: 900, y: 700 },
+ { x: -20, y: 100 },
+ { width: 800, height: 600 },
+ ),
+ { x: 0, y: 100, width: 800, height: 500 },
+ );
+ assert.deepEqual(
+ clampCropRect(
+ { x: 790.4, y: 590.2, width: 100, height: 100 },
+ { width: 800, height: 600 },
+ ),
+ { x: 790, y: 590, width: 10, height: 10 },
+ );
+});
+
+test("landscape preview coordinates map to the same source rectangle", () => {
+ const start = displayPointToSource(
+ { x: 40, y: 20 },
+ { width: 400, height: 200 },
+ { width: 4000, height: 2000 },
+ );
+ const end = displayPointToSource(
+ { x: 240, y: 120 },
+ { width: 400, height: 200 },
+ { width: 4000, height: 2000 },
+ );
+ assert.deepEqual(
+ cropRectFromPoints(start, end, { width: 4000, height: 2000 }),
+ { x: 400, y: 200, width: 2000, height: 1000 },
+ );
+});
+
+test("portrait preview coordinates keep the decoded natural orientation", () => {
+ const start = displayPointToSource(
+ { x: 25, y: 100 },
+ { width: 200, height: 500 },
+ { width: 1200, height: 3000 },
+ );
+ const end = displayPointToSource(
+ { x: 150, y: 400 },
+ { width: 200, height: 500 },
+ { width: 1200, height: 3000 },
+ );
+ assert.deepEqual(
+ cropRectFromPoints(start, end, { width: 1200, height: 3000 }),
+ { x: 150, y: 600, width: 750, height: 1800 },
+ );
+});
+
+test("fractional display edges include every selected source pixel", () => {
+ const start = displayPointToSource(
+ { x: 1.2, y: 2.2 },
+ { width: 10, height: 10 },
+ { width: 100, height: 100 },
+ );
+ const end = displayPointToSource(
+ { x: 4.3, y: 6.3 },
+ { width: 10, height: 10 },
+ { width: 100, height: 100 },
+ );
+ assert.deepEqual(
+ cropRectFromPoints(start, end, { width: 100, height: 100 }),
+ { x: 12, y: 22, width: 31, height: 41 },
+ );
+});
+
+test("moving a crop preserves its size and keeps it inside the source", () => {
+ assert.deepEqual(
+ moveCropRect(
+ { x: 200, y: 100, width: 400, height: 300 },
+ { x: 500, y: -200 },
+ { width: 800, height: 600 },
+ ),
+ { x: 400, y: 0, width: 400, height: 300 },
+ );
+ assert.deepEqual(
+ moveCropRect(
+ { x: 200, y: 100, width: 400, height: 300 },
+ { x: -50.4, y: 25.6 },
+ { width: 800, height: 600 },
+ ),
+ { x: 150, y: 126, width: 400, height: 300 },
+ );
+});
+
+test("raster output uses the selected source pixels without upscaling", () => {
+ const source = {} as CanvasImageSource;
+ const calls: unknown[][] = [];
+ const canvas: CropRasterCanvas = {
+ width: 0,
+ height: 0,
+ getContext: () => ({
+ drawImage: (...args: unknown[]) => calls.push(args),
+ }),
+ toDataURL: (type) => {
+ assert.equal(type, "image/png");
+ return "data:image/png;base64,CROP";
+ },
+ };
+
+ assert.equal(
+ rasterizeReferenceImageCrop(
+ source,
+ { x: 20, y: 30, width: 40, height: 50 },
+ { width: 100, height: 100 },
+ () => canvas,
+ ),
+ "data:image/png;base64,CROP",
+ );
+ assert.equal(canvas.width, 40);
+ assert.equal(canvas.height, 50);
+ assert.deepEqual(calls, [[source, 20, 30, 40, 50, 0, 0, 40, 50]]);
+});
+
+test("applying a crop retains the original data URL and picture ordering", () => {
+ const staged = ["original-1", "original-2", "original-3"].map(
+ stageReferenceImage,
+ );
+ const crop = { x: 10, y: 20, width: 300, height: 200 };
+ const cropped = applyReferenceImageCrop(staged, 1, "crop-2", crop);
+
+ assert.deepEqual(referenceImageDataUrls(cropped), [
+ "original-1",
+ "crop-2",
+ "original-3",
+ ]);
+ assert.equal(cropped[1]?.originalDataUrl, "original-2");
+ assert.deepEqual(cropped[1]?.crop, crop);
+ assert.strictEqual(cropped[0], staged[0]);
+ assert.strictEqual(cropped[2], staged[2]);
+
+ const restored = applyReferenceImageCrop(
+ cropped,
+ 1,
+ cropped[1]?.originalDataUrl ?? "",
+ null,
+ );
+ assert.equal(restored[1]?.dataUrl, "original-2");
+ assert.equal(restored[1]?.crop, null);
+});
+
+test("request serialization keeps current rasters in picture order", () => {
+ let images = ["original-1", "original-2", "original-3"].map(
+ stageReferenceImage,
+ );
+ images = applyReferenceImageCrop(images, 0, "crop-1", {
+ x: 1,
+ y: 2,
+ width: 3,
+ height: 4,
+ });
+ images = applyReferenceImageCrop(images, 2, "crop-3", {
+ x: 5,
+ y: 6,
+ width: 7,
+ height: 8,
+ });
+ assert.deepEqual(referenceImageDataUrls(images), [
+ "crop-1",
+ "original-2",
+ "crop-3",
+ ]);
+});
+
+test("only the latest image decode claim can publish editor state", () => {
+ const gate = createCropImageLoadGate();
+ const oldLoad = gate.begin("old-picture");
+ const currentLoad = gate.begin("current-picture");
+ assert.equal(oldLoad.isCurrent(), false);
+ assert.equal(currentLoad.isCurrent(), true);
+ currentLoad.cancel();
+ assert.equal(currentLoad.isCurrent(), false);
+});
+
+test("a crop export over the request field cap is rejected locally", () => {
+ assert.equal(
+ referenceImageDataUrlError("x".repeat(MAX_REFERENCE_IMAGE_DATA_URL_LENGTH)),
+ null,
+ );
+ assert.match(
+ referenceImageDataUrlError(
+ "x".repeat(MAX_REFERENCE_IMAGE_DATA_URL_LENGTH + 1),
+ ) ?? "",
+ /too large/,
+ );
+});
+
+test("Cancel closes without invoking Apply while Apply performs both actions", () => {
+ const applied: Array<{ dataUrl: string; crop: unknown }> = [];
+ const openChanges: boolean[] = [];
+ const actions = createReferenceImageEditorActions({
+ onApply: (dataUrl, crop) => applied.push({ dataUrl, crop }),
+ onOpenChange: (open) => openChanges.push(open),
+ });
+
+ actions.cancel();
+ assert.deepEqual(applied, []);
+ assert.deepEqual(openChanges, [false]);
+
+ const crop = { x: 1, y: 2, width: 3, height: 4 };
+ actions.apply("crop", crop);
+ assert.deepEqual(applied, [{ dataUrl: "crop", crop }]);
+ assert.deepEqual(openChanges, [false, false]);
+});
+
+test("a crop larger than the model can use is exported at a size it can", () => {
+ // Measured in real engines, an unbounded PNG export of a 12MP photo reaches ~52 MiB and a
+ // 24MP one 36-105 MiB, all past the 32 MiB cap this module enforces.
+ assert.deepEqual(referenceCropExportSize({ width: 5712, height: 4284 }), {
+ width: 2730,
+ height: 2048,
+ });
+ assert.deepEqual(referenceCropExportSize({ width: 4032, height: 3024 }), {
+ width: 2730,
+ height: 2048,
+ });
+ // The long edge is capped too, for aspects whose short edge already fits.
+ assert.deepEqual(referenceCropExportSize({ width: 8192, height: 2000 }), {
+ width: 4096,
+ height: 1000,
+ });
+ // Anything already within the bounds is untouched, including both exact edges.
+ assert.deepEqual(referenceCropExportSize({ width: 40, height: 50 }), {
+ width: 40,
+ height: 50,
+ });
+ assert.deepEqual(referenceCropExportSize({ width: 4096, height: 2048 }), {
+ width: 4096,
+ height: 2048,
+ });
+});
+
+test("the raster is drawn at the reduced size, from the full selected source rect", () => {
+ const source = {} as CanvasImageSource;
+ const calls: unknown[][] = [];
+ const canvas: CropRasterCanvas = {
+ width: 0,
+ height: 0,
+ getContext: () => ({
+ drawImage: (...args: unknown[]) => calls.push(args),
+ }),
+ toDataURL: () => "data:image/png;base64,BIG",
+ };
+
+ rasterizeReferenceImageCrop(
+ source,
+ { x: 100, y: 200, width: 5712, height: 4284 },
+ { width: 6000, height: 4500 },
+ () => canvas,
+ );
+
+ assert.equal(canvas.width, 2730);
+ assert.equal(canvas.height, 2048);
+ // Source rect unchanged, destination reduced: the downscale crops nothing away, and the
+ // stored crop stays in source pixels for the editor to restore.
+ assert.deepEqual(calls, [[source, 100, 200, 5712, 4284, 0, 0, 2730, 2048]]);
+});
diff --git a/studio/frontend/tests/video-reference-selection-gate.test.ts b/studio/frontend/tests/video-reference-selection-gate.test.ts
new file mode 100644
index 00000000000..f69c9ce005d
--- /dev/null
+++ b/studio/frontend/tests/video-reference-selection-gate.test.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { createReferenceSelectionGate } from "../src/features/video/reference-budget.ts";
+
+test("the newest read is the only one allowed to write back", () => {
+ const gate = createReferenceSelectionGate();
+ const first = gate.begin();
+ assert.equal(first.isCurrent(), true);
+
+ const second = gate.begin();
+ assert.equal(first.isCurrent(), false);
+ assert.equal(second.isCurrent(), true);
+
+ assert.equal(first.isCurrent(), false);
+});
+
+test("a value this picker did not set retires the read in flight", () => {
+ const gate = createReferenceSelectionGate();
+ const claim = gate.begin();
+
+ gate.invalidate();
+ assert.equal(claim.isCurrent(), false);
+
+ assert.equal(gate.begin().isCurrent(), true);
+});
+
+test("unmounting revokes a read, and a remount does not revive it", () => {
+ const gate = createReferenceSelectionGate();
+ const unmount = gate.mount();
+ const claim = gate.begin();
+ assert.equal(claim.isCurrent(), true);
+
+ unmount();
+ assert.equal(claim.isCurrent(), false);
+
+ gate.mount();
+ assert.equal(claim.isCurrent(), false);
+ assert.equal(gate.begin().isCurrent(), true);
+});
diff --git a/studio/frontend/tests/video-reference-trim.test.ts b/studio/frontend/tests/video-reference-trim.test.ts
new file mode 100644
index 00000000000..1fc1440a1f4
--- /dev/null
+++ b/studio/frontend/tests/video-reference-trim.test.ts
@@ -0,0 +1,114 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ defaultReferenceVideoTrim,
+ referenceVideoTrimError,
+ referenceVideoTrimFeedback,
+} from "../src/features/video/reference-trim.ts";
+
+test("long reference videos default to the first model-sized interval", () => {
+ assert.deepEqual(defaultReferenceVideoTrim(20), { start: 0, end: 15 });
+ assert.deepEqual(defaultReferenceVideoTrim(15), { start: null, end: null });
+ assert.deepEqual(defaultReferenceVideoTrim(undefined), {
+ start: null,
+ end: null,
+ });
+});
+
+test("short reference videos need no explicit trim", () => {
+ assert.equal(referenceVideoTrimError("Video 1", null, null, 15), null);
+});
+
+test("an overlong reference video requires both endpoints", () => {
+ assert.match(
+ referenceVideoTrimError("Video 2", null, null, 20) ?? "",
+ /2 to 15 second section/,
+ );
+ assert.match(
+ referenceVideoTrimError("Video 2", 3, null, 20) ?? "",
+ /both start and end times/,
+ );
+});
+
+test("exact two and fifteen second intervals are accepted", () => {
+ assert.equal(referenceVideoTrimError("Video 1", 3, 5, 20), null);
+ assert.equal(referenceVideoTrimError("Video 1", 3, 18, 20), null);
+});
+
+test("invalid or out-of-source intervals are refused", () => {
+ for (const [start, end] of [
+ [-1, 3],
+ [3, 3],
+ [3, 4.9],
+ [0, 15.1],
+ [10, 21],
+ [Number.NaN, 5],
+ [0, Number.POSITIVE_INFINITY],
+ ]) {
+ assert.match(
+ referenceVideoTrimError("Video 3", start, end, 20) ?? "",
+ /2 to 15 seconds within/,
+ );
+ }
+});
+
+test("trim feedback distinguishes required, optional and selected states", () => {
+ assert.deepEqual(referenceVideoTrimFeedback("Video 1", null, null, 10), {
+ message: "10.0s source. Trim is optional.",
+ invalid: false,
+ });
+ assert.deepEqual(referenceVideoTrimFeedback("Video 1", null, null, 20), {
+ message: "20.0s source. Select a 2 to 15 second section for Video 1.",
+ invalid: true,
+ });
+ assert.deepEqual(referenceVideoTrimFeedback("Video 1", 0, 15, 20), {
+ message:
+ "20.0s source. First 15.0s selected automatically. Adjust the times to use another section.",
+ invalid: false,
+ });
+ assert.deepEqual(referenceVideoTrimFeedback("Video 1", 5, 13, 20), {
+ message: "20.0s source. Selected 5.0s to 13.0s (8.0s).",
+ invalid: false,
+ });
+});
+
+test("intervals the backend accepts are not refused over floating point", () => {
+ // validate_h3_reference_trim allows 1e-6 of slack. The 0.1-step inputs reach differences
+ // that are inexact in binary, and comparing exactly here refused them.
+ assert.equal(2.3 - 0.3 < 2, true);
+ assert.equal(16.1 - 1.1 > 15, true);
+ for (const [start, end] of [
+ [0.3, 2.3],
+ [0.8, 2.8],
+ [1.3, 3.3],
+ [2.1, 4.1],
+ [1.1, 16.1],
+ [3.1, 18.1],
+ ]) {
+ assert.equal(
+ referenceVideoTrimError("Video 1", start, end, 30),
+ null,
+ `${start} to ${end} should be accepted`,
+ );
+ }
+});
+
+test("a source shorter than the model minimum is refused before it is sent", () => {
+ // No interval inside a 1.5s clip reaches 2s, so the fields are a dead end and the backend
+ // refuses it regardless.
+ assert.equal(
+ referenceVideoTrimError("Video 1", null, null, 1.5),
+ "Video 1 is shorter than the 2 second minimum",
+ );
+ assert.equal(
+ referenceVideoTrimError("Video 1", 0, 1.5, 1.5),
+ "Video 1 is shorter than the 2 second minimum",
+ );
+ // Exactly the minimum is fine, and so is an unknown duration.
+ assert.equal(referenceVideoTrimError("Video 1", null, null, 2), null);
+ assert.equal(referenceVideoTrimError("Video 1", null, null, undefined), null);
+});