Skip to content

Commit 099fc72

Browse files
committed
feat: return generation metadata with core results
1 parent 95ff762 commit 099fc72

37 files changed

Lines changed: 1528 additions & 758 deletions

‎docs/generation_metadata.md‎

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
# Generation results and metadata
2+
3+
`generate_image()`, `generate_video()`, `adetail_image()` and `upscale()` return
4+
owned results containing the media and its generation record. This is a breaking
5+
C API change: applications and bindings must update their calls and rebuild.
6+
7+
```c
8+
sd_img_gen_params_t params;
9+
sd_img_gen_params_init(&params);
10+
params.prompt = "a small house";
11+
12+
sd_image_generation_result_t* result = NULL;
13+
if (generate_image(ctx, &params, &result)) {
14+
for (int i = 0; i < result->count; ++i) {
15+
const sd_image_result_t* item = &result->items[i];
16+
/* Consume item->image and item->generation_info together. */
17+
}
18+
free_sd_image_generation_result(result);
19+
}
20+
```
21+
22+
`result_out` is required and is set to `NULL` on failure. A successful result
23+
owns its pixels and UTF-8 JSON strings. The video result additionally owns its
24+
audio and contains the effective `fps` and `frame_count`. Results remain valid
25+
after freeing the generation context. Use the matching library result destructor;
26+
do not separately free fields unless transferring ownership and clearing them.
27+
Both result destructors accept `NULL`.
28+
29+
## Reproduction parameters
30+
31+
The `sdcpp.generation/v1` JSON is a snapshot of generation parameters for the
32+
same loaded context and the same input images, masks, reference media and other
33+
assets. It is created after `GenerationRequest` resolves the request, before
34+
preprocessing or sampling. A failed call returns no result or metadata.
35+
36+
Fields follow the C generation parameter structs: `prompt`, `negative_prompt`,
37+
`width`, `height`, `seed`, `sample_params`, `hires`, `cache`,
38+
`vae_tiling_params`, `image_preprocess`, and the image/video-specific options.
39+
`kind` distinguishes image and video parameters. There is no inferred `task`.
40+
Enums use their API string names. Seeds are decimal strings to preserve their
41+
full integer range. Omitted optional fields retain the parameter initializer's
42+
defaults, including automatic values represented by infinity in the C API.
43+
44+
Disabled optional features are omitted entirely: `cache`, `hires`, VAE tiling,
45+
zero/nonpositive `shifted_timestep`, inactive SLG, false circular axes, and empty
46+
preprocessing/reference arguments. SLG layers remain present when `slg_uncond`
47+
is enabled even with zero SLG scale. Enabled caches store their mode's parameters;
48+
TaylorSeer retains the shared DBCache thresholds and limits used by the runtime.
49+
Image CFG at its neutral value of 1 is omitted and resolves back to 1 by default.
50+
51+
Image strength, ControlNet/IP-Adapter strength and PhotoMaker settings are stored
52+
when their corresponding input images are supplied. PuLID requires an embedding
53+
path. Layer count is stored for layered generation; video VACE and high-noise
54+
settings require those models. High-noise settings omit scheduler, custom sigmas,
55+
flow shift and timestep shifting because that pass shares the base configuration.
56+
Explicit nonempty argument strings are retained without rewriting their contents.
57+
Core sampling values such as seed, sampler, scheduler, steps and guidance remain
58+
explicit even when equal to their defaults. ADetailer always retains its inpaint
59+
strength because its input crops are created later.
60+
Model-required VAE tiling is resolved before serialization, so forced tiling
61+
(such as MiniMax-H3) remains present even if the caller did not enable it.
62+
63+
The request fixes the seed, dimensions, clip skip, guidance, sampler, scheduler
64+
and eta before taking the snapshot. `custom_sigmas` is stored only when supplied
65+
as an input. Automatically computed schedules, preprocessing transforms,
66+
conditioning/cache decisions, detector regions and output statistics are not
67+
stored: they are recomputed from the same parameters and inputs.
68+
69+
Each image records the seed used to sample its latent. `batch_count` is omitted;
70+
replay image parameters with `batch_count = 1`. Layers or frames decoded from
71+
the same latent share its seed, so layered generation reproduces that group of
72+
layers. Video frames share the video request. Partial batch cancellation returns
73+
metadata only for completed outputs. Full cancellation returns no result.
74+
75+
The current image pipeline prepares input latents once using the starting seed
76+
and shares them across a batch. With a stochastic VAE encoder, replaying a later
77+
image alone using its sampling seed can change those input latents. Per-image
78+
seeds therefore do not guarantee independent reproduction for these paths.
79+
80+
To replay a record, initialize the matching C parameter struct, populate its
81+
fields from the JSON, restore the same input buffers, and call generation with
82+
the same context. Keep custom-sigma/SLG arrays and string storage alive for the
83+
call. Paths supplied as generation parameters (LoRAs, hires models and identity
84+
embeddings) are retained. `models` identifies successfully loaded context model
85+
files by component (`model`, `diffusion_model`, `clip_l`, `vae`, etc.), using
86+
filenames with extensions and omitting directories. Optional components disabled
87+
for the request and preview-only TAE are omitted. WebUI text includes `Model`
88+
(the diffusion model when supplied separately, otherwise the checkpoint, without
89+
the extension) and `VAE` for a separate active VAE. These names are identifiers,
90+
not hashes or sufficient configuration to rebuild a context; replay still requires
91+
the same model files and context settings. The JSON does not embed media buffers
92+
or model weights.
93+
94+
When `--lora-model-dir` is configured, CLI/server output records express LoRA
95+
paths relative to that directory, preserving subdirectories and file extensions
96+
and using `/` separators. This applies to file metadata, API responses and
97+
ADetailer records. Resolve these paths against the same LoRA directory before
98+
passing them back to the C API. Core results retain the supplied loading paths.
99+
Files outside the directory retain `..` components; paths on another volume,
100+
or records without a configured LoRA directory, retain their original paths.
101+
102+
## Postprocessing
103+
104+
Upscale records `upscale.upscale_factor`. ADetailer records `adetailer` and
105+
`inpaint_params`, with a concrete starting seed chosen before detection. These
106+
operations require the same upscaler/detector context and source image on replay.
107+
They do not store detection results or per-region generation traces.
108+
109+
The CLI/server append operation parameter snapshots to `postprocess` in call
110+
order. The source generation parameters remain unchanged. Frame postprocessing
111+
uses the same operation parameters for each video frame. Standalone
112+
postprocessing does not invent source diffusion parameters for an input image.
113+
114+
## File metadata
115+
116+
Image encoders accept the native record and derive WebUI infotext from it.
117+
Images use the existing metadata locations and combined text layout:
118+
`<WebUI infotext>, SDCPP: <native JSON>`. Standalone postprocessing without
119+
source diffusion parameters stores only native JSON. Video metadata stores
120+
only native JSON.
121+
122+
| Container | Metadata location |
123+
| --- | --- |
124+
| PNG | `tEXt`, keyword `parameters` |
125+
| JPEG | COM segment, `parameters` label followed by a NUL byte |
126+
| WebP image / animated WebP | XMP property `sdcpp:parameters` |
127+
| AVI | RIFF INFO `ICMT` |
128+
| WebM | `COMMENT` tag |
129+
130+
Inspect images or videos with `sd-cli -M metadata --image <file>`; the same
131+
command supports all containers above, with `--metadata-format json` for a
132+
structured report. Video metadata inspection does not require a model or video
133+
decoder.
134+
Matroska containers are also supported, including `.webm` outputs whose audio
135+
codec causes the muxer to select the Matroska document type.
136+
137+
The XMP namespace is `https://github.com/leejet/stable-diffusion.cpp/ns/1.0/`.
138+
PNG and JPEG retain the existing UTF-8 text payload convention. Memory encoding
139+
and file saving use the same implementation. The core result and API
140+
`generation_info` fields remain pure JSON; the combined layout applies only
141+
to embedded image metadata.
142+
143+
WebUI conversion is lossy: known samplers and schedules have explicit name
144+
mappings; unsupported ones use `SDCPP Sampler`/`SDCPP Schedule` fields. Hires
145+
keeps the base request size and separate configured hires size/steps. The native
146+
record retains the full generation parameters. Standalone postprocessing has no WebUI
147+
infotext because its original diffusion settings are unknown.
148+
149+
WebUI prompt text appends ordinary LoRAs as `<lora:filename_without_extension:weight>`.
150+
Directory components are omitted to match WebUI's filename lookup; the native
151+
`loras` array retains relative paths and weights. High-noise-only LoRAs and names
152+
that cannot be represented by this tag syntax remain in the native record only.
153+
The native prompt is not modified, and postprocessing LoRAs are not added to the
154+
source generation prompt.
155+
156+
JPEG requires the COM payload, including the label and terminating NUL bytes,
157+
to fit within 65,533 bytes. Larger records fail encoding with an error rather
158+
than being truncated. Use PNG or WebP for larger records.
159+
160+
Disabling file metadata omits both image representations, but does not disable
161+
the core generation record or its API response. Native async image results and
162+
OpenAI image response items contain `generation_info`; video results contain a
163+
sequence-level `generation_info`. The SD API `info` object contains per-output
164+
`generation_info` alongside derived `infotexts` and each image's seed. Its outer
165+
`parameters` field continues to echo the request.

