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: accept chat videos up to 256 MB (#17400)

Daniel Han7499966a8e7b
diff --git a/studio/backend/core/inference/llama_video_input.py b/studio/backend/core/inference/llama_video_input.py
index d18d371dd81..5818b618409 100644
--- a/studio/backend/core/inference/llama_video_input.py
+++ b/studio/backend/core/inference/llama_video_input.py
@@ -234,12 +234,15 @@ def shrink_video_for_llama(
return video_b64
oversized = area > max_pixels
too_short = duration is not None and 0 < duration < MIN_SAMPLED_SECONDS
- if not oversized and not too_short:
- return video_b64
- # Keeping the decoded copy alive just to log its length costs 64 MiB.
raw_bytes = len(raw)
+ if not oversized and not too_short and raw_bytes <= max_bytes:
+ return video_b64
+ # Keeping the decoded copy alive just to log its length costs up to the upload cap.
del raw
shrunk = Path(tmp) / "shrunk.mkv"
+ # A size-only re-encode has no filter, and ffmpeg refuses an empty -vf.
+ chain = _filter_chain(max_pixels, rate, duration, oversized, sampled_fps)
+ filters = ["-vf", chain] if chain else []
result = _run(
[
ffmpeg,
@@ -256,8 +259,7 @@ def shrink_video_for_llama(
"-an",
"-sn",
"-dn",
- "-vf",
- _filter_chain(max_pixels, rate, duration, oversized, sampled_fps),
+ *filters,
"-c:v",
"mpeg4",
# mpeg4 is widely supported but can outgrow low-bitrate sources; -fs caps output at the upload limit.
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 8017c485da4..c44cc87b89f 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -26891,8 +26891,15 @@ def _decode_audio_base64(b64: str) -> "np.ndarray":
# base64 inflates ~4/3; _MAX_AUDIO_SECONDS bounds decoded length of compressed files.
_MAX_AUDIO_RAW_BYTES = STT_AUDIO_RAW_MAX_BYTES
_MAX_AUDIO_B64_CHARS = STT_AUDIO_B64_MAX_CHARS
-# Padded base64 of the composer's 64 MB, rounded up (flooring refused exact-size files).
-_MAX_VIDEO_BYTES = 64 * 1024 * 1024
+# Padded base64 of the composer's 256 MB, rounded up (flooring refused exact-size files).
+_MAX_VIDEO_BYTES = 256 * 1024 * 1024
+# llama-server's HTTP layer refuses bodies over 100 MB, so a clip larger than this is transcoded first.
+_LLAMA_VIDEO_FORWARD_BYTES = 64 * 1024 * 1024
+_LLAMA_VIDEO_FORWARD_B64_CHARS = 4 * math.ceil(_LLAMA_VIDEO_FORWARD_BYTES / 3)
+_VIDEO_OVER_FORWARD_BUDGET = (
+ "Video is too large to send to the model even after compressing it. "
+ "Trim it to a shorter clip and try again."
+)
_MAX_VIDEO_B64_CHARS = 4 * math.ceil(_MAX_VIDEO_BYTES / 3)
# Longest scheme named back to the caller; bounds the scan over a megabytes-long clip.
_MAX_VIDEO_SCHEME_CHARS = 16
@@ -27661,7 +27668,7 @@ def _video_size_rejection(clip: str) -> Optional[tuple[int, str]]:
if not payload_len:
return (400, "Could not read the provided video file.")
if payload_len > _MAX_VIDEO_B64_CHARS:
- return (413, "Video file is too large (max 64 MB).")
+ return (413, "Video file is too large (max 256 MB).")
return None
@@ -27672,7 +27679,7 @@ def _video_b64_rejection(video_b64: str) -> tuple[str, Optional[tuple[int, str]]
if not video_b64:
return "", (400, "Could not read the provided video file.")
if len(video_b64) > _MAX_VIDEO_B64_CHARS:
- return video_b64, (413, "Video file is too large (max 64 MB).")
+ return video_b64, (413, "Video file is too large (max 256 MB).")
return video_b64, None
@@ -27882,7 +27889,7 @@ def _request_video_rejection(payload) -> Optional[tuple[int, str]]:
total += _video_payload_chars(clip)
# And bytes bound the per-clip transcode cost the count cannot see.
if total > _MAX_VIDEO_B64_CHARS:
- return (413, "Videos are too large (max 64 MB per request).")
+ return (413, "Videos are too large (max 256 MB per request).")
return None
@@ -27895,10 +27902,10 @@ async def _shrink_clip_for_llama(video_b64: str, llama_backend) -> str:
else None
)
try:
- return await asyncio.to_thread(
+ shrunk = await asyncio.to_thread(
shrink_video_for_llama,
video_b64,
- _MAX_VIDEO_BYTES,
+ _LLAMA_VIDEO_FORWARD_BYTES,
sampled_fps = requested_video_fps(getattr(llama_backend, "extra_args", None)),
ffmpeg_dir = getattr(llama_backend, "_video_ffmpeg_dir", None),
env = child_env,
@@ -27909,6 +27916,20 @@ async def _shrink_clip_for_llama(video_b64: str, llama_backend) -> str:
raise HTTPException(
status_code = 400, detail = "Could not process the provided video file."
) from None
+ return shrunk
+
+
+def _forwarded_video_chars(messages: list[dict]) -> int:
+ total = 0
+ for msg in messages:
+ content = msg.get("content")
+ if not isinstance(content, list):
+ continue
+ for part in content:
+ if isinstance(part, dict) and part.get("type") == "input_video":
+ data = (part.get("input_video") or {}).get("data")
+ total += len(data) if isinstance(data, str) else 0
+ return total
async def _shrink_video_parts(messages: list[dict], llama_backend) -> None:
@@ -32481,7 +32502,10 @@ async def produce_openai_chat_completions(
raise _reject(*video_rejection)
if payload.video_base64:
video_b64, _ = _video_b64_rejection(payload.video_base64)
- video_b64 = await _shrink_clip_for_llama(video_b64, llama_backend)
+ try:
+ video_b64 = await _shrink_clip_for_llama(video_b64, llama_backend)
+ except HTTPException as e:
+ raise _reject(e.status_code, e.detail) from None
# The loop's image cap counts the whole conversation, so seed it with replayed parts.
_gguf_replayed_image_parts: list = []
@@ -32497,8 +32521,14 @@ async def produce_openai_chat_completions(
_inject_audio_part(gguf_messages, audio_b64, audio_format)
if video_b64:
_inject_video_part(gguf_messages, video_b64)
- await _shrink_video_parts(gguf_messages, llama_backend)
+ try:
+ await _shrink_video_parts(gguf_messages, llama_backend)
+ except HTTPException as e:
+ raise _reject(e.status_code, e.detail) from None
_translate_video_parts(gguf_messages)
+ # A failed transcode hands back the original, so this also catches one clip still over budget.
+ if _forwarded_video_chars(gguf_messages) > _LLAMA_VIDEO_FORWARD_B64_CHARS:
+ raise _reject(413, _VIDEO_OVER_FORWARD_BUDGET)
cancel_event = _chat_cancel_event(request)
diff --git a/studio/backend/tests/test_llama_video_frame_budget.py b/studio/backend/tests/test_llama_video_frame_budget.py
index 45c582d2e12..ba5ce7ca705 100644
--- a/studio/backend/tests/test_llama_video_frame_budget.py
+++ b/studio/backend/tests/test_llama_video_frame_budget.py
@@ -328,6 +328,40 @@ def test_a_clip_already_within_the_budget_is_forwarded_untouched(tmp_path):
assert shrink_video_for_llama(clip, _CAP) is clip
+@needs_ffmpeg
+def test_a_small_frame_clip_over_the_forward_budget_is_transcoded(tmp_path):
+ clip = _clip(tmp_path, "heavy.mp4", "640x360", rate = 30, seconds = 2)
+ raw_bytes = len(base64.b64decode(clip))
+
+ shrunk = shrink_video_for_llama(clip, raw_bytes - 1)
+
+ assert shrunk is not clip
+ assert len(base64.b64decode(shrunk)) < raw_bytes
+ info = _probe(tmp_path, shrunk)
+ assert (info["width"], info["height"]) == (640, 360)
+
+
+@needs_ffmpeg
+def test_a_low_rate_small_frame_clip_over_the_budget_is_transcoded_without_filters(tmp_path):
+ # Lossless, so the mpeg4 re-encode has room to come in under the source size.
+ path = tmp_path / "slow.mkv"
+ subprocess.run(
+ [
+ *("ffmpeg", "-nostdin", "-loglevel", "error", "-y"),
+ *("-f", "lavfi", "-i", "testsrc2=size=640x360:rate=2", "-t", "3"),
+ *("-c:v", "libx264", "-qp", "0", "-pix_fmt", "yuv420p", str(path)),
+ ],
+ check = True,
+ )
+ clip = base64.b64encode(path.read_bytes()).decode("ascii")
+ raw_bytes = len(base64.b64decode(clip))
+
+ shrunk = shrink_video_for_llama(clip, raw_bytes - 1)
+
+ assert shrunk is not clip
+ assert len(base64.b64decode(shrunk)) < raw_bytes
+
+
@needs_ffmpeg
def test_a_shrunk_clip_that_outgrows_the_cap_is_forwarded_untouched(tmp_path):
clip = _clip(tmp_path, "wide.mp4", "1280x720")
diff --git a/studio/backend/tests/test_video_attachment_part.py b/studio/backend/tests/test_video_attachment_part.py
index 3d82007027c..72580cd4881 100644
--- a/studio/backend/tests/test_video_attachment_part.py
+++ b/studio/backend/tests/test_video_attachment_part.py
@@ -98,7 +98,7 @@ def test_the_cap_admits_a_clip_of_exactly_the_composer_limit():
from routes.inference import _MAX_VIDEO_B64_CHARS
- limit_bytes = 64 * 1024 * 1024
+ limit_bytes = 256 * 1024 * 1024
# Padded base64 is 4 characters per 3 bytes, rounded up.
assert len(base64.b64encode(b"x" * 3001)) == 4 * math.ceil(3001 / 3)
assert 4 * math.ceil(limit_bytes / 3) <= _MAX_VIDEO_B64_CHARS
@@ -322,7 +322,7 @@ def test_every_data_uri_part_is_sized_not_only_the_first():
assert _request_video_rejection(fits) is None
oversized = "data:video/mp4;base64," + "A" * (_MAX_VIDEO_B64_CHARS + 1)
too_big = _video_url_request("data:video/mp4;base64,QUJD", oversized)
- assert _request_video_rejection(too_big) == (413, "Video file is too large (max 64 MB).")
+ assert _request_video_rejection(too_big) == (413, "Video file is too large (max 256 MB).")
assert _request_video_rejection(_video_url_request("")) == (
400,
"Could not read the provided video file.",
@@ -334,7 +334,7 @@ def test_the_legacy_field_is_sized_beside_a_message_part():
req = _video_url_request(
"https://example.com/clip.mp4", video_base64 = "A" * (_MAX_VIDEO_B64_CHARS + 1)
)
- assert _request_video_rejection(req) == (413, "Video file is too large (max 64 MB).")
+ assert _request_video_rejection(req) == (413, "Video file is too large (max 256 MB).")
def test_admission_prices_a_message_clip_as_media_not_prompt_text():
diff --git a/studio/backend/tests/test_video_chat_completions_behaviour.py b/studio/backend/tests/test_video_chat_completions_behaviour.py
index 3d2e774f2b1..1d3d93962c3 100644
--- a/studio/backend/tests/test_video_chat_completions_behaviour.py
+++ b/studio/backend/tests/test_video_chat_completions_behaviour.py
@@ -965,3 +965,39 @@ def test_the_clip_count_includes_the_legacy_field():
body["video_base64"] = tiny
rejection = inference_route._request_video_rejection(ChatCompletionRequest.model_validate(body))
assert rejection is not None and rejection[0] == 400
+
+
+def test_a_clip_still_over_the_forward_budget_after_transcoding_is_refused(monkeypatch):
+ """shrink_video_for_llama returns the original on failure; past 100 MB llama-server 413s it blind."""
+ limit = inference_route._LLAMA_VIDEO_FORWARD_B64_CHARS
+ returned = {}
+ monkeypatch.setattr(
+ inference_route, "shrink_video_for_llama", lambda clip, cap, **_: returned["clip"]
+ )
+ failed = []
+ monkeypatch.setattr(
+ inference_route.api_monitor, "fail", lambda mid, detail: failed.append(detail)
+ )
+
+ returned["clip"] = "A" * limit
+ with _client(monkeypatch, _VideoGguf()) as client:
+ assert client.post("/v1/chat/completions", json = _part_body(_DATA_URI)).status_code == 200
+
+ returned["clip"] = "A" * (limit + 1)
+ with _client(monkeypatch, _VideoGguf()) as client:
+ response = client.post("/v1/chat/completions", json = _part_body(_DATA_URI))
+ assert response.status_code == 413
+ assert "Trim it" in response.json()["detail"]
+ assert any("Trim it" in d for d in failed), "the monitor entry must be finalized"
+
+
+def test_the_forward_budget_covers_every_clip_in_the_request_together(monkeypatch):
+ half = "A" * (inference_route._LLAMA_VIDEO_FORWARD_B64_CHARS // 2 + 4)
+ monkeypatch.setattr(inference_route, "shrink_video_for_llama", lambda clip, cap, **_: half)
+
+ with _client(monkeypatch, _VideoGguf()) as client:
+ assert client.post("/v1/chat/completions", json = _part_body(_DATA_URI)).status_code == 200
+ with _client(monkeypatch, _VideoGguf()) as client:
+ response = client.post("/v1/chat/completions", json = _part_body(_DATA_URI, _DATA_URI))
+ assert response.status_code == 413
+ assert "Trim it" in response.json()["detail"]
diff --git a/studio/backend/tests/test_video_pr9057_simulation.py b/studio/backend/tests/test_video_pr9057_simulation.py
index 70eb99eca50..5094ff87c9a 100644
--- a/studio/backend/tests/test_video_pr9057_simulation.py
+++ b/studio/backend/tests/test_video_pr9057_simulation.py
@@ -24,7 +24,7 @@ from routes.inference import ( # noqa: E402
_video_b64_rejection,
)
-LIMIT = 64 * 1024 * 1024
+LIMIT = 256 * 1024 * 1024
def _props_backend(props):
@@ -40,23 +40,23 @@ def test_the_ceiling_formula_matches_what_base64_actually_produces(n):
def test_a_clip_of_exactly_the_composer_limit_is_admitted():
- # 67108864 = 3*22369621 + 1, so the last byte costs a full padded quad.
- assert _MAX_VIDEO_B64_CHARS == 89478488
- assert 4 * math.ceil(LIMIT / 3) == 89478488
- exact = "A" * 89478488
+ # 268435456 = 3*89478485 + 1, so the last byte costs a full padded quad.
+ assert _MAX_VIDEO_B64_CHARS == 357913944
+ assert 4 * math.ceil(LIMIT / 3) == 357913944
+ exact = "A" * 357913944
assert _video_b64_rejection(exact)[1] is None
def test_the_old_floor_expression_would_have_refused_it():
floored = (LIMIT * 4) // 3
- assert floored == 89478485
+ assert floored == 357913941
assert floored < 4 * math.ceil(LIMIT / 3)
def test_one_character_over_the_ceiling_is_refused_413():
assert _video_b64_rejection("A" * (_MAX_VIDEO_B64_CHARS + 1))[1] == (
413,
- "Video file is too large (max 64 MB).",
+ "Video file is too large (max 256 MB).",
)
diff --git a/studio/frontend/src/lib/video-utils.ts b/studio/frontend/src/lib/video-utils.ts
index 7c071b4ec2f..e8ad3ba1cca 100644
--- a/studio/frontend/src/lib/video-utils.ts
+++ b/studio/frontend/src/lib/video-utils.ts
@@ -6,7 +6,8 @@ export const VIDEO_ACCEPT =
"video/mp4,video/x-m4v,video/quicktime,video/webm,video/x-matroska,video/x-msvideo,video/mpeg,video/x-ms-wmv,video/x-flv,video/3gpp,video/3gpp2,video/ogg,video/mp2t,.mp4,.m4v,.mov,.webm,.mkv,.avi,.mpg,.mpeg,.wmv,.flv,.3gp,.3g2,.ogv,.m2ts";
// Matches _MAX_VIDEO_B64_CHARS in the backend so the composer does not accept a refused clip.
-const MAX_VIDEO_SIZE_MB = 64;
+// Its base64 (~341M chars) stays under V8's 2^29 - 24 string length limit.
+const MAX_VIDEO_SIZE_MB = 256;
export const MAX_VIDEO_SIZE = MAX_VIDEO_SIZE_MB * 1024 * 1024;
export const MAX_VIDEO_SIZE_LABEL = `${MAX_VIDEO_SIZE_MB}MB`;
diff --git a/studio/frontend/tests/pr9057-video-simulation.test.ts b/studio/frontend/tests/pr9057-video-simulation.test.ts
index 7a08e532b6f..0cb643f9744 100644
--- a/studio/frontend/tests/pr9057-video-simulation.test.ts
+++ b/studio/frontend/tests/pr9057-video-simulation.test.ts
@@ -201,9 +201,9 @@ test("the composer's accept attribute is the union, so the picker offers video",
}
});
-test("the composer cap is exactly 64 MiB", () => {
- assert.equal(MAX_VIDEO_SIZE, 64 * 1024 * 1024);
- assert.equal(MAX_VIDEO_SIZE, 67108864);
+test("the composer cap is exactly 256 MiB", () => {
+ assert.equal(MAX_VIDEO_SIZE, 256 * 1024 * 1024);
+ assert.equal(MAX_VIDEO_SIZE, 268435456);
});
test("a clip of exactly the cap is accepted, one byte over is refused", () => {
@@ -216,7 +216,7 @@ test("a clip of exactly the cap is accepted, one byte over is refused", () => {
test("the backend ceiling admits every clip this composer admits", () => {
// _MAX_VIDEO_B64_CHARS in routes/inference.py, padded base64 of the same cap.
const backendCeiling = 4 * Math.ceil(MAX_VIDEO_SIZE / 3);
- assert.equal(backendCeiling, 89478488);
+ assert.equal(backendCeiling, 357913944);
const encodedAtCap = 4 * Math.ceil(MAX_VIDEO_SIZE / 3);
assert.ok(encodedAtCap <= backendCeiling, "the largest allowed clip must not 413");
assert.ok(Math.floor((MAX_VIDEO_SIZE * 4) / 3) < encodedAtCap);
@@ -307,7 +307,7 @@ test("the recount declines a video turn, as it already declines image and audio"
});
test("the video bail is paid before the branch signature hashes the base64", () => {
- // branchSignature stringifies every part on the UI thread; a 64 MB clip is ~85 MB of base64.
+ // branchSignature stringifies every part on the UI thread; a 256 MB clip is ~341 MB of base64.
const bail = recountSource.indexOf("findLatestUserVideoBase64(runMessages)");
const hash = recountSource.indexOf("countedBranch = branchSignature(");
assert.ok(bail >= 0 && hash >= 0);