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.

Unsloth Studio: Cosmos3 256p, NVIDIA's frame ranges and a per-model frame-rate picker (#16737)

Leo Borcherding681fd0174bab
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index e508e957006..dcf8eeeb7ed 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -284,6 +284,7 @@ from .video_families import (
validate_video_flow_controls,
validate_video_keyframe_conditioning,
validate_video_reference_conditioning,
+ validate_video_fps,
validate_video_request_shape,
video_custom_size_bounds,
video_family_prequant_available,
@@ -13280,7 +13281,11 @@ class VideoBackend:
if self._generate_job_active:
raise RuntimeError(VIDEO_GENERATION_BUSY_MSG)
validate_video_request_shape(
- state.family, width = width, height = height, num_frames = run_num_frames
+ state.family,
+ width = width,
+ height = height,
+ num_frames = run_num_frames,
+ fps = fps,
)
if before_commit is not None:
before_commit()
@@ -13638,6 +13643,7 @@ class VideoBackend:
shift = _resolved_inputs.flow_shift
audio_shift = _resolved_inputs.audio_flow_shift
frames = snap_num_frames(fam, num_frames or fam.default_num_frames)
+ validate_video_fps(fam, fps)
out_fps = (
fam.default_fps if fam.name == "minimax-h3" else int(fps or fam.default_fps)
)
@@ -15492,6 +15498,10 @@ class VideoBackend:
"guidance": default_guidance,
"num_frames": fam.default_num_frames,
"fps": fam.default_fps,
+ "fps_range": list(fam.fps_range) if fam.fps_range else None,
+ "fps_choices": list(fam.fps_choices),
+ "min_num_frames": max(int(fam.frame_offset), int(fam.min_num_frames)),
+ "max_num_frames": fam.max_num_frames,
"frame_step": fam.frame_step,
"frame_offset": fam.frame_offset,
"duration_presets": list(fam.duration_presets),
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index 10f52d5a98c..d76f6b9463d 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -234,6 +234,9 @@ class VideoFamily:
default_guidance: float = 4.0
default_num_frames: int = 121
default_fps: int = 24
+ # Neither set = the rate is fixed.
+ fps_range: Optional[tuple[int, int]] = None
+ fps_choices: tuple[int, ...] = ()
frame_step: int = 8
# Offset in the temporal lattice. Existing pipelines use k*step+1; MiniMax-H3 uses 17k+5.
frame_offset: int = 1
@@ -429,6 +432,8 @@ _COSMOS3_PROFILE = FamilyProfile(
# Model-card sampling; the shipped scheduler_config.json's flow_shift 1.0 is used by neither card.
_COSMOS3_NANO_SCHEDULER = (("flow_shift", 10.0),)
_COSMOS3_EDGE_SCHEDULER = (("flow_shift", 12.0), ("use_karras_sigmas", False))
+# The pipeline's 256 tier: 16:9, 9:16, 1:1, 4:3, 3:4 (NVIDIA runs 448x256 too, which the custom bounds take).
+_COSMOS3_256P = ((320, 192), (192, 320), (256, 256), (320, 256), (256, 320))
def local_cosmos3_pipeline_family(path: Optional[str]) -> Optional[str]:
@@ -1019,10 +1024,13 @@ _FAMILIES: tuple[VideoFamily, ...] = (
default_guidance = 6.0,
default_num_frames = 189,
default_fps = 24,
+ # NVIDIA/cosmos docs/reference/models.md, "Generation settings": 10, 16, 24, 30 FPS.
+ fps_choices = (10, 16, 24, 30),
frame_step = 4,
min_num_frames = 5,
max_num_frames = 397,
resolution_multiple = 16,
+ # The pipeline's 720 / 480 / 256 tiers (_ACTION_RESOLUTION_BINS, same as cosmos-framework's VIDEO_RES_SIZE_INFO).
resolution_presets = (
(1280, 720),
(720, 1280),
@@ -1031,6 +1039,10 @@ _FAMILIES: tuple[VideoFamily, ...] = (
(832, 1104),
(832, 480), # faster
(480, 832), # faster
+ (640, 640), # faster
+ (736, 544), # faster
+ (544, 736), # faster
+ *_COSMOS3_256P,
),
duration_presets = (2.0, 5.0, 7.875),
bf16_components_gb = (30.4, 0.0, 1.4),
@@ -1052,11 +1064,20 @@ _FAMILIES: tuple[VideoFamily, ...] = (
default_guidance = 6.0,
default_num_frames = 121,
default_fps = 24,
+ # Card: "12-30 fps, and 50-150 frames"; 53 and 149 are the 4k+1 counts inside 50-150.
+ fps_range = (12, 30),
frame_step = 4,
min_num_frames = 53,
max_num_frames = 149,
resolution_multiple = 16,
- resolution_presets = ((832, 480), (480, 832), (640, 640), (736, 544), (544, 736)),
+ resolution_presets = (
+ (832, 480),
+ (480, 832),
+ (640, 640),
+ (736, 544),
+ (544, 736),
+ *_COSMOS3_256P,
+ ),
duration_presets = (3.0, 5.0, 6.0),
bf16_components_gb = (6.7, 0.0, 1.4),
supports_torch_compile = False,
@@ -1419,6 +1440,31 @@ class VideoShapeError(ValueError):
widening the 400 it gives every other bad-input ValueError."""
+def video_family_fps_options(fam: VideoFamily) -> Optional[tuple[int, ...]]:
+ choices = tuple(sorted({int(f) for f in getattr(fam, "fps_choices", ()) or ()}))
+ if choices:
+ return choices
+ bounds = getattr(fam, "fps_range", None)
+ if bounds:
+ return tuple(range(int(bounds[0]), int(bounds[1]) + 1))
+ return None
+
+
+def validate_video_fps(fam: VideoFamily, fps: Optional[int]) -> None:
+ """Refuse a frame rate outside the family's declared ones; a family that declares none is not judged."""
+ options = video_family_fps_options(fam)
+ if fps is None or options is None or int(fps) in options:
+ return
+ if getattr(fam, "fps_choices", ()):
+ supported = ", ".join(str(f) for f in options)
+ else:
+ supported = f"{options[0]} to {options[-1]}"
+ raise VideoShapeError(
+ f"{fps} fps is not a supported frame rate for {fam.name}. Supported: {supported} fps "
+ f"(the default is {fam.default_fps})."
+ )
+
+
def _validate_custom_video_size(fam: VideoFamily, width: int, height: int) -> None:
bounds = video_custom_size_bounds(fam)
if bounds is None:
@@ -1450,6 +1496,7 @@ def validate_video_request_shape(
width: Optional[int] = None,
height: Optional[int] = None,
num_frames: Optional[int] = None,
+ fps: Optional[int] = None,
) -> None:
"""Raise ``ValueError`` when a request asks for a shape ``fam`` does not support.
@@ -1458,8 +1505,10 @@ def validate_video_request_shape(
old silent floor snap let 256x256 through to a size no checkpoint was trained for, so sizes far
from the presets are refused rather than snapped. A family that declares no presets keeps the
old SIZE snapping, and ``None`` means "use the family default". The frame lattice has no escape
- hatch: every family declares a ``frame_step``, so an off-lattice count is always refused.
+ hatch: every family declares a ``frame_step``, so an off-lattice count is always refused. ``fps`` is
+ judged only for a family that declares ``fps_range`` / ``fps_choices``.
"""
+ validate_video_fps(fam, fps)
presets = tuple((int(w), int(h)) for w, h in fam.resolution_presets)
if presets and (width is not None or height is not None):
# A half-specified request resolves against the default preset, as generate() does. Keyed on None, not
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 1291b24dcdd..a03f43b71ed 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -7869,6 +7869,18 @@ class VideoGenerationDefaults(BaseModel):
guidance: float = Field(..., description = "Default guidance scale")
num_frames: int = Field(..., description = "Default frame count")
fps: int = Field(..., description = "Default playback frame rate")
+ fps_range: Optional[list[int]] = Field(
+ None,
+ description = "Inclusive [min, max] frame rate a request may pick, or null (see fps_choices)",
+ )
+ fps_choices: list[int] = Field(
+ default_factory = list,
+ description = "Frame rates a request may pick; with neither this nor fps_range the rate is fixed",
+ )
+ min_num_frames: Optional[int] = Field(None, description = "Smallest frame count the family takes")
+ max_num_frames: Optional[int] = Field(
+ None, description = "Largest frame count the family takes, or null for no family cap"
+ )
frame_step: int = Field(..., description = "Temporal lattice stride")
frame_offset: int = Field(
1, description = "Temporal lattice offset: valid counts are k * frame_step + frame_offset"
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index cecc65d93de..8810ed912d2 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -304,6 +304,8 @@ class VideoGenerationPresetParams(BaseModel):
guidance: float = Field(default = 1, ge = 0, le = 20)
flowShift: Optional[float] = Field(default = None, gt = 0, le = 100)
audioFlowShift: Optional[float] = Field(default = None, gt = 0, le = 100)
+ # None = the family's default rate; only families with a frame-rate picker store one.
+ fps: Optional[int] = Field(default = None, ge = 1, le = 120)
class TrainingPresetParams(BaseModel):
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index d50faa312ee..641963c4fcc 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -740,7 +740,9 @@ async def generate_video(
fam = _detect_load_family(pick.model_path, pick.gguf_filename, None)
if fam is None:
return
- validate_video_request_shape(fam, request.width, request.height, request.num_frames)
+ validate_video_request_shape(
+ fam, request.width, request.height, request.num_frames, fps = request.fps
+ )
h3_task = expected_partition(pick)
validate_video_keyframe_conditioning(
fam,
@@ -1841,6 +1843,8 @@ def _all_videos() -> list[VideoJob]:
def _shape_error_param(exc: Exception, body) -> str:
+ if "frame rate" in str(exc):
+ return "fps"
if "frame count" not in str(exc):
return "size"
return "num_frames" if body.num_frames is not None else "seconds"
@@ -2238,7 +2242,7 @@ def _refuse_family_inputs(
if seconds is not None
else None
)
- validate_video_request_shape(fam, width, height, want_frames)
+ validate_video_request_shape(fam, width, height, want_frames, fps = body.fps)
ref2va = h3_task == H3_TASK_REFERENCES
validate_video_keyframe_conditioning(
fam,
diff --git a/studio/backend/tests/test_media_generation_preset_settings.py b/studio/backend/tests/test_media_generation_preset_settings.py
index 7e2c47299b3..11394d39ac9 100644
--- a/studio/backend/tests/test_media_generation_preset_settings.py
+++ b/studio/backend/tests/test_media_generation_preset_settings.py
@@ -509,6 +509,26 @@ def test_a_store_holding_load_options_is_read_without_them_and_keeps_them(monkey
assert kept["customPresets"][0]["loadConfig"] == {"memoryMode": "low_vram"}
+def test_a_video_preset_keeps_its_frame_rate(monkeypatch):
+ # A Cosmos3 preset saved at 10 fps must render at 10 fps when loaded, not at whatever rate is picked.
+ client = _client(monkeypatch)
+ preset = {"name": "Nano slow", "params": {"durationSeconds": 7.875, "fps": 10}}
+ assert (
+ client.put("/api/settings/generation-presets/video/custom", json = preset).status_code == 200
+ )
+ video = client.get("/api/settings/generation-presets/video").json()
+ assert video["customPresets"][0]["params"]["fps"] == 10
+ assert video["currentParams"]["fps"] is None
+ for fps in (0, 121):
+ assert (
+ client.put(
+ "/api/settings/generation-presets/video/custom",
+ json = {"name": "Bad rate", "params": {"fps": fps}},
+ ).status_code
+ == 422
+ ), fps
+
+
_TRAINING_RECIPE = {
"familyName": "z-image",
"baseChoice": "__custom__",
diff --git a/studio/backend/tests/test_video_cosmos3.py b/studio/backend/tests/test_video_cosmos3.py
index 0e6ecda23cd..0afa9181da4 100644
--- a/studio/backend/tests/test_video_cosmos3.py
+++ b/studio/backend/tests/test_video_cosmos3.py
@@ -1327,3 +1327,164 @@ def test_wide_tiles_keep_the_seam_floor_for_cosmos3():
tiles = _diffusers_tiles(length, tile, stride)
assert G.check_axis(tiles, floor) == [], (family, width, height, plan)
assert planned
+
+
+# NVIDIA's settings: the pipeline's 256 tier, Edge "12-30 fps", Nano 10/16/24/30 fps (NVIDIA/cosmos models.md).
+_256P = [(320, 192), (192, 320), (256, 256), (320, 256), (256, 320)]
+_480P = [(832, 480), (480, 832), (640, 640), (736, 544), (544, 736)]
+
+
+def test_presets_carry_the_pipelines_256p_and_480p_tiers():
+ edge, nano = _fam("cosmos3-edge"), _fam("cosmos3-nano")
+ assert list(edge.resolution_presets) == _480P + _256P
+ assert list(nano.resolution_presets[:5]) == [
+ (1280, 720),
+ (720, 1280),
+ (960, 960),
+ (1104, 832),
+ (832, 1104),
+ ]
+ assert set(nano.resolution_presets[5:]) == set(_480P) | set(_256P)
+ for fam in (edge, nano):
+ assert len(set(fam.resolution_presets)) == len(fam.resolution_presets)
+ for w, h in fam.resolution_presets:
+ assert w % fam.resolution_multiple == 0 and h % fam.resolution_multiple == 0
+ vf.validate_video_request_shape(fam, w, h)
+
+
+def test_preset_tiers_match_the_pipelines_resolution_bins():
+ pytest.importorskip("diffusers", reason = "Backend CI installs no diffusers")
+ from diffusers.pipelines.cosmos.pipeline_cosmos3_omni import _ACTION_RESOLUTION_BINS
+
+ tier = lambda key: {(w, h) for h, w in _ACTION_RESOLUTION_BINS[key].values()} # noqa: E731
+ assert set(_256P) == tier("256") and set(_480P) == tier("480")
+ assert set(_fam("cosmos3-nano").resolution_presets[:5]) == tier("720")
+
+
[email protected]("name", ["cosmos3-edge", "cosmos3-nano"])
[email protected]("size", [(320, 192), (448, 256), (256, 448), (256, 256)])
+def test_256p_and_nvidias_jetson_size_are_accepted(name, size):
+ fam = _fam(name)
+ assert vf.video_custom_size_bounds(fam)[0] == 192 * 320
+ vf.validate_video_request_shape(fam, *size)
+
+
+ "name, size, fragment",
+ [
+ ("cosmos3-edge", (176, 176), "61,440"),
+ ("cosmos3-nano", (240, 160), "61,440"),
+ ("cosmos3-edge", (1280, 720), "409,600 pixels"),
+ ("cosmos3-edge", (448, 250), "multiples of 16"),
+ ],
+)
+def test_sizes_below_256p_or_above_the_top_tier_are_refused(name, size, fragment):
+ with pytest.raises(vf.VideoShapeError, match = fragment):
+ vf.validate_video_request_shape(_fam(name), *size)
+
+
+ "name, requested, snapped",
+ [
+ ("cosmos3-edge", 49, 53),
+ ("cosmos3-edge", 50, 53),
+ ("cosmos3-edge", 150, 149),
+ ("cosmos3-edge", 54, 53),
+ ("cosmos3-nano", 400, 397),
+ ("cosmos3-nano", 4, 5),
+ ],
+)
+def test_frames_snap_inside_nvidias_window(name, requested, snapped):
+ assert vf.snap_num_frames(_fam(name), requested) == snapped
+
+
[email protected]("frames", [49, 153])
+def test_lattice_counts_outside_the_cards_window_are_refused(frames):
+ with pytest.raises(vf.VideoShapeError, match = "run from 53 to 149"):
+ vf.validate_video_request_shape(_fam("cosmos3-edge"), num_frames = frames)
+
+
+def test_fps_options_follow_nvidias_settings():
+ assert vf.video_family_fps_options(_fam("cosmos3-edge")) == tuple(range(12, 31))
+ assert vf.video_family_fps_options(_fam("cosmos3-nano")) == (10, 16, 24, 30)
+ for name in ("cosmos3-edge", "cosmos3-nano"):
+ assert _fam(name).default_fps == 24
+ others = [f for f in vf._FAMILIES if f.name not in ("cosmos3-edge", "cosmos3-nano")]
+ assert others and all(vf.video_family_fps_options(f) is None for f in others)
+
+
+ "name, fps, ok",
+ [
+ ("cosmos3-edge", 12, True),
+ ("cosmos3-edge", 30, True),
+ ("cosmos3-edge", 17, True),
+ ("cosmos3-edge", 11, False),
+ ("cosmos3-edge", 31, False),
+ ("cosmos3-nano", 10, True),
+ ("cosmos3-nano", 16, True),
+ ("cosmos3-nano", 30, True),
+ ("cosmos3-nano", 12, False),
+ ("cosmos3-nano", 60, False),
+ ],
+)
+def test_fps_is_validated_against_the_family(name, fps, ok):
+ fam = _fam(name)
+ if ok:
+ vf.validate_video_request_shape(fam, fps = fps)
+ return
+ expected = "12 to 30" if name == "cosmos3-edge" else "10, 16, 24, 30"
+ with pytest.raises(
+ vf.VideoShapeError, match = f"{fps} fps is not a supported frame rate.*{expected}"
+ ):
+ vf.validate_video_request_shape(fam, fps = fps)
+
+
+ "fam",
+ [f for f in vf._FAMILIES if vf.video_family_fps_options(f) is None],
+ ids = lambda f: f.name,
+)
+def test_a_family_without_fps_options_takes_any_rate(fam):
+ for fps in (None, 1, 7, 24, 60, 120):
+ vf.validate_video_fps(fam, fps)
+
+
[email protected]("seconds, fps, frames", [(5.0, 12, 61), (5.0, 30, 149), (4.0, 24, 97)])
+def test_duration_converts_at_the_chosen_fps(seconds, fps, frames):
+ from routes.video import _frames_for_seconds
+
+ fam = _fam("cosmos3-edge")
+ defaults = {"fps": fps, "frame_step": fam.frame_step, "frame_offset": fam.frame_offset}
+ assert _frames_for_seconds(seconds, defaults) == frames
+ vf.validate_video_request_shape(fam, num_frames = frames, fps = fps)
+
+
[email protected]("repo", [NANO, EDGE])
+def test_status_exposes_the_fps_options_and_frame_window(cosmos3_runtime, repo):
+ from models.inference import VideoGenerationDefaults
+
+ _backend, status = _loaded(repo)
+ got = status["defaults"]
+ rng, choices, window = {
+ EDGE: ([12, 30], [], (53, 149)),
+ NANO: (None, [10, 16, 24, 30], (5, 397)),
+ }[repo]
+ assert (got["fps"], got["fps_range"], got["fps_choices"]) == (24, rng, choices)
+ assert (got["min_num_frames"], got["max_num_frames"]) == window
+ assert [320, 192] in got["resolution_presets"] and got["custom_size_min_pixels"] == 61440
+ VideoGenerationDefaults(**got)
+
+
[email protected]("repo, fps, bad", [(EDGE, 12, 31), (NANO, 30, 12)])
+def test_generate_renders_and_exports_at_the_chosen_fps(cosmos3_runtime, repo, fps, bad):
+ backend, _status = _loaded(repo)
+ result = backend.generate(prompt = "p", steps = 1, fps = fps, width = 320, height = 192)
+ passed = backend._state.pipe.passed
+ assert passed["fps"] == float(fps) and (passed["width"], passed["height"]) == (320, 192)
+ assert result["fps"] == fps and cosmos3_runtime[-1]["fps"] == fps
+ with pytest.raises(vf.VideoShapeError, match = "frame rate"):
+ backend.begin_generate(prompt = "p", steps = 1, fps = bad)
+ with pytest.raises(vf.VideoShapeError, match = "frame rate"):
+ backend.generate(prompt = "p", steps = 1, fps = bad)
+ assert backend.generate_progress()["active"] is False
diff --git a/studio/backend/tests/test_video_shape_validation.py b/studio/backend/tests/test_video_shape_validation.py
index 4cd389a479f..415348949fe 100644
--- a/studio/backend/tests/test_video_shape_validation.py
+++ b/studio/backend/tests/test_video_shape_validation.py
@@ -48,7 +48,10 @@ def test_every_declared_preset_is_accepted(fam):
@pytest.mark.parametrize("fam", _FAMILIES, ids = lambda f: f.name)
def test_256x256_is_rejected_and_the_message_names_the_real_presets(fam):
- """Snap leaves 256x256 alone, but no family lists it, so every family must refuse it."""
+ """Snap leaves 256x256 alone, so a family that does not list it must refuse it (Cosmos3's 256p tier lists it)."""
+ if (256, 256) in fam.resolution_presets:
+ validate_video_request_shape(fam, width = 256, height = 256)
+ return
with pytest.raises(ValueError) as excinfo:
validate_video_request_shape(fam, width = 256, height = 256)
message = str(excinfo.value)
diff --git a/studio/frontend/src/features/generation-presets/types.ts b/studio/frontend/src/features/generation-presets/types.ts
index ca9b50fb74d..fff020736b5 100644
--- a/studio/frontend/src/features/generation-presets/types.ts
+++ b/studio/frontend/src/features/generation-presets/types.ts
@@ -39,6 +39,7 @@ export interface VideoGenerationPresetParams {
guidance: number;
flowShift: number | null;
audioFlowShift: number | null;
+ fps?: number | null;
}
export interface TrainingPresetParams {
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
index 8b6366e624f..b08b12ea8a0 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
@@ -708,7 +708,7 @@ export const VIDEO_CATALOG: CatalogGroup[] = [
{
canonicalId: "nvidia/Cosmos3-Edge",
displayName: "Cosmos3 Edge",
- description: "Text and image to video 480p, small",
+ description: "Text and image to video up to 480p, small",
scope: "video",
artifacts: [bf16Pipeline("nvidia/Cosmos3-Edge", 9, { totalParams: 3858999728 })],
},
diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.ts
index 144b03e316c..8a828b843f7 100644
--- a/studio/frontend/src/features/video/api.ts
+++ b/studio/frontend/src/features/video/api.ts
@@ -28,6 +28,11 @@ export interface VideoGenerationDefaults {
guidance: number;
num_frames: number;
fps: number;
+ fps_range?: [number, number] | null;
+ fps_choices?: number[];
+ // Absent on older backends.
+ min_num_frames?: number | null;
+ max_num_frames?: number | null;
// Valid frame counts are k * frame_step + frame_offset.
frame_step: number;
frame_offset: number;
diff --git a/studio/frontend/src/features/video/video-fps.ts b/studio/frontend/src/features/video/video-fps.ts
new file mode 100644
index 00000000000..321ebea9743
--- /dev/null
+++ b/studio/frontend/src/features/video/video-fps.ts
@@ -0,0 +1,111 @@
+// 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 { VideoGenerationDefaults } from "./api";
+
+const FALLBACK_FPS = 24;
+
+/** Mirrors validate_video_fps; null when the rate is fixed. */
+export function videoFpsOptions(
+ defaults: VideoGenerationDefaults | null | undefined,
+): number[] | null {
+ const choices = defaults?.fps_choices ?? [];
+ if (choices.length > 0) return [...new Set(choices)].sort((a, b) => a - b);
+ const range = defaults?.fps_range;
+ if (range && range.length === 2 && range[0] <= range[1]) {
+ const out: number[] = [];
+ for (let f = range[0]; f <= range[1]; f++) out.push(f);
+ return out;
+ }
+ return null;
+}
+
+export interface FpsPick {
+ family: string | null;
+ fps: number;
+}
+
+export function pickedFpsFor(pick: FpsPick | null, family: string | null): number | null {
+ return pick != null && pick.family === family ? pick.fps : null;
+}
+
+/** A stored preset rate the loaded family offers, else null (the family default). */
+export function presetVideoFps(options: number[] | null, stored: number | null | undefined): number | null {
+ return stored != null && options?.includes(stored) ? stored : null;
+}
+
+export function resolveVideoFps(
+ defaults: VideoGenerationDefaults | null | undefined,
+ picked: number | null,
+): number {
+ const fallback = defaults?.fps ?? FALLBACK_FPS;
+ if (picked == null) return fallback;
+ return videoFpsOptions(defaults)?.includes(picked) ? picked : fallback;
+}
+
+export function videoDurationOptions(
+ targets: number[],
+ fps: number,
+ frameStep: number,
+ frameOffset: number,
+ minFrames?: number | null,
+ maxFrames?: number | null,
+): Array<{ frames: number; seconds: number }> {
+ const seen = new Set<number>();
+ const out: Array<{ frames: number; seconds: number }> = [];
+ for (const t of targets) {
+ const desired = t * fps;
+ const k = Math.max(1, Math.round((desired - frameOffset) / frameStep));
+ let frames = k * frameStep + frameOffset;
+ if (minFrames != null && frames < minFrames) {
+ frames = Math.ceil((minFrames - frameOffset) / frameStep) * frameStep + frameOffset;
+ }
+ if (maxFrames != null && frames > maxFrames) {
+ frames = Math.floor((maxFrames - frameOffset) / frameStep) * frameStep + frameOffset;
+ }
+ if (seen.has(frames)) continue;
+ seen.add(frames);
+ out.push({ frames, seconds: frames / fps });
+ }
+ return out;
+}
+
+/** Nearest option when the clip's count is outside this family's window, so a restore never sets a refused count. */
+export function restoredClipDuration(
+ options: Array<{ frames: number; seconds: number }>,
+ frames: number,
+ fps: number,
+): { frames: number; seconds: number } | null {
+ return options.find((o) => o.frames === frames) ?? nearestDuration(options, frames / fps);
+}
+
+function nearestDuration(
+ options: Array<{ frames: number; seconds: number }>,
+ seconds: number,
+): { frames: number; seconds: number } | null {
+ let best: { frames: number; seconds: number } | null = null;
+ for (const o of options) {
+ if (best == null || Math.abs(o.seconds - seconds) < Math.abs(best.seconds - seconds)) best = o;
+ }
+ return best;
+}
+
+/** After a new family or rate, reseat on the picked length: the same count at another rate is another length. */
+export function keptNumFrames(
+ options: Array<{ frames: number; seconds: number }>,
+ current: number,
+ intentSeconds: number,
+ reseat: boolean,
+): number {
+ if (!reseat && options.some((o) => o.frames === current)) return current;
+ return nearestDuration(options, intentSeconds)?.frames ?? current;
+}
+
+// Status names the outgoing family until a load finishes, so a preset applied mid-load waits for the incoming one.
+export function presetFamilyKnown(defaults: VideoGenerationDefaults | null | undefined, loading: boolean): boolean {
+ return defaults != null && !loading;
+}
+
+export function resolvePresetFps(options: number[] | null, stored: number | null, familyFps: number): number | null {
+ return options ? (presetVideoFps(options, stored) ?? familyFps) : null;
+}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index e90e5e17a35..93130f6eacb 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -145,6 +145,18 @@ import {
videoDimOptions,
videoSizeLimits,
} from "./video-size";
+import {
+ type FpsPick,
+ keptNumFrames,
+ pickedFpsFor,
+ presetFamilyKnown,
+ resolvePresetFps,
+ presetVideoFps,
+ resolveVideoFps,
+ restoredClipDuration,
+ videoDurationOptions,
+ videoFpsOptions,
+} from "./video-fps";
import { usePersistedChoice } from "@/hooks/use-persisted-choice";
import { useScrollFades } from "@/hooks/use-scroll-fades";
import { ModelSelector } from "@/features/model-picker/components/model-selector";
@@ -1277,6 +1289,10 @@ function VideoGenerator({
const [durationIntentSeconds, setDurationIntentSeconds] = useState(
numFrames / FALLBACK_FPS,
);
+ const [fpsPick, setFpsPick] = useState<FpsPick | null>(null);
+ // Rate of a preset or clip applied before the family is known; boxed so a null rate (family default) still waits.
+ const [pendingPresetFps, setPendingPresetFps] = useState<{ fps: number | null } | null>(null);
+ const [loadProbed, setLoadProbed] = useState(false);
const [advancedOpen, setAdvancedOpen] = usePersistedToggle(
"unsloth_video_advanced_open",
);
@@ -1511,24 +1527,27 @@ function VideoGenerator({
const frameStep = status?.defaults?.frame_step ?? FALLBACK_FRAME_STEP;
const frameOffset = status?.defaults?.frame_offset ?? FALLBACK_FRAME_OFFSET;
- const fps = status?.defaults?.fps ?? FALLBACK_FPS;
+ const fpsOptions = useMemo(() => videoFpsOptions(status?.defaults), [status?.defaults]);
+ const loadedFamily = status?.loaded ? status.family : null;
+ // Scoped to its family in render: a reset effect would land after the next family's defaults are seeded.
+ const fps = resolveVideoFps(status?.defaults, pickedFpsFor(fpsPick, loadedFamily));
+ const setPickedFps = useCallback(
+ (picked: number) => {
+ setPendingPresetFps(null);
+ setFpsPick({ family: loadedFamily, fps: picked });
+ },
+ [loadedFamily],
+ );
const durationTargets =
status?.defaults?.duration_presets ?? FALLBACK_DURATION_TARGETS;
+ const minFrames = status?.defaults?.min_num_frames;
+ const maxFrames = status?.defaults?.max_num_frames;
- // Frame counts closest to ~1s/2s/3s/5s at the current fps, deduped.
- const durationOptions = useMemo<Array<{ frames: number; seconds: number }>>(() => {
- const seen = new Set<number>();
- const out: Array<{ frames: number; seconds: number }> = [];
- for (const t of durationTargets) {
- const desired = t * fps;
- const k = Math.max(1, Math.round((desired - frameOffset) / frameStep));
- const frames = k * frameStep + frameOffset;
- if (seen.has(frames)) continue;
- seen.add(frames);
- out.push({ frames, seconds: frames / fps });
- }
- return out;
- }, [frameStep, frameOffset, fps, durationTargets]);
+ const durationOptions = useMemo<Array<{ frames: number; seconds: number }>>(
+ () =>
+ videoDurationOptions(durationTargets, fps, frameStep, frameOffset, minFrames, maxFrames),
+ [frameStep, frameOffset, fps, durationTargets, minFrames, maxFrames],
+ );
const { first: supportsFirstFrame, last: supportsLastFrame } = keyframeSupport(status);
const supportsKeyframes = supportsFirstFrame || supportsLastFrame;
@@ -1605,14 +1624,40 @@ function VideoGenerator({
guidance,
flowShift,
audioFlowShift,
+ fps: pendingPresetFps ? pendingPresetFps.fps : status?.defaults != null && fpsOptions ? fps : null,
};
- }, [audioFlowShift, durationIntentSeconds, flowShift, guidance, matchedResolution, negativePrompt, sourceSized, videoSize, steps]);
+ }, [audioFlowShift, durationIntentSeconds, flowShift, fps, fpsOptions, guidance, pendingPresetFps, status?.defaults, matchedResolution, negativePrompt, sourceSized, videoSize, steps]);
const defaultSteps = status?.defaults?.steps;
const defaultGuidance = status?.defaults?.guidance;
const familyDefaultFrames = status?.defaults?.num_frames;
const defaultFlowShift = status?.defaults?.flow_shift ?? null;
const defaultAudioFlowShift = status?.defaults?.audio_flow_shift ?? null;
const presetRepoId = status?.repo_id ?? "";
+ const familyFps = status?.defaults?.fps ?? FALLBACK_FPS;
+ const statusKnown = presetFamilyKnown(status?.defaults, busy === "loading" || !loadProbed);
+ // Null where the rate is fixed; kept as stored until the family is known.
+ const presetFps = useCallback(
+ (stored: number | null | undefined) =>
+ !statusKnown
+ ? (stored ?? null)
+ : fpsOptions
+ ? (presetVideoFps(fpsOptions, stored) ?? familyFps)
+ : null,
+ [familyFps, fpsOptions, statusKnown],
+ );
+ useEffect(() => {
+ if (!statusKnown || pendingPresetFps == null) return;
+ const rate = resolvePresetFps(fpsOptions, pendingPresetFps.fps, familyFps);
+ setPendingPresetFps(null);
+ if (rate != null) setPickedFps(rate);
+ }, [familyFps, fpsOptions, pendingPresetFps, setPickedFps, statusKnown]);
+ const presetDurationOptions = useCallback(
+ (rate: number | null) =>
+ rate == null || rate === fps
+ ? durationOptions
+ : videoDurationOptions(durationTargets, rate, frameStep, frameOffset, minFrames, maxFrames),
+ [durationOptions, durationTargets, fps, frameOffset, frameStep, maxFrames, minFrames],
+ );
const videoDefaultRecipe = useMemo<VideoGenerationPresetParams>(() => {
const resolution = resolutionPresets[0] ?? [768, 512];
const recommended =
@@ -1620,9 +1665,10 @@ function VideoGenerator({
(defaultSteps != null && defaultGuidance != null
? { steps: defaultSteps, guidance: defaultGuidance }
: defaultsFor(presetRepoId));
+ const defaultOptions = presetDurationOptions(fpsOptions ? familyFps : null);
const defaultDuration = familyDefaultFrames
- ? durationOptions[
- closestDurationIndex(durationOptions, familyDefaultFrames / fps)
+ ? defaultOptions[
+ closestDurationIndex(defaultOptions, familyDefaultFrames / (fpsOptions ? familyFps : fps))
]?.seconds
: status?.loaded
? durationOptions[2]?.seconds ?? durationOptions[0]?.seconds ?? 3
@@ -1636,14 +1682,18 @@ function VideoGenerator({
guidance: recommended.guidance,
flowShift: defaultFlowShift,
audioFlowShift: defaultAudioFlowShift,
+ fps: presetFps(null),
};
- }, [defaultAudioFlowShift, defaultFlowShift, defaultGuidance, defaultSteps, durationOptions, familyDefaultFrames, fps, pendingModelDefaults, presetRepoId, resolutionPresets, status?.loaded]);
+ }, [presetFps, presetDurationOptions, familyFps, fpsOptions, defaultAudioFlowShift, defaultFlowShift, defaultGuidance, defaultSteps, durationOptions, familyDefaultFrames, fps, pendingModelDefaults, presetRepoId, resolutionPresets, status?.loaded]);
const applyVideoPresetParams = useCallback(
(params: VideoGenerationPresetParams) => {
const size = fitVideoSize(params.width, params.height, sizeLimits);
- const durationIndex = closestDurationIndex(durationOptions, params.durationSeconds);
- const durationFrames =
- durationOptions[durationIndex]?.frames ?? durationOptions[0]?.frames ?? numFrames;
+ const rate = presetFps(params.fps);
+ const options = presetDurationOptions(rate);
+ const durationIndex = closestDurationIndex(options, params.durationSeconds);
+ const durationFrames = options[durationIndex]?.frames ?? options[0]?.frames ?? numFrames;
+ if (!statusKnown) setPendingPresetFps({ fps: rate });
+ else if (rate != null) setPickedFps(rate);
setResolutionIntent(size);
const matched = matchAspect(size[0], size[1]);
setAspect(matched.key);
@@ -1658,25 +1708,26 @@ function VideoGenerator({
setGuidance(params.guidance);
setFlowShift(params.flowShift);
setAudioFlowShift(params.audioFlowShift);
- return params;
+ return { ...params, fps: rate };
},
- [durationOptions, numFrames, sizeLimits],
+ [numFrames, presetDurationOptions, presetFps, setPickedFps, sizeLimits, statusKnown],
);
const normalizeVideoPresetParams = useCallback(
(params: VideoGenerationPresetParams) => {
const resolution = fitVideoSize(params.width, params.height, sizeLimits);
+ const rate = presetFps(params.fps);
+ const options = presetDurationOptions(rate);
const duration =
- durationOptions[
- closestDurationIndex(durationOptions, params.durationSeconds)
- ]?.seconds ?? params.durationSeconds;
+ options[closestDurationIndex(options, params.durationSeconds)]?.seconds ?? params.durationSeconds;
return {
...params,
width: resolution[0],
height: resolution[1],
durationSeconds: duration,
+ fps: rate,
};
},
- [durationOptions, sizeLimits],
+ [presetDurationOptions, presetFps, sizeLimits],
);
const videoPresets = useMediaGenerationPresets({
kind: "video",
@@ -1728,11 +1779,13 @@ function VideoGenerator({
setMatchSource(has);
}, [canvasKeyframe, matchedResolution]);
- const loadedFamily = status?.loaded ? status.family : null;
const prevFamilyRef = useRef<string | null>(null);
+ const prevFpsRef = useRef(fps);
useEffect(() => {
const familyChanged = loadedFamily !== prevFamilyRef.current;
prevFamilyRef.current = loadedFamily;
+ const fpsChanged = fps !== prevFpsRef.current;
+ prevFpsRef.current = fps;
// Apply the family's default clip length, or every default run stays a ~1s clip.
const applyFamilyDefault = shouldApplyModelDefaults(
familySeeded.current,
@@ -1751,14 +1804,9 @@ function VideoGenerator({
return;
}
}
- setNumFrames((cur) => {
- if (!familyChanged && durationOptions.some((o) => o.frames === cur)) return cur;
- return (
- durationOptions[
- closestDurationIndex(durationOptions, durationIntentSeconds)
- ]?.frames ?? cur
- );
- });
+ setNumFrames((cur) =>
+ keptNumFrames(durationOptions, cur, durationIntentSeconds, familyChanged || fpsChanged),
+ );
}, [
durationIntentSeconds,
durationOptions,
@@ -2397,14 +2445,30 @@ function VideoGenerator({
setAspect(matched.key);
setPortrait(matched.portrait);
setMatchSource(false);
- // Restore the frame count when it lies on the current lattice.
- if (durationOptions.some((o) => o.frames === video.num_frames)) {
+ // The clip's count only when this family's window takes it.
+ if (!statusKnown) {
+ setPendingPresetFps({ fps: video.fps });
+ setDurationIntentSeconds(video.num_frames / video.fps);
+ setNumFrames(video.num_frames);
+ } else if (fpsOptions?.includes(video.fps)) {
+ const option = restoredClipDuration(
+ videoDurationOptions(durationTargets, video.fps, frameStep, frameOffset, minFrames, maxFrames),
+ video.num_frames,
+ video.fps,
+ );
+ setPickedFps(video.fps);
+ if (option) {
+ setDurationIntentSeconds(option.seconds);
+ setNumFrames(option.frames);
+ }
+ } else if (durationOptions.some((o) => o.frames === video.num_frames)) {
+ // Restore the frame count when it lies on the current lattice.
setDurationIntentSeconds(video.num_frames / fps);
setNumFrames(video.num_frames);
}
toast.success("Settings restored to inputs");
},
- [sizeLimits, durationOptions, fps],
+ [sizeLimits, durationOptions, fps, fpsOptions, durationTargets, frameStep, frameOffset, minFrames, maxFrames, setPickedFps, statusKnown],
);
// No periodic poll corrects a stale read, so only the newest ticket may write.
@@ -2700,6 +2764,7 @@ function VideoGenerator({
} catch {
// Resume is best-effort; a failed probe just leaves the idle view.
}
+ setLoadProbed(true);
// Generation also runs on a daemon thread, so a reload re-enters the poll loop.
try {
const g = await getVideoGenerateProgress();
@@ -4588,13 +4653,43 @@ function VideoGenerator({
</Select>
</Field>
- <div className="flex items-center justify-between">
- <span className="flex items-center gap-1 text-xs font-medium text-muted-foreground">
- Frame rate
- <InfoHint>Playback frame rate, fixed per model.</InfoHint>
- </span>
- <span className="font-mono text-xs font-medium text-foreground">{fps} fps</span>
- </div>
+ {fpsOptions == null ? (
+ <div className="flex items-center justify-between">
+ <span className="flex items-center gap-1 text-xs font-medium text-muted-foreground">
+ Frame rate
+ <InfoHint>Playback frame rate, fixed per model.</InfoHint>
+ </span>
+ <span className="font-mono text-xs font-medium text-foreground">{fps} fps</span>
+ </div>
+ ) : status?.defaults?.fps_choices?.length ? (
+ <Field
+ label="Frame rate"
+ hint="Frames per second the model generates and the clip plays at. Durations above follow it."
+ >
+ <Select value={String(fps)} onValueChange={(v) => setPickedFps(Number(v))}>
+ <SelectTrigger aria-label="Frame rate">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {fpsOptions.map((f) => (
+ <SelectItem key={f} value={String(f)}>
+ {f} fps
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ ) : (
+ <SliderField
+ label="Frame rate"
+ hint={`Frames per second the model generates and the clip plays at (${fpsOptions[0]} to ${fpsOptions[fpsOptions.length - 1]}). Durations above follow it.`}
+ value={fps}
+ min={fpsOptions[0]}
+ max={fpsOptions[fpsOptions.length - 1]}
+ step={1}
+ onChange={(v) => setPickedFps(Math.round(v))}
+ />
+ )}
<SliderField
label="Steps"
@@ -4673,7 +4768,7 @@ function VideoGenerator({
variant="primary"
className="relative z-10 h-11 px-8 text-ui-14 bg-control-accent text-control-accent-foreground hover:bg-control-accent/85 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100"
onClick={handleGenerate}
- disabled={busy !== null || !status?.loaded}
+ disabled={busy !== null || !status?.loaded || !statusKnown || pendingPresetFps != null}
>
Generate
</Button>
diff --git a/studio/frontend/tests/video-fps.test.ts b/studio/frontend/tests/video-fps.test.ts
new file mode 100644
index 00000000000..b8389d938ef
--- /dev/null
+++ b/studio/frontend/tests/video-fps.test.ts
@@ -0,0 +1,216 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Cosmos3 declares the frame rates NVIDIA lists (Edge 12-30, Nano 10/16/24/30); every other family keeps a
+// fixed rate, so its page and requests must not change.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import type { VideoGenerationDefaults } from "../src/features/video/api.ts";
+import {
+ keptNumFrames,
+ pickedFpsFor,
+ presetFamilyKnown,
+ resolvePresetFps,
+ presetVideoFps,
+ resolveVideoFps,
+ restoredClipDuration,
+ videoDurationOptions,
+ videoFpsOptions,
+} from "../src/features/video/video-fps.ts";
+import { isValidVideoSize, videoSizeLimits } from "../src/features/video/video-size.ts";
+
+const P256: Array<[number, number]> = [
+ [320, 192],
+ [192, 320],
+ [256, 256],
+ [320, 256],
+ [256, 320],
+];
+
+function defaults(extra: Partial<VideoGenerationDefaults> = {}): VideoGenerationDefaults {
+ return {
+ steps: 20,
+ guidance: 6,
+ num_frames: 121,
+ fps: 24,
+ frame_step: 4,
+ frame_offset: 1,
+ duration_presets: [3, 5, 6],
+ resolution_multiple: 16,
+ resolution_presets: [[832, 480], [480, 832], [640, 640], [736, 544], [544, 736], ...P256],
+ ...extra,
+ };
+}
+
+// What the Video page computed before the picker; a family without a window must still get exactly this.
+function previousDurationOptions(targets: number[], fps: number, step: number, offset: number) {
+ const seen = new Set<number>();
+ const out: Array<{ frames: number; seconds: number }> = [];
+ for (const t of targets) {
+ const k = Math.max(1, Math.round((t * fps - offset) / step));
+ const frames = k * step + offset;
+ if (seen.has(frames)) continue;
+ seen.add(frames);
+ out.push({ frames, seconds: frames / fps });
+ }
+ return out;
+}
+
+test("a family with no fps options keeps its fixed rate whatever was picked", () => {
+ const fixed = defaults({ fps: 25, fps_range: null, fps_choices: [] });
+ assert.equal(videoFpsOptions(fixed), null);
+ assert.equal(resolveVideoFps(fixed, null), 25);
+ assert.equal(resolveVideoFps(fixed, 12), 25);
+ // An older backend sends neither field.
+ assert.equal(videoFpsOptions(defaults()), null);
+ assert.equal(resolveVideoFps(null, 30), 24);
+});
+
+test("Edge offers every rate from 12 to 30 and Nano NVIDIA's four", () => {
+ const edge = defaults({ fps_range: [12, 30], fps_choices: [] });
+ assert.deepEqual(videoFpsOptions(edge), Array.from({ length: 19 }, (_, i) => 12 + i));
+ assert.equal(resolveVideoFps(edge, null), 24);
+ assert.equal(resolveVideoFps(edge, 12), 12);
+ assert.equal(resolveVideoFps(edge, 30), 30);
+ assert.equal(resolveVideoFps(edge, 31), 24);
+ const nano = defaults({ fps_range: null, fps_choices: [30, 10, 24, 16] });
+ assert.deepEqual(videoFpsOptions(nano), [10, 16, 24, 30]);
+ assert.equal(resolveVideoFps(nano, 16), 16);
+ assert.equal(resolveVideoFps(nano, 12), 24);
+});
+
+test("durations without a frame window are what the page computed before", () => {
+ for (const [targets, fps, step, offset] of [
+ [[1, 2, 3, 5], 24, 8, 1],
+ [[1, 2, 3, 5], 25, 8, 1],
+ [[5, 10, 15], 25, 17, 5],
+ [[2, 5, 7.875], 24, 4, 1],
+ ] as Array<[number[], number, number, number]>) {
+ assert.deepEqual(
+ videoDurationOptions(targets, fps, step, offset),
+ previousDurationOptions(targets, fps, step, offset),
+ );
+ // A window the presets already sit inside changes nothing either.
+ assert.deepEqual(
+ videoDurationOptions(targets, fps, step, offset, offset, 2000),
+ previousDurationOptions(targets, fps, step, offset),
+ );
+ }
+});
+
+test("Edge durations follow the picked rate and stay inside 53-149 frames", () => {
+ const at = (fps: number) => videoDurationOptions([3, 5, 6], fps, 4, 1, 53, 149);
+ assert.deepEqual(
+ at(24).map((o) => o.frames),
+ [73, 121, 145],
+ );
+ assert.deepEqual(
+ at(12).map((o) => o.frames),
+ [53, 61, 73],
+ );
+ assert.deepEqual(
+ at(30).map((o) => o.frames),
+ [89, 149],
+ );
+ for (const fps of [12, 30]) {
+ for (const { frames, seconds } of at(fps)) {
+ assert.equal((frames - 1) % 4, 0);
+ assert.equal(seconds, frames / fps);
+ }
+ }
+});
+
+test("the 256p presets and NVIDIA's 448x256 Jetson size pass the size check", () => {
+ const edge = defaults({
+ custom_size_min_pixels: 192 * 320,
+ custom_size_max_pixels: 640 * 640,
+ custom_size_max_aspect: 4,
+ });
+ const limits = videoSizeLimits(edge, edge.resolution_presets);
+ for (const [w, h] of [...P256, [448, 256], [256, 448]] as Array<[number, number]>) {
+ assert.ok(isValidVideoSize(w, h, limits), `${w}x${h}`);
+ }
+ assert.ok(!isValidVideoSize(176, 176, limits));
+});
+
+test("a restored clip takes its frame count only when the loaded family's window offers it", () => {
+ const edgeAt24 = videoDurationOptions([3, 5, 6], 24, 4, 1, 53, 149);
+ // An Edge clip restores as it was.
+ assert.deepEqual(restoredClipDuration(edgeAt24, 121, 24), { frames: 121, seconds: 121 / 24 });
+ // A 189-frame Nano clip at 24 fps maps to Edge's nearest option, never 189.
+ assert.deepEqual(restoredClipDuration(edgeAt24, 189, 24), { frames: 145, seconds: 145 / 24 });
+ const edgeAt12 = videoDurationOptions([3, 5, 6], 12, 4, 1, 53, 149);
+ assert.deepEqual(restoredClipDuration(edgeAt12, 25, 12), { frames: 53, seconds: 53 / 12 });
+ assert.equal(restoredClipDuration([], 121, 24), null);
+});
+
+test("a new frame rate keeps the picked length, not a frame count that is another length at that rate", () => {
+ // Nano at 24 fps, 2 s picked (49 frames). 49 is also an option at 10 fps, where it lasts 4.9 s.
+ const nanoAt10 = videoDurationOptions([2, 5, 7.875], 10, 4, 1, 5, 397);
+ assert.ok(nanoAt10.some((o) => o.frames === 49));
+ assert.equal(keptNumFrames(nanoAt10, 49, 49 / 24, true), 21);
+ // Edge at 24 fps, 3 s (73 frames); at 12 fps 73 is 6.1 s, so the nearest to 3 s (53, 4.4 s) wins.
+ const edgeAt12 = videoDurationOptions([3, 5, 6], 12, 4, 1, 53, 149);
+ assert.equal(keptNumFrames(edgeAt12, 73, 73 / 24, true), 53);
+ // Same rate: a count still on offer stays, one that is not snaps to the picked length.
+ const edgeAt24 = videoDurationOptions([3, 5, 6], 24, 4, 1, 53, 149);
+ assert.equal(keptNumFrames(edgeAt24, 145, 145 / 24, false), 145);
+ assert.equal(keptNumFrames(edgeAt24, 61, 5, false), 121);
+ assert.equal(keptNumFrames([], 61, 5, true), 61);
+});
+
+test("a picked rate applies only to the family it was picked on", () => {
+ const pick = { family: "cosmos3-edge", fps: 30 };
+ assert.equal(pickedFpsFor(pick, "cosmos3-edge"), 30);
+ // Edge at 30 fps to Nano: Nano's defaults are seeded at its own 24 fps, not at Edge's pick.
+ assert.equal(pickedFpsFor(pick, "cosmos3-nano"), null);
+ const edge = defaults({ fps_range: [12, 30] });
+ assert.equal(resolveVideoFps(edge, pickedFpsFor({ family: "cosmos3-nano", fps: 16 }, "cosmos3-edge")), 24);
+ assert.equal(pickedFpsFor(null, "cosmos3-edge"), null);
+});
+
+test("a preset's stored rate is restored only when the loaded family offers it", () => {
+ const nano = videoFpsOptions(defaults({ fps_choices: [10, 16, 24, 30] }));
+ assert.equal(presetVideoFps(nano, 10), 10);
+ // A preset saved before rates were stored, or on another family, falls back to the family default.
+ assert.equal(presetVideoFps(nano, null), null);
+ assert.equal(presetVideoFps(nano, 12), null);
+ assert.equal(presetVideoFps(null, 30), null);
+ // Nano's 7.875 s target: 77 frames at 10 fps, not the 237 a stale 30 fps pick would render.
+ const at10 = videoDurationOptions([7.875], 10, 4, 1, 5, 397);
+ assert.deepEqual(at10.map((o) => o.frames), [77]);
+});
+
+test("a preset applied while Nano loads over Edge keeps its rate for Nano", () => {
+ const edge = defaults({ fps_range: [12, 30] });
+ const nano = defaults({ fps_choices: [10, 16, 24, 30] });
+ // Mid-load, status still describes Edge: the stored 30 fps stays pending instead of binding to Edge.
+ assert.equal(presetFamilyKnown(edge, true), false);
+ assert.equal(presetFamilyKnown(nano, false), true);
+ const rate = presetVideoFps(videoFpsOptions(nano), 30);
+ assert.equal(rate, 30);
+ assert.equal(resolveVideoFps(nano, pickedFpsFor({ family: "cosmos3-nano", fps: rate! }, "cosmos3-nano")), 30);
+ assert.equal(presetFamilyKnown(null, false), false);
+});
+
+test("a pending preset without a rate resets to the family default, as it does when applied idle", () => {
+ const edge = videoFpsOptions(defaults({ fps_range: [12, 30] }));
+ // Default picked during an Edge Reapply with 30 fps picked: 24, not the old 30.
+ assert.equal(resolvePresetFps(edge, null, 24), 24);
+ assert.equal(resolvePresetFps(edge, 30, 24), 30);
+ assert.equal(resolvePresetFps(edge, 31, 24), 24);
+ assert.equal(resolvePresetFps(null, 30, 24), null);
+});
+
+test("a rate picked or restored mid-load goes through the pending preset rate", () => {
+ const page = readFileSync(new URL("../src/features/video/video-page.tsx", import.meta.url), "utf8");
+ assert.match(page, /setPickedFps = useCallback\(\s*\(picked: number\) => \{\s*setPendingPresetFps\(null\);/);
+ assert.match(page, /if \(!statusKnown\) \{\s*setPendingPresetFps\(\{ fps: video\.fps \}\);/);
+ assert.match(page, /setPendingPresetFps\(\{ fps: video\.fps \}\);[^}]*setNumFrames\(video\.num_frames\);/);
+ assert.match(page, /disabled=\{busy !== null \|\| !status\?\.loaded \|\| !statusKnown \|\| pendingPresetFps != null\}/);
+ const edge = videoDurationOptions([1, 2, 3, 5], 24, 4, 1, 5, 149);
+ assert.equal(keptNumFrames(edge, 121, 121 / 24, false), 121);
+});