feat: add inline media previews to the DGL editor (#2423)
Some checks are pending
CI / ubuntu-latest-cmake (push) Waiting to run
CI / ubuntu-latest-cmake-vulkan (push) Waiting to run
CI / Build and push container images (push) Waiting to run
CI / macOS-latest-cmake (push) Waiting to run
CI / windows-latest-cmake (cpu, -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_LIBS=ON -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON) (push) Waiting to run
CI / windows-latest-cmake (cuda12, -DSD_CUDA=ON -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_CUDA_COMPILER_LAUNCHER=ccache -DSD_BUILD_SHARED_LIBS=ON -DCMAKE_CUDA_ARCHITECTURES='61;70;75;80;86;89;90;100;120' -DCMAKE_CUDA_FL… (push) Waiting to run
CI / windows-latest-cmake (vulkan, -DSD_VULKAN=ON -DSD_BUILD_SHARED_LIBS=ON -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON) (push) Waiting to run
CI / windows-latest-rocm (push) Waiting to run
CI / ubuntu-latest-rocm (10.1.0, x64, gfx900;gfx906;gfx908;gfx90a;gfx90c;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1103;gfx1150;gfx1151;gfx1152;gfx1153;gfx1200;gfx1201) (push) Waiting to run
CI / release (push) Blocked by required conditions

This commit is contained in:
leejet 2026-11-26 02:38:21 +08:00 • committed by GitHub
parent 5fa203c758
commit 52491bd9f1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 591 additions and 240 deletions

1
.gitignore vendored
View file

@ -5,6 +5,7 @@ tests/
/dgl/*
!/dgl/.gitkeep
logs/
input/
output/
.vscode/
.idea/

View file

@ -1163,8 +1163,7 @@ return {cover = cover, clip = clip, latent = latent}
`media::save(path, media)` writes these exact bytes, with no re-encoding or
metadata changes. It checks file-write permission and the extension against the
MIME type. Omit the save calls for in-memory results only. The server's DGL
editor displays returned media from the existing job result; ordinary tensors
remain available for inspection.
editor displays returned media and ordinary tensor metadata in the job result.
| Encoding | MIME type | Requirements |
| --- | --- | --- |
@ -1892,7 +1891,8 @@ clears the registration. The sampling pass counter starts at one on each
run. Progress can report model loading in tensors, sampling in steps, video
upscaling in frames, or a stage with no known total.
Without a progress callback, the DGL execution layer displays sampling and
weight-loading progress bars. With a callback, the host controls their display.
weight-loading progress bars. Set `sd_dgl_ctx_set(ctx, "console_progress", "on")`
on an idle context to display those bars alongside a progress callback.
The default observer handles previews. Preview mode `proj` uses latent projection. Modes `tae` and `vae`
use the decoder supplied to `preview(decoder=...)`, falling back to projection. A positive interval

View file

@ -78,6 +78,7 @@ add_executable(${TARGET}
routes_sdapi.cpp
routes_sdcpp.cpp
routes_dgl.cpp
routes_media.cpp
)
if(APPLE)
sd_set_macos_rpaths(${TARGET})

View file

@ -126,21 +126,46 @@ and are not parsed by the native server API.
### DGL editor
Open the Web UI using the local server address and select **DGL** in the header.
Select a saved script or choose **New**. **Duplicate** saves a copy of the
current editor text under a new name. Edit **File name** before saving to save
under a different name. **Run** submits the editor text to the generation queue,
so you can run unsaved edits. The results panel shows text, scalar and tensor
information and returned encoded media. PNG appears as an image, WebM as a
video player, and AVI as a download. WebM encoding is silent; use AVI for
a PCM16 soundtrack.
Open the Web UI and select **DGL** in the header. The workspace follows the
server's `--listen-ip` setting. The default `127.0.0.1` limits access to the
server machine. When the server listens on a LAN interface, open the Web UI
using the server's LAN IP and port to use the workspace from another device.
Use **Search scripts** to filter the script list, then select a saved script or
choose **New**. **Save** updates the current file or asks for a name for a new
script. Use **Save as…** to save a copy. The editor reopens the last saved script
used in that browser when it is still available. **Run** submits the current
editor text to the generation queue, including unsaved edits. The status bar
below the editor shows progress and keeps the final status and elapsed time.
The server terminal displays weight-loading throughput and sampling speed.
When a script returns values, **View result** appears in the status bar. Open it
to inspect text, scalars, tensor metadata, and encoded media. PNG appears as an
image, WebM as a video player, and AVI as a download. WebM encoding is silent.
Use AVI for a PCM16 soundtrack.
Use `image::encode` or `video::encode` and return their `{data, mime_type}`
dicts, either directly or as named fields of the root dict. To save the same
encoded output, call `media::save("output/cover.png", cover)` before returning
it. Saving is optional. The job result contains the same encoded bytes, and
polling does not encode them again. Tensor frames can be inspected separately
with **Inspect tensor frames**; they are not fetched automatically.
polling returns them without re-encoding.
The editor underlines supported media paths and shows compact previews below
their lines. Previews align with the code indentation, and files on the same
line appear side by side when space permits. Media loads near the visible area
of the editor. An output path without a file stays collapsed, and a completed
run refreshes its preview when the file becomes available. Drag the handle in
a preview's lower-right corner to resize it, or double-click the handle to reset it.
Click an image or video preview to open it at a larger size. Expanded videos
open at the current playback position. Click the picture to play or pause, or
drag the timeline below it to seek. AVI path previews support MJPEG and
uncompressed 24-bit RGB video with up to 64 MiB of PCM or 32-bit float audio.
The speaker button mutes the preview. To adjust volume in an inline preview,
hover or focus the speaker button to open the volume slider.
Use a relative path under the server's working directory, such as
`assets/reference.png` or `output/clip.webm`. Turn off **Media view** in the
editor toolbar to hide the preview. The server previews files under `input/`,
`output/`, and `assets/`. Start the server
with `--no-media-view` to disable file previews at the server.
DGL jobs share an execution context for the lifetime of the server. Compatible
scripts can reuse loaded model components across runs. The context can release
@ -433,29 +458,37 @@ configured defaults.
| --- | --- | --- |
| `--listen-ip <ip>` | `127.0.0.1` | Server listen address |
| `--listen-port <port>` | `1234` | Server listen port |
| `--dgl-dir <path>` | `dgl` | Script directory for the local DGL editor |
| `--dgl-dir <path>` | `dgl` | Script directory for the DGL editor |
| `--no-media-view` | Off | Disable the media view endpoint |
| `--max-pending-jobs <count>` | `64` | Maximum async jobs queued or generating |
| `--completed-ttl-seconds <seconds>` | `600` | Retention time for completed async jobs |
### Access
By default any program on the machine, and any web page open in a browser on
it, can call the server. To limit that:
The default listener accepts connections from the server machine. A listener
bound to a LAN interface also accepts connections from devices that can reach
it. You can open the Web UI from a link on another site. Browser API requests
are same-origin by default. Use an IP address, `localhost`, or the hostname
configured as the listen address when connecting directly.
| Option | Default | Purpose |
| --- | --- | --- |
| `--api-key <key>` | none | Key clients must send as `Authorization: Bearer <key>` or `X-Api-Key: <key>`. Separate multiple keys with commas. |
| `--api-key-file <file>` | none | The same, one key per line, so keys don't show in the process list |
| `--cors-origins <origins>` | any | Web origins allowed to read the server's answers in a browser, comma-separated |
| `--cors-origins <origins>` | none | Additional browser origins allowed to make cross-origin requests, comma-separated |
With a key, the page at `/` still loads, but the bundled Web UI can't send
the key, so its calls get `401`; it is meant for use without a key.
With a key, the page at `/` still loads. Enter the key in **Settings → Server API Key**
and select **Apply**. The Web UI saves it for that server in the current browser tab.
Leave **Base URL** blank when connecting to the server that serves the Web UI.
DGL scripts and media previews use the server that serves the Web UI.
Authentication failures return `401` with a `WWW-Authenticate` Bearer challenge.
Protected responses include `Cache-Control: no-store`.
`--cors-origins` only decides which web pages may read the answers: other
pages get no CORS headers, but their requests still reach the server. To
refuse requests, set a key as well.
The server rejects requests from other browser origins with `403` unless their
origin is listed in `--cors-origins`. For a reverse proxy that preserves the
public Host header, include its full public origin in that list, such as
`https://sd.example.com`. The origin policy applies to DGL and media requests
as well as the generation APIs.
Startup fails if an access option is missing its value, a list is empty
(such as `--api-key ,`), or the key file contains no keys.

View file

@ -768,8 +768,8 @@ Field types:
the elapsed generation time in seconds, including output encoding and excluding
queue time.
`progress` is available independently of the preview setting, for both image
and video jobs. Continue polling until `status` is terminal: a sampling pass
`progress` is available independently of the preview setting for image, video,
and local DGL jobs. Continue polling until `status` is terminal: a sampling pass
can finish before decoding, ADetailer, or output encoding finishes.
| Field | Type | Notes |
@ -858,6 +858,7 @@ Top-level fields:
| `loras` | `array<object>` | Available LoRA entries |
| `upscalers` | `array<object>` | Available highres upscalers, built-in and model-backed |
| `preview_modes` | `array<string>` | Available preview modes, e.g. `["none", "proj", "tae", "vae"]` |
| `media_view` | `boolean` | Whether the media view endpoint is enabled |
| `limits` | `object` | Shared queue and size limits |
`model`
@ -1071,11 +1072,12 @@ Typical status codes:
#### `POST /sdcpp/v1/jobs/{id}/cancel`
Cancels a queued job immediately, or requests interruption of a generating image or
video job. A generating job returns `200 OK` with `cancel_requested: true` and
remains `generating` until execution stops at a cancellation checkpoint. Continue
polling until its status becomes `cancelled`. Cancelled jobs have no result.
Repeated cancellation requests are safe; terminal jobs are returned unchanged.
Cancels a queued image, video, or DGL job immediately, or requests interruption
if it is already running. No request body is required. A running job returns
`200 OK` with `cancel_requested: true` and remains `generating` until it reaches
a cancellation checkpoint. Poll `GET /sdcpp/v1/jobs/{id}` for the final status.
Cancelled jobs have no result. Repeated cancellation requests are safe and
return the current status of terminal jobs.
Typical status codes:
@ -1827,20 +1829,31 @@ Example cancelled job:
- `429 Too Many Requests` when the job queue is full
- `500 Internal Server Error` for unexpected server exceptions during submission
## Media view
`GET /sdcpp/v1/view?root=assets&path=reference.png` serves an image or video
over the configured listener. `root` selects `input`, `output`, or `assets`
in the server's working directory. `path` is a slash-separated relative path
within that directory. Supported formats are PNG, JPEG, GIF, WebP, WebM, MP4,
and AVI. The endpoint supports HTTP byte ranges and sends `Cache-Control: no-store`.
The server returns `403` when access is denied or the server was started with
`--no-media-view`. Unavailable paths, links, and unsupported files return
`404`.
## DGL editor API
These endpoints are available to the local, same-origin Web UI. The server uses
the working directory's ./dgl directory unless --dgl-dir is set.
These endpoints follow the server's access rules and `--listen-ip`. The server
uses `./dgl` in the working directory unless `--dgl-dir` is set.
| Method and path | Request or response |
| --- | --- |
| GET /sdcpp/v1/dgl/scripts | Returns directory and a list of scripts |
| GET /sdcpp/v1/dgl/script?name=example.dgl | Returns the script as source |
| POST /sdcpp/v1/dgl/script | Saves UTF-8 source with the given name. Pass previous_source to update an existing script. A conflict returns HTTP 409. |
| POST /sdcpp/v1/dgl/jobs | Queues the source string and returns a job ID with HTTP 202 |
| GET /sdcpp/v1/dgl/jobs/{id} | Returns the job status, error or result with tensor descriptions and inline encoded media |
| POST /sdcpp/v1/dgl/jobs/{id}/cancel | Cancels a queued job or requests cancellation of a running job. Send `Content-Type: application/json`. |
| GET /sdcpp/v1/dgl/jobs/{id}/outputs/{index}?frame=0 | Returns a PNG of an image output or a video frame. Output and frame indexes start at zero. |
| POST /sdcpp/v1/dgl/jobs | Queues the source string and returns a job ID and `poll_url` with HTTP 202 |
| GET /sdcpp/v1/jobs/{id} | Returns job status and progress, plus any error or result with tensor descriptions and inline encoded media |
| POST /sdcpp/v1/jobs/{id}/cancel | Cancels a queued job or requests cancellation of a running job |
Failed jobs report `error.code` and `error.message`. When execution reports
`out_of_memory`, the message includes the memory failure details available
@ -1878,9 +1891,7 @@ The name of a root media dict is `result`.
The script encodes media once. After execution releases the generation lock,
the server converts returned bytes to Base64 once, before publishing
`completed`. Polling returns the stored result; it does not encode a video,
convert Base64 again, or require frame requests. The frame endpoint remains
available for explicit tensor inspection. Native `/sdcpp/v1/vid_gen` is unchanged.
`completed`. Polling returns the stored metadata and inline Base64 media.
Inline media share a 64 MiB raw-byte budget per job. An item that exceeds the
remaining budget has no `b64_json`; it instead contains

View file

@ -126,22 +126,25 @@ static void finish_job_progress(AsyncGenerationJob& job) {
job.progress.finished = std::chrono::steady_clock::now();
}
static void job_progress_callback(const sd_generation_progress_t* progress, void* data) noexcept {
try {
auto& job = *static_cast<AsyncGenerationJob*>(data);
update_job_progress(job, progress->stage, progress->detail,
progress->sample_pass, progress->completed, progress->total, progress->unit);
} catch (...) {
// Progress callbacks must not unwind into the generation context.
}
}
class JobCallbacksGuard {
sd_ctx_t* ctx_;
AsyncGenerationJob& job_;
static void progress_callback(const sd_generation_progress_t* progress, void* data) {
auto& guard = *static_cast<JobCallbacksGuard*>(data);
update_job_progress(guard.job_, progress->stage, progress->detail,
progress->sample_pass, progress->completed, progress->total, progress->unit);
}
public:
JobCallbacksGuard(sd_ctx_t* ctx, AsyncGenerationJob& job)
: ctx_(ctx), job_(job) {
: ctx_(ctx) {
clear_preview_callback();
set_preview_callback(job);
sd_set_generation_progress_callback(ctx_, progress_callback, this);
sd_set_generation_progress_callback(ctx_, job_progress_callback, &job);
}
~JobCallbacksGuard() {
@ -153,6 +156,24 @@ public:
JobCallbacksGuard& operator=(const JobCallbacksGuard&) = delete;
};
class DglJobProgressGuard {
sd_dgl_ctx_t* ctx_;
public:
DglJobProgressGuard(sd_dgl_ctx_t* ctx, AsyncGenerationJob& job) : ctx_(ctx) {
if (sd_dgl_ctx_set_progress_callback(ctx_, job_progress_callback, &job) != SD_STATUS_OK)
throw std::runtime_error(sd_dgl_error());
}
~DglJobProgressGuard() {
if (sd_dgl_ctx_set_progress_callback(ctx_, nullptr, nullptr) != SD_STATUS_OK)
LOG_WARN("could not clear DGL job progress callback: %s", sd_dgl_error());
}
DglJobProgressGuard(const DglJobProgressGuard&) = delete;
DglJobProgressGuard& operator=(const DglJobProgressGuard&) = delete;
};
const char* async_job_kind_name(AsyncJobKind kind) {
switch (kind) {
case AsyncJobKind::ImgGen:
@ -503,7 +524,7 @@ bool execute_vid_gen_job(ServerRuntime& runtime,
return true;
}
int64_t dgl_image_frame_count(const sd_tensor_t* tensor) {
static int64_t dgl_image_frame_count(const sd_tensor_t* tensor) {
if (!tensor || sd_tensor_type(tensor) != SD_TENSOR_U8)
return 0;
const auto rank = sd_tensor_rank(tensor);
@ -602,6 +623,23 @@ static json describe_dgl_result(const sd_dgl_result_t* result) {
namespace {
namespace fs = std::filesystem;
bool has_resolved_model_parent(const fs::path& path) {
std::error_code error;
for (auto part = path; !part.empty(); part = part.parent_path()) {
const auto status = fs::symlink_status(part, error);
if (status.type() != fs::file_type::not_found) {
if (error || !fs::is_directory(status))
return false;
// A dangling link or junction must not be treated as a missing dependency.
const auto canonical = fs::canonical(part, error);
return !error && model_path_key(canonical) == model_path_key(part);
}
if (part == part.root_path())
break;
}
return false;
}
bool allowed_dgl_path(const char* path, sd_dgl_file_access_t access, void* userdata) try {
const auto& policy = *static_cast<const ServerFileAccess*>(userdata);
std::error_code error;
@ -655,16 +693,18 @@ namespace {
const bool readable = !error && (fs::is_regular_file(status) || fs::is_directory(status));
if (access == SD_DGL_FILE_READ)
return readable;
const auto key = model_path_key(resolved);
if (readable || status.type() == fs::file_type::not_found) {
if (policy.configured_files.count(key))
return true;
if (std::any_of(policy.model_bundles.begin(), policy.model_bundles.end(), [&](const fs::path& root) { return model_path_inside(root, resolved); }))
return true;
}
return readable && std::any_of(policy.models.begin(), policy.models.end(), [&](const ModelRoot& root) {
return model_path_key(root.path) == key || model_path_inside(root.path, resolved);
});
if (!readable && status.type() != fs::file_type::not_found)
return false;
const auto key = model_path_key(resolved);
const bool allowed = policy.configured_files.count(key) ||
std::any_of(policy.model_bundles.begin(), policy.model_bundles.end(), [&](const fs::path& root) {
return model_path_inside(root, resolved);
}) ||
std::any_of(policy.models.begin(), policy.models.end(), [&](const ModelRoot& root) {
return model_path_key(root.path) == key || model_path_inside(root.path, resolved);
});
return allowed && (readable || has_resolved_model_parent(resolved));
} catch (const std::exception&) {
return false;
}
@ -689,7 +729,6 @@ void configure_server_file_access(ServerModels& models, const SDSvrParams& param
static sd_status_t execute_dgl_job(ServerRuntime& runtime,
AsyncGenerationJob& job,
std::shared_ptr<sd_dgl_result_t>& result,
json& result_info,
std::string& error_message) {
try {
@ -699,17 +738,19 @@ static sd_status_t execute_dgl_job(ServerRuntime& runtime,
std::lock_guard<std::mutex> lock(*runtime.sd_ctx_mutex);
if (job.cancel_requested.load())
return SD_STATUS_CANCELLED;
JobCancellationMonitor cancellation(job, [ctx = runtime.sd_ctx]() {
sd_dgl_ctx_cancel(sd_ctx_get_dgl_ctx(ctx));
auto* ctx = sd_ctx_get_dgl_ctx(runtime.sd_ctx);
DglJobProgressGuard progress(ctx, job);
JobCancellationMonitor cancellation(job, [ctx]() {
sd_dgl_ctx_cancel(ctx);
});
update_job_progress(job, "executing", "dgl");
const auto status = sd_dgl_run(sd_ctx_get_dgl_ctx(runtime.sd_ctx), source.c_str(), nullptr, 0, &raw_result);
const auto status = sd_dgl_run(ctx, source.c_str(), nullptr, 0, &raw_result);
if (status != SD_STATUS_OK) {
error_message = sd_dgl_error();
return status;
}
}
result.reset(raw_result, sd_dgl_result_free);
std::unique_ptr<sd_dgl_result_t, decltype(&sd_dgl_result_free)> result(raw_result, sd_dgl_result_free);
result_info = describe_dgl_result(result.get());
return SD_STATUS_OK;
} catch (const std::exception& error) {
@ -796,11 +837,10 @@ void async_job_worker(ServerRuntime& runtime) {
std::string output_media_mime_type;
int output_frame_count = 0;
int output_fps = 0;
std::shared_ptr<sd_dgl_result_t> dgl_result;
json dgl_result_info;
std::string error_message;
const char* error_code = "generation_failed";
bool ok = false;
bool ok = false;
if (job->kind == AsyncJobKind::ImgGen) {
ok = execute_img_gen_job(runtime, *job, output_images, output_info, error_message);
@ -814,7 +854,7 @@ void async_job_worker(ServerRuntime& runtime) {
output_info,
error_message);
} else if (job->kind == AsyncJobKind::Dgl) {
const auto status = execute_dgl_job(runtime, *job, dgl_result, dgl_result_info, error_message);
const auto status = execute_dgl_job(runtime, *job, dgl_result_info, error_message);
ok = status == SD_STATUS_OK;
if (status == SD_STATUS_OUT_OF_MEMORY) {
error_code = "out_of_memory";
@ -845,7 +885,6 @@ void async_job_worker(ServerRuntime& runtime) {
job->result_media_mime_type = std::move(output_media_mime_type);
job->result_frame_count = output_frame_count;
job->result_fps = output_fps;
job->dgl_result = std::move(dgl_result);
job->dgl_result_info = std::move(dgl_result_info);
job->error_code.clear();
job->error_message.clear();

View file

@ -56,7 +56,6 @@ struct AsyncGenerationJob {
ImgGenJobRequest img_gen;
VidGenJobRequest vid_gen;
std::string dgl_source;
std::shared_ptr<sd_dgl_result_t> dgl_result;
json dgl_result_info;
std::vector<std::string> result_images_b64;
json result_generation_info;
@ -99,7 +98,6 @@ size_t count_pending_jobs(const AsyncJobManager& manager);
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);
int64_t dgl_image_frame_count(const sd_tensor_t* tensor);
bool parse_native_job_request(const json& body, ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message);
bool execute_img_gen_job(ServerRuntime& runtime,
AsyncGenerationJob& job,

@ -1 +1 @@
Subproject commit d9fd4e6a938b74ad97c7e464a8e689474b70c533
Subproject commit e5929111fc43e5e492f30607a163e0859cdefb2c

View file

@ -1,6 +1,7 @@
#include <cstdlib>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
@ -103,6 +104,8 @@ int main(int argc, const char** argv) {
}
try {
configure_server_file_access(models, svr_params, ctx_params);
if (!sd_dgl_ctx_set(sd_ctx_get_dgl_ctx(models.context.get()), "console_progress", "on"))
throw std::runtime_error(sd_dgl_error());
} catch (const std::exception& error) {
LOG_ERROR("Context setup failed: %s", error.what());
return 1;
@ -151,6 +154,7 @@ int main(int argc, const char** argv) {
index_html = "Stable Diffusion Server is running";
#endif
register_index_endpoints(svr, svr_params, index_html);
register_media_view_endpoint(svr, svr_params);
register_openai_api_endpoints(svr, runtime);
register_sdapi_endpoints(svr, runtime);
register_sdcpp_api_endpoints(svr, runtime);

View file

@ -6,6 +6,7 @@
#include "runtime.h"
void register_index_endpoints(httplib::Server& svr, const SDSvrParams& svr_params, const std::string& index_html);
void register_media_view_endpoint(httplib::Server& svr, const SDSvrParams& svr_params);
void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt);
void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt);
void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt);

View file

@ -1,14 +1,11 @@
#include "routes.h"
#include <algorithm>
#include <charconv>
#include <fstream>
#include <optional>
#include <stdexcept>
#include <string_view>
#include "async_jobs.h"
#include "common/media_io.h"
namespace {
namespace fs = std::filesystem;
@ -32,31 +29,9 @@ namespace {
res.set_content(json({{"error", message}}).dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
}
bool local_origin(const Request& req) {
if (req.remote_addr != "127.0.0.1" && req.remote_addr != "::1" && req.remote_addr != "::ffff:127.0.0.1")
return false;
const auto host = req.get_header_value("Host");
const auto port = ":" + std::to_string(req.local_port);
const auto origin = req.get_header_value("Origin");
const auto site = req.get_header_value("Sec-Fetch-Site");
if ((!site.empty() && site != "same-origin" && site != "none") ||
(!origin.empty() && origin != "http://" + host && origin != "https://" + host))
return false;
for (const std::string address : {"localhost", "127.0.0.1", "[::1]"}) {
if (host == address || host == address + port)
return true;
}
return false;
}
httplib::Server::Handler local_dgl_route(httplib::Server::Handler handler) {
httplib::Server::Handler with_dgl_errors(httplib::Server::Handler handler) {
return [handler = std::move(handler)](const Request& req, Response& res) {
res.set_header("Cache-Control", "no-store");
res.set_header("Cross-Origin-Resource-Policy", "same-origin");
if (!local_origin(req)) {
send_error(res, 403, "DGL is available from the local server's Web UI");
return;
}
if (req.method == "POST") {
const auto content_type = req.get_header_value("Content-Type");
if (content_type.substr(0, content_type.find(';')) != "application/json") {
@ -125,54 +100,11 @@ namespace {
std::error_code ignored;
fs::remove(staging, ignored);
}
std::optional<size_t> parse_index(std::string_view value) {
size_t index = 0;
const auto parsed = std::from_chars(value.data(), value.data() + value.size(), index);
if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size())
return std::nullopt;
return index;
}
std::shared_ptr<AsyncGenerationJob> find_dgl_job(AsyncJobManager& manager, const std::string& id, Response& res) {
purge_expired_jobs(manager);
auto it = manager.jobs.find(id);
if (it != manager.jobs.end() && it->second->kind == AsyncJobKind::Dgl)
return it->second;
const bool expired = manager.expired_jobs.count(id) != 0;
send_error(res, expired ? 410 : 404, expired ? "Job expired" : "Job not found");
return {};
}
void send_output_preview(const Request& req, Response& res, const sd_dgl_result_t* result) {
const auto output = parse_index(req.matches[2].str());
if (!output || *output >= sd_dgl_result_count(result)) {
send_error(res, 404, "Output not found");
return;
}
const auto* tensor = sd_dgl_result_tensor(result, sd_dgl_result_name(result, *output));
const auto frames = dgl_image_frame_count(tensor);
const auto frame = req.has_param("frame") ? parse_index(req.get_param_value("frame")) : std::optional<size_t>(0);
if (!frame || *frame >= static_cast<size_t>(frames)) {
send_error(res, 404, "Frame not found");
return;
}
const size_t stride = sd_tensor_byte_size(tensor) / static_cast<size_t>(frames);
const auto* pixels = static_cast<const uint8_t*>(sd_tensor_data(tensor)) + *frame * stride;
const auto png = encode_image_to_vector(EncodedImageFormat::PNG, pixels,
int(sd_tensor_dim(tensor, 1)), int(sd_tensor_dim(tensor, 2)),
int(sd_tensor_dim(tensor, 0)));
if (png.empty()) {
send_error(res, 500, "Could not encode preview");
return;
}
res.set_content(reinterpret_cast<const char*>(png.data()), png.size(), "image/png");
}
}
void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
auto workspace = std::make_shared<DglWorkspace>(runtime.svr_params->dgl_dir);
svr.Get("/sdcpp/v1/dgl/scripts", local_dgl_route([workspace](const Request&, Response& res) {
svr.Get("/sdcpp/v1/dgl/scripts", with_dgl_errors([workspace](const Request&, Response& res) {
std::lock_guard<std::mutex> lock(workspace->mutex);
std::vector<std::string> names;
if (fs::exists(workspace->directory)) {
@ -186,7 +118,7 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
send_json(res, 200, {{"directory", workspace->directory.generic_u8string()}, {"scripts", names}});
}));
svr.Get("/sdcpp/v1/dgl/script", local_dgl_route([workspace](const Request& req, Response& res) {
svr.Get("/sdcpp/v1/dgl/script", with_dgl_errors([workspace](const Request& req, Response& res) {
const auto name = req.get_param_value("name");
if (!valid_script_name(name)) {
send_error(res, 400, "Expected a .dgl file name");
@ -201,7 +133,7 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
send_json(res, 200, {{"source", read_script(path)}});
}));
svr.Post("/sdcpp/v1/dgl/script", local_dgl_route([workspace](const Request& req, Response& res) {
svr.Post("/sdcpp/v1/dgl/script", with_dgl_errors([workspace](const Request& req, Response& res) {
const auto body = json::parse(req.body);
const auto name = body.at("name").get<std::string>();
const auto source = body.at("source").get<std::string>();
@ -227,7 +159,7 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
send_json(res, updating ? 200 : 201, {{"name", name}});
}));
svr.Post("/sdcpp/v1/dgl/jobs", local_dgl_route([&runtime](const Request& req, Response& res) {
svr.Post("/sdcpp/v1/dgl/jobs", with_dgl_errors([&runtime](const Request& req, Response& res) {
auto source = json::parse(req.body).at("source").get<std::string>();
if (source.empty() || !valid_source(source)) {
send_error(res, 400, "Expected non-empty UTF-8 source");
@ -247,49 +179,10 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
job->id = make_async_job_id(manager);
manager.jobs.emplace(job->id, job);
manager.queue.push_back(job->id);
send_json(res, 202, make_async_job_json(manager, *job));
auto response = make_async_job_json(manager, *job);
response["poll_url"] = "/sdcpp/v1/jobs/" + job->id;
send_json(res, 202, response);
}
manager.cv.notify_one();
}));
svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+))", local_dgl_route([&runtime](const Request& req, Response& res) {
auto& manager = *runtime.async_job_manager;
std::lock_guard<std::mutex> lock(manager.mutex);
if (auto job = find_dgl_job(manager, req.matches[1].str(), res))
send_json(res, 200, make_async_job_json(manager, *job));
}));
svr.Post(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/cancel)", local_dgl_route([&runtime](const Request& req, Response& res) {
auto& manager = *runtime.async_job_manager;
std::lock_guard<std::mutex> lock(manager.mutex);
auto job = find_dgl_job(manager, req.matches[1].str(), res);
if (!job)
return;
if (job->status == AsyncJobStatus::Queued) {
if (!cancel_queued_job(manager, *job)) {
send_error(res, 409, "Job queue state changed before cancellation");
return;
}
} else if (job->status == AsyncJobStatus::Generating) {
job->cancel_requested.store(true);
}
send_json(res, 200, make_async_job_json(manager, *job));
}));
svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/outputs/([0-9]+))", local_dgl_route([&runtime](const Request& req, Response& res) {
auto& manager = *runtime.async_job_manager;
std::shared_ptr<sd_dgl_result_t> result;
{
std::lock_guard<std::mutex> lock(manager.mutex);
const auto job = find_dgl_job(manager, req.matches[1].str(), res);
if (!job)
return;
result = job->dgl_result;
}
if (!result) {
send_error(res, 404, "Job has no result");
return;
}
send_output_preview(req, res, result.get());
}));
}

View file

@ -0,0 +1,276 @@
#include "routes.h"
#include <array>
#include <limits>
#include <string_view>
#include <utility>
#ifdef _WIN32
#include <winternl.h>
#else
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#endif
namespace media_view {
#ifdef _WIN32
class FileHandle {
HANDLE handle_;
public:
explicit FileHandle(HANDLE handle = INVALID_HANDLE_VALUE) : handle_(handle) {}
~FileHandle() {
if (*this)
CloseHandle(handle_);
}
FileHandle(FileHandle&& other) noexcept : handle_(std::exchange(other.handle_, INVALID_HANDLE_VALUE)) {}
FileHandle& operator=(FileHandle&& other) noexcept {
std::swap(handle_, other.handle_);
return *this;
}
explicit operator bool() const { return handle_ != INVALID_HANDLE_VALUE; }
HANDLE get() const { return handle_; }
};
static FileHandle working_directory() {
return FileHandle(CreateFileW(L".", FILE_TRAVERSE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr));
}
static FileHandle open_child(const FileHandle& parent, const std::string& part, bool directory) {
static const auto open_file = reinterpret_cast<decltype(&NtOpenFile)>(
GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtOpenFile"));
if (!open_file)
return FileHandle();
auto name = std::filesystem::u8path(part).native();
const auto bytes = static_cast<USHORT>(name.size() * sizeof(wchar_t));
UNICODE_STRING relative{bytes, bytes, name.data()};
OBJECT_ATTRIBUTES object;
InitializeObjectAttributes(&object, &relative, OBJ_CASE_INSENSITIVE, parent.get(), nullptr);
IO_STATUS_BLOCK status{};
HANDLE handle = INVALID_HANDLE_VALUE;
const auto access = (directory ? FILE_TRAVERSE : FILE_READ_DATA) | FILE_READ_ATTRIBUTES | SYNCHRONIZE;
// A handle-relative open keeps every component under the directory already checked.
if (open_file(&handle, access, &object, &status, FILE_SHARE_READ | FILE_SHARE_WRITE,
FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT) < 0)
return FileHandle();
FileHandle file(handle);
BY_HANDLE_FILE_INFORMATION info{};
if (GetFileType(handle) != FILE_TYPE_DISK || !GetFileInformationByHandle(handle, &info) ||
(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ||
static_cast<bool>(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != directory ||
(!directory && info.nNumberOfLinks != 1))
return FileHandle();
return file;
}
static uint64_t file_size(const FileHandle& file) {
LARGE_INTEGER size{};
return GetFileSizeEx(file.get(), &size) && size.QuadPart > 0 ? static_cast<uint64_t>(size.QuadPart) : 0;
}
static size_t read_at(const FileHandle& file, size_t offset, char* buffer, size_t length) {
LARGE_INTEGER position{};
position.QuadPart = static_cast<LONGLONG>(offset);
DWORD count = 0;
if (!SetFilePointerEx(file.get(), position, nullptr, FILE_BEGIN) ||
!ReadFile(file.get(), buffer, static_cast<DWORD>(length), &count, nullptr))
return 0;
return count;
}
#else
class FileHandle {
int fd_;
public:
explicit FileHandle(int fd = -1) : fd_(fd) {}
~FileHandle() {
if (*this)
close(fd_);
}
FileHandle(FileHandle&& other) noexcept : fd_(std::exchange(other.fd_, -1)) {}
FileHandle& operator=(FileHandle&& other) noexcept {
std::swap(fd_, other.fd_);
return *this;
}
explicit operator bool() const { return fd_ >= 0; }
int get() const { return fd_; }
};
static FileHandle working_directory() {
return FileHandle(open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
}
static FileHandle open_child(const FileHandle& parent, const std::string& part, bool directory) {
const auto flags = O_RDONLY | O_NOFOLLOW | O_CLOEXEC | (directory ? O_DIRECTORY : O_NONBLOCK);
return FileHandle(openat(parent.get(), part.c_str(), flags));
}
static uint64_t file_size(const FileHandle& file) {
struct stat info{};
if (fstat(file.get(), &info) != 0 || !S_ISREG(info.st_mode) || info.st_nlink != 1 || info.st_size <= 0)
return 0;
return static_cast<uint64_t>(info.st_size);
}
static size_t read_at(const FileHandle& file, size_t offset, char* buffer, size_t length) {
ssize_t count;
do {
count = pread(file.get(), buffer, length, static_cast<off_t>(offset));
} while (count < 0 && errno == EINTR);
return count > 0 ? static_cast<size_t>(count) : 0;
}
#endif
static bool valid_component(std::string_view part) {
return !part.empty() && part.size() <= 1020 && part != "." && part != ".." &&
part.back() != '.' && part.back() != ' ' && part.find_first_of("\\:*?\"<>|") == std::string_view::npos &&
std::none_of(part.begin(), part.end(), [](unsigned char c) { return c < 32 || c == 127; });
}
static FileHandle open_media(const std::string& root, std::string_view path) {
if (root != "input" && root != "output" && root != "assets")
return FileHandle();
const auto cwd = working_directory();
if (!cwd)
return FileHandle();
auto parent = open_child(cwd, root, true);
while (parent) {
const auto slash = path.find('/');
const auto part = path.substr(0, slash);
if (!valid_component(part))
break;
const bool directory = slash != std::string_view::npos;
auto child = open_child(parent, std::string(part), directory);
if (!directory)
return child;
parent = std::move(child);
path.remove_prefix(slash + 1);
}
return FileHandle();
}
static size_t ebml_vint_width(std::string_view bytes, size_t max_width) {
if (bytes.empty())
return 0;
const auto first = static_cast<unsigned char>(bytes.front());
for (size_t width = 1; width <= std::min(max_width, bytes.size()); ++width) {
if (first & (0x80u >> (width - 1)))
return width;
}
return 0;
}
static bool read_ebml_size(std::string_view& bytes, uint64_t& size) {
const auto width = ebml_vint_width(bytes, 8);
if (width == 0)
return false;
size = static_cast<unsigned char>(bytes.front()) & (0xffu >> width);
for (size_t i = 1; i < width; ++i)
size = (size << 8) | static_cast<unsigned char>(bytes[i]);
bytes.remove_prefix(width);
return size != (uint64_t{1} << (7 * width)) - 1;
}
static bool has_webm_doctype(std::string_view header, uint64_t file_size) {
constexpr std::string_view ebml_id = "\x1a\x45\xdf\xa3";
if (header.substr(0, ebml_id.size()) != ebml_id)
return false;
const auto probe_size = header.size();
header.remove_prefix(ebml_id.size());
uint64_t size;
if (!read_ebml_size(header, size))
return false;
const auto prefix_size = probe_size - header.size();
if (prefix_size > file_size || size > file_size - prefix_size)
return false;
header = header.substr(0, static_cast<size_t>(size));
while (!header.empty()) {
const auto width = ebml_vint_width(header, 4);
if (width == 0)
return false;
const bool is_doctype = header.substr(0, width) == "\x42\x82";
header.remove_prefix(width);
if (!read_ebml_size(header, size) || size > header.size())
return false;
if (is_doctype)
return header.substr(0, static_cast<size_t>(size)) == "webm";
header.remove_prefix(static_cast<size_t>(size));
}
return false;
}
static const char* media_type(std::string extension, std::string_view header, uint64_t size) {
for (auto& ch : extension) {
if (ch >= 'A' && ch <= 'Z')
ch += 'a' - 'A';
}
if (extension == ".png" && header.substr(0, 8) == "\x89PNG\r\n\x1a\n")
return "image/png";
if ((extension == ".jpg" || extension == ".jpeg") && header.substr(0, 3) == "\xff\xd8\xff")
return "image/jpeg";
if (extension == ".gif" && (header.substr(0, 6) == "GIF87a" || header.substr(0, 6) == "GIF89a"))
return "image/gif";
if (extension == ".webp" && header.size() >= 16 && header.substr(0, 4) == "RIFF" && header.substr(8, 7) == "WEBPVP8" &&
(header[15] == ' ' || header[15] == 'L' || header[15] == 'X'))
return "image/webp";
if (extension == ".webm" && has_webm_doctype(header, size))
return "video/webm";
if (extension == ".avi" && header.size() >= 12 && header.substr(0, 4) == "RIFF" && header.substr(8, 4) == "AVI ")
return "video/x-msvideo";
if (extension == ".mp4" && header.size() >= 16 && header.substr(4, 4) == "ftyp") {
uint32_t box_size = 0;
for (size_t i = 0; i < 4; ++i)
box_size = (box_size << 8) | static_cast<unsigned char>(header[i]);
if (box_size >= 16 && box_size <= size)
return "video/mp4";
}
return nullptr;
}
static bool set_media_content(const std::string& root, const std::string& path, httplib::Response& res) {
auto file = open_media(root, path);
if (!file)
return false;
const auto size = file_size(file);
if (size == 0 || size > std::numeric_limits<size_t>::max())
return false;
std::array<char, 256> header;
const auto count = read_at(file, 0, header.data(), header.size());
const auto extension = path.find_last_of('.');
if (extension == std::string::npos)
return false;
const auto* type = media_type(path.substr(extension), {header.data(), count}, size);
if (!type)
return false;
res.set_header("Accept-Ranges", "bytes");
res.set_content_provider(static_cast<size_t>(size), type,
[file = std::make_shared<FileHandle>(std::move(file))](size_t offset, size_t length, httplib::DataSink& sink) {
std::array<char, 64 * 1024> buffer;
const auto count = read_at(*file, offset, buffer.data(), std::min(length, buffer.size()));
return count != 0 && sink.write(buffer.data(), count);
});
return true;
}
}
void register_media_view_endpoint(httplib::Server& svr, const SDSvrParams& params) {
svr.Get("/sdcpp/v1/view", [enabled = params.media_view](const httplib::Request& req, httplib::Response& res) {
res.set_header("Cache-Control", "no-store");
res.set_header("X-Content-Type-Options", "nosniff");
if (!enabled) {
res.status = 403;
return;
}
try {
if (req.get_param_value_count("root") == 1 && req.get_param_value_count("path") == 1 &&
media_view::set_media_content(req.get_param_value("root"), req.get_param_value("path"), res))
return;
} catch (const std::system_error&) {
// Invalid path encodings are treated like unavailable files.
}
res.status = 404;
});
}

View file

@ -341,6 +341,7 @@ static json make_capabilities_json(ServerRuntime& runtime) {
};
result["generation_features"] = generation_features;
result["generation_model_selection"] = true;
result["media_view"] = runtime.svr_params->media_view;
result["runtime"] = model_status(runtime);
result["current_mode"] = current_mode;
result["supported_modes"] = supported_modes;
@ -549,17 +550,13 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) {
});
routes.get(R"(/sdcpp/v1/jobs/([A-Za-z0-9_\-]+))", [runtime](const httplib::Request& req, httplib::Response& res) {
res.set_header("Cache-Control", "no-store");
AsyncJobManager& manager = *runtime->async_job_manager;
std::lock_guard<std::mutex> lock(manager.mutex);
purge_expired_jobs(manager);
std::string job_id = req.matches[1];
auto it = manager.jobs.find(job_id);
if (it != manager.jobs.end() && it->second->kind == AsyncJobKind::Dgl) {
res.status = 404;
res.set_content(R"({"error":"job not found"})", "application/json");
return;
}
if (it == manager.jobs.end()) {
if (manager.expired_jobs.find(job_id) != manager.expired_jobs.end()) {
res.status = 410;
@ -576,6 +573,7 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) {
});
routes.post(R"(/sdcpp/v1/jobs/([A-Za-z0-9_\-]+)/cancel)", [runtime](const httplib::Request& req, httplib::Response& res) {
res.set_header("Cache-Control", "no-store");
AsyncJobManager& manager = *runtime->async_job_manager;
std::lock_guard<std::mutex> lock(manager.mutex);
purge_expired_jobs(manager);
@ -594,27 +592,14 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) {
}
auto& job = *it->second;
if (job.kind == AsyncJobKind::Dgl) {
res.status = 404;
res.set_content(R"({"error":"job not found"})", "application/json");
return;
}
if (job.status == AsyncJobStatus::Queued) {
if (!cancel_queued_job(manager, job)) {
res.status = 409;
res.set_content(R"({"error":"job queue state changed before cancellation"})", "application/json");
return;
}
res.status = 200;
res.set_content(make_async_job_json(manager, job).dump(), "application/json");
return;
}
if (job.status == AsyncJobStatus::Generating) {
} else if (job.status == AsyncJobStatus::Generating) {
job.cancel_requested.store(true);
res.status = 200;
res.set_content(make_async_job_json(manager, job).dump(), "application/json");
return;
}
res.status = 200;

View file

@ -318,6 +318,7 @@ ArgOptions SDSvrParams::get_options() {
options.bool_options = {
{"", "--color", "colors the logging tags according to level", true, &color},
{"", "--no-media-view", "disable media file viewing", false, &media_view},
};
auto on_help_arg = [&](int, const char**, int, bool& valid) {
@ -400,6 +401,7 @@ std::string SDSvrParams::to_string() const {
<< " dgl_dir: \"" << dgl_dir << "\",\n"
<< " api_keys: " << api_keys.size() << ",\n"
<< " cors_origins: " << cors_origins.size() << ",\n"
<< " media_view: " << std::boolalpha << media_view << ",\n"
<< "}";
return oss.str();
}

View file

@ -28,6 +28,7 @@ struct SDSvrParams {
int weight_residency_ttl = -1;
std::string serve_html_path;
std::string dgl_dir = "dgl";
bool media_view = true;
std::vector<std::string> model_dirs;
std::vector<std::string> api_keys;
std::string api_key_file;

View file

@ -59,7 +59,7 @@ void SDSvrParams::add_access_options(ArgOptions& options, const std::vector<ArgO
api_key_file = argv_to_utf8(index, argv);
return true;
});
add_option("--cors-origins", "web origins allowed to read cross-origin responses, comma-separated (default: any)",
add_option("--cors-origins", "additional web origins allowed to make cross-origin requests, comma-separated (default: none)",
[this](int index, const char** argv) {
return append_option_list(argv[index - 1], argv[index], "origin", cors_origins);
});
@ -89,8 +89,12 @@ bool SDSvrParams::load_api_keys() {
return true;
}
static bool is_web_ui_request(const httplib::Request& req) {
return req.method == "GET" && req.path == "/";
}
static bool requires_api_key(const SDSvrParams& params, const httplib::Request& req) {
return !params.api_keys.empty() && req.method != "OPTIONS" && !(req.method == "GET" && req.path == "/");
return !params.api_keys.empty() && req.method != "OPTIONS" && !is_web_ui_request(req);
}
static bool api_key_matches(const std::vector<std::string>& keys, std::string_view key) {
@ -125,23 +129,88 @@ static bool has_valid_api_key(const httplib::Request& req, const std::vector<std
return key_start != std::string::npos && api_key_matches(keys, std::string_view(auth).substr(key_start));
}
static bool is_allowed_origin(const std::vector<std::string>& allowed, std::string_view origin) {
return !origin.empty() && std::find(allowed.begin(), allowed.end(), origin) != allowed.end();
}
static void set_cors_headers(const httplib::Request& req, httplib::Response& res, const std::vector<std::string>& allowed) {
const bool preflight = req.method == "OPTIONS";
res.set_header("Vary", preflight ? "Origin, Access-Control-Request-Headers" : "Origin");
std::string vary = "Origin, Sec-Fetch-Site";
if (preflight)
vary += ", Access-Control-Request-Headers";
else if (is_web_ui_request(req))
vary += ", Sec-Fetch-Mode, Sec-Fetch-Dest";
res.set_header("Vary", vary);
const auto origin = req.get_header_value("Origin");
if (!allowed.empty() && std::find(allowed.begin(), allowed.end(), origin) == allowed.end()) {
if (!is_allowed_origin(allowed, origin)) {
return;
}
res.set_header("Access-Control-Allow-Origin", origin.empty() ? "*" : origin);
res.set_header("Access-Control-Allow-Origin", origin);
res.set_header("Access-Control-Allow-Credentials", "true");
res.set_header("Access-Control-Allow-Methods", "*");
res.set_header("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
const auto headers = preflight ? req.get_header_value("Access-Control-Request-Headers") : std::string{};
res.set_header("Access-Control-Allow-Headers", headers.empty() ? "*" : headers);
}
static bool is_server_host(std::string_view host, const std::string& listen_ip) {
if (host.empty())
return false;
if (host.back() != ']') {
const auto port_separator = host.rfind(':');
if (port_separator != std::string_view::npos) {
const auto port = host.substr(port_separator + 1);
if (port.empty() || port.find_first_not_of("0123456789") != std::string_view::npos)
return false;
host = host.substr(0, port_separator);
}
}
if (host == "localhost" || host == listen_ip)
return true;
if (host.size() > 2 && host.front() == '[' && host.back() == ']') {
const std::string ipv6(host.substr(1, host.size() - 2));
in6_addr address{};
return inet_pton(AF_INET6, ipv6.c_str(), &address) == 1;
}
const std::string ipv4(host);
in_addr address{};
return inet_pton(AF_INET, ipv4.c_str(), &address) == 1;
}
static bool is_allowed_request_origin(const httplib::Request& req, const SDSvrParams& params) {
if (req.get_header_value_count("Host") != 1 ||
req.get_header_value_count("Origin") > 1 || req.get_header_value_count("Sec-Fetch-Site") > 1)
return false;
// Same-origin browser headers alone do not distinguish a DNS-rebound hostname.
const auto host = req.get_header_value("Host");
const auto http_origin = "http://" + host;
const auto https_origin = "https://" + host;
if (!is_server_host(host, params.listen_ip) && !is_allowed_origin(params.cors_origins, http_origin) &&
!is_allowed_origin(params.cors_origins, https_origin))
return false;
if (is_web_ui_request(req) && req.get_header_value_count("Sec-Fetch-Mode") == 1 &&
req.get_header_value_count("Sec-Fetch-Dest") == 1 && req.get_header_value("Sec-Fetch-Mode") == "navigate" &&
req.get_header_value("Sec-Fetch-Dest") == "document")
return true;
const auto origin = req.get_header_value("Origin");
if (is_allowed_origin(params.cors_origins, origin))
return true;
const auto site = req.get_header_value("Sec-Fetch-Site");
return (site.empty() || site == "same-origin" || site == "none") &&
(origin.empty() || origin == http_origin);
}
SDHttpServer::SDHttpServer(const SDSvrParams& params) {
set_pre_routing_handler([&params](const httplib::Request& req, httplib::Response& res) {
if (!is_allowed_request_origin(req, params)) {
res.status = 403;
res.set_content(R"({"error":"Request origin is not allowed"})", "application/json");
close_after_response_ = true;
return HandlerResponse::Handled;
}
if (req.method == "OPTIONS") {
close_after_response_ = req.has_header("Transfer-Encoding") || req.get_header_value_u64("Content-Length") > 0;
res.status = 204;
@ -168,6 +237,7 @@ SDHttpServer::SDHttpServer(const SDSvrParams& params) {
res.headers.erase("Cache-Control");
res.set_header("Cache-Control", "no-store");
}
res.set_header("Cross-Origin-Resource-Policy", "same-origin");
set_cors_headers(req, res, params.cors_origins);
});
}

View file

@ -360,7 +360,8 @@ SD_API sd_dgl_ctx_t* sd_dgl_ctx_create_once(void);
SD_API void sd_dgl_ctx_free(sd_dgl_ctx_t* ctx);
// Sets options on an idle context: max_vram, max_ram, conditioning_cache_size, batched_cfg,
// n_threads, auto_fit, enable_mmap, eager_load, disable_prefetch, disable_segmented_compute,
// embed_metadata (default on; controls generation metadata in DGL image/video saves).
// embed_metadata (default on; controls generation metadata in DGL image/video saves),
// console_progress (default off; keeps built-in progress output alongside callbacks).
// Threading, placement and weight-loading options invalidate cached models when changed.
SD_API bool sd_dgl_ctx_set(sd_dgl_ctx_t* ctx, const char* key, const char* value);

View file

@ -978,10 +978,10 @@ namespace sd {
const auto budget_bytes = available.available_budget_bytes == SIZE_MAX
? std::string("unlimited")
: sd_format("%.2f MB", available.available_budget_bytes / (1024.0 * 1024.0));
auto message = sd_format("execution engine cannot make enough memory available on %s: need %.2f MB device / %.2f MB budget, available %s device / %s budget",
ggml_backend_name(request.compute_backend),
available.required_device_bytes / (1024.0 * 1024.0),
available.required_budget_bytes / (1024.0 * 1024.0), device_bytes.c_str(), budget_bytes.c_str());
auto message = sd_format("execution engine cannot make enough memory available on %s: need %.2f MB device / %.2f MB budget, available %s device / %s budget",
ggml_backend_name(request.compute_backend),
available.required_device_bytes / (1024.0 * 1024.0),
available.required_budget_bytes / (1024.0 * 1024.0), device_bytes.c_str(), budget_bytes.c_str());
LOG_WARN("%s", message.c_str());
if (device_memory_error != nullptr && available.valid) {
*device_memory_error = std::move(message);

View file

@ -4,6 +4,7 @@
#include <cstdint>
void pretty_progress(int step, int steps, float time);
void pretty_console_progress(int step, int steps, float time);
void pretty_bytes_progress(int step, int steps, uint64_t bytes_processed, float elapsed_seconds);
namespace sd {

View file

@ -592,14 +592,17 @@ static void print_progress_line(int step, int steps, const std::string& speed_te
fflush(stdout); // for linux
}
static int show_eta = -1; // -1 - estimate duration, 0 - hide, 1 - show
static float passed_time = 0.f;
void pretty_progress(int step, int steps, float time) {
if (sd_progress_cb) {
sd_progress_cb(step, steps, time, sd_progress_cb_data);
return;
}
pretty_console_progress(step, steps, time);
}
void pretty_console_progress(int step, int steps, float time) {
static thread_local int show_eta = -1; // -1 - estimate duration, 0 - hide, 1 - show
static thread_local float passed_time = 0.f;
if (step == 0) {
show_eta = -1; // reinitialize for batch generations
passed_time = 0.f;
@ -654,7 +657,7 @@ void pretty_bytes_progress(int step, int steps, uint64_t bytes_processed, float
if (!byte_progress_console)
return;
}
if (sd_progress_cb) {
if (!byte_progress_console && sd_progress_cb) {
float time = elapsed_seconds / (step + 1e-6f);
sd_progress_cb(step, steps, time, sd_progress_cb_data);
return;

View file

@ -132,6 +132,9 @@ namespace sd::dgl {
if (!parse_strict_bool(value, enabled))
throw std::runtime_error("batched_cfg expects a boolean");
batched_cfg = enabled;
} else if (key == "console_progress") {
if (!parse_strict_bool(value, callbacks.console_progress))
throw std::runtime_error("console_progress expects a boolean");
} else if (key == "max_vram") {
ggml_graph_cut::MaxVramAssignment limit;
std::string error;

View file

@ -202,8 +202,8 @@ namespace sd::dgl::models {
return decoded;
}
if (!sd::backend_fit::prepare_vae_decode_retry_tiling(tiling_params, prefer_temporal_tiling,
first_stage_model->last_compute_status(),
tile_size_w, tile_size_h, first_stage_model->get_scale_factor())) {
first_stage_model->last_compute_status(),
tile_size_w, tile_size_h, first_stage_model->get_scale_factor())) {
break;
}
}

View file

@ -1,5 +1,7 @@
#include "run_events.h"
#include <cstdio>
#include "diagnostic.h"
namespace sd::dgl {
@ -43,29 +45,48 @@ namespace sd::dgl {
run.progress_.report("loading", "", completed, total, "tensors");
}
void RunEvents::render_sample_progress(int completed, int total_steps, float time) {
const bool console_only = forces_console_progress();
const bool renders_line = console_only || !sd_get_progress_callback();
if (console_only)
pretty_console_progress(completed, total_steps, time);
else
pretty_progress(completed, total_steps, time);
sample_line_open_ = renders_line && completed > 0 && completed < total_steps;
}
void RunEvents::begin_sample(int total_steps) {
check_cancelled();
finish_sample_line();
++preview_info_.sample_pass;
preview_info_.total_steps = total_steps;
if (legacy_preview_)
sd_begin_preview_pass(total_steps);
last_progress_us_ = ggml_time_us();
if (legacy_progress_ || !callbacks_.progress)
pretty_progress(0, total_steps, 0.f);
if (uses_console_progress())
render_sample_progress(0, total_steps, 0.f);
progress_.begin_sample(total_steps, "");
check_cancelled();
}
void RunEvents::sample_step(int completed, int total_steps) {
if (legacy_progress_ || !callbacks_.progress) {
if (uses_console_progress()) {
const auto now = ggml_time_us();
pretty_progress(completed, total_steps, (now - last_progress_us_) / 1000000.f);
render_sample_progress(completed, total_steps, (now - last_progress_us_) / 1000000.f);
last_progress_us_ = now;
}
progress_.report_sample(completed, total_steps);
check_cancelled();
}
void RunEvents::finish_sample_line() {
if (sample_line_open_) {
std::fputc('\n', stdout);
std::fflush(stdout);
sample_line_open_ = false;
}
}
void RunEvents::preview_bridge(int step, int frame_count, const sd_tensor_t* const* frames, bool noisy, void* userdata) {
auto& run = *static_cast<RunEvents*>(userdata);
if (run.cancelled())
@ -78,11 +99,12 @@ namespace sd::dgl {
RunEventsScope::RunEventsScope(RunEvents& events)
: previous_(active_events),
byte_progress_(events.uses_legacy_progress() ? nullptr : RunEvents::report_loading, &events),
console_progress_(events.uses_legacy_progress() || !events.callbacks().progress) {
byte_progress_(!events.uses_legacy_progress() && events.callbacks().progress ? RunEvents::report_loading : nullptr, &events),
console_progress_(events.forces_console_progress()) {
active_events = &events;
}
RunEventsScope::~RunEventsScope() {
active_events->finish_sample_line();
active_events = previous_;
}

View file

@ -17,6 +17,7 @@ namespace sd::dgl {
int interval = 0;
bool denoised = false;
bool noisy = false;
bool console_progress = false;
};
class RunEvents {
@ -28,8 +29,10 @@ namespace sd::dgl {
void* legacy_preview_data_ = nullptr;
bool legacy_progress_ = false;
int64_t last_progress_us_ = 0;
bool sample_line_open_ = false;
static void preview_bridge(int step, int frame_count, const sd_tensor_t* const* frames, bool noisy, void* userdata);
void render_sample_progress(int completed, int total_steps, float time);
public:
RunEvents(const RunCallbacks& callbacks, bool legacy_callbacks);
@ -41,8 +44,11 @@ namespace sd::dgl {
void report_frames(const char* stage, int completed, int total) const;
static void report_loading(int completed, int total, void* data);
bool uses_legacy_progress() const { return legacy_progress_; }
bool forces_console_progress() const { return !legacy_progress_ && callbacks_.console_progress; }
bool uses_console_progress() const { return legacy_progress_ || !callbacks_.progress || forces_console_progress(); }
void begin_sample(int total_steps);
void sample_step(int completed, int total_steps);
void finish_sample_line();
const RunCallbacks& callbacks() const { return callbacks_; }
const sd_preview_info_t& preview_info() const { return preview_info_; }
bool uses_legacy_preview() const { return legacy_preview_ != nullptr; }

View file

@ -87,19 +87,19 @@ namespace RelayVSR {
}
ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* context, ggml_tensor* query_rope, ggml_tensor* key_rope, const VSR::LocalAttention* local, const std::string& cut_group, const std::string& attention_name) {
auto to_q = std::dynamic_pointer_cast<Linear>(blocks["to_q"]);
auto to_k = std::dynamic_pointer_cast<Linear>(blocks["to_k"]);
auto to_v = std::dynamic_pointer_cast<Linear>(blocks["to_v"]);
auto to_out_0 = std::dynamic_pointer_cast<Linear>(blocks["to_out.0"]);
auto norm_q = std::dynamic_pointer_cast<RMSNorm>(blocks["norm_q"]);
auto norm_k = std::dynamic_pointer_cast<RMSNorm>(blocks["norm_k"]);
auto c = ctx->ggml_ctx;
auto q = norm_q->forward(ctx, to_q->forward(ctx, x));
auto to_q = std::dynamic_pointer_cast<Linear>(blocks["to_q"]);
auto to_k = std::dynamic_pointer_cast<Linear>(blocks["to_k"]);
auto to_v = std::dynamic_pointer_cast<Linear>(blocks["to_v"]);
auto to_out_0 = std::dynamic_pointer_cast<Linear>(blocks["to_out.0"]);
auto norm_q = std::dynamic_pointer_cast<RMSNorm>(blocks["norm_q"]);
auto norm_k = std::dynamic_pointer_cast<RMSNorm>(blocks["norm_k"]);
auto c = ctx->ggml_ctx;
auto q = norm_q->forward(ctx, to_q->forward(ctx, x));
const auto cache_name = cut_group + "." + attention_name;
auto past_k = ctx->get_cache_tensor(cache_name + ".key");
auto past_v = ctx->get_cache_tensor(cache_name + ".value");
ggml_tensor* k = nullptr;
ggml_tensor* v = nullptr;
auto past_k = ctx->get_cache_tensor(cache_name + ".key");
auto past_v = ctx->get_cache_tensor(cache_name + ".value");
ggml_tensor* k = nullptr;
ggml_tensor* v = nullptr;
if (context && past_k) {
k = past_k;
v = past_v;

View file

@ -6216,7 +6216,7 @@ inline bool range_error(Request &req, Response &res) {
}
if (first_pos == -1) {
first_pos = content_len - last_pos;
first_pos = content_len - (std::min)(content_len, last_pos);
last_pos = content_len - 1;
}