sd

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 17 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	SDTypeF32 SDType = iota
	SDTypeF16
	SDTypeQ4_0
	SDTypeQ4_1
	// SDTypeQ4_2 = 4, support has been removed
	// SDTypeQ4_3 = 5, support has been removed
	SDTypeQ5_0    = 6
	SDTypeQ5_1    = 7
	SDTypeQ8_0    = 8
	SDTypeQ8_1    = 9
	SDTypeQ2_K    = 10
	SDTypeQ3_K    = 11
	SDTypeQ4_K    = 12
	SDTypeQ5_K    = 13
	SDTypeQ6_K    = 14
	SDTypeQ8_K    = 15
	SDTypeIQ2_XXS = 16
	SDTypeIQ2_XS  = 17
	SDTypeIQ3_XXS = 18
	SDTypeIQ1_S   = 19
	SDTypeIQ4_NL  = 20
	SDTypeIQ3_S   = 21
	SDTypeIQ2_S   = 22
	SDTypeIQ4_XS  = 23
	SDTypeI8      = 24
	SDTypeI16     = 25
	SDTypeI32     = 26
	SDTypeI64     = 27
	SDTypeF64     = 28
	SDTypeIQ1_M   = 29
	SDTypeBF16    = 30
	// SDTypeQ4_0_4_4 = 31, support has been removed from gguf files
	// SDTypeQ4_0_4_8 = 32,
	// SDTypeQ4_0_8_8 = 33,
	SDTypeTQ1_0 = 34
	SDTypeTQ2_0 = 35
	// SDTypeIQ4_NL_4_4 = 36,
	// SDTypeIQ4_NL_4_8 = 37,
	// SDTypeIQ4_NL_8_8 = 38,
	SDTypeMXFP4   = 39
	SDTypeNVFP4   = 40 // NVFP4 (4 blocks, E4M3 scale)
	SDTypeQ1_0    = 41
	SDTypeQ2_0    = 42
	SDTypeF8_E4M3 = 43
	SDTypeF8_E5M2 = 44
	SDTypeCount   = 45
)

Variables

This section is empty.

Functions

func CGoString

func CGoString(cStr *uint8) string

Helper function: Convert C string to Go string

func CString

func CString(str string) *uint8

Helper function: Convert Go string to C string

func CacheParamsInit

func CacheParamsInit(params *SDCacheParams)

CacheParamsInit initializes cache parameters

func CleanupTempDir

func CleanupTempDir(tempDir string) error

CleanupTempDir cleans up temporary directory

func Commit

func Commit() string

Commit gets commit information

func ContextParamsInit

func ContextParamsInit(params *SDContextParams)

ContextParamsInit initializes context parameters

func ContextParamsToStr

func ContextParamsToStr(params *SDContextParams) string

ContextParamsToStr converts context parameters to string

func Convert

func Convert(inputPath, vaePath, outputPath string, outputType SDType, tensorTypeRules string, convertName bool) bool

Convert converts model

func EncodePNG

func EncodePNG(img *SDImage) ([]byte, error)

EncodePNG encodes an SDImage as PNG and returns the bytes, without touching the filesystem — useful for serving generated images directly (e.g. base64 over an API) instead of round-tripping through a file.

func EncodeVideo

func EncodeVideo(inputDir, outputPath string, framerate int) error

EncodeVideo encodes PNG frame sequence to video using FFmpeg

func FreeAudio

func FreeAudio(audio *SDAudio)

FreeAudio releases a native audio buffer allocated by the library. Audio from SDVideoGenerationResult.Audio belongs to that result and is released by its Free method instead. It is safe to call with a nil audio or when the native binding is unavailable (the library has not been loaded / the symbol was not registered), in which case it does nothing — consistent with FreeImage/FreeImages.

func FreeCString

func FreeCString(cStr *uint8)

Helper function: Free C string

func FreeImage

func FreeImage(img *SDImage)

FreeImage frees a single SDImage returned by the native library: its pixel buffer and the struct allocation itself. It is safe to call with a nil image or when the free binding is unavailable (in which case it does nothing).

func FreeImages

func FreeImages(imgs *SDImage, count int)

FreeImages frees an array of count SDImages allocated by the native library: a malloc'd array of images, each owning a malloc'd pixel buffer. It frees every image's pixel buffer and then the backing array allocation. It is safe to call with a nil pointer, a non-positive count, or when the free binding is unavailable (in which case it does nothing).

Never use it on images from SDImageGenerationResult or SDVideoGenerationResult. Those belong to the result, are not laid out as an SDImage array, and are released by the result's Free method.

