Commit c4adf9c for stable-diffusion.cpp

commit c4adf9c997c4bc76918f950faf8622a76f3f2a8b
Author: Salah Eddine Bekhouche <bekhouchesalah@gmail.com>
Date:   Thu Dec 3 15:58:17 2026 +0200

    feat: decode video files from memory and accept them in the server's vid_gen (#2447)

diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md
index 0ee98d3..cebea0c 100644
--- a/docs/guides/c_api.md
+++ b/docs/guides/c_api.md
@@ -94,6 +94,11 @@ 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, model_options, frames)` returns the frame count
+a request of `frames` produces; Wan, for example, aligns 6 to 9. With `model_options`
+NULL it uses the context's model, otherwise it inspects those model options without
+changing the context. It returns 0 on error or when the count does not fit in an
+`int`. 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
@@ -225,6 +230,16 @@ 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 a video held in memory as DGL `video::load` reads a file: AVI (RGB or
+MJPEG), animated WebP and independent-frame VP8 WebM are built in, and other
+formats use the [FFmpeg fallback](../dgl.md#ffmpeg-fallback) when it is available. `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 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
diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp
index dd9089f..89bee03 100644
--- a/examples/cli/main.cpp
+++ b/examples/cli/main.cpp
@@ -727,20 +727,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;
-        }
-    }
-
     // A single generation run needs no component cache; each model is released after its last use.
     if (cli_params.mode == VID_GEN || (cli_params.mode == IMG_GEN && gen_params.batch_count.value_or(1) <= 1))
         ctx_params.run_once = true;
@@ -782,6 +768,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(), nullptr, 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;
diff --git a/examples/common/common.cpp b/examples/common/common.cpp
index 1101f94..66b2b5d 100644
--- a/examples/common/common.cpp
+++ b/examples/common/common.cpp
@@ -1733,6 +1733,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<SDImageOwner>& 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<uint8_t> 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<uint8_t*>(static_cast<const uint8_t*>(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<const float*>(sd_tensor_data(samples.get()));
+            std::vector<float> 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,
@@ -1822,27 +1872,43 @@ 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; 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,
-                                         std::vector<std::vector<SDImageOwner>>& out_videos) {
+                                         size_t explicit_audios,
+                                         std::vector<std::vector<SDImageOwner>>& out_videos,
+                                         std::vector<SDAudioOwner>& 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<SDImageOwner> frames;
+        SDAudioOwner audio;
+        if (video.is_string()) {
+            const bool explicit_audio = out_videos.size() < explicit_audios;
+            if (!decode_base64_video(video.get<std::string>(), 24, 0, frames, explicit_audio ? nullptr : &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<SDImageOwner> frames;
         for (const auto& frame : video) {
             if (!frame.is_string()) {
                 return false;
@@ -1854,6 +1920,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;
 }
@@ -1949,6 +2016,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(sd_ctx_t* ctx, const sd_ctx_opt_t* model_options) {
+    if (control_video.empty()) {
+        return true;
+    }
+    const int frames = sd_ctx_get_video_frame_count(ctx, model_options, 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()) {
@@ -2137,14 +2218,22 @@ bool SDGenerationParams::from_json_str(
         !load_image("ip_adapter_image", 3, ip_adapter_image)) {
         return false;
     }
+    const bool has_control_video = j.contains("control_video") && !j.at("control_video").is_null();
     if (!parse_image_array_json_field(j, "ref_images", 0, ref_images) ||
-        !parse_image_array_json_field(j, "control_frames", 3, control_frames) ||
+        (!has_control_video && !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_video_audios.size(), ref_videos, ref_video_file_audios)) {
         LOG_ERROR("invalid input image/audio/video array");
         return false;
     }
+    if (has_control_video) {
+        if (!j.at("control_video").is_string() || j.at("control_video").get_ref<const std::string&>().empty()) {
+            LOG_ERROR("invalid control_video");
+            return false;
+        }
+        control_video = j.at("control_video").get<std::string>();
+    }

     return true;
 } catch (const std::exception& error) {
@@ -2600,7 +2689,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<int>(frame_views.size()),
                                    24,
diff --git a/examples/common/common.h b/examples/common/common.h
index 509f673..f505318 100644
--- a/examples/common/common.h
+++ b/examples/common/common.h
@@ -235,6 +235,7 @@ struct SDGenerationParams {
     std::vector<std::string> ref_video_audio_paths;
     std::vector<std::string> ref_audio_paths;
     std::string control_video_path;
+    std::string control_video;

     SDSampleParams sample_params;
     SDSampleParams high_noise_sample_params;
@@ -291,6 +292,7 @@ struct SDGenerationParams {
     std::map<std::string, SDImageOwner> prompt_images;
     std::vector<std::vector<SDImageOwner>> ref_videos;
     std::vector<SDAudioOwner> ref_video_audios;
+    std::vector<SDAudioOwner> ref_video_file_audios;
     std::vector<SDAudioOwner> ref_audios;
     SDImageOwner mask_image;
     SDImageOwner control_image;
@@ -313,6 +315,7 @@ struct SDGenerationParams {
     bool from_json_str(const std::string& json_str,
                        const std::function<std::string(const std::string&)>& lora_path_resolver = {});
     bool parse_prompt_images_json(const std::string& json_str);
+    bool decode_control_video(sd_ctx_t* ctx, const sd_ctx_opt_t* model_options = nullptr);
     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/api.md b/examples/server/api.md
index 5a08131..ccea2c7 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 |
@@ -1432,7 +1432,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:

@@ -1535,6 +1535,26 @@ 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, plus formats
+such as H.264 MP4 through the
+[FFmpeg fallback](../../docs/dgl.md#ffmpeg-fallback) when it is available.
+
+- `control_video` is sampled at `fps` (default 16) and keeps at most the
+  frame count the model generates for `video_frames` (default 6) after its
+  alignment; Wan, for example, aligns 6 to 9. It replaces `control_frames`,
+  which is then not read.
+- A `ref_videos` file is sampled at 24 fps. Its soundtrack is used when
+  `ref_video_audios` has no entry at the same index. A soundtrack the built-in
+  readers do not support, such as MP3 in an AVI, needs FFmpeg and otherwise
+  fails the request. A WAV in `ref_video_audios` at that index is used instead,
+  and the file's soundtrack is not decoded.
+- A file that cannot be decoded fails the request.
+
 If omitted or null:

 - single-image fields clear the corresponding image tensor
@@ -1568,6 +1588,8 @@ Image and frame fields:
 | `end_image` | `string \| null` |
 | `ref_images` | `array<string>` |
 | `control_frames` | `array<string>` |
+| `control_video` | `string \| null` |
+| `ref_videos` | `array<array<string> \| string>` |

 LoRA fields:

diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp
index 6e7275b..42de12b 100644
--- a/examples/server/async_jobs.cpp
+++ b/examples/server/async_jobs.cpp
@@ -376,7 +376,9 @@ 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);
+        // Decode against the selected model first, so a clip that fails leaves the current model in place.
+        return decode_native_job_control_video(runtime, job, error_message, model->options.get()) &&
+               set_current_model(runtime, std::move(*model), mode, 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 0f8b932..fb16643 100644
--- a/examples/server/async_jobs.h
+++ b/examples/server/async_jobs.h
@@ -98,6 +98,10 @@ 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,
+                                     const sd_ctx_opt_t* model_options = nullptr);
 bool execute_img_gen_job(ServerRuntime& runtime,
                          AsyncGenerationJob& job,
                          std::vector<std::string>& output_images,
diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp
index 6dbb1e2..4a64eb7 100644
--- a/examples/server/routes_sdcpp.cpp
+++ b/examples/server/routes_sdcpp.cpp
@@ -460,8 +460,23 @@ 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,
+                                     const sd_ctx_opt_t* model_options) {
+    if (job.kind == AsyncJobKind::VidGen && !job.vid_gen.gen_params.decode_control_video(runtime.sd_ctx, model_options)) {
+        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) {
diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h
index 47de984..9b0208b 100644
--- a/include/stable-diffusion.h
+++ b/include/stable-diffusion.h
@@ -124,6 +124,21 @@ 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 a video held in memory as the DGL video::load operation reads a file: AVI (RGB or
+// MJPEG), animated WebP and independent-frame VP8 WebM are built in, and other formats use
+// the FFmpeg fallback when it is available. 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, the 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 {
@@ -206,6 +221,10 @@ 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 (Wan, for example, aligns
+// 6 to 9), or 0 on error or when it does not fit in an int. model_options NULL uses the
+// context's model; otherwise those model options are inspected without changing the context.
+SD_API int sd_ctx_get_video_frame_count(sd_ctx_t* sd_ctx, const sd_ctx_opt_t* model_options, 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 fa6b766..43830ab 100644
--- a/src/api/api.cpp
+++ b/src/api/api.cpp
@@ -7,10 +7,12 @@
 #include <algorithm>
 #include <cstdio>
 #include <cstring>
+#include <limits>

 #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 +201,31 @@ const char* sd_get_model_version_name(const sd_ctx_t* context) {
     return definition ? definition->name : "Unknown";
 }

+int sd_ctx_get_video_frame_count(sd_ctx_t* context, const sd_ctx_opt_t* model_options, int frames) {
+    if (frames <= 0)
+        return 0;
+    const ModelDefinition* definition = nullptr;
+    if (!model_options) {
+        definition = context_definition(context);
+    } else {
+        sd::api::call([&] {
+            if (!context || !context->engine)
+                return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "context is required");
+            auto& engine = *context->engine;
+            sd::api::GenerationModel candidate(sd::api::copy_options(model_options), sd::api::Context);
+            sd::FileAccessScope access(engine.file_access);
+            definition = &candidate.definition(engine);
+            sd::api::clear_error();
+            return SD_STATUS_OK;
+        },
+                      SD_STATUS_LOAD_FAILED);
+    }
+    if (!definition)
+        return 0;
+    const int64_t aligned = sd::vae::aligned_frame_count(definition->version, frames);
+    return aligned <= std::numeric_limits<int>::max() ? int(aligned) : 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)
diff --git a/src/api/video.cpp b/src/api/video.cpp
new file mode 100644
index 0000000..9d21167
--- /dev/null
+++ b/src/api/video.cpp
@@ -0,0 +1,36 @@
+#include "api.h"
+
+#include "dgl/ops/ffmpeg.h"
+#include "dgl/ops/media_input.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 || 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");
+        if (size > sd::dgl::ops::media_decode_limit)
+            return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "video data exceeds 256 MiB");
+        const auto* bytes = static_cast<const uint8_t*>(data);
+        const std::vector<uint8_t> buffer(bytes, bytes + size);
+        sd::dgl::ops::MediaInput input(buffer);
+        auto video = sd::dgl::ops::decode_video_with_fallback(input, 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;
+    });
+}
diff --git a/src/model/vae/geometry.hpp b/src/model/vae/geometry.hpp
index 1958149..d5daaf4 100644
--- a/src/model/vae/geometry.hpp
+++ b/src/model/vae/geometry.hpp
@@ -35,18 +35,22 @@ namespace sd::vae {
         return 8;
     }

-    inline int aligned_frames(SDVersion version, int frames) {
+    inline int64_t aligned_frame_count(SDVersion version, int64_t frames) {
         if (frames <= 0)
             throw std::invalid_argument("video frame count must be positive");
         if (sd_version_is_minimax_h3(version))
-            return int(sd::align_video_frame_count(frames, 17, 5));
+            return sd::align_video_frame_count(frames, 17, 5);
         if (sd_version_is_ltxav(version))
-            return int(sd::align_video_frame_count(frames, 8));
+            return sd::align_video_frame_count(frames, 8);
         if (sd_version_is_wan(version) || sd_version_is_lingbot_video(version) ||
             sd_version_is_hunyuan_video(version) || version == VERSION_SEEDVR2)
-            return int(sd::align_video_frame_count(frames, 4));
+            return sd::align_video_frame_count(frames, 4);
         return frames;
     }
+
+    inline int aligned_frames(SDVersion version, int frames) {
+        return int(aligned_frame_count(version, frames));
+    }
 }

 #endif  // __SD_MODEL_VAE_GEOMETRY_HPP__