stable-diffusion.cpp/examples/server/runtime.h
Claude c2f6e845b1
Merge leejet/stable-diffusion.cpp 532d2c1 into fork-pull (sync 3/4)
Third of four steps towards upstream 3b12781: the opaque C API with
options, tensors and results (#2365).

The fork's additions move to the new API:
- multi_gpu, memory_guard and disable_backend_fallback are context
  options (sd::ContextConfig, registered in src/api/options.cpp) that
  sd-cli and sd-server set through SDContextParams::to_context_opt().
- Our classified error code is renamed sd_get_last_error_code(), since
  upstream's sd_get_last_error() now returns the diagnostic text.
  sd_ctx_create, sd_generate_image and sd_generate_video record it again
  (src/api/api.cpp); the device, system-memory and error-code functions
  stay in the public header.
- ContextKeeper creates contexts with sd_ctx_create() from the settings
  of each profile; its create_context hook takes SDContextParams. Every
  attempt builds fresh image or video options and forces VAE tiling with
  the vae_tiling.enabled key; ADetailer follows the keeper's context.
- Settings that became std::optional are read with the library defaults
  (profiles, keeper, conditioning-cache check); the obsolete seed
  workaround in sd-server is gone, since an unset seed is now random.
- test/profile_test, server_recovery_test and api_robustness use the new
  API; the scripted contexts are real sd_ctx_t objects, as sd_ctx_free()
  deletes them.

Verified with a CPU build: the library, sd-cli and sd-server build; all
eight unit-test programs pass, server_recovery_test also eight times in
a row and under ASan and TSan; sd-server answers /sdcpp/v1/health,
/sdcpp/v1/resources and refuses img_gen with model_not_loaded; sd-cli
reports a missing model as model_file. docs/integrazione_progetti.md
still shows the old API in its C examples; the docs follow after the
last step.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-11-24 13:01:39 +01:00

157 lines
5.3 KiB
C++

#pragma once
#include <algorithm>
#include <cstdint>
#include <filesystem>
#include <mutex>
#include <string>
#include <vector>
#include <json.hpp>
#include "common/common.h"
#include "common/resource_owners.hpp"
#include "stable-diffusion.h"
using json = nlohmann::json;
struct ArgOptions;
struct SDContextParams;
struct AsyncJobManager;
class ContextKeeper;
struct ServerModels;
struct SDSvrParams {
std::string listen_ip = "127.0.0.1";
int listen_port = 1234;
int max_pending_jobs = 64;
int completed_ttl_seconds = 600;
std::string serve_html_path;
std::string api_key; // empty = no authentication
std::string cors_origins; // comma-separated allowlist; empty = reflect any origin
bool disable_degradation = false;
int degradation_cooldown = 300; // seconds before the server tries a heavier profile again; 0 = never
std::vector<std::string> model_dirs;
bool normal_exit = false;
sd_log_level_t log_level = SD_LOG_INFO;
bool color = false;
ArgOptions get_options();
bool validate();
bool resolve_and_validate();
std::string to_string() const;
};
struct LoraEntry {
std::string name;
std::string path;
std::string fullpath;
std::string display_path;
std::filesystem::path root;
};
struct UpscalerEntry {
std::string name;
std::string path;
std::string fullpath;
std::string model_name;
int scale = 4;
int image_upscale_factor = 0;
uintmax_t file_size = 0;
std::filesystem::file_time_type last_modified;
};
struct ServerRuntime {
ContextKeeper* keeper;
const SDSvrParams* svr_params;
SDContextParams* ctx_params;
SDGenerationParams* default_gen_params;
std::vector<LoraEntry>* lora_cache;
std::mutex* lora_mutex;
std::vector<UpscalerEntry>* upscaler_cache;
std::mutex* upscaler_mutex;
AsyncJobManager* async_job_manager;
ServerModels* models;
};
struct ServerADetailerPass {
std::string prompt;
std::string negative_prompt;
std::string extra_args;
std::optional<int> width;
std::optional<int> height;
std::optional<float> strength;
std::optional<int> clip_skip;
bool automatic_scheduler = false;
};
struct ImgGenJobRequest {
SDGenerationParams gen_params;
std::string output_format = "png";
int output_compression = 100;
std::string preview_mode = "none";
int preview_interval = 1;
bool adetailer_enabled = true;
std::vector<ServerADetailerPass> adetailer_passes;
SDOptPtr to_image_opt() { return gen_params.to_image_opt(); }
};
class PromptImageCallbackGuard {
sd_ctx_t* ctx_;
const SDGenerationParams& params_;
SDTensorPtr image_tensor_;
static bool load_image(const char* source, void* data, const sd_tensor_t** image_out);
public:
PromptImageCallbackGuard(sd_ctx_t* ctx, const SDGenerationParams& params);
~PromptImageCallbackGuard();
PromptImageCallbackGuard(const PromptImageCallbackGuard&) = delete;
PromptImageCallbackGuard& operator=(const PromptImageCallbackGuard&) = delete;
};
constexpr int k_max_generation_dimension = 4096;
constexpr int k_max_adetailer_steps = 100;
bool validate_server_img_gen_request(const ServerRuntime& runtime,
const ImgGenJobRequest& request,
std::string& error_message);
struct VidGenJobRequest {
SDGenerationParams gen_params;
std::string output_format = "webm";
int output_compression = 100;
std::string preview_mode = "none";
int preview_interval = 1;
SDOptPtr to_video_opt() { return gen_params.to_video_opt(); }
};
std::string base64_encode(const std::vector<uint8_t>& bytes);
std::string normalize_output_format(std::string output_format);
std::vector<std::string> supported_img_output_formats(bool allow_webp = true);
std::vector<std::string> supported_vid_output_formats();
bool assign_output_options(ImgGenJobRequest& request,
std::string output_format,
int output_compression,
bool allow_webp,
std::string& error_message);
bool assign_output_options(VidGenJobRequest& request,
std::string output_format,
int output_compression,
std::string& error_message);
std::string video_mime_type(const std::string& output_format);
bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode);
std::string unsupported_generation_mode_error(const ServerRuntime& runtime, SDMode mode);
void refresh_lora_cache(ServerRuntime& rt);
std::string get_lora_full_path(ServerRuntime& rt, const std::string& path);
void refresh_upscaler_cache(ServerRuntime& rt);
int64_t unix_timestamp_now_ms();
// Runs ADetailer on the results, with the context that made them and the settings it was created with: after
// the server stepped down to a lighter profile, those differ from the ones it started with.
bool apply_server_adetailer(ServerRuntime& runtime,
sd_ctx_t* ctx,
const SDContextParams& ctx_params,
ImgGenJobRequest& request,
bool force_vae_tiling,
SDImageVec& results);