When the library exports free_sd_images (added upstream in the master-802 resync) that is used, so the memory is released by the same C runtime that allocated it — the safe path on Windows, where the library and the process may link different CRTs. The manual free(3) walk is kept only as a fallback for the pathological case where the symbol failed to bind.

func GetCpuAVX

func GetCpuAVX() string

GetCpuAVX gets CPU AVX instruction set

func GetGPUName

func GetGPUName() (string, error)

GetGPUName names the vendor of this Windows machine's hardware GPU: "NVIDIA", "AMD", "Intel", or "" when it has none. Load uses it to pick a GPU build.

It reads the present display adapters from the device manager, which runs no program. It used to run `wmic path win32_VideoController get name`, and a failure to run wmic read as "no GPU": recent Windows 11 does not install wmic, and a PATH without System32\Wbem cannot find it, so Load fell back to a CPU build on a GPU machine. wmic is still tried when the device manager cannot be read or names no GPU, so no machine the old probe recognised is lost; its failure then just means "none".

func GetNumPhysicalCores

func GetNumPhysicalCores() int

GetNumPhysicalCores gets the number of physical cores

func GetSystemInfo

func GetSystemInfo() string

GetSystemInfo gets system information

func GetVulkanGPU

func GetVulkanGPU() (string, error)

GetVulkanGPU gets Vulkan GPU information

func HiresParamsInit

func HiresParamsInit(params *SDHiresParams)

HiresParamsInit initializes hi-res fix parameters with library defaults.

func ImgGenParamsInit

func ImgGenParamsInit(params *SDImgGenParams)

ImgGenParamsInit initializes image generation parameters

func ImgGenParamsToStr

func ImgGenParamsToStr(params *SDImgGenParams) string

ImgGenParamsToStr converts image generation parameters to string

func Load

func Load(libDir string) (err error)

Load resolves and dlopens the stable-diffusion shared library from libDir. An empty libDir falls back to the OS default search path. Load is idempotent and safe for concurrent use; it returns an error (and never panics) when the library is absent or incompatible, so that merely importing this package — or calling Load when the library is missing — keeps the caller healthy.

func LoraApplyModeName

func LoraApplyModeName(mode LoraApplyMode) string

LoraApplyModeName gets LoRA apply mode name

func PredictionName

func PredictionName(prediction Prediction) string

PredictionName gets prediction type name

func PreprocessCanny

func PreprocessCanny(image SDImage, highThreshold, lowThreshold, weak, strong float32, inverse bool) bool

PreprocessCanny preprocesses Canny edge detection. It always returns false on linux/amd64, see byValueImageArgsSupported.

func PreviewName

func PreviewName(preview Preview) string

PreviewName gets preview type name

func RNGTypeName

func RNGTypeName(rngType RngType) string

RNGTypeName gets RNG type name

func SDHiresUpscalerName

func SDHiresUpscalerName(upscaler SDHiresUpscaler) string

SDHiresUpscalerName gets the hi-res upscaler name.

func SDTypeName

func SDTypeName(typ SDType) string

SDTypeName gets SD type name

func SampleMethodName

func SampleMethodName(method SampleMethod) string

SampleMethodName gets sample method name

func SampleParamsInit

func SampleParamsInit(params *SDSampleParams)

SampleParamsInit initializes sample parameters

func SampleParamsToStr

func SampleParamsToStr(params *SDSampleParams) string

SampleParamsToStr converts sample parameters to string

func SaveFrames

func SaveFrames(frames []SDImage, outputDir string) error

SaveFrames saves all video frames as PNG files

func SaveImage

func SaveImage(img *SDImage, path string) error

SaveImage saves SDImage as PNG file

func SchedulerName

func SchedulerName(scheduler Scheduler) string

SchedulerName gets scheduler name

func SetLogCallback

func SetLogCallback(cb SDLogCallbackType, data interface{})

SetLogCallback sets log callback

func SetPreviewCallback

func SetPreviewCallback(cb func(step int, frameCount int, frames []SDImage, isNoisy bool, data interface{}), mode Preview, interval int, denoised bool, noisy bool, data interface{})

SetPreviewCallback sets preview callback

func SetProgressCallback

func SetProgressCallback(cb func(step int, steps int, time float32, data interface{}), data interface{})

SetProgressCallback sets progress callback.