‎docs/image_preprocessing.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -149,20 +149,23 @@ an array of rule strings:
149149
OpenAI-compatible requests accept it through
150150
`<sd_cpp_extra_args>{...}</sd_cpp_extra_args>` in the prompt.
151151
Request rules replace server-default rules. Generation metadata records the
152-
user rules; image encodings and channel conventions are unchanged.
152+
user rules for replay with the same input images; image encodings and channel conventions are unchanged.
153153

154154
## C API
155155

156156
Set `image_preprocess` on the existing image/video generation parameters.
157-
The `generate_image()` and `generate_video()` signatures are unchanged:
157+
Generation returns media and actual parameters together; see [generation metadata](generation_metadata.md):
158158

159159
```c
160160
sd_img_gen_params_t params;
161161
sd_img_gen_params_init(&params);
162162
/* Set prompt, original-resolution input images, and generation options. */
163163
params.image_preprocess.rules = "target=init,mode=crop-resize,filter=lanczos;"
164164
"target=mask,filter=nearest-exact";
165-
bool ok = generate_image(ctx, &params, &images, &count);
165+
sd_image_generation_result_t* result = NULL;
166+
bool ok = generate_image(ctx, &params, &result);
167+
/* Consume result->items and their generation_info on success. */
168+
free_sd_image_generation_result(result);
166169
```
167170
168171
Both generation parameter initializers set `image_preprocess.rules` to `NULL`,

