gpu

package
v0.3.12 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 38 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

Overview

Package gpu renders on the GPU through Vulkan, into memory shared with the compositor (or a display) as dmabufs: what a frame draws is handed over by file descriptor, with no copy. lys-ui's windows, lys-shell's surfaces and lys-wm's output all draw through it.

Vulkan loads at runtime (third_party/vk, pure Go, no cgo). Open fails with ErrNoVulkan or ErrNoDevice where there is no loader or no device that draws; callers then draw on the CPU (package render). A device that cannot export dmabufs still renders offscreen (NewOffscreen); its NewTarget fails with ErrNoDmabuf.

A Device and everything made from it belong to one goroutine.

Index

Constants

View Source
const ColorUniforms = 9

ColorUniforms is how many vec4s ColorGLSL reads through CP.

View Source
const LossLimit = 3

LossLimit is how many device losses within LossWindow a consumer recovers from by opening a new device; one more within the window is a GPU that cannot keep a device, and the consumer stops recovering.

View Source
const LossWindow = time.Minute

LossWindow is the span over which Losses counts losses against LossLimit.

Variables

View Source
var ColorGLSL string

ColorGLSL is the GLSL of ColorTransform.Apply, colorApply, valid as GLSL 4.50 and as GLSL ES 1.00, for renderers outside this package to share. CP must name its nine vec4s, ColorTransform.Uniforms.

View Source
var CutGLSL string

CutGLSL is the GLSL of CutUniforms.Keeps at CutUniforms.UV, cutCoverage, valid as GLSL 4.50 and as GLSL ES 1.00 with SAMPLE naming the sampling function and CUT_SAMPLER the sampler type, for renderers outside this package to share.

View Source
var ErrBusy = errors.New("gpu: frames in flight are at their bound")

ErrBusy reports a frame Render refused, having done nothing, because the GPU is too far behind for one more: try again once the frames ahead of it finish, as FrameDone or a compositor's release will show.

View Source
var ErrDeviceClosed = errors.New("gpu: the device is closed")

ErrDeviceClosed reports a target prepared after its device's Close began.

View Source
var ErrDeviceLost = errors.New("gpu: the Vulkan device is lost")

ErrDeviceLost reports a Vulkan device that was lost (VK_ERROR_DEVICE_LOST): a GPU reset or a driver fault. Nothing further submitted to it runs: a consumer closes it and opens a new one, or ends so that a supervisor can.

View Source
var ErrNoDevice = errors.New("gpu: no Vulkan device draws")

ErrNoDevice reports that no Vulkan device has a graphics queue.

View Source
var ErrNoDmabuf = errors.New("gpu: the device does not export dmabufs")

ErrNoDmabuf reports a device that cannot render into dmabufs.

View Source
var ErrNoFrameTime = errors.New("gpu: the device has no calibrated timestamps")

ErrNoFrameTime reports a device whose GPU timestamps do not map onto CLOCK_MONOTONIC (no calibrated timestamps).

View Source
var ErrNoSyncFile = errors.New("gpu: the device has no sync_file semaphores")

ErrNoSyncFile reports a device that exports or imports no sync_file.

View Source
var ErrNoVideoEncoder = errors.New("gpu: the device has no video encoder")

ErrNoVideoEncoder reports a device that does not encode the codec asked for: neither on a Vulkan video encode queue (lavapipe, older radv, anv on Xe2) nor through a VA-API driver.

View Source
var ErrNoVulkan = errors.New("gpu: no Vulkan loader")

ErrNoVulkan reports that the Vulkan loader (libvulkan) is missing.

View Source
var GlassGLSL string

GlassGLSL is the GLSL of a Glass draw, glassBackdrop and glassAdjust, valid as GLSL 4.50 and as GLSL ES 1.00 after MaskGLSL and with SAMPLE naming the sampling function, for renderers outside this package to share.

View Source
var MaskGLSL string

MaskGLSL is the GLSL of Mask.Coverage, maskCoverage, of GradientAt's texture coordinate, gradientUV, and, when SAMPLE names the sampling function (texture or texture2D), of KawaseAt's kawaseDown and kawaseUp, valid as GLSL 4.50 and as GLSL ES 1.00, for renderers outside this package to share.

Functions

func Bilinear

func Bilinear(pix []byte, stride, w, h int, u, v float32) [4]float32

Bilinear samples pix, w x h premultiplied BGRA pixels stride bytes a row, at texture coordinate (u, v) as a linear sampler clamped to its edges does, returning B, G, R, A in 0..255.

func GooCoverage

func GooCoverage(g Goo, px, py float32) float32

GooCoverage is the fraction of the pixel whose centre is (px, py) that FillGoo covers for g, as the shader computes it.

func GradientAt

func GradientAt(from, to [2]float32, stops []color.RGBA, px, py float32) color.RGBA

GradientAt is the premultiplied colour FillGradient gives the pixel whose centre is (px, py), for stops spread from from to to, as the shader computes it.

func KawaseAt

func KawaseAt(sample func(u, v float32) [4]float32, up bool, u, v, hx, hy float32) [4]float32