Windows limitation (handled gracefully): the C progress callback takes a `float` argument, and Windows' syscall.NewCallback — which purego uses to turn a Go func into a C callback there — supports neither float arguments nor float returns. Registering a progress callback on Windows would panic ("float arguments not supported"). Rather than leave that as a latent crash, SetProgressCallback is a no-op for a non-nil cb on Windows: progress reporting is simply unavailable there. Clearing (cb == nil) still works on every platform. The log and preview callbacks have no float in their signatures and work everywhere.

func Version

func Version() string

Version gets version information

func VidGenParamsInit

func VidGenParamsInit(params *SDVidGenParams)

VidGenParamsInit initializes video generation parameters

Types

type GpuDevice

type GpuDevice struct {
	Name       string        // "CUDA0", "Metal", "Vulkan0", "CPU", ...
	Type       GpuDeviceType // CPU / GPU / IGPU (see constants)
	FreeBytes  uint64        // live free memory (real VRAM on CUDA; working-set on Metal)
	TotalBytes uint64        // total memory
}

GpuDevice is one ggml backend device reported by the statically-linked ggml inside libstable-diffusion, with its live free/total memory.

func GpuDevices

func GpuDevices() (devs []GpuDevice, ok bool)

GpuDevices enumerates the ggml backend devices and their live free/total memory. ok is false when the library isn't loaded, or the running libstable-diffusion predates the sd_backend_dev_* wrappers (v0.3.0+). The enumeration is panic-safe: a misbehaving FFI call yields (nil, false) rather than crashing the caller, mirroring Load's contract.

type GpuDeviceType

type GpuDeviceType int

GpuDeviceType classifies a ggml backend device (ggml_backend_dev_type).

const (
	GpuDeviceCPU  GpuDeviceType = 0 // GGML_BACKEND_DEVICE_TYPE_CPU
	GpuDeviceGPU  GpuDeviceType = 1 // GGML_BACKEND_DEVICE_TYPE_GPU  — dedicated VRAM
	GpuDeviceIGPU GpuDeviceType = 2 // GGML_BACKEND_DEVICE_TYPE_IGPU — shares host RAM
)

type LoraApplyMode

type LoraApplyMode int32
const (
	LoraApplyAuto LoraApplyMode = iota
	LoraApplyImmediately
	LoraApplyAtRuntime
	LoraApplyModeCount
)

func StrToLoraApplyMode

func StrToLoraApplyMode(str string) LoraApplyMode

StrToLoraApplyMode converts string to LoRA apply mode

type Prediction

type Prediction int32
const (
	EPSPred Prediction = iota
	VPred
	EDMVPred
	FlowPred
	FluxFlowPred
	// SefiFlowPred occupies the enum slot that FLUX2_FLOW_PRED held before the
	// master-802 resync: upstream replaced FLUX2_FLOW_PRED with SEFI_FLOW_PRED
	// (same integer value, 5) and appended MINIT2I_FLOW_PRED.
	SefiFlowPred
	Minit2iFlowPred
	SenseNovaU1FlowPred
	Flux3FlowPred
	H3AVFlowPred
	MingImageFlowPred
	PredictionCount
)

func StrToPrediction

func StrToPrediction(str string) Prediction

StrToPrediction converts string to prediction type

type Preview

type Preview int32
const (
	PreviewNone Preview = iota
	PreviewProj
	PreviewTAE
	PreviewVAE
	PreviewCount
)

func StrToPreview

func StrToPreview(str string) Preview

StrToPreview converts string to preview type

type RngType

type RngType int32
const (
	DefaultRNG RngType = iota
	CUDARNG
	CPURNG
	RNGTypeCount
)

func StrToRNGType

func StrToRNGType(str string) RngType

StrToRNGType converts string to RNG type

type SDAudio

type SDAudio struct {
	SampleRate  uint32
	Channels    uint32
	SampleCount uint64
	Data        *float32
}

SDAudio mirrors sd_audio_t. It is produced by audio-capable video models (e.g. LTX2) and accepted as a reference by generate_video.

type SDCacheMode

type SDCacheMode int32
const (
	SDCacheDisabled SDCacheMode = iota
	SDCacheEasycache
	SDCacheUcache
	SDCacheDbcache
	SDCacheTaylorseer
	SDCacheCacheDit
	SDCacheSpectrum
)

type SDCacheParams

