/* videos.cpp -- OpenAI's video endpoints over a video generator (core/gen/video_driver.h): a video * and its soundtrack from a prompt. * * A video takes minutes, so it is a job, as OpenAI's API has it: POST /v1/videos queues one and * answers with the video object at once, GET /v1/videos/{id} reports its status and progress, and * GET /v1/videos/{id}/content downloads the MP4 once it is completed (`variant` thumbnail gives * the first frame as WebP). GET /v1/videos lists the jobs, newest first, and DELETE removes one, * cancelling it when it is still running. A finished video is kept for `video_ttl_s` seconds * (`expires_at`), at most `max_videos` of them. * * The request takes OpenAI's fields (`prompt`, `model`, `seconds`, `size`) as JSON or as a * multipart form, and SGLang's for the same model: `task` (t2va), `target` {`short_edge`, * `aspect_ratio`, `duration_seconds`}, `conditions` (empty), `seed`, and `num_inference_steps`. * `size` is the frame's width x height, multiples of the model's size multiple; `aspect_ratio` * (`w:h`) instead lays the model's own canvas over that ratio: the short edge (the model's, or * `short_edge`), the area capped at the model's largest, both sides rounded to the multiple. * A video's length is a whole number of the model's chunks: `seconds` is rounded up to the next. * A model that takes reference media (VideoGenInfo) also serves SGLang's `task` value `ref2va`: * the media are form file parts named `ref_image_N` (at most 9), `ref_video_N` (3), a video's * soundtrack as `ref_video_audio_N` and standalone audios as `ref_audio_N` (3), N 1-based and * contiguous within each kind. `input_reference` and non-empty `conditions` are still refused: * the parts carry the bytes, so no JSON array of media is read. * * A model with a latent upscaler also takes `latent_upscale`, a factor from 1 to its largest: the * first steps run at `size` divided by it and the latent is enlarged to `size` for the last * `upscale_refine_steps` (the model's default when absent; abi/rad_builder.h, RadVideoGenDecl). * The video object of an upscaled video says how it was made: the factor, the refine steps and the * small size (`upscale_from`). * * The prompt is the model's template with `{prompt}` filled; the template is tokenised with its * special tokens and the prompt without, so a caller cannot write control tokens into it. */ #include "server.h" #include "oai.h" #include "gen/video.h" #include "mm/media.h" #include "mm/mp4.h" #include "rad_internal.h" #include #include #include #include #include #include #include #include #include #include #include namespace rad { namespace server { struct Server::VideoJob { std::string id, model, prompt, seconds, size; int64_t created_at = 0; uint64_t seed = 0; std::shared_ptr ticket; std::thread worker; /* Under Server::videos_m_ from here on. */ std::string status = "queued"; int progress = 0; int64_t completed_at = 0, expires_at = 0; bool failed = false; std::string err_code, err_message; std::string mp4; std::vector first; /* the first frame, RGB, for the thumbnail */ /* Reference conditioning: the reference parts' names in conditioning order, empty for a * text-only job. */ std::vector refs; /* Latent upscaling, as the generator resolved it: the factor, the evaluations after it and the * small size; refine 0 when the video is not upscaled. */ double upscale = 0.0; int32_t refine = 0; std::string upscale_from; int32_t w = 0, h = 0; bool worker_done = false; /* its thread has nothing left to do but return */ }; namespace { std::string new_video_id() { static const char* hex = "0123456789abcdef"; std::random_device rd; std::string id = "video_"; for (int i = 0; i < 32; ++i) id.push_back(hex[rd() & 15]); return id; } /* "1344x768" -> (1344, 768); false for anything else. */ bool parse_size(const std::string& s, int64_t* w, int64_t* h) { const size_t x = s.find_first_of("xX"); if (x == std::string::npos || x == 0 || x + 1 >= s.size()) return false; char* e = nullptr; *w = std::strtoll(s.c_str(), &e, 10); if (e != s.c_str() + x) return false; *h = std::strtoll(s.c_str() + x + 1, &e, 10); return *e == '\0' && *w > 0 && *h > 0; } /* "16:9" -> 16/9 as two positives; false for anything else. */ bool parse_ratio(const std::string& s, double* a, double* b) { const size_t c = s.find(':'); if (c == std::string::npos) return false; char* e = nullptr; *a = std::strtod(s.c_str(), &e); if (e != s.c_str() + c) return false; *b = std::strtod(s.c_str() + c + 1, &e); return *e == '\0' && *a > 0 && *b > 0; } /* The model's canvas for a ratio: the short edge, the area capped, both sides rounded to the * multiple (ties to even, as the reference's float round). */ void canvas_for(double rw, double rh, int64_t short_edge, int64_t max_area, int64_t mult, int64_t* w, int64_t* h) { const double ratio = rw / rh; double W = ratio >= 1.0 ? short_edge * ratio : (double)short_edge; double H = ratio >= 1.0 ? (double)short_edge : short_edge / ratio; if (W * H > (double)max_area) { const double sc = std::sqrt((double)max_area / (W * H)); W *= sc; H *= sc; } *w = std::max(mult, (int64_t)std::nearbyint(W / mult) * mult); *h = std::max(mult, (int64_t)std::nearbyint(H / mult) * mult); } /* What a ref2va request may carry whatever a model declares: the reference media the source * workflows were built with — nine images, three videos each with an optional soundtrack, three * standalone audios. A model's declaration can only lower these. */ constexpr int32_t kMaxRefImages = 9, kMaxRefVideos = 3, kMaxRefAudios = 3; /* A form file part's name for task ref2va: `ref_image_N`, `ref_video_N`, `ref_video_audio_N` * (a video's separately-given soundtrack) or `ref_audio_N`, N plain and 1-based. False for any * other name; `ref_video_audio_` is tried before `ref_video_` because one contains the other. */ bool parse_ref_name(const std::string& name, gen::VideoRefMedia::Kind* kind, int32_t* index) { static const struct { const char* pfx; gen::VideoRefMedia::Kind kind; } kKinds[] = { { "ref_image_", gen::VideoRefMedia::IMAGE }, { "ref_video_audio_", gen::VideoRefMedia::VIDEO_AUDIO }, { "ref_video_", gen::VideoRefMedia::VIDEO }, { "ref_audio_", gen::VideoRefMedia::AUDIO }, }; for (const auto& k : kKinds) { const size_t n = std::strlen(k.pfx); if (name.compare(0, n, k.pfx) != 0 || name.size() == n) continue; char* e = nullptr; const long v = std::strtol(name.c_str() + n, &e, 10); if (*e == '\0' && v >= 1 && v <= 99) { *kind = k.kind; *index = (int32_t)v; return true; } } return false; } /* True when the file ends in one of these extensions, case-insensitively — what the client * called the file, which the media readers make the first word of what it holds. */ bool has_ext(const std::string& f, const std::vector& exts) { const size_t d = f.find_last_of('.'); if (d == std::string::npos) return false; std::string e = f.substr(d + 1); for (char& c : e) c = (char)std::tolower((unsigned char)c); for (const std::string& x : exts) if (e == x) return true; return false; } std::string ext_list(const std::vector& exts) { std::string s; for (const std::string& x : exts) { if (!s.empty()) s += ", "; s += "." + x; } return s; } /* The reference parts of a ref2va request, and their order. Refused with `*err` naming the part * when one carries no bytes or an extension the media readers do not take, when a kind is over * the API's or the model's count, when a kind's numbers leave a gap or repeat, or when a * soundtrack has no video of the same number. On return `refs` is sorted by (kind, number): the * order the generator builds the conditioning in. */ int validate_refs(std::vector& refs, const VideoGenInfo& info, ApiError* err) { if (refs.empty()) { *err = err_bad("task", "ref2va takes at least one reference part: ref_image_N, " "ref_video_N, ref_video_audio_N or ref_audio_N"); return -1; } const struct { const char* pfx; gen::VideoRefMedia::Kind kind; int32_t cap; std::vector exts; } kinds[] = { { "ref_image", gen::VideoRefMedia::IMAGE, std::min(kMaxRefImages, (int32_t)info.max_ref_images), { "png", "jpg", "jpeg", "webp" } }, { "ref_video", gen::VideoRefMedia::VIDEO, std::min(kMaxRefVideos, (int32_t)info.max_ref_videos), { "mp4", "mov" } }, { "ref_video_audio", gen::VideoRefMedia::VIDEO_AUDIO, std::min(kMaxRefVideos, (int32_t)info.max_ref_videos), { "mp4", "mov", "wav", "mp3", "m4a", "aac", "flac", "ogg" } }, { "ref_audio", gen::VideoRefMedia::AUDIO, std::min(kMaxRefAudios, (int32_t)info.max_ref_audios), { "wav", "mp3", "m4a", "aac", "flac", "ogg" } }, }; for (const auto& k : kinds) { std::vector got(k.cap + 1, false); int n = 0; for (const gen::VideoRefMedia& m : refs) { if (m.kind != k.kind) continue; ++n; if (m.data.empty()) return *err = err_bad(m.name, "'" + m.name + "' carries an empty file"), -1; if (!has_ext(m.filename, k.exts)) return *err = err_bad(m.name, "'" + m.name + "' must be one of " + ext_list(k.exts)), -1; if (m.index > k.cap) return *err = err_bad(m.name, k.cap == 0 ? "this model takes no parts named " + std::string(k.pfx) + "_N" : "this model takes at most " + std::to_string(k.cap) + " parts named " + std::string(k.pfx) + "_N"), -1; if (got[m.index]) return *err = err_bad(m.name, "two parts are numbered " + std::string(k.pfx) + "_" + std::to_string(m.index)), -1; got[m.index] = true; } for (int i = 1; i <= n; ++i) if (!got[i]) return *err = err_bad(std::string(k.pfx) + "_" + std::to_string(i), "the " + std::string(k.pfx) + "_N parts must be numbered 1 " "to " + std::to_string(n) + " without gaps or repeats"), -1; } for (const gen::VideoRefMedia& m : refs) { if (m.kind != gen::VideoRefMedia::VIDEO_AUDIO) continue; bool paired = false; for (const gen::VideoRefMedia& v : refs) paired = paired || (v.kind == gen::VideoRefMedia::VIDEO && v.index == m.index); if (!paired) return *err = err_bad(m.name, "'" + m.name + "' is the soundtrack of a reference " "video; give ref_video_" + std::to_string(m.index) + " with it"), -1; } std::stable_sort(refs.begin(), refs.end(), [](const gen::VideoRefMedia& a, const gen::VideoRefMedia& b) { return a.kind != b.kind ? a.kind < b.kind : a.index < b.index; }); return 0; } } /* namespace */ /* The caps the /v1/models and /server_info capability block reports for a video model. The * counts are the ones validate_refs() will apply — the model's declaration under the API's, * since a declaration can only lower those — so what a client gates on is what it will meet. */ void Server::video_caps(json& caps, const IVideoGen* gen) { const VideoGenInfo& info = gen->info(); caps["video_max_text"] = info.max_text; caps["video_max_ref_images"] = std::min(kMaxRefImages, (int32_t)info.max_ref_images); caps["video_max_ref_videos"] = std::min(kMaxRefVideos, (int32_t)info.max_ref_videos); caps["video_max_ref_audios"] = std::min(kMaxRefAudios, (int32_t)info.max_ref_audios); } HttpResponse Server::handle_video_create(const HttpRequest& req) { if (!deps_.videos || !deps_.tok) return error_response(err_not_implemented( "/v1/videos requires a video generation model; this one does not make video"), req.peer); const VideoGenInfo& info = deps_.videos->info(); const bool takes_refs = info.max_ref_images > 0 || info.max_ref_videos > 0 || info.max_ref_audios > 0; /* JSON, or a form whose fields are strings (OpenAI's clients send the create call as a form, * since it may carry a file). A form may carry the reference media of a ref2va request as * named file parts; they are collected here and checked once the task is known. */ std::vector refs; /* Endpoint keyframes: the "first_frame"/"last_frame" file parts, kept apart from the reference * media because they are conditioned on differently (pinned rows, not reference rows) and are * validated and encoded on their own path below. At most one of each; together they are FL2VA, * alone they are I2VA (first) or L2VA (last). */ std::vector keys; json body = json::object(); if (!req.form.empty()) { for (const FormPart& p : req.form) { if (p.name == "input_reference") return error_response(err_unsupported("input_reference", takes_refs ? "this server reads reference media as " "ref_image_N file parts" : "this server makes video from text " "only"), req.peer); if (p.name == "first_frame" || p.name == "last_frame") { if (p.filename.empty()) return error_response(err_bad(p.name, "'" + p.name + "' must carry an image " "file"), req.peer); gen::VideoRefMedia m; m.kind = p.name == "first_frame" ? gen::VideoRefMedia::FIRST_FRAME : gen::VideoRefMedia::LAST_FRAME; m.index = 1; m.name = p.name; m.filename = p.filename; m.content_type = p.content_type; m.data = p.data; keys.push_back(std::move(m)); continue; } if (!p.filename.empty()) { gen::VideoRefMedia m; if (!parse_ref_name(p.name, &m.kind, &m.index)) return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a " "file"), req.peer); m.name = p.name; m.filename = p.filename; m.content_type = p.content_type; m.data = p.data; refs.push_back(std::move(m)); continue; } json v = p.data; if (p.name == "target" || p.name == "conditions") { v = json::parse(p.data, nullptr, false); if (v.is_discarded()) return error_response(err_bad(p.name, "expected JSON"), req.peer); } body[p.name] = v; } } else { ApiError err; if (parse_request_object(req.body, lim_, &body, &err) < 0) return error_response(err, req.peer); } static const char* kKnown[] = { "model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps", "task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps", }; for (auto it = body.begin(); it != body.end(); ++it) { bool known = false; for (const char* k : kKnown) known = known || it.key() == k; if (!known) return error_response(err_bad(it.key(), "'" + it.key() + "' is not a field of " "/v1/videos"), req.peer); } auto bad = [&](const char* k, const std::string& why) { return error_response(err_bad(k, why), req.peer); }; auto has = [&](const json& o, const char* k) { return o.contains(k) && !o[k].is_null(); }; /* A number, or a string holding one (a form's fields are strings). */ auto number = [&](const json& v, double* out) { if (v.is_number()) { *out = v.get(); return true; } if (!v.is_string()) return false; const std::string s = v.get(); char* e = nullptr; *out = std::strtod(s.c_str(), &e); return !s.empty() && *e == '\0'; }; if (!has(body, "prompt") || !body["prompt"].is_string() || body["prompt"].get().find_first_not_of(" \t\r\n") == std::string::npos) return bad("prompt", "the prompt is required, as a non-empty string"); const std::string prompt = body["prompt"].get(); if (has(body, "input_reference")) return error_response(err_unsupported("input_reference", takes_refs ? "this server reads reference media as ref_image_N " "file parts" : "this server makes video from text only"), req.peer); /* The task: text always; reference conditioning for a model that takes reference media. */ bool ref2va = false; std::string kf_task; /* an explicitly named keyframe task (i2va / l2va / fl2va), if any */ if (has(body, "task")) { const std::string task = body["task"].is_string() ? body["task"].get() : ""; if (task == "ref2va" && takes_refs) ref2va = true; /* The keyframe-completion tasks: a first and/or last frame pinned at the output's ends. * They are recognised whatever a model declares (any model with a video encoder can pin a * keyframe); which frames are actually present is decided by the file parts, cross-checked * against this name below. t2va with a first_frame part is I2VA; a named task missing its * frame is refused there. */ else if (task == "i2va" || task == "l2va" || task == "fl2va") kf_task = task; else if (task != "t2va") { ApiError e = err_unsupported("task", takes_refs ? "this server makes video from text, from reference " "media, or between keyframes: t2va, ref2va, i2va, l2va, " "fl2va" : "this server makes video from text or between keyframes: " "t2va, i2va, l2va, fl2va"); e.supported = takes_refs ? std::vector{ "t2va", "ref2va", "i2va", "l2va", "fl2va" } : std::vector{ "t2va", "i2va", "l2va", "fl2va" }; return error_response(e, req.peer); } } if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty())) return error_response(err_unsupported("conditions", takes_refs ? "reference media arrive as ref_* file parts; " "conditions must be empty" : "this server makes video from text only; " "conditions must be empty"), req.peer); /* The reference parts, in conditioning order, before anything else reads them. Files with no * task are a caller's mistake about the task, not about the part. */ if (!refs.empty() && !ref2va) return bad("task", "reference files are given: send them with task ref2va, or send " "none"); if (ref2va) { ApiError e; if (validate_refs(refs, info, &e) < 0) return error_response(e, req.peer); } /* Endpoint keyframes: at most one of each, not alongside reference media (a request either * completes between two pinned frames or conditions on references -- the two conditioning * paths are different rows), and only on a model that encodes (a keyframe reaches the DiT as a * pinned VAE latent). */ { int n_first = 0, n_last = 0; for (const gen::VideoRefMedia& m : keys) if (m.kind == gen::VideoRefMedia::FIRST_FRAME) ++n_first; else ++n_last; if (n_first > 1) return bad("first_frame", "at most one first_frame part"); if (n_last > 1) return bad("last_frame", "at most one last_frame part"); if (!keys.empty()) { if (!info.encodes) return bad("first_frame", "this model has no video encoder, so it cannot pin a " "keyframe"); if (!refs.empty()) return bad("first_frame", "a keyframe completion conditions on its pinned frames, " "not on reference media: give first_frame/last_frame or " "the ref_* parts, not both"); } /* A named keyframe task must carry the frame(s) it promises; t2va with parts is fine, the * parts alone decide the mode. */ if (!kf_task.empty()) { if ((kf_task == "i2va" || kf_task == "fl2va") && n_first < 1) return bad("first_frame", "task '" + kf_task + "' pins a first frame: give a " "first_frame part"); if ((kf_task == "l2va" || kf_task == "fl2va") && n_last < 1) return bad("last_frame", "task '" + kf_task + "' pins a last frame: give a " "last_frame part"); } } json target = json::object(); if (has(body, "target")) { if (!body["target"].is_object()) return bad("target", "expected an object"); target = body["target"]; for (auto it = target.begin(); it != target.end(); ++it) if (it.key() != "short_edge" && it.key() != "aspect_ratio" && it.key() != "duration_seconds") return bad("target", "'" + it.key() + "' is not a field of target"); } /* ---- the size */ int64_t W = info.default_width, H = info.default_height; const int64_t short_def = std::min(info.default_width, info.default_height); if (has(body, "size")) { if (!body["size"].is_string() || !parse_size(body["size"].get(), &W, &H)) return bad("size", "expected WIDTHxHEIGHT, e.g. " + std::to_string(info.default_width) + "x" + std::to_string(info.default_height)); if (has(target, "aspect_ratio") || has(target, "short_edge")) return bad("size", "give size or target's aspect_ratio and short_edge, not both"); } else if (has(target, "aspect_ratio") || has(target, "short_edge")) { double rw = (double)info.default_width, rh = (double)info.default_height; if (has(target, "aspect_ratio")) { if (!target["aspect_ratio"].is_string()) return bad("target", "aspect_ratio is a string, w:h or auto"); const std::string ar = target["aspect_ratio"].get(); if (ar != "auto" && !parse_ratio(ar, &rw, &rh)) return bad("target", "aspect_ratio must be w:h (16:9) or auto"); } int64_t se = short_def; if (has(target, "short_edge")) { double v = 0; if (!number(target["short_edge"], &v) || v < 1 || v != std::floor(v)) return bad("target", "short_edge must be a positive whole number of pixels"); se = (int64_t)v; } if (std::max(rw, rh) > (double)info.max_aspect * std::min(rw, rh)) return bad("target", "the aspect ratio may be at most " + std::to_string(info.max_aspect) + ":1 either way"); canvas_for(rw, rh, se, info.max_area, info.size_multiple, &W, &H); } if (W % info.size_multiple || H % info.size_multiple || W < info.min_side || H < info.min_side || W * H > info.max_area || std::max(W, H) > info.max_aspect * std::min(W, H)) { int64_t sw = 0, sh = 0; canvas_for((double)W, (double)H, short_def, info.max_area, info.size_multiple, &sw, &sh); return bad("size", std::to_string(W) + "x" + std::to_string(H) + " is not a size this " "model makes: sides are multiples of " + std::to_string(info.size_multiple) + " from " + std::to_string(info.min_side) + ", at most " + std::to_string(info.max_area) + " pixels and " + std::to_string(info.max_aspect) + ":1; its canvas at that ratio is " + std::to_string(sw) + "x" + std::to_string(sh)); } /* ---- the length, in whole chunks */ const double fps = (double)info.fps_num / (double)info.fps_den; const double min_s = (double)(info.frames_per_chunk * info.min_chunks + info.frames_tail) / fps; const double max_s = (double)(info.frames_per_chunk * info.max_chunks + info.frames_tail) / fps; int64_t chunks = info.default_chunks; const bool has_sec = has(body, "seconds"), has_dur = has(target, "duration_seconds"); if (has_sec && has_dur) return bad("seconds", "give seconds or target's duration_seconds, not both"); if (has_sec || has_dur) { double sec = 0; if (!number(has_sec ? body["seconds"] : target["duration_seconds"], &sec) || !(sec > 0)) return bad(has_sec ? "seconds" : "target", "the length is a positive number of seconds"); const int64_t want = (int64_t)std::ceil(sec * fps - 1e-9); chunks = std::max(info.min_chunks, (want - info.frames_tail + info.frames_per_chunk - 1) / info.frames_per_chunk); if (chunks > info.max_chunks) return bad(has_sec ? "seconds" : "target", "this model makes " + rad::fmt("%.2f", min_s) + " to " + rad::fmt("%.2f", max_s) + " seconds"); } const int64_t frames = info.frames_per_chunk * chunks + info.frames_tail; std::unique_ptr r = std::make_unique(); r->width = (int32_t)W; r->height = (int32_t)H; r->chunks = (int32_t)chunks; if (has(body, "num_inference_steps")) { double v = 0; if (info.fixed_steps && (!number(body["num_inference_steps"], &v) || v != (double)info.max_steps)) return bad("num_inference_steps", "this model runs the schedule it was trained on: " + std::to_string(info.max_steps) + " sigma grid points, the last one 0"); if (!number(body["num_inference_steps"], &v) || v != std::floor(v) || v < 2 || v > (double)info.max_steps) return bad("num_inference_steps", "expected an integer in 2.." + std::to_string(info.max_steps) + " (sigma grid points, the last one 0)"); r->steps = (int32_t)v; } if (has(body, "latent_upscale")) { double v = 0; if (!(info.upscale_max > 0.0)) return error_response(err_unsupported("latent_upscale", "this model has no latent " "upscaler"), req.peer); if (!number(body["latent_upscale"], &v) || !(v >= 1.0) || v > info.upscale_max) return bad("latent_upscale", "expected a factor from 1 to " + rad::fmt("%g", info.upscale_max)); r->upscale = v > 1.0 ? v : 0.0; } if (has(body, "upscale_refine_steps")) { double v = 0; if (r->upscale <= 1.0) return bad("upscale_refine_steps", "counts the steps after a latent upscale; give " "latent_upscale above 1 with it"); if (!number(body["upscale_refine_steps"], &v) || v != std::floor(v) || v < 1 || v > 1e6) return bad("upscale_refine_steps", "expected a positive integer"); r->refine = (int32_t)v; } bool seed_given = false; if (has(body, "seed")) { double v = 0; if (!number(body["seed"], &v) || v != std::floor(v)) return bad("seed", "expected an integer"); r->seed = (uint64_t)(int64_t)v; seed_given = v != -1; } if (!seed_given) { /* 53 bits, as the other generators choose one: JavaScript reads a number as a double. */ std::random_device rd; r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1); } r->refs = std::move(refs); /* Keyframes ride the reference vector for the driver's sake (its encode queue indexes it), but * always AFTER every reference: the driver lays the reference rows down first, then folds each * FIRST_FRAME/LAST_FRAME into the pack's keyframe table. first before last, so they keyframe-order * 0 and 1 and take image slots 1 and 2. */ r->refs.insert(r->refs.end(), keys.begin(), keys.end()); /* ---- the prompt: the template's text with special tokens, the reference media in its * presentation order, the prompt last (docs/PORT-REF2VA.md §3: images, then videos each * after its soundtrack's label, then the standalone audios). Each `: ` label is * encoded as its own string, as the tokenizer the source workflows were checked against sees * it; the picture's token run follows its label, taken from the processed item. */ { static const std::string kSlot = "{prompt}"; const std::string& t = info.tmpl; const size_t p = t.find(kSlot); auto put = [&](const std::string& s, bool special) { if (s.empty()) return; const auto ids = deps_.tok->encode(s, false, special); r->tokens.insert(r->tokens.end(), ids.begin(), ids.end()); }; /* The reference media are presented between the template's head and the prompt. Only the * images reach the language model as soft-token rows, so only they are decoded and placed * here; a reference video and every audio reach the model through the VAEs (decoded into the * encoder's form below), so in the prompt they contribute only their spoken label. That * label still rides ahead of the prompt in the reference's presentation order, because the * text encoder sees `