KawaseAt is Kawase's colour at texture coordinate (u, v) of a texture sample samples, with taps h source texels apart in texture coordinates.

Types

type AlphaCut

type AlphaCut struct {
	Src       FRect
	Dst       image.Rectangle
	Transform Transform
	Threshold float32
}

AlphaCut keeps a draw only where a texture's alpha is above Threshold: the texture's Src region laid over Dst, in target pixels, through Transform, as DrawTexture lays it. Outside Dst nothing is kept. A texture sampling opaque has alpha 1 everywhere.

func (AlphaCut) Check

func (c AlphaCut) Check(size image.Point) error

Check reports a cut that does not fit a texture of size: an empty Dst, a Src outside the texture, no wl_output transform or a threshold outside [0, 1].

func (AlphaCut) Uniforms

func (c AlphaCut) Uniforms(size image.Point, opaque bool) CutUniforms

Uniforms packs c over a texture of size, opaque when it samples opaque.

type Buffer

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

Buffer is an image whose memory is a dmabuf this device allocates for others to write and read, a screencast frame a compositor copies into, and never draws into itself: it asks only for transfer and sampling, so layouts a device cannot render to (NVIDIA's linear) are on offer (ExportModifiers).

func (*Buffer) Close

func (b *Buffer) Close()

Close releases the buffer and its fd; closing it again, or after its device, does nothing.

func (*Buffer) Dmabuf

func (b *Buffer) Dmabuf() dmabuf.Buffer

Dmabuf describes the buffer's memory. Its fd is the buffer's, open until Close.

func (*Buffer) ReadPixels

func (b *Buffer) ReadPixels() (*image.RGBA, error)

ReadPixels copies what the buffer holds (the frame a compositor last copied into it) back into memory as RGBA, opaque when its format has no alpha: screenshots and tests.

type Carry

type Carry struct {
	From   *Target
	Rects  []image.Rectangle
	Offset image.Point
}

Carry is what a consumer rotating through targets copies into the one it reuses before drawing: Rects of From, which was shown since, the rest of the target already being up to date. From is read where it stands, since it may still be on screen. A rect r takes From's pixels at r moved by Offset, as scrolling does, and the part of r without a source stays as it was. From may be the target itself when Offset is not zero: the pixels then go through a scratch surface, as one image's overlapping copies are undefined.

type ChromaSiting

type ChromaSiting struct {
	X, Y Siting
}

ChromaSiting is where a subsampled chroma sample lies along each axis, relative to the luma samples it covers.

type Codec

type Codec int

Codec is a video coding format the encoder writes.

const (
	H264 Codec = iota
	H265
)

The codecs.

func (Codec) String

func (c Codec) String() string

type ColorFunc

type ColorFunc struct {
	Kind                ColorKind
	G, A, B, C, D, E, F float32
}

ColorFunc is one transfer function. A ColorCurve is ICC's parametric form, mirrored through the origin: (A*x + B)^G + E where x >= D, and C*x + F below it.

type ColorKind

type ColorKind uint8

ColorKind is a family of transfer functions.

const (
	ColorLinear ColorKind = iota
	ColorCurve
	ColorPQ
	ColorHLG
)

The families. ColorHLG only decodes: nothing is encoded to HLG here.

type ColorTransform

type ColorTransform struct {
	Decode   ColorFunc
	Luma     [3]float32
	HLGGamma float32
	Matrix   [9]float32
	Knee     float32
	Compress float32
	Scale    float32
	Encode   ColorFunc
}

ColorTransform takes a premultiplied colour from one encoding to another: un-premultiply, Decode (then, for HLG, the OOTF: scene light scaled by its Luma luminance to the power HLGGamma - 1), Matrix, compress the largest channel above Knee when Compress is positive, multiply by Scale, Encode, and premultiply again. It is a value, so equal transforms compare equal.

func (*ColorTransform) Apply

func (t *ColorTransform) Apply(c [4]float32) [4]float32

Apply is colorApply in Go: c, premultiplied, through the transform. What a client's float buffer holds beyond the finite, NaN and infinities, comes out as nothing, so it cannot stick in a target that blends over it for good.

func (*ColorTransform) Uniforms

func (t *ColorTransform) Uniforms() [ColorUniforms][4]float32

Uniforms packs t for ColorGLSL.

type CutUniforms

type CutUniforms [2][4]float32

CutUniforms is an AlphaCut over one texture as CutGLSL reads it: the texture coordinate's change per target pixel along x and y, then its value at the target's origin, the threshold and 1 for an opaque texture.

func (CutUniforms) Keeps

func (u CutUniforms) Keeps(a float32) bool

Keeps reports whether a texel of alpha a keeps what is drawn over it.

func (CutUniforms) UV

func (u CutUniforms) UV(x, y float32) (s, t float32, on bool)

UV is the normalised texture coordinate under the target point (x, y), and whether it lies on the texture.

type Device

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

Device is a Vulkan device rendering into dmabufs.

func Open

func Open() (*Device, error)

Open picks the first Vulkan device with a graphics queue that exports dmabufs, else the first with a graphics queue.

func OpenNode

func OpenNode(dev uint64) (*Device, error)

OpenNode opens the Vulkan device behind the DRM node dev, its device number (st_rdev, as of /dev/dri/renderD128 or /dev/dri/card0): the device a dmabuf consumer negotiated, which must export dmabufs. linux-dmabuf's main device may name either node of a GPU.

func (*Device) Begin

func (d *Device) Begin(t *Target, damage []image.Rectangle) (*Pass, error)

Begin starts a pass drawing into t, where only damage, clipped to t, changes. One pass at a time is open on a device.

func (*Device) BlockingWaits

func (d *Device) BlockingWaits() uint64

BlockingWaits counts the times this device's goroutine has waited for the GPU to finish: a frame that adds to it could have missed its deadline for the work ahead of it.

func (*Device) Close

func (d *Device) Close()

Close releases the device and the targets still open on it: a target closed after is already closed. Closing it again does nothing. The process's Vulkan instance stays for the next Open.

func (*Device) Codecs

func (d *Device) Codecs() []Codec

Codecs are the codecs the device encodes, on its Vulkan video queue or its VA-API driver.

func (*Device) CopyToLinear

func (d *Device) CopyToLinear(dst *Linear, src *Target, rects []image.Rectangle) error

CopyToLinear copies rects of src, clipped to it, into the same rects of dst, a buffer of src's size and format, with the copy engine: no render pass touches dst. Like a Pass it is submitted without waiting; SyncFile signals when it is done. dst outside rects keeps what it held.

func (*Device) ExportModifiers

func (d *Device) ExportModifiers(format fourcc.Format) ([]fourcc.Modifier, error)

ExportModifiers are the single-plane DRM modifiers the device allocates format in for a Buffer: what to intersect with the ones a consumer imports before NewBuffer.

func (*Device) Exports

func (d *Device) Exports() bool

Exports reports whether the device renders into dmabufs, for NewTarget.

func (*Device) Finish

func (d *Device) Finish() error

Finish waits until everything submitted to the device has finished: a CPU read of a target's dmabuf, a test.

func (*Device) Flush

func (d *Device) Flush() error

Flush submits the passes ended and the uploads made since the last submission, without waiting for them: what a consumer that waits on no SyncFile calls before handing a target over. SyncFile, Finish and a CPU read submit them too.

func (*Device) Forget

func (d *Device) Forget(id render.ImageID)

Forget drops what the device keeps for the raster of identity id, its textures and its mask atlas slot, once the frame the device is drawing, or else its next one, is done: an owner that frees the raster (render.Retire) frees the GPU copy with it rather than leaving it to the maxImages bound or Trim, and a List recorded before the eviction still draws from the texture in that frame. A List still open after that frame that draws the raster uploads it again, from pixels Retire keeps until that List ends. It is safe from any goroutine. Zero, no identity, panics: a raster without one is kept by its pixels' address and is the garbage collector's to free.

func (*Device) FrameDone

func (d *Device) FrameDone() (time.Duration, bool, error)

FrameDone reports when the last ended Pass finished on the GPU, on CLOCK_MONOTONIC: what a compositor's latch budget samples. It reports false while that pass is still running, or before any pass. A pass not yet submitted is submitted, as Flush does.

func (*Device) FrameIncomplete

func (d *Device) FrameIncomplete() bool

FrameIncomplete reports that the last Render left out an image still on its way to the GPU: the caller keeps that frame's damage for its next one.

func (*Device) ImportFormats

func (d *Device) ImportFormats() []fourcc.Format

ImportFormats are the DRM formats ImportTexture may take: what to ask TextureModifiers about, which is empty for one the driver lacks.

func (*Device) ImportLinear

func (d *Device) ImportLinear(b dmabuf.Buffer) (*Linear, error)

ImportLinear imports b, a dmabuf in one of TextureFormats with the linear modifier and one plane, as a Linear that CopyToLinear writes. b's fd stays the caller's.

func (*Device) ImportTarget

func (d *Device) ImportTarget(b dmabuf.Buffer) (*Target, error)

ImportTarget imports b, a dmabuf in one of TextureFormats and a modifier of TargetModifiers (a scanout buffer GBM allocated), as a target a Pass draws into, its contents kept between passes. Like an exported target it is handed back to its consumer after each pass. Its Dmabuf has no planes: b's fds stay the caller's.

func (*Device) ImportTexture

func (d *Device) ImportTexture(b dmabuf.Buffer) (*Texture, error)

ImportTexture imports b, a client's dmabuf in one of ImportFormats (a YUV one as BT.601 limited range; ImportTextureYCbCr takes the buffer's hints), and a modifier of TextureModifiers, as a texture a Pass samples. Its producer writes it; Update refuses it. b's fds stay the caller's: the texture holds the memory itself until Close.