‎examples/cli/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ set(TARGET sd-cli)
22

33
add_executable(${TARGET}
44
../common/common.cpp
5+
../common/generation_metadata.cpp
56
../common/log.cpp
67
../common/media_io.cpp
8+
../common/media_metadata.cpp
79
image_metadata.cpp
810
main.cpp
911
)

‎examples/cli/README.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,21 @@ rule for edge detection. See
3131
[Image preprocessing](../../docs/image_preprocessing.md) for input selectors,
3232
input defaults, downstream model processing, mask alignment, and examples.
3333

34-
Metadata mode inspects PNG/JPEG container metadata without loading any model:
34+
Metadata mode inspects PNG, JPEG, WebP (including animated WebP), AVI, WebM, and Matroska
35+
container metadata without loading any model. Use `--image` for both images and videos:
3536

3637
```bash
3738
./bin/sd-cli -M metadata --image ./output.png
3839
./bin/sd-cli -M metadata --image ./output.jpg --metadata-format json
40+
./bin/sd-cli -M metadata --image ./output.webm
41+
./bin/sd-cli -M metadata --image ./output.avi --metadata-format json
3942
./bin/sd-cli -M metadata --image ./output.png --metadata-raw
4043
./bin/sd-cli -M metadata --image ./output.png --metadata-all
4144
```
4245

4346
For completely black or white images or videos, NaNs, and the `--linear-scale` /
4447
`--attn-scale` workaround, see [Troubleshooting](../../docs/troubleshooting.md).
48+
49+
Generation outputs embed the core [generation record](../../docs/generation_metadata.md).
50+
Images retain the native JSON and an additional WebUI-compatible infotext.
51+
`--disable-image-metadata` omits both from files.

0 commit comments

Comments
 (0)