Documentation
¶
Overview ¶
Package desktop is the RemoHop remote desktop. The host captures the screen and encodes it with an ffmpeg subprocess, AV1, HEVC or H.264 (GPU encoders when present, SVT-AV1, libx264, libx265 or libaom otherwise; 10-bit where the encoder and the viewer can), streams it over the P2P session, and injects the client's mouse and keyboard input (XTEST on X11, SendInput on Windows), relative movement included for a viewer that locks the mouse. A client that draws the mouse pointer itself gets it apart from the video, as a shape and a position (cursor.go), so that it moves at the local mouse's rate. A host without ffmpeg (the RemoHop phone apps) serves a provided screen instead (provided.go): native code encodes H.264 and injects input, and this package speaks the same protocol. The client side is a Go API (Open, Session, Probe, Recorder) and the `remohop <ID> desktop` command, which serves a WebCodecs browser viewer on loopback and can record the stream to MP4.
Index ¶
- Constants
- Variables
- func CheckScreen() (found, warning string, err error)
- func FFmpegInstalled() (ok bool, hint string)
- func FindFFmpeg() (ffmpeg.Found, error)
- type AVCInfo
- type AudioHello
- type AudioOptions
- type AudioPacket
- type AudioResult
- type AudioSession
- type BenchOptions
- type BenchResult
- type CodecSource
- type Config
- type Control
- type CursorShape
- type CursorState
- type CursorUpdate
- type DisplayInfo
- type Event
- type Frame
- type HEVCInfo
- type Hello
- type HostInfo
- type HostStats
- type InputEvent
- type InputSink
- type Latency
- type Options
- type ProvidedAudio
- type ProvidedAudioConfig
- type RealtimeStats
- type Recorder
- type Region
- type Reply
- type Screen
- func (sc *Screen) Close()
- func (sc *Screen) PushFrame(annexB []byte, capture int64) error
- func (sc *Screen) ScreenInfo() (width, height, rotation int)
- func (sc *Screen) Serve(ctx context.Context, c *peer.Conn, s peer.Stream, raw json.RawMessage) error
- func (sc *Screen) SetScreenInfo(width, height, rotation int)
- func (sc *Screen) Viewers() int
- type ScreenConfig
- type ScreenSource
- type SequenceInfo
- type Session
- func (s *Session) Ack(seq uint32) error
- func (s *Session) Blackout(ctx context.Context, on bool) error
- func (s *Session) BlockInput(ctx context.Context, on bool) error
- func (s *Session) Close() error
- func (s *Session) Configure(c Config) error
- func (s *Session) DecodeFailed(ctx context.Context, codec string) error
- func (s *Session) Done() <-chan struct{}
- func (s *Session) Err() error
- func (s *Session) Hello() Hello
- func (s *Session) HostToLocal(t time.Time) time.Time
- func (s *Session) LocalDrops() uint64
- func (s *Session) Lock(ctx context.Context) error
- func (s *Session) Next(ctx context.Context) (Event, error)
- func (s *Session) Privacy(ctx context.Context, on bool) error
- func (s *Session) RTT() time.Duration
- func (s *Session) Realtime() RealtimeStats
- func (s *Session) ReportBehind() error
- func (s *Session) RequestKeyframe() error
- func (s *Session) SendInput(ev InputEvent) error
- func (s *Session) SetCursor(on bool) error
- func (s *Session) SetDisplay(ctx context.Context, display int) error
- func (s *Session) SetRegion(x, y, w, h float64) error
- func (s *Session) SetTransport(ctx context.Context, transport string) error
- func (s *Session) SetViewOnly(on bool)
- func (s *Session) TypeText(ctx context.Context, text string) error
- func (s *Session) ViewOnly() bool
Constants ¶
const ( // PrivacyEndedLocked: the host's session was locked, logged off or // disconnected from the console. PrivacyEndedLocked = "locked" // PrivacyEndedSecure: the host showed a secure screen (the lock or // sign-in screen, Ctrl+Alt+Del, a UAC prompt). PrivacyEndedSecure = "secure" // PrivacyEndedQuiet: nothing was heard from the viewer for // privacyQuiet. PrivacyEndedQuiet = "quiet" )
Why the host ended privacy mode on its own (Hello.PrivacyEnded).
const ( CaptureAuto = "auto" CaptureCompatible = "compatible" )
Options.Capture and Hello.CaptureMode values.
const ( ControlType = "type" // type text ControlLock = "lock" // lock the screen ControlBlockInput = "block_input" // disable the physical keyboard and mouse ControlBlackout = "blackout" // hide the physical screen ControlCtrlAltDel = "ctrl_alt_del" // the secure attention sequence // ControlPrivacy is privacy mode: a cover on the physical screen that // the capture does not see, with local input blocked where the host // can (docs/design/privacy-mode.md). ControlPrivacy = "privacy" // ControlAllMonitors is the all-monitors view (DisplayAll). ControlAllMonitors = "all_monitors" )
Names of the host controls, as used in Hello.Unsupported.
const ( InputMove = "move" // X, Y InputButton = "button" // Button, Down (and X, Y) InputWheel = "wheel" // DX, DY in notches (positive: right/down) InputKey = "key" // Code, Down InputReleaseAll = "release_all" // release every key/button held // InputMoveBy moves the pointer by DX, DY host pixels from where it // is, like a mouse (a pointer locked by the client). Only for a host // whose Hello sets Relative. InputMoveBy = "move_by" )
Input event kinds (InputEvent.Kind and Control.Type).
const ( TransportAuto = "auto" TransportRealtime = "realtime" TransportStream = "stream" )
Transports, for Options.Transport and Hello.Transport.
const AudioServiceName = "desktop.audio"
AudioServiceName is the peer service for audio forwarding.
const CursorShapesKept = 32
CursorShapesKept is how many pointer shapes a client must keep, by ID: the host sends a shape again once it has sent this many others since.
const (
// DisplayAll selects every monitor at once; see Options.Display.
DisplayAll = -1
)
const ServiceName = "desktop"
ServiceName is the peer service the host registers.
const SettingUnattendedCapture = "unattended-capture"
SettingUnattendedCapture chooses how the Windows unattended-access service captures the screen (capture_session_windows.go).
const UnattendedCaptureEnv = "REMOHOP_UNATTENDED_CAPTURE"
UnattendedCaptureEnv overrides SettingUnattendedCapture.
Variables ¶
var AudioJS []byte
AudioJS plays the host's audio in a page (see audio.js): the viewer has it inlined, and the web console serves it. Read only.
var ErrNoCodecFallback = errors.New("desktop: the host cannot switch to another codec")
ErrNoCodecFallback is DecodeFailed's answer for a host that cannot switch codecs (one that predates it).
var ErrNoROI = errors.New("desktop: the host does not send regions of its screen")
ErrNoROI is SetRegion's answer for a host that does not take regions (Hello.ROI is false).
var ErrNoRelative = errors.New("desktop: the host does not take relative mouse input")
ErrNoRelative is returned by SendInput for relative input (InputMoveBy, InputEvent.Rel) to a host that does not take it (Hello.Relative).
var ErrNoTransport = errors.New("desktop: this session cannot switch the video's transport")
ErrNoTransport is SetTransport's answer for a host that predates real-time mode, or a session without datagrams.
var ErrViewOnly = errors.New("desktop: input is disabled on this session")
ErrViewOnly is returned by SendInput on a session without input.
var ErrWaitingForOwner = errors.New("waiting for the device's owner to allow screen sharing")
ErrWaitingForOwner is wrapped by a ScreenSource's StartScreen error when the screen cannot be captured until someone at the device allows it (Android's screen recording prompt, say).
var PointerJS []byte
PointerJS draws the host's pointer in a page and locks the mouse (see pointer.js): the viewer has it inlined, and the web console serves it. Read only.
Functions ¶
func CheckScreen ¶
CheckScreen looks for the screen a desktop session would capture, as a probe does, without capturing: what it found (for example "1920x1080, 2 monitors"), a warning about it, or why there is none (no X display, no permission, ...).
func FFmpegInstalled ¶
FFmpegInstalled reports whether this machine has ffmpeg (named by REMOHOP_FFMPEG, on PATH, or RemoHop's copy), which screen sharing needs, and if not, how to install it.
func FindFFmpeg ¶
FindFFmpeg is the ffmpeg screen sharing would use and where it comes from (ffmpeg.Find), or an error that says how to install it on this system.
Types ¶
type AVCInfo ¶
type AVCInfo struct {
Profile, Compat, Level byte
Width, Height int
// NALLength is the size in bytes of the length prefix of each NAL
// unit in a sample.
NALLength int
}
AVCInfo is what the viewer needs from an avcC record.
type AudioHello ¶
type AudioHello struct {
// Codec is "opus"; packets are plain Opus packets (RFC 6716), one per
// frame, decodable by WebCodecs AudioDecoder without a description.
Codec string `json:"codec"`
SampleRate int `json:"sample_rate"`
Channels int `json:"channels"`
FrameMS int `json:"frame_ms"`
Bitrate int `json:"bitrate"`
// Source says what is captured, for display.
Source string `json:"source"`
Warning string `json:"warning,omitempty"`
}
AudioHello describes the audio stream that follows.
func ProbeAudio ¶
ProbeAudio checks whether the host can forward its audio, without starting a stream that keeps running.
type AudioOptions ¶
type AudioOptions struct {
// Bitrate of the Opus stream in bits per second (default 96000).
Bitrate int `json:"bitrate,omitempty"`
// FrameMS is the Opus frame length: 10 or 20 (default); smaller is
// lower latency and costs bitrate.
FrameMS int `json:"frame_ms,omitempty"`
// Probe only checks that audio can be captured, then ends the stream
// after the AudioHello.
Probe bool `json:"probe,omitempty"`
}
AudioOptions is the client's request on the audio stream.
type AudioPacket ¶
type AudioPacket struct {
Seq uint32
// Capture is when the packet's first sample was captured, on the host's
// clock, the one video frames use (Session.HostToLocal converts it).
Capture time.Time
// Received is when it arrived here, on the local clock.
Received time.Time
// Data is one Opus packet (48 kHz; stereo from a computer, mono from a
// phone: Hello().Channels says which).
Data []byte
}
AudioPacket is one Opus packet of the host's audio.
type AudioResult ¶
type AudioResult struct {
Source string `json:"source"`
Packets int `json:"packets"`
BitrateKbps float64 `json:"bitrate_kbps"`
Latency Latency `json:"latency_capture_to_received"`
Dropped uint64 `json:"dropped"`
}
AudioResult is the audio half of a benchmark.
type AudioSession ¶
type AudioSession struct {
// contains filtered or unexported fields
}
AudioSession is an open audio stream from the host.
func OpenAudio ¶
func OpenAudio(ctx context.Context, conn *peer.Conn, o AudioOptions) (*AudioSession, error)
OpenAudio starts audio forwarding on conn and waits for the host to say it captures: a host without a way to capture its output, or with audio switched off, answers with an error that says why.
func (*AudioSession) Close ¶
func (a *AudioSession) Close() error
Close ends the stream; the host stops capturing.
func (*AudioSession) Done ¶
func (a *AudioSession) Done() <-chan struct{}
Done is closed when the stream ends; Err says why.
func (*AudioSession) Dropped ¶
func (a *AudioSession) Dropped() uint64
Dropped is how many packets were discarded because the caller was slow.
func (*AudioSession) Err ¶
func (a *AudioSession) Err() error
Err is why the stream ended (nil while it runs).
func (*AudioSession) Next ¶
func (a *AudioSession) Next(ctx context.Context) (AudioPacket, error)
Next returns the next packet.
type BenchOptions ¶
type BenchOptions struct {
// Duration of the measured period (default 10 s); Warmup before it
// (default 1.5 s) lets the clock-offset estimate settle and the
// encoder's start-up key frame pass.
Duration time.Duration
Warmup time.Duration
// Audio also measures audio forwarding.
Audio bool
}
BenchOptions control Bench.
type BenchResult ¶
type BenchResult struct {
Codec string `json:"codec"`
Encoder string `json:"encoder"`
Hardware bool `json:"hardware"`
Width int `json:"width"`
Height int `json:"height"`
Seconds float64 `json:"seconds"`
// RequestedFPS is the frame rate asked for; FPS what arrived.
RequestedFPS int `json:"requested_fps"`
Frames int `json:"frames"`
KeyFrames int `json:"key_frames"`
FPS float64 `json:"fps"`
// BitrateMbps is the video payload received, in megabits per second.
BitrateMbps float64 `json:"bitrate_mbps"`
// Latency is capture on the host to receipt here.
Latency Latency `json:"latency_capture_to_received"`
// HostPipelineMS is the host's own capture-to-encoded delay (mean of
// its reports), RTTMS the session's round-trip time.
HostPipelineMS float64 `json:"host_pipeline_ms"`
// HostCaptureMS and HostEncodeMS split it where frames go into the
// encoder (means of the host's reports; zero when the host does not
// say, as older hosts and an ffmpeg before 6.1 do not).
HostCaptureMS float64 `json:"host_capture_ms,omitempty"`
HostEncodeMS float64 `json:"host_encode_ms,omitempty"`
RTTMS float64 `json:"rtt_ms"`
HostDropped uint64 `json:"host_dropped"`
LocalDrops uint64 `json:"local_drops"`
// Restarts counts encoder restarts during the run (a stable run has
// none beyond start-up).
Restarts int `json:"encoder_restarts"`
// Transport is how the video travelled at the end; Realtime what
// arrived in real-time mode over the whole session.
Transport string `json:"transport,omitempty"`
Realtime RealtimeStats `json:"realtime"`
Audio *AudioResult `json:"audio,omitempty"`
}
BenchResult is what Bench measured.
func Bench ¶
func Bench(ctx context.Context, conn *peer.Conn, opts Options, bo BenchOptions) (BenchResult, error)
Bench measures a session with the host on conn.
func (BenchResult) String ¶
func (r BenchResult) String() string
String renders the result for people.
type CodecSource ¶
type CodecSource interface {
SetScreenCodec(codec string)
}
CodecSource is implemented by a ScreenSource that can encode more than H.264. The hub calls SetScreenCodec (codec is "h264" or "hevc") before the StartScreen that must produce that codec.
type Config ¶
type Config struct {
FPS int
Bitrate int64
MaxHeight int
Scale float64
// Display switches to another monitor (see Options.Display; DisplayAll
// shows every monitor); nil keeps the current one.
Display *int
// TenBit switches 10-bit video on or off (see Hello.TenBitAvailable);
// nil keeps it as it is.
TenBit *bool
// Capture switches the capture (see Options.Capture; CaptureAuto for
// the host's choice) on a host whose Hello sets CaptureMode; ""
// keeps it.
Capture string
}
Config changes encoding parameters mid-session; zero fields keep the current value. The host restarts the encoder to apply it.
type Control ¶
type Control struct {
Type string `json:"type"`
// ID, when not zero, makes the host answer with a Reply.
ID uint32 `json:"id,omitempty"`
Seq uint32 `json:"seq,omitempty"` // ack
T int64 `json:"t,omitempty"` // ping: client clock, echoed
// Dropped, on an ack: the frame was not consumed but given up (lost on
// the way, or dropped for want of a key frame after one was), so the
// time the ack took says nothing about the path. Older hosts ignore it.
Dropped bool `json:"dropped,omitempty"`
// config
FPS int `json:"fps,omitempty"`
Bitrate int64 `json:"bitrate,omitempty"`
MaxHeight int `json:"max_height,omitempty"`
Scale float64 `json:"scale,omitempty"`
Display *int `json:"display,omitempty"`
TenBit *bool `json:"ten_bit,omitempty"`
Capture string `json:"capture,omitempty"`
// decode_error: the codec string of the stream the client failed to
// decode.
Codec string `json:"codec,omitempty"`
// transport: the transport wanted (Options.Transport); rt_report:
// what arrived.
Transport string `json:"transport,omitempty"`
RT *rtReport `json:"rt,omitempty"`
// roi: the region wanted, in host screen pixels (X, Y and these); W
// 0 asks for the whole screen.
W float64 `json:"w,omitempty"`
H float64 `json:"h,omitempty"`
// host controls
Text string `json:"text,omitempty"` // type
On bool `json:"on,omitempty"` // block_input, blackout, privacy
// input; see InputEvent
X float64 `json:"x,omitempty"`
Y float64 `json:"y,omitempty"`
Button int `json:"button,omitempty"`
Down bool `json:"down,omitempty"`
DX float64 `json:"dx,omitempty"`
DY float64 `json:"dy,omitempty"`
Code string `json:"code,omitempty"`
Rel bool `json:"rel,omitempty"`
}
Control is one client -> host message. Type selects which fields matter.
type CursorShape ¶
type CursorShape struct {
// ID names the shape for the rest of the session; it is never 0.
ID uint32 `json:"id"`
Width int `json:"width"`
Height int `json:"height"`
// HotX, HotY is the hotspot: the pixel of the image that is the
// pointer's position.
HotX int `json:"hot_x"`
HotY int `json:"hot_y"`
// PNG is the image, Width x Height host pixels, with alpha.
PNG []byte `json:"png"`
}
CursorShape is one image of the host's mouse pointer.
type CursorState ¶
type CursorState struct {
// ID is the current shape; 0 when it is unknown (draw a default
// arrow) or the pointer is hidden.
ID uint32 `json:"id"`
// X, Y is the hotspot's position in host pixels from the captured
// area's top-left (Hello.ScreenWidth x ScreenHeight). It lies outside
// that area when the pointer is on another monitor.
X int `json:"x"`
Y int `json:"y"`
// Visible is false while the pointer is hidden: a game or a video
// player hid it, or an application shows an empty pointer.
Visible bool `json:"visible"`
}
CursorState is where the host's pointer is and how it looks.
type CursorUpdate ¶
type CursorUpdate struct {
// Shapes are images not delivered before, oldest first. Keep at
// least the last CursorShapesKept of them: states name them by ID.
Shapes []CursorShape
// State is the latest position, shape and visibility.
State CursorState
}
CursorUpdate is what changed about the host's pointer (Event.Cursor).
type DisplayInfo ¶
type DisplayInfo struct {
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
}
DisplayInfo is one monitor of the host, in screen pixels.
type Event ¶
type Event struct {
// Hello announces new stream parameters (after an encoder restart);
// the frames that follow use them, starting with a key frame.
Hello *Hello
Frame *Frame
Stats *HostStats
// Cursor is the host's pointer, for a session opened with
// Options.Cursor while the latest Hello has Cursor set. Updates are
// coalesced: a client that falls behind gets the latest state with
// every shape it has not had yet.
Cursor *CursorUpdate
}
Event is one item from Session.Next: exactly one field is set.
type Frame ¶
type Frame struct {
Seq uint32
Key bool // starts with a sequence header and a key frame
// PTS is the presentation time since the session started.
PTS time.Duration
// Capture is when the host captured the frame, on the host's clock
// (zero if the capture device has no wall-clock timestamps). Use
// Session.HostToLocal to compare it with local time.
Capture time.Time
// Sent is when the host sent the frame, on the host's clock.
Sent time.Time
// Received is when it arrived here, on the local clock.
Received time.Time
Data []byte
}
Frame is one AV1 temporal unit, ready for a decoder (WebCodecs EncodedVideoChunk, ffmpeg, dav1d, ...).
type HEVCInfo ¶
type HEVCInfo struct {
ProfileSpace int // general_profile_space
HighTier bool
Profile int // general_profile_idc: 1 Main, 2 Main 10
// Compat is general_profile_compatibility_flags as stored, flag 0 in
// the most significant bit; Constraints the six bytes of constraint
// flags.
Compat uint32
Constraints [6]byte
Level int // general_level_idc, 30 times the level number
Width int
Height int
BitDepth int
// NALLength is the size in bytes of the length prefix of each NAL
// unit in a sample.
NALLength int
}
HEVCInfo is what the viewer needs from an hvcC record.
func (HEVCInfo) Codec ¶
Codec is the WebCodecs / RFC 6381 codec string (ISO 14496-15 annex E), e.g. hvc1.1.6.L93.90 for Main at level 3.1: the profile (with its space as a letter), the compatibility flags in reverse bit order in hex, the tier and level, and the constraint bytes without the trailing zeros.
type Hello ¶
type Hello struct {
Width int `json:"width"`
Height int `json:"height"`
FPS int `json:"fps"`
Bitrate int64 `json:"bitrate"`
// Codec is the WebCodecs codec string: av01.P.LLT.DD for AV1,
// avc1.PPCCLL for H.264, hvc1.P.C.TLL.CC for HEVC.
Codec string `json:"codec"`
// CodecConfig is the codec's MP4 configuration record: av1C for AV1,
// avcC for H.264, hvcC for HEVC (for the last two also the WebCodecs
// "description" that makes a decoder take length-prefixed NAL units).
CodecConfig []byte `json:"codec_config,omitempty"`
// BitDepth is 10 for a 10-bit stream; 0 means 8.
BitDepth int `json:"bit_depth,omitempty"`
// TenBitAvailable says the session can switch to 10-bit (or is
// 10-bit): the encoder can and the client decodes the codec at 10
// bits. A config control with TenBit switches.
TenBitAvailable bool `json:"ten_bit_available,omitempty"`
// CodecFallback says the host takes the "decode_error" control (see
// "Decoder failure" above). Older hosts do not set it.
CodecFallback bool `json:"codec_fallback,omitempty"`
Encoder string `json:"encoder"`
// Hardware is true for GPU encoders.
Hardware bool `json:"hardware"`
// ScreenWidth/ScreenHeight are the captured area in host pixels, when
// the host knows them.
ScreenWidth int `json:"screen_width,omitempty"`
ScreenHeight int `json:"screen_height,omitempty"`
// Input reports whether the host accepts input on this session;
// InputError says why not. It can change during the session: when
// the host's owner switches keyboard and mouse off, the host releases
// whatever the client holds, ignores input from then on and sends a
// new Hello with Input false; switched back on, another Hello brings
// input back.
Input bool `json:"input"`
InputError string `json:"input_error,omitempty"`
// Warning is a non-fatal problem worth showing (e.g. capturing an
// XWayland display).
Warning string `json:"warning,omitempty"`
// Display is the monitor requested (see Options.Display) and Displays
// the host's monitors, when it knows them. AllDisplays is true when the
// picture covers every monitor, however that was requested.
Display int `json:"display"`
Displays []DisplayInfo `json:"displays,omitempty"`
AllDisplays bool `json:"all_displays,omitempty"`
// Unsupported maps the host controls (Control* names) that this host
// cannot offer to the reason why.
Unsupported map[string]string `json:"unsupported,omitempty"`
// Generation counts encoder (re)starts.
Generation int `json:"generation"`
// Cursor is true when the video of this generation leaves the mouse
// pointer out and the host sends it in 'C' frames instead, for a
// client that asked with Options.Cursor. ScreenWidth and ScreenHeight
// are then set: cursor positions and images are in those pixels.
Cursor bool `json:"cursor,omitempty"`
// Relative is true when the host takes relative pointer movement
// (InputMoveBy) and buttons that act where the pointer is (Rel).
Relative bool `json:"relative,omitempty"`
// Transport is how the video is sent now: TransportRealtime (as
// datagrams) or TransportStream. A host that sets it takes the
// "transport" and "rt_report" controls; an older host leaves it empty
// and streams.
Transport string `json:"transport,omitempty"`
// ROI says the host takes the "roi" control (see "Regions" above).
// Older hosts never set it.
ROI bool `json:"roi,omitempty"`
// CaptureMode, set by a host with more than one way to capture the
// screen (the Windows unattended-access service with
// Desktop Duplication), is the capture the client chose: CaptureAuto
// or CaptureCompatible. Such a host takes Config.Capture; older hosts
// and hosts without a choice leave it empty.
CaptureMode string `json:"capture_mode,omitempty"`
// Privacy says the host takes the "privacy" control on this session
// (privacy mode; it is false whenever Unsupported names it). Older
// hosts never set it. PrivacyOn says the cover is up for this session;
// a host that drops it on its own (the owner switched input off) says
// so in the Hello that follows.
Privacy bool `json:"privacy,omitempty"`
PrivacyOn bool `json:"privacy_on,omitempty"`
// PrivacyEnded, in the first Hello after the host ended this
// session's privacy mode on its own, says why: PrivacyEndedLocked,
// PrivacyEndedSecure or PrivacyEndedQuiet (others may come; show a
// general message for those).
PrivacyEnded string `json:"privacy_ended,omitempty"`
// Region, when set, is the part of the screen the frames after this
// Hello show, in host screen pixels: that part scaled to Width x
// Height. nil means the whole screen.
Region *Region `json:"region,omitempty"`
}
Hello describes the video stream that follows.
type HostInfo ¶
type HostInfo struct {
OS string `json:"os"`
// ScreenWidth/ScreenHeight are the whole screen in pixels (0 if the
// host does not know); Displays are its monitors, when known.
ScreenWidth int `json:"screen_width,omitempty"`
ScreenHeight int `json:"screen_height,omitempty"`
Displays []DisplayInfo `json:"displays,omitempty"`
// Encoders maps each codec the host can encode ("av1", "hevc",
// "h264") to the encoder it would use.
Encoders map[string]string `json:"encoders"`
// Input reports whether a session could send input; InputError says
// why not.
Input bool `json:"input"`
InputError string `json:"input_error,omitempty"`
// Unsupported maps the controls this host cannot offer to the reason.
Unsupported map[string]string `json:"unsupported,omitempty"`
Warning string `json:"warning,omitempty"`
}
HostInfo is the answer to a probe: what a session on this host would offer, without starting one.
type HostStats ¶
type HostStats struct {
FPS float64 `json:"fps"` // frames sent per second
Bitrate int64 `json:"bitrate"` // current encoder target, bits/s
SendRate int64 `json:"send_rate"` // bits/s actually sent
Dropped uint64 `json:"dropped"` // frames dropped so far
InFlight int `json:"in_flight"` // unacknowledged frames
PipelineMS float64 `json:"pipeline_ms"` // capture -> encoded, when known
Restarts int `json:"restarts"` // encoder restarts so far
// RestartWhy is why the running encoder was started (the session's
// start, a lower frame rate on congestion, a probe back up, ...), in
// English; older hosts leave it out.
RestartWhy string `json:"restart_why,omitempty"`
// CaptureMS and EncodeMS split PipelineMS where the frame goes into
// the encoder: capture, colour conversion and scaling up to there,
// and the encoder from there (zero when the host cannot tell; older
// hosts never set them).
CaptureMS float64 `json:"capture_ms,omitempty"`
EncodeMS float64 `json:"encode_ms,omitempty"`
// ForcedKeys counts the key frames the running encoder was asked for
// (served without a restart, see keyforce.go).
ForcedKeys int `json:"forced_keys,omitempty"`
// AckMS is the smoothed time from sending a frame to its ack (round
// trip plus the viewer's decode), WindowMS how much video may be
// unacknowledged (see flow.go).
AckMS float64 `json:"ack_ms,omitempty"`
// Paused says why the host cannot capture its screen right now (the
// session goes on and the picture resumes when it can; "" otherwise).
// On Windows: the secure desktop of a UAC prompt, the lock screen or
// Ctrl+Alt+Del, which only the unattended service can capture.
Paused string `json:"paused,omitempty"`
// PrivacyEnded, once, says the host ended this session's privacy
// mode on its own and why (as Hello.PrivacyEnded, which a host that
// sends it here leaves out of the next Hello). It comes in a stats
// frame sent at once, not with the next Hello: a Hello waits for the
// next key frame, which a capture restarting on Windows' secure
// desktop can hold up for seconds.
PrivacyEnded string `json:"privacy_ended,omitempty"`
// WaitingOwner is set with Paused when the screen waits for someone
// at the host to allow it (a phone whose owner has not yet accepted
// the system's screen recording prompt). Older clients ignore it.
WaitingOwner bool `json:"waiting_owner,omitempty"`
WindowMS float64 `json:"window_ms,omitempty"`
// Transport is the video's transport now (TransportRealtime or
// TransportStream; "" from an older host). In real-time mode LossPct
// is the share of shards the client reports lost (smoothed) and
// FECPct the parity the host adds to the data, both in percent.
Transport string `json:"transport,omitempty"`
LossPct float64 `json:"loss_pct,omitempty"`
FECPct float64 `json:"fec_pct,omitempty"`
// Capture names how the screen is captured ("ddagrab", "gdigrab",
// "console-session helper (GDI)"); FramesTotal is the frames sent
// in the session so far; RestartCounts counts the encoder restarts by
// cause (RestartWhy without its numbers). Older hosts leave them out.
Capture string `json:"capture,omitempty"`
FramesTotal uint64 `json:"frames_total,omitempty"`
RestartCounts map[string]int `json:"restart_counts,omitempty"`
// The frame rate in place (rate.go): RateInPlace says the running
// encoder takes frame rates by command (its filter chain is one where
// that is known to work), PassesFPS is the frame rate it is held to
// below the one it was started for (0: it codes every frame),
// RateChanges how often the frame rate was changed without a restart
// so far, and RateWhy why it last was. Older hosts leave them out.
RateInPlace bool `json:"rate_in_place,omitempty"`
PassesFPS int `json:"passes_fps,omitempty"`
RateChanges int `json:"rate_changes,omitempty"`
RateWhy string `json:"rate_why,omitempty"`
// From a capture that times itself (the unattended service's
// console-session helper), over its last second or so: captures a
// second (CapFPS) and how many of them changed (CapChangedFPS), the
// average capture (GrabMS), the time a frame takes from the capture
// to ffmpeg's input (PipeMS: the pipe from the helper, then the write
// into ffmpeg), and frames not fed to ffmpeg because a newer one came
// first (CapDropped).
CapFPS float64 `json:"cap_fps,omitempty"`
CapChangedFPS float64 `json:"cap_changed_fps,omitempty"`
GrabMS float64 `json:"grab_ms,omitempty"`
PipeMS float64 `json:"pipe_ms,omitempty"`
CapDropped int `json:"cap_dropped,omitempty"`
}
HostStats is the host's periodic report.
type InputEvent ¶
type InputEvent struct {
Kind string
// X, Y are the pointer position as fractions of the video frame, 0..1
// from the top-left, so they stay valid whatever the scaling.
X, Y float64
// Button follows DOM MouseEvent.button: 0 left, 1 middle, 2 right,
// 3 back, 4 forward.
Button int
Down bool
// DX, DY are wheel notches (positive scrolls right/down), or for
// InputMoveBy the movement in host pixels (positive: right/down).
DX, DY float64
// Code is a DOM KeyboardEvent.code value such as "KeyA" or "ShiftLeft".
Code string
// Rel makes a button act where the pointer is, without moving it to
// X, Y first (a pointer locked by the client). Only for a host whose
// Hello sets Relative.
Rel bool
}
InputEvent is one pointer or keyboard event.
type InputSink ¶
type InputSink interface {
// can), e.g. that the accessibility service is off. It is asked about
// once a second while a session is open, and when one starts.
Unavailable() string
// Inject delivers one pointer or keyboard event.
Inject(ev InputEvent) error
// TypeText enters text into whatever has the focus.
TypeText(text string) error
// ReleaseAll lets go of anything held down (a session ended or lost
// control in the middle of a gesture).
ReleaseAll()
}
InputSink delivers the input of sessions that may control the device. Its methods are called from session goroutines, one at a time per session.
type Latency ¶
type Latency struct {
N int `json:"n"`
Mean float64 `json:"mean_ms"`
P50 float64 `json:"p50_ms"`
P95 float64 `json:"p95_ms"`
Max float64 `json:"max_ms"`
}
Latency summarises a set of latencies in milliseconds.
type Options ¶
type Options struct {
// FPS is the requested frame rate (default 60, max 240). A software
// encoder that cannot keep up makes the host lower it.
FPS int `json:"fps,omitempty"`
// Bitrate in bits per second; 0 picks one from resolution and frame
// rate and lets the host adapt it to the link.
Bitrate int64 `json:"bitrate,omitempty"`
// MaxHeight downscales (keeping the aspect ratio) so the video is at
// most this many pixels high. 0 keeps the native size.
MaxHeight int `json:"max_height,omitempty"`
// Scale downscales by a factor in (0, 1]. 0 means 1.
Scale float64 `json:"scale,omitempty"`
// Display selects a monitor: DisplayAll (-1) is every monitor in one
// picture (the virtual desktop), 0 the host's default (X11: the entire
// root window, which is every monitor; Windows/macOS: the primary
// display), N >= 1 the Nth monitor of HostInfo.Displays.
Display int `json:"display,omitempty"`
// ViewOnly asks the host not to accept input on this session.
ViewOnly bool `json:"view_only,omitempty"`
// Encoder forces a specific ffmpeg encoder (e.g. "libsvtav1") instead
// of the host's automatic choice.
Encoder string `json:"encoder,omitempty"`
// Codec restricts the video codec to "av1", "hevc" or "h264"; empty
// lets the host choose (AV1 with a GPU AV1 encoder, else HEVC with a
// GPU HEVC encoder, else H.264; software AV1 or HEVC only for a viewer
// that decodes nothing else). A host that predates HEVC refuses "hevc".
Codec string `json:"codec,omitempty"`
// Decode lists the codecs the viewer can decode, of "av1" and "h264"
// only (see "Codecs" above); empty means both. The host never picks a
// codec outside it.
Decode []string `json:"decode,omitempty"`
// Codecs lists every codec the viewer can decode, "hevc" included. A
// host that knows it uses it instead of Decode. SetDecodable fills
// both.
Codecs []string `json:"codecs,omitempty"`
// Codecs10 lists the codecs the viewer decodes at 10 bits per sample
// (HEVC Main 10, AV1 Main at 10 bits). With TenBit and no list, any.
Codecs10 []string `json:"codecs_10bit,omitempty"`
// TenBit asks for 10-bit video where the encoder and the viewer allow
// it (see "10-bit" above); off by default.
TenBit bool `json:"ten_bit,omitempty"`
// Probe asks only for the host's HostInfo; see Probe.
Probe bool `json:"probe,omitempty"`
// Cursor says the client draws the mouse pointer itself: the host may
// then leave it out of the video and send its shape and position
// instead (Hello.Cursor says whether it does).
Cursor bool `json:"cursor,omitempty"`
// Transport is how the client wants the video sent: TransportAuto
// (the default: as datagrams where the path carries them),
// TransportRealtime (as datagrams wherever the session has them) or
// TransportStream (on the stream). See realtime.go.
Transport string `json:"transport,omitempty"`
// Capture is how the client wants the screen captured: "" or
// CaptureAuto for the host's choice, CaptureCompatible for its most
// compatible capture (slower, but where the host's faster one shows
// a wrong picture or none). Only a host whose Hello sets CaptureMode
// has a choice; the others ignore it.
Capture string `json:"capture,omitempty"`
// RealtimeID, when not zero, says the client receives video
// datagrams on this session and names its stream in them. Open sets
// it; it is not for applications to choose.
RealtimeID uint32 `json:"rt_id,omitempty"`
// ManualAck makes the client application acknowledge frames itself
// with Session.Ack (the browser viewer acks after decoding). By default
// Session.Next acknowledges each frame it returns. Not sent to the host.
ManualAck bool `json:"-"`
// Waiting, if not nil, is called (from the session's reader) with each
// report the host sends before its first Hello: while it cannot start
// its screen yet, it says why in Paused, and WaitingOwner when someone
// at the host must still allow it. Open may wait a long time then;
// this lets an application say what it waits for. Not sent to the
// host; it must not block.
Waiting func(HostStats) `json:"-"`
}
Options is the client's request: what to capture and how to encode it. Zero values mean "host default".
func (*Options) SetDecodable ¶
SetDecodable records what the viewer decodes: codecs (any of "av1", "hevc", "h264") and, of those, the ones it decodes at 10 bits. It fills Codecs, and Decode for hosts that predate HEVC (see "Codecs" above). Unknown names and repeats are left out.
type ProvidedAudio ¶
type ProvidedAudio struct {
// contains filtered or unexported fields
}
ProvidedAudio is the hub.
func NewProvidedAudio ¶
func NewProvidedAudio(cfg ProvidedAudioConfig) *ProvidedAudio
NewProvidedAudio makes a hub with no listeners.
func (*ProvidedAudio) CloseAll ¶
func (p *ProvidedAudio) CloseAll(err error)
CloseAll ends every stream with an 'E' frame carrying err, and makes new requests fail with it until Reopen.
func (*ProvidedAudio) Listeners ¶
func (p *ProvidedAudio) Listeners() int
Listeners is the number of viewers subscribed.
func (*ProvidedAudio) Push ¶
func (p *ProvidedAudio) Push(data []byte, captured time.Time)
Push hands the hub one Opus packet captured at the given time (the zero time: now). The bytes are copied once. It never blocks, and returns at once when nobody listens.
func (*ProvidedAudio) Reopen ¶
func (p *ProvidedAudio) Reopen()
Reopen lets new requests in again after CloseAll.
type ProvidedAudioConfig ¶
type ProvidedAudioConfig struct {
// Channels is the channel count of the pushed Opus packets (default 1).
Channels int
// Source is what the hello says is captured (default "phone microphone").
Source string
// Ready, if set, says whether the source could start now; a probe is
// answered with its error.
Ready func() error
// Start is called when the first listener arrives, with the frame
// length the listener asked for; an error is sent to that listener and
// refuses it. Stop is called when the last one leaves. Calls are
// serialised and must not block for long.
Start func(channels, frameMS int) error
Stop func()
}
ProvidedAudioConfig configures a ProvidedAudio.
type RealtimeStats ¶
type RealtimeStats struct {
// Transport is the one the host uses now: TransportRealtime or
// TransportStream ("" for a host that predates real-time mode).
Transport string `json:"transport,omitempty"`
// Frames that came as datagrams, and of those the ones parity had to
// rebuild; frames lost on the way; shards received and expected (of
// frames that are complete or given up).
Frames uint64 `json:"frames"`
Recovered uint64 `json:"recovered"`
Lost uint64 `json:"lost"`
Shards uint64 `json:"shards"`
Expected uint64 `json:"expected"`
}
RealtimeStats is what the client saw of real-time video.
func (RealtimeStats) LossPct ¶
func (r RealtimeStats) LossPct() float64
LossPct is the share of shards lost, in percent.
type Recorder ¶
type Recorder struct {
// contains filtered or unexported fields
}
Recorder saves a session's video to MP4 on the client exactly as it arrives: the AV1, HEVC or H.264 frames are remuxed, never re-encoded.
The file is a fragmented MP4: an ftyp and a moov that describe the one video track (sample entry av01 with av1C, avc1 with avcC, or hev1 with hvcC: hev1, as encoders also repeat the parameter sets in band) and declare no samples, then one moof+mdat fragment per frame carrying its decode time, duration, size and sync flag. Nothing has to be patched when the recording ends, so a file is complete after every frame: stopping, exiting and being killed all leave a playable recording that at worst lacks its last frame.
A recording starts at the first key frame. Timestamps are the frames' presentation times (the host's capture clock), so the recording keeps the session's real pace, including pauses where frames were dropped. When the stream changes shape mid-recording (another resolution or codec: a quality preset, another monitor), an MP4 track cannot follow, so the recorder finishes the file and continues in a new one next to it, named NAME-2.mp4, NAME-3.mp4, ...; an encoder restart with unchanged parameters stays in the same file.
func NewRecorder ¶
NewRecorder creates the recording file, readable by its owner only. It refuses to replace an existing file unless force is set.
func (*Recorder) Close ¶
Close finishes the recording. A recording that never saw a key frame leaves an empty file, which is removed.
func (*Recorder) SetStream ¶
SetStream tells the recorder the parameters of the frames that follow; call it with the session's Hello, and again with every new one.
func (*Recorder) WriteFrame ¶
WriteFrame records one frame. Frames before the first key frame (and after a stream change, up to its key frame) are skipped.
type Region ¶
Region is a rectangle of the host's screen, in pixels from the captured area's top-left.
type Reply ¶
type Reply struct {
ID uint32 `json:"id"`
Type string `json:"type"`
Error string `json:"error,omitempty"`
}
Reply is the host's answer to a control sent with an id.
type Screen ¶
type Screen struct {
// contains filtered or unexported fields
}
Screen is a provided screen: the hub between one ScreenSource and the sessions watching it.
func NewScreen ¶
func NewScreen(cfg ScreenConfig) *Screen
NewScreen makes a provided screen. Serve it as the desktop service.
func (*Screen) Close ¶
func (sc *Screen) Close()
Close ends every session of the screen and stops the source. A closed screen refuses new sessions.
func (*Screen) PushFrame ¶
PushFrame takes one encoder output buffer: H.264 in Annex B form, either parameter sets alone (a codec-config buffer) or an access unit, which may carry the parameter sets in front. capture is when the picture was captured, in Unix microseconds (0 if unknown). The data is copied.
func (*Screen) ScreenInfo ¶
ScreenInfo is what SetScreenInfo last reported.
func (*Screen) Serve ¶
func (sc *Screen) Serve(ctx context.Context, c *peer.Conn, s peer.Stream, raw json.RawMessage) error
Serve is the desktop service handler for this screen.
func (*Screen) SetScreenInfo ¶
SetScreenInfo reports the screen's size in pixels and its rotation in degrees. The source calls it when the screen turns or changes size (and then restarts its encoder, whose new SPS starts a new stream).
type ScreenConfig ¶
type ScreenConfig struct {
Source ScreenSource
// Input, if not nil, takes the input of sessions allowed to control.
Input InputSink
// Encoder names the encoder in the Hello (e.g. "android-mediacodec").
Encoder string
// OS is reported in probes; empty means runtime.GOOS.
OS string
// MaxSize caps the long edge of the picture (default 1920); MaxFPS the
// frame rate (default 60); MaxBitrate the automatic bitrate (default
// 16 Mbit/s).
MaxSize int
MaxFPS int
MaxBitrate int64
// Codecs lists the codecs the source can encode, in the desktop
// protocol's names (empty: H.264 only). The hub picks HEVC while every
// viewer decodes it, and falls back to H.264 otherwise.
Codecs []string
Logger *slog.Logger
}
ScreenConfig configures NewScreen.
type ScreenSource ¶
type ScreenSource interface {
// StartScreen starts capturing and encoding, or applies new limits to
// the running encoder (restarting it if it must): the picture's long
// edge at most maxSize pixels (0: as large as the screen), at most fps
// frames per second, aiming at bitrate bits per second. The encoded
// frames come back through Screen.PushFrame. An error means the screen
// cannot be captured now (its owner has not allowed it, for example);
// the sessions report it and ask again a little later. An error that
// wraps ErrWaitingForOwner says that someone at the device must still
// allow it, which viewers are told (HostStats.WaitingOwner).
StartScreen(maxSize, fps int, bitrate int64) error
// StopScreen stops capturing: nobody watches any more.
StopScreen()
// RequestKeyframe asks for an IDR frame (with its SPS and PPS) soon.
RequestKeyframe()
// SetBitrate changes the target bitrate without restarting.
SetBitrate(bitrate int64)
}
ScreenSource is the native side of a provided screen. Its methods are called from the sessions' goroutines, one at a time; they must not block for long (they run on the session's control path).
type SequenceInfo ¶
type SequenceInfo struct {
Profile int
Level int // seq_level_idx of operating point 0
Tier int // 0 main, 1 high
BitDepth int
Mono bool
// SubX, SubY and ChromaPos are the chroma subsampling (both true for
// 4:2:0) and chroma_sample_position.
SubX, SubY bool
ChromaPos int
Width int // max_frame_width
Height int // max_frame_height
// ReducedStill is reduced_still_picture_header; it changes how frame
// headers are laid out.
ReducedStill bool
}
SequenceInfo is what the viewer needs from an AV1 sequence header.
func (SequenceInfo) Codec ¶
func (s SequenceInfo) Codec() string
Codec is the WebCodecs / ISO-BMFF codec string, av01.P.LLT.DD.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is an open remote-desktop stream.
func Open ¶
Open starts a remote-desktop stream on conn and waits for the host's first Hello (so capture and encoder errors surface here).
func (*Session) Ack ¶
Ack tells the host the frame seq (and everything before it) has been consumed. Only needed with Options.ManualAck.
func (*Session) Blackout ¶
Blackout hides (or shows again) the host's physical screen. Hosts that cannot do it return an error saying so; see Hello.Unsupported.
func (*Session) BlockInput ¶
BlockInput disables (or re-enables) the host's physical keyboard and mouse while the session controls it. Hosts that cannot do it return an error saying so; see Hello.Unsupported.
func (*Session) Configure ¶
Configure changes encoding parameters; zero fields keep their value, a negative Bitrate returns to automatic bitrate and a negative MaxHeight removes the height limit. The host restarts its encoder to apply it.
func (*Session) DecodeFailed ¶
DecodeFailed tells the host that the viewer cannot decode the stream whose codec string is codec (Hello.Codec). The host goes back to 8 bits if that stream was 10-bit, or else moves to the next codec the viewer decodes, and follows with a new Hello; an error means it has nothing else to offer and the stream goes on as it was.
func (*Session) Done ¶
func (s *Session) Done() <-chan struct{}
Done is closed when the stream ends.
func (*Session) HostToLocal ¶
HostToLocal converts a host-clock time to the local clock using the session's running clock-offset estimate.
func (*Session) LocalDrops ¶
LocalDrops is how many frames were dropped because the caller fell behind.
func (*Session) Next ¶
Next returns the next event. Video is dropped locally (up to the next key frame) rather than queued when the caller falls behind, so a slow caller sees gaps, never growing latency. Unless Options.ManualAck is set, each returned frame is acknowledged to the host.
func (*Session) Privacy ¶ added in v1.0.12
Privacy switches privacy mode on or off: the host's physical screen is covered (the stream still shows the desktop) and its local keyboard and mouse are blocked where the host can. Only a host whose Hello sets Privacy offers it; others return an error saying why. Switching it off is allowed even in view-only mode, and the host switches it off by itself when the session ends.
func (*Session) Realtime ¶
func (s *Session) Realtime() RealtimeStats
Realtime reports what arrived in real-time mode, and the transport the host uses now.
func (*Session) ReportBehind ¶
ReportBehind tells the host the consumer (a decoder that cannot keep up) is skipping to the next key frame, so it sends one and slows down.
func (*Session) RequestKeyframe ¶
RequestKeyframe asks for a key frame soon (decoder error, joining late).
func (*Session) SendInput ¶
func (s *Session) SendInput(ev InputEvent) error
SendInput injects a pointer or keyboard event on the host.
func (*Session) SetCursor ¶
SetCursor asks the host to leave the pointer out of the video and send it as Event.Cursor (on), or to draw it into the video again (off), for a session opened with Options.Cursor. The host restarts its encoder for it; the next Hello says what it does. A host that cannot read its pointer keeps drawing it.
func (*Session) SetDisplay ¶
SetDisplay switches the stream to another of the host's monitors (0: the host's default, DisplayAll: every monitor in one picture) and waits for the host to accept it; the new picture follows with a new Hello.
func (*Session) SetRegion ¶
SetRegion asks the host to show only the region x, y, w, h of its screen, in host screen pixels, at up to full resolution; w 0 asks for the whole screen again (see "Regions" in protocol.go). It returns at once: the Hello whose Region says what the frames show comes before the first frame of the new region. A viewer that zooms calls it at most a few times a second.
func (*Session) SetTransport ¶
SetTransport switches the video to another transport (TransportAuto, TransportRealtime or TransportStream; see realtime.go) and waits for the host to accept it. HostStats.Transport and Realtime().Transport follow.
func (*Session) SetViewOnly ¶
SetViewOnly switches input off or back on at run time. It cannot switch input on for a session that was opened view-only or while the host takes no input: see Hello.Input.
Source Files
¶
- adapt.go
- annexb.go
- audio.go
- audio_client.go
- audio_devices.go
- audio_linux.go
- audio_loopback.go
- audio_sck.go
- bench.go
- browser.go
- capture.go
- capture_change.go
- capture_choice_other.go
- capture_hub.go
- capture_orphans_other.go
- check.go
- cli.go
- client.go
- color.go
- control_linux.go
- controls_hook.go
- cursor.go
- cursor_linux.go
- cursor_mac.go
- doc.go
- encoder.go
- encstats.go
- failures.go
- fec.go
- ffmpeg_version.go
- flow.go
- h264.go
- hevc.go
- host.go
- injector.go
- ivf.go
- keyforce.go
- keyforce_other.go
- keymap.go
- mkvpipe.go
- mp4.go
- obu.go
- ogg.go
- pathctl.go
- privacy.go
- proc_linux.go
- proc_unix.go
- protocol.go
- provided.go
- provided_audio.go
- rate.go
- rateprobe.go
- realtime.go
- roi.go
- rtrecv.go
- rtsend.go
- sck_picture.go
- secure_other.go
- stall.go
- unattended_capture.go
- viewer.go
- viewer_extra.go
- vt_other.go
- wayland_input_linux.go
- wayland_linux.go
- x11_linux.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package h264test makes synthetic H.264 elementary streams in Annex B form for tests of the provided-screen path (internal/svc/desktop's Screen and the mobile host mode): a real SPS that parses to the size asked for, a PPS, and slice NAL units whose payload is filler.
|
Package h264test makes synthetic H.264 elementary streams in Annex B form for tests of the provided-screen path (internal/svc/desktop's Screen and the mobile host mode): a real SPS that parses to the size asked for, a PPS, and slice NAL units whose payload is filler. |