func (*Device) ImportTextureYCbCr

func (d *Device) ImportTextureYCbCr(b dmabuf.Buffer, c YCbCr) (*Texture, error)

ImportTextureYCbCr is ImportTexture sampling a YUV buffer through c; an RGB buffer ignores c.

func (*Device) Modifiers

func (d *Device) Modifiers(format fourcc.Format) ([]fourcc.Modifier, error)

Modifiers are the DRM modifiers the device renders format into as a single-plane color attachment: what to intersect with the ones a consumer imports before NewTarget.

func (*Device) Name

func (d *Device) Name() string

Name is the device's name, "NVIDIA GeForce RTX 3060 Ti" or "llvmpipe (LLVM 21.1.8, 256 bits)".

func (*Device) NewBuffer

func (d *Device) NewBuffer(width, height int, format fourcc.Format, offered []fourcc.Modifier) (*Buffer, error)

NewBuffer allocates a width x height Buffer in format (fourcc.ARGB8888 or XRGB8888) whose layout the driver picks among offered, the modifiers the consumer imports, that the device exports format in (ExportModifiers). None in common, as with only the implicit fourcc.Invalid on offer, is an error naming both lists.

func (*Device) NewEncoder

func (d *Device) NewEncoder(cfg EncoderConfig) (*Encoder, error)

