Commit 825c96f for stable-diffusion.cpp
commit 825c96f06ddbe1611a128b9365cac15383deb20c
Author: leejet <leejet714@gmail.com>
Date: Sun Dec 6 13:46:26 2026 +0800
fix(api): let embedders control log threads and upscaler progress (#2539)
diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md
index c353553..d3e9256 100644
--- a/docs/guides/c_api.md
+++ b/docs/guides/c_api.md
@@ -179,11 +179,26 @@ The bundled CLI and server retain these modes as strings and pass them directly
to setters. Enum parsers, enum name helpers, parameter configuration layouts and
name tables are internal and are not exported by the shared library.
+## Logging
+
+Register a process-wide log callback with
+`sd_set_log_callback(callback, user_data, use_output_thread)`. Pass `false` to
+receive logs synchronously on their emitting threads, which can call the
+callback concurrently. Pass `true` to queue logs on the library's output
+thread. Normally, replacing or clearing a callback drains its queued logs and
+waits for its active invocations before returning. The caller can then release
+the previous `user_data`.
+
+Replacing or clearing a callback from inside a log callback or on the output
+thread discards pending deliveries to the previous callback and returns without
+waiting for its active invocations. Keep its `user_data` valid until those
+invocations finish.
+
## Progress and previews
-Register a progress callback on an idle context. Both context types use the
-same event and options. A DGL context borrowed from `sd_ctx_get_dgl_ctx()`
-shares the registration with its owning context.
+Register a progress callback on an idle generation, DGL, or upscaler context.
+All three use the same event and options. A DGL context borrowed from
+`sd_ctx_get_dgl_ctx()` shares the registration with its owning context.
```c
const sd_progress_options_t options = {
@@ -196,6 +211,10 @@ sd_status_t status = sd_ctx_set_progress_callback(ctx, callback, user_data, &opt
sd_ctx_set_progress_callback(ctx, NULL, NULL, NULL);
```
+After `sd_upscaler_create()`, call
+`sd_upscaler_set_progress_callback(upscaler, callback, user_data, NULL)` to
+receive upscaling progress events and suppress the built-in tile progress bars.
+
With a callback registered, set `console_progress` to keep the library's
progress bars visible. A null options pointer subscribes to progress with
previews and console output disabled. Passing a null callback clears the
diff --git a/examples/cli/dgl.cpp b/examples/cli/dgl.cpp
index 64d8087..99a4599 100644
--- a/examples/cli/dgl.cpp
+++ b/examples/cli/dgl.cpp
@@ -304,7 +304,7 @@ int DGLModeParams::run(const SDContextParams& options,
}
check_dgl(sd_dgl_ctx_set(context.get(), "embed_metadata", embed_metadata ? "on" : "off"));
sd_dgl_result_t* raw_result = nullptr;
- const auto status = sd_dgl_run(context.get(), source.c_str(), nullptr, 0, &raw_result);
+ const auto status = sd_dgl_run(context.get(), source.c_str(), nullptr, 0, &raw_result);
log_callback.flush();
check_dgl(status == SD_STATUS_OK);
std::unique_ptr<sd_dgl_result_t, decltype(&sd_dgl_result_free)> result(raw_result, sd_dgl_result_free);
diff --git a/examples/common/log.h b/examples/common/log.h
index acf0076..ccba82e 100644
--- a/examples/common/log.h
+++ b/examples/common/log.h
@@ -27,14 +27,14 @@ class LogCallbackRegistration {
public:
LogCallbackRegistration(sd_log_cb_t callback, void* data)
: callback_(callback), data_(data) {
- sd_set_log_callback(callback_, data_);
+ sd_set_log_callback(callback_, data_, true);
}
- ~LogCallbackRegistration() { sd_set_log_callback(nullptr, nullptr); }
+ ~LogCallbackRegistration() { sd_set_log_callback(nullptr, nullptr, true); }
LogCallbackRegistration(const LogCallbackRegistration&) = delete;
LogCallbackRegistration& operator=(const LogCallbackRegistration&) = delete;
// Re-registering the callback waits for output queued by the previous phase.
- void flush() const { sd_set_log_callback(callback_, data_); }
+ void flush() const { sd_set_log_callback(callback_, data_, true); }
};
std::string sd_basename(const std::string& path);
diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h
index 88019e1..fdd63fc 100644
--- a/include/stable-diffusion.h
+++ b/include/stable-diffusion.h
@@ -280,10 +280,15 @@ enum sd_log_level_t {
SD_LOG_ERROR
};
-// Log callbacks run on the library's output thread. Keep data valid until the callback is cleared or replaced.
typedef void (*sd_log_cb_t)(enum sd_log_level_t level, const char* text, void* data);
-// Calls from application threads wait for queued output. Call outside locks the previous callback may need.
-SD_API void sd_set_log_callback(sd_log_cb_t sd_log_cb, void* data);
+// Set use_output_thread to queue callbacks on the library's output thread.
+// Otherwise, each callback runs on its emitting thread and may run concurrently
+// with other log callbacks. A NULL callback clears the registration.
+// Ordinary calls drain queued logs and wait for the previous callback to finish.
+// Calls from a log callback or the output thread skip these waits and discard
+// pending deliveries to the previous callback. Keep its data valid until any
+// invocations already in flight finish. Call outside locks the callback may need.
+SD_API void sd_set_log_callback(sd_log_cb_t sd_log_cb, void* data, bool use_output_thread);
typedef struct {
int frame_count;
@@ -359,6 +364,12 @@ SD_API void sd_set_backend_eval_callback(sd_graph_eval_callback_t cb, void* data
SD_API sd_status_t sd_upscaler_create(const sd_upscaler_opt_t* opt, sd_upscaler_t** out);
SD_API void sd_upscaler_free(sd_upscaler_t* upscaler);
+// Same registration and console progress options as sd_ctx_set_progress_callback.
+SD_API sd_status_t sd_upscaler_set_progress_callback(
+ sd_upscaler_t* upscaler,
+ sd_generation_progress_cb_t callback,
+ void* userdata,
+ const sd_progress_options_t* options);
SD_API sd_status_t sd_upscale(sd_upscaler_t* upscaler, const sd_upscale_opt_t* opt, sd_result_t** out);
SD_API int sd_upscaler_get_scale(const sd_upscaler_t* upscaler);
diff --git a/src/api/upscaler.cpp b/src/api/upscaler.cpp
index 65aaaed..b47c4db 100644
--- a/src/api/upscaler.cpp
+++ b/src/api/upscaler.cpp
@@ -66,6 +66,18 @@ void sd_upscaler_free(sd_upscaler_t* upscaler) {
delete upscaler;
}
+sd_status_t sd_upscaler_set_progress_callback(sd_upscaler_t* upscaler, sd_generation_progress_cb_t callback, void* userdata, const sd_progress_options_t* options) {
+ return sd::api::call([&] {
+ if (!upscaler)
+ return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "upscaler is required");
+ auto& context = upscaler->context;
+ std::unique_lock<std::recursive_mutex> lock(context.mutex, std::try_to_lock);
+ if (!lock.owns_lock() || context.executing)
+ return sd::api::error(SD_STATUS_BUSY, nullptr, "upscaler is busy");
+ return sd_dgl_ctx_set_progress_callback(&context.execution, callback, userdata, options);
+ });
+}
+
int sd_upscaler_get_scale(const sd_upscaler_t* upscaler) {
sd::api::clear_error();
if (!upscaler || !upscaler->model) {
diff --git a/src/core/console_output.cpp b/src/core/console_output.cpp
index dea6c23..58d39a6 100644
--- a/src/core/console_output.cpp
+++ b/src/core/console_output.cpp
@@ -84,16 +84,59 @@ struct SegmentConsoleFrame {
std::shared_ptr<const sd::ConsoleProgressLine> sampling;
};
+static thread_local bool wait_for_log_delivery = true;
+
+class ConsoleLogCallback {
+ std::mutex mutex_;
+ std::condition_variable completed_;
+ const sd_log_cb_t callback_;
+ void* const data_;
+ size_t active_ = 0;
+ bool enabled_ = true;
+
+public:
+ ConsoleLogCallback(sd_log_cb_t callback, void* data)
+ : callback_(callback), data_(data) {}
+
+ void deliver(sd_log_level_t level, const char* message) {
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (!enabled_)
+ return;
+ ++active_;
+ }
+
+ const bool previous_wait = std::exchange(wait_for_log_delivery, false);
+ try {
+ callback_(level, message, data_);
+ } catch (...) {
+ // A diagnostic callback must not interrupt library execution.
+ }
+ wait_for_log_delivery = previous_wait;
+
+ std::lock_guard<std::mutex> lock(mutex_);
+ --active_;
+ if (!enabled_)
+ completed_.notify_all();
+ }
+
+ void clear(bool wait) {
+ std::unique_lock<std::mutex> lock(mutex_);
+ enabled_ = false;
+ if (wait)
+ completed_.wait(lock, [&] { return active_ == 0; });
+ }
+};
+
struct ConsoleLog {
sd_log_level_t level;
std::string message;
-};
+ std::shared_ptr<ConsoleLogCallback> callback;
-struct ConsoleLogCallback {
- sd_log_cb_t callback = nullptr;
- void* data = nullptr;
+ void deliver() const { callback->deliver(level, message.c_str()); }
};
+struct ConsoleLogFlush {};
struct ConsoleNewline {};
using ConsoleClock = std::chrono::steady_clock;
@@ -109,7 +152,7 @@ struct ConsoleSampleEnd {
bool newline;
};
-using ConsoleEvent = std::variant<ConsoleLine, SegmentConsoleFrame, ConsoleLog, ConsoleLogCallback, ConsoleNewline, ConsoleSampleBegin, ConsoleSampleEnd>;
+using ConsoleEvent = std::variant<ConsoleLine, SegmentConsoleFrame, ConsoleLog, ConsoleLogFlush, ConsoleNewline, ConsoleSampleBegin, ConsoleSampleEnd>;
class SamplingCursor {
std::thread::id owner_;
@@ -272,26 +315,15 @@ class ConsoleWriter {
SegmentConsole segment_;
std::optional<SegmentConsoleFrame> frame_;
std::optional<FirstSample> first_sample_;
- ConsoleLogCallback sink_;
std::vector<ConsoleLog> deferred_debug_;
bool frame_dirty_ = false;
- void deliver(const ConsoleLog& log) const noexcept {
- if (sink_.callback) {
- try {
- sink_.callback(log.level, log.message.c_str(), sink_.data);
- } catch (...) {
- // A diagnostic callback must not stop the output worker.
- }
- }
- }
-
void split_output() {
segment_.clear();
frame_dirty_ = frame_.has_value();
const auto deferred = std::exchange(deferred_debug_, {});
for (const auto& log : deferred)
- deliver(log);
+ log.deliver();
}
bool end_first_sample(std::thread::id owner) {
@@ -322,21 +354,15 @@ public:
}
void write(ConsoleLog log) {
- if (!sink_.callback)
- return;
if (frame_ && log.level == SD_LOG_DEBUG) {
deferred_debug_.push_back(std::move(log));
} else {
split_output();
- deliver(log);
+ log.deliver();
}
}
- void write(ConsoleLogCallback sink) {
- split_output();
- sink_ = sink;
- console_log_enabled.store(sink.callback != nullptr, std::memory_order_relaxed);
- }
+ void write(ConsoleLogFlush) { split_output(); }
void write(ConsoleLine output) {
const bool sampling = output.sampler != std::thread::id{};
@@ -417,17 +443,17 @@ public:
}
};
-static thread_local ConsoleWriter* current_console_writer = nullptr;
-
class ConsoleOutput {
std::mutex mutex_;
std::condition_variable ready_;
std::condition_variable completed_;
std::deque<ConsoleEvent> events_;
std::thread worker_;
- size_t submitted_ = 0;
- size_t written_ = 0;
- bool stopping_ = false;
+ std::shared_ptr<ConsoleLogCallback> log_callback_;
+ size_t submitted_ = 0;
+ size_t written_ = 0;
+ bool stopping_ = false;
+ bool use_output_thread_ = false;
static bool can_replace(const ConsoleEvent& previous, const ConsoleEvent& next) {
if (const auto* frame = std::get_if<SegmentConsoleFrame>(&previous)) {
@@ -444,7 +470,7 @@ class ConsoleOutput {
void run() {
ConsoleWriter writer;
- current_console_writer = &writer;
+ wait_for_log_delivery = false;
std::deque<ConsoleEvent> batch;
std::unique_lock<std::mutex> lock(mutex_);
for (;;) {
@@ -480,7 +506,24 @@ class ConsoleOutput {
}
}
lock.unlock();
- current_console_writer = nullptr;
+ }
+
+ size_t submit_locked(ConsoleEvent event) noexcept {
+ try {
+ if (stopping_)
+ return 0;
+ if (!worker_.joinable())
+ worker_ = std::thread([this] { run(); });
+ if (!events_.empty() && can_replace(events_.back(), event)) {
+ events_.back() = std::move(event);
+ } else {
+ events_.push_back(std::move(event));
+ }
+ ready_.notify_one();
+ return ++submitted_;
+ } catch (...) {
+ return 0;
+ }
}
public:
@@ -497,25 +540,44 @@ public:
size_t submit(ConsoleEvent event) noexcept {
try {
std::lock_guard<std::mutex> lock(mutex_);
- if (stopping_)
- return 0;
- if (!worker_.joinable())
- worker_ = std::thread([this] { run(); });
- if (!events_.empty() && can_replace(events_.back(), event)) {
- events_.back() = std::move(event);
- } else {
- events_.push_back(std::move(event));
- }
- ready_.notify_one();
- return ++submitted_;
+ return submit_locked(std::move(event));
} catch (...) {
return 0;
}
}
- void wait_until_written(size_t end) {
+ void write_log(ConsoleLog log) {
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (stopping_ || !log_callback_)
+ return;
+ log.callback = log_callback_;
+ if (use_output_thread_) {
+ submit_locked(std::move(log));
+ return;
+ }
+ }
+ log.deliver();
+ }
+
+ void set_log_callback(sd_log_cb_t callback, void* data, bool use_output_thread) {
+ auto next = callback ? std::make_shared<ConsoleLogCallback>(callback, data) : nullptr;
std::unique_lock<std::mutex> lock(mutex_);
- completed_.wait(lock, [&] { return written_ >= end; });
+ if (stopping_)
+ return;
+ const auto previous = std::exchange(log_callback_, std::move(next));
+ const bool flush = use_output_thread_ || use_output_thread;
+ use_output_thread_ = callback && use_output_thread;
+ console_log_enabled.store(callback != nullptr, std::memory_order_relaxed);
+ // Reentrant registration can be part of the delivery another caller is draining.
+ if (flush && wait_for_log_delivery) {
+ const auto end = submit_locked(ConsoleLogFlush{});
+ completed_.wait(lock, [&] { return written_ >= end; });
+ }
+ if (wait_for_log_delivery)
+ lock.unlock();
+ if (previous)
+ previous->clear(wait_for_log_delivery);
}
};
@@ -634,7 +696,7 @@ static void sd_log_dispatch(sd_log_level_t level, const std::string& origin, con
} else {
message += " --- " + origin + '\n';
}
- console_output().submit(ConsoleLog{level, std::move(message)});
+ console_output().write_log(ConsoleLog{level, std::move(message), {}});
}
void log_printf(sd_log_level_t level, const char* file, int line, const char* format, ...) {
@@ -668,14 +730,9 @@ void sd_ggml_log_callback(ggml_log_level level, const char* text, void*) {
sd_log_dispatch(sd_level, "ggml", text);
}
-void sd_set_log_callback(sd_log_cb_t cb, void* data) {
- const ConsoleLogCallback callback{cb, data};
- if (current_console_writer) {
- current_console_writer->write(callback);
- } else {
- auto& output = console_output();
- const auto update = output.submit(callback);
- if (update)
- output.wait_until_written(update);
+void sd_set_log_callback(sd_log_cb_t cb, void* data, bool use_output_thread) {
+ try {
+ console_output().set_log_callback(cb, data, use_output_thread);
+ } catch (...) {
}
}