type SDCacheParams struct {
	Mode                     SDCacheMode
	ReuseThreshold           float32
	StartPercent             float32
	EndPercent               float32
	ErrorDecayRate           float32
	UseRelativeThreshold     bool
	ResetErrorOnCompute      bool
	FnComputeBlocks          int32
	BnComputeBlocks          int32
	ResidualDiffThreshold    float32
	MaxWarmupSteps           int32
	MaxCachedSteps           int32
	MaxContinuousCachedSteps int32
	TaylorseerNDerivatives   int32
	TaylorseerSkipInterval   int32
	ScmMask                  *uint8
	ScmPolicyDynamic         bool
	SpectrumW                float32
	SpectrumM                int32
	SpectrumLam              float32
	SpectrumWindowSize       int32
	SpectrumFlexWindow       float32
	SpectrumWarmupSteps      int32
	SpectrumStopPercent      float32
}

type SDCancelMode

type SDCancelMode int32

SDCancelMode mirrors enum sd_cancel_mode_t (added upstream in the master-802 resync) and selects how sd_cancel_generation interrupts an in-flight generation.

const (
	// CancelAll stops the current generation as soon as possible.
	CancelAll SDCancelMode = iota
	// CancelNewLatents finishes the current image sample, then skips
	// additional batch latents and returns the completed images.
	CancelNewLatents
	// CancelReset clears a pending cancellation request.
	CancelReset
)

type SDContext

type SDContext struct {
	// contains filtered or unexported fields
}

Define context types

func NewContext

func NewContext(params *SDContextParams) *SDContext

NewContext creates a new context

func (*SDContext) CancelGeneration

func (ctx *SDContext) CancelGeneration(mode SDCancelMode)

CancelGeneration requests cancellation of the in-flight generation on this context (or clears a pending request, with CancelReset). It is safe to call from another goroutine while GenerateImage/GenerateVideo is running — that is its purpose.

func (*SDContext) Free

func (ctx *SDContext) Free()

FreeContext frees context

func (*SDContext) GenerateImage

func (ctx *SDContext) GenerateImage(params *SDImgGenParams) *SDImageGenerationResult

GenerateImage generates images. On success the caller owns the returned result and must call its Free method once done reading it; on failure, or when the library produced no images, it returns nil. Results do not depend on the context, so they may outlive it.

func (*SDContext) GenerateVideo

func (ctx *SDContext) GenerateVideo(params *SDVidGenParams) *SDVideoGenerationResult

GenerateVideo generates a video. On success the caller owns the returned result and must call its Free method once done reading it; on failure, or when the library produced no frames, it returns nil.

func (*SDContext) GetDefaultSampleMethod

func (ctx *SDContext) GetDefaultSampleMethod() SampleMethod

GetDefaultSampleMethod gets default sample method

func (*SDContext) GetDefaultScheduler

func (ctx *SDContext) GetDefaultScheduler(sampleMethod SampleMethod) Scheduler

GetDefaultScheduler gets default scheduler

func (*SDContext) ModelVersionName added in v0.4.0

func (ctx *SDContext) ModelVersionName() string

ModelVersionName returns the name of the loaded model's version, or "Unknown" when the context holds no model.

func (*SDContext) SupportsImageGeneration

func (ctx *SDContext) SupportsImageGeneration() bool

SupportsImageGeneration reports whether the loaded model can generate images.

func (*SDContext) SupportsVideoGeneration

func (ctx *SDContext) SupportsVideoGeneration() bool

SupportsVideoGeneration reports whether the loaded model can generate video.

type SDContextParams

type SDContextParams struct {
	ModelPath                   *uint8
	ClipLPath                   *uint8
	ClipGPath                   *uint8
	ClipVisionPath              *uint8
	T5XXLPath                   *uint8
	LLMPath                     *uint8
	LLMVisionPath               *uint8
	DiffusionModelPath          *uint8
	HighNoiseDiffusionModelPath *uint8
	UncondDiffusionModelPath    *uint8
	EmbeddingsConnectorsPath    *uint8
	VAEPath                     *uint8
	AudioVAEPath                *uint8
	AudioEncoderPath            *uint8
	TAESDPath                   *uint8
	ControlNetPath              *uint8
	IPAdapterPath               *uint8
	MotionModulePath            *uint8
	Embeddings                  *SDEmbedding
	EmbeddingCount              uint32
	PhotoMakerPath              *uint8
	PulidWeightsPath            *uint8
	TensorTypeRules             *uint8
	NThreads                    int32
	WType                       SDType
	RNGType                     RngType
	SamplerRNGType              RngType
	Prediction                  Prediction
	LoraApplyMode               LoraApplyMode
	EnableMmap                  bool
	FlashAttn                   bool
	DiffusionFlashAttn          bool
	TAEPreviewOnly              bool
	DiffusionConvDirect         bool
	VAEConvDirect               bool
	ForceSDXLVAConvScale        bool
	VAEFormat                   SDVAEFormat
	MaxVRAM                     *uint8
	DisablePrefetch             bool // disable asynchronous next-segment weight prefetch
	EagerLoad                   bool
	Backend                     *uint8
	ParamsBackend               *uint8
	SplitMode                   *uint8
	AutoFit                     bool
	RPCServers                  *uint8
	ModelArgs                   *uint8
	DisableSegmentedCompute     bool    // force monolithic graph execution
	BatchedCFG                  bool    // run the CFG branches in one batched forward when supported
	LinearScale                 float32 // override linear input scaling; 0 keeps the model default
	AttnScale                   float32 // override flash-attention K/V scaling; 0 keeps the model default
	Tokenizer                   *uint8  // tokenizer.json path or main=FILE,clip-l=FILE,clip-g=FILE assignments; required for PiD and Lens
	SageAttn                    bool
	ConditioningCacheSize       int32  // cached conditioning entries per context; 0 disables caching
	FlashAttnMode               *uint8 // on/off/auto or module assignments; nil or empty honours the legacy flags
	ConvDirectMode              *uint8 // on/off/auto or diffusion/vae/controlnet assignments; nil or empty honours the legacy flags
}