NewEncoder makes an encoder for cfg on the device's Vulkan video queue when it encodes cfg.Codec, else on its VA-API driver: ErrNoVideoEncoder, with both backends' reasons, when neither does, and an error naming the limit when the encoder cannot code cfg's size.

func (*Device) NewFragmentShader

func (d *Device) NewFragmentShader(spv []byte) (*FragmentShader, error)

NewFragmentShader takes spv, whole SPIR-V words in the host's byte order. A driver's refusal is an error and leaves the device as it was; the module must still be valid SPIR-V, which nothing checks here.

func (*Device) NewOffscreen

func (d *Device) NewOffscreen(width, height int) (*Target, error)

NewOffscreen allocates a width x height target in device memory no other process imports: a frame rendered for its pixels (ReadPixels), a screenshot or a test.

func (*Device) NewOffscreenFloat

func (d *Device) NewOffscreenFloat(width, height int) (*Target, error)

NewOffscreenFloat is NewOffscreen in half floats: premultiplied linear light that keeps values above one and below zero, for a compositor's working space. A pass draws into it and samples it as any other, with the same premultiplied blending; its pixels are not read back. It starts transparent: a NaN in fresh memory would survive every blend over it.

func (*Device) NewReadback

func (d *Device) NewReadback(width, height int) (*Readback, error)

NewReadback allocates memory for copies of a width x height target.

func (*Device) NewTarget

func (d *Device) NewTarget(width, height int, format fourcc.Format, modifiers []fourcc.Modifier) (*Target, error)

NewTarget allocates a width x height image in format (one of TextureFormats; Render draws only into ARGB8888 and XRGB8888, a Pass into any) whose layout the driver picks among modifiers, the ones the consumer imports, that the device renders format in (Modifiers): linear when both take it. None in common, as with only the implicit fourcc.Invalid on offer, is an error naming both lists.

func (*Device) NewTexture

func (d *Device) NewTexture(format fourcc.Format, width, height int) (*Texture, error)

NewTexture allocates a width x height texture in format, one of TextureFormats; the X formats sample opaque. It holds transparent black until Update writes it.

func (*Device) OpaqueRuns

func (d *Device) OpaqueRuns() uint64

OpaqueRuns counts the runs of draws this device recorded with blending off: opaque fills, opaque textures at full alpha, unmasked, and Kawase levels.

func (*Device) Prepare

func (d *Device) Prepare(formats ...fourcc.Format) error

Prepare builds, on a worker, the pipelines drawing into targets of formats takes, including the ones a device builds only when first drawn, and from then on any pipeline a frame finds missing goes to the worker too: nothing compiles while a pass records. A pass that meets a pipeline not built yet skips that draw and reports Incomplete. Prepared reports when the worker has nothing left. Bad formats fail at once; a driver's refusal comes from a later Begin.

func (*Device) PrepareOffscreen

func (d *Device) PrepareOffscreen(width, height int) (*Target, error)

PrepareOffscreen is NewOffscreen from any goroutine, as PrepareTarget.

func (*Device) PrepareTarget

func (d *Device) PrepareTarget(width, height int, format fourcc.Format, modifiers []fourcc.Modifier) (*Target, error)

PrepareTarget is NewTarget from any goroutine, with the driver's allocation and the view and framebuffer a first draw would make done there. The target reaches the device's goroutine with no lock: use it there as any other. Close waits for the prepares running; one starting after it is ErrDeviceClosed.

func (*Device) Prepared

func (d *Device) Prepared() (bool, error)

Prepared reports whether the worker has built everything asked of it; the pipelines reach passes from the next Begin.

func (*Device) Render

func (d *Device) Render(l *render.List, t *Target, carry ...Carry) error

Render draws l onto t and hands t back to its consumer, without waiting for the GPU where the device can tell the consumer when it is done (publish). l is recorded at t's size; its layers keep their GPU surfaces on this device across frames. ErrBusy, before anything is done, means the GPU is too far behind for one more frame. carry is copied into t first, in the frame's own submission.

func (*Device) RenderExplicit

func (d *Device) RenderExplicit(l *render.List, t *Target, carry ...Carry) (int, error)

