From 515602598d56c7fed6c68bd63db599f561d744e6 Mon Sep 17 00:00:00 2001 From: Salah Eddine Bekhouche Date: Fri, 27 Nov 2026 21:12:40 +0200 Subject: [PATCH 01/11] refactor(dgl): read video inputs through a byte source The AVI, animated WebP and WebM readers now read through VideoSource, which holds either an open file or a buffer, so the same code can decode a video held in memory. Reading a file behaves as before. --- src/dgl/ops/video.cpp | 65 ++++++++++++++++++++++++++------------ src/dgl/ops/video.h | 17 +++++++++- src/dgl/ops/video_webm.cpp | 21 ++++++------ src/dgl/ops/video_webm.h | 2 +- src/dgl/ops/video_webp.cpp | 16 ++++------ src/dgl/ops/video_webp.h | 2 +- 6 files changed, 78 insertions(+), 45 deletions(-) diff --git a/src/dgl/ops/video.cpp b/src/dgl/ops/video.cpp index 2e11f1bccc..3dbe35b0e5 100644 --- a/src/dgl/ops/video.cpp +++ b/src/dgl/ops/video.cpp @@ -33,22 +33,52 @@ namespace sd::dgl::ops { return {uint32_t(shape[1]), uint32_t(shape[2]), 3, const_cast(data)}; } - VideoReadResult load_video(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) { - std::ifstream file(path, std::ios::binary); + VideoSource::VideoSource(const std::filesystem::path& path) + : file_(path, std::ios::binary | std::ios::ate) { + const auto end = file_ ? std::streamoff(file_.tellg()) : std::streamoff(-1); + size_ = end > 0 ? uint64_t(end) : 0; + } + + VideoSource::VideoSource(const void* data, size_t size) + : data_(static_cast(data)), size_(size) { + if (!data_ && size_) + throw std::runtime_error("video input data is required"); + } + + bool VideoSource::read(uint64_t offset, uint64_t size, uint8_t* out) { + if (offset > size_ || size > size_ - offset) + return false; + if (!size) + return true; + if (data_) { + std::memcpy(out, data_ + offset, size_t(size)); + return true; + } + file_.clear(); + file_.seekg(std::streamoff(offset)); + return bool(file_.read(reinterpret_cast(out), std::streamsize(size))); + } + + VideoReadResult load_video(VideoSource& source, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) { uint8_t header[12]{}; - if (!file || !file.read(reinterpret_cast(header), sizeof(header))) + if (!source.read(0, sizeof(header), header)) throw std::runtime_error("cannot read video input header"); if (!std::memcmp(header, "RIFF", 4)) { if (!std::memcmp(header + 8, "AVI ", 4)) - return load_avi(path, max_frames, fps_num, fps_den, include_audio); + return load_avi(source, max_frames, fps_num, fps_den, include_audio); if (!std::memcmp(header + 8, "WEBP", 4)) - return load_webp(path, max_frames, fps_num, fps_den); + return load_webp(source, max_frames, fps_num, fps_den); } if (header[0] == 0x1a && header[1] == 0x45 && header[2] == 0xdf && header[3] == 0xa3) - return load_webm(path, max_frames, fps_num, fps_den, include_audio); + return load_webm(source, max_frames, fps_num, fps_den, include_audio); throw std::runtime_error("unsupported video input; expected AVI, WebP or independent-frame VP8 WebM"); } + VideoReadResult load_video(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) { + VideoSource source(path); + return load_video(source, max_frames, fps_num, fps_den, include_audio); + } + static uint32_t fourcc(const char* text) { return uint32_t(uint8_t(text[0])) | (uint32_t(uint8_t(text[1])) << 8) | (uint32_t(uint8_t(text[2])) << 16) | (uint32_t(uint8_t(text[3])) << 24); @@ -64,26 +94,23 @@ namespace sd::dgl::ops { }; class AVIReader { - std::ifstream file_; - uint64_t size_; + VideoSource& source_; size_t chunks_ = 0; public: - explicit AVIReader(const std::filesystem::path& path) - : file_(path, std::ios::binary | std::ios::ate) { - if (!file_ || file_.tellg() < 12) + explicit AVIReader(VideoSource& source) + : source_(source) { + if (source_.size() < 12) throw std::runtime_error("cannot read AVI file"); - size_ = uint64_t(file_.tellg()); } - uint64_t size() const { return size_; } + uint64_t size() const { return source_.size(); } std::vector read(uint64_t offset, uint64_t size) { - if (offset > size_ || size > size_ - offset || size > 256 * 1024 * 1024) + if (offset > this->size() || size > this->size() - offset || size > 256 * 1024 * 1024) throw std::runtime_error("invalid AVI data size"); std::vector bytes(size_t(size), 0); - file_.seekg(std::streamoff(offset)); - if (size && !file_.read(reinterpret_cast(bytes.data()), std::streamsize(size))) + if (!source_.read(offset, size, bytes.data())) throw std::runtime_error("truncated AVI file"); return bytes; } @@ -213,10 +240,8 @@ namespace sd::dgl::ops { } } - VideoReadResult load_avi(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) { - if (!std::filesystem::is_regular_file(path)) - throw std::runtime_error("video path is not a regular file"); - AVIReader reader(path); + VideoReadResult load_avi(VideoSource& source, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) { + AVIReader reader(source); auto root = reader.read(0, 12); if (read_u32(root.data()) != fourcc("RIFF") || read_u32(root.data() + 8) != fourcc("AVI ")) throw std::runtime_error("video input supports AVI (RGB or MJPEG) only"); diff --git a/src/dgl/ops/video.h b/src/dgl/ops/video.h index 18ff43dbce..981c87417d 100644 --- a/src/dgl/ops/video.h +++ b/src/dgl/ops/video.h @@ -1,7 +1,9 @@ #ifndef __SD_DGL_OPS_VIDEO_H__ #define __SD_DGL_OPS_VIDEO_H__ +#include #include +#include #include "dgl/ops/audio.h" #include "dgl/tensor.h" @@ -24,11 +26,24 @@ namespace sd::dgl::ops { std::string metadata; }; + class VideoSource { + std::ifstream file_; + const uint8_t* data_ = nullptr; + uint64_t size_ = 0; + + public: + explicit VideoSource(const std::filesystem::path& path); + VideoSource(const void* data, size_t size); + uint64_t size() const { return size_; } + bool read(uint64_t offset, uint64_t size, uint8_t* out); + }; + void validate_video_frames(const sd_tensor_t& frames); sd::Image video_frame_view(const sd_tensor_t& frames, size_t index); VideoReadResult load_frame_directory(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den); VideoReadResult load_video(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio); - VideoReadResult load_avi(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio); + VideoReadResult load_video(VideoSource& source, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio); + VideoReadResult load_avi(VideoSource& source, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio); void save_video(const sd_tensor_t& frames, const std::filesystem::path& path, const VideoSaveOptions& options); std::vector encode_avi(const sd_tensor_t& frames, const VideoSaveOptions& options); } diff --git a/src/dgl/ops/video_webm.cpp b/src/dgl/ops/video_webm.cpp index cf314468b1..572c16d698 100644 --- a/src/dgl/ops/video_webm.cpp +++ b/src/dgl/ops/video_webm.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include "dgl/ops/tensor.h" @@ -14,22 +13,20 @@ namespace sd::dgl::ops { class WebMReader : public mkvparser::IMkvReader { - std::ifstream file_; + VideoSource& source_; long long size_; public: - explicit WebMReader(const std::filesystem::path& path) - : file_(path, std::ios::binary | std::ios::ate) { - if (!file_ || file_.tellg() <= 0) + explicit WebMReader(VideoSource& source) + : source_(source) { + if (!source_.size() || source_.size() > uint64_t(std::numeric_limits::max())) throw std::runtime_error("cannot read WebM input"); - size_ = static_cast(file_.tellg()); + size_ = static_cast(source_.size()); } int Read(long long position, long length, unsigned char* buffer) override { if (position < 0 || length < 0 || position > size_ || length > size_ - position) return -1; - file_.clear(); - file_.seekg(position); - return !length || file_.read(reinterpret_cast(buffer), length) ? 0 : -1; + return source_.read(uint64_t(position), uint64_t(length), buffer) ? 0 : -1; } int Length(long long* total, long long* available) override { *total = *available = size_; @@ -50,8 +47,8 @@ namespace sd::dgl::ops { long size; }; - VideoReadResult load_webm(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) { - WebMReader reader(path); + VideoReadResult load_webm(VideoSource& source, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio) { + WebMReader reader(source); mkvparser::EBMLHeader header; long long position = 0; if (header.Parse(&reader, position) || !header.m_docType || @@ -198,7 +195,7 @@ namespace sd::dgl::ops { } #else namespace sd::dgl::ops { - VideoReadResult load_webm(const std::filesystem::path&, size_t, int64_t, int64_t, bool) { + VideoReadResult load_webm(VideoSource&, size_t, int64_t, int64_t, bool) { throw std::runtime_error("WebM video input requires a build with SD_WEBM=ON"); } } diff --git a/src/dgl/ops/video_webm.h b/src/dgl/ops/video_webm.h index ed2863a672..fc784b0e40 100644 --- a/src/dgl/ops/video_webm.h +++ b/src/dgl/ops/video_webm.h @@ -4,7 +4,7 @@ #include "dgl/ops/video.h" namespace sd::dgl::ops { - VideoReadResult load_webm(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio); + VideoReadResult load_webm(VideoSource& source, size_t max_frames, int64_t fps_num, int64_t fps_den, bool include_audio); } #endif // __SD_DGL_OPS_VIDEO_WEBM_H__ diff --git a/src/dgl/ops/video_webp.cpp b/src/dgl/ops/video_webp.cpp index aebbd77993..ec121f0003 100644 --- a/src/dgl/ops/video_webp.cpp +++ b/src/dgl/ops/video_webp.cpp @@ -1,7 +1,6 @@ #include "dgl/ops/video_webp.h" #include -#include #include #include "dgl/ops/tensor.h" @@ -11,16 +10,13 @@ #include namespace sd::dgl::ops { - VideoReadResult load_webp(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den) { - std::ifstream file(path, std::ios::binary | std::ios::ate); - if (!file || file.tellg() <= 0) + VideoReadResult load_webp(VideoSource& source, size_t max_frames, int64_t fps_num, int64_t fps_den) { + if (!source.size()) throw std::runtime_error("cannot read WebP input"); - const auto length = uint64_t(file.tellg()); - if (length > std::numeric_limits::max() || length > uint64_t(std::numeric_limits::max())) + if (source.size() > std::numeric_limits::max()) throw std::runtime_error("WebP input is too large"); - std::vector bytes(size_t(length), 0); - file.seekg(0); - if (!file.read(reinterpret_cast(bytes.data()), std::streamsize(bytes.size()))) + std::vector bytes(size_t(source.size()), 0); + if (!source.read(0, bytes.size(), bytes.data())) throw std::runtime_error("truncated WebP input"); WebPBitstreamFeatures features{}; if (WebPGetFeatures(bytes.data(), bytes.size(), &features) != VP8_STATUS_OK || @@ -90,7 +86,7 @@ namespace sd::dgl::ops { } #else namespace sd::dgl::ops { - VideoReadResult load_webp(const std::filesystem::path&, size_t, int64_t, int64_t) { + VideoReadResult load_webp(VideoSource&, size_t, int64_t, int64_t) { throw std::runtime_error("WebP video input requires a build with SD_WEBP=ON"); } } diff --git a/src/dgl/ops/video_webp.h b/src/dgl/ops/video_webp.h index 5eb6d35dd9..9304e85d6e 100644 --- a/src/dgl/ops/video_webp.h +++ b/src/dgl/ops/video_webp.h @@ -4,7 +4,7 @@ #include "dgl/ops/video.h" namespace sd::dgl::ops { - VideoReadResult load_webp(const std::filesystem::path& path, size_t max_frames, int64_t fps_num, int64_t fps_den); + VideoReadResult load_webp(VideoSource& source, size_t max_frames, int64_t fps_num, int64_t fps_den); } #endif // __SD_DGL_OPS_VIDEO_WEBP_H__ From da4399b45bb399d1390c0eda4533a6214902b16c Mon Sep 17 00:00:00 2001 From: Salah Eddine Bekhouche Date: Fri, 27 Nov 2026 21:17:14 +0200 Subject: [PATCH 02/11] feat: add sd_video_decode to decode a video held in memory It decodes the formats video::load reads and returns the frames, and the PCM soundtrack when asked, as tensors the caller frees. --- include/stable-diffusion.h | 13 +++++++++++++ src/api/video.cpp | 31 +++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 src/api/video.cpp diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index c41818a581..eb1089a7f8 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -147,6 +147,19 @@ SD_API const void* sd_tensor_data(const sd_tensor_t* tensor); // Failures use sd_get_last_error(). SD_API bool sd_tensor_save(const sd_tensor_t* tensor, const char* path); +// Decodes an AVI (RGB or MJPEG), animated WebP or independent-frame VP8 WebM held in +// memory, as the DGL video::load operation reads a file. fps 0 keeps the source frame rate +// and max_frames 0 keeps every frame. frames_out receives U8 [3,W,H,T]. With samples_out, +// a PCM soundtrack is returned as F32 [C,N] with its rate in *sample_rate_out, or NULL when +// the input has none. Free returned tensors with sd_tensor_free. Failures use sd_get_last_error(). +SD_API sd_status_t sd_video_decode(const void* data, + size_t size, + int fps, + size_t max_frames, + sd_tensor_t** frames_out, + sd_tensor_t** samples_out, + uint32_t* sample_rate_out); + // Options typedef struct { diff --git a/src/api/video.cpp b/src/api/video.cpp new file mode 100644 index 0000000000..0fcc863e5b --- /dev/null +++ b/src/api/video.cpp @@ -0,0 +1,31 @@ +#include "api.h" + +#include "dgl/ops/video.h" + +sd_status_t sd_video_decode(const void* data, + size_t size, + int fps, + size_t max_frames, + sd_tensor_t** frames_out, + sd_tensor_t** samples_out, + uint32_t* sample_rate_out) { + if (frames_out) + *frames_out = nullptr; + if (samples_out) + *samples_out = nullptr; + if (sample_rate_out) + *sample_rate_out = 0; + return sd::api::call([&] { + if (!data || !size || !frames_out || fps < 0) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "data, size and frames_out are required, and fps must not be negative"); + sd::dgl::ops::VideoSource source(data, size); + auto video = sd::dgl::ops::load_video(source, max_frames, fps, 1, samples_out != nullptr); + if (samples_out && video.audio.samples) { + *samples_out = sd_tensor_retain(video.audio.samples.get()); + if (sample_rate_out) + *sample_rate_out = uint32_t(video.audio.sample_rate); + } + *frames_out = sd_tensor_retain(video.frames.get()); + return SD_STATUS_OK; + }); +} From c2950166d3972e7389af9c76eefb8c4a895307c9 Mon Sep 17 00:00:00 2001 From: Salah Eddine Bekhouche Date: Fri, 27 Nov 2026 21:19:14 +0200 Subject: [PATCH 03/11] feat(server): accept video files in vid_gen control_video and string items of ref_videos take a base64 or data URL video file, decoded with sd_video_decode. control_video is sampled at fps and capped at video_frames like --control-video in sd-cli, and replaces control_frames. A reference file's soundtrack is used when ref_video_audios has none at that index. --- examples/common/common.cpp | 88 +++++++++++++++++++++++++++++++++++--- examples/common/common.h | 1 + examples/server/api.md | 21 +++++++-- 3 files changed, 100 insertions(+), 10 deletions(-) diff --git a/examples/common/common.cpp b/examples/common/common.cpp index 17b2fa3e0a..56e8ea7ba5 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -1732,6 +1732,56 @@ bool decode_base64_image(const std::string& encoded_input, return true; } +/** Decodes a base64 AVI, animated WebP or VP8 WebM into frames that share one decoded tensor. */ +static bool decode_base64_video(const std::string& encoded_input, + int fps, + size_t max_frames, + std::vector& out_frames, + SDAudioOwner* out_audio) { + std::string encoded = encoded_input; + auto comma_pos = encoded.find(','); + if (comma_pos != std::string::npos) { + encoded = encoded.substr(comma_pos + 1); + } + std::vector video_bytes = decode_base64_bytes(encoded); + if (video_bytes.empty()) { + return false; + } + + sd_tensor_t* raw_frames = nullptr; + sd_tensor_t* raw_samples = nullptr; + uint32_t sample_rate = 0; + if (sd_video_decode(video_bytes.data(), video_bytes.size(), fps, max_frames, &raw_frames, + out_audio ? &raw_samples : nullptr, &sample_rate) != SD_STATUS_OK) { + LOG_ERROR("cannot decode video input: %s", sd_get_last_error()); + return false; + } + SDTensorPtr frames(raw_frames); + SDTensorPtr samples(raw_samples); + + const auto channels = uint32_t(sd_tensor_dim(frames.get(), 0)); + const auto width = uint32_t(sd_tensor_dim(frames.get(), 1)); + const auto height = uint32_t(sd_tensor_dim(frames.get(), 2)); + const auto count = size_t(sd_tensor_dim(frames.get(), 3)); + const size_t frame_size = size_t(channels) * width * height; + auto* pixels = const_cast(static_cast(sd_tensor_data(frames.get()))); + out_frames.clear(); + out_frames.reserve(count); + for (size_t i = 0; i < count; ++i) { + out_frames.emplace_back(SDImage{width, height, channels, pixels + i * frame_size, sd_tensor_retain(frames.get())}); + } + + if (out_audio) { + out_audio->reset(); + if (samples) { + const auto* data = static_cast(sd_tensor_data(samples.get())); + std::vector values(data, data + sd_tensor_byte_size(samples.get()) / sizeof(float)); + out_audio->reset(std::move(values), sample_rate, uint32_t(sd_tensor_dim(samples.get(), 0))); + } + } + return true; +} + static bool parse_image_json_field(const json& parent, const char* key, int channels, @@ -1821,27 +1871,40 @@ static bool parse_audio_array_json_field(const json& parent, return true; } -/** Parses a JSON array of per-video base64 frame arrays into owned videos. */ +/** + * Parses a JSON array of reference videos, each a base64 frame array or a base64 video file, + * into owned videos. A file's soundtrack goes to out_audios at the video's index. + */ static bool parse_video_array_json_field(const json& parent, const char* key, - std::vector>& out_videos) { + std::vector>& out_videos, + std::vector& out_audios) { if (!parent.contains(key)) { return true; } + out_videos.clear(); + out_audios.clear(); if (parent.at(key).is_null()) { - out_videos.clear(); return true; } if (!parent.at(key).is_array()) { return false; } - out_videos.clear(); for (const auto& video : parent.at(key)) { + std::vector frames; + SDAudioOwner audio; + if (video.is_string()) { + if (!decode_base64_video(video.get(), 24, 0, frames, &audio)) { + return false; + } + out_videos.push_back(std::move(frames)); + out_audios.push_back(std::move(audio)); + continue; + } if (!video.is_array() || video.empty()) { return false; } - std::vector frames; for (const auto& frame : video) { if (!frame.is_string()) { return false; @@ -1853,6 +1916,7 @@ static bool parse_video_array_json_field(const json& parent, frames.push_back(std::move(image)); } out_videos.push_back(std::move(frames)); + out_audios.push_back(std::move(audio)); } return true; } @@ -2140,10 +2204,18 @@ bool SDGenerationParams::from_json_str( !parse_image_array_json_field(j, "control_frames", 3, control_frames) || !parse_audio_array_json_field(j, "ref_audios", ref_audios) || !parse_audio_array_json_field(j, "ref_video_audios", ref_video_audios) || - !parse_video_array_json_field(j, "ref_videos", ref_videos)) { + !parse_video_array_json_field(j, "ref_videos", ref_videos, ref_video_file_audios)) { LOG_ERROR("invalid input image/audio/video array"); return false; } + if (j.contains("control_video") && !j.at("control_video").is_null()) { + if (!j.at("control_video").is_string() || + !decode_base64_video(j.at("control_video").get(), fps.value_or(16), + size_t(std::max(video_frames.value_or(0), 0)), control_frames, nullptr)) { + LOG_ERROR("invalid control_video"); + return false; + } + } return true; } catch (const std::exception& error) { @@ -2599,7 +2671,9 @@ SDOptPtr SDGenerationParams::to_video_opt() { for (auto& frame : ref_videos[i]) { frame_views.push_back(frame.get()); } - SDAudio audio = i < ref_video_audios.size() ? ref_video_audios[i].get() : SDAudio{}; + SDAudio audio = i < ref_video_audios.size() ? ref_video_audios[i].get() + : i < ref_video_file_audios.size() ? ref_video_file_audios[i].get() + : SDAudio{}; ref_video_views.push_back({frame_views.empty() ? nullptr : frame_views.data(), static_cast(frame_views.size()), 24, diff --git a/examples/common/common.h b/examples/common/common.h index cddfaf0c88..bbb5562e64 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -290,6 +290,7 @@ struct SDGenerationParams { std::map prompt_images; std::vector> ref_videos; std::vector ref_video_audios; + std::vector ref_video_file_audios; std::vector ref_audios; SDImageOwner mask_image; SDImageOwner control_image; diff --git a/examples/server/api.md b/examples/server/api.md index ae61d0598f..37b27fd76e 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -180,14 +180,14 @@ Default-enabled features are `img2img`, `mask_image`, `lora`, `vae_tiling`, | `clip_skip` | CLIP Skip | | `img2img`, `mask_image` | Image initialization/strength and masks | | `ref_images` | Reference image inputs | -| `ref_videos` | Reference videos as frame arrays | +| `ref_videos` | Reference videos as frame arrays or video files | | `ref_audios` | Standalone reference audio; runtime requires an Audio VAE or Audio Encoder | | `ref_video_audios` | Soundtracks paired with reference videos; runtime requires an Audio VAE | | `controlnet` | Control image and ControlNet strength | | `control_image` | Control image without a separate ControlNet (FLUX Canny/Depth) | | `ip_adapter` | IP-Adapter image and strength | | `init_image`, `end_image` | Video start/end frames | -| `control_frames`, `vace` | Video control frames and VACE strength | +| `control_frames`, `vace` | Video control frames or `control_video`, and VACE strength | | `high_noise` | High-noise pass, MoE boundary and high-noise LoRAs | | `lora`, `vae_tiling` | LoRA overrides and VAE tiling | | `cache`, `cache_unet`, `cache_dit` | Cache panel and architecture-specific algorithms | @@ -1435,7 +1435,7 @@ Compared with `img_gen`, the `vid_gen` request body: - `vid_gen` is a single video sequence job, so `batch_count` is not part of the request schema - `mask_image`, `control_image`, `control_strength`, `ip_adapter_image`, `ip_adapter_strength`, and `embed_image_metadata` are not part of the request schema - `ref_images` is accepted for MiniMax-H3 Ref2VA conditioning; other video model families currently ignore it -- `vid_gen` adds `end_image`, `control_frames`, `high_noise_sample_params`, `video_frames`, `fps`, `moe_boundary`, and `vace_strength` +- `vid_gen` adds `end_image`, `control_frames`, `control_video`, `high_noise_sample_params`, `video_frames`, `fps`, `moe_boundary`, and `vace_strength` Example: @@ -1561,6 +1561,19 @@ Frame ordering rules: - `control_frames[]` order is the conditioning frame order - `control_frames[]` is preserved in request order +### Video File Inputs + +`control_video` and each item of `ref_videos` can be a video file instead of +frames: a raw base64 string or a data URL such as `data:video/webm;base64,...`. +The server reads the same formats as `video::load`: AVI with RGB or MJPEG +frames, animated WebP, and WebM whose VP8 frames are all keyframes. + +- `control_video` is sampled at `fps` (default 16) and keeps at most + `video_frames` frames. It replaces `control_frames`. +- A `ref_videos` file is sampled at 24 fps. Its PCM soundtrack is used when + `ref_video_audios` has no entry at the same index. +- A file that cannot be decoded fails the request. + If omitted or null: - single-image fields clear the corresponding image tensor @@ -1594,6 +1607,8 @@ Image and frame fields: | `end_image` | `string \| null` | | `ref_images` | `array` | | `control_frames` | `array` | +| `control_video` | `string \| null` | +| `ref_videos` | `array \| string>` | LoRA fields: From 2afdaea34eeaf1a26abb197fdca5e118df671320 Mon Sep 17 00:00:00 2001 From: Salah Eddine Bekhouche Date: Fri, 27 Nov 2026 22:49:53 +0200 Subject: [PATCH 04/11] docs: describe sd_video_decode in the C API guide --- docs/guides/c_api.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md index e456c0050d..205221d0be 100644 --- a/docs/guides/c_api.md +++ b/docs/guides/c_api.md @@ -222,6 +222,14 @@ whose items also carry sample-rate/FPS metadata. These setters retain all nested tensors. Freeing the caller's tensor handles or descriptor arrays does not invalidate configured options. +`sd_video_decode(data, size, fps, max_frames, &frames, &samples, &sample_rate)` +decodes an AVI (RGB or MJPEG), animated WebP or independent-frame VP8 WebM held in +memory, as DGL `video::load` reads a file. `fps` 0 keeps the source rate and +`max_frames` 0 keeps every frame. The frames come back as one 4D tensor ready for +`control_frames`. When `samples` is not NULL and the input has a PCM soundtrack, +it comes back as an F32 sample tensor with its rate in `sample_rate`. Free both +with `sd_tensor_free()`. + `sd_result_get_image()` returns a U8 image/frame tensor. `sd_result_get_audio()` returns sample-rate metadata and a F32 sample tensor. `sd_result_get_video()` returns FPS, optional audio and a contiguous 4D tensor, assembled and cached on From 24fb98928f879e112f913cbc30eb7721adb5115c Mon Sep 17 00:00:00 2001 From: Salah Eddine Bekhouche Date: Sat, 28 Nov 2026 09:03:53 +0200 Subject: [PATCH 05/11] fix(server): skip a reference video's soundtrack when its audio is given --- examples/common/common.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/examples/common/common.cpp b/examples/common/common.cpp index 56e8ea7ba5..7d142dd21b 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -1873,10 +1873,12 @@ static bool parse_audio_array_json_field(const json& parent, /** * Parses a JSON array of reference videos, each a base64 frame array or a base64 video file, - * into owned videos. A file's soundtrack goes to out_audios at the video's index. + * into owned videos. A file's soundtrack goes to out_audios at the video's index; it is not + * decoded for the first explicit_audios videos, whose audio comes from ref_video_audios. */ static bool parse_video_array_json_field(const json& parent, const char* key, + size_t explicit_audios, std::vector>& out_videos, std::vector& out_audios) { if (!parent.contains(key)) { @@ -1895,7 +1897,8 @@ static bool parse_video_array_json_field(const json& parent, std::vector frames; SDAudioOwner audio; if (video.is_string()) { - if (!decode_base64_video(video.get(), 24, 0, frames, &audio)) { + const bool explicit_audio = out_videos.size() < explicit_audios; + if (!decode_base64_video(video.get(), 24, 0, frames, explicit_audio ? nullptr : &audio)) { return false; } out_videos.push_back(std::move(frames)); @@ -2204,7 +2207,7 @@ bool SDGenerationParams::from_json_str( !parse_image_array_json_field(j, "control_frames", 3, control_frames) || !parse_audio_array_json_field(j, "ref_audios", ref_audios) || !parse_audio_array_json_field(j, "ref_video_audios", ref_video_audios) || - !parse_video_array_json_field(j, "ref_videos", ref_videos, ref_video_file_audios)) { + !parse_video_array_json_field(j, "ref_videos", ref_video_audios.size(), ref_videos, ref_video_file_audios)) { LOG_ERROR("invalid input image/audio/video array"); return false; } From d66e31dc17101ad3429122bb4a72fb4dc68d4921 Mon Sep 17 00:00:00 2001 From: Salah Eddine Bekhouche Date: Sat, 28 Nov 2026 09:07:30 +0200 Subject: [PATCH 06/11] fix: limit sd_video_decode fps and note that 0 needs a fixed rate --- docs/guides/c_api.md | 5 +++-- include/stable-diffusion.h | 9 +++++---- src/api/video.cpp | 4 ++-- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md index 205221d0be..9fc9ca110f 100644 --- a/docs/guides/c_api.md +++ b/docs/guides/c_api.md @@ -224,8 +224,9 @@ invalidate configured options. `sd_video_decode(data, size, fps, max_frames, &frames, &samples, &sample_rate)` decodes an AVI (RGB or MJPEG), animated WebP or independent-frame VP8 WebM held in -memory, as DGL `video::load` reads a file. `fps` 0 keeps the source rate and -`max_frames` 0 keeps every frame. The frames come back as one 4D tensor ready for +memory, as DGL `video::load` reads a file. `fps` 0 keeps the source rate, and +fails when the input has no fixed rate, such as an animated WebP with uneven frame +durations; `fps` is at most 1000000. `max_frames` 0 keeps every frame. The frames come back as one 4D tensor ready for `control_frames`. When `samples` is not NULL and the input has a PCM soundtrack, it comes back as an F32 sample tensor with its rate in `sample_rate`. Free both with `sd_tensor_free()`. diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index eb1089a7f8..338e61f0a3 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -148,10 +148,11 @@ SD_API const void* sd_tensor_data(const sd_tensor_t* tensor); SD_API bool sd_tensor_save(const sd_tensor_t* tensor, const char* path); // Decodes an AVI (RGB or MJPEG), animated WebP or independent-frame VP8 WebM held in -// memory, as the DGL video::load operation reads a file. fps 0 keeps the source frame rate -// and max_frames 0 keeps every frame. frames_out receives U8 [3,W,H,T]. With samples_out, -// a PCM soundtrack is returned as F32 [C,N] with its rate in *sample_rate_out, or NULL when -// the input has none. Free returned tensors with sd_tensor_free. Failures use sd_get_last_error(). +// memory, as the DGL video::load operation reads a file. fps is at most 1000000; 0 keeps +// the source frame rate and fails when the input has no fixed rate. max_frames 0 keeps +// every frame. frames_out receives U8 [3,W,H,T]. With samples_out, a PCM soundtrack is +// returned as F32 [C,N] with its rate in *sample_rate_out, or NULL when the input has none. +// Free returned tensors with sd_tensor_free. Failures use sd_get_last_error(). SD_API sd_status_t sd_video_decode(const void* data, size_t size, int fps, diff --git a/src/api/video.cpp b/src/api/video.cpp index 0fcc863e5b..cc9c290088 100644 --- a/src/api/video.cpp +++ b/src/api/video.cpp @@ -16,8 +16,8 @@ sd_status_t sd_video_decode(const void* data, if (sample_rate_out) *sample_rate_out = 0; return sd::api::call([&] { - if (!data || !size || !frames_out || fps < 0) - return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "data, size and frames_out are required, and fps must not be negative"); + if (!data || !size || !frames_out || fps < 0 || fps > 1000000) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "data, size and frames_out are required, and fps must be 0 to 1000000"); sd::dgl::ops::VideoSource source(data, size); auto video = sd::dgl::ops::load_video(source, max_frames, fps, 1, samples_out != nullptr); if (samples_out && video.audio.samples) { From d1747d2c043f8ea2f7a74c79e5f1b416342a1cd4 Mon Sep 17 00:00:00 2001 From: Salah Eddine Bekhouche Date: Sat, 28 Nov 2026 21:30:36 +0200 Subject: [PATCH 07/11] fix(server): decode control_video up to the default frame count --- examples/common/common.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/common/common.cpp b/examples/common/common.cpp index 7d142dd21b..1d320060c7 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -2214,7 +2214,7 @@ bool SDGenerationParams::from_json_str( if (j.contains("control_video") && !j.at("control_video").is_null()) { if (!j.at("control_video").is_string() || !decode_base64_video(j.at("control_video").get(), fps.value_or(16), - size_t(std::max(video_frames.value_or(0), 0)), control_frames, nullptr)) { + size_t(std::max(video_frames.value_or(6), 0)), control_frames, nullptr)) { LOG_ERROR("invalid control_video"); return false; } From ef253aafc3de3b337ab6917fa62a163ade1a1b20 Mon Sep 17 00:00:00 2001 From: Salah Eddine Bekhouche Date: Mon, 30 Nov 2026 18:01:54 +0200 Subject: [PATCH 08/11] feat: add sd_ctx_get_video_frame_count for the aligned frame count --- docs/guides/c_api.md | 3 +++ include/stable-diffusion.h | 3 +++ src/api/api.cpp | 8 ++++++++ 3 files changed, 14 insertions(+) diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md index 9fc9ca110f..ed31352f92 100644 --- a/docs/guides/c_api.md +++ b/docs/guides/c_api.md @@ -91,6 +91,9 @@ exposes frames through the same image accessors, optional audio through `sd_result_get_audio()`, and effective frame rate through `sd_result_get_fps()`. `sd_result_get_kind()` distinguishes image batches from videos. Video generation metadata is sequence-wide and is returned for every valid frame index. +`sd_ctx_get_video_frame_count(ctx, frames)` returns the frame count the loaded +model produces for a request of `frames`; Wan, for example, aligns 6 to 9. Use it +to size `control_frames` or the `max_frames` of `sd_video_decode()`. All option names are aliases of the same opaque `sd_opt_t` type and share all `sd_opt_set_*()`, `sd_opt_unset()` and `sd_opt_free()` functions. The constructor diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index 338e61f0a3..f446cc7f1e 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -243,6 +243,9 @@ SD_API bool sd_ctx_supports_video_generation(const sd_ctx_t* sd_ctx); // Probes model metadata lazily; returns a static string, or "Unknown" on error. SD_API const char* sd_get_model_version_name(const sd_ctx_t* sd_ctx); +// Returns the frame count a video request for `frames` produces with the loaded model +// (Wan, for example, aligns 6 to 9), or 0 on error. +SD_API int sd_ctx_get_video_frame_count(const sd_ctx_t* sd_ctx, int frames); enum sd_cancel_mode_t { // Stop the current generation as soon as possible. diff --git a/src/api/api.cpp b/src/api/api.cpp index fa6b766c5f..3ce82d7ba9 100644 --- a/src/api/api.cpp +++ b/src/api/api.cpp @@ -11,6 +11,7 @@ #include "core/ggml_extend.h" #include "core/option_types.h" #include "core/util.h" +#include "model/vae/geometry.hpp" static thread_local char last_error[512] = {}; @@ -199,6 +200,13 @@ const char* sd_get_model_version_name(const sd_ctx_t* context) { return definition ? definition->name : "Unknown"; } +int sd_ctx_get_video_frame_count(const sd_ctx_t* context, int frames) { + if (frames <= 0) + return 0; + const auto* definition = context_definition(context); + return definition ? sd::vae::aligned_frames(definition->version, frames) : 0; +} + sd_status_t sd_ctx_set_file_access_callback(sd_ctx_t* context, sd_dgl_file_access_cb_t callback, void* data) { return sd::api::call([&] { if (!context || !context->engine) From 9650c44d5d99e71d644868c5c33c5c100c52796e Mon Sep 17 00:00:00 2001 From: Salah Eddine Bekhouche Date: Mon, 30 Nov 2026 18:08:27 +0200 Subject: [PATCH 09/11] fix(server): decode control_video up to the model's aligned frame count --- examples/common/common.cpp | 19 ++++++++++++++++--- examples/common/common.h | 2 ++ examples/server/routes_sdcpp.cpp | 4 ++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/examples/common/common.cpp b/examples/common/common.cpp index 1d320060c7..4aa9c1a02b 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -2015,6 +2015,20 @@ static bool resolve_model_file_from_dir(const std::string& model_name, return false; } +// The model aligns the frame count (Wan turns 6 into 9), so decode up to the count it generates. +bool SDGenerationParams::decode_control_video(const sd_ctx_t* ctx) { + if (control_video.empty()) { + return true; + } + const int frames = sd_ctx_get_video_frame_count(ctx, video_frames.value_or(6)); + if (frames <= 0 || !decode_base64_video(control_video, fps.value_or(16), size_t(frames), control_frames, nullptr)) { + LOG_ERROR("invalid control_video"); + return false; + } + control_video.clear(); + return true; +} + bool SDGenerationParams::parse_prompt_images_json(const std::string& json_str) { auto images = json::parse(json_str, nullptr, false); if (!images.is_object()) { @@ -2212,12 +2226,11 @@ bool SDGenerationParams::from_json_str( return false; } if (j.contains("control_video") && !j.at("control_video").is_null()) { - if (!j.at("control_video").is_string() || - !decode_base64_video(j.at("control_video").get(), fps.value_or(16), - size_t(std::max(video_frames.value_or(6), 0)), control_frames, nullptr)) { + if (!j.at("control_video").is_string() || j.at("control_video").get_ref().empty()) { LOG_ERROR("invalid control_video"); return false; } + control_video = j.at("control_video").get(); } return true; diff --git a/examples/common/common.h b/examples/common/common.h index bbb5562e64..8151c5c045 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -234,6 +234,7 @@ struct SDGenerationParams { std::vector ref_video_audio_paths; std::vector ref_audio_paths; std::string control_video_path; + std::string control_video; SDSampleParams sample_params; SDSampleParams high_noise_sample_params; @@ -313,6 +314,7 @@ struct SDGenerationParams { bool from_json_str(const std::string& json_str, const std::function& lora_path_resolver = {}); bool parse_prompt_images_json(const std::string& json_str); + bool decode_control_video(const sd_ctx_t* ctx); bool initialize_cache_params(); bool extract_and_remove_lora(const std::string& lora_model_dir); bool width_and_height_are_set() const; diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index d107229983..212cd25472 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -420,6 +420,10 @@ static bool parse_vid_gen_request(const json& body, error_message = "invalid generation parameters"; return false; } + if (!request.gen_params.decode_control_video(runtime.sd_ctx)) { + error_message = "invalid control_video"; + return false; + } auto& params = request.gen_params; auto merge_shared_sample_input = [&](const char* key, auto member) { From 79962a1b996e66aced4517458de536fe33a1f628 Mon Sep 17 00:00:00 2001 From: Salah Eddine Bekhouche Date: Mon, 30 Nov 2026 18:14:05 +0200 Subject: [PATCH 10/11] fix(cli): read --control-video up to the model's aligned frame count --- examples/cli/main.cpp | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp index e3b7202f45..0001639cb8 100644 --- a/examples/cli/main.cpp +++ b/examples/cli/main.cpp @@ -745,20 +745,6 @@ int main(int argc, const char* argv[]) { } } - VideoInput control_video_input; - if (!gen_params.control_video_path.empty()) { - gen_params.control_frames.clear(); - if (fs::is_directory(fs::u8path(gen_params.control_video_path))) { - if (!load_images_from_dir(gen_params.control_video_path, - gen_params.control_frames, - gen_params.video_frames.value_or(0))) - return 1; - } else if (!load_video_input(gen_params.control_video_path, gen_params.fps.value_or(16), - gen_params.video_frames.value_or(0), false, control_video_input)) { - return 1; - } - } - SDOptPtr sd_ctx_params = ctx_params.to_context_opt(); SDImageVec results; @@ -797,6 +783,23 @@ int main(int argc, const char* argv[]) { results.adopt(generated); num_results = results.count(); } else if (cli_params.mode == VID_GEN) { + VideoInput control_video_input; + if (!gen_params.control_video_path.empty()) { + // The model aligns the frame count (Wan turns 6 into 9), so read up to the count it generates. + const int frames = sd_ctx_get_video_frame_count(sd_ctx.get(), gen_params.video_frames.value_or(6)); + if (frames <= 0) { + LOG_ERROR("invalid video frame count"); + return 1; + } + gen_params.control_frames.clear(); + if (fs::is_directory(fs::u8path(gen_params.control_video_path))) { + if (!load_images_from_dir(gen_params.control_video_path, gen_params.control_frames, frames)) + return 1; + } else if (!load_video_input(gen_params.control_video_path, gen_params.fps.value_or(16), + size_t(frames), false, control_video_input)) { + return 1; + } + } SDOptPtr vid_gen_params = gen_params.to_video_opt(); if (!vid_gen_params || !set_video_inputs(vid_gen_params.get(), reference_video_inputs, control_video_input.frames.get())) return 1; From a1a6ddf35da5d4bef4ecaa052bd2301280439b3c Mon Sep 17 00:00:00 2001 From: Salah Eddine Bekhouche Date: Mon, 30 Nov 2026 18:49:47 +0200 Subject: [PATCH 11/11] fix(server): decode control_video with the model selected for the job --- examples/server/async_jobs.cpp | 3 ++- examples/server/async_jobs.h | 1 + examples/server/routes_sdcpp.cpp | 20 ++++++++++++++------ 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index 329cf29e8d..e8a83dd13f 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -376,7 +376,8 @@ static bool prepare_native_job(ServerRuntime& runtime, AsyncGenerationJob& job, const SDMode mode = job.kind == AsyncJobKind::VidGen ? VID_GEN : IMG_GEN; if (job.model) { auto model = std::move(job.model); - return set_current_model(runtime, std::move(*model), mode, error_message); + return set_current_model(runtime, std::move(*model), mode, error_message) && + decode_native_job_control_video(runtime, job, error_message); } auto body = std::move(job.request_body); if (job.model_revision == runtime.models->revision) diff --git a/examples/server/async_jobs.h b/examples/server/async_jobs.h index 0f8b932315..66ae99b208 100644 --- a/examples/server/async_jobs.h +++ b/examples/server/async_jobs.h @@ -98,6 +98,7 @@ std::string make_async_job_id(AsyncJobManager& manager); bool cancel_queued_job(AsyncJobManager& manager, AsyncGenerationJob& job); json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJob& job); bool parse_native_job_request(const json& body, ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message); +bool decode_native_job_control_video(ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message); bool execute_img_gen_job(ServerRuntime& runtime, AsyncGenerationJob& job, std::vector& output_images, diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index cc52f21608..1c3cb25ad5 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -428,10 +428,6 @@ static bool parse_vid_gen_request(const json& body, error_message = "invalid generation parameters"; return false; } - if (!request.gen_params.decode_control_video(runtime.sd_ctx)) { - error_message = "invalid control_video"; - return false; - } auto& params = request.gen_params; auto merge_shared_sample_input = [&](const char* key, auto member) { @@ -464,8 +460,20 @@ static bool parse_vid_gen_request(const json& body, } bool parse_native_job_request(const json& body, ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message) { - return job.kind == AsyncJobKind::VidGen ? parse_vid_gen_request(body, runtime, job.vid_gen, error_message) - : parse_img_gen_request(body, runtime, job.img_gen, error_message); + if (job.kind != AsyncJobKind::VidGen) + return parse_img_gen_request(body, runtime, job.img_gen, error_message); + if (!parse_vid_gen_request(body, runtime, job.vid_gen, error_message)) + return false; + // A selected model is only active once the job starts, so its frame count is not known yet. + return job.model || decode_native_job_control_video(runtime, job, error_message); +} + +bool decode_native_job_control_video(ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message) { + if (job.kind == AsyncJobKind::VidGen && !job.vid_gen.gen_params.decode_control_video(runtime.sd_ctx)) { + error_message = "invalid control_video"; + return false; + } + return true; } static void submit_generation_job(ServerRuntime& runtime, const httplib::Request& req, httplib::Response& res, SDMode mode) {