SDContextParams mirrors sd_ctx_params_t at upstream master-1031-c6dfa9d. Field order, types and implicit padding MUST match the C struct exactly — this layout is what crosses the FFI boundary, and TestStructLayoutMatchesHeader pins it. Notable drift from the previous pin (master-802-e92e86f):

  • added: AudioEncoderPath (after AudioVAEPath); DisableSegmentedCompute, BatchedCFG, LinearScale, AttnScale, Tokenizer, SageAttn, ConditioningCacheSize, FlashAttnMode, ConvDirectMode (after ModelArgs)
  • replaced: StreamLayers became DisablePrefetch in the same slot, with the opposite sense. Segmented streaming is automatic now and prefetch is on unless disabled, so there is nothing left to opt into.
  • library defaults changed: AutoFit is true (was false), BatchedCFG is true and ConditioningCacheSize is 4, so set them after ContextParamsInit, not from a zero value.

type SDEmbedding

type SDEmbedding struct {
	Name *uint8
	Path *uint8
}

type SDGuidanceParams

type SDGuidanceParams struct {
	TxtCfg            float32
	ImgCfg            float32
	DistilledGuidance float32
	SLG               SDSLGParams
}

type SDHiresParams

type SDHiresParams struct {
	Enabled           bool
	Upscaler          SDHiresUpscaler
	ModelPath         *uint8
	Scale             float32
	TargetWidth       int32
	TargetHeight      int32
	Steps             int32
	DenoisingStrength float32
	UpscaleTileSize   int32
	CustomSigmas      *float32
	CustomSigmasCount int32
}

type SDHiresUpscaler

type SDHiresUpscaler int32
const (
	HiresUpscalerNone SDHiresUpscaler = iota
	HiresUpscalerLatent
	HiresUpscalerLatentNearest
	HiresUpscalerLatentNearestExact
	HiresUpscalerLatentAntialiased
	HiresUpscalerLatentBicubic
	HiresUpscalerLatentBicubicAntialiased
	HiresUpscalerLanczos
	HiresUpscalerNearest
	HiresUpscalerModel
	HiresUpscalerCount
)

func StrToSDHiresUpscaler

func StrToSDHiresUpscaler(str string) SDHiresUpscaler

StrToSDHiresUpscaler converts a string to a hi-res upscaler.

type SDImage

type SDImage struct {
	Width   uint32
	Height  uint32
	Channel uint32
	Data    *uint8
}

func GenerateImageFromPath

func GenerateImageFromPath(imagePath string) SDImage

GenerateImageFromPath generates SDImage from path

func GenerateImagesFromPaths

func GenerateImagesFromPaths(path []string) *SDImage

func LoadImage

func LoadImage(path string) (SDImage, error)

LoadImage loads image from file and converts to SDImage format

type SDImageGenerationResult added in v0.4.0

type SDImageGenerationResult struct {
	// contains filtered or unexported fields
}

SDImageGenerationResult owns the native result of GenerateImage or Upscale: the pixels and generation info of every image. They stay in native memory until Free, independently of the context that produced them.

All methods are safe on a nil result and after Free. A result must not be used from several goroutines at once.

func (*SDImageGenerationResult) Count added in v0.4.0

func (r *SDImageGenerationResult) Count() int

Count returns the number of images in the result.

func (*SDImageGenerationResult) Free added in v0.4.0

func (r *SDImageGenerationResult) Free()