RenderExplicit is Render for a consumer that takes its fence explicitly, never waiting for the GPU: the sync_file it returns, the caller's to close, signals when the frame is done, for wp_linux_drm_syncobj_surface_v1's acquire point (drm.Device.ImportSyncFile then SetAcquirePoint). -1 means it is done already. ErrNoSyncFile reports a device with no sync_files.

func (*Device) RenderNode

func (d *Device) RenderNode() (string, bool)

RenderNode is the path of the device's DRM render node, as the driver names its major and minor (VK_EXT_physical_device_drm): what a caller opens to reach the same GPU, for timeline syncobjs. False for a device the driver names none for, lavapipe's.

func (*Device) Submissions

func (d *Device) Submissions() uint64

Submissions counts the queue submissions this device made: a frame of passes followed by SyncFile is one.

func (*Device) SyncFile

func (d *Device) SyncFile() (int, error)

SyncFile returns a sync_file, the caller's to close, that signals once everything submitted to the device so far has finished: a pass's out-fence for KMS or a linux-drm-syncobj release point. -1 with no error means it has all finished already: there is nothing to wait on, as for WaitSyncFile. It costs a submission only when nothing submitted can answer: the newest pass signals a semaphore once SyncFile has been asked for, and until the next submission every later call shares that one fence.

func (*Device) SyncFiles

func (d *Device) SyncFiles() bool

SyncFiles reports whether SyncFile and WaitSyncFile work here.

func (*Device) TargetModifiers

func (d *Device) TargetModifiers(format fourcc.Format) ([]fourcc.Modifier, error)

TargetModifiers are the DRM modifiers ImportTarget takes format in: what to allocate a scanout buffer the device renders into in.

func (*Device) TextureFormats

func (d *Device) TextureFormats() []fourcc.Format

TextureFormats are the formats NewTexture takes.

func (*Device) TextureModifiers

func (d *Device) TextureModifiers(format fourcc.Format) ([]fourcc.Modifier, error)

TextureModifiers are the DRM modifiers ImportTexture takes format in: what a compositor offers its clients through linux-dmabuf.

func (*Device) Trim

func (d *Device) Trim() error

Trim hands back what the device keeps only for speed: the CPU scratch canvases, freed off the Go heap and unmapped, the buffers of finished segments, and the image textures not drawn since the last Trim. A device that draws again allocates them anew. Call it when the device has been idle a while, between frames, on the device's goroutine.

func (*Device) WaitSyncFile

func (d *Device) WaitSyncFile(fd int) error

WaitSyncFile makes the device's next submission (the one carrying the passes ended since the last, an upload, a copy) wait for the fence in the sync_file fd before it runs: a client's acquire fence, or a DRM syncobj point exported as one. The device takes fd, closing it even on error; -1 is a fence already signalled, and one that has signalled costs the submission nothing.

type Encoder

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

Encoder encodes frames into H.264 or H.265 on the device's hardware encoder: its Vulkan video queue, else its VA-API driver. A frame's pixels come from a Buffer a compositor copied a screen into: a compute pass crops, turns, overlays and converts them to NV12, and the backend encodes that while the next frame converts. Like the Device, it belongs to one goroutine.

func (*Encoder) Backend

func (e *Encoder) Backend() EncoderBackend

Backend is the path the encoder encodes through, the Vulkan video queue or the VA-API driver, as NewEncoder chose it.

func (*Encoder) Close

func (e *Encoder) Close()

Close waits for the frames in flight, dropping their packets, and releases the encoder; closing it again does nothing.

func (*Encoder) Encode

func (e *Encoder) Encode(src *Buffer, pts time.Duration) ([]Packet, error)

Encode converts src's pixels (a Buffer the size the encoder was made for) and queues them for encoding, presented at pts; it returns the packets of the frames that finished meanwhile, oldest first. src is free to take the next frame when Encode returns.

func (*Encoder) Flush

func (e *Encoder) Flush() ([]Packet, error)

Flush waits for the frames in flight and returns their packets, oldest first.

func (*Encoder) ParameterSets

func (e *Encoder) ParameterSets() [][]byte

ParameterSets are the stream's parameter sets as NAL units without start codes: the SPS and the PPS for H.264, the VPS, SPS and PPS for H.265.

func (*Encoder) SetOverlay

func (e *Encoder) SetOverlay(img *image.RGBA, dst image.Rectangle) error

SetOverlay draws img over every following frame's pixels, scaled (linear filtering) to fill dst in frame coordinates, opaque, before the NV12 conversion; nil removes it. img is uploaded here, so the caller may reuse it once SetOverlay returns. dst is clipped to the frame; an empty dst, or one off the frame, is an error.

type EncoderBackend

type EncoderBackend int

EncoderBackend is the path an Encoder encodes through.

const (
	// VulkanVideo is the device's Vulkan video encode queue.
	VulkanVideo EncoderBackend = iota
	// VAAPI is the device's VA-API driver.
	VAAPI
)

The encoder backends.

func (EncoderBackend) String

func (b EncoderBackend) String() string

type EncoderConfig

type EncoderConfig struct {
	Codec Codec
	// Width and Height are the frame size. The stream is coded in the
	// device's units and at least its smallest size, the padding's
	// pixels the edge's repeated and cropped off on decode; an odd size
	// decodes one pixel larger, its last row or column twice.
	Width, Height int
	// FrameRate is the frames a second the stream runs at, for its
	// level; frames may come at any time.
	FrameRate int
	// KeyInterval is the frames from one keyframe to the next.
	KeyInterval int
	// Source is the region of the buffer Encode reads, in the buffer's
	// own orientation; the zero rectangle reads all of it.
	Source image.Rectangle
	// Transform is the captured output's wl_output transform: the
	// buffer holds the output's pixels so turned, and the encoder turns
	// them back, so the frame shows what the output shows. Width and
	// Height are the frame's, turned: a 90 or 270 degree transform
	// swaps the source region's.
	Transform Transform
	// QP is the constant quantiser, 0 (best) to 51. A device without
	// constant-QP coding runs its own rate control at a bitrate
	// matching QP 20 on desktop content instead.
	QP int
}

EncoderConfig is a video stream's shape.

type FRect

type FRect struct {
	X, Y, W, H float64
}

FRect is a rectangle in fractional pixels: the region of a texture a draw samples, as wp_viewporter crops a buffer.

type Falloff

type Falloff struct {
	Range, Power float32
}

Falloff softens Keep's edge: coverage falls from 1 at the edge to 0 Range pixels outside it, as (1 - d/Range)^Power, a drop shadow's shape. The zero Falloff is an anti-aliased edge.

type FragmentShader

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

FragmentShader is a fragment shader the caller built at runtime, to draw a whole texture through. Its SPIR-V module takes the compositor pipeline's interface: the texture at set 0 binding 0, its coordinate at input location 0 (0,0 at the top left of dst), colour at output location 0, and comp.glsl's Draw push constants, of which DrawFragmentShader's constants are keep.

func (*FragmentShader) Close

func (s *FragmentShader) Close() error

Close frees the shader once the frames in flight that may draw with it finish.

func (*FragmentShader) Prepare

func (s *FragmentShader) Prepare(t *Target) error

Prepare builds what drawing into t takes, the part a driver may yet refuse, so that a caller can learn of that before it opens a pass.

type Glass

type Glass struct {
	Saturation, Brightness, Contrast float32
	Bezel, Amount                    float32
}

Glass is how DrawGlass turns a blurred backdrop into a glass surface: the factors of saturate(), brightness() and contrast(), where 1 changes nothing, and the bezel the backdrop bends through along the edge, with its displacement at the rim, both in target pixels, as -lys-refract() does; an empty bezel or no displacement bends nothing.

func (Glass) Adjust

func (g Glass) Adjust(c [4]float32) [4]float32

Adjust is the shader's glassAdjust over a premultiplied R, G, B, A in 0..255.

func (Glass) Check

func (g Glass) Check(m Mask) error

Check reports a factor or length that is negative, infinite or NaN, and a mask DrawGlass cannot draw through: a falloff or a merge, which a glass surface has no use for.

func (Glass) Mask

func (g Glass) Mask(m Mask, dst image.Rectangle) Mask

Mask is the mask a glass draw over dst uses: m, whose Keep is also the shape the bezel runs along, taking dst for a Keep it does not have.

func (Glass) RefractPlan

func (g Glass) RefractPlan(box RoundRect) render.RefractPlan

RefractPlan is the bend through a bezel along box, the arithmetic lys-ui's -lys-refract() runs, for a renderer without a shader.

func (Glass) Refracts

func (g Glass) Refracts() bool

Refracts reports whether the glass bends its backdrop at all.

type Goo

type Goo struct {
	A, B   RoundRect
	Smooth float32
}

Goo is two rounded rectangles merged into one blob: their distance fields joined by a smooth minimum that melts them together where they come within Smooth pixels of each other, as metaballs do; zero Smooth is their plain union. GooCoverage mirrors it in Go.

type Gradient

type Gradient struct {
	Stops    *Texture
	From, To [2]float32
	Alpha    float32
}

Gradient is a linear gradient from From to To, in target pixels: Stops, an N x 1 texture of N >= 2 premultiplied colours, spread evenly from From (the first) to To (the last), each pixel taking the colour at its projection onto the line, clamped at the ends, the stops between interpolated linearly, all of it at Alpha.

type Linear

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

Linear is a linear single-plane dmabuf imported as a buffer, not an image: what a copy engine writes a frame into for a device that scans out only linear buffers another GPU allocated, even where this device renders into no linear layout (NVIDIA's). Close it when done; the device closes the ones still open with it.

func (*Linear) Close

func (l *Linear) Close()

Close releases the buffer; closing it again, or after its device, does nothing.

func (*Linear) Size

func (l *Linear) Size() image.Point

Size is the buffer's size in pixels.

type Losses

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

Losses is the record of a consumer's recent device losses, deciding whether the next one is recovered from. The zero value has none.

func (*Losses) Count

func (l *Losses) Count() int

Count is the number of losses within the window of the last Record.

func (*Losses) Err

func (l *Losses) Err() error

Err joins every loss within the window of the last Record, oldest first; nil when there is none.

func (*Losses) Record

func (l *Losses) Record(now time.Time, err error) bool

Record adds a loss at now and reports whether it is within LossLimit for the LossWindow ending at now. Losses older than the window are forgotten.

type Mask

type Mask struct {
	Keep, Cut RoundRect
	Falloff   Falloff
	Merge     image.Rectangle
	Smooth    float32
}

Mask limits a draw to the pixels inside Keep and outside Cut, each edge anti-aliased by its signed distance at the pixel centre, Keep's softened by Falloff. A non-empty Merge melts a second rectangle with Keep's radius into Keep as Goo does, over Smooth pixels. An empty Keep keeps everything; an empty Cut cuts nothing.

func (Mask) Check

func (m Mask) Check() error

Check reports a radius, falloff range or smoothing that is negative, infinite or NaN, and a falloff with a range whose power is not positive.

func (Mask) Coverage

func (m Mask) Coverage(px, py float32) float32

Coverage is the fraction of the pixel whose centre is (px, py) that the mask keeps, as the shaders compute it.

type Packet

type Packet struct {
	Data []byte
	PTS  time.Duration
	Key  bool
}

Packet is one encoded frame: an Annex-B access unit (start-code delimited NAL units, without the parameter sets, which ParameterSets gives), the time it was handed in at, and whether it is a keyframe (an IDR).

type Pass

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

Pass draws a compositor's frame into a Target, every call clipped to the damage it began with. The first bad call fails the pass: End reports it and draws nothing. The device reuses it for its next Begin, so a frame costs no allocation: nothing holds one past that Begin.

func (*Pass) Clear

func (p *Pass) Clear(c color.RGBA)

Clear sets the damage to c, premultiplied.

func (*Pass) ClearCut

func (p *Pass) ClearCut()

ClearCut draws the pass's later calls uncut, as it began.

func (*Pass) DrawFragmentShader

func (p *Pass) DrawFragmentShader(s *FragmentShader, t *Texture, dst image.Rectangle, constants [4]float32)

DrawFragmentShader writes all of t through s into dst's damaged part, sampling t linearly, with no blending and the target's alpha kept.

func (*Pass) DrawGlass

func (p *Pass) DrawGlass(t *Texture, src FRect, dst image.Rectangle, alpha float32, m Mask, g Glass)

DrawGlass blends src of t, scaled to dst and bent and adjusted by g, at alpha over dst's damaged part within m, always sampling linearly, so that a bent pixel lands between texels. The bezel runs along m's Keep, or along dst without one, and the adjusted colour goes through what SetColor set. The pipeline is built at the first draw.

func (*Pass) DrawTexture

func (p *Pass) DrawTexture(t *Texture, src FRect, dst image.Rectangle, tr Transform, alpha float32, m Mask)

DrawTexture blends src of t, scaled to dst and turned by tr, at alpha over dst's damaged part within m. tr is the buffer transform of the texture's content: under Transform90, dst's x runs along src's y and dst's y against src's x. A draw that maps whole source pixels one to one samples them as they are; any other samples bilinearly.

func (*Pass) End

func (p *Pass) End() error

End records what the pass drew, to draw into its target and hand the target back to its consumer, and returns without waiting for the GPU. The passes of a frame reach the queue together, in one submission with one fence: when SyncFile exports, a CPU read or Finish needs them, FrameDone asks about them, or Flush is called, so a consumer that waits on no SyncFile calls Flush before taking the target. SyncFile signals when it is done, and FrameDone says when. A pass whose call failed records nothing and reports the first error.

func (*Pass) FillGoo

func (p *Pass) FillGoo(r image.Rectangle, c color.RGBA, g Goo)

FillGoo blends c, premultiplied, over the blob g covers within r's damaged part.

func (*Pass) FillGradient

func (p *Pass) FillGradient(r image.Rectangle, g Gradient, m Mask)

FillGradient blends g over r's damaged part within m.

func (*Pass) FillRect

func (p *Pass) FillRect(r image.Rectangle, c color.RGBA, m Mask)

FillRect blends c, premultiplied, over r's damaged part within m.

func (*Pass) Incomplete

func (p *Pass) Incomplete() bool

Incomplete reports a draw skipped because its pipeline is still being built (Prepare): the caller keeps this pass's damage for its next frame.

func (*Pass) Kawase

func (p *Pass) Kawase(t *Texture, dst image.Rectangle, offset float32, up bool)

Kawase draws all of t scaled to dst through one pass of a dual Kawase blur, sampling t linearly at offset source half-pixels from each pixel: four diagonal taps around a centre weighted four (down, for a target smaller than t) or eight taps around it (up, for a larger one). KawaseAt mirrors it in Go. It replaces dst's pixels rather than blending over them, so a level covering its whole target needs no Clear and never reads what the target held.

func (*Pass) SetColor

func (p *Pass) SetColor(t *ColorTransform)

SetColor sends every later draw of the pass through t before it blends: a fill's colour, a gradient's stops and a texture's samples of any format after YCbCr conversion, while coverage and alpha stay outside it. Nil, what a pass starts with, draws without a transform. Kawase never takes one: it averages a target already in the pass's encoding.

func (*Pass) SetCut

func (p *Pass) SetCut(t *Texture, c AlphaCut)

SetCut sends every later FillRect, DrawTexture and DrawGlass of the pass through c over t, until ClearCut: each keeps only what lies over t's texels of alpha above c's threshold. Gradients, goo and Kawase draw uncut.

type Readback

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

Readback is host-visible memory a target is copied into for the CPU to read, without stalling whoever draws: Copy only queues the copy, and Wait, on any goroutine, blocks until it is done. It needs neither a dmabuf nor a sync_file, so it works on every device. Close it when done; the device closes the ones still open with it.

func (*Readback) Close

func (r *Readback) Close()

Close releases the readback; closing it again, or after its device, does nothing.

func (*Readback) Copy

func (r *Readback) Copy(src *Target) error

Copy queues copying src, a target of the readback's size that has been drawn, over what the readback held. A copy still running refuses it.

func (*Readback) Pixels

func (r *Readback) Pixels() ([]byte, int, error)

Pixels is the last finished copy: the target's rows in its own format, 4 bytes a pixel, and the bytes between rows. They stay valid until the next Copy or Close.

func (*Readback) Wait

func (r *Readback) Wait() error

Wait blocks until the last Copy is done, on any goroutine, while the device goes on drawing on another; Close must not overlap it.

type RoundRect

type RoundRect struct {
	Rect   image.Rectangle
	Radius float32
}

RoundRect is a rectangle in target pixels whose corners are rounded by Radius, clamped to half its shorter side.

type Siting

type Siting uint8

Siting is a chroma sample's position along one axis.

const (
	SitingDefault Siting = iota
	SitedAt0
	SitedAtHalf
)

The sitings: the axis's default (with the first luma sample along X, between the two along Y, or the other where the device samples only that), with the first luma sample, or midway between the two.

type Target

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

Target is an image the GPU renders into whose memory is a dmabuf: a window's frame handed to the compositor, or an output's scanout buffer. Its layout (the DRM modifier) is one the caller offered, as the consumer imports it. Between frames it belongs to the consumer.

func (*Target) Close

func (t *Target) Close()

Close releases the target and its dmabuf fd; closing it again, or after its device, does nothing.

func (*Target) Dmabuf

func (t *Target) Dmabuf() dmabuf.Buffer

Dmabuf describes the target's memory for its consumer. Its fd is the target's, open until Close; an offscreen target has none.

func (*Target) ReadPixels

func (t *Target) ReadPixels() (*image.RGBA, error)

ReadPixels copies the target back into memory as premultiplied RGBA: tests and screenshots.

func (*Target) ReadRect

func (t *Target) ReadRect(r image.Rectangle) (*image.RGBA, error)

ReadRect copies only r of the target back into memory as premultiplied RGBA, in an image whose bounds are r: nothing outside r leaves the GPU.

func (*Target) Size

func (t *Target) Size() image.Point

Size is the target's size in pixels.

func (*Target) Texture

func (t *Target) Texture() (*Texture, error)

Texture is an offscreen target as a texture a later Pass samples: what the target's last pass drew, premultiplied ARGB8888. It lives as long as the target; a pass cannot draw a target into itself.

type Texture

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

Texture is an image a Pass samples, kept across frames: one the device allocates and the CPU uploads into (NewTexture), or a dmabuf imported from its producer (ImportTexture). Close it when done; the device closes the ones still open with it.

func (*Texture) Close

func (t *Texture) Close()

Close releases the texture; closing it again, after its device, or closing a target's texture, which its target owns, does nothing.

func (*Texture) Format

func (t *Texture) Format() fourcc.Format

Format is the texture's DRM format.

func (*Texture) Size

func (t *Texture) Size() image.Point

Size is the texture's size in pixels.

func (*Texture) Update

func (t *Texture) Update(r image.Rectangle, stride int, pix []byte) error

Update copies pix into r of the texture, rows stride bytes apart; the rest of the texture keeps what it held.

type Transform

type Transform int

Transform is a wl_output transform: how an output's pixels are turned in its buffer.

const (
	TransformNormal Transform = iota
	Transform90
	Transform180
	Transform270
	TransformFlipped
	TransformFlipped90
	TransformFlipped180
	TransformFlipped270
)

The transforms, valued as wl_output's.

type YCbCr

type YCbCr struct {
	Matrix YCbCrMatrix
	Range  YCbCrRange
	Chroma ChromaSiting
}

YCbCr is how a YUV buffer's samples become RGB: the colour hints a client gives with it (wp_color_representation, or a video's own). The zero value is BT.601 in limited range, chroma sited as MPEG-2 and H.264 site 4:2:0 chroma.

type YCbCrMatrix

type YCbCrMatrix uint8

YCbCrMatrix is the matrix coefficients a YUV buffer was encoded with.

const (
	BT601 YCbCrMatrix = iota
	BT709
	BT2020
)

The matrices.

type YCbCrRange

type YCbCrRange uint8

YCbCrRange is the range a YUV buffer's samples span.

const (
	LimitedRange YCbCrRange = iota
	FullRange
)

The ranges: limited (16 to 235 for 8-bit luma) and full.

Jump to

Keyboard shortcuts

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