screencast

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: BSD-3-Clause Imports: 11 Imported by: ? modules, 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.

README

go-freedesktop/screencast

ci Go Reference License Go Coverage

Capture the pixels of displays and windows on Linux, in pure Go, with CGO_ENABLED=0, without shelling out to anything.

No Xlib. No XCB. No cgo. No exec.Command to xwd, import, grim or ffmpeg. This package speaks the X11 wire protocol itself, over the display's unix socket, and lets the X server write captured frames straight into shared memory it handed over with SCM_RIGHTS.

It is the Linux sibling of go-macos/screencapture and presents deliberately the same shape, so one consumer can drive both platforms through near-identical adapters.

ctx := context.Background()

content, err := screencast.Shareable(ctx)
d, err := content.MainDisplay()

s, err := screencast.CaptureDisplay(ctx, d, screencast.Options{FPS: 60})
defer s.Close()

for {
    f, fresh := s.Frame()      // borrowed BGRA bytes; no allocation
    if fresh {
        upload(f.Pix, f.Width, f.Height, f.Stride)   // index with Stride
    }
}

What it does

Enumerate displays one per RANDR 1.5 monitor, per XINERAMA screen, or per X screen
Enumerate windows _NET_CLIENT_LIST, or a walk of the window tree with WM_STATE resolution
Capture a display MIT-SHM ShmGetImage, falling back to core GetImage
Capture a window same, on the window drawable
Pixel format BGRA, always, converted from whatever visual the server has
Cursor composited from XFIXES GetCursorImage, on request
Resampling nearest-neighbour on the CPU, optional letterboxing
Other platforms compile and report ErrUnsupported

Two contract details

Stride is carried, never assumed. Frame.Stride is the number of BYTES per row and is not necessarily Width*4: X11 pads every scanline to the pixmap format's boundary. Index with Stride, or use Frame.Row(y). A consumer that assumes Width*4 shears the picture progressively down the screen.

Frame() does not allocate. It hands back a borrowed view of the capture buffer — for MIT-SHM, the shared segment the X server itself wrote into. Measured at 35 ns/op, 0 allocs/op. The consumer's whole frame budget is 16.6 ms.

Measured

On a Debian 13 cloud VM (32 vCPU, no GPU), against Xvfb, CGO_ENABLED=0:

capture transport ms/frame fps
1280×800, depth 24 MIT-SHM 2.50 400
1280×800, depth 24 GetImage 3.76 266
800×600, depth 16 (converted) MIT-SHM 4.61 217
800×600, depth 30 (converted) MIT-SHM 5.30 189
3840×2160, depth 24 MIT-SHM 24.3 41
3840×2160, depth 24, RawAlpha MIT-SHM 5.81 172

Stream.Frame(): 35 ns/op, 0 allocs/op, at every size.

That last pair is worth reading twice. On the common path the captured bytes are ALREADY BGRA, so the only per-frame work the capture does is forcing the fourth byte opaque — and at 4K that one pass costs 18 of the 24 milliseconds. A consumer that ignores alpha, or sets it itself on the GPU, sets Options.RawAlpha and gets it back.

Proof, not assertion

"The frame is not all zeroes" is a weak claim: a capture that read the wrong drawable, swapped red and blue, or sheared every row would pass it. A static grey buffer is the classic silent failure of a screen capture.

So the integration suite and sccheck -selftest paint: they cover the display with an override-redirect window, fill it with a colour built from the visual's OWN channel masks, and then require every captured pixel to be exactly that colour, in that byte order, at the declared stride — and then require the next colour to be seen.

$ DISPLAY=:99 sccheck -selftest
self-test: painting root 0x21f, visual 0x21 masks r=0xff0000 g=0xff00 b=0xff
self-test red   (pixel 0x00ff0000): all 1024000 pixels are 00 00 ff ff, stride 5120, seq 9
self-test green (pixel 0x0000ff00): all 1024000 pixels are 00 ff 00 ff, stride 5120, seq 12
self-test blue  (pixel 0x000000ff): all 1024000 pixels are ff 00 00 ff, stride 5120, seq 15
self-test white (pixel 0x00ffffff): all 1024000 pixels are ff ff ff ff, stride 5120, seq 18
self-test black (pixel 0x00000000): all 1024000 pixels are 00 00 00 ff, stride 5120, seq 21
self-test: PASS

That passes identically on a 5-6-5 visual, an 8-8-8 one and a 10-10-10 one, because a full-scale channel widens to 255 whatever its bit width.

A frame captured this way is committed at testdata/xvfb-1280x800-capture.png.

Backends

X11 — works. The whole of it: MIT-SHM 1.2 with AttachFd descriptor passing, core GetImage fallback, MIT-MAGIC-COOKIE-1 authorization, RANDR 1.5 and XINERAMA monitor enumeration, XFIXES cursor, every TrueColor and DirectColor visual at 16, 24 and 32 bits per pixel.

The wire codec, the .Xauthority parser, the setup exchange, the shared-memory segment and the monitor enumeration are not owned here: they are go-freedesktop/x11, shared with go-widgets/window. Which display is where is not a capture question — a toolkit putting a window full-screen on a chosen panel needs the identical answer — and two copies of a protocol parser drift silently until something fails on one back-end only.

Wayland — not implemented. A wlroots compositor exposing wlr-screencopy-unstable-v1 could be driven the same way. It is not done here. Under Wayland, capture works only through Xwayland.

xdg-desktop-portal — deliberately not started. On GNOME and KDE the sanctioned route is org.freedesktop.portal.ScreenCast, which negotiates over D-Bus and then hands back a PipeWire stream. A pure-Go PipeWire client is a large piece of work. Rather than half-build it, this package DETECTS that situation and says so:

if err := screencast.Diagnose(); errors.Is(err, screencast.ErrPortalPipeWire) {
    // "this session can only be captured through xdg-desktop-portal's
    //  org.freedesktop.portal.ScreenCast, which delivers frames over PipeWire;
    //  this package implements no PipeWire client. ..."
}

Diagnose consults the session bus to say whether the portal is actually there — it only LOOKS, and never opens a session, prompts anyone or starts a stream.

Differences from the macOS sibling

The API is the same shape. Where Linux genuinely differs:

  • FPS is a polling RATE, not a ceiling. X11 GetImage is pull-based: the loop asks for a frame every tick and gets one whether or not anything changed. ScreenCaptureKit is change-driven and delivers nothing while the screen is still. A consumer written against the macOS fresh flag still works; it just sees fresh on every tick.
  • Options.Width/Height resample on the CPU. X11 has no server-side scaler, so any size other than native costs a pass over the pixels.
  • Rect coordinates are in PIXELS. X11 has no points. Display.PixelWidth == Display.Width for the same reason; both pairs are kept so a consumer's field access is identical on both platforms.
  • Authorized/RequestAuthorization are not a permission dance. X11 has no per-application capture grant: if the connection authenticates, capture is allowed. They report whether a usable connection can be opened. Probe reports WHY when the answer is no.
  • Options.ExcludeWindows is rejected, not ignored: the X server cannot capture a screen minus a window.
  • New: Options.RawAlpha, Options.ForceGetImage, Stream.Transport(), Stream.Converts(), Probe(), Diagnose(), Session(), PortalAvailable().

Two X11 facts a window capture cannot hide

  • A window that is not VIEWABLE has no pixels. X11 keeps no offscreen copy of a minimised window unless a compositing manager has redirected it. Capturing one reports ErrNotFound rather than a stale or black frame.
  • Without a compositing manager, reading a window's pixels reads the FRAMEBUFFER where that window is, so anything overlapping it is in the capture. Under a compositing manager — which is every modern desktop — each window is redirected to its own offscreen pixmap and the capture is clean.

The probe

go run ./cmd/sccheck                 # enumerate, capture, measure, report
go run ./cmd/sccheck -list           # enumerate only
go run ./cmd/sccheck -selftest       # paint known colours and verify them
go run ./cmd/sccheck -png frame.png  # save a captured frame
go run ./cmd/sccheck -slow           # force the core GetImage path
go run ./cmd/sccheck -raw-alpha      # skip the opaque-alpha pass

Tested against real hardware

Or rather: mostly not against hardware, and that is worth saying outright. A capture path that has only ever run against a software framebuffer can be wrong in ways nothing here would report.

What was actually run
Where What was done
Debian 13 cloud VM, 32 vCPU, no GPU, X server = Xvfb every figure in Measured, and every self-test transcript in Proof, not assertion
Depths 16, 24 and 30; TrueColor and DirectColor visuals the painted self-test passes identically on all of them, because a full-scale channel widens to 255 whatever its bit width
MIT-SHM 1.2 with AttachFd, and the core GetImage fallback both exercised, and compared against each other
Every other platform the whole wire codec runs in-process over a net.Pipe against a scripted server, so a protocol bug fails the macOS and Windows lanes too
Not proven
  • No physical GPU, and no physical X server. Xvfb renders into ordinary memory. A real driver's read-back cost is the one number here that a software framebuffer cannot stand in for, and the 4K figures should be read as the cost of this package's own work, not of the whole path on a real display.
  • No physical monitor, so no real RANDR 1.5 layout. Monitor enumeration is exercised against a scripted server and against Xvfb's single screen; a multi-head desktop, a rotated panel or a mixed-DPI arrangement has not been seen.
  • Wayland is not implemented at all, and is stated as such above rather than left to be discovered. Under Wayland this captures only through Xwayland.
  • xdg-desktop-portal / PipeWire is detected, never driven. Diagnose only looks; it never opens a session.
Send us hardware

A machine with a real GPU, a multi-head RANDR 1.5 desktop, or a rotated panel would each turn one of the lines above into a measurement. If you want one settled, send us the hardware and what it shows will be listed here. Until then, an unverified line says so.

Testing

go test ./...                        # everything portable, on any platform
go test -race ./...

Xvfb :99 -screen 0 1280x800x24 -ac &
DISPLAY=:99 SCREENCAST_LIVE=1 go test -tags integration -run Live -v ./...

Captures never go in the repository. The live suite writes its PNG to os.UserConfigDir()/go-freedesktop-screencast/captures, or to SCREENCAST_ARTIFACT_DIR when set — and either way the directory is walked up to the filesystem root looking for a .git, and REFUSED if one is found, including a .git that is a file, which is what a worktree has. A capture is a picture of whatever the machine happened to be showing, and a .gitignore entry is not a control: it is one git add -f away from being published forever. The refusal is tested, on every platform and every lane, in capturedir_test.go — a guard that only compiles where the live suite runs is a guard nobody runs. The committed frame under testdata/ was put there by hand, from a disposable Xvfb.

The X11 wire codec is transport-agnostic: internal/x11.Handshake wraps any io.ReadWriteCloser, so the whole request/reply/error machine runs in-process over a net.Pipe against a scripted fake server. That is why a protocol bug is caught on macOS and on Windows as well as on Linux, and why internal/x11 reaches 100% coverage on every platform.

CI gates 100% coverage on the portable layer — the public types and their arithmetic, the stream machinery, the resampler, the cursor blend, the stubs and the entire wire codec. It does not gate the code that drives a real X server; that runs against a real Xvfb in the Linux lane, and the lane prints what it reached.

Licence

BSD-3-Clause.

Documentation

Overview

Package screencast captures the pixels of displays and windows on Linux, in pure Go, with CGO_ENABLED=0 and without shelling out to anything.

It is the Linux sibling of github.com/go-macos/screencapture and presents deliberately the same shape, so one consumer can drive both platforms through near-identical adapters. Where Linux genuinely differs, the difference is named in the doc comment of the affected symbol and collected under "Deviations from the macOS sibling" below.

Backends

X11 is the backend that works. It speaks the X11 wire protocol directly — no Xlib, no XCB, no cgo — over the display's unix socket, authenticating with the MIT-MAGIC-COOKIE-1 from the Xauthority file. Frames are fetched with MIT-SHM ShmGetImage into a shared memory segment the X server writes straight into (the descriptor is handed over with SCM_RIGHTS), so a frame costs one small request and no pixel ever travels through the socket. When the server does not offer MIT-SHM, or the transport cannot pass a descriptor, it falls back to core GetImage, which is correct but ships every pixel over the socket.

Wayland is NOT implemented. A compositor exposing wlr-screencopy could be driven the same way; it is not done here. See ErrNoBackend.

xdg-desktop-portal ScreenCast (the correct route on GNOME and KDE) hands back a PipeWire stream, and a pure-Go PipeWire client is a large piece of work that this package deliberately does not start. When the portal is the only route left, capture fails with ErrPortalPipeWire, which says exactly that. Knowing precisely where the wall is, is the useful result.

The hot path

The package is written for a compositor that redraws every frame and cannot afford a copy or an allocation per frame. Stream.Frame hands back a BORROWED view of the most recent captured frame — for the MIT-SHM backend those are the bytes the X server itself wrote into the shared segment, not a copy — together with a boolean saying whether it is newer than the one the previous call returned. In steady state a Frame call performs no allocation at all.

The borrow is valid until the QueueDepth-th subsequent frame overwrites the buffer; with the default depth that is comfortably longer than one consumer's turn. Copy out of it (see Frame.CopyTight or Frame.NRGBA) if you need it to outlive the borrow.

Stride

A captured frame's rows may be PADDED. Stride is the number of bytes per row and it is NOT necessarily Width*4: X11 pads every scanline to the pixmap format's scanline-pad boundary, which for the usual 32-bits-per-pixel depth 24 visual lands on Width*4, but for a 16-bit or a 30-bit visual does not. Always index with Stride, or use Frame.Row. This is the single most common way to get a sheared image.

Pixel format

Frames are handed back as FormatBGRA: four bytes per pixel, blue first, then green, red, alpha. That is the memory layout a little-endian X server with a depth-24 TrueColor visual already produces, so on the overwhelmingly common case there is no conversion at all. On a server whose visual masks or image byte order say otherwise, the capture converts each frame in place and Stream.Converts reports true.

Deviations from the macOS sibling

  • Authorized and RequestAuthorization are not a permission dance. X11 has no per-application capture grant: if the connection authenticates, capture is allowed. They report whether a usable display connection can be opened.
  • FPS is a real POLLING RATE, not a ceiling. X11 GetImage is pull-based: the capture loop asks for a frame every tick and gets one whether or not anything changed. ScreenCaptureKit is change-driven and delivers nothing while the screen is still. A consumer written against the macOS "fresh" flag still works; it just sees fresh on every tick.
  • Options.Width and Options.Height resample on the CPU (nearest neighbour). X11 has no server-side scaler, so asking for a size other than the source's native one costs a pass over the pixels.
  • Rect coordinates are in PIXELS, not points. X11 has no points.
  • Display.PixelWidth equals Display.Width for the same reason; both pairs are kept so a consumer's field access is identical on both platforms.
  • Options.ExcludeWindows is not supported and is rejected: the X server has no notion of capturing the screen minus a window.

Index

Constants

View Source
const (
	// DefaultFPS is the polling rate used when Options.FPS is zero.
	DefaultFPS = 60.0
	// DefaultQueueDepth is the buffer count used when Options.QueueDepth is
	// zero.
	DefaultQueueDepth = 6
	// MinQueueDepth is the smallest queue depth this package accepts: one
	// buffer lent to the consumer, one holding the published frame, one being
	// filled.
	MinQueueDepth = 3
	// MaxDimension is the largest frame edge accepted, a sanity bound well
	// above any real display; it exists so a mistaken value fails loudly
	// instead of asking the X server for a terabyte.
	MaxDimension = 32768
	// MinFPS is the slowest polling rate accepted.
	MinFPS = 0.01
)

Defaults applied to the zero value of the corresponding Options field.

View Source
const (
	// LayerNormal is an ordinary application window.
	LayerNormal = 0
	// LayerDesktop is the desktop background window.
	LayerDesktop = -1
	// LayerDock is a panel, taskbar or dock.
	LayerDock = 1
	// LayerOverride is an override-redirect window: a menu, a tooltip, a
	// drag icon. The window manager never sees it.
	LayerOverride = 2
)

Window layers. X11 has no layer number; these are derived from _NET_WM_WINDOW_TYPE and the override-redirect flag so a consumer can tell an application window from the panel and the desktop, which is what the macOS sibling's Layer field is for.

View Source
const (
	PortalService = "org.freedesktop.portal.Desktop"
	PortalPath    = "/org/freedesktop/portal/desktop"
	PortalIface   = "org.freedesktop.portal.ScreenCast"
)

PortalService, PortalPath and PortalIface name the xdg-desktop-portal ScreenCast interface PortalAvailable looks for. They are exported on every platform so a consumer that reports them compiles everywhere, even where there is no session bus to look on.

View Source
const Backend = "X11"

Backend names the capture route in use.

Variables

View Source
var (
	// ErrUnsupported is reported on every non-Linux platform.
	ErrUnsupported = errors.New("screencast: unsupported on this platform (Linux only)")

	// ErrNoBackend is reported when no capture backend can serve this
	// session: there is no X11 display to connect to and the Wayland route
	// this package implements is not available.
	ErrNoBackend = errors.New("screencast: no usable capture backend " +
		"(no X11 display reachable; set DISPLAY, or run under Xwayland)")

	// ErrPortalPipeWire is reported when the only remaining capture route is
	// xdg-desktop-portal's org.freedesktop.portal.ScreenCast, which delivers
	// frames over PipeWire. This package speaks no PipeWire and deliberately
	// does not try: the message names the wall rather than pretending.
	ErrPortalPipeWire = errors.New("screencast: this session can only be captured through " +
		"xdg-desktop-portal's org.freedesktop.portal.ScreenCast, which delivers frames over " +
		"PipeWire; this package implements no PipeWire client. Run the session under X11 or " +
		"Xwayland, or use a wlroots compositor, to capture with this package")

	// ErrPermissionDenied is reported when the X server refuses the
	// connection because no usable authorization cookie was found.
	ErrPermissionDenied = errors.New("screencast: the display server refused the connection — " +
		"no matching MIT-MAGIC-COOKIE-1 in the Xauthority file; set XAUTHORITY to the file " +
		"holding a cookie for this display, or run as the user who owns the session")

	// ErrNoDisplay is reported when a capture was asked for and the server
	// listed no display at all.
	ErrNoDisplay = errors.New("screencast: no capturable display")

	// ErrNotFound is reported when a display or window ID does not name
	// anything currently capturable.
	ErrNotFound = errors.New("screencast: no such display or window")

	// ErrClosed is reported by every [Stream] method after [Stream.Close].
	ErrClosed = errors.New("screencast: stream is closed")

	// ErrNoFrame is reported by [Stream.WaitFrame] when no frame arrived
	// before its context expired, and by frame helpers called on a frame that
	// holds no pixels.
	ErrNoFrame = errors.New("screencast: no frame available")

	// ErrInvalidOption is reported by [Options.Validate] and wraps a
	// description of the offending field.
	ErrInvalidOption = errors.New("screencast: invalid option")

	// ErrShortBuffer is reported by [Frame.CopyTight] when the destination is
	// too small to hold the frame.
	ErrShortBuffer = errors.New("screencast: destination buffer too short")

	// ErrProtocol is reported when the display server answered something this
	// package cannot make sense of. It always wraps a description.
	ErrProtocol = errors.New("screencast: display server protocol error")
)

Sentinel errors. All are stable and may be matched with errors.Is.

Functions

func Authorized

func Authorized() bool

Authorized reports whether capture is allowed WITHOUT asking anyone.

X11 has no per-application capture grant: a client that completes the setup handshake may read any drawable on the server. So this reports whether the handshake succeeds, which is the same question in X11 terms — and unlike macOS, the answer is not something a user can change in a settings pane. It is identical to Available by construction; both are kept so a consumer's startup check reads the same on every platform.

func Available

func Available() bool

Available reports whether this process can reach a capturable display server. It opens a connection and closes it again, so it answers about the server that is actually there rather than about an environment variable.

Use Probe instead when you want to know WHY the answer is no.

func Diagnose

func Diagnose() error

Diagnose explains why no X11 capture is possible, given the session the process is in. It is what CaptureDisplay reports when the connection cannot be made, and it is worth calling directly to print a useful message.

It returns nil when an X11 display is at least NAMED — whether the connection then succeeds is a separate question, answered by Authorized.

On a Wayland session it consults the portal. If the portal is there, the answer is ErrPortalPipeWire with the portal's version spliced in: the route exists, it just ends in PipeWire. If it is not, the answer is ErrNoBackend.

func PortalAvailable

func PortalAvailable() (present bool, version uint32)

PortalAvailable reports whether xdg-desktop-portal's ScreenCast interface is on the session bus, and the interface version it advertises.

It only LOOKS. It never opens a session, never prompts the user and never starts a PipeWire stream, because this package cannot consume one.

func Probe

func Probe() error

Probe reports nil when a capture backend is reachable, and the reason otherwise — ErrPortalPipeWire for a portal-only Wayland session, ErrNoBackend when there is no display server at all, ErrPermissionDenied when the server refused the cookie.

func RequestAuthorization

func RequestAuthorization() bool

RequestAuthorization reports Authorized. There is nothing to request: X11 prompts for nothing and grants nothing per-application. It never blocks and never shows a dialog.

Types

type Application

type Application struct {
	PID      int32
	Name     string
	BundleID string
}

Application is a process owning capturable windows.

type Content

type Content struct {
	Displays     []Display
	Windows      []Window
	Applications []Application
}

Content is a snapshot of what the calling process may capture. It is a snapshot: windows open and close, so re-read it rather than caching it.

func CurrentProcessShareable

func CurrentProcessShareable(ctx context.Context) (*Content, error)

CurrentProcessShareable returns the content owned by the CALLING process: every display (X11 restricts nobody from reading the root window) and only this process's own windows.

It exists because the macOS sibling has it, where it is the permission-free path that makes the package testable without a TCC grant. Here it is simply a filter — but it is the same filter, so a test written once runs on both.

func Shareable

func Shareable(ctx context.Context) (*Content, error)

Shareable returns everything this process may capture.

func (*Content) Display

func (c *Content) Display(id uint32) (Display, error)

Display returns the display with the given id.

func (*Content) MainDisplay

func (c *Content) MainDisplay() (Display, error)

MainDisplay returns the primary display, or the first one if none is flagged primary.

func (*Content) Window

func (c *Content) Window(id uint32) (Window, error)

Window returns the window with the given id.

func (*Content) WindowsByTitle

func (c *Content) WindowsByTitle(title string) []Window

WindowsByTitle returns every window whose title is exactly title.

func (*Content) WindowsOfPID

func (c *Content) WindowsOfPID(pid int32) []Window

WindowsOfPID returns every window owned by the given process.

type Display

type Display struct {
	ID          uint32 // RandR monitor/CRTC id, or the root window for a whole screen
	Name        string // RandR output name, e.g. "HDMI-1"; "" when unnamed
	Width       int    // pixels
	Height      int    // pixels
	PixelWidth  int    // pixels; equal to Width on X11
	PixelHeight int    // pixels; equal to Height on X11
	Frame       Rect   // position within the X screen, pixels
	Main        bool   // this is the RandR primary monitor
	Screen      int    // X screen index this display belongs to
	Root        uint32 // root window of that screen; the drawable capture reads
}

Display is a capturable display: one monitor of one X screen, as RandR reports it, or the whole X screen when the server has no RandR.

Width/Height and PixelWidth/PixelHeight are equal on X11 — there is no backing-scale factor to separate them — and both pairs exist so the struct is field-for-field the macOS sibling's.

func Displays

func Displays(ctx context.Context) ([]Display, error)

Displays lists the capturable displays: one per RANDR monitor of every X screen the server has, or one per X screen when the server has no RANDR and no XINERAMA.

The ID is the monitor's RANDR name atom when it has one, which is stable for the lifetime of the server, and a synthetic screen/index composite otherwise. Compare displays by ID, not by position in the slice.

func (Display) Scale

func (d Display) Scale() float64

Scale is the display's backing scale factor. It is always 1 on X11, and exists so a consumer can call it on either platform.

func (Display) String

func (d Display) String() string

String renders the display for logs.

type Frame

type Frame struct {
	// Pix is the frame's bytes in [FormatBGRA], Stride bytes per row, Height
	// rows. len(Pix) >= Stride*Height.
	Pix []byte
	// Width and Height are the frame's size in pixels.
	Width, Height int
	// Stride is the number of BYTES per row. It is NOT necessarily Width*4:
	// the X server pads each scanline to the pixmap format's boundary.
	Stride int
	// Seq counts frames since the stream started; it is 0 before the first
	// frame and strictly increases afterwards.
	Seq uint64
	// At is when the capture loop received the frame.
	At time.Time
}

Frame is a BORROWED view of one captured frame.

Pix aliases a capture buffer owned by the stream — for the MIT-SHM backend, the shared segment the X server wrote into. It stays valid until the stream cycles back round to that buffer, which with the default Options.QueueDepth is several frames away. Do not retain it; copy with Frame.CopyTight or Frame.NRGBA if you need it to outlive the borrow.

func (Frame) CopyTight

func (f Frame) CopyTight(dst []byte) (int, error)

CopyTight copies the frame into dst with the row padding removed, so dst holds Width*4*Height bytes of contiguous BGRA. It reports how many bytes it wrote, or ErrShortBuffer if dst is too small. It allocates nothing.

func (Frame) Format

func (f Frame) Format() PixelFormat

Format reports the pixel format of the frame, always FormatBGRA.

func (Frame) NRGBA

func (f Frame) NRGBA() (*image.NRGBA, error)

NRGBA copies the frame into a freshly allocated image.NRGBA, swapping BGRA to RGBA as it goes and forcing alpha opaque, because an X11 screen capture carries no meaningful alpha. It is the convenience path for saving a frame to disk; it allocates, so it does not belong in a per-frame loop.

func (Frame) Row

func (f Frame) Row(y int) []byte

Row returns row y of the frame, Width*4 bytes with the padding trimmed off. It does not allocate. It returns nil for an out-of-range y or an invalid frame.

func (Frame) TightLen

func (f Frame) TightLen() int

TightLen is the number of bytes the frame occupies with no row padding, Width*4*Height.

func (Frame) Valid

func (f Frame) Valid() bool

Valid reports whether the frame holds pixels.

type Options

type Options struct {
	// Width and Height are the requested frame size in PIXELS. Zero means
	// "the source's native pixel size", which is what you want: any other
	// value costs a CPU resample of every frame, because X11 has no
	// server-side scaler.
	Width, Height int

	// FPS is the POLLING RATE of the capture loop. Unlike the macOS sibling,
	// where it is a ceiling on a change-driven stream, here it is the rate at
	// which frames are actually fetched. Zero means [DefaultFPS].
	FPS float64

	// ShowsCursor composites the mouse pointer into the captured frames,
	// using the XFIXES extension's GetCursorImage. It is rejected at capture
	// time when the server has no XFIXES rather than silently producing
	// cursorless frames.
	ShowsCursor bool

	// QueueDepth is how many capture buffers the stream cycles through. Zero
	// means [DefaultQueueDepth]. It must leave room for the two frames the
	// package holds on the consumer's behalf (the one lent out and the one
	// being filled), so values below [MinQueueDepth] are rejected.
	QueueDepth int

	// ExcludeWindows exists only so the struct matches the macOS sibling. The
	// X server cannot capture a screen minus a window, so a non-empty value
	// is rejected by [Options.Validate] rather than silently ignored.
	ExcludeWindows []uint32

	// ScalesToFit letterboxes the source into Width×Height, preserving its
	// aspect ratio, instead of stretching it.
	ScalesToFit bool

	// RawAlpha hands back the fourth byte of each pixel exactly as the
	// display server wrote it, instead of forcing it opaque.
	//
	// On the common path — a little-endian server with a depth-24 TrueColor
	// visual, where the captured bytes are already BGRA — forcing alpha
	// opaque is the ONLY per-frame work the capture does, and it is a whole
	// pass over the frame. It is not free: a 3840x2160 capture on a Debian 13
	// cloud VM measured 24.3 ms a frame with the fill and 5.8 ms without it —
	// 41 fps against 172. A consumer that ignores alpha, or that sets it
	// itself on the GPU, gets that back by setting this.
	//
	// The bytes are then UNDEFINED — in practice zero, which reads as fully
	// transparent. Do not set it unless you know what you do with the fourth
	// byte. It has no effect on a visual that needs a conversion pass anyway,
	// nor on a depth-32 visual, where the alpha is real and always carried.
	RawAlpha bool

	// ForceGetImage disables the MIT-SHM fast path and fetches every frame
	// with core GetImage. It exists to make the slow path testable and to
	// give a way out if a server's MIT-SHM is broken.
	ForceGetImage bool
}