Free releases the result and everything it owns, including images obtained from Image. It is safe to call more than once.

func (*SDImageGenerationResult) GenerationInfo added in v0.4.0

func (r *SDImageGenerationResult) GenerationInfo(i int) string

GenerationInfo returns a copy of the i-th image's JSON metadata (schema sdcpp.generation/v1), or "" when i is out of range.

func (*SDImageGenerationResult) Image added in v0.4.0

func (r *SDImageGenerationResult) Image(i int) *SDImage

Image returns the i-th image, or nil when i is out of range or the slot has no pixels. The image points into native memory and is valid until Free.

type SDImagePreprocessParams added in v0.4.0

type SDImagePreprocessParams struct {
	Rules *uint8
}

SDImagePreprocessParams mirrors sd_image_preprocess_params_t. Rules is a list of semicolon-separated target=...,key=value rules; nil preserves the defaults.

type SDImageResult added in v0.4.0

type SDImageResult struct {
	Image          SDImage
	GenerationInfo *uint8
}

SDImageResult mirrors sd_image_result_t, one item of a generation result. GenerationInfo is owned UTF-8 JSON using the sdcpp.generation/v1 schema.

type SDImgGenParams

type SDImgGenParams struct {
	Loras             *SDLora
	LoraCount         uint32
	Prompt            *uint8
	NegativePrompt    *uint8
	ClipSkip          int32
	InitImage         SDImage
	RefImages         *SDImage
	RefImagesCount    int32
	RefImageArgs      *uint8
	MaskImage         SDImage
	Width             int32
	Height            int32
	SampleParams      SDSampleParams
	Strength          float32
	Seed              int64
	BatchCount        int32
	ControlImage      SDImage
	ControlStrength   float32
	IPAdapterImage    SDImage
	IPAdapterStrength float32
	PMParams          SDPMParams
	PulidParams       SDPulidParams
	VAETilingParams   SDTilingParams
	Cache             SDCacheParams
	Hires             SDHiresParams
	QwenImageLayers   int32
	CircularX         bool
	CircularY         bool
	ImagePreprocess   SDImagePreprocessParams
}

SDImgGenParams mirrors sd_img_gen_params_t at upstream master-1031-c6dfa9d. Drift from the previous pin: ImagePreprocess was appended.

type SDLogCallback

type SDLogCallback func(level SDLogLevel, text *uint8, data unsafe.Pointer) uintptr

Define callback function types.

These mirror the C signatures, which are `void (*)(...)`. They are nonetheless declared to return uintptr because a Go func becomes a C callback through purego.NewCallback, and on Windows purego delegates to syscall.NewCallback -> runtime.compileCallback, which REQUIRES the callback return exactly one uintptr-sized result. A void Go callback panics there with "compileCallback: expected function with one uintptr-sized result" (the symptom seen during stable-diffusion image generation on Windows). The C caller declares these as void and simply ignores the returned register, so always returning 0 is safe on every platform. (This is the same shape used for ggml's log callback shim elsewhere in the ecosystem.)

type SDLogCallbackType

type SDLogCallbackType func(level SDLogLevelType, text string, data interface{})

type SDLogLevel

type SDLogLevel int32

SDLogLevel mirrors enum sd_log_level_t. Compare levels through these constants only: SD_LOG_VERBOSE took slot 1 at the master-1031 resync, which moved INFO/WARN/ERROR from 1/2/3 to 2/3/4.

const (
	SDLogDebug SDLogLevel = iota
	SDLogVerbose
	SDLogInfo
	SDLogWarn
	SDLogError
)

type SDLogLevelType

type SDLogLevelType = SDLogLevel

SDLogLevelType is the level handed to an SDLogCallbackType. It is SDLogLevel, so the SDLog* constants compare against it directly.

type SDLora

type SDLora struct {
	IsHighNoise bool
	Multiplier  float32
	Path        *uint8
}

type SDPMParams

type SDPMParams struct {
	IDImages      *SDImage
	IDImagesCount int32
	IDEmbedPath   *uint8
	StyleStrength float32
}

type SDPreviewCallback

type SDPreviewCallback func(step int32, frameCount int32, frames *SDImage, isNoisy bool, data unsafe.Pointer) uintptr

type SDPreviewInfo added in v0.4.0

type SDPreviewInfo struct {
	SamplePass int32
	TotalSteps int32
}

SDPreviewInfo mirrors sd_preview_info_t. SamplePass counts sampling passes from 1 since the last SetPreviewCallback; TotalSteps is the step count of that pass. Both are zero before sampling starts.

func GetPreviewInfo added in v0.4.0

func GetPreviewInfo() SDPreviewInfo

GetPreviewInfo reports the sampling pass the current preview belongs to. Call it from a preview callback; both fields are zero before sampling starts.

type SDProgressCallback

type SDProgressCallback func(step int32, steps int32, time float32, data unsafe.Pointer) uintptr

SDProgressCallback NOTE (Windows): this callback takes a float32 argument. purego's callback support on Windows is syscall.NewCallback, which supports neither float arguments nor float returns — so this callback cannot be wrapped on Windows. SetProgressCallback handles that gracefully (it skips registration on Windows rather than panicking), so progress reporting is simply unavailable there. The log and preview callbacks have no float in their signatures and work on every platform. Lifting this would require removing the float from the C-ABI signature.

type SDPulidParams

type SDPulidParams struct {
	IDEmbeddingPath *uint8
	IDWeight        float32
}

SDPulidParams mirrors sd_pulid_params_t (added upstream in the master-802 resync).

type SDRefVideo added in v0.4.0

type SDRefVideo struct {
	Frames     *SDImage
	FrameCount int32
	Fps        int32
	Audio      SDAudio
}

SDRefVideo mirrors sd_ref_video_t, a reference video for video generation.

type SDSLGParams

type SDSLGParams struct {
	Layers     *int32
	LayerCount uintptr
	LayerStart float32
	LayerEnd   float32
	Scale      float32
}

type SDSampleParams

type SDSampleParams struct {
	Guidance          SDGuidanceParams
	Scheduler         Scheduler
	SampleMethod      SampleMethod
	SampleSteps       int32
	Eta               float32
	ShiftedTimestep   int32
	CustomSigmas      *float32
	CustomSigmasCount int32
	FlowShift         float32
	ExtraSampleArgs   *uint8
}

type SDTilingParams

type SDTilingParams struct {
	Enabled        bool
	TemporalTiling bool
	// TileSizeW and TileSizeH are the spatial tile dimensions in image pixels,
	// for both encode and decode; 0 uses 256.
	TileSizeW     int32
	TileSizeH     int32
	TargetOverlap float32
	// RelSizeW and RelSizeH override the tile size when positive: <= 1 is a
	// fraction of the dimension, > 1 a target tile count.
	RelSizeW        float32
	RelSizeH        float32
	ExtraTilingArgs *uint8
}

SDTilingParams mirrors sd_tiling_params_t. The master-1031 resync renamed the X/Y fields to W/H without changing the layout.

type SDType

type SDType int32

func StrToSDType

func StrToSDType(str string) SDType

StrToSDType converts string to SD type

type SDVAEFormat

type SDVAEFormat int32
const (
	VAEFormatAuto  SDVAEFormat = -1
	FluxVAEFormat  SDVAEFormat = 0
	SD3VAEFormat   SDVAEFormat = 1
	Flux2VAEFormat SDVAEFormat = 2
	WanVAEFormat   SDVAEFormat = 3
	VAEFormatCount SDVAEFormat = 4
)

type SDVidGenParams

type SDVidGenParams struct {
	Loras                 *SDLora
	LoraCount             uint32
	Prompt                *uint8
	NegativePrompt        *uint8
	ClipSkip              int32
	InitImage             SDImage
	EndImage              SDImage
	RefImages             *SDImage
	RefImagesCount        int32
	RefVideos             *SDRefVideo
	RefVideosCount        int32
	RefAudios             *SDAudio
	RefAudiosCount        int32
	ControlFrames         *SDImage
	ControlFramesSize     int32
	Width                 int32
	Height                int32
	SampleParams          SDSampleParams
	HighNoiseSampleParams SDSampleParams
	MOEBoundary           float32
	Strength              float32
	Seed                  int64
	VideoFrames           int32
	Fps                   int32
	VaceStrength          float32
	VAETilingParams       SDTilingParams
	Cache                 SDCacheParams
	Hires                 SDHiresParams
	CircularX             bool
	CircularY             bool
	ImagePreprocess       SDImagePreprocessParams
	RefImageArgs          *uint8
}

SDVidGenParams mirrors sd_vid_gen_params_t at upstream master-1031-c6dfa9d. Drift from the previous pin: RefImages, RefImagesCount, RefVideos, RefVideosCount, RefAudios and RefAudiosCount were inserted before ControlFrames, and ImagePreprocess and RefImageArgs were appended.

type SDVideoGenerationResult added in v0.4.0

type SDVideoGenerationResult struct {
	// contains filtered or unexported fields
}

SDVideoGenerationResult owns the native result of GenerateVideo: frames, audio and generation info. The ownership rules of SDImageGenerationResult apply.

func (*SDVideoGenerationResult) Audio added in v0.4.0

func (r *SDVideoGenerationResult) Audio() *SDAudio

Audio returns the generated audio track, or nil when the model produced none. It is valid until Free and must not be passed to FreeAudio.

func (*SDVideoGenerationResult) Fps added in v0.4.0

func (r *SDVideoGenerationResult) Fps() int

Fps returns the frame rate of the generated video, or 0 after Free.

func (*SDVideoGenerationResult) Frame added in v0.4.0

func (r *SDVideoGenerationResult) Frame(i int) *SDImage

Frame returns the i-th frame, or nil when i is out of range or the slot has no pixels. The frame points into native memory and is valid until Free.

func (*SDVideoGenerationResult) FrameCount added in v0.4.0

func (r *SDVideoGenerationResult) FrameCount() int

FrameCount returns the number of frames in the result.

func (*SDVideoGenerationResult) Frames added in v0.4.0

func (r *SDVideoGenerationResult) Frames() []SDImage

Frames returns the frames as a slice. The slice itself is a Go copy, but each element's pixels stay in native memory and are valid until Free.

func (*SDVideoGenerationResult) Free added in v0.4.0

func (r *SDVideoGenerationResult) Free()

Free releases the result and everything it owns, including frames and audio obtained from it. It is safe to call more than once.

func (*SDVideoGenerationResult) GenerationInfo added in v0.4.0

func (r *SDVideoGenerationResult) GenerationInfo() string

GenerationInfo returns a copy of the video's JSON metadata (schema sdcpp.generation/v1).

type SampleMethod

type SampleMethod int32
const (
	EulerSampleMethod SampleMethod = iota
	EulerASampleMethod
	HeunSampleMethod
	DPM2SampleMethod
	DPMPP2SASampleMethod
	DPMPP2MSampleMethod
	DPMPP2Mv2SampleMethod
	IPNDMSampleMethod
	IPNDMSampleMethodV
	LCMSampleMethod
	DDIMTrailingSampleMethod
	TCDSampleMethod
	ResMultistepSampleMethod
	Res2SSampleMethod
	ERSDESampleMethod
	EulerCFGPPSampleMethod
	EulerACFGPPSampleMethod
	EulerGESampleMethod
	DPMPP2MSDESampleMethod
	DPMPP2MSDEBTSampleMethod
	LMSSampleMethod
	SampleMethodCount
)

func StrToSampleMethod

func StrToSampleMethod(str string) SampleMethod

StrToSampleMethod converts string to sample method

type Scheduler

type Scheduler int32
const (
	DiscreteScheduler Scheduler = iota
	KarrasScheduler
	ExponentialScheduler
	AYSScheduler
	GITScheduler
	SGMUniformScheduler
	SimpleScheduler
	SmoothstepScheduler
	KLOptimalScheduler
	LCMScheduler
	BongTangentScheduler
	LTX2Scheduler
	LogitNormalScheduler
	Flux2Scheduler
	FluxScheduler
	BetaScheduler
	LLaDAImageScheduler
	SchedulerCount
)

func StrToScheduler

func StrToScheduler(str string) Scheduler

StrToScheduler converts string to scheduler

type UpscalerContext

type UpscalerContext struct {
	// contains filtered or unexported fields
}

func NewUpscalerContext

func NewUpscalerContext(esrganPath string, direct bool, nThreads int, tileSize int, backend string, paramsBackend string) *UpscalerContext

NewUpscalerContext creates a new upscaler context. backend and paramsBackend select the runtime backend; empty strings fall back to the library default. (Upstream removed the offload_params_to_cpu argument in the master-802 resync; CPU offload is now expressed as a params-backend assignment spec, e.g. paramsBackend = "*=cpu".)

func (*UpscalerContext) Free

func (ctx *UpscalerContext) Free()

FreeUpscalerContext frees upscaler context

func (*UpscalerContext) GetUpscaleFactor

func (ctx *UpscalerContext) GetUpscaleFactor() int

GetUpscaleFactor gets upscale factor

func (*UpscalerContext) Upscale

func (ctx *UpscalerContext) Upscale(inputImage SDImage, upscaleFactor uint32) *SDImageGenerationResult

Upscale upscales an image. On success the caller owns the returned result and must call its Free method once done reading it; on failure it returns nil. It always returns nil on linux/amd64, see byValueImageArgsSupported.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL