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
- Variables
- func Authorized() bool
- func Available() bool
- func Diagnose() error
- func PortalAvailable() (present bool, version uint32)
- func Probe() error
- func RequestAuthorization() bool
- type Application
- type Content
- type Display
- type Frame
- type Options
- type PixelFormat
- type Rect
- type SessionKind
- type Stats
- type Stream
- func (s *Stream) Close() error
- func (s *Stream) Converts() bool
- func (s *Stream) Err() error
- func (s *Stream) Frame() (Frame, bool)
- func (s *Stream) Options() Options
- func (s *Stream) Source() string
- func (s *Stream) Stats() Stats
- func (s *Stream) Transport() string
- func (s *Stream) WaitFrame(ctx context.Context) (Frame, error)
- type Window
Constants ¶
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.
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.
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.
const Backend = "X11"
Backend names the capture route in use.
Variables ¶
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 ¶
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 ¶
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 ¶
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 (*Content) MainDisplay ¶
MainDisplay returns the primary display, or the first one if none is flagged primary.
func (*Content) WindowsByTitle ¶
WindowsByTitle returns every window whose title is exactly title.
func (*Content) WindowsOfPID ¶
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 ¶
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.
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 ¶
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 ¶
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 ¶
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.
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 ¶
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.
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Options returns the stream's resolved options: every zero field replaced by the default that was actually used.
func (*Stream) Source ¶
Source names what is being captured, e.g. "display HDMI-1" or "window 0x1400007".
func (*Stream) Transport ¶
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 ¶
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.
Source Files
¶
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
|
|