Options configures a capture stream.

The zero Options is usable: it captures the source at its native pixel size, at DefaultFPS frames per second, without the cursor.

func (Options) Validate

func (o Options) Validate() error

Validate reports whether the options are self-consistent, wrapping ErrInvalidOption. It does not consult the system, and it behaves identically on every platform so a consumer's option bug surfaces the same everywhere.

type PixelFormat

type PixelFormat uint32

PixelFormat names the layout of a captured frame. It is spelled as a four-character code so it matches the macOS sibling's OSType field for field, which lets one consumer print or switch on it identically.

const FormatBGRA PixelFormat = 0x42475241 // 'BGRA'

FormatBGRA is 32-bit BGRA: blue, green, red, alpha, in that byte order. It is the only format this package hands back. It is what a compositor wants, it is what a little-endian X server with a depth-24 TrueColor visual already produces, and it is packed rather than planar so a frame is one contiguous run of bytes.

func (PixelFormat) BytesPerPixel

func (f PixelFormat) BytesPerPixel() int

BytesPerPixel is the size of one pixel in this format.

func (PixelFormat) String

func (f PixelFormat) String() string

String renders the code as its four characters, e.g. "BGRA".

type Rect

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

Rect is a rectangle in the global desktop coordinate space, in PIXELS.

The macOS sibling states these in points; X11 has no points, so the numbers here are pixels. The field names and types are identical so a consumer's arithmetic is unchanged.

func (Rect) Empty

func (r Rect) Empty() bool

Empty reports whether the rectangle encloses no area.

func (Rect) String

func (r Rect) String() string

String renders the rectangle as "(x,y)+(w×h)".

type SessionKind

type SessionKind int

SessionKind is what kind of display session the process is sitting in, as the environment describes it.

const (
	// SessionNone means neither DISPLAY nor WAYLAND_DISPLAY is set: there is
	// no graphical session here at all.
	SessionNone SessionKind = iota
	// SessionX11 means DISPLAY is set. This package can capture it.
	SessionX11
	// SessionWayland means WAYLAND_DISPLAY is set and DISPLAY is not, so
	// there is not even an Xwayland to fall back on.
	SessionWayland
	// SessionXwayland means both are set: a Wayland compositor running an
	// Xwayland server. Whether an X11 capture sees the whole desktop or only
	// the X11 clients depends on the compositor, and is stated in the doc of
	// [Diagnose].
	SessionXwayland
)

The recognised session kinds.

func Session

func Session() SessionKind

Session reports what kind of display session the environment describes.

func (SessionKind) String

func (k SessionKind) String() string

String names the session kind.

type Stats

type Stats struct {
	// Frames is the number of frames actually captured.
	Frames uint64
	// Idle is the number of capture ticks that produced no new frame. On the
	// X11 backend it counts ticks skipped because the previous capture was
	// still in flight; the pull-based backend has no "nothing changed" reply.
	Idle uint64
	// Superseded is the number of captured frames that were replaced by a
	// newer one before the consumer ever asked for them. A large value next
	// to Frames means the consumer is slower than the capture.
	Superseded uint64
	// Last is when the most recent frame arrived.
	Last time.Time
	// Interval is the gap between the two most recent frames.
	Interval time.Duration
}

Stats reports what a stream has seen since it started.

func (Stats) FPS

func (s Stats) FPS() float64

FPS is the instantaneous rate implied by Stats.Interval, 0 when fewer than two frames have arrived.

type Stream

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

Stream is a live capture. Create one with CaptureDisplay or CaptureWindow; stop it with Stream.Close, which is idempotent.

A Stream runs one goroutine that grabs a frame every tick and publishes it. The consumer never blocks behind the capture: Stream.Frame takes whatever the most recent published frame is and says whether it is new.

func CaptureDisplay

func CaptureDisplay(ctx context.Context, d Display, opt Options) (*Stream, error)

CaptureDisplay starts a stream on a display.

The stream owns its own connection to the X server, so several captures run independently and closing one does not disturb another.

Frames come from MIT-SHM ShmGetImage when the server offers the extension and the socket can pass a descriptor, which is the case for every local Xorg, Xvfb and Xephyr of the last decade; otherwise from core GetImage, which is correct but pushes every pixel through the socket. Set Options.ForceGetImage to take the slow path deliberately.

func CaptureWindow

func CaptureWindow(ctx context.Context, w Window, opt Options) (*Stream, error)

CaptureWindow starts a stream on a single window.

Two X11 facts a consumer must know, because no amount of API can hide them:

  • A window that is not VIEWABLE has no pixels. X11 keeps no offscreen copy of a minimised or fully-obscured window unless a compositing manager has redirected it. Capturing one reports ErrNotFound rather than handing back a stale or black frame.
  • Without a compositing manager, reading a window's pixels reads the FRAMEBUFFER where that window is. Anything overlapping it — another window, a menu — is in the capture, because on a non-composited X server that is genuinely what is on those pixels. Under a compositing manager (which is every modern desktop) each window is redirected to its own offscreen pixmap and the capture is clean.

func (*Stream) Close

func (s *Stream) Close() error

Close stops the capture and releases the backend's resources.

It interrupts a capture that is in flight before waiting for the loop, so a display server that has stopped answering cannot make Close hang, and it releases the buffers only once the loop can no longer be writing into them.

It is idempotent and safe to call from any goroutine; every subsequent Stream.Frame reports no frame and every Stream.WaitFrame reports ErrClosed.

func (*Stream) Converts

func (s *Stream) Converts() bool

Converts reports whether each frame goes through a pixel-format conversion pass. It is false on the common case — a little-endian server with a depth-24 TrueColor visual already hands back BGRA — and true when the server's visual forced a rewrite.

func (*Stream) Err

func (s *Stream) Err() error

Err reports the error that stopped the capture loop, or nil while it is running. A closed stream reports the error it stopped on, not ErrClosed.

func (*Stream) Frame

func (s *Stream) Frame() (Frame, bool)

Frame returns the most recent captured frame and whether it is newer than the one the previous call returned.

The returned Frame BORROWS the capture buffer. It stays valid until the capture loop cycles back round to that buffer, which with the default Options.QueueDepth is several frames away; the stream will not reuse the buffer handed out by the most recent Frame call before the call after it.

It allocates nothing.

func (*Stream) Options

func (s *Stream) Options() Options

Options returns the stream's resolved options: every zero field replaced by the default that was actually used.

func (*Stream) Source

func (s *Stream) Source() string

Source names what is being captured, e.g. "display HDMI-1" or "window 0x1400007".

func (*Stream) Stats

func (s *Stream) Stats() Stats

Stats reports what the stream has seen since it started.

func (*Stream) Transport

func (s *Stream) Transport() string

Transport names how a frame's pixels reach this process, for logs and for a consumer that wants to know whether it got the fast path. On the X11 backend it is "X11/MIT-SHM" when the server writes straight into a shared segment and "X11/GetImage" when every pixel comes back through the socket.

func (*Stream) WaitFrame

func (s *Stream) WaitFrame(ctx context.Context) (Frame, error)

WaitFrame blocks until a frame newer than the one the previous Stream.Frame or WaitFrame call returned is available, then returns it. It reports ErrNoFrame when ctx expires first, ErrClosed after Stream.Close, and the capture error when the loop has failed.

type Window

type Window struct {
	ID       uint32 // X window id
	Title    string // _NET_WM_NAME, or WM_NAME
	AppName  string // WM_CLASS class part, e.g. "Firefox"
	BundleID string // WM_CLASS instance part; the closest X11 has to a bundle id
	PID      int32  // _NET_WM_PID, 0 when the window does not advertise one
	Frame    Rect   // position within the X screen, pixels
	Layer    int    // 0 for a normal application window; see [Window.Layer]
	OnScreen bool   // mapped and viewable
	Active   bool   // named by _NET_ACTIVE_WINDOW
	Screen   int    // X screen index
	Root     uint32 // root window of that screen
}

Window is a capturable top-level window.

func Windows

func Windows(ctx context.Context) ([]Window, error)

Windows lists the capturable top-level windows, newest-mapped last, as the window manager's _NET_CLIENT_LIST states them. A server with no EWMH-compliant window manager falls back to walking the window tree.

func (Window) String

func (w Window) String() string

String renders the window for logs.

Directories

Path Synopsis
cmd
sccheck command
Command sccheck probes what github.com/go-freedesktop/screencast can capture on this machine, and proves it by capturing.
Command sccheck probes what github.com/go-freedesktop/screencast can capture on this machine, and proves it by capturing.
internal
x11

Jump to

Keyboard shortcuts

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