selkies-ws-core
WebSocket streaming core: the page-side half of the WebSocket transport,
started by selkies-core.js when the stored stream mode is websockets.
One socket at <route prefix>/api/websockets carries the whole session. It
is read in a worker (SOCKET_WORKER_SRC, reached through
WorkerWebSocket), which passes audio straight to the decoder and the
playback worklet, routes video straight to the video worker while it
decodes -- full frames through one decoder, the striped modes decoded per
row and composited there, acked from the socket worker (received id for
full frames, presented id for stripes) -- and carries the microphone and
webcam encoders' frames out over their own ports: nothing occupying the
page's thread can interrupt any of them.
Binary messages are typed by their first byte. From the server: 0x01
audio (Opus, with the RED redundancy layout documented on
extractOpusFrames), 0x03 a JPEG stripe (u8 reserved, u16 frame id,
u16 stripe Y, JPEG data), 0x04 a video stripe or full frame (u8
codec and frame kind, u16 frame id, u16 stripe Y, u16 width, u16 height, u16 the id of the frame it predicts from -- its own id when it
predicts from nothing or the encoder does not say -- then the coded data),
and 0x05 a gzip-wrapped control text once the client
advertised _gz,1. From the
client: 0x02 microphone Opus, 0x06 webcam frames (startWebcamCapture),
and 0x05 gzipped large text once the server echoed _gz,1. Text messages
are control. The client sends SETTINGS,{json}, r,WxH,displayId,
START_VIDEO, STOP_VIDEO, START_AUDIO, STOP_AUDIO,
REQUEST_KEYFRAME, LOST_FRAME <id> (a frame the decoder dropped, which
the encoder then predicts past), CLIENT_FRAME_ACK <id> <heldMs>, cr, REQUEST_CLIPBOARD, the
chunked clipboard upload of lib/clipboard-worker-bridge.js,
cmd,<command>, SET_NATIVE_CURSOR_RENDERING,<0|1>,
vp,<originX>,<originY>,<scaleX>,<scaleY> (this page's stream box on the
user's desktop, relayed to the other displays) and the input verbs of
lib/input.js. The server sends MODE websockets, AUTH_SUCCESS,{json},
ROLE_UPDATE,{json}, MK_ACCESS,<0|1>, VIDEO_STARTED, VIDEO_STOPPED,
AUDIO_STARTED, AUDIO_STOPPED, AUDIO_DISABLED, MICROPHONE_DISABLED,
WEBCAM_DISABLED, WEBCAM_KEYFRAME, CAPTURE_DEMAND <subject> <0|1>,
PIPELINE_RESETTING <display>,
DISPLAY_CONFIG_UPDATE,{json}, cursor,{json}, system,{json},
KILL <reason>, the clipboard family (clipboard,, clipboard_binary,,
clipboard_start,, clipboard_data,, clipboard_finish,
clipboard_reply,), and JSON objects typed server_settings,
server_apps, pipeline_status, stream_resolution, stream_info and
stream_stats (lib/stream-stats.js).
Video is decoded with WebCodecs: a JPEG stripe through ImageDecoder, an
H.264 stripe through a VideoDecoder per row offset -- in the video worker
while the divert holds, on the page as the fallback -- and a full frame --
controller or shared viewer alike -- in the video worker or through the
row-0 stripe decoder. Decoded frames reach the
screen through the first sink available: a track generator feeding a
<video>, the worker's OffscreenCanvas, or the page canvas, with the
striped modes composited on a back-buffer and blitted whole at frame
boundaries. Audio is decoded in a worker and played through an
AudioWorklet, the microphone is encoded to Opus in a worker, and the webcam
is lib/webcam-capture.js.
Dashboards talk to the core over same-origin window messages. The core
handles setVolume, setMute, setScaleLocally, setSynth,
showVirtualKeyboard, setUseCssScaling, setAntiAliasing,
setUseBrowserCursors, setRawPointerMotion, setManualResolution,
resetResolutionToWindow,
settings, getStats, clipboardUpdateFromUI, clipboardImageUpdate,
pipelineStatusUpdate, pipelineControl, audioDeviceSelected,
gamepadControl, requestFullscreen, command, touchinput:trackpad,
touchinput:touch, sidebarVisibilityChanged and statsOpen, and posts
pipelineStatusUpdate, sidebarButtonStatusUpdate, serverSettings,
systemApps, stats (to the parent window), clientRoleUpdate,
effectiveCursorState, scalingDpiFollowed, trackpadModeUpdate,
clipboardContentUpdate, the clipboard preview of lib/clipboard-sync.js,
fileUpload,
toggleDashboard and toggleTouchGamepad. The window globals it
publishes for the dashboards and the tests are webrtcInput (the Input
handler), fps, videoChunksReceived, videoDivertOn, videoStripeRows
(the row layout the video worker is decoding), webcamCodec,
stream_info, stream_client and stream_stats (lib/stream-stats.js),
currentAudioBufferSize,
currentAudioBufferDuration, currentAudioLevel,
currentAudioUnderrunSamples, currentAudioWorkletDropped,
currentAudioDropped, manual_resolution, enable_resize,
streamResolutionDiverged, isAudioInitializing, isFallingBack,
isCleaningUp, applyTimestamp and selkiesTransport (the page-side
handle on the session socket, which itself runs in a worker), plus one
window[key] per server setting mirrored by sanitizeAndStoreSettings.
Settings are read from localStorage at init with fallbacks only and persist
nothing, so a fresh profile keeps every key unset and server-pushed
defaults stay re-pushable; only genuine user actions, and
sanitizeAndStoreSettings for keys the user already overrode, write
localStorage. Keys in PER_DISPLAY_SETTINGS carry a _display2 suffix on
the secondary display.
Functions
audioTsNewer()
function audioTsNewer(a, b): boolean;Defined in: selkies-ws-core.js:173
32-bit wrap-safe comparison of audio timestamps.
Parameters
| Parameter | Type | Description |
|---|---|---|
a | number | - |
b | number | - |
Returns
boolean
True when a is strictly newer than b.
extractOpusFrames()
function extractOpusFrames(arrayBuffer): ArrayBuffer[];Defined in: selkies-ws-core.js:193
Parses an audio message body into the ordered Opus frames to decode, using RED redundancy to recover frames the sender dropped under backpressure (pcmflux's delivery ring and the server's audio queue both drop-oldest, and a dropped frame rides along as redundancy in the next packet).
n_red == 0 is the plain path: [0x01, 0x00] + opus. n_red > 0 is
[0x01, n_red, pts32] + n_red * (4-byte header) + 1-byte primary header + block data, redundant blocks oldest-first and then the primary; each block's
timestamp is pts - tsOffset. Every frame is decoded at most once, in
order: any block newer than the last one already played is taken, so a
redundant copy fills the gap left by a dropped primary. The first RED packet
anchors on its primary without replaying its redundancy.
Parameters
| Parameter | Type | Description |
|---|---|---|
arrayBuffer | ArrayBuffer | The whole binary message, type byte included. |
Returns
ArrayBuffer[]
Opus frames in decode order; empty for a malformed packet.
websockets()
function websockets(): void;Defined in: selkies-ws-core.js:239
Starts the WebSocket streaming core in this page. Everything below is
closure state of one session; the public surface is the window contract
described in the module docblock.
Returns
void
isFullFrameVideo()
function isFullFrameVideo(mode): boolean;Defined in: selkies-ws-core.js:465
Whether an encoder wire value streams whole video frames through one decoder.
Parameters
| Parameter | Type |
|---|---|
mode | any |
Returns
boolean
isVideoEncoder()
function isVideoEncoder(mode): boolean;Defined in: selkies-ws-core.js:467
Whether an encoder wire value streams video at all rather than JPEG stills.
Parameters
| Parameter | Type |
|---|---|
mode | any |
Returns
boolean
streamDensity()
function streamDensity(): number;Defined in: selkies-ws-core.js:472
Stream pixels per CSS pixel this page requests and draws at (lib/stream-density.js).
Returns
number
followStreamDensity()
function followStreamDensity(): void;Defined in: selkies-ws-core.js:487
Hands the density to the input layer and, on a secondary whose density moved (a HiDPI or UI-scaling change, or on X11 the primary's scale), requests the stream at it again.
Returns
void
autoDeriveDpi()
function autoDeriveDpi(): number;Defined in: selkies-ws-core.js:508
Derives the default scaling_dpi (lib/stream-density.js): from the local
display scaling, so the remote desktop's UI matches the local one, or from a
manual resolution, which is a framebuffer of its own that the local screen
says nothing about. A stored pick overrides either.
Returns
number
effectiveScalingDpi()
function effectiveScalingDpi(): number;Defined in: selkies-ws-core.js:525
The DPI the desktop is asked for: 96 under CSS scaling, where the pick divides the requested resolution instead (lib/stream-density.js).
A manual resolution is the exact framebuffer either way -- a HiDPI toggle must not swing the size the operator asked for -- so there is nothing for the pick to divide there and it governs the desktop, HiDPI or not. Applying it once is not the double scaling that CSS scaling had: the request it would have divided is fixed.
Returns
number
followDerivedDpi()
function followDerivedDpi(reason): boolean;Defined in: selkies-ws-core.js:536
Re-derives scaling_dpi while it sits on its automatic default; a stored
value is the dashboard's explicit pick and is left alone. The new value is
posted as scalingDpiFollowed so the dashboards show it.
Parameters
| Parameter | Type | Description |
|---|---|---|
reason | string | What changed, for the log. |
Returns
boolean
Whether the derived value moved; the caller pushes it.
maybeFollowDpr()
function maybeFollowDpr(): void;Defined in: selkies-ws-core.js:556
Follows a live devicePixelRatio change while scaling_dpi sits on its
automatic default, re-deriving and pushing it so the remote UI density
matches the display the window is on. Called from both the resize handler
and the matchMedia density watcher: an OS scaling change can surface as
either, and emulated density changes fire only the resize.
Returns
void
applyEffectiveCursorSetting()
function applyEffectiveCursorSetting(): void;Defined in: selkies-ws-core.js:581
Applies the cursor preference to the input handler, forced to browser
cursors whenever a second display is involved, and posts the value in
effect as effectiveCursorState so the dashboard toggle reflects the
override rather than the preference alone.
Returns
void
applyRawPointerMotion()
function applyRawPointerMotion(): void;Defined in: selkies-ws-core.js:602
Applies the raw pointer motion setting to the input handler.
Returns
void
applyMacCmdAsCtrl()
function applyMacCmdAsCtrl(): void;Defined in: selkies-ws-core.js:614
Applies the Command-as-Control setting to the input handler.
Returns
void
applyKeyboardShortcuts()
function applyKeyboardShortcuts(): void;Defined in: selkies-ws-core.js:626
Applies the chord setting to the input handler.
Returns
void
setRealViewportHeight()
function setRealViewportHeight(): void;Defined in: selkies-ws-core.js:632
Publishes the real viewport height as the --vh CSS unit (mobile browser chrome excluded).
Returns
void
reencodePngOffThread()
function reencodePngOffThread(blob): Promise<Blob>;Defined in: selkies-ws-core.js:644
PNG-normalizes an image on the worker, which is where the decode and re-encode of a large one belong; the page's own canvas covers a worker that cannot do it.
Parameters
| Parameter | Type |
|---|---|
blob | any |
Returns
Promise<Blob>
sendExplicitClipboard()
function sendExplicitClipboard(
data,
mime?,
onSkip?
): Promise<void>;Defined in: selkies-ws-core.js:701
Sends content the user named (the clipboard box, the image upload) so it outranks the focus read. Refused before the connection builds the sender.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | string | ArrayBuffer | Blob | - |
mime? | string | - |
onSkip? | Function | Told why nothing was sent. |
Returns
Promise<void>
safeSetItem()
function safeSetItem(key, value): void;Defined in: selkies-ws-core.js:783
localStorage write that degrades a full or unavailable store to a warning instead of throwing QuotaExceededError into the caller.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | - |
value | string | - |
Returns
void
noteSessionRange()
function noteSessionRange(info): void;Defined in: selkies-ws-core.js:827
Take the range a session converted at from its report and hand it to every decoder: no engine reads it out of an H.264 bitstream, so one that is not told renders a full range session wrong.
Parameters
| Parameter | Type | Description |
|---|---|---|
info | any | A stream_info payload. |
Returns
void
rememberSoftwareDecode()
function rememberSoftwareDecode(enabled): void;Defined in: selkies-ws-core.js:839
Persists or clears the software-decode preference.
Parameters
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | - |
Returns
void
decoderConfigFor()
function decoderConfigFor(config): VideoDecoderConfig;Defined in: selkies-ws-core.js:861
Applies the acceleration preference to a VideoDecoder config; every decoder (main, stripe, SPS-driven, worker) goes through here so they agree. Unset, the UA default picks a hardware decoder when one works.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | VideoDecoderConfig | - |
Returns
VideoDecoderConfig
retireCrashCountWhenHealthy()
function retireCrashCountWhenHealthy(): void;Defined in: selkies-ws-core.js:874
Clears the crash count once this session has proven healthy; runs on every metrics tick.
Returns
void
checkVideoOutputWatchdog()
function checkVideoOutputWatchdog(): void;Defined in: selkies-ws-core.js:895
A hardware decoder can take its config and then neither output a frame nor raise an error,
so nothing signals the fallback ladder and the screen stays black (older iOS and Intel parts
do this when fed a stream the part cannot decode). When video chunks keep arriving yet no
frame has been presented on any path for NO_OUTPUT_WATCHDOG_MS, this trips the same
one-shot software-decode retry a decoder error would; its escalation carries on from there,
and a real decoder error still gets there first. A still screen sends no chunks, so it never
triggers, and the retry is spent once so an engine that ignores the software hint cannot loop.
A stream this engine has said it cannot decode produces no output by definition, and neither
a retry nor the reset the escalation ends in changes that, so the notice stands instead.
Returns
void
notePageDecoded()
function notePageDecoded(frame): void;Defined in: selkies-ws-core.js:968
Times one frame out of the page's decoder and keeps its pixel format.
Parameters
| Parameter | Type |
|---|---|
frame | any |
Returns
void
probePageHardware()
function probePageHardware(config): void;Defined in: selkies-ws-core.js:978
Asks, once per configuration, whether the engine has a hardware decoder for the page's stream.
Parameters
| Parameter | Type |
|---|---|
config | any |
Returns
void
sampleStreamStats()
function sampleStreamStats(): void;Defined in: selkies-ws-core.js:1009
One second of this page's own figures, for lib/stream-stats.js.
Returns
void
getIntParam()
function getIntParam(key, default_value): number;Defined in: selkies-ws-core.js:1068
Reads an integer setting from localStorage under the app prefix; keys in
PER_DISPLAY_SETTINGS carry a _display2 suffix on the secondary display.
The get/set helpers below share that key scheme.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | - |
default_value | number | Returned when the key is unset. |
Returns
number
getFloatParam()
function getFloatParam(key, default_value): any;Defined in: selkies-ws-core.js:1078
Float variant of getIntParam, for range settings with fractional bounds.
Parameters
| Parameter | Type |
|---|---|
key | any |
default_value | any |
Returns
any
setIntParam()
function setIntParam(key, value): void;Defined in: selkies-ws-core.js:1089
Stores an integer setting; null removes the key.
Parameters
| Parameter | Type |
|---|---|
key | any |
value | any |
Returns
void
prefixedStorageKey()
function prefixedStorageKey(key): string;Defined in: selkies-ws-core.js:1102
The localStorage key a setting is stored under, display suffix included.
Parameters
| Parameter | Type |
|---|---|
key | any |
Returns
string
getBoolParam()
function getBoolParam(key, default_value): any;Defined in: selkies-ws-core.js:1108
Reads a boolean setting stored as 'true'/'false'.
Parameters
| Parameter | Type |
|---|---|
key | any |
default_value | any |
Returns
any
setBoolParam()
function setBoolParam(key, value): void;Defined in: selkies-ws-core.js:1121
Stores a boolean setting; null removes the key.
Parameters
| Parameter | Type |
|---|---|
key | any |
value | any |
Returns
void
getStringParam()
function getStringParam(key, default_value): any;Defined in: selkies-ws-core.js:1134
Reads a string setting.
Parameters
| Parameter | Type |
|---|---|
key | any |
default_value | any |
Returns
any
setStringParam()
function setStringParam(key, value): void;Defined in: selkies-ws-core.js:1144
Stores a string setting; null removes the key.
Parameters
| Parameter | Type |
|---|---|
key | any |
value | any |
Returns
void
resolvedCssScaling()
function resolvedCssScaling(serverSettings): boolean;Defined in: selkies-ws-core.js:1186
The use_css_scaling the deployment implies, off the shared ladder: a locked
or operator value, else the client's explicit pick, else CSS scaling whenever
a resolution is configured. Resolved here rather than left to a settings
panel, which a dashboard may mount only when it is opened -- until then the
session would stream pixel-perfect against a configuration that says
otherwise, on every load.
Parameters
| Parameter | Type | Description |
|---|---|---|
serverSettings | { } | The server_settings payload. |
Returns
boolean
resolvedRawPointerMotion()
function resolvedRawPointerMotion(serverSettings): boolean;Defined in: selkies-ws-core.js:1203
The raw_pointer_motion the deployment implies, off the shared ladder: a
locked or operator value, else the client's stored pick, else the platform
default (off on macOS). Resolved here for the reason CSS scaling is: pointer
lock is taken from the stream, whether or not a settings panel ever mounts.
Parameters
| Parameter | Type | Description |
|---|---|---|
serverSettings | { } | The server_settings payload. |
Returns
boolean
resolvedMacCmdAsCtrl()
function resolvedMacCmdAsCtrl(serverSettings): boolean;Defined in: selkies-ws-core.js:1215
The mac_cmd_as_ctrl the deployment implies, off the shared ladder. Resolved
here for the reason raw pointer motion is: the keyboard is taken from the
stream, whether or not a settings panel ever mounts.
Parameters
| Parameter | Type | Description |
|---|---|---|
serverSettings | { } | The server_settings payload. |
Returns
boolean
enterFullscreen()
function enterFullscreen(gaming): void;Defined in: selkies-ws-core.js:1354
Enters fullscreen through the input handler, which owns both modes; before it exists only plain fullscreen is possible.
Parameters
| Parameter | Type | Description |
|---|---|---|
gaming | boolean | Whether to hold the pointer and the keyboard. |
Returns
void
playStream()
function playStream(): void;Defined in: selkies-ws-core.js:1367
Hides the start overlay and keeps the screen awake once the user starts the stream.
Returns
void
updateStatusDisplay()
function updateStatusDisplay(): void;Defined in: selkies-ws-core.js:1379
Shows loadingText, or else the sentence-cased status word (the internal
value stays lower-case for comparisons).
Returns
void
alignResolution()
function alignResolution(num): number;Defined in: selkies-ws-core.js:1403
Floors a dimension to the encoder's alignment: 16 when
force_aligned_resolution is set, 2 otherwise.
Parameters
| Parameter | Type | Description |
|---|---|---|
num | number | - |
Returns
number
checkWorkerSinkAlive()
function checkWorkerSinkAlive(): void;Defined in: selkies-ws-core.js:1489
Watches the canvas-mode placeholder actually take committed frames: its element mirrors the worker-side size on the first commit everywhere the sink works, so one that stays at the default size while the worker reports presenting is inert, and presentation falls back to the page canvas.
Returns
void
createVideoTrackGenerator()
function createVideoTrackGenerator(): object;Defined in: selkies-ws-core.js:2020
Creates the main-thread (Chromium) track generator; the worker-only VideoTrackGenerator is handled by the video worker instead.
Returns
object
track
track: MediaStreamTrack;writable
writable: WritableStream;ensureMstgWriter()
function ensureMstgWriter(): boolean;Defined in: selkies-ws-core.js:2037
Lazily wires the <video> element to a fresh track generator; a writable
that later errors or closes falls back to the canvas so the element never freezes.
Returns
boolean
True when the writer is ready.
teardownMstgWriter()
function teardownMstgWriter(): void;Defined in: selkies-ws-core.js:2061
Closes the track generator writer and detaches its stream from the <video>.
Returns
void
presentFrameToVideo()
function presentFrameToVideo(frame): boolean;Defined in: selkies-ws-core.js:2079
Presents a VideoFrame through the main-thread track generator, showing the
<video> and hiding the canvas once it has rendered. Until then the frame
is also painted on the canvas, since a fresh connection has nothing there
yet and an empty <video> would show black. The resize handlers re-show
the canvas with a fresh transform, so it is re-hidden every frame and its
box re-mirrored whenever it changed; a backpressured sink drops the frame
rather than building latency.
Parameters
| Parameter | Type | Description |
|---|---|---|
frame | VideoFrame | - |
Returns
boolean
True when consumed (the caller must not close it), false to fall back to the canvas.
syncWireGeom()
function syncWireGeom(): void;Defined in: selkies-ws-core.js:2144
Tells the video worker the display geometry, which sizes the back-buffer its striped composite persists on; the canvas buffer is stream-resolution physical pixels, exactly the space stripe offsets address.
Returns
void
wireSocketToVideoWorker()
function wireSocketToVideoWorker(): void;Defined in: selkies-ws-core.js:2157
Connects the socket worker to the video worker, so diverted stripes reach decode without the page's thread on them; a fresh channel per call, for a restarted transport or video worker. The divert itself stays off until updateVideoDivert turns it on.
Returns
void
updateVideoDivert()
function updateVideoDivert(force?): void;Defined in: selkies-ws-core.js:2194
Points the socket worker's divert at the current truth: on while the video
worker is the decoder for h264enc and healthy, or, in the striped modes,
while it can decode and composite them (any sink; gated off with the
worker escape hatch). Called wherever any input flips -- the worker's mode
reply, its deactivation or decoder failure, an encoder switch, a rebuilt
transport. Striped acks report the presented id, so a client that cannot
render sheds load exactly as the page path does.
Parameters
| Parameter | Type | Description |
|---|---|---|
force? | boolean | Resend even when the value is unchanged, for a transport whose worker started fresh and holds the default. |
Returns
void
jpegDecodePath()
function jpegDecodePath(): string;Defined in: selkies-ws-core.js:2246
How a JPEG stripe becomes a picture on this engine: ImageDecoder where
WebCodecs offers it, createImageBitmap otherwise, and neither where the
engine has no path at all. Named with where it runs, since the video worker
decodes for the page when it reported that it can.
Returns
string
ensureVideoWorker()
function ensureVideoWorker(): boolean;Defined in: selkies-ws-core.js:2273
Lazily creates the video worker and completes its capability handshake.
The worker self-probes VideoTrackGenerator on startup and reports vtg
(it transferred a track back for <video>.srcObject) or canvas (it is
handed an OffscreenCanvas to composite on). Its other messages: ack per
consumed frame, error when the generator writable failed, presented
once its canvas has real content, needKeyframe (no_key after a
reconfigure, overload when the decode backlog forced a resync; throttled
to one per 800 ms) and decoderError, after which chunks return to
main-thread decode while the sink stays up for transferred frames.
Returns
boolean
True once a sink is wired; until then frames fall back to the main canvas.
deactivateVideoWorker()
function deactivateVideoWorker(): void;Defined in: selkies-ws-core.js:2420
Terminates the video worker and returns presentation to the main canvas.
The worker decoder config is forgotten so a recreated worker is configured
afresh, and a transferred OffscreenCanvas, which can never be transferred
again, is replaced by a fresh <canvas> element. The sink is announced from
here as well: this is where a worker that failed to start or died hands
presentation back, and a session that ends up somewhere other than where it
asked to be is the one that most needs to say so.
Returns
void
activateWorkerSinkDisplay()
function activateWorkerSinkDisplay(): boolean;Defined in: selkies-ws-core.js:2461
Shows the active worker sink (<video> for VTG, the worker canvas
otherwise), hides the main canvas once the sink has rendered
(requestVideoFrameCallback for VTG, the worker's one-time presented
message for canvas mode), and mirrors the canvas box onto the sink whenever
it changed.
Returns
boolean
False while no sink target exists yet.
presentFrameToWorker()
function presentFrameToWorker(frame): boolean;Defined in: selkies-ws-core.js:2509
Transfers a main-thread-decoded VideoFrame to the worker sink, the fallback while the worker decoder warms up. A frame past the in-flight cap is dropped rather than queued behind a stalled decoder, and a frame that postMessage detached or closed is reported consumed so the caller never reuses it.
Parameters
| Parameter | Type | Description |
|---|---|---|
frame | VideoFrame | - |
Returns
boolean
True when consumed (the caller must not close it).
logWorkerDecoderConfig()
function logWorkerDecoderConfig(
codec,
w,
h
): void;Defined in: selkies-ws-core.js:2537
Rate-limited log of worker decoder reconfigures. A healthy stream reconfigures about once per session (join, resolution change), so a storm with flipping codec strings is the diagnostic; at most one line per interval, with a suppressed count so repeats stay visible.
Parameters
| Parameter | Type | Description |
|---|---|---|
codec | string | - |
w | number | - |
h | number | - |
Returns
void
feedWorkerDecoder()
function feedWorkerDecoder(
isKey,
dataBuf,
w,
h,
codec,
frameId,
reference
): boolean;Defined in: selkies-ws-core.js:2560
Forwards an encoded full-frame H.264 chunk to the worker's own decoder, reconfiguring it when the codec or coded dimensions change and requesting the keyframe WebCodecs needs after a configure.
Parameters
| Parameter | Type | Description |
|---|---|---|
isKey | boolean | - |
dataBuf | ArrayBuffer | The Annex-B payload; transferred, not copied. |
w | number | Coded width. |
h | number | Coded height. |
codec | string | The avc1.PPCCLL codec string. |
frameId | any | - |
reference | any | - |
Returns
boolean
True when handled there, false to fall back to main-thread decode.
deactivateMstg()
function deactivateMstg(): void;Defined in: selkies-ws-core.js:2583
Returns presentation from the main-thread track generator to the canvas; idempotent.
Returns
void
wireCodecString()
function wireCodecString(
typeByte,
payload,
width,
height
): string;Defined in: selkies-ws-core.js:2606
The WebCodecs codec string of the stream a video frame belongs to: read from the frame itself when it is a key frame (the parameter sets every codec here repeats on its key frames), from the geometry otherwise. Every engine uses this: Safari's VideoDecoder errors when the configured profile or level is lower than the stream's real one, and the parsed value always matches the bitstream.
Parameters
| Parameter | Type | Description |
|---|---|---|
typeByte | number | The frame's wire type byte. |
payload | ArrayBuffer | The frame's payload. |
width | number | - |
height | number | - |
Returns
string
updateCanvasImageRendering()
function updateCanvasImageRendering(): void;Defined in: selkies-ws-core.js:2618
Picks the canvas image-rendering: pixelated for a 1:1 display or when
anti-aliasing is off, smoothed whenever the picture is scaled (manual
resolution, high-DPR CSS scaling, shared mode). Part of cssText, so the box
is re-mirrored to the active sink.
Returns
void
injectCSS()
function injectCSS(): void;Defined in: selkies-ws-core.js:2645
Installs the page's base stylesheet: the video container, its sinks, the overlay input and the start button.
Returns
void
settleFullColorSupport()
function settleFullColorSupport(): Promise<void>;Defined in: selkies-ws-core.js:2757
Settles whether full color is on the table for this engine, before the first SETTINGS payload is built.
An engine whose decoder has no 4:4:4 profile cannot show a full-color stream at all -- every stripe is refused and nothing paints -- so the setting is turned off rather than asked for. It is written to storage, not merely dropped from one payload: every payload is built from storage, and the dashboards read the same keys, so the toggle shows what the stream is. The decoder is only asked where full color is on, since the session waits here to start and the answer settles nothing for a stream not asking for it.
Returns
Promise<void>
declineUndecodableFullColor()
function declineUndecodableFullColor(reason): Promise<boolean>;Defined in: selkies-ws-core.js:2780
Turns a full color the server announced off again where this engine cannot decode the codec's 4:4:4, so the stream comes back 4:2:0 on the same codec rather than stepping to a codec it does decode. A locked setting cannot be turned off and is left to the refusal ladder.
Parameters
| Parameter | Type | Description |
|---|---|---|
reason | string | Logged with the settings update. |
Returns
Promise<boolean>
Whether full color was turned off.
isFullColorProfile()
function isFullColorProfile(label): boolean;Defined in: selkies-ws-core.js:2794
Whether a refused codec string names a 4:4:4 profile.
Parameters
| Parameter | Type |
|---|---|
label | any |
Returns
boolean
serverFullColor()
function serverFullColor(codec): boolean;Defined in: selkies-ws-core.js:2818
Whether a full-color session on codec streams 4:4:4 from this server: the fullcolor of
its backend on the side in effect, the engine's unless use_cpu or it has none; null
while the server has not said.
Parameters
| Parameter | Type | Description |
|---|---|---|
codec | string | The codec name. |
Returns
boolean
nextRung()
function nextRung(refused?): string;Defined in: selkies-ws-core.js:2849
The next encoder a refusal steps to: the first of LADDER_ORDER, among
those the server allows, whose codec this engine has not refused and
decodes, and whose 4:4:4 it decodes where the server holds full color on
and the codec carries it; JPEG is the last rung, and the only one when
nothing else is left.
Parameters
| Parameter | Type | Description |
|---|---|---|
refused? | string | The codec just refused. |
Returns
string
The encoder, or null when nothing is left.
fallbackEncoder()
function fallbackEncoder(pick): string;Defined in: selkies-ws-core.js:2872
The encoder a pick this engine cannot decode falls back to: the ladder's first rung past it.
Parameters
| Parameter | Type |
|---|---|
pick | any |
Returns
string
answerRefusedCodec()
function answerRefusedCodec(label, codec): void;Defined in: selkies-ws-core.js:2892
Answers a stream this engine will not decode, and reports it.
label is what was refused: the codec string read from a key frame, which
is what the server really sends rather than what the settings say (a
video_fullcolor the server holds locked arrives as 4:4:4 in the bitstream
and as nothing at all in the settings echo), or the encoder the server
announced when its codec fails the decoder probe.
A client that owns the encoder steps down the ladder nextRung walks:
every video codec it decodes before JPEG. The step stays pending until the
server confirms it, by its settings echo or by the new stream's first
frame; refusals in the meantime are the old stream still in flight. A
server that holds the encoder, and a shared viewer, which owns none of the
stream's settings, are told once.
Parameters
| Parameter | Type | Description |
|---|---|---|
label | string | The refused codec string or encoder. |
codec | string | The refused stream's codec name. |
Returns
void
stepRefusalLadder()
function stepRefusalLadder(label, codec): void;Defined in: selkies-ws-core.js:2912
The ladder step behind answerRefusedCodec, once full color is not the answer.
Parameters
| Parameter | Type | Description |
|---|---|---|
label | string | The refused codec string or encoder. |
codec | string | The refused stream's codec name. |
Returns
void
settleServerEncoder()
function settleServerEncoder(encoder, entry?): void;Defined in: selkies-ws-core.js:2947
Takes the server's word on the encoder: what it streams, whether it holds the setting, and whether the ladder's pending step landed. An encoder whose codec fails the decoder probe goes to the ladder; an announcement that changes what an unanswerable refusal was reached under clears the notice, one that repeats it leaves the notice standing.
Parameters
| Parameter | Type | Description |
|---|---|---|
encoder | string | The announced encoder. |
entry? | { locked?: boolean; allowed?: string[]; } | Its settings entry. |
entry.locked? | boolean | - |
entry.allowed? | string[] | - |
Returns
void
sendFullSettingsUpdateToServer()
function sendFullSettingsUpdateToServer(reason): void;Defined in: selkies-ws-core.js:2967
Sends the full SETTINGS,{json} payload; never from a shared viewer.
Parameters
| Parameter | Type | Description |
|---|---|---|
reason | string | Logged with the send. |
Returns
void
currentDisplayScale()
function currentDisplayScale(dpr): number;Defined in: selkies-ws-core.js:2987
This page's remote pixels per CSS pixel, reported so a neighboring display can scale a cross-display drag's travel over this one and stream at this page's density (lib/stream-density.js).
Parameters
| Parameter | Type | Description |
|---|---|---|
dpr | number | The density the resolution request was built with. |
Returns
number
getCurrentSettingsPayload()
function getCurrentSettingsPayload(): object;Defined in: selkies-ws-core.js:3015
Builds the SETTINGS payload. Only keys with a stored (user-set) value are
included, so the fallbacks here never override server-configured defaults
for an untouched setting; scaling_dpi is the exception, being
client-authoritative (the derived default or the dashboard's pick, sent
live so it reaches the running server; the desktop DPI is independent of
the resolution). The payload also carries the keyboard layout, the client
geometry or manual resolution, the display identity and the audio-RED
capability that makes the server enable Opus redundancy.
Returns
object
updateToggleButtonAppearance()
function updateToggleButtonAppearance(buttonElement, isActive): void;Defined in: selkies-ws-core.js:3085
Labels a pipeline toggle button with its name and ON/OFF state.
Parameters
| Parameter | Type | Description |
|---|---|---|
buttonElement | HTMLElement | - |
isActive | boolean | - |
Returns
void
sendResolutionToServer()
function sendResolutionToServer(width, height): void;Defined in: selkies-ws-core.js:3109
Sends r,WxH,displayId with the aligned, DPR-scaled and 4080-capped stream
resolution; blocked in shared mode, where the viewer follows the controller.
Parameters
| Parameter | Type | Description |
|---|---|---|
width | number | CSS pixels, or the exact size in manual mode. |
height | number | - |
Returns
void
syncSinkToCanvasStyle()
function syncSinkToCanvasStyle(): void;Defined in: selkies-ws-core.js:3162
Mirrors the canvas box onto the active video sink right after a canvas-style
writer rewrote it. The present paths do the same, but only when frames flow:
on a static remote a resize would otherwise leave the stale canvas covering
the live sink until the next decoded frame. A sink that has proven it
renders gets the geometry and hides the canvas immediately; during warm-up
nothing changes. Covers all three sinks (main-thread and worker generators
drive the <video>, the OffscreenCanvas worker drives videoWorkerCanvas).
Returns
void
applyManualCanvasStyle()
function applyManualCanvasStyle(
targetWidth,
targetHeight,
scaleToFit
): void;Defined in: selkies-ws-core.js:3196
Sizes the canvas for a manual resolution: the backing buffer at the target size (DPR-scaled unless CSS scaling, shared mode or manual mode pin it to 1), the CSS box either scaled to fit the container or exact and centered. Exact is one stream pixel per device pixel, independent of the HiDPI flag, which a manual resolution does not read. The overlay input follows the box and the input handler is told to resize. The per-row JPEG stripe ids, keyed by row offset, are reset because a geometry change invalidates them.
Parameters
| Parameter | Type | Description |
|---|---|---|
targetWidth | number | - |
targetHeight | number | - |
scaleToFit | boolean | - |
Returns
void
resetCanvasStyle()
function resetCanvasStyle(streamWidth, streamHeight): void;Defined in: selkies-ws-core.js:3294
Sizes the canvas for the stream's own resolution: the backing buffer at the DPR-scaled size and the CSS box at the stream size, centered in the container, with the overlay input following. The per-row JPEG stripe ids are reset as in applyManualCanvasStyle.
Parameters
| Parameter | Type | Description |
|---|---|---|
streamWidth | number | - |
streamHeight | number | - |
Returns
void
enableAutoResize()
function enableAutoResize(): void;Defined in: selkies-ws-core.js:3367
Switches the window resize listener to the automatic (stream follows the viewport) handler and applies it once.
Returns
void
directManualLocalScalingHandler()
function directManualLocalScalingHandler(): void;Defined in: selkies-ws-core.js:3388
Resize listener for manual resolution: restyles the canvas box without touching the stream size.
Returns
void
disableAutoResize()
function disableAutoResize(): void;Defined in: selkies-ws-core.js:3395
Switches the window resize listener to the manual-resolution handler and applies it once.
Returns
void
updateUIForSharedMode()
function updateUIForSharedMode(): void;Defined in: selkies-ws-core.js:3410
Marks the container as a shared viewer (default cursor) and disables file upload.
Returns
void
initializeUI()
function initializeUI(): void;Defined in: selkies-ws-core.js:3435
Builds the page: the video container with its status bar, overlay input,
canvas, the sink elements the engine can use, and the start button, plus
the hidden file input and keyboard-assist input on the body. Chooses the
video sink (see supportsWindowMSTG), logging it once since a canvas
fallback explains a session's CPU cost, and starts the worker handshake
early so its decoder is ready before the first frame, then sizes the canvas
for shared, manual or automatic resolution.
Returns
void
clearAllVncStripeDecoders()
function clearAllVncStripeDecoders(): void;Defined in: selkies-ws-core.js:3592
Closes every stripe decoder and forgets their soft-error counts.
Returns
void
handleStripeDecodeError()
function handleStripeDecodeError(e, vncStripeYStart): void;Defined in: selkies-ws-core.js:3624
Routes a stripe decoder error. Safari's main-thread VideoDecoder rejects streams its worker decoder plays fine, so while the worker path is elected for a full-frame encoder and still healthy the error is handoff noise: the stripe decoder is rebuilt on the next keyframe instead of escalating into the fallback ladder, which closes the socket and reloads. A burst that keeps repeating within the window still reaches the ladder.
Parameters
| Parameter | Type | Description |
|---|---|---|
e | any | The decoder error. |
vncStripeYStart | number | The stripe's row offset, which keys its decoder. |
Returns
void
stripeDecodesDrained()
function stripeDecodesDrained(): boolean;Defined in: selkies-ws-core.js:3648
Whether every stripe chunk handed to a stripe decoder has come back out.
Returns
boolean
processPendingChunksForStripe()
function processPendingChunksForStripe(stripe_y_start): void;Defined in: selkies-ws-core.js:3662
Decodes the chunks a stripe queued while its decoder was still configuring.
Parameters
| Parameter | Type | Description |
|---|---|---|
stripe_y_start | number | - |
Returns
void
ensureStripeBackBuffer()
function ensureStripeBackBuffer(): CanvasRenderingContext2D;Defined in: selkies-ws-core.js:3708
Creates the back-buffer, resized to the canvas.
Returns
CanvasRenderingContext2D
deactivateStripeWorker()
function deactivateStripeWorker(): void;Defined in: selkies-ws-core.js:3757
Terminates the stripe compositor worker.
Returns
void
ensureStripeWorker()
function ensureStripeWorker(): boolean;Defined in: selkies-ws-core.js:3767
Creates the stripe compositor worker; idempotent.
Returns
boolean
False when it cannot run, so the caller composites on the main-thread back-buffer instead.
stripeCompositeBegin()
function stripeCompositeBegin(): boolean;Defined in: selkies-ws-core.js:3800
Starts a stripe compositing cycle on the worker (its back-buffer resized to the canvas) or the main-thread back-buffer.
Returns
boolean
False while the canvas has no size yet.
stripeCompositeDraw()
function stripeCompositeDraw(stripe, yPos): void;Defined in: selkies-ws-core.js:3820
Composites one decoded stripe at its row offset; always consumes the stripe.
Parameters
| Parameter | Type | Description |
|---|---|---|
stripe | VideoFrame | ImageBitmap | - |
yPos | number | - |
Returns
void
stripeCompositePresent()
function stripeCompositePresent(): void;Defined in: selkies-ws-core.js:3835
Presents the composited frame: the worker commits an ImageBitmap, the main
thread blits its back-buffer. Counted as the striped modes' displayed frame,
which is what window.fps reports for them.
Returns
void
clearStartVideoWatchdog()
function clearStartVideoWatchdog(): void;Defined in: selkies-ws-core.js:3850
Disarms the START_VIDEO watchdog.
Returns
void
armVisibleFrameProbe()
function armVisibleFrameProbe(): void;Defined in: selkies-ws-core.js:3865
Proves a stream the returning tab believes is running: a reconnect or
reload while hidden can leave the server holding this display stopped, and
a screen with no damage since sends nothing to repaint the cleared canvas
either way. A keyframe request answers the second case; if nothing arrives
within VISIBLE_FRAME_PROBE_MS, the stream really is stopped and is restarted.
Returns
void
onStartVideoWatchdogTimeout()
function onStartVideoWatchdogTimeout(): void;Defined in: selkies-ws-core.js:3886
Resends START_VIDEO while no video arrives, up to the attempt limit, then forces a reconnect through the onclose path. Stands down when the tab is hidden again (the visibilitychange path owns that state, and a shared viewer's resume can be rate-limited by the server) or the socket is not open (the reconnect logic owns recovery).
Returns
void
armStartVideoWatchdog()
function armStartVideoWatchdog(): void;Defined in: selkies-ws-core.js:3903
Arms the START_VIDEO watchdog with a fresh attempt count for this visibility cycle.
Returns
void
clearSharedStallWatchdog()
function clearSharedStallWatchdog(): void;Defined in: selkies-ws-core.js:3910
Disarms the shared-mode stall watchdog.
Returns
void
armSharedStallWatchdog()
function armSharedStallWatchdog(): void;Defined in: selkies-ws-core.js:3924
Arms the shared-mode stall watchdog (see sharedStallWatchdogId). While the
viewer is hidden, paused or not yet ready it expects no chunks, so the clock
is kept fresh and the watchdog cannot fire the instant those states end.
Returns
void
handleDecodedVncStripeFrame()
function handleDecodedVncStripeFrame(yPos, frame): void;Defined in: selkies-ws-core.js:3960
Output callback of the stripe decoders. A full-frame h264enc frame (the single decoder at row 0) is presented the instant it decodes, for the lowest glass-to-glass latency, superseding anything still queued: through the main-thread track generator, else the worker sink, else the canvas. h264enc-striped composites partial-height stripes and drains through the rAF queue instead.
Parameters
| Parameter | Type | Description |
|---|---|---|
yPos | number | The stripe's row offset. |
frame | VideoFrame | - |
Returns
void
requestWakeLock()
function requestWakeLock(): Promise<void>;Defined in: selkies-ws-core.js:4000
Requests a screen wake lock so the device does not sleep mid-session.
Returns
Promise<void>
releaseWakeLock()
function releaseWakeLock(): Promise<void>;Defined in: selkies-ws-core.js:4019
Releases the screen wake lock if one is held.
Returns
Promise<void>
debounce()
function debounce(func, delay): Function;Defined in: selkies-ws-core.js:4032
Trailing-edge debounce.
Parameters
| Parameter | Type | Description |
|---|---|---|
func | Function | - |
delay | number | Milliseconds of quiet before func runs. |
Returns
Function
hideStreamOverlay()
function hideStreamOverlay(): void;Defined in: selkies-ws-core.js:4043
Hides the status bar and start button: a frame arrived, or the page is up with no stream to wait for.
Returns
void
startStream()
function startStream(): void;Defined in: selkies-ws-core.js:4049
Marks the stream as started and hides the status bar and start button.
Returns
void
initializeInput()
function initializeInput(): void;Defined in: selkies-ws-core.js:4065
Creates the Input handler on the overlay input once the server has assigned
the client's role and slot, wires its dashboard chords to the dashboards
(toggleDashboard, toggleTouchGamepad window messages; fullscreen,
Ctrl+Shift+F, stays inside Input), publishes it as
window.webrtcInput, installs the automatic or manual resize handling, and
attaches file drop and mobile keyboard assistance. A viewer role keeps the
gamepad but has its pointer and keyboard context detached.
Returns
void
handleResizeUI()
function handleResizeUI(): void;Defined in: selkies-ws-core.js:4189
Automatic resize: sends the aligned, capped viewport size and restyles
the canvas. Skipped in shared and manual mode, and on the primary when
enable_resize=false pins its resolution server-side (a secondary's
resize is its layout bring-up and stays allowed, matching the server).
Stripe decoders are closed first, since rows that vanish on shrink would
keep a live decoder nothing feeds, and the divergence flag is reset for
stream_resolution to re-flag.
Returns
void
watchDevicePixelRatio()
function watchDevicePixelRatio(): void;Defined in: selkies-ws-core.js:4251
Re-runs the automatic resize when devicePixelRatio changes. The stream
resolution is logical size times DPR, but a DPR change alone (a window
dragged to a monitor of another density, an OS scaling change) fires no
resize event. While scaling_dpi sits on its automatic default it is
re-derived too, so the remote UI density follows the display the window
is on. matchMedia resolution queries are one-shot at a given dppx, so
the query is re-armed after each change.
Returns
void
applyOutputDevice()
function applyOutputDevice(): Promise<void>;Defined in: selkies-ws-core.js:4320
Routes playback to the preferred output device. Audio plays out of the
AudioContext (no media element carries it), so this needs
AudioContext.setSinkId; where it is missing, or the context is not
running yet, playback stays on the default device.
Returns
Promise<void>
applyGamepadPolling()
function applyGamepadPolling(): void;Defined in: selkies-ws-core.js:4349
Applies the gamepad toggle to the manager's polling; a shared page always polls.
Returns
void
applyStartPolicy()
function applyStartPolicy(serverSettings): void;Defined in: selkies-ws-core.js:4376
Applies the session's start policy from a connection's first
server_settings payload: the *_on_start settings say which pipelines
this page starts with. Only a session owner's primary display page is
governed (a shared viewer cannot switch video or audio on, and a second
display page exists to show its display), and a pipeline the user already
toggled keeps that choice. Video and audio off are applied before anything
was requested, and the server starts neither for this page; the
microphone and webcam start their uplinks; the gamepad policy seeds a
toggle the browser has not persisted.
Parameters
| Parameter | Type | Description |
|---|---|---|
serverSettings | { } | - |
Returns
void
postSidebarButtonUpdate()
function postSidebarButtonUpdate(): void;Defined in: selkies-ws-core.js:4426
Posts sidebarButtonStatusUpdate with the state of every pipeline toggle to the dashboards.
Returns
void
receiveMessage()
function receiveMessage(event): void;Defined in: selkies-ws-core.js:4453
Handles the window messages the dashboards post to the core (same origin
only): volume and mute, local scaling, the virtual keyboard, CSS scaling,
anti-aliasing, cursor rendering, manual resolution and its reset, pipeline
and gamepad control, audio device selection, stream commands, clipboard
pushes, and the getStats and settings requests. See the module
docblock for the full vocabulary. A setUseCssScaling with persist: false is server-authored and leaves the user's stored key untouched; the
resolution paths honor enable_resize=false, which pins the primary's
resolution server-side while a secondary stays resizable; and
clipboardImageUpdate reports every skip so a dead click never reads as a
bug.
Parameters
| Parameter | Type | Description |
|---|---|---|
event | MessageEvent<any> | - |
Returns
void
notifyClipboardImageSkip()
function notifyClipboardImageSkip(reason, code): void;Defined in: selkies-ws-core.js:4961
Tells the dashboard why a clipboard-image upload was skipped, in the
fileUpload warning channel transfer warnings already use.
Parameters
| Parameter | Type | Description |
|---|---|---|
reason | string | Human-readable reason. |
code | string | Translation key the dashboards map to a localized message. |
Returns
void
notifyClipboardImageWriteFailed()
function notifyClipboardImageWriteFailed(error): void;Defined in: selkies-ws-core.js:4976
Tells the dashboard that a server image never reached the local clipboard.
The panel shows nothing of an inbound image but this notice, so a write the browser refuses would otherwise read as the feature not working at all.
Parameters
| Parameter | Type | Description |
|---|---|---|
error | any | What the write threw. |
Returns
void
sendClipboardData()
function sendClipboardData(
data,
mimeType?,
onSkip?
): Promise<void>;Defined in: selkies-ws-core.js:4999
Sends local clipboard content to the server as a chunked transfer (lib/clipboard-worker-bridge.js, the same wire protocol and worker offload as the WebRTC core), gated on the clipboard-in setting and the change-only sync. A bufferedAmount backpressure gate keeps a burst from starving the microphone and input on the same socket; only a completed transfer marks the content synced, so an aborted one stays re-sendable.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
data | string | ArrayBuffer | Uint8Array<ArrayBufferLike> | undefined | Text, or image bytes. |
mimeType? | string | 'text/plain' | Forced to text/plain for text. |
onSkip? | Function | null | Called with reason and code when nothing was sent. |
Returns
Promise<void>
handleSettingsMessage()
function handleSettingsMessage(settings, fromServer?): void;Defined in: selkies-ws-core.js:5074
Applies a settings payload to the runtime and pushes the result to the server. A dashboard-authored payload is persisted; a server-authored one (the locked and overridden values replayed on every connect) is applied but never written to the user's own keys, where it would outlive the lock and masquerade as their pick. An encoder switch tears the decoders down and asks for a keyframe once the server's restart settles, in case its restart IDR beat the reset over the wire.
Parameters
| Parameter | Type | Description |
|---|---|---|
settings | { } | Keys named as the server knows them. |
fromServer? | boolean | - |
Returns
void
fetchLatestRCvalue()
function fetchLatestRCvalue(newMode): void;Defined in: selkies-ws-core.js:5266
Re-reads the stored value the new rate-control mode governs (bitrate for
cbr, CRF for crf).
Parameters
| Parameter | Type | Description |
|---|---|---|
newMode | string | - |
Returns
void
sendStatsMessage()
function sendStatsMessage(): void;Defined in: selkies-ws-core.js:5279
Posts a stats snapshot to the parent window: the stream's description on
both sides, the last second's figures where the stats are open, client fps,
buffers and pipeline state.
Returns
void
initWebsockets()
function initWebsockets(): void;Defined in: selkies-ws-core.js:5309
Runs the connection: pre-flight checks and the page build, the clipboard gesture wiring, the tab visibility handling, the paint loop, audio setup, and the socket with its message dispatch, reconnect and fallback paths. Called once the document has loaded.
Returns
void
clearVideoCanvasVisually()
function clearVideoCanvasVisually(): void;Defined in: selkies-ws-core.js:5350
Clears the canvas so a paused stream does not show a stale frame.
Returns
void
uniqueJpeg()
function uniqueJpeg(jpeg, tag): Uint8Array<ArrayBuffer>;Defined in: selkies-ws-core.js:5484
A byte-unique copy of jpeg: a JPEG comment segment carrying tag is spliced in after
SOI. The decode work is identical and the bytes have never been seen, so nothing the race
measures can be answered from a cache -- which is not hypothetical, since sharing one
sample across the routes makes a later one measure two to four times faster than it
sustains, and picked the wrong route for Firefox one run in three.
Parameters
| Parameter | Type |
|---|---|
jpeg | any |
tag | any |
Returns
Uint8Array<ArrayBuffer>
settleJpegRoute()
function settleJpegRoute(): Promise<string>;Defined in: selkies-ws-core.js:5520
Race the routes this engine has and keep the fastest, on a stripe the size the session sends and at the concurrency it decodes at.
Which wins is an engine's own business and moves with its releases, so it is measured
rather than named: at 1080p in eight stripes, Firefox decodes 160 fps through
ImageDecoder against 48 through createImageBitmap, while Chromium runs 99 through
createImageBitmap against 62 through ImageDecoder -- opposite answers, and a fixed
order hands one of them the slower route. WebKit carries no ImageDecoder at all, and an
<img> is raced beside them because Safari is reported to decode faster through one than
through createImageBitmap -- an engine no proxy here stands in for, and the reason the
choice is raced rather than named.
The race draws each decode, because ImageDecoder resolves before the pixels are
drawable on some engines and only defers that cost into the paint loop: timing the
decode alone picks ImageDecoder on Chromium, which the sustained rate contradicts.
A small serial sample misleads the same way, measuring per-call latency rather than the
throughput the paint loop spends. Falls back to the first working route if it cannot run.
Returns
Promise<string>
decodeAndQueueJpegStripe()
function decodeAndQueueJpegStripe(
startY,
jpegData,
frameId
): Promise<void>;Defined in: selkies-ws-core.js:5581
Decodes a JPEG stripe and queues it for the paint loop, through whichever route this
engine decodes fastest (see settleJpegRoute).
Parameters
| Parameter | Type | Description |
|---|---|---|
startY | number | - |
jpegData | ArrayBuffer | - |
frameId | number | - |
Returns
Promise<void>
schedulePaintVideoFrame()
function schedulePaintVideoFrame(): void;Defined in: selkies-ws-core.js:5614
Schedules the next paint tick on one rAF chain; starting the loop again (a reconnect) must never create a second permanent chain.
Returns
void
paintVideoFrame()
function paintVideoFrame(): void;Defined in: selkies-ws-core.js:5637
The per-rAF paint tick. Full-frame h264enc presents only the newest queued frame; the striped modes composite their stripes and present the whole frame as soon as its last row lands (the server emits a frame's stripes in ascending order, so the last row proves it complete) or the socket and the decoders go quiet (the stripe clock), falling back to presenting at frame-id boundaries while stripes still flow; JPEG skips stripes that decoded out of order; the shared main decoder path keeps the adaptive jitter cushion, closing everything older than it in one tick because draining one per rAF would let a burst back up the decoder's bounded output pool. Leaving a full-frame mode tears both video sinks down symmetrically, or a worker canvas would stay shown over the striped content.
Returns
void
wireDecoderToWorklet()
function wireDecoderToWorklet(): void;Defined in: selkies-ws-core.js:5820
Connects the decoder worker straight to the playback worklet.
Decoded packets otherwise pass through the page to reach the worklet, so
anything occupying its thread -- a dashboard re-render, a getUserMedia
prompt -- stops playback being fed and the queue drains into concealment.
Called whenever either end appears; the page's own relay stays as the
fallback for a build where the channel never gets made.
Returns
void
wireSocketToDecoder()
function wireSocketToDecoder(): void;Defined in: selkies-ws-core.js:5835
Connects the socket worker to the decoder, completing a path that reaches playback without the page's thread on it at any point.
Returns
void
initializeDecoderAudio()
function initializeDecoderAudio(): Promise<void>;Defined in: selkies-ws-core.js:6553
Reinitializes the audio decoder in its worker, building the whole pipeline first if it is missing.
Returns
Promise<void>
sendBackpressureAck()
function sendBackpressureAck(): void;Defined in: selkies-ws-core.js:6622
Acks the newest video frame the client is done with, so the server can pace its sends against what this client actually keeps up with. The striped modes composite on the page and ack what reached the screen; a client whose rendering falls behind is then throttled instead of being sent frames it will never show. Full-frame h264enc presents through sinks the page cannot observe, so there the newest received id is the best the client knows. An unchanged id is repeated every ACK_HEARTBEAT_MS, the liveness signal an idle damage-gated stream otherwise lacks.
Returns
void
sendClientMetrics()
function sendClientMetrics(): void;Defined in: selkies-ws-core.js:6654
Metrics tick: refreshes the audio buffer depth the backpressure gates
read and publishes window.fps — composites presented per second in the
striped modes, and the wire's frame ids per second for full-frame h264enc,
whose sinks present outside the page — independent of whether a dashboard
is open.
Returns
void
reloadPossiblyFlippingMode()
function reloadPossiblyFlippingMode(): Promise<void>;Defined in: selkies-ws-core.js:8110
Reloads the page, first switching the stored stream mode to WebRTC when the server is serving that transport: a plain GET on the transport endpoint answers 409 exactly then. One attempt per connect cycle, and only if this session never connected, so a client whose stored mode disagrees with the server converges instead of loop-reloading.
Returns
Promise<void>
cleanupJpegStripeQueue()
function cleanupJpegStripeQueue(): void;Defined in: selkies-ws-core.js:8139
Closes every queued JPEG stripe image and resets the frame-boundary blit latch, which stale would blit the previous mode's back-buffer once.
Returns
void
clearDecodedStripesQueue()
function clearDecodedStripesQueue(): void;Defined in: selkies-ws-core.js:8159
Closes every decoded stripe awaiting the paint loop.
Returns
void
getAudioChannelCount()
function getAudioChannelCount(): number;Defined in: selkies-ws-core.js:8186
The server's audio_channels setting, limited to the layouts the decoder handles.
Returns
number
1, 2, 6 or 8; 2 when unset or unknown.
buildMultiopusDescription()
function buildMultiopusDescription(channels): ArrayBuffer;Defined in: selkies-ws-core.js:8199
Builds the OpusHead description for a surround layout: magic, version 1, channel count, a zero pre-skip (a live stream has nothing to trim), the 48 kHz input rate, zero output gain, mapping family 1 (multistream), then the stream and coupled counts and the channel mapping table.
Parameters
| Parameter | Type | Description |
|---|---|---|
channels | number | - |
Returns
ArrayBuffer
null for a layout the client does not know.
startMicrophoneCapture()
function startMicrophoneCapture(askedByServer?): Promise<void>;Defined in: selkies-ws-core.js:8495
Starts the microphone uplink: getUserMedia at 24 kHz mono with processing on, the capture worklet, and the encode worker whose Opus frames go straight onto the socket, so only encoded bytes cross the wire and the server decodes in pcmflux. Blocked for shared viewers.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
askedByServer? | boolean | false | The session asked rather than the user, so a refusal latches instead of raising a dialog. |
Returns
Promise<void>
stopMicrophoneCapture()
function stopMicrophoneCapture(): void;Defined in: selkies-ws-core.js:8589
Stops the microphone uplink and releases the stream, worklet, worker and context.
Returns
void
startWebcamCapture()
function startWebcamCapture(askedByServer?): void;Defined in: selkies-ws-core.js:8662
Starts the webcam uplink (lib/webcam-capture.js): each encoded frame is
sent as one binary [0x06][codec][flags][payload] message that the
server's virtual camera decodes for the V4L2 device. Flags bit 0 marks a
keyframe; bits 1 to 2 carry the frame's clockwise rotation in quarter turns
and bit 3 a horizontal flip applied after it, the orientation metadata the
encoder never bakes into the bitstream. Frames are dropped rather than
queued while the socket is backed up (WEBCAM_QUEUE_MS). Blocked for
shared viewers.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
askedByServer? | boolean | false | The session asked rather than the user, so a refusal latches instead of raising a dialog. |
Returns
void
stopWebcamCapture()
function stopWebcamCapture(): void;Defined in: selkies-ws-core.js:8713
Stops the webcam uplink.
Returns
void
cleanup()
function cleanup(): void;Defined in: selkies-ws-core.js:8725
Tears everything down on unload: timers, capture, socket, audio, decoders and buffers, then resets the UI state.
Returns
void
performServerInitiatedVideoReset()
function performServerInitiatedVideoReset(reason?): void;Defined in: selkies-ws-core.js:8795
Resets the video state after the server's PIPELINE_RESETTING: the shared keyframe gate, the frame id, every buffer and the decoders of the current mode, clearing the canvas for the modes that repaint it whole.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
reason? | string | "unknown" | Logged. |
Returns
void
requestKeyframe()
function requestKeyframe(): void;Defined in: selkies-ws-core.js:8837
Asks the server for an IDR when a decoder waits for its first keyframe (a recreated stripe decoder, a shared viewer joining). The GOP is infinite, so this is the only recovery path and shared viewers request too; debounced here, harder for shared viewers, and rate-limited server-side.
Returns
void
restartDecodersForAcceleration()
function restartDecodersForAcceleration(): void;Defined in: selkies-ws-core.js:8853
Rebuilds every video decoder so a changed acceleration preference takes hold, then resyncs from a fresh IDR. The main decoder is only fed in shared mode; the stripe and worker decoders are rebuilt from the next keyframe by the paths that own them, and a worker decoder disqualified by the same broken path gets its turn back.
Returns
void
initiateFallback()
function initiateFallback(error, context): void;Defined in: selkies-ws-core.js:8879
The decoder fallback ladder. A codec reclaimed by the browser is a soft error left to the tab-focus re-init. A decoder that accepted its config and then failed is the signature of a broken hardware path, so the first hard error retries the same encoder on software decode; errors from the decoders that switch replaced are absorbed for a settle period. A failure after that forgets the preference, counts a crash, and reloads: a shared viewer just resyncs, a controller resets its settings to safe defaults, stepping the encoder down to h264enc and, at three crashes, to jpeg. jpeg mode runs no VideoDecoder, so an error there is handover noise from a stream the server has yet to stop and never escalates.
Parameters
| Parameter | Type | Description |
|---|---|---|
error | Error | DOMException | - |
context | string | Which decoder failed. |
Returns
void
runPreflightChecks()
function runPreflightChecks(): boolean;Defined in: selkies-ws-core.js:8969
Builds the UI and checks the engine: a secure context is required; without WebCodecs the stream is pinned to the jpeg encoder, which decodes through createImageBitmap, and a server-locked H.264 encoder is reported when it arrives rather than decoded into a crash loop.
Returns
boolean
False when the page cannot run.
pinJpegEncoder()
function pinJpegEncoder(): void;Defined in: selkies-ws-core.js:8991
Pins the jpeg encoder, the fallback ladder's last rung.
Returns
void
References
websockets
Re-exports websockets