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.

120 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""API routes for local text-to-video inference.

The video backend is a deliberate sibling of the diffusion (image) backend, so these routes mirror the
/images/* routes one-for-one: the same validate-before-evict load ordering, the same GPU arbiter handoff (VIDEO
owner in place of DIFFUSION), the same error boundary mapping backend exceptions to HTTP, and the same gallery
CRUD shape. The backend runs in-process and is synchronous, so the blocking calls are offloaded with
asyncio.to_thread to keep the event loop free; the slow operations (load AND generate) run as background jobs
whose begin_* calls return at once, with progress + terminal outcome polled from their *-progress routes. This
module is the single error boundary: backend methods raise, we map to HTTP here.
"""

from __future__ import annotations

import asyncio
import base64
import hashlib as _hashlib
import inspect
import json
import hmac as _hmac
import re as _re
import secrets as _secrets
import threading
import time as _time
import uuid
import weakref
from dataclasses import asdict, dataclass
from dataclasses import field as _dc_field
from datetime import datetime, timezone
from typing import Annotated, Any, Literal, Optional

from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
from starlette.datastructures import UploadFile

from auth.authentication import (
    authenticated_via_api_key,
    get_current_subject,
    request_admitted_without_credential,
)
from core.inference.model_ids import public_model_id
from hub.dependencies import get_hf_token
from hub.services.models import account_access
from hub.services.models.account_access import media_link_account, media_link_target
from utils.account_context import AccountContext, arun_as, current_account, run_as
from loggers import get_logger
from loggers.media_progress import (
    byte_fraction,
    log_media_generation_progress,
    log_media_load_progress,
    reset_media_generation_progress,
    reset_media_load_progress,
)
from models.inference import (
    AudioInputRecord,
    DiffusionDownloadPlanResponse,
    GalleryFlagsPatch,
    GalleryMoveRequest,
    GalleryProjectRequest,
    GalleryProjectResponse,
    GalleryVideo,
    MediaUnloadOutcome,
    MediaUnloadRequest,
    VideoGalleryListResponse,
    VideoGenerateProgressResponse,
    VideoGenerateRequest,
    VideoGenerateResponse,
    VideoJob,
    VideoJobCreateRequest,
    VideoJobDeleteResponse,
    VideoJobError,
    VideoJobListResponse,
    VideoLoadProgressResponse,
    VideoLoadRequest,
    VideoLoadUnloadedResponse,
    VideoStatusResponse,
    VideoUnloadResponse,
)
from utils.account_context import current_account_id, is_owner_context
from utils.api_errors import openai_error_body, problem_headers
from utils.upload_limits import VIDEO_INPUT_REFERENCE_MAX_BYTES

logger = get_logger(__name__)

router = APIRouter()
openai_router = APIRouter()


def _selected_gpu_ordinal(gpu_ids, *, allow_ranking: bool = True):
    """The images route's resolver, shared so both media routes apply one rule."""
    from routes.inference import _selected_gpu_ordinal as _resolve
    return _resolve(gpu_ids, allow_ranking = allow_ranking)


def _training_is_active() -> bool:
    """The non-raising half of the load guard, for callers that must not take the GPU."""
    from routes.inference import _training_is_active as _images_training_is_active
    return _images_training_is_active()


def _video_backend():
    from core.inference.video import get_video_backend
    return get_video_backend()


def _derived_h3_task(gguf_filename: Optional[str], kind: str) -> Optional[str]:
    """The MiniMax-H3 partition a GGUF load resolves to from its filename, else None."""
    if kind != "gguf" or not gguf_filename:
        return None
    try:
        from core.inference.video_minimax_h3 import h3_transformer_task
        from pathlib import Path as _Path

        name = _Path(gguf_filename).name.lower()
        return h3_transformer_task(name) if name.startswith("minimax_h3_") else None
    except Exception:  # noqa: BLE001 -- a probe failure must not fail the load
        return None


def _guard_video_load_against_training() -> None:
    """Video VRAM cannot be estimated up front: an active training run refuses the load with 409."""
    from core.training import get_training_backend

    try:
        llm_active = get_training_backend().is_training_active()
    except Exception as e:  # noqa: BLE001
        # Independent probes: an unreadable LLM backend must not disable the diffusion interlock below.
        logger.warning("Could not check training state for video-load guard: %s", e)
        llm_active = False
    diffusion_active = False
    try:
        from core.training.diffusion_training_service import get_diffusion_training_service
        diffusion_active = get_diffusion_training_service().is_active()
    except Exception:  # noqa: BLE001
        diffusion_active = False
    # An SDXL LoRA trainer runs in its own subprocess on the same GPU, so refuse a video load while one is active.
    if not llm_active and not diffusion_active:
        return
    raise HTTPException(
        status_code = 409,
        detail = (
            "Can't load a video model while training is running: the video "
            "pipeline would compete with the training run for GPU memory. Training "
            "was left untouched. Try again after training finishes."
        ),
    )


@router.post("/video/download-plan", response_model = DiffusionDownloadPlanResponse)
async def video_download_plan(
    request: VideoLoadRequest, current_subject: str = Depends(get_current_subject)
):
    """The repos + files this pick needs, so the frontend stages them through the Hub
    download manager instead of the load downloading inline. Mirrors /images/download-plan."""
    from routes.inference import (
        _refuse_disabled_nvfp4_checkpoint,
        _refuse_disabled_nvfp4_request,
        _route_nvfp4_request,
    )

    _refuse_disabled_nvfp4_request(request)
    if account_access.managed_account():
        await asyncio.to_thread(account_access.require_media_references, request)
    if account_access.managed_account():
        await asyncio.to_thread(account_access.require_media_model_access, request)
    if account_access.managed_account():
        request = request.model_copy(
            update = {"hf_token": account_access.account_hf_token(request.hf_token)}
        )
    await _refuse_disabled_nvfp4_checkpoint(request)
    request, _ = await _route_nvfp4_request(request, "video")
    from core.inference.diffusion import split_local_checkpoint_path
    from core.inference.diffusion_local_files import resolve_local_single_file
    from core.inference.video import (
        assert_video_precision_available,
        get_video_backend,
        resolve_video_model_kind,
    )
    from utils.native_path_leases import redact_native_paths

    backend = get_video_backend()
    try:
        kind = resolve_video_model_kind(request.gguf_filename, request.model_kind)
        if kind == "pipeline" and not request.gguf_filename:
            split = await asyncio.to_thread(split_local_checkpoint_path, request.model_path)
            if split is not None:
                request.model_path, request.gguf_filename = split
                kind = resolve_video_model_kind(split[1], None)
            sole = (
                None
                if split is not None
                else await asyncio.to_thread(resolve_local_single_file, request.model_path)
            )
            if sole is not None:
                request.gguf_filename = sole
                kind = resolve_video_model_kind(sole, None)
        fam = await asyncio.to_thread(
            backend.validate_load_request,
            request.model_path,
            gguf_filename = request.gguf_filename,
            family_override = request.family_override,
            display_repo_id = request.display_repo_id,
            model_kind = kind,
            base_repo = request.base_repo,
            transformer_quant = request.transformer_quant,
            text_encoder_quant = request.text_encoder_quant,
            # And the partition, because one of those quant-keyed refusals is task-keyed. Without it here the plan below
            # staged the 66 GB dense transformer_ref/ AND the incompatible fl2va quant first: the hosted pre-quantized
            # H3 checkpoints are fl2va denoisers, so a quantized ref2va is rejected.
            h3_task = request.h3_task,
        )
        # Precision preflight BEFORE staging the plan so unsupported FP8 fails before downloading.
        # Skipped while training holds the GPU (probe initialises CUDA). One resolution, reused below.
        gpu_ordinal = None
        training = fam is not None and await asyncio.to_thread(_training_is_active)
        if fam is not None:
            gpu_ordinal = await _selected_gpu_ordinal(request.gpu_ids, allow_ranking = not training)
        if fam is not None and not training:
            from core.inference.video_ltx2 import ltx23_identity_without_hashing
            def _plan_precision_check(*args, **kwargs):
                with ltx23_identity_without_hashing():
                    assert_video_precision_available(*args, **kwargs)

            await asyncio.to_thread(
                _plan_precision_check,
                fam,
                model_kind = kind,
                transformer_quant = request.transformer_quant,
                text_encoder_quant = request.text_encoder_quant,
                memory_mode = request.memory_mode,
                # Judged on the card this pick would load on, as the loader does.
                gpu_ordinal = gpu_ordinal,
                checkpoint_filename = request.gguf_filename,
                checkpoint_repo = request.model_path,
            )
        plan = await asyncio.to_thread(
            backend.download_plan,
            request.model_path,
            gpu_ordinal = gpu_ordinal,
            gguf_filename = request.gguf_filename,
            base_repo = request.base_repo,
            family_override = request.family_override,
            display_repo_id = request.display_repo_id,
            model_kind = kind,
            hf_token = request.hf_token,
            # fp8 takes a hosted pre-cast encoder; staging the dense one wastes ~49 GB on LTX-2.
            text_encoder_quant = request.text_encoder_quant,
            # A hosted pre-quantized DiT replaces the dense one; avoids staging 66.3 GB unused shards.
            transformer_quant = request.transformer_quant,
            # H3 denoisers live in separate subfolders (transformer_ref/ vs transformer/).
            h3_task = request.h3_task,
            # Forward the memory / speed policy: an fp8 LTX-2.3 pick under balanced / low_vram loads bf16 and must not stage the FP8 DiT.
            memory_mode = request.memory_mode,
            speed_mode = request.speed_mode,
            allow_device_probe = not training,
        )
        return DiffusionDownloadPlanResponse(**plan)
    except (ValueError, FileNotFoundError) as exc:
        raise HTTPException(status_code = 400, detail = redact_native_paths(str(exc)))
    except RuntimeError as exc:
        # Mirrors /video/load and /images/download-plan: a precision-gate RuntimeError is a 409, not a fault.
        raise HTTPException(status_code = 409, detail = redact_native_paths(str(exc)))


_VIDEO_LOAD_CANCELLED = "Video load was cancelled."


@router.post("/video/load", response_model = VideoStatusResponse)
@account_access.gpu_busy_route
async def load_video_model(
    request: VideoLoadRequest,
    current_subject: str = Depends(get_current_subject),
    via_api_key: bool = Depends(authenticated_via_api_key),
):
    # The status may describe a PREVIOUS model resolved by an earlier request.
    from hub.utils.host_paths import (
        raised_inventory_detail,
        redact_host_paths,
        restore_inventory_handles,
    )
    from core.inference.chat_swap_kv import preparing_load

    try:
        with preparing_load("video", request.load_token):
            loaded = await load_video_model_gated(request, current_subject, user_initiated = True)
    except HTTPException as exc:
        # Raising loads skip the wrappers; the inner loader redacts native paths, not inventory handles.
        exc.detail = raised_inventory_detail(exc.detail, via_api_key = via_api_key)
        raise
    return redact_host_paths(
        restore_inventory_handles(loaded),
        via_api_key = via_api_key,
    )


async def load_video_model_gated(
    request: VideoLoadRequest,
    current_subject: str,
    *,
    user_initiated: bool = False,
):
    """Everything ``POST /video/load`` does, plus who asked for it. Media auto-switch awaits this rather than the
    route so the idle unload can tell an API-loaded pipeline from one the user picked on the Video page.
    """
    from routes.inference import (
        _nvfp4_route_kwarg,
        _refuse_disabled_nvfp4_checkpoint,
        _refuse_disabled_nvfp4_request,
        _route_nvfp4_request,
    )

    _refuse_disabled_nvfp4_request(request)
    if account_access.managed_account():
        await asyncio.to_thread(account_access.require_media_references, request)
    account_access.require_idle_other_accounts()
    if account_access.managed_account():
        await asyncio.to_thread(account_access.require_media_model_access, request)
    if account_access.managed_account():
        request = request.model_copy(
            update = {"hf_token": account_access.account_hf_token(request.hf_token)}
        )
    await _refuse_disabled_nvfp4_checkpoint(request)
    request, nvfp4_route = await _route_nvfp4_request(
        request, "video", user_initiated = user_initiated
    )
    # Tested at entry (begin_load returns early) and written at launch (validation may 400 first).
    from routes.inference import (
        _note_load_fetched_with_a_request_token,
        _repo_is_in_the_hub_cache,
    )

    _media_repos_to_record = [
        ref
        for ref in (request.model_path, request.base_repo)
        if ref and _repo_is_in_the_hub_cache(ref) is not True
    ]
    from core.inference.diffusion import split_local_checkpoint_path
    from core.inference.diffusion_local_files import resolve_local_single_file
    from core.inference.diffusion_device import (
        resolve_diffusion_device_target,
        resolve_selected_cuda_ordinal,
    )
    from core.inference.gpu_arbiter import (
        DIFFUSION,
        VIDEO,
        MultiModelAlwaysRefusal,
        acquire_for_request,
        eviction_sink,
        note_evictions,
        begin_media_load,
        guarded_media_begin,
        refusal_for,
        refuse_replacing_media,
        release,
        require_no_foreign_generations,
        resident_slots,
    )
    from core.inference.media_keepwarm import note_load_origin
    from hub.utils.gguf import extract_quant_token
    from core.inference.video import (
        assert_video_precision_available,
        get_video_backend,
        resolve_video_model_kind,
    )
    from utils.native_path_leases import redact_native_paths

    from core.inference import media_load_ids

    backend = get_video_backend()
    try:
        # A load an unload already cancelled by its token starts nothing (checked again at admission).
        media_load_ids.refuse_cancelled("video", request.load_token)
        # Resolve the load kind once (gguf / single_file / pipeline) so validation and the load agree; a bad kind raises
        # here, so a 400.
        kind = resolve_video_model_kind(request.gguf_filename, request.model_kind)
        # A bare single-file .safetensors dir holding one checkpoint loads as single_file.
        if kind == "pipeline" and not request.gguf_filename:
            split = await asyncio.to_thread(split_local_checkpoint_path, request.model_path)
            if split is not None:
                request.model_path, request.gguf_filename = split
                kind = resolve_video_model_kind(split[1], None)
            sole = (
                None
                if split is not None
                else await asyncio.to_thread(resolve_local_single_file, request.model_path)
            )
            if sole is not None:
                request.gguf_filename = sole
                kind = resolve_video_model_kind(sole, None)
        # Validate cheaply BEFORE touching the GPU so an unloadable pick can't evict chat then 400.
        fam = await asyncio.to_thread(
            backend.validate_load_request,
            request.model_path,
            gguf_filename = request.gguf_filename,
            base_repo = request.base_repo,
            family_override = request.family_override,
            display_repo_id = request.display_repo_id,
            model_kind = kind,
            transformer_quant = request.transformer_quant,
            text_encoder_quant = request.text_encoder_quant,
            h3_task = request.h3_task,
        )
        # Refuse while training runs, BEFORE the precision check, whose GPU probe opens a CUDA context.
        _guard_video_load_against_training()
        # begin_load repeats this check, but inside acquire_for after chat is evicted. `auto` never refused.
        gpu_ordinal = await _selected_gpu_ordinal(request.gpu_ids)
        await asyncio.to_thread(
            assert_video_precision_available,
            fam,
            model_kind = kind,
            transformer_quant = request.transformer_quant,
            text_encoder_quant = request.text_encoder_quant,
            # Memory request settles balanced/low_vram offload before measuring; offloaded parts skip torchao.
            memory_mode = request.memory_mode,
            gpu_ordinal = gpu_ordinal,
            checkpoint_filename = request.gguf_filename,
            checkpoint_repo = request.model_path,
        )
        # Speech GGUF check here, since the backend's runs after acquire_for evicts chat.
        from core.inference.diffusion_compat import assert_pick_is_not_speech

        await asyncio.to_thread(
            assert_pick_is_not_speech,
            request.model_path,
            request.gguf_filename,
            request.hf_token,
            user_initiated,
        )
        # Non-CPU loads take the GPU from chat; CPU loads only release stale VIDEO ownership, owner-guarded.
        device = await asyncio.to_thread(lambda: resolve_diffusion_device_target().device)

        def _start_load():
            # Recorded only after every cheap refusal, before the worker gets the credential.
            for _ref in _media_repos_to_record:
                _note_load_fetched_with_a_request_token(_ref, request.hf_token)
            # Kicks the (slow) load onto a background thread and returns at once; begin_load itself validates
            # network-free. Recorded with its token, so an unload can name this load.
            prior = media_load_ids.admitting("video", backend, request.load_token)
            started = backend.begin_load(
                request.model_path,
                display_repo_id = request.display_repo_id,
                # A load nobody asked for may not reach the hub.
                local_files_only = not user_initiated,
                gguf_filename = request.gguf_filename,
                base_repo = request.base_repo,
                family_override = request.family_override,
                hf_token = request.hf_token,
                memory_mode = request.memory_mode,
                speed_mode = request.speed_mode,
                attention_backend = request.attention_backend,
                transformer_cache = request.transformer_cache,
                transformer_cache_threshold = request.transformer_cache_threshold,
                transformer_quant = request.transformer_quant,
                text_encoder_quant = request.text_encoder_quant,
                model_kind = kind,
                h3_task = request.h3_task,
                gpu_ids = request.gpu_ids,
                # The already-ranked card, so free VRAM drift cannot change the pick.
                gpu_ordinal = gpu_ordinal,
                allow_oversized_load = request.allow_oversized_load,
                **_nvfp4_route_kwarg(backend.begin_load, nvfp4_route),
            )
            media_load_ids.admitted("video", backend, request.load_token, prior)
            return started

        from core.inference.chat_swap_kv import (
            preparing_load_token,
            raise_if_load_cancelled,
            run_unless_load_cancelled,
        )

        preflight = preparing_load_token()

        def _begin_load():
            # Checked under the preflight lock through admission, so a cancel lands before or after it.
            return run_unless_load_cancelled(
                _VIDEO_LOAD_CANCELLED,
                account_access.admit_media_load,
                "video",
                _start_load,
                request.model_path,
            )

        # begin_load signals whatever generation is running, so guard on every device.
        require_no_foreign_generations()
        from core.inference.sd_cpp_args import forces_cpu_backend
        from core.inference.video_minimax_h3 import is_h3_native
        from utils.multi_model_settings import get_multi_model_mode

        multi_model_mode = await asyncio.to_thread(get_multi_model_mode)
        media_names = (request.model_path,)
        # On any device: the load would replace the loaded video model, which no acquire evicts.
        replaced_media = await asyncio.to_thread(
            refuse_replacing_media, VIDEO, multi_model_mode, media_names
        )
        evicted: list = []
        note_evictions(replaced_media, evicted)

        def begin():
            return begin_media_load(VIDEO, multi_model_mode, media_names, _begin_load)

        if is_h3_native(fam, kind):
            from core.inference.diffusion_engine_router import get_active_diffusion_engine
            images = get_active_diffusion_engine()
            if getattr(images, "runs_off_torch_device", False) is True:
                # No arbiter owner evicts it, yet it holds the one managed sd.cpp tree H3 installs into.
                image_slots = resident_slots(DIFFUSION) or [{"kind": "image", "model": ""}]
                if multi_model_mode == "always":
                    raise refusal_for(image_slots, "image")
                note_evictions(image_slots, evicted)
                # A load an unload cancelled never unloads the image model.
                await asyncio.to_thread(
                    run_unless_load_cancelled, _VIDEO_LOAD_CANCELLED, images.unload
                )
        # sd.cpp runs a paravirtual Mac GPU on the CPU backend: take no VIDEO claim, but keep any existing one until the
        # worker tears the old model down and releases it.
        forced_cpu = (
            is_h3_native(fam, kind)
            and device == "mps"
            and await asyncio.to_thread(forces_cpu_backend, device)
        )
        if forced_cpu:
            status_dict = await asyncio.to_thread(begin)
        elif device != "cpu":
            # Register the load under the arbiter lock, else a racing acquire evicts VIDEO and both
            # allocate.
            from core.inference.gpu_residency import media_fit_kwargs
            from routes.inference import _diffusion_training_admission

            fit_kwargs = await asyncio.to_thread(
                media_fit_kwargs, VIDEO, request, gpu_ordinal, multi_model_mode
            )

            def _acquire_and_begin():
                raise_if_load_cancelled(_VIDEO_LOAD_CANCELLED)
                admitted = []

                def _admit():
                    # Under the arbiter lock, before anything is evicted; the preflight lock is held
                    # until the load registers, so a cancel never lands between the two.
                    if preflight is None:
                        return
                    preflight.lock.acquire()
                    admitted.append(True)
                    raise_if_load_cancelled(_VIDEO_LOAD_CANCELLED)

                token = eviction_sink.set(evicted)
                try:
                    with _diffusion_training_admission():
                        return acquire_for_request(
                            VIDEO,
                            guarded_media_begin(VIDEO, multi_model_mode, media_names, _begin_load),
                            admit = _admit,
                            **fit_kwargs,
                        )
                finally:
                    if admitted:
                        preflight.lock.release()
                    eviction_sink.reset(token)

            from core.inference.chat_swap_kv import acquire_then_close, save_chat_kv_before_swap

            swap = await save_chat_kv_before_swap(VIDEO, "video", **fit_kwargs)
            try:
                raise_if_load_cancelled(_VIDEO_LOAD_CANCELLED)
            except BaseException:
                swap.close()
                raise
            status_dict = await acquire_then_close(swap, _acquire_and_begin)
        else:
            await asyncio.to_thread(release, VIDEO)
            status_dict = await asyncio.to_thread(begin)
        # Keyed to the target: this load can still fail with the previous model resident
        note_load_origin(
            VIDEO,
            request.model_path,
            extract_quant_token(request.gguf_filename) if kind == "gguf" else None,
            # Derived when the caller left it unset, since that is what the backend publishes.
            request.h3_task or _derived_h3_task(request.gguf_filename, kind),
            user_action = user_initiated,
        )
        account_access.note_resident_components(
            "video",
            request.model_path,
            request.base_repo,
            *account_access.media_adapter_references(request),
        )
        reset_media_load_progress("video")
        status_dict = {
            **status_dict,
            "evicted": [slot["model"] for slot in evicted if slot.get("model")],
            "evicted_slots": evicted,
        }
        return VideoStatusResponse(**status_dict)
    except (ValueError, FileNotFoundError) as exc:
        raise HTTPException(status_code = 400, detail = redact_native_paths(str(exc)))
    except account_access.GpuBusyForAnotherAccountError as exc:
        raise account_access.gpu_busy_error() from exc
    except MultiModelAlwaysRefusal as exc:
        raise exc.as_http_exception() from exc
    except RuntimeError as exc:
        # A video load is already in progress.
        raise HTTPException(status_code = 409, detail = str(exc))


@router.get("/video/load-progress", response_model = VideoLoadProgressResponse)
async def video_load_progress(
    current_subject: str = Depends(get_current_subject),
    via_api_key: bool = Depends(authenticated_via_api_key),
):
    from core.inference.chat_swap_kv import saving_progress

    saving = saving_progress("video")
    if saving is not None:
        return VideoLoadProgressResponse(**saving)
    if account_access.resident_hidden("video"):
        return account_access.hidden_resident_response()
    from core.inference.video import get_video_backend

    if account_access.managed_account() and account_access.resident_hidden(
        "video", get_video_backend().status().get("repo_id")
    ):
        return account_access.hidden_resident_response()
    progress = get_video_backend().load_progress()
    fraction = byte_fraction(progress.get("downloaded_bytes"), progress.get("expected_bytes"))
    log_media_load_progress("video", progress.get("phase"), fraction)
    from hub.utils.host_paths import redact_load_progress

    return VideoLoadProgressResponse(**redact_load_progress(progress, via_api_key = via_api_key))


_generation_account: Optional[str] = None
_generation_lock = threading.Lock()


def _note_generation_account() -> None:
    global _generation_account
    from utils.account_context import current_account
    with _generation_lock:
        _generation_account = current_account().account_id


def _reserved_generation_account(backend) -> Optional[str]:
    reserved = getattr(backend, "generate_job_account", None)
    return reserved() if callable(reserved) else None


def _generation_started_by(backend) -> Optional[str]:
    """The backend's own reservation wins: it is taken before begin_generate returns."""
    reserved = _reserved_generation_account(backend)
    if reserved is not None:
        return reserved
    with _generation_lock:
        return _generation_account


def _read_generate_progress(backend, expected_account):
    """Recheck progress against the authorized reservation, if the backend supports it."""
    if expected_account is None:
        return backend.generate_progress()
    try:
        params = inspect.signature(backend.generate_progress).parameters
    except (TypeError, ValueError):
        params = {}
    accepts = "expected_account" in params or any(
        p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()
    )
    if not accepts:
        return backend.generate_progress()
    return backend.generate_progress(expected_account = expected_account)


_UNREAD = object()


def _generation_hidden(backend, started_by = _UNREAD) -> bool:
    """A caller that acts on the reservation passes the read it will act on."""
    if started_by is _UNREAD:
        started_by = _generation_started_by(backend)
    if started_by is not None:
        # Owner included: administering the machine covers a resident model, not a clip's prompt.
        from utils.account_context import current_account
        return started_by != current_account().account_id
    return account_access.resident_hidden("video") or (
        account_access.managed_account()
        and account_access.resident_hidden("video", backend.status().get("repo_id"))
    )


@router.post("/video/generate", response_model = VideoGenerateResponse)
@account_access.gpu_busy_route
async def generate_video(
    request: VideoGenerateRequest,
    current_subject: str = Depends(get_current_subject),
    hf_token: Optional[str] = Depends(get_hf_token),
):
    """Start a generation job and return at once (the begin_load pattern): a clip
    takes minutes, and secure mode's tunnel caps the origin response window near
    100 seconds, so the response must not span the generation. The worker runs the
    generate + gallery-persist pipeline; the terminal outcome (completed with the
    saved record / failed with a client-safe error) arrives via generate-progress.

    With media auto-switch on, ``model`` names the video model to generate on and is loaded
    when it is not the resident one."""
    from core.inference.gpu_arbiter import VIDEO
    from core.inference.media_auto_switch import maybe_auto_switch_media_model
    from core.inference.video import get_video_backend, video_failure_detail
    from core.inference.video_families import (
        VIDEO_GENERATION_BUSY_MSG,
        VIDEO_MODEL_CHANGED_MSG,
        VIDEO_NOT_LOADED_MSG,
        VideoShapeError,
    )

    def _refuse_unservable_request(pick) -> None:
        """Checks the request against the target family before any eviction or multi-minute load."""
        from core.inference.media_model_index import expected_partition
        from core.inference.video import (
            _detect_load_family,
            assert_first_frame_pipeline_available,
            resolve_video_model_kind,
        )
        from core.inference.video_minimax_h3 import is_h3_native
        from core.inference.video_families import (
            snap_num_frames,
            validate_video_continuation,
            validate_video_flow_controls,
            validate_video_keyframe_conditioning,
            validate_video_reference_conditioning,
            validate_video_request_shape,
        )

        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, fps = request.fps
        )
        h3_task = expected_partition(pick)
        validate_video_keyframe_conditioning(
            fam,
            h3_task,
            has_keyframes = bool(request.first_frame or request.last_frame),
            has_last_frame = bool(request.last_frame),
        )
        if request.first_frame:
            assert_first_frame_pipeline_available(fam)
        # the engine is only knowable up front where the pick decides it, as an h3 gguf does
        kind = resolve_video_model_kind(pick.gguf_filename, pick.model_kind)
        engine = "sd_cpp" if is_h3_native(fam, kind) else None
        validate_video_reference_conditioning(
            fam,
            h3_task,
            has_references = bool(
                request.reference_images or request.reference_videos or request.reference_audios
            ),
            reference_image_size = request.reference_image_size,
            engine = engine,
        )
        validate_video_flow_controls(
            fam, request.flow_shift, request.audio_flow_shift, engine = engine
        )
        validate_video_continuation(
            fam,
            has_video = bool(request.continuation_video),
            keep = request.continuation_keep,
            num_frames = snap_num_frames(fam, request.num_frames or fam.default_num_frames),
        )

    # Before the backend is resolved: the requested model may be the one this brings up.
    try:
        await maybe_auto_switch_media_model(
            request.model,
            owner = VIDEO,
            current_subject = current_subject,
            openai_errors = False,
            hf_token = hf_token,
            before_switch = _refuse_unservable_request,
        )
    except VideoShapeError as exc:
        raise HTTPException(status_code = 422, detail = str(exc))
    except ValueError as exc:
        # the conditioning rules, which begin_generate reports the same way below
        raise HTTPException(status_code = 400, detail = str(exc))

    backend = get_video_backend()
    generate_kwargs = dict(
        prompt = request.prompt,
        negative_prompt = request.negative_prompt,
        width = request.width,
        height = request.height,
        num_frames = request.num_frames,
        fps = request.fps,
        steps = request.steps,
        guidance = request.guidance,
        guidance_2 = request.guidance_2,
        seed = request.seed,
        first_frame = request.first_frame,
        last_frame = request.last_frame,
        reference_images = request.reference_images,
        reference_videos = [r.model_dump() for r in request.reference_videos or []] or None,
        reference_audios = request.reference_audios,
        reference_image_size = request.reference_image_size,
        flow_shift = request.flow_shift,
        audio_flow_shift = request.audio_flow_shift,
        continuation_video = request.continuation_video,
        continuation_keep = request.continuation_keep,
        live_preview = request.live_preview,
    )
    # Authorize the reservation-pinned token: a gap load must not render weights of another account.
    for attempt in range(2):
        expected_state = None
        if account_access.managed_account():
            status, expected_state = await asyncio.to_thread(backend.generation_snapshot)
            await asyncio.to_thread(account_access.require_media_generation_access, status, "video")
        try:
            await asyncio.to_thread(
                backend.begin_generate,
                **generate_kwargs,
                **({"expected_state": expected_state} if expected_state is not None else {}),
            )
        except VideoShapeError as exc:
            # Must stay before the 400 below: VideoShapeError IS a ValueError.
            raise HTTPException(status_code = 422, detail = str(exc))
        except ValueError as exc:
            # Bad client input: 400 with the reason, not a generic 500.
            raise HTTPException(status_code = 400, detail = str(exc))
        except RuntimeError as exc:
            # Match the sentinels exactly so an unrelated failure cannot leak its message.
            msg = str(exc)
            if msg == VIDEO_MODEL_CHANGED_MSG and attempt == 0:
                continue
            if msg == VIDEO_NOT_LOADED_MSG:
                raise HTTPException(
                    status_code = 409,
                    detail = msg,
                    headers = problem_headers("not_loaded", kind = "video"),
                )
            if msg in (VIDEO_GENERATION_BUSY_MSG, VIDEO_MODEL_CHANGED_MSG):
                raise HTTPException(status_code = 409, detail = msg)
            logger.error("video.generate_failed: %s", exc, exc_info = True)
            raise HTTPException(status_code = 500, detail = video_failure_detail(exc))
        break

    _note_generation_account()
    reset_media_generation_progress("video")
    return VideoGenerateResponse()


@router.get("/video/generate-progress", response_model = VideoGenerateProgressResponse)
async def video_generate_progress(current_subject: str = Depends(get_current_subject)):
    from core.inference.video import get_video_backend

    backend = get_video_backend()
    # The backend rechecks the owner under its lock; a successor can reserve mid-poll.
    reserved = _reserved_generation_account(backend)
    if reserved is not None:
        started_by = reserved
    else:
        with _generation_lock:
            started_by = _generation_account
    if _generation_hidden(backend, started_by):
        return account_access.hidden_generate_progress_response(VideoGenerateProgressResponse)
    progress = _read_generate_progress(backend, reserved)
    if progress is None:
        # The reservation changed hands mid-poll; the successor's progress is not ours to see.
        return account_access.hidden_generate_progress_response(VideoGenerateProgressResponse)
    log_media_generation_progress("video", progress)
    return VideoGenerateProgressResponse(**progress)


_CANCEL_BODY_MSG = 'Send a JSON object such as {"video_id": "..."}, or no body.'


async def _cancel_video_id(request: Request) -> Optional[str]:
    """The optional ``video_id`` a cancel names; no body means the running render."""
    import json

    raw = await request.body()
    if not raw.strip():
        return None
    try:
        body = json.loads(raw)
    except ValueError:
        raise HTTPException(status_code = 422, detail = _CANCEL_BODY_MSG)
    if not isinstance(body, dict):
        raise HTTPException(status_code = 422, detail = _CANCEL_BODY_MSG)
    video_id = body.get("video_id")
    if video_id is not None and not isinstance(video_id, str):
        raise HTTPException(status_code = 422, detail = _CANCEL_BODY_MSG)
    if video_id is not None and not video_id.strip():
        # An empty id must not widen into a cancel of whatever is rendering.
        raise HTTPException(
            status_code = 422, detail = "video_id is empty; leave it out to stop the running render."
        )
    return video_id


@router.post("/video/generate/cancel")
async def cancel_video_generation(
    request: Request, current_subject: str = Depends(get_current_subject)
):
    from core.inference.video import get_video_backend

    video_id = await _cancel_video_id(request)
    queued = _own_queued_video(video_id) if video_id is not None else None
    if queued is not None and queued.starting:
        if not await _await_queued_start(queued):
            raise HTTPException(status_code = 409, detail = "The video is starting; retry shortly.")
        queued = _own_queued_video(video_id)
    if queued is not None:
        _drop_queued_video(queued)
        return {"cancelled": True}
    backend = get_video_backend()
    # One read: a second could name a successor and hand it back as expected_account.
    reserved = _reserved_generation_account(backend)
    if reserved is not None:
        started_by = reserved
    else:
        with _generation_lock:
            started_by = _generation_account
    if _generation_hidden(backend, started_by):
        cancelled = False
    elif started_by is None and account_access.foreign_work_active():
        cancelled = False
    else:
        if reserved is None:
            # No reservation yet: bind the cancel to the caller so a later reservation can't receive it.
            from utils.account_context import current_account
            expected = current_account().account_id
        else:
            expected = reserved
        # The id is rechecked under the backend's lock, so a finished render's successor is safe.
        cancelled = await asyncio.to_thread(
            backend.cancel_generate, expected_video_id = video_id, expected_account = expected
        )
    if video_id is not None and not cancelled:
        # Hidden and foreign renders answer the same, so this reveals nothing about them.
        raise HTTPException(status_code = 409, detail = "That video is not rendering.")
    return {"cancelled": cancelled}


@router.get("/video/status", response_model = VideoStatusResponse)
async def video_status(
    current_subject: str = Depends(get_current_subject),
    via_api_key: bool = Depends(authenticated_via_api_key),
):
    if account_access.resident_hidden("video"):
        return account_access.hidden_resident_response()
    from hub.utils.host_paths import redact_host_paths

    from core.inference import media_load_ids

    # Polled on page mount, so usually the first import of the video stack: keep it off the loop.
    backend = await asyncio.to_thread(_video_backend)
    # With the load id of the same state, so an unload can name exactly what this answer shows.
    status_dict, load_id, resident_load_id = await asyncio.to_thread(
        media_load_ids.snapshot_ids, "video", backend, backend.status
    )
    if account_access.resident_hidden("video", status_dict.get("repo_id")):
        return account_access.hidden_resident_response()
    # Step-skip counters are shown only to the clip's own account.
    if (
        status_dict.get("transformer_cache_stats") is not None
        and account_access.account_scope() is not None
    ):
        view = getattr(backend, "static_skip_view", None)
        owner, stats = view() if callable(view) else (None, status_dict["transformer_cache_stats"])
        visible = owner is None or owner == current_account_id()
        status_dict = {**status_dict, "transformer_cache_stats": stats if visible else None}
    if status_dict.get("loaded") and status_dict.get("resident_mib") is None:
        from core.inference.gpu_residency import media_owner_held_mib
        status_dict = {**status_dict, "resident_mib": media_owner_held_mib("video")}
    status_dict = {**status_dict, "load_id": load_id, "resident_load_id": resident_load_id}
    # This route answers after the resolving request ended, so no handle is in context to restore.
    return redact_host_paths(VideoStatusResponse(**status_dict), via_api_key = via_api_key)


@router.post("/video/unload", response_model = VideoUnloadResponse)
@account_access.gpu_busy_route
async def unload_video_model(
    request: Optional[MediaUnloadRequest] = None,
    current_subject: str = Depends(get_current_subject),
    via_api_key: bool = Depends(authenticated_via_api_key),
):
    from core.inference.gpu_arbiter import VIDEO, release_if
    from core.inference.video import get_video_backend

    expected_load_id = request.expected_load_id if request is not None else None
    if not expected_load_id:
        account_access.require_resident_control("video")
    backend = get_video_backend()
    if not expected_load_id and account_access.managed_account():
        account_access.require_resident_control("video", backend.status().get("repo_id"))
    unload_kwargs = {}
    if account_access.account_scope() is not None:
        unload_kwargs["expected_account"] = current_account_id()
    if expected_load_id:
        from core.inference import media_load_ids
        from core.inference.chat_swap_kv import cancel_preparing_loads

        # The POST carrying this token, if it is still in preflight: stopped (or registered, which
        # the check below then names) before any eviction it would run.
        await asyncio.to_thread(
            cancel_preparing_loads,
            "video",
            current_account_id(),
            load_token = expected_load_id,
        )

        def unload(only_if):
            account_access.require_resident_control("video")
            if account_access.managed_account():
                account_access.require_resident_control("video", backend.status().get("repo_id"))
            return backend.unload(**unload_kwargs, only_if = only_if)

        # Only the load that token started, checked and unloaded under the admission lock; any other
        # load (a newer one, the UI's, another account's) is left alone and not described.
        outcome, status_dict = await asyncio.to_thread(
            media_load_ids.unload_if_current, "video", backend, expected_load_id, unload
        )
        if outcome != "unloaded":
            return MediaUnloadOutcome(unloaded = False, outcome = outcome)
    else:
        status_dict = await asyncio.to_thread(backend.unload, **unload_kwargs)
    # Release VIDEO only if nothing is resident or loading; release_if keeps the check atomic.
    await asyncio.to_thread(
        release_if,
        VIDEO,
        lambda: not backend.loading_repo_ids() and not backend.status()["loaded"],
    )
    # An unload answers with the state it left behind, which still names the model it dropped.
    from hub.utils.host_paths import redact_host_paths, restore_inventory_handles

    answer = redact_host_paths(
        restore_inventory_handles(VideoStatusResponse(**status_dict)),
        via_api_key = via_api_key,
    )
    if expected_load_id:
        return VideoLoadUnloadedResponse(
            **jsonable_encoder(answer), unloaded = True, outcome = "unloaded"
        )
    return answer


@router.get("/video/gallery", response_model = VideoGalleryListResponse)
async def list_gallery_videos(
    limit: int = 50,
    offset: int = 0,
    archived: bool = False,
    current_subject: str = Depends(get_current_subject),
):
    from core.inference import video_gallery

    limit = max(1, min(limit, 200))
    offset = max(0, offset)

    # Validate inside the pager so offset / limit / has_more count over valid records.
    def _valid_gallery_video(record: dict) -> bool:
        try:
            GalleryVideo(**record)
        except ValidationError:
            return False
        return True

    # Fetch one extra to learn whether more remain, without a second scan.
    records = await asyncio.to_thread(
        video_gallery.list_videos,
        limit + 1,
        offset,
        valid = _valid_gallery_video,
        archived = archived,
    )
    has_more = len(records) > limit
    videos = [GalleryVideo(**r) for r in records[:limit]]
    return VideoGalleryListResponse(videos = videos, has_more = has_more)


@router.get("/video/gallery/{video_id}/file")
async def get_gallery_video_file(
    video_id: str, current_subject: str = Depends(get_current_subject)
):
    from core.inference import video_gallery

    # Resolve only an Unsloth-owned MP4 so a guessed stem cannot stream a foreign clip.
    path = await asyncio.to_thread(video_gallery.owned_video_path, video_id)
    if path is None:
        raise HTTPException(status_code = 404, detail = "Video not found.")
    from fastapi.responses import FileResponse

    return FileResponse(
        path,
        media_type = "video/mp4",
        headers = {"Cache-Control": "private, max-age=31536000, immutable"},
    )


# Clips are too large for blob fetch; /file is bearer-gated, so mint a 12-hour HMAC link.
_VIDEO_LINK_TTL = 12 * 3600
_VIDEO_LINK_SECRET = _secrets.token_bytes(32)


def _sign_video_id(video_id: str, ttl_s: Optional[int] = None) -> str:
    exp = int(_time.time()) + (_VIDEO_LINK_TTL if ttl_s is None else ttl_s)
    payload = f"{media_link_target(video_id)}.{exp}"
    sig = _hmac.new(_VIDEO_LINK_SECRET, payload.encode(), _hashlib.sha256).hexdigest()
    return f"{payload}.{sig}"


def _verify_video_link_token(token: str) -> Optional[str]:
    """The video id a valid, unexpired token names, else None. A separate secret from the image
    links, so a token minted for one media type can never serve the other."""
    try:
        video_id, exp_s, sig = token.rsplit(".", 2)
    except ValueError:
        return None
    expected = _hmac.new(
        _VIDEO_LINK_SECRET, f"{video_id}.{exp_s}".encode(), _hashlib.sha256
    ).hexdigest()
    if not _hmac.compare_digest(sig, expected):
        return None
    try:
        if int(exp_s) < int(_time.time()):
            return None
    except ValueError:
        return None
    return video_id


@router.get("/video/gallery/{video_id}/signed-url")
async def get_gallery_video_signed_url(
    video_id: str,
    current_subject: str = Depends(get_current_subject),
    no_credential: Annotated[bool, Depends(request_admitted_without_credential)] = False,
    ttl_s: Optional[int] = Query(None, ge = 60, le = 12 * 3600),
):
    """A directly playable, range-capable link for one clip (bearer-gated to mint, HMAC to use).

    Returned as a relative URL so it works behind any proxy the page itself is served through.
    ``ttl_s`` shortens the life (MCP asks for 1 h); omitted, the UI's 12 h applies."""
    if no_credential:
        raise HTTPException(
            status_code = 403,
            detail = "Video links can only be created from the Unsloth UI or with an API key.",
        )

    from core.inference import video_gallery

    path = await asyncio.to_thread(video_gallery.owned_video_path, video_id)
    if path is None:
        raise HTTPException(status_code = 404, detail = "Video not found.")
    token = _sign_video_id(video_id, ttl_s)
    return {"url": f"/api/inference/video/gallery/{video_id}/file-signed?token={token}"}


@router.get("/video/gallery/{video_id}/file-signed")
async def get_gallery_video_file_signed(video_id: str, token: str = Query(...)):
    """Stream one gallery MP4 gated by the HMAC token instead of the bearer, so it can be a plain
    <video src> and the browser can range-request it. Same ownership gate as the bearer route, and
    the token names the single clip it may serve."""
    from core.inference import video_gallery

    account = media_link_account(_verify_video_link_token(token), video_id)
    if account is None:
        raise HTTPException(status_code = 401, detail = "Invalid or expired video link.")
    path = await asyncio.to_thread(run_as, account, video_gallery.owned_video_path, video_id)
    if path is None:
        raise HTTPException(status_code = 404, detail = "Video not found.")
    from fastapi.responses import FileResponse

    return FileResponse(
        path,
        media_type = "video/mp4",
        headers = {"Cache-Control": "private, max-age=31536000, immutable"},
    )


@router.get("/video/gallery/{video_id}/frame")
async def get_gallery_video_frame(
    video_id: str,
    at: str = Query("first", max_length = 32),
    max_px: Optional[int] = Query(None, ge = 32, le = 4096),
    current_subject: str = Depends(get_current_subject),
):
    """One frame of an owned clip as PNG: ``at`` is ``first``, ``last`` or a time in seconds.
    Nothing is saved to the Images gallery."""
    from core.inference import video_gallery

    path = await asyncio.to_thread(video_gallery.owned_video_path, video_id)
    if path is None:
        raise HTTPException(status_code = 404, detail = "Video not found.")
    try:
        data = await asyncio.to_thread(video_gallery.frame_png, path, at, max_px)
    except FileNotFoundError:
        raise HTTPException(status_code = 404, detail = "Video not found.") from None
    except ValueError as exc:
        raise HTTPException(status_code = 400, detail = str(exc)) from None
    except RuntimeError as exc:
        raise HTTPException(status_code = 501, detail = str(exc)) from None
    return Response(
        content = data,
        media_type = "image/png",
        headers = {"Cache-Control": "private, max-age=31536000, immutable"},
    )


class _VideoAudioInput(BaseModel):
    model_config = ConfigDict(extra = "forbid")

    start_s: float = Field(0.0, ge = 0, le = 3600)
    end_s: Optional[float] = Field(None, gt = 0, le = 3600)

    @model_validator(mode = "after")
    def _ordered(self):
        if self.end_s is not None and self.end_s <= self.start_s:
            raise ValueError("end_s must be after start_s.")
        return self


@router.post(
    "/video/gallery/{video_id}/audio-input", status_code = 201, response_model = AudioInputRecord
)
async def extract_gallery_video_audio(
    video_id: str,
    body: _VideoAudioInput,
    response: Response,
    current_subject: str = Depends(get_current_subject),
):
    """Register an owned clip's audio track (optionally trimmed) as an audio input; the same
    extract again returns the existing record with 200."""
    from core.inference import audio_inputs, video_gallery

    record = await asyncio.to_thread(video_gallery.get_record, video_id)
    path = await asyncio.to_thread(video_gallery.owned_video_path, video_id)
    if record is None or path is None:
        raise HTTPException(status_code = 404, detail = "Video not found.")
    # The name is cleaned as a file name, so '/' and line breaks in the prompt become spaces first.
    prompt = " ".join(str(record.get("prompt") or "").replace("/", " ").replace("\\", " ").split())
    name = f"{(prompt or 'Video')[:60]} (audio).wav"
    try:
        saved, created = await asyncio.to_thread(
            audio_inputs.save_from_media, path, name, body.start_s, body.end_s
        )
    except audio_inputs.AudioInputError as exc:
        raise HTTPException(status_code = exc.status, detail = exc.detail) from None
    if not created:
        response.status_code = 200
    return AudioInputRecord(**saved)


@router.get("/video/gallery/{video_id}/export")
async def export_gallery_video(
    video_id: str,
    format: str = "webm",
    current_subject: str = Depends(get_current_subject),
):
    """Download-menu transcodes: WebM (VP9) or GIF, re-encoded on demand from the
    stored MP4 (which the /file route serves verbatim). 501 with a clear message
    when the codec/deps for the requested format are missing."""
    from core.inference import video_gallery

    fmt = format.strip().lower()
    if fmt not in ("webm", "gif"):
        raise HTTPException(status_code = 400, detail = "Unsupported format. Use webm or gif.")
    try:
        path = await asyncio.to_thread(video_gallery.transcode_to_file, video_id, fmt)
    except RuntimeError as exc:
        raise HTTPException(status_code = 501, detail = str(exc)) from exc
    if path is None:
        raise HTTPException(status_code = 404, detail = "Video not found.")
    from fastapi.responses import FileResponse
    from starlette.background import BackgroundTask

    def _cleanup() -> None:
        try:
            path.unlink(missing_ok = True)
        except OSError as e:  # noqa: BLE001 -- a leaked temp file must not fail the download
            logger.debug(f"Could not remove the export temp file {path}: {e}")

    # FileResponse streams from disk, so a large VP9 export is never fully resident. The temp file is deleted once sent.
    return FileResponse(
        path,
        media_type = "video/webm" if fmt == "webm" else "image/gif",
        filename = f"{video_id}.{fmt}",
        # Transcodes are deterministic per id+format; let the browser cache them.
        headers = {"Cache-Control": "private, max-age=31536000, immutable"},
        background = BackgroundTask(_cleanup),
    )


def _forget_terminal_video(video_id: Optional[str]) -> None:
    """Clear the backend's completed-job record for a clip that just left the gallery, so a page reload does not
    merge it back as a card whose file is gone. Best-effort: an unavailable backend only means the stale record
    survives, which is what happened before this call existed."""
    try:
        from core.inference.video import get_video_backend
        get_video_backend().forget_terminal_video(video_id)
    except Exception as e:  # noqa: BLE001 -- never fail a delete over progress bookkeeping
        logger.debug(f"Could not clear the terminal video record for {video_id!r}: {e}")


@router.post("/video/gallery/{video_id}/move", response_model = GalleryVideo)
async def move_gallery_video(
    video_id: str,
    body: GalleryMoveRequest,
    current_subject: str = Depends(get_current_subject),
):
    """Move one video to just after ``after_id``. Dropping among pins pins it, elsewhere unpins it."""
    from core.inference import video_gallery

    try:
        record = await asyncio.to_thread(video_gallery.move, video_id, body.after_id)
    except KeyError:
        # The neighbour left the shelf; the client resyncs.
        raise HTTPException(status_code = 409, detail = "The gallery changed; try the move again.")
    except OSError as exc:
        logger.warning("video_gallery.move_failed: %s", exc)
        raise HTTPException(status_code = 500, detail = "Could not save the new order.")
    if record is None:
        raise HTTPException(status_code = 404, detail = "Video not found.")
    return GalleryVideo(**record)


@router.post("/video/gallery/{video_id}/project", response_model = GalleryProjectResponse)
async def add_gallery_video_to_project(
    video_id: str,
    body: GalleryProjectRequest,
    current_subject: str = Depends(get_current_subject),
):
    """Copy one video into a chat project's folder."""
    from core.inference import video_gallery
    from core.inference.gallery_projects import ProjectNotFound, copy_into_project

    path = await asyncio.to_thread(video_gallery.owned_video_path, video_id)
    if path is None:
        raise HTTPException(status_code = 404, detail = "Video not found.")
    try:
        result = await asyncio.to_thread(copy_into_project, path, body.project_id, "videos")
    except ProjectNotFound:
        raise HTTPException(status_code = 404, detail = "Project not found.")
    except OSError as exc:
        logger.warning("video_gallery.add_to_project_failed: %s", exc)
        raise HTTPException(status_code = 500, detail = "Could not copy the video into the project.")
    return GalleryProjectResponse(**result)


@router.patch("/video/gallery/{video_id}", response_model = GalleryVideo)
async def update_gallery_video_flags(
    video_id: str,
    patch: GalleryFlagsPatch,
    current_subject: str = Depends(get_current_subject),
):
    """Pin/unpin or archive/restore one clip. Omitted fields are left alone."""
    from core.inference import video_gallery

    try:
        record = await asyncio.to_thread(
            video_gallery.set_flags, video_id, pinned = patch.pinned, archived = patch.archived
        )
    except OSError as exc:
        # The client applied this optimistically; a silent miss would undo on reload.
        logger.warning("video_gallery.set_flags_failed: %s", exc)
        raise HTTPException(status_code = 500, detail = "Could not save the change to this video.")
    if record is None:
        raise HTTPException(status_code = 404, detail = "Video not found.")
    # Archiving takes the clip off the strip.
    if patch.archived:
        _forget_terminal_video(video_id)
    return GalleryVideo(**record)


@router.delete("/video/gallery/{video_id}")
async def delete_gallery_video(video_id: str, current_subject: str = Depends(get_current_subject)):
    from core.inference import video_gallery

    deleted = await asyncio.to_thread(video_gallery.delete, video_id)
    if not deleted:
        raise HTTPException(status_code = 404, detail = "Video not found.")
    _forget_terminal_video(video_id)
    if not await asyncio.to_thread(_forget_openai_job, video_id):
        raise HTTPException(status_code = 500, detail = "Could not delete the video job.")
    return {"deleted": True}


@router.delete("/video/gallery")
async def clear_gallery_videos(current_subject: str = Depends(get_current_subject)):
    from core.inference import video_gallery
    from core.inference.gallery_flags import FlagsUnavailable

    try:
        cleared = await asyncio.to_thread(video_gallery.clear, return_ids = True)
    except FlagsUnavailable as exc:
        # Refuse rather than delete the archive we cannot prove is archived.
        logger.warning("video_gallery.clear_blocked: %s", exc)
        raise HTTPException(
            status_code = 503,
            detail = "Could not read the gallery's pin/archive data, so clearing was stopped to "
            "avoid deleting archived videos.",
        )
    # Clear-all takes the terminal record's clip with it whatever its id.
    _forget_terminal_video(None)
    failed = await asyncio.to_thread(_forget_openai_jobs, cleared)
    if failed:
        raise HTTPException(status_code = 500, detail = "Could not delete every video job.")
    return {"removed": len(cleared)}


_VIDEO_SIZE_RE = _re.compile(r"^(\d{1,5})\s*x\s*(\d{1,5})$")
_VIDEO_SECONDS_MAX = 120.0
_VIDEO_JOB_ID_PREFIX = "video_"
_MAX_REMEMBERED_JOBS = 256
_VIDEO_POLL_AFTER_MS = "2000"
_NO_VIDEO_MODEL_MSG = "No video model loaded. Load a video model first."
_VIDEO_FAILED_CODE = "video_generation_failed"
_VIDEO_CREATE_FIELDS = (
    "prompt",
    "model",
    "seconds",
    "size",
    "seed",
    "negative_prompt",
    "steps",
    "guidance",
    "num_frames",
    "fps",
    "last_frame",
)
_VIDEO_CREATE_LISTS = ("reference_images", "reference_audios")
# VideoJobCreateRequest's list limits, checked before multipart files are encoded.
_VIDEO_CREATE_LIST_MAX = {"reference_images": 9, "reference_audios": 3}
_VIDEO_IMAGE_DECODE_CACHE_MAX_BYTES = 64 * 1024 * 1024
# The OpenAI SDK flattens a list of objects to key[][field]; each such part is one item.
_OBJECT_PART = {
    "reference_images": _re.compile(r"reference_images(?:\[\d*\])?\[(image_url|file_id)\]"),
    "reference_audios": _re.compile(r"reference_audios(?:\[\d*\])?\[(input_id|clip_id|voice_id)\]"),
}
# A reference audio rides as base64 in a field capped at 32 MiB, which is 24 MiB of audio.
_VIDEO_REFERENCE_AUDIO_MAX_BYTES = 24 * 1024 * 1024
# Upper bound on how long DELETE waits for a cancelled run to stop writing.
_DELETE_SETTLE_TIMEOUT_S = 10.0


@dataclass
class _VideoJob:
    id: str
    created_at: int
    prompt: str
    model: str
    size: str
    seconds: str
    seed: Optional[int] = None
    status: str = "queued"
    progress: int = 0
    completed_at: Optional[int] = None
    error: Optional[dict] = None

    @property
    def terminal(self) -> bool:
        return self.status in ("completed", "failed")


_jobs: dict[str, _VideoJob] = {}
_jobs_lock = threading.Lock()
_managed_jobs: dict[str, dict[str, _VideoJob]] = {}


def _account_jobs() -> dict[str, _VideoJob]:
    """Called under _jobs_lock; the owner's registry and ids stay unchanged."""
    if is_owner_context():
        return _jobs
    return _managed_jobs.setdefault(current_account_id(), {})


def _forget_openai_job(video_id: str) -> bool:
    """Forget disk and memory state without letting a stale poll save between them."""
    from core.inference import video_gallery

    with _jobs_lock:
        if not video_gallery.forget_job(video_id):
            return False
        _account_jobs().pop(video_id, None)
    return True


def _forget_openai_jobs(video_ids: list[str]) -> list[str]:
    failed = []
    for video_id in video_ids:
        if not _forget_openai_job(video_id):
            failed.append(video_id)
    return failed


def _openai_video_error(
    status: int,
    message: str,
    *,
    code: Optional[str] = None,
    param: Optional[str] = None,
) -> HTTPException:
    return HTTPException(
        status_code = status,
        detail = openai_error_body(message, status = status, code = code, param = param),
    )


def _not_found(video_id: str) -> HTTPException:
    return _openai_video_error(
        404, f"No video found with id '{video_id[:128]}'.", code = "video_not_found", param = "video_id"
    )


def _parse_openai_video_size(size: Optional[str]) -> Optional[tuple[int, int]]:
    text = (size or "").strip().lower()
    if text in ("", "auto"):
        return None
    match = _VIDEO_SIZE_RE.match(text)
    if not match:
        raise ValueError("size must be '<width>x<height>', e.g. '768x512'.")
    width, height = int(match.group(1)), int(match.group(2))
    for label, value in (("width", width), ("height", height)):
        if not 32 <= value <= 2048:
            raise ValueError(f"size {label} must be between 32 and 2048.")
    return width, height


def _parse_openai_video_seconds(seconds: Optional[str]) -> Optional[float]:
    text = (seconds or "").strip().lower()
    if text in ("", "auto"):
        return None
    try:
        value = float(text)
    except ValueError:
        raise ValueError("seconds must be a number of seconds, e.g. '4'.") from None
    if value != value or not 0 < value <= _VIDEO_SECONDS_MAX:
        raise ValueError(f"seconds must be between 0 and {_VIDEO_SECONDS_MAX:g}.")
    return value


def _frames_for_seconds(seconds: float, defaults: dict) -> int:
    fps = int(defaults.get("fps") or 24)
    step = max(1, int(defaults.get("frame_step") or 1))
    offset = max(1, int(defaults.get("frame_offset") or 1))
    wanted = max(offset, int(round(seconds * fps)))
    k = max(1, int(round((wanted - offset) / step)))
    return k * step + offset


def _refuse_fixed_fps(
    family: Optional[str], default_fps: Optional[int], fps: Optional[int]
) -> None:
    """MiniMax-H3 always writes its clip at the family rate, so another fps would only skew the frame count."""
    if family == "minimax-h3" and fps is not None and default_fps and fps != int(default_fps):
        raise _openai_video_error(
            400,
            f"MiniMax-H3 renders at a fixed {int(default_fps)} fps; leave fps out.",
            param = "fps",
        )


def _format_seconds(value: float) -> str:
    return f"{round(float(value), 2):g}"


def _record_epoch(record: dict) -> int:
    raw = record.get("created_at")
    if isinstance(raw, (int, float)):
        return int(raw)
    if isinstance(raw, str):
        try:
            parsed = datetime.fromisoformat(raw.strip().replace("Z", "+00:00"))
        except ValueError:
            return 0
        if parsed.tzinfo is None:
            parsed = parsed.replace(tzinfo = timezone.utc)
        return int(parsed.timestamp())
    return 0


_IMAGE_MAGIC = (
    (b"\x89PNG\r\n\x1a\n", "image/png"),
    (b"\xff\xd8\xff", "image/jpeg"),
    (b"GIF87a", "image/gif"),
    (b"GIF89a", "image/gif"),
    (b"BM", "image/bmp"),
)


def _sniff_image_type(data: bytes) -> Optional[str]:
    for magic, mime in _IMAGE_MAGIC:
        if data.startswith(magic):
            return mime
    if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
        return "image/webp"
    return None


def _valid_gallery_video_record(record: dict) -> bool:
    try:
        GalleryVideo(**record)
    except ValidationError:
        return False
    return True


def _record_to_job(record: dict, job: Optional[_VideoJob] = None) -> VideoJob:
    saved_at = _record_epoch(record)
    created = job.created_at if job is not None else saved_at
    completed = (job.completed_at if job is not None else None) or saved_at or created
    return VideoJob(
        id = record["id"],
        model = public_model_id(
            str(record.get("model") or (job.model if job is not None else "") or "video")
        ),
        status = "completed",
        progress = 100,
        created_at = created,
        completed_at = completed,
        prompt = record.get("prompt"),
        size = f"{record.get('width')}x{record.get('height')}",
        seconds = _format_seconds(record.get("duration_s") or 0.0),
        seed = _record_seed(record, job),
    )


def _record_seed(record: dict, job: Optional[_VideoJob]) -> Optional[int]:
    """The seed the engine saved with the clip, else the one the job was created with."""
    seed = record.get("seed")
    if isinstance(seed, int) and not isinstance(seed, bool):
        return seed
    return job.seed if job is not None else None


def _job_to_openai(job: _VideoJob) -> VideoJob:
    return VideoJob(
        id = job.id,
        model = job.model,
        status = job.status,  # type: ignore[arg-type]
        progress = job.progress,
        created_at = job.created_at,
        completed_at = job.completed_at,
        prompt = job.prompt,
        size = job.size,
        seconds = job.seconds,
        seed = job.seed,
        error = VideoJobError(**job.error) if job.error else None,
    )


def _remember_job(job: _VideoJob) -> None:
    from core.inference import video_gallery

    with _jobs_lock:
        pending = [existing for existing in _account_jobs().values() if not existing.terminal]
    for existing in pending:
        persisted = _job_from_record(video_gallery.get_job(existing.id) or {})
        if persisted is not None and persisted.terminal:
            with _jobs_lock:
                if _account_jobs().get(existing.id) is existing:
                    _account_jobs()[existing.id] = persisted
    with _jobs_lock:
        _account_jobs()[job.id] = job
        excess = len(_account_jobs()) - _MAX_REMEMBERED_JOBS
        if excess > 0:
            for stale in [j for j in _account_jobs().values() if j.terminal][:excess]:
                _account_jobs().pop(stale.id, None)
        try:
            video_gallery.save_job(job.id, asdict(job))
        except OSError as exc:
            logger.warning("openai_videos.persist_job_failed: %s", exc)


def _job_from_record(record: dict) -> Optional[_VideoJob]:
    from core.inference.video_families import VIDEO_CANCELLED_MSG
    try:
        stored = dict(record)
        outcome = stored.pop("_worker_outcome", None)
        job = _VideoJob(**stored)
        if isinstance(outcome, dict):
            message = outcome.get("error")
            job.completed_at = int(outcome.get("completed_at") or job.completed_at or 0) or None
            if message is None:
                job.status, job.progress, job.error = "completed", 100, None
            else:
                message = str(message)
                job.status, job.progress = "failed", 0
                job.error = {
                    "code": "cancelled" if message == VIDEO_CANCELLED_MSG else _VIDEO_FAILED_CODE,
                    "message": message,
                }
        if job.status not in ("queued", "in_progress", "completed", "failed"):
            return None
        _job_to_openai(job)
    except (TypeError, ValueError, OverflowError, ValidationError):
        return None
    return job


def _hydrate_job(video_id: str) -> None:
    from core.inference import video_gallery
    with _jobs_lock:
        if video_id in _account_jobs():
            return
        job = _job_from_record(video_gallery.get_job(video_id) or {})
        if job is not None:
            _account_jobs().setdefault(job.id, job)


def _hydrate_jobs() -> list[_VideoJob]:
    from core.inference import video_gallery
    with _jobs_lock:
        jobs = [
            job for raw in video_gallery.list_jobs() if (job := _job_from_record(raw)) is not None
        ]
        jobs.sort(key = lambda job: job.created_at, reverse = True)
        for job in jobs[:_MAX_REMEMBERED_JOBS]:
            _account_jobs().setdefault(job.id, job)
    return jobs


def _sync_jobs() -> None:
    from core.inference import video_gallery
    from core.inference.video import get_video_backend
    from core.inference.video_families import VIDEO_CANCELLED_MSG

    with _jobs_lock:
        open_jobs = [job for job in _account_jobs().values() if not job.terminal]
    if not open_jobs:
        return
    gen = get_video_backend().generate_progress()
    now = int(_time.time())
    for job in open_jobs:
        persisted_job = _job_from_record(video_gallery.get_job(job.id) or {})
        if persisted_job is not None and persisted_job.terminal:
            with _jobs_lock:
                if _account_jobs().get(job.id) is job:
                    _account_jobs()[job.id] = persisted_job
            continue
        status: Optional[str] = None
        progress = 0
        completed_at: Optional[int] = None
        error: Optional[dict] = None
        if gen.get("video_id") == job.id:
            phase = gen.get("phase")
            if phase == "queued":
                status = "queued"
            elif phase in ("denoise", "export") or gen.get("active"):
                fraction = float(gen.get("fraction") or 0.0)
                status = "in_progress"
                progress = 99 if phase == "export" else max(0, min(99, int(fraction * 100)))
            elif phase == "completed":
                status, progress, completed_at = "completed", 100, now
            elif phase == "failed":
                message = str(gen.get("error") or "Video generation failed.")
                status = "failed"
                error = {
                    "code": "cancelled" if message == VIDEO_CANCELLED_MSG else _VIDEO_FAILED_CODE,
                    "message": message,
                }
        if status is None:
            if video_gallery.owned_video_path(job.id) is not None:
                status, progress, completed_at = "completed", 100, now
            else:
                status = "failed"
                error = {
                    "code": _VIDEO_FAILED_CODE,
                    "message": "The generation ended before a clip was saved.",
                }
        with _jobs_lock:
            if _account_jobs().get(job.id) is not job:
                continue
            if job.terminal:
                continue
            if job.status == "in_progress" and status == "queued":
                continue
            if job.status == "in_progress" and status == "in_progress":
                progress = max(job.progress, progress)
            job.status = status
            job.progress = progress
            if completed_at is not None:
                job.completed_at = completed_at
            if error is not None:
                job.error = error
            persisted = asdict(job)
            try:
                video_gallery.save_job(job.id, persisted)
            except OSError as exc:
                logger.warning("openai_videos.persist_job_failed: %s", exc)


def _await_generate_settled(video_id: str, timeout: float = _DELETE_SETTLE_TIMEOUT_S) -> bool:
    """False if the run is still live at timeout; never report deletion or the clip reappears."""
    from core.inference.video import get_video_backend

    backend = get_video_backend()
    deadline = _time.monotonic() + timeout
    while _time.monotonic() < deadline:
        gen = backend.generate_progress()
        if gen.get("video_id") != video_id or not gen.get("active"):
            return True
        _time.sleep(0.05)
    return False


def _lookup_video(video_id: str) -> Optional[VideoJob]:
    from core.inference import video_gallery

    queued = _own_queued_video(video_id)
    if queued is not None:
        return _queued_video_job(queued)
    _hydrate_job(video_id)
    _sync_jobs()
    with _jobs_lock:
        job = _account_jobs().get(video_id)
    if job is not None and job.status != "completed":
        return _job_to_openai(job)
    record = video_gallery.get_record(video_id)
    if record is None:
        return None
    return _record_to_job(record, job)


def _all_videos() -> list[VideoJob]:
    from core.inference import video_gallery

    persisted_jobs = _hydrate_jobs()
    _sync_jobs()
    with _jobs_lock:
        jobs = {job.id: job for job in persisted_jobs}
        jobs.update(_account_jobs())
    records = video_gallery.list_videos(None, 0, valid = _valid_gallery_video_record)
    records.extend(
        video_gallery.list_videos(None, 0, valid = _valid_gallery_video_record, archived = True)
    )
    listed = [_record_to_job(record, jobs.get(record["id"])) for record in records]
    seen = {video.id for video in listed}
    listed.extend(
        _job_to_openai(job)
        for job in jobs.values()
        if job.id not in seen and job.status != "completed"
    )
    seen.update(video.id for video in listed)
    listed.extend(video for video in _own_queued_videos() if video.id not in seen)
    return listed


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"


async def _read_video_create_body(request: Request) -> tuple[dict, Any]:
    ctype = (request.headers.get("content-type") or "").lower()
    if ctype.startswith(("multipart/form-data", "application/x-www-form-urlencoded")):
        try:
            form = await request.form()
        except Exception:  # noqa: BLE001
            raise _openai_video_error(400, "Could not parse the multipart form body.")
        fields = {key: form.get(key) for key in _VIDEO_CREATE_FIELDS if key in form}
        for key in _VIDEO_CREATE_LISTS:
            # In wire order across both spellings: <Picture n> follows the order sent.
            items = []
            for name, value in form.multi_items():
                if name in (key, f"{key}[]"):
                    items.append(value)
                elif match := _OBJECT_PART[key].fullmatch(name):
                    items.append({match.group(1): value})
            if len(items) > _VIDEO_CREATE_LIST_MAX[key]:
                raise _openai_video_error(
                    400, f"{key}: send at most {_VIDEO_CREATE_LIST_MAX[key]}.", param = key
                )
            if items:
                fields[key] = items
        if "last_frame" not in fields and (nested := _nested_image_ref(form, "last_frame")):
            fields["last_frame"] = nested
        reference = form.get("input_reference")
        if reference is None:
            reference = _nested_image_ref(form, "input_reference")
        return await _media_fields(fields), reference
    try:
        data = await request.json()
    except Exception:  # noqa: BLE001
        raise _openai_video_error(400, "Request body must be JSON or multipart/form-data.")
    if not isinstance(data, dict):
        raise _openai_video_error(400, "Request body must be a JSON object.")
    fields = {
        key: data.get(key) for key in _VIDEO_CREATE_FIELDS + _VIDEO_CREATE_LISTS if key in data
    }
    return await _media_fields(fields), data.get("input_reference")


def _nested_image_ref(form, key: str) -> Optional[dict]:
    nested = {
        field: form.get(f"{key}[{field}]")
        for field in ("image_url", "file_id")
        if f"{key}[{field}]" in form
    }
    return nested or None


async def _media_fields(fields: dict) -> dict:
    """last_frame, reference_images and uploaded reference_audios as the data URLs the engine takes.
    Audio given as a string or an Unsloth Studio audio id is left for validation and resolution."""
    if fields.get("last_frame") is not None:
        fields["last_frame"] = await _reference_to_data_url(
            fields["last_frame"], param = "last_frame"
        )
    images = fields.get("reference_images")
    if isinstance(images, list):
        fields["reference_images"] = [
            await _reference_to_data_url(item, param = f"reference_images[{index}]")
            for index, item in enumerate(images)
        ]
    audios = fields.get("reference_audios")
    if isinstance(audios, list):
        for index, item in enumerate(audios):
            if isinstance(item, UploadFile):
                audios[index] = await _audio_upload_to_data_url(item, f"reference_audios[{index}]")
            elif isinstance(item, str) and item.lstrip().startswith("{"):
                # A multipart part can only carry an id object as JSON text.
                try:
                    audios[index] = json.loads(item)
                except ValueError:
                    pass
    return fields


async def _audio_upload_to_data_url(upload: UploadFile, name: str) -> str:
    data = await upload.read(_VIDEO_REFERENCE_AUDIO_MAX_BYTES + 1)
    if not data:
        raise _openai_video_error(400, f"{name} is empty.", param = "reference_audios")
    if len(data) > _VIDEO_REFERENCE_AUDIO_MAX_BYTES:
        raise _openai_video_error(
            400, f"{name} is too large; the limit is 24 MB.", param = "reference_audios"
        )
    content_type = (upload.content_type or "").split(";")[0].strip().lower()
    if not content_type.startswith("audio/"):
        content_type = "application/octet-stream"
    return f"data:{content_type};base64,{base64.b64encode(data).decode('ascii')}"


def _audio_ref_data_url(ref) -> str:
    """An Unsloth Studio audio id as a data URL, resolved in the caller's account."""
    import mimetypes

    from core.inference import audio_inputs

    source = audio_inputs.resolve_source(ref.model_dump(exclude_none = True))
    # Stored audio can reach 200 MB, so size it before reading it into memory.
    if source.path.stat().st_size > _VIDEO_REFERENCE_AUDIO_MAX_BYTES:
        raise audio_inputs.AudioInputError(
            400, "This audio is too large for a video reference; the limit is 24 MB."
        )
    data = source.path.read_bytes()
    suffix = source.path.suffix.lower()
    mime = "audio/wav" if suffix == ".wav" else mimetypes.guess_type(source.path.name)[0]
    return (
        f"data:{mime or 'application/octet-stream'};base64,{base64.b64encode(data).decode('ascii')}"
    )


def _refuse_unreadable_audio(audios: Optional[list[str]]):
    """Decode each reference audio the engine would, refusing one it could not read.

    Returns the decoded audios for this request's render to reuse, or None when nothing was decoded."""
    if not audios:
        return None
    from core.inference.video import _decode_b64_media

    try:
        from core.inference.video_minimax_h3 import (
            DecodedReferenceAudios,
            decode_h3_reference_audio,
        )
    except ImportError:  # no media decoder here; begin_generate reports it
        return None
    decoded = []
    for index, item in enumerate(audios):
        try:
            decoded.append(decode_h3_reference_audio(_decode_b64_media(item)))
        except ImportError:
            return None
        except Exception:  # noqa: BLE001 -- any decode failure is client input feedback
            raise _openai_video_error(
                400, f"reference_audios[{index}] is not readable audio.", param = "reference_audios"
            )
    return DecodedReferenceAudios(sources = tuple(audios), decoded = tuple(decoded))


def _conditioning_param(
    body: VideoJobCreateRequest,
    reference: Optional[str],
    default: Optional[str] = None,
) -> Optional[str]:
    """The one conditioning field a request carries, to name it in a refusal: ``default`` for none, None for several."""
    given = [
        name
        for name, value in (
            ("input_reference", reference),
            ("last_frame", body.last_frame),
            ("reference_images", body.reference_images),
            ("reference_audios", body.reference_audios),
        )
        if value
    ]
    if not given:
        return default
    return given[0] if len(given) == 1 else None


def _validate_create_fields(fields: dict) -> VideoJobCreateRequest:
    try:
        return VideoJobCreateRequest(**fields)
    except ValidationError as exc:
        errors = exc.errors()
        first = errors[0] if errors else {}
        loc = first.get("loc") or ()
        param = str(loc[0]) if loc else None
        message = str(first.get("msg") or "Invalid request.")
        raise _openai_video_error(400, f"{param}: {message}" if param else message, param = param)


async def _reference_to_data_url(reference: Any, param: str = "input_reference") -> Optional[str]:
    if reference is None:
        return None
    if isinstance(reference, dict):
        if reference.get("file_id"):
            raise _openai_video_error(
                400,
                f"{param}.file_id is not supported; send the image as a file upload or a base64 data URL.",
                param = param,
            )
        reference = reference.get("image_url")
        if reference is None:
            return None
    if isinstance(reference, UploadFile):
        data = await reference.read(VIDEO_INPUT_REFERENCE_MAX_BYTES + 1)
        if not data:
            raise _openai_video_error(400, f"{param} is empty.", param = param)
        if len(data) > VIDEO_INPUT_REFERENCE_MAX_BYTES:
            raise _openai_video_error(
                400,
                f"{param} is too large; the limit is {VIDEO_INPUT_REFERENCE_MAX_BYTES // (1024 * 1024)} MB.",
                param = param,
            )
        content_type = (reference.content_type or "").split(";")[0].strip().lower()
        sniffed = _sniff_image_type(data)
        if not content_type.startswith("image/"):
            if sniffed is None:
                raise _openai_video_error(400, f"{param} must be an image.", param = param)
            content_type = sniffed
        encoded = base64.b64encode(data).decode("ascii")
        return f"data:{content_type};base64,{encoded}"
    if isinstance(reference, str):
        text = reference.strip()
        if not text:
            return None
        if text.lower().startswith(("http://", "https://")):
            raise _openai_video_error(
                400,
                f"Remote {param} URLs are not fetched; send the image as a file upload or a base64 data URL.",
                param = param,
            )
        return text
    raise _openai_video_error(
        400, f"{param} must be an image file or a base64 data URL.", param = param
    )


@openai_router.post("/videos", response_model = VideoJob)
@account_access.gpu_busy_route
async def openai_create_video(
    request: Request,
    current_subject: str = Depends(get_current_subject),
    hf_token: Optional[str] = Depends(get_hf_token),
):
    # The body must be parsed before the monitor row can name the model.
    from routes.inference import _monitored_media_request

    fields, raw_reference = await _read_video_create_body(request)
    body = _validate_create_fields(fields)
    reference = await _reference_to_data_url(raw_reference)
    from core.inference.api_monitor import api_monitor

    async with _monitored_media_request(
        request,
        model = public_model_id(body.model) or body.model or "",
        prompt = body.prompt,
        subject = current_subject,
    ) as monitor_id:
        inputs = await _validated_video_inputs(body, reference)
        job = await _create_or_queue_openai_video(
            body, reference, inputs, current_subject, hf_token
        )
        api_monitor.relabel(monitor_id, job.model)
        return job


@dataclass
class _VideoCreateInputs:
    size: Optional[tuple[int, int]]
    seconds: Optional[float]
    reference_audios: Optional[list[str]]
    decoded_images: Optional[Any] = _dc_field(default = None, compare = False, repr = False)


async def _validated_video_inputs(
    body: VideoJobCreateRequest, reference: Optional[str]
) -> _VideoCreateInputs:
    try:
        size = _parse_openai_video_size(body.size)
    except ValueError as exc:
        raise _openai_video_error(400, str(exc), param = "size")
    try:
        seconds = _parse_openai_video_seconds(body.seconds)
    except ValueError as exc:
        raise _openai_video_error(400, str(exc), param = "seconds")
    if reference is not None and body.reference_images:
        raise _openai_video_error(
            400,
            "input_reference cannot be combined with reference_images; send that image as a reference_images entry.",
            param = "reference_images",
        )
    if body.reference_audios and not body.reference_images and reference is None:
        raise _openai_video_error(
            400,
            "reference audio needs at least one reference image or video to go with",
            param = "reference_audios",
        )
    reference_audios: Optional[list[str]] = None
    if body.reference_audios:
        from core.inference.audio_inputs import AudioInputError

        # Resolved while the resident model is still loaded, so a bad id costs no switch.
        try:
            reference_audios = [
                item
                if isinstance(item, str)
                else await asyncio.to_thread(_audio_ref_data_url, item)
                for item in body.reference_audios
            ]
        except AudioInputError as exc:
            raise _openai_video_error(exc.status, exc.detail, param = "reference_audios")
    images = [("input_reference", reference), ("last_frame", body.last_frame)]
    images += [("reference_images", item) for item in body.reference_images or []]
    decoded_images = []
    decoded_bytes = 0
    for param, image in images:
        if image is None:
            continue
        # Validate before switching; task-specific limits apply during resolution.
        from core.inference.diffusion import decode_b64_image_sized
        from core.inference.video_minimax_h3 import (
            H3_REF_IMAGE_SOURCE_MAX_PIXELS,
            H3_REF_IMAGE_SOURCE_MAX_SIDE,
        )

        try:
            decoded, stored_size = await asyncio.to_thread(
                decode_b64_image_sized,
                image,
                mode = "RGB",
                max_side = H3_REF_IMAGE_SOURCE_MAX_SIDE,
                max_pixels = H3_REF_IMAGE_SOURCE_MAX_PIXELS,
            )
        except Exception:  # noqa: BLE001 -- any decode failure is client input feedback
            raise _openai_video_error(400, f"{param} is not a readable image.", param = param)
        if decoded_images is not None:
            decoded_bytes += 4 * decoded.width * decoded.height
            if decoded_bytes <= _VIDEO_IMAGE_DECODE_CACHE_MAX_BYTES:
                decoded_images.append((image, stored_size, decoded))
            else:
                decoded_images = None
        del decoded
    from core.inference.video_minimax_h3 import DecodedReferenceImages

    return _VideoCreateInputs(
        size = size,
        seconds = seconds,
        reference_audios = reference_audios,
        decoded_images = DecodedReferenceImages(tuple(decoded_images)) if decoded_images else None,
    )


def _new_video_id() -> str:
    return _VIDEO_JOB_ID_PREFIX + uuid.uuid4().hex


def _video_seed(body: VideoJobCreateRequest) -> int:
    return body.seed if body.seed is not None else _secrets.randbelow(2**53)


async def _create_openai_video(
    body: VideoJobCreateRequest,
    reference: Optional[str],
    current_subject: str,
    hf_token: Optional[str],
):
    inputs = await _validated_video_inputs(body, reference)
    return await _start_openai_video(
        body,
        reference,
        inputs,
        current_subject,
        hf_token,
        video_id = _new_video_id(),
        seed = _video_seed(body),
    )


def _refuse_family_inputs(
    fam,
    h3_task,
    body: VideoJobCreateRequest,
    reference: Optional[str],
    inputs: "_VideoCreateInputs",
) -> None:
    from core.inference.video import assert_first_frame_pipeline_available
    from core.inference.video_families import (
        validate_video_keyframe_conditioning,
        validate_video_reference_conditioning,
        validate_video_request_shape,
    )
    from core.inference.video_minimax_h3 import H3_TASK_REFERENCES

    width, height = inputs.size if inputs.size is not None else (None, None)
    seconds = inputs.seconds
    _refuse_fixed_fps(fam.name, fam.default_fps, body.fps)
    # Judge seconds against the target family's lattice now: None deferred the refusal until after the target loaded.
    want_frames = (
        body.num_frames
        if body.num_frames is not None
        else _frames_for_seconds(
            seconds,
            {
                "fps": body.fps or fam.default_fps,
                "frame_step": fam.frame_step,
                "frame_offset": fam.frame_offset,
            },
        )
        if seconds is not None
        else None
    )
    validate_video_request_shape(fam, width, height, want_frames, fps = body.fps)
    ref2va = h3_task == H3_TASK_REFERENCES
    validate_video_keyframe_conditioning(
        fam,
        h3_task,
        has_keyframes = (reference is not None and not ref2va) or bool(body.last_frame),
        has_last_frame = bool(body.last_frame),
    )
    if reference is not None and not ref2va:
        assert_first_frame_pipeline_available(fam)
    validate_video_reference_conditioning(
        fam,
        h3_task,
        has_references = (reference is not None and ref2va)
        or bool(body.reference_images or inputs.reference_audios),
    )


class _QueuedAccountDisabled(Exception):
    pass


def _begin_video_generate(backend, queued_account: Optional[AccountContext], kwargs: dict):
    if queued_account is None:
        return backend.begin_generate(**kwargs)

    def _still_active() -> None:
        if not _queued_account_active(queued_account):
            raise _QueuedAccountDisabled()

    _still_active()
    return backend.begin_generate(**kwargs, before_commit = _still_active)


async def _start_openai_video(
    body: VideoJobCreateRequest,
    reference: Optional[str],
    inputs: _VideoCreateInputs,
    current_subject: str,
    hf_token: Optional[str],
    *,
    video_id: str,
    seed: int,
    created_at: Optional[int] = None,
    queued_account: Optional[AccountContext] = None,
):
    from core.inference.gpu_arbiter import VIDEO
    from core.inference.media_auto_switch import (
        maybe_auto_switch_media_model,
        resident_answers_media_request,
    )
    from core.inference.video import get_video_backend, video_failure_detail
    from core.inference.video_families import (
        VIDEO_GENERATION_BUSY_MSG,
        VIDEO_MODEL_CHANGED_MSG,
        VIDEO_NOT_LOADED_MSG,
        VideoShapeError,
    )
    from utils.openai_auto_switch_settings import get_media_auto_switch_enabled

    size, seconds, reference_audios = inputs.size, inputs.seconds, inputs.reference_audios
    width, height = size if size is not None else (None, None)
    audio_checked = [False]
    decoded_audios = [None]

    def _refuse_unservable_request(pick) -> None:
        from core.inference.media_model_index import expected_partition
        from core.inference.video import _detect_load_family

        # Release pixels before loading another model.
        inputs.decoded_images = None
        fam = _detect_load_family(pick.model_path, pick.gguf_filename, None)
        if fam is None:
            return
        _refuse_family_inputs(fam, expected_partition(pick), body, reference, inputs)
        # Decoded here, like the images above, so unreadable audio never costs a switch.
        decoded_audios[0] = _refuse_unreadable_audio(reference_audios)
        audio_checked[0] = True

    pin_requested_model = bool(
        isinstance(body.model, str) and body.model.strip() and get_media_auto_switch_enabled()
    )
    try:
        await maybe_auto_switch_media_model(
            body.model,
            owner = VIDEO,
            current_subject = current_subject,
            openai_errors = True,
            hf_token = hf_token,
            before_switch = _refuse_unservable_request,
        )
    except VideoShapeError as exc:
        raise _openai_video_error(400, str(exc), param = _shape_error_param(exc, body))
    except ValueError as exc:
        raise _openai_video_error(
            400, str(exc), param = _conditioning_param(body, reference, "input_reference")
        )
    if not audio_checked[0]:
        # No switch ran the check, and the engine's own decode can fail with more than ValueError.
        decoded_audios[0] = await asyncio.to_thread(_refuse_unreadable_audio, reference_audios)

    backend = get_video_backend()
    # Managed callers are authorized against the exact resident state, pinned to the reservation;
    # on a mismatch, re-authorize once and retry, as /video/generate does.
    # An explicit fps is judged against the family, so it is pinned to the state it was judged on.
    pin_state = pin_requested_model or account_access.managed_account() or body.fps is not None
    for attempt in range(2):
        expected_state = None
        if pin_state:
            status, expected_state = await asyncio.to_thread(backend.generation_snapshot)
            if pin_requested_model and not await asyncio.to_thread(
                resident_answers_media_request, status, body.model, owner = VIDEO
            ):
                raise _openai_video_error(
                    409,
                    VIDEO_MODEL_CHANGED_MSG,
                    code = "model_changed",
                    param = "model",
                )
        else:
            status = await asyncio.to_thread(backend.status)
        if not status.get("loaded"):
            raise HTTPException(
                status_code = 503,
                detail = _NO_VIDEO_MODEL_MSG,
                headers = problem_headers("not_loaded", kind = "video"),
            )
        if account_access.managed_account():
            await asyncio.to_thread(account_access.require_media_generation_access, status, "video")
        defaults = status.get("defaults") or {}
        # The pinned snapshot names no family, so read it off the state it pinned.
        family = status.get("family") or getattr(
            getattr(expected_state, "family", None), "name", None
        )
        _refuse_fixed_fps(family, defaults.get("fps"), body.fps)
        num_frames = (
            _frames_for_seconds(seconds, defaults) if seconds is not None else body.num_frames
        )
        try:
            generate_kwargs = dict(
                prompt = body.prompt,
                width = width,
                height = height,
                duration_s = seconds,
                input_reference = reference,
                video_id = video_id,
                seed = seed,
            )
            controls = dict(
                negative_prompt = body.negative_prompt,
                steps = body.steps,
                guidance = body.guidance,
                num_frames = body.num_frames,
                fps = body.fps,
                last_frame = body.last_frame,
                reference_images = body.reference_images,
                reference_audios = reference_audios,
            )
            generate_kwargs.update({k: v for k, v in controls.items() if v is not None})
            if decoded_audios[0] is not None:
                generate_kwargs["decoded_reference_audios"] = decoded_audios[0]
            if inputs.decoded_images is not None:
                generate_kwargs["decoded_reference_images"] = inputs.decoded_images
            if expected_state is not None:
                generate_kwargs["expected_state"] = expected_state
            resolved = await asyncio.to_thread(
                _begin_video_generate, backend, queued_account, generate_kwargs
            )
        except VideoShapeError as exc:
            raise _openai_video_error(400, str(exc), param = _shape_error_param(exc, body))
        except ValueError as exc:
            raise _openai_video_error(400, str(exc), param = _conditioning_param(body, reference))
        except RuntimeError as exc:
            msg = str(exc)
            if msg == VIDEO_NOT_LOADED_MSG:
                raise HTTPException(
                    status_code = 503,
                    detail = _NO_VIDEO_MODEL_MSG,
                    headers = problem_headers("not_loaded", kind = "video"),
                )
            if msg == VIDEO_GENERATION_BUSY_MSG:
                raise _openai_video_error(409, msg)
            if msg == VIDEO_MODEL_CHANGED_MSG:
                if attempt == 0:
                    continue
                raise _openai_video_error(409, msg, code = "model_changed", param = "model")
            logger.error("openai_videos.generate_failed: %s", exc, exc_info = True)
            raise HTTPException(status_code = 500, detail = video_failure_detail(exc))
        break

    _note_generation_account()
    reset_media_generation_progress("video")

    # Use begin_generate's resolved canvas; reference-image requests render at source aspect.
    if isinstance(resolved, dict) and resolved.get("width") and resolved.get("height"):
        width, height = int(resolved["width"]), int(resolved["height"])
    else:
        presets = defaults.get("resolution_presets") or []
        if size is None and presets:
            width, height = int(presets[0][0]), int(presets[0][1])
    # Prefer what begin_generate reserved: a concurrent load can swap the family under status().
    reserved = resolved if isinstance(resolved, dict) else {}
    run_frames = reserved.get("num_frames") or num_frames
    fps = reserved.get("fps") or defaults.get("fps")
    if run_frames and fps:
        seconds_text = _format_seconds(int(run_frames) / float(fps))
    elif seconds is None and defaults.get("num_frames") and fps:
        seconds_text = _format_seconds(int(defaults["num_frames"]) / float(fps))
    else:
        seconds_text = body.seconds or "auto"
    job = _VideoJob(
        id = video_id,
        created_at = created_at if created_at is not None else int(_time.time()),
        prompt = body.prompt,
        model = public_model_id(
            str(reserved.get("model") or status.get("repo_id") or body.model or "video")
        ),
        size = f"{width}x{height}" if width and height else "auto",
        seconds = seconds_text,
        seed = seed,
    )
    _remember_job(job)
    return _job_to_openai(job)


VIDEO_QUEUE_POLL_S = 2.0
VIDEO_QUEUE_MAX = 64
VIDEO_QUEUE_MAX_PER_ACCOUNT = 32
VIDEO_QUEUE_IDLE_CONFLICTS = 12
_VIDEO_WAIT_CODES = ("model_busy", "model_loading", "gpu_busy")


@dataclass
class _QueuedVideo:
    id: str
    account: AccountContext
    subject: str
    hf_token: Optional[str]
    body: VideoJobCreateRequest
    reference: Optional[str]
    inputs: _VideoCreateInputs
    seed: int
    created_at: int
    model: str
    size: str
    seconds: str
    starting: bool = False
    idle_conflicts: int = 0


_VIDEO_QUEUE: list[_QueuedVideo] = []
_video_drainer: Optional[asyncio.Task] = None
_video_start_locks: "weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock]" = (
    weakref.WeakKeyDictionary()
)


def _video_start_lock() -> asyncio.Lock:
    loop = asyncio.get_running_loop()
    lock = _video_start_locks.get(loop)
    if lock is None:
        lock = _video_start_locks[loop] = asyncio.Lock()
    return lock


def _video_engine_busy() -> bool:
    from core.inference.video import get_video_backend

    backend = get_video_backend()
    progress = backend.generate_progress() or {}
    return bool(progress.get("active")) or bool(backend.loading_repo_ids())


def _refusal_error(exc: BaseException) -> dict:
    from core.inference.gpu_arbiter import GpuBusyForAnotherAccountError

    if isinstance(exc, GpuBusyForAnotherAccountError):
        return {"code": "gpu_busy", "message": str(exc)}
    if isinstance(exc, HTTPException):
        detail = exc.detail
        if isinstance(detail, dict) and isinstance(detail.get("error"), dict):
            return {
                "code": detail["error"].get("code"),
                "message": str(detail["error"].get("message") or "Video generation failed."),
            }
        if isinstance(detail, dict):
            return {"code": detail.get("error"), "message": str(detail.get("message") or "")}
        return {"code": None, "message": str(detail)}
    return {"code": None, "message": "Video generation failed."}


def _video_wait(exc: BaseException) -> Optional[str]:
    from core.inference.gpu_arbiter import GpuBusyForAnotherAccountError
    from core.inference.video_families import VIDEO_GENERATION_BUSY_MSG

    if isinstance(exc, GpuBusyForAnotherAccountError):
        return "busy"
    if not isinstance(exc, HTTPException) or exc.status_code not in (409, 503):
        return None
    error = _refusal_error(exc)
    if error["message"] == VIDEO_GENERATION_BUSY_MSG or error["code"] in _VIDEO_WAIT_CODES:
        return "busy"
    return "conflict" if error["code"] == "model_changed" else None


def _queued_video_job(entry: _QueuedVideo) -> VideoJob:
    return VideoJob(
        id = entry.id,
        model = entry.model,
        status = "queued",
        progress = 0,
        created_at = entry.created_at,
        prompt = entry.body.prompt,
        size = entry.size,
        seconds = entry.seconds,
        seed = entry.seed,
    )


def _own_queued_video(video_id: str) -> Optional[_QueuedVideo]:
    account_id = current_account_id()
    return next(
        (
            entry
            for entry in list(_VIDEO_QUEUE)
            if entry.id == video_id and entry.account.account_id == account_id
        ),
        None,
    )


def _own_queued_videos() -> list[VideoJob]:
    account_id = current_account_id()
    return [
        _queued_video_job(entry)
        for entry in list(_VIDEO_QUEUE)
        if entry.account.account_id == account_id
    ]


def _keyframe_canvas(
    fam,
    h3_task,
    reference: Optional[str],
    last_frame: Optional[str],
    size = None,
):
    from core.inference.video import VideoBackend
    from core.inference.video_minimax_h3 import H3_TASK_REFERENCES

    first = None if h3_task == H3_TASK_REFERENCES else reference
    width, height = size if size is not None else (None, None)
    return VideoBackend._resolve_keyframes(fam, h3_task, first, last_frame, width, height)


def _queued_job_display(
    body: VideoJobCreateRequest, reference: Optional[str], inputs: _VideoCreateInputs
) -> tuple[str, str, str]:
    from core.inference.gpu_arbiter import VIDEO
    from core.inference.media_auto_switch import resident_answers_media_request
    from core.inference.media_model_index import (
        VIDEO_TASK,
        expected_partition,
        resolve_local_media_model,
    )
    from core.inference.video import (
        _detect_load_family,
        _family_shape_defaults,
        get_video_backend,
    )
    from core.inference.video_families import VideoShapeError
    from utils.openai_auto_switch_settings import get_media_auto_switch_enabled

    backend = get_video_backend()
    status = backend.status()
    named = isinstance(body.model, str) and bool(body.model.strip())
    resident_renders = (
        not named
        or not get_media_auto_switch_enabled()
        or resident_answers_media_request(status, body.model, owner = VIDEO)
    )
    if resident_renders and account_access.managed_account():
        account_access.require_media_generation_access(status, "video")
    if resident_renders:
        state = backend.generation_snapshot()[1]
        fam, h3_task = getattr(state, "family", None), getattr(state, "h3_task", None)
    else:
        pick = resolve_local_media_model(body.model.strip(), task = VIDEO_TASK)
        fam = pick and _detect_load_family(pick.model_path, pick.gguf_filename, None)
        h3_task = expected_partition(pick) if fam else None
    canvas = None
    if fam is not None:
        try:
            _refuse_family_inputs(fam, h3_task, body, reference, inputs)
            if reference is not None or body.last_frame:
                canvas = _keyframe_canvas(fam, h3_task, reference, body.last_frame, inputs.size)
        except VideoShapeError as exc:
            raise _openai_video_error(400, str(exc), param = _shape_error_param(exc, body))
        except ValueError as exc:
            raise _openai_video_error(
                400, str(exc), param = _conditioning_param(body, reference, "input_reference")
            )
    if resident_renders:
        defaults = status.get("defaults") or {}
    else:
        defaults = _family_shape_defaults(fam) if fam is not None else {}
    resident = status.get("repo_id") if resident_renders else None
    if resident:
        model = public_model_id(str(resident))
    elif named:
        model = public_model_id(body.model) or body.model
    else:
        model = "video"
    presets = defaults.get("resolution_presets") or []
    if inputs.size is not None:
        size = f"{inputs.size[0]}x{inputs.size[1]}"
    elif canvas is not None:
        size = f"{canvas[2]}x{canvas[3]}"
    elif presets:
        size = f"{int(presets[0][0])}x{int(presets[0][1])}"
    else:
        size = "auto"
    fps = body.fps or defaults.get("fps")
    if inputs.seconds is not None:
        frames = _frames_for_seconds(inputs.seconds, {**defaults, "fps": fps})
    else:
        frames = body.num_frames or defaults.get("num_frames")
    seconds = (
        _format_seconds(int(frames) / float(fps)) if frames and fps else body.seconds or "auto"
    )
    return model, size, seconds


async def _create_or_queue_openai_video(
    body: VideoJobCreateRequest,
    reference: Optional[str],
    inputs: _VideoCreateInputs,
    current_subject: str,
    hf_token: Optional[str],
) -> VideoJob:
    video_id = _new_video_id()
    seed = _video_seed(body)
    engine_busy = await asyncio.to_thread(_video_engine_busy)
    if not _VIDEO_QUEUE and not engine_busy:
        try:
            return await _start_openai_video(
                body,
                reference,
                inputs,
                current_subject,
                hf_token,
                video_id = video_id,
                seed = seed,
            )
        except Exception as exc:
            if _video_wait(exc) != "busy":
                raise
    inputs.decoded_images = None
    await asyncio.to_thread(_refuse_unreadable_audio, inputs.reference_audios)
    model, size, seconds = await asyncio.to_thread(_queued_job_display, body, reference, inputs)
    account = current_account()
    waiting = sum(1 for entry in _VIDEO_QUEUE if entry.account.account_id == account.account_id)
    if waiting >= VIDEO_QUEUE_MAX_PER_ACCOUNT or len(_VIDEO_QUEUE) >= VIDEO_QUEUE_MAX:
        full = (
            f"{VIDEO_QUEUE_MAX_PER_ACCOUNT} videos are already waiting for this account"
            if waiting >= VIDEO_QUEUE_MAX_PER_ACCOUNT
            else f"{VIDEO_QUEUE_MAX} videos are already waiting"
        )
        raise _openai_video_error(
            429,
            f"{full} in Unsloth Studio; create this one once some have started.",
            code = "rate_limit_exceeded",
        )
    entry = _QueuedVideo(
        id = video_id,
        account = account,
        subject = current_subject,
        hf_token = hf_token,
        body = body,
        reference = reference,
        inputs = inputs,
        seed = seed,
        created_at = int(_time.time()),
        model = model,
        size = size,
        seconds = seconds,
    )
    _VIDEO_QUEUE.append(entry)
    _ensure_video_drainer()
    return _queued_video_job(entry)


def _fail_queued_video(entry: _QueuedVideo, exc: BaseException) -> None:
    error = _refusal_error(exc)
    job = _VideoJob(
        id = entry.id,
        created_at = entry.created_at,
        prompt = entry.body.prompt,
        model = entry.model,
        size = entry.size,
        seconds = entry.seconds,
        seed = entry.seed,
        status = "failed",
        completed_at = int(_time.time()),
        error = {
            "code": error["code"] or _VIDEO_FAILED_CODE,
            "message": error["message"] or "Video generation failed.",
        },
    )
    run_as(entry.account, _remember_job, job)


def _drop_queued_video(entry: _QueuedVideo) -> None:
    if entry in _VIDEO_QUEUE:
        _VIDEO_QUEUE.remove(entry)


async def _settle_failed_queued_video(entry: _QueuedVideo, exc: BaseException) -> None:
    entry.starting = True
    try:
        await asyncio.to_thread(_fail_queued_video, entry, exc)
    except Exception:  # noqa: BLE001 -- persistence failure must not block the queue
        logger.exception("Could not record queued video %s as failed", entry.id)
    finally:
        _drop_queued_video(entry)
        entry.starting = False


async def _await_queued_start(entry: _QueuedVideo) -> bool:
    deadline = _time.monotonic() + _DELETE_SETTLE_TIMEOUT_S
    while entry.starting and _time.monotonic() < deadline:
        await asyncio.sleep(0.05)
    return not entry.starting


def _queued_account_active(account: AccountContext) -> bool:
    if account.is_owner:
        return True
    from auth.storage import get_account_by_id
    return get_account_by_id(account.account_id) is not None


async def _start_queued_video(entry: _QueuedVideo) -> bool:
    from core.inference import media_keepwarm
    from core.inference.gpu_arbiter import VIDEO
    from core.inference.llama_keepwarm import InferenceActivityReservation

    async with _video_start_lock():
        if entry not in _VIDEO_QUEUE:
            return True
        if await asyncio.to_thread(_video_engine_busy):
            return False
        active = await asyncio.to_thread(_queued_account_active, entry.account)
        if entry not in _VIDEO_QUEUE:
            return True
        if not active:
            logger.info("openai_videos.queued_account_disabled: %s", entry.id)
            _drop_queued_video(entry)
            return True
        entry.starting = True
        entered = started = False
        # Counted like an HTTP create so an idle unload or auto-switch cannot cancel the accepted clip.
        activity = InferenceActivityReservation()
        activity.reserve()
        try:
            await activity.start()
            await media_keepwarm.begin_request(VIDEO)
            entered = True
            if await asyncio.to_thread(_video_engine_busy):
                entry.starting = False
                return False
            await arun_as(
                entry.account,
                _start_openai_video(
                    entry.body,
                    entry.reference,
                    entry.inputs,
                    entry.subject,
                    entry.hf_token,
                    video_id = entry.id,
                    seed = entry.seed,
                    created_at = entry.created_at,
                    queued_account = entry.account,
                ),
            )
            started = True
        except _QueuedAccountDisabled:
            logger.info("openai_videos.queued_account_disabled: %s", entry.id)
            _drop_queued_video(entry)
            entry.starting = False
            return True
        except Exception as exc:  # noqa: BLE001 -- settle failures and continue draining
            wait = _video_wait(exc)
            if wait is None and await asyncio.to_thread(_video_engine_busy):
                wait = "busy"
            if wait == "conflict":
                entry.idle_conflicts += 1
                if entry.idle_conflicts >= VIDEO_QUEUE_IDLE_CONFLICTS:
                    wait = None
            if wait is not None:
                entry.starting = False
                return False
            if not isinstance(exc, HTTPException):
                logger.exception("Could not start queued video %s", entry.id)
            await _settle_failed_queued_video(entry, exc)
            return True
        finally:
            if entered:
                media_keepwarm.end_request(VIDEO, counted = started)
            activity.finish()
        _drop_queued_video(entry)
        entry.starting = False
    return True


async def _drain_video_queue_once() -> None:
    if not _VIDEO_QUEUE:
        return
    entry = _VIDEO_QUEUE[0]
    try:
        await _start_queued_video(entry)
    except Exception as exc:  # noqa: BLE001 -- the next video must still start
        logger.exception("Could not settle queued video %s", entry.id)
        if entry in _VIDEO_QUEUE:
            await _settle_failed_queued_video(entry, exc)
        entry.starting = False


async def _drain_video_queue() -> None:
    while _VIDEO_QUEUE:
        head = _VIDEO_QUEUE[0]
        await _drain_video_queue_once()
        if _VIDEO_QUEUE and _VIDEO_QUEUE[0] is head:
            await asyncio.sleep(VIDEO_QUEUE_POLL_S)


def _ensure_video_drainer() -> None:
    global _video_drainer
    if _video_drainer is None or _video_drainer.done():
        _video_drainer = asyncio.get_running_loop().create_task(_drain_video_queue())


@openai_router.get("/videos", response_model = VideoJobListResponse)
async def openai_list_videos(
    limit: int = Query(20, ge = 1, le = 100),
    after: Optional[str] = None,
    order: Literal["asc", "desc"] = "desc",
    current_subject: str = Depends(get_current_subject),
):
    videos = await asyncio.to_thread(_all_videos)
    videos.sort(key = lambda video: (video.created_at, video.id), reverse = order == "desc")
    if after:
        index = next((i for i, video in enumerate(videos) if video.id == after), None)
        if index is None:
            raise _openai_video_error(
                400, f"No video found with id '{after[:128]}'.", param = "after"
            )
        videos = videos[index + 1 :]
    page = videos[:limit]
    return VideoJobListResponse(
        data = page,
        first_id = page[0].id if page else None,
        last_id = page[-1].id if page else None,
        has_more = len(videos) > limit,
    )


@openai_router.get("/videos/{video_id}", response_model = VideoJob)
async def openai_retrieve_video(
    video_id: str,
    response: Response,
    current_subject: str = Depends(get_current_subject),
):
    video = await asyncio.to_thread(_lookup_video, video_id)
    if video is None:
        raise _not_found(video_id)
    if video.status in ("queued", "in_progress"):
        response.headers["openai-poll-after-ms"] = _VIDEO_POLL_AFTER_MS
    return video


@openai_router.get("/videos/{video_id}/content")
async def openai_download_video_content(
    video_id: str,
    variant: str = "video",
    current_subject: str = Depends(get_current_subject),
):
    from core.inference import video_gallery

    normalized_variant = (variant or "video").strip().lower()
    if normalized_variant not in ("video", "thumbnail"):
        raise _openai_video_error(
            400, "Unsupported variant. Use 'video' or 'thumbnail'.", param = "variant"
        )
    path = await asyncio.to_thread(video_gallery.owned_video_path, video_id)
    if path is None:
        video = await asyncio.to_thread(_lookup_video, video_id)
        if video is None:
            raise _not_found(video_id)
        if video.status == "failed":
            raise _openai_video_error(
                400,
                video.error.message if video.error else "Video generation failed.",
                code = video.error.code if video.error else _VIDEO_FAILED_CODE,
            )
        raise _openai_video_error(
            400,
            "Video is still generating; retrieve it until its status is 'completed'.",
            code = "video_not_ready",
        )
    if normalized_variant == "thumbnail":
        try:
            thumbnail = await asyncio.to_thread(video_gallery.thumbnail, video_id)
        except RuntimeError as exc:
            raise _openai_video_error(501, str(exc), code = "video_thumbnail_unavailable") from exc
        if thumbnail is None:
            raise _not_found(video_id)
        return Response(
            content = thumbnail,
            media_type = "image/webp",
            headers = {
                "Cache-Control": "private, max-age=31536000, immutable",
                "Content-Disposition": f'attachment; filename="{video_id}.webp"',
            },
        )
    from fastapi.responses import FileResponse

    return FileResponse(
        path,
        media_type = "video/mp4",
        filename = f"{video_id}.mp4",
        headers = {"Cache-Control": "private, max-age=31536000, immutable"},
    )


@openai_router.delete("/videos/{video_id}", response_model = VideoJobDeleteResponse)
async def openai_delete_video(video_id: str, current_subject: str = Depends(get_current_subject)):
    from core.inference import video_gallery
    from core.inference.video import get_video_backend

    queued = _own_queued_video(video_id)
    if queued is not None and queued.starting:
        if not await _await_queued_start(queued):
            raise _openai_video_error(
                409,
                "The video is starting; retry the delete shortly.",
                code = "video_not_ready",
            )
        queued = _own_queued_video(video_id)
    if queued is not None:
        _drop_queued_video(queued)
        return VideoJobDeleteResponse(id = video_id)
    video = await asyncio.to_thread(_lookup_video, video_id)
    if video is None:
        raise _not_found(video_id)
    if video.status in ("queued", "in_progress"):
        await asyncio.to_thread(get_video_backend().cancel_generate, video_id)
        # The run can reach its terminal state between the lookup and the cancel
        if not await asyncio.to_thread(_await_generate_settled, video_id):
            raise _openai_video_error(
                409,
                "The video is still being written; retry the delete once it is no longer generating.",
                code = "video_not_ready",
            )
    deleted = await asyncio.to_thread(video_gallery.delete, video_id)
    if deleted:
        _forget_terminal_video(video_id)
    elif await asyncio.to_thread(video_gallery.get_record, video_id) is not None:
        raise _openai_video_error(500, "Could not delete the video; retry the request.")
    if not await asyncio.to_thread(_forget_openai_job, video_id):
        raise _openai_video_error(500, "Could not delete the video job; retry the request.")
    return VideoJobDeleteResponse(id = video_id)