@myrialabs/clopen 0.4.21 → 0.4.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +2 -1
  2. package/backend/artifacts/generate.ts +11 -5
  3. package/backend/auth/permissions.ts +8 -8
  4. package/backend/engine/README.md +11 -8
  5. package/backend/engine/adapters/codex/error-handler.ts +1 -1
  6. package/backend/engine/adapters/qwen/error-handler.ts +1 -1
  7. package/backend/engine/docs/adapter-contract.md +66 -2
  8. package/backend/engine/docs/adding-an-engine.md +46 -7
  9. package/backend/engine/docs/frontend-and-chat.md +80 -17
  10. package/backend/engine/docs/lessons-learned.md +126 -7
  11. package/backend/engine/docs/quick-reference.md +12 -3
  12. package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
  13. package/backend/engine/docs/websocket-routes.md +54 -15
  14. package/backend/engine/install-runner.ts +4 -4
  15. package/backend/engine/resolve-model.ts +87 -0
  16. package/backend/engine/structured-helpers.test.ts +64 -0
  17. package/backend/engine/structured-helpers.ts +105 -13
  18. package/backend/mcp/README.md +32 -11
  19. package/backend/mcp/internal/config.ts +3 -20
  20. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
  21. package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
  22. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
  23. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
  24. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
  25. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
  26. package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
  27. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -0
  28. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +79 -0
  29. package/backend/mcp/internal/servers/browser-automation/context.ts +100 -0
  30. package/backend/mcp/internal/servers/browser-automation/description.ts +60 -0
  31. package/backend/mcp/internal/servers/browser-automation/format.ts +62 -0
  32. package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
  33. package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
  34. package/backend/mcp/internal/servers/browser-automation/runner.ts +269 -0
  35. package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
  36. package/backend/preview/browser/browser-console-manager.ts +310 -156
  37. package/backend/preview/browser/browser-dialog-handler.ts +45 -16
  38. package/backend/preview/browser/browser-host-bridge.ts +471 -0
  39. package/backend/preview/browser/browser-interaction-handler.ts +868 -297
  40. package/backend/preview/browser/browser-mcp-control.ts +7 -2
  41. package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
  42. package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
  43. package/backend/preview/browser/browser-pool.ts +83 -9
  44. package/backend/preview/browser/browser-preview-service.ts +432 -53
  45. package/backend/preview/browser/browser-tab-manager.ts +16 -16
  46. package/backend/preview/browser/browser-video-capture.ts +1334 -386
  47. package/backend/preview/browser/capture-profile.ts +213 -0
  48. package/backend/preview/browser/element-locator.ts +357 -0
  49. package/backend/preview/browser/frame-targeting.ts +92 -0
  50. package/backend/preview/browser/scripts/audio-stream.ts +258 -78
  51. package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
  52. package/backend/preview/browser/scripts/video-stream.ts +803 -177
  53. package/backend/preview/browser/types.ts +397 -37
  54. package/backend/utils/cli.ts +1 -1
  55. package/backend/utils/path-enrich.ts +2 -2
  56. package/backend/ws/README.md +1 -1
  57. package/backend/ws/artifacts/generate.ts +2 -1
  58. package/backend/ws/engine/codex/accounts.ts +1 -1
  59. package/backend/ws/engine/codex/status.ts +1 -1
  60. package/backend/ws/git/branch-name.ts +11 -5
  61. package/backend/ws/git/commit-message.ts +11 -5
  62. package/backend/ws/index.ts +3 -3
  63. package/backend/ws/preview/browser/host.ts +95 -0
  64. package/backend/ws/preview/browser/interact.ts +204 -10
  65. package/backend/ws/preview/browser/native-ui.ts +31 -1
  66. package/backend/ws/preview/browser/tab-info.ts +10 -1
  67. package/backend/ws/preview/browser/tab.ts +43 -0
  68. package/backend/ws/preview/browser/webcodecs.ts +180 -53
  69. package/backend/ws/preview/index.ts +58 -1
  70. package/backend/ws/{system-tools → stack}/access.ts +1 -1
  71. package/backend/ws/stack/index.ts +16 -0
  72. package/backend/ws/{system-tools → stack}/install.ts +7 -7
  73. package/backend/ws/{system-tools → stack}/status.ts +7 -7
  74. package/dist/assets/{index-CEGW8vEt.js → index-DH_GO0Lf.js} +1 -1
  75. package/dist/assets/{index-B8YRz8wG.js → index-igSQ3JaM.js} +1 -1
  76. package/dist/assets/main-BD3-qPfT.css +1 -0
  77. package/dist/assets/{main-D-2ByODy.js → main-D-d8SFfW.js} +384 -358
  78. package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
  79. package/dist/index.html +2 -2
  80. package/package.json +1 -1
  81. package/shared/types/stores/settings.ts +6 -0
  82. package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
  83. package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
  84. package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
  85. package/backend/ws/system-tools/index.ts +0 -16
  86. package/dist/assets/main-D8I0MfRQ.css +0 -1
@@ -6,9 +6,23 @@
6
6
  * 2. Initialize VideoEncoder for encoding frames
7
7
  * 3. Handle WebRTC signaling (offer/answer/ICE)
8
8
  * 4. Send encoded video chunks via DataChannel
9
+ *
10
+ * Two capture modes feed the encoder:
11
+ *
12
+ * - **native** — `getDisplayMedia({preferCurrentTab})` + MediaStreamTrackProcessor.
13
+ * Compositor frames arrive as VideoFrame objects and go straight into the
14
+ * encoder. No JPEG encode, no base64, no CDP round-trip; the still-page
15
+ * refresh re-encodes the retained last frame, which is pristine.
16
+ * Requires a secure context, so it is probed and silently skipped otherwise.
17
+ *
18
+ * - **push** — the backend feeds base64 JPEG frames from `Page.screencastFrame`
19
+ * into `encodeFrame()`. Universal fallback; the still-page refresh comes from
20
+ * a high-quality screenshot pushed by the backend.
21
+ *
22
+ * Both modes share one encoder, one adaptive quality ladder and one wire format.
9
23
  */
10
24
 
11
- import type { StreamingConfig } from '../types';
25
+ import type { StreamingConfig, VideoCodecCandidate } from '../types';
12
26
 
13
27
  /**
14
28
  * Generate video encoder script that runs in the browser
@@ -22,8 +36,26 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
22
36
  (window as any).__webCodecsPeer = null;
23
37
  }
24
38
 
25
- let peerConnection: RTCPeerConnection | null = null;
26
- let dataChannel: RTCDataChannel | null = null;
39
+ /**
40
+ * One peer per viewer, all fed by a single encoder.
41
+ *
42
+ * A tab can legitimately be watched from several places at once — the same
43
+ * project open on a laptop and a phone through Remote Access, or the preview
44
+ * shown in two split panels. With a single connection each new viewer's
45
+ * handshake tore down the previous one's channel, whose health check then
46
+ * reconnected and tore down the newcomer's: the tab flickered between them
47
+ * and at least one side sat on "Loading preview…" forever.
48
+ *
49
+ * Encoding once and fanning the chunks out is what keeps that affordable —
50
+ * a second encoder would double the most expensive stage of the pipeline.
51
+ */
52
+ interface ViewerPeer {
53
+ id: string;
54
+ pc: RTCPeerConnection;
55
+ dc: RTCDataChannel | null;
56
+ }
57
+
58
+ const viewers = new Map<string, ViewerPeer>();
27
59
  let videoEncoder: VideoEncoder | null = null;
28
60
  let isCapturing = false;
29
61
  let videoFrameCount = 0;
@@ -33,14 +65,57 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
33
65
  let motionSeq = 0; // Increments per motion frame — used to detect staleness of deferred top-offs
34
66
  let topOffRetryTimer: any = null;
35
67
 
36
- // Codec selection: prefer VP9 in quantizer mode (per-frame quality control,
37
- // Chrome-Remote-Desktop-style), fall back to VP8 with fixed bitrate.
38
- // codecId is embedded in every video packet so the client picks the right decoder.
39
- // vp9Allowed comes from the CLIENT (decode capability, negotiated at stream
40
- // start) — the headless browser can encode VP9, but the viewer must decode it.
41
- let codecId = 0; // 0 = vp8, 1 = vp9
68
+ // Active codec. `codecId` is embedded in every video packet so the client
69
+ // picks the matching decoder; `activeCodec` also decides whether quality is
70
+ // controlled per frame (quantizer mode) or by the configured bitrate.
71
+ let activeCodec: VideoCodecCandidate = config.codecCandidates?.[config.codecCandidates.length - 1] || {
72
+ codec: 'vp8',
73
+ name: 'vp8',
74
+ id: 0
75
+ };
76
+ let codecId = activeCodec.id;
42
77
  let usingQuantizer = false;
43
- let vp9Allowed = true;
78
+
79
+ // Encoder geometry. Kept in sync with whatever the capture source actually
80
+ // produces — Chrome's screencast rounds `maxWidth/maxHeight` to preserve
81
+ // aspect ratio, and tab-capture constraints are advisory, so the incoming
82
+ // frame size is the authority rather than what we asked for.
83
+ let encoderWidth = config.width;
84
+ let encoderHeight = config.height;
85
+ let currentBitrate = config.bitrate;
86
+ let reconfiguring = false;
87
+
88
+ // Adaptive framerate. The backend owns the ladder (it also sees the
89
+ // viewer's decode queue) and pushes the target down here so native capture
90
+ // can ask the compositor for fewer frames instead of discarding them.
91
+ let targetFramerate = config.framerate;
92
+
93
+ // Capture mode + retained frame for still-page refreshes in native mode.
94
+ let captureMode: 'push' | 'native' = 'push';
95
+ let nativeStream: MediaStream | null = null;
96
+ let nativeTrack: MediaStreamTrack | null = null;
97
+ let nativeReader: any = null;
98
+ let lastNativeFrame: VideoFrame | null = null;
99
+ let nativeIdleTimer: any = null;
100
+ let lastNativeEncodeTime = 0;
101
+
102
+ // Encoder cost tracking, reported back to the backend so the framerate
103
+ // ladder reacts to CPU saturation and not just to network congestion.
104
+ //
105
+ // The cost that matters is the whole frame path on this thread — image
106
+ // decode plus the encode call — not the encode call alone, which merely
107
+ // enqueues and always measures near zero. And the queue is tracked as a
108
+ // window maximum: sampling it once every couple of seconds says nothing
109
+ // about whether the encoder is actually falling behind.
110
+ let frameCostSamples = 0;
111
+ let frameCostTotalMs = 0;
112
+ let framesAttempted = 0;
113
+ let framesSkippedEncoder = 0;
114
+ let framesSkippedNetwork = 0;
115
+ let framesEncodedWindow = 0;
116
+ let encodeQueueMax = 0;
117
+ let statsWindowStart = 0;
118
+ let statsReportTimer: any = null;
44
119
 
45
120
  // Source-side backpressure threshold: when the DataChannel can't drain
46
121
  // (slow network), skip encoding motion frames instead of queueing them.
@@ -50,11 +125,26 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
50
125
  // stream degrades to coarser-but-current rather than sharp-but-stale.
51
126
  const MAX_BUFFERED_BYTES = 64 * 1024;
52
127
 
128
+ // Same idea for CPU: anything sitting in the encoder queue is latency the
129
+ // viewer will see. Encoding is asynchronous, so a depth of one or two is
130
+ // normal even on a fast host — the threshold has to sit above that or the
131
+ // pipeline throws away frames it could comfortably have encoded.
132
+ const MAX_ENCODE_QUEUE = 3;
133
+
53
134
  // Frames larger than this are split into fragments (packet type 2) to stay
54
135
  // well under the SCTP max-message-size (~256KB on common WebRTC stacks).
55
136
  // Mostly hit by near-lossless top-off keyframes of complex pages.
56
137
  const FRAGMENT_SIZE = 64 * 1024;
57
138
 
139
+ // Frame sizes within this many pixels of the encoder are treated as the
140
+ // same geometry and snapped, rather than triggering a reconfiguration.
141
+ const SIZE_SNAP_TOLERANCE = 8;
142
+
143
+ // How long the native capture track must be quiet before the retained
144
+ // frame is re-encoded near-losslessly. Mirrors the backend's screencast
145
+ // top-off delay so both modes sharpen at the same moment.
146
+ const NATIVE_TOP_OFF_DELAY_MS = 300;
147
+
58
148
  // Cursor tracking
59
149
  let lastCursor = 'default';
60
150
  let cursorCheckInterval: any = null;
@@ -118,121 +208,205 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
118
208
  lastCursor = 'default';
119
209
  }
120
210
 
121
- // Build encoder config for the currently selected codec mode
122
- function buildEncoderConfig(width: number, height: number, bitrate?: number): VideoEncoderConfig {
123
- if (usingQuantizer) {
124
- // Quantizer mode: no bitrate — quality is controlled per-frame in encode()
125
- return {
126
- codec: 'vp09.00.10.08',
127
- width,
128
- height,
129
- framerate: config.framerate,
130
- bitrateMode: 'quantizer',
131
- hardwareAcceleration: config.hardwareAcceleration,
132
- latencyMode: config.latencyMode
133
- } as VideoEncoderConfig;
134
- }
135
-
136
- return {
137
- codec: config.codec,
211
+ // Build encoder config for a codec candidate at the current geometry
212
+ function buildEncoderConfig(candidate: VideoCodecCandidate, width: number, height: number, bitrate: number): VideoEncoderConfig {
213
+ const base: any = {
214
+ codec: candidate.codec,
138
215
  width,
139
216
  height,
140
- bitrate: bitrate || config.bitrate,
141
- framerate: config.framerate,
217
+ framerate: targetFramerate,
142
218
  hardwareAcceleration: config.hardwareAcceleration,
143
219
  latencyMode: config.latencyMode
144
220
  };
221
+
222
+ if (candidate.annexb) {
223
+ // Raw chunks travel without a `description`, so the stream has to
224
+ // be self-describing. AVCC (Chrome's default) would be undecodable.
225
+ base.avc = { format: 'annexb' };
226
+ }
227
+
228
+ if (candidate.quantizerKey) {
229
+ // Quantizer mode: no bitrate — quality is chosen per frame in encode()
230
+ base.bitrateMode = 'quantizer';
231
+ } else {
232
+ base.bitrate = bitrate;
233
+ base.bitrateMode = 'variable';
234
+ }
235
+
236
+ return base as VideoEncoderConfig;
145
237
  }
146
238
 
147
- // Detect supported video codec — prefer VP9 quantizer mode, fall back to VP8
148
- async function detectVideoCodec() {
149
- if (vp9Allowed) {
150
- usingQuantizer = true;
151
- codecId = 1;
152
- const vp9Config = buildEncoderConfig(config.width, config.height);
239
+ /**
240
+ * Pick the first codec candidate this browser can actually encode.
241
+ * The list arrives pre-ordered by the backend from the viewer's decode
242
+ * capabilities, so the first supported entry is also the best for the pair.
243
+ */
244
+ async function detectVideoCodec(width: number, height: number, bitrate: number) {
245
+ const candidates: VideoCodecCandidate[] =
246
+ config.codecCandidates && config.codecCandidates.length > 0
247
+ ? config.codecCandidates
248
+ : [{ codec: config.codec || 'vp8', name: 'vp8', id: 0 } as VideoCodecCandidate];
249
+
250
+ for (const candidate of candidates) {
251
+ const encoderConfig = buildEncoderConfig(candidate, width, height, bitrate);
153
252
  try {
154
- const support = await VideoEncoder.isConfigSupported(vp9Config);
253
+ const support = await VideoEncoder.isConfigSupported(encoderConfig);
155
254
  if (support.supported) {
156
- return vp9Config;
255
+ activeCodec = candidate;
256
+ codecId = candidate.id;
257
+ usingQuantizer = !!candidate.quantizerKey;
258
+ return encoderConfig;
157
259
  }
158
260
  } catch (e) {}
159
261
  }
160
262
 
161
- usingQuantizer = false;
162
- codecId = 0;
163
- const vp8Config = buildEncoderConfig(config.width, config.height);
164
- try {
165
- const support = await VideoEncoder.isConfigSupported(vp8Config);
166
- if (support.supported) {
167
- return vp8Config;
168
- }
169
- } catch (e) {}
170
-
171
263
  return null;
172
264
  }
173
265
 
174
- // Initialize RTCPeerConnection
175
- async function initPeerConnection() {
176
- if (peerConnection) {
177
- peerConnection.close();
266
+ /** Channels that can be written to right now. */
267
+ function openChannels(): RTCDataChannel[] {
268
+ const channels: RTCDataChannel[] = [];
269
+ viewers.forEach((viewer) => {
270
+ if (viewer.dc && viewer.dc.readyState === 'open') channels.push(viewer.dc);
271
+ });
272
+ return channels;
273
+ }
274
+
275
+ function hasOpenChannel(): boolean {
276
+ let open = false;
277
+ viewers.forEach((viewer) => {
278
+ if (viewer.dc && viewer.dc.readyState === 'open') open = true;
279
+ });
280
+ return open;
281
+ }
282
+
283
+ /**
284
+ * Congestion of the *worst* viewer.
285
+ *
286
+ * Every backpressure decision below is about whether to produce the next
287
+ * frame at all, and a frame is produced once for everyone. Pacing to the
288
+ * slowest link is therefore the only coherent answer: the encoded stream is
289
+ * a delta chain, so chunks cannot be dropped for one viewer and kept for
290
+ * another without corrupting that viewer's picture until the next keyframe.
291
+ */
292
+ function peakBufferedAmount(): number {
293
+ let peak = 0;
294
+ viewers.forEach((viewer) => {
295
+ if (viewer.dc && viewer.dc.readyState === 'open' && viewer.dc.bufferedAmount > peak) {
296
+ peak = viewer.dc.bufferedAmount;
297
+ }
298
+ });
299
+ return peak;
300
+ }
301
+
302
+ function broadcast(packet: ArrayBuffer) {
303
+ const channels = openChannels();
304
+ for (let i = 0; i < channels.length; i++) {
305
+ try {
306
+ channels[i].send(packet);
307
+ } catch (e) {
308
+ // One stalled viewer must not cost the others their frame.
309
+ }
178
310
  }
311
+ }
312
+
313
+ function closePeer(viewerId: string) {
314
+ const viewer = viewers.get(viewerId);
315
+ if (!viewer) return false;
316
+
317
+ viewers.delete(viewerId);
318
+ try {
319
+ viewer.dc?.close();
320
+ } catch (e) {}
321
+ try {
322
+ viewer.pc.close();
323
+ } catch (e) {}
324
+ return true;
325
+ }
326
+
327
+ // Create a peer connection for one viewer
328
+ function createViewerPeer(viewerId: string): ViewerPeer {
329
+ closePeer(viewerId);
179
330
 
180
- peerConnection = new RTCPeerConnection({ iceServers });
331
+ const pc = new RTCPeerConnection({ iceServers });
332
+ const viewer: ViewerPeer = { id: viewerId, pc, dc: null };
333
+ viewers.set(viewerId, viewer);
181
334
 
182
335
  // Handle ICE candidates
183
- peerConnection.onicecandidate = (event) => {
336
+ pc.onicecandidate = (event) => {
184
337
  if (event.candidate && (window as any).__sendIceCandidate) {
185
338
  const candidateInit = {
186
339
  candidate: event.candidate.candidate,
187
340
  sdpMid: event.candidate.sdpMid,
188
341
  sdpMLineIndex: event.candidate.sdpMLineIndex
189
342
  };
190
- (window as any).__sendIceCandidate(candidateInit);
343
+ // The viewer is named explicitly: several handshakes can be in
344
+ // flight at once, and a candidate that reaches the wrong one is
345
+ // simply dropped there — which is a connection that never completes.
346
+ (window as any).__sendIceCandidate(viewerId, candidateInit);
191
347
 
192
348
  // Also send loopback version for VPN compatibility (same-machine peers)
193
349
  const loopback = createLoopbackCandidate(candidateInit);
194
350
  if (loopback) {
195
- (window as any).__sendIceCandidate(loopback);
351
+ (window as any).__sendIceCandidate(viewerId, loopback);
196
352
  }
197
353
  }
198
354
  };
199
355
 
200
356
  // Handle connection state
201
- peerConnection.onconnectionstatechange = () => {
202
- if ((window as any).__sendConnectionState && peerConnection) {
203
- (window as any).__sendConnectionState(peerConnection.connectionState);
357
+ pc.onconnectionstatechange = () => {
358
+ const state = pc.connectionState;
359
+ if ((window as any).__sendConnectionState) {
360
+ (window as any).__sendConnectionState(viewerId, state);
361
+ }
362
+ // A viewer that closed its tab or lost the network leaves a peer
363
+ // behind that would otherwise keep pacing the encoder forever.
364
+ if (state === 'closed' || state === 'failed') {
365
+ if (viewers.get(viewerId) === viewer) closePeer(viewerId);
204
366
  }
205
367
  };
206
368
 
207
- peerConnection.oniceconnectionstatechange = () => {};
369
+ pc.oniceconnectionstatechange = () => {};
208
370
 
209
371
  // Create DataChannel for encoded chunks.
210
- // Reliable + ordered: VP8/VP9 delta chains require in-order, lossless
211
- // delivery — a single lost/reordered chunk corrupts decoding until the
212
- // next keyframe (smearing/ghosting). Latency is bounded by source-side
213
- // frame dropping instead (see MAX_BUFFERED_BYTES backpressure).
214
- dataChannel = peerConnection.createDataChannel('media', {
372
+ // Reliable + ordered: VP8/VP9/H.264 delta chains require in-order,
373
+ // lossless delivery — a single lost/reordered chunk corrupts decoding
374
+ // until the next keyframe (smearing/ghosting). Latency is bounded by
375
+ // source-side frame dropping instead (see MAX_BUFFERED_BYTES).
376
+ const dc = pc.createDataChannel('media', {
215
377
  ordered: true
216
378
  });
217
379
 
218
- dataChannel.binaryType = 'arraybuffer';
380
+ dc.binaryType = 'arraybuffer';
219
381
 
220
- dataChannel.onopen = () => {
221
- // Force keyframe when DataChannel opens — the decoder on the other
222
- // side needs a sync point (keyframes are on-demand only)
382
+ dc.onopen = () => {
383
+ // Force keyframe when a DataChannel opens — the decoder on the other
384
+ // side needs a sync point (keyframes are on-demand only). A viewer
385
+ // joining an established stream needs one just as much as the first.
223
386
  forceNextKeyframe = true;
387
+
388
+ // And produce a frame to carry it. The source pushes a refresh frame
389
+ // when the *peer* reports connected, which is typically a moment before
390
+ // this channel exists — that frame was encoded and then dropped for
391
+ // want of anywhere to send it. On a page that is not moving, nothing
392
+ // else would ever be encoded, and the viewer sits on "Loading
393
+ // preview…" over a perfectly healthy connection.
394
+ forceKeyframe();
395
+ (window as any).__requestRefreshFrame?.(viewerId);
224
396
  };
225
397
 
226
- dataChannel.onclose = () => {};
398
+ dc.onclose = () => {};
399
+
400
+ dc.onerror = (error) => {};
227
401
 
228
- dataChannel.onerror = (error) => {};
402
+ viewer.dc = dc;
229
403
 
230
- return peerConnection;
404
+ return viewer;
231
405
  }
232
406
 
233
407
  // Initialize VideoEncoder
234
408
  async function initVideoEncoder() {
235
- const codecConfig = await detectVideoCodec();
409
+ const codecConfig = await detectVideoCodec(encoderWidth, encoderHeight, currentBitrate);
236
410
  if (!codecConfig) {
237
411
  throw new Error('No supported video codec');
238
412
  }
@@ -247,9 +421,82 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
247
421
  await videoEncoder.configure(codecConfig);
248
422
  }
249
423
 
424
+ /**
425
+ * Keep the encoder's geometry aligned with the frames actually arriving.
426
+ *
427
+ * The capture source is authoritative: CDP rounds screencast dimensions to
428
+ * preserve aspect ratio and tab-capture honours constraints only
429
+ * approximately, so asking for 648×406 can yield 648×405. Encoding a frame
430
+ * whose size differs from the configuration throws, which would stall the
431
+ * stream — reconfiguring on mismatch makes every rounding difference
432
+ * self-healing instead.
433
+ */
434
+ async function ensureEncoderSize(width: number, height: number, tolerant = false): Promise<boolean> {
435
+ if (!videoEncoder || width <= 0 || height <= 0) return false;
436
+ if (width === encoderWidth && height === encoderHeight) return true;
437
+
438
+ // A difference of a pixel or two is rounding, not a geometry change:
439
+ // the screencast fits the viewport inside maxWidth/maxHeight while
440
+ // preserving aspect ratio, and the still-page screenshot is clipped by
441
+ // a single scalar, so the two can land a pixel apart on the same page.
442
+ // Reconfiguring on that reset the encoder — and forced a keyframe plus
443
+ // a client canvas resize — every time motion started or stopped.
444
+ // Callers that pass `tolerant` snap the source instead (see snapSource).
445
+ if (
446
+ tolerant &&
447
+ Math.abs(width - encoderWidth) <= SIZE_SNAP_TOLERANCE &&
448
+ Math.abs(height - encoderHeight) <= SIZE_SNAP_TOLERANCE
449
+ ) {
450
+ return true;
451
+ }
452
+
453
+ if (reconfiguring) return false;
454
+
455
+ reconfiguring = true;
456
+ try {
457
+ encoderWidth = width;
458
+ encoderHeight = height;
459
+ currentBitrate = Math.max(400_000, Math.round(width * height * targetFramerate * 0.045));
460
+
461
+ const encoderConfig = buildEncoderConfig(activeCodec, width, height, currentBitrate);
462
+ videoEncoder.configure(encoderConfig);
463
+ forceNextKeyframe = true;
464
+ return true;
465
+ } catch (e) {
466
+ return false;
467
+ } finally {
468
+ reconfiguring = false;
469
+ }
470
+ }
471
+
472
+ // Scratch surface used to snap an off-by-a-few-pixels source onto the
473
+ // encoder's exact geometry. Only the still-page refresh normally needs it,
474
+ // so this runs about once per still period, not per frame.
475
+ let snapCanvas: OffscreenCanvas | null = null;
476
+ let snapCtx: OffscreenCanvasRenderingContext2D | null = null;
477
+
478
+ function snapSource(bitmap: ImageBitmap): CanvasImageSource {
479
+ if (bitmap.width === encoderWidth && bitmap.height === encoderHeight) {
480
+ return bitmap as unknown as CanvasImageSource;
481
+ }
482
+
483
+ try {
484
+ if (!snapCanvas || snapCanvas.width !== encoderWidth || snapCanvas.height !== encoderHeight) {
485
+ snapCanvas = new OffscreenCanvas(encoderWidth, encoderHeight);
486
+ snapCtx = snapCanvas.getContext('2d', { alpha: false }) as OffscreenCanvasRenderingContext2D | null;
487
+ }
488
+ if (!snapCtx) return bitmap as unknown as CanvasImageSource;
489
+
490
+ snapCtx.drawImage(bitmap, 0, 0, encoderWidth, encoderHeight);
491
+ return snapCanvas as unknown as CanvasImageSource;
492
+ } catch (e) {
493
+ return bitmap as unknown as CanvasImageSource;
494
+ }
495
+ }
496
+
250
497
  // Handle encoded video chunk
251
498
  function handleEncodedVideoChunk(chunk: EncodedVideoChunk, metadata: any) {
252
- if (!dataChannel || dataChannel.readyState !== 'open') return;
499
+ if (!hasOpenChannel()) return;
253
500
 
254
501
  const isKeyframe = chunk.type === 'key' ? 1 : 0;
255
502
  const timestamp = chunk.timestamp;
@@ -270,14 +517,14 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
270
517
  view.setBigUint64(1, BigInt(timestamp), true);
271
518
  // Keyframe flag
272
519
  view.setUint8(9, isKeyframe);
273
- // Codec: 0 = vp8, 1 = vp9 (lets the client pick the right decoder)
520
+ // Codec: 0 = vp8, 1 = vp9, 2 = avc (lets the client pick the right decoder)
274
521
  view.setUint8(10, codecId);
275
522
  // Data size
276
523
  view.setUint32(11, data.byteLength, true);
277
524
  // Copy data
278
525
  packetData.set(data, 15);
279
526
 
280
- dataChannel.send(packet);
527
+ broadcast(packet);
281
528
  } else {
282
529
  // Large frame (e.g. near-lossless top-off keyframe) — fragment.
283
530
  // The channel is reliable + ordered, so fragments arrive in order
@@ -303,7 +550,7 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
303
550
  view.setUint32(15, fragData.byteLength, true);
304
551
  packetData.set(fragData, 19);
305
552
 
306
- dataChannel.send(packet);
553
+ broadcast(packet);
307
554
  }
308
555
  }
309
556
 
@@ -313,11 +560,11 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
313
560
 
314
561
  // Send audio chunk (called from AudioContext interception)
315
562
  function sendAudioChunk(timestamp: number, data: Uint8Array) {
316
- if (!dataChannel || dataChannel.readyState !== 'open') return;
563
+ if (!hasOpenChannel()) return;
317
564
 
318
565
  // Backpressure: drop audio when the channel is congested — the client's
319
566
  // playback scheduler handles gaps cleanly, and stale audio is worthless
320
- if (dataChannel.bufferedAmount > MAX_BUFFERED_BYTES) return;
567
+ if (peakBufferedAmount() > MAX_BUFFERED_BYTES) return;
321
568
 
322
569
  // Format: [type(1)][timestamp(8)][size(4)][data]
323
570
  const packet = new ArrayBuffer(1 + 8 + 4 + data.byteLength);
@@ -334,7 +581,7 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
334
581
  packetData.set(data, 13);
335
582
 
336
583
  try {
337
- dataChannel.send(packet);
584
+ broadcast(packet);
338
585
  audioFrameCount++;
339
586
  } catch (e) {}
340
587
  }
@@ -344,30 +591,119 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
344
591
  // still-page top-off restores full quality once motion stops, so temporary
345
592
  // coarseness during congestion is invisible in the end result.
346
593
  function currentMotionQuantizer(): number {
347
- const buffered = dataChannel ? dataChannel.bufferedAmount : 0;
594
+ const buffered = peakBufferedAmount();
348
595
  if (buffered > MAX_BUFFERED_BYTES / 2) return Math.min(60, config.motionQuantizer + 16);
349
596
  if (buffered > MAX_BUFFERED_BYTES / 4) return Math.min(60, config.motionQuantizer + 8);
350
597
  return config.motionQuantizer;
351
598
  }
352
599
 
353
- // Encode video frame from image data.
600
+ /**
601
+ * Whether a motion frame should be skipped before any decode/encode work.
602
+ *
603
+ * Two independent limits, both of which mean "the viewer is already behind":
604
+ * the network can't drain the channel, or this host can't encode fast
605
+ * enough. Dropping input frames is safe — the encoder simply references the
606
+ * last encoded frame — whereas dropping encoded chunks would corrupt the
607
+ * delta chain.
608
+ */
609
+ function shouldSkipMotionFrame(): boolean {
610
+ framesAttempted++;
611
+
612
+ if (peakBufferedAmount() > MAX_BUFFERED_BYTES) {
613
+ framesSkippedNetwork++;
614
+ return true;
615
+ }
616
+ if (videoEncoder) {
617
+ if (videoEncoder.encodeQueueSize > encodeQueueMax) {
618
+ encodeQueueMax = videoEncoder.encodeQueueSize;
619
+ }
620
+ if (videoEncoder.encodeQueueSize >= MAX_ENCODE_QUEUE) {
621
+ framesSkippedEncoder++;
622
+ return true;
623
+ }
624
+ }
625
+ return false;
626
+ }
627
+
628
+ /**
629
+ * Encode a VideoFrame with the right quality for its kind.
630
+ *
631
+ * In quantizer mode quality is per frame: coarse during motion (raised
632
+ * further under congestion), near-lossless for the still-page refresh. In
633
+ * fixed-bitrate mode (H.264, VP8) the same effect is achieved by briefly
634
+ * raising the target bitrate around the refresh keyframe, since there is no
635
+ * per-frame quality knob.
636
+ */
637
+ function encodeVideoFrame(frame: VideoFrame, isTopOff: boolean) {
638
+ if (!videoEncoder) return;
639
+
640
+ const now = Date.now();
641
+ const needsKeyframe =
642
+ forceNextKeyframe ||
643
+ (isTopOff && !usingQuantizer) ||
644
+ (config.keyframeInterval > 0 && now - lastKeyframeTime > config.keyframeInterval * 1000);
645
+
646
+ if (needsKeyframe) {
647
+ lastKeyframeTime = now;
648
+ forceNextKeyframe = false;
649
+ }
650
+
651
+ if (usingQuantizer && activeCodec.quantizerKey) {
652
+ const quantizer = isTopOff ? config.topOffQuantizer : currentMotionQuantizer();
653
+ const options: any = { keyFrame: needsKeyframe };
654
+ options[activeCodec.quantizerKey] = { quantizer };
655
+ videoEncoder.encode(frame, options as VideoEncoderEncodeOptions);
656
+ } else {
657
+ // Fixed-bitrate codec. The still-page refresh is a plain keyframe:
658
+ // VBR already spends far more on keyframes than on deltas, and
659
+ // reconfiguring the encoder to bump the bitrate around it resets
660
+ // the codec twice per still period — on a page with any recurring
661
+ // damage (a blinking caret is enough) that is a reset storm.
662
+ videoEncoder.encode(frame, { keyFrame: needsKeyframe || isTopOff });
663
+ }
664
+
665
+ videoFrameCount++;
666
+ if (!isTopOff) framesEncodedWindow++;
667
+ }
668
+
669
+ /**
670
+ * Decode base64 into bytes.
671
+ *
672
+ * `Uint8Array.fromBase64` is a single native pass; the manual loop it
673
+ * replaces ran `charCodeAt` per byte, which at full-viewport resolution was
674
+ * millions of calls per second on the page's main thread.
675
+ */
676
+ function base64ToBytes(input: string): Uint8Array<ArrayBuffer> {
677
+ const fromBase64 = (Uint8Array as any).fromBase64;
678
+ if (typeof fromBase64 === 'function') {
679
+ try {
680
+ return fromBase64.call(Uint8Array, input) as Uint8Array<ArrayBuffer>;
681
+ } catch (e) {}
682
+ }
683
+
684
+ const binaryStr = atob(input);
685
+ const len = binaryStr.length;
686
+ const bytes = new Uint8Array(len);
687
+ for (let i = 0; i < len; i++) {
688
+ bytes[i] = binaryStr.charCodeAt(i);
689
+ }
690
+ return bytes;
691
+ }
692
+
693
+ // Encode video frame from image data (push mode).
354
694
  // Motion frames arrive as JPEG (CDP screencast); top-off frames arrive as
355
- // lossless PNG (Page.captureScreenshot) when the page goes still, and are
356
- // encoded near-losslessly so the last motion-degraded frame doesn't stick.
357
- async function encodeFrame(imageData: string, isTopOff?: boolean) {
695
+ // a high-quality screenshot when the page goes still, and are encoded
696
+ // near-losslessly so the last motion-degraded frame doesn't stick.
697
+ async function encodeFrame(imageData: string, isTopOff?: boolean, mimeType?: string) {
358
698
  if (!videoEncoder || !isCapturing) return;
699
+ // Native capture owns the encoder — a stray pushed frame would fight it.
700
+ if (captureMode === 'native' && !isTopOff) return;
359
701
 
360
702
  try {
361
- // Source-side backpressure: if the network can't drain the channel,
362
- // skip motion frames BEFORE decoding/encoding. Dropping input frames
363
- // is safe (the encoder just references the last encoded frame);
364
- // dropping encoded chunks would corrupt the delta chain.
365
703
  if (!isTopOff) {
366
704
  motionSeq++;
367
- if (dataChannel && dataChannel.bufferedAmount > MAX_BUFFERED_BYTES) {
368
- return;
369
- }
370
- } else if (dataChannel && dataChannel.bufferedAmount > MAX_BUFFERED_BYTES) {
705
+ if (shouldSkipMotionFrame()) return;
706
+ } else if (peakBufferedAmount() > MAX_BUFFERED_BYTES) {
371
707
  // Channel congested — dumping a large near-lossless frame on it
372
708
  // now would spike latency. Defer briefly; abandon if new motion
373
709
  // arrives (the backend captures a fresh top-off after the next
@@ -377,81 +713,336 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
377
713
  topOffRetryTimer = setTimeout(() => {
378
714
  topOffRetryTimer = null;
379
715
  if (motionSeq === seqAtCapture && isCapturing) {
380
- encodeFrame(imageData, true);
716
+ encodeFrame(imageData, true, mimeType);
381
717
  }
382
718
  }, 250);
383
719
  return;
384
720
  }
385
721
 
386
- // Direct base64 decode (avoids fetch() + data URL parsing overhead)
387
- const binaryStr = atob(imageData);
388
- const len = binaryStr.length;
389
- const bytes = new Uint8Array(len);
390
- for (let i = 0; i < len; i++) {
391
- bytes[i] = binaryStr.charCodeAt(i);
392
- }
722
+ const costStart = performance.now();
723
+ const bytes = base64ToBytes(imageData);
393
724
 
394
725
  // Decode via createImageBitmap (avoids per-frame ImageDecoder
395
726
  // constructor/destructor overhead)
396
- const blob = new Blob([bytes], { type: isTopOff ? 'image/png' : 'image/jpeg' });
727
+ const blob = new Blob([bytes], { type: mimeType || (isTopOff ? 'image/png' : 'image/jpeg') });
397
728
  const bitmap = await createImageBitmap(blob);
398
729
 
730
+ if (!videoEncoder || !isCapturing) {
731
+ bitmap.close();
732
+ return;
733
+ }
734
+
735
+ // The source is authoritative for geometry (see ensureEncoderSize),
736
+ // but only for real changes — small rounding differences are
737
+ // snapped onto the current geometry instead.
738
+ if (!(await ensureEncoderSize(bitmap.width, bitmap.height, true))) {
739
+ bitmap.close();
740
+ return;
741
+ }
742
+
399
743
  // Get aligned timestamp in microseconds
400
744
  const timestamp = performance.now() * 1000;
401
745
 
402
- // Create VideoFrame from ImageBitmap
403
- const frame = new VideoFrame(bitmap, {
746
+ const frame = new VideoFrame(snapSource(bitmap), {
404
747
  timestamp,
405
748
  alpha: 'discard'
406
749
  });
407
750
 
408
- // Keyframes are on-demand only (stream start, reconnect, reconfigure,
409
- // client request) — the channel is reliable so no periodic keyframes
410
- // are needed. keyframeInterval > 0 re-enables a periodic timer.
411
- const now = Date.now();
412
- const needsKeyframe = forceNextKeyframe ||
413
- (config.keyframeInterval > 0 && (now - lastKeyframeTime) > (config.keyframeInterval * 1000));
414
-
415
- if (needsKeyframe) {
416
- lastKeyframeTime = now;
417
- forceNextKeyframe = false;
418
- }
419
-
420
- // Encode frame — in quantizer mode, quality is chosen per frame:
421
- // cheap during motion (raised further under congestion),
422
- // near-lossless for still-page top-off refreshes
423
- if (usingQuantizer) {
424
- const quantizer = isTopOff ? config.topOffQuantizer : currentMotionQuantizer();
425
- videoEncoder.encode(frame, {
426
- keyFrame: needsKeyframe,
427
- vp9: { quantizer }
428
- } as VideoEncoderEncodeOptions);
429
- } else {
430
- videoEncoder.encode(frame, { keyFrame: needsKeyframe });
431
- }
432
- videoFrameCount++;
751
+ encodeVideoFrame(frame, !!isTopOff);
433
752
 
434
753
  // Close immediately to prevent memory leaks
435
754
  frame.close();
436
755
  bitmap.close();
756
+
757
+ if (!isTopOff) {
758
+ frameCostTotalMs += performance.now() - costStart;
759
+ frameCostSamples++;
760
+ }
437
761
  } catch (error) {}
438
762
  }
439
763
 
764
+ // ------------------------------------------------------------------
765
+ // Native capture (getDisplayMedia + MediaStreamTrackProcessor)
766
+ // ------------------------------------------------------------------
767
+
768
+ function retainNativeFrame(frame: VideoFrame) {
769
+ if (lastNativeFrame) {
770
+ try {
771
+ lastNativeFrame.close();
772
+ } catch (e) {}
773
+ }
774
+ try {
775
+ lastNativeFrame = frame.clone();
776
+ } catch (e) {
777
+ lastNativeFrame = null;
778
+ }
779
+ }
780
+
781
+ /**
782
+ * Still-page refresh for native capture.
783
+ *
784
+ * The retained frame came straight from the compositor, so re-encoding it
785
+ * near-losslessly is genuinely lossless relative to the source — no
786
+ * screenshot, no JPEG round-trip, no CDP traffic. Push mode can't do this:
787
+ * its retained frame would already carry JPEG artifacts.
788
+ */
789
+ function scheduleNativeTopOff() {
790
+ if (nativeIdleTimer) clearTimeout(nativeIdleTimer);
791
+ nativeIdleTimer = setTimeout(() => {
792
+ nativeIdleTimer = null;
793
+ if (!isCapturing || !lastNativeFrame || !videoEncoder) return;
794
+ if (peakBufferedAmount() > MAX_BUFFERED_BYTES) {
795
+ scheduleNativeTopOff();
796
+ return;
797
+ }
798
+ try {
799
+ encodeVideoFrame(lastNativeFrame, true);
800
+ } catch (e) {}
801
+ }, NATIVE_TOP_OFF_DELAY_MS);
802
+ }
803
+
804
+ async function readNativeFrames() {
805
+ if (!nativeReader) return;
806
+
807
+ while (isCapturing && nativeReader) {
808
+ let result: any;
809
+ try {
810
+ result = await nativeReader.read();
811
+ } catch (e) {
812
+ break;
813
+ }
814
+
815
+ if (result.done) break;
816
+
817
+ const frame: VideoFrame = result.value;
818
+ try {
819
+ // Secondary rate limit. The track is already constrained to
820
+ // `targetFramerate`, so this only exists for a source that
821
+ // ignores the constraint.
822
+ //
823
+ // The tolerance is essential: with the track delivering at
824
+ // exactly the target, frame-to-frame jitter puts gaps a hair
825
+ // under a full interval, and a threshold of one full interval
826
+ // then rejects roughly every second frame — halving the frame
827
+ // rate the viewer sees while every other counter still reads
828
+ // perfectly healthy.
829
+ const now = performance.now();
830
+ const minInterval = 1000 / Math.max(1, targetFramerate);
831
+ if (now - lastNativeEncodeTime < minInterval * 0.75) {
832
+ continue;
833
+ }
834
+
835
+ if (shouldSkipMotionFrame()) continue;
836
+
837
+ if (!(await ensureEncoderSize(frame.displayWidth, frame.displayHeight))) continue;
838
+
839
+ const costStart = performance.now();
840
+ lastNativeEncodeTime = now;
841
+ motionSeq++;
842
+ encodeVideoFrame(frame, false);
843
+ retainNativeFrame(frame);
844
+ scheduleNativeTopOff();
845
+
846
+ frameCostTotalMs += performance.now() - costStart;
847
+ frameCostSamples++;
848
+ } catch (e) {
849
+ } finally {
850
+ try {
851
+ frame.close();
852
+ } catch (e) {}
853
+ }
854
+ }
855
+ }
856
+
857
+ /**
858
+ * Probe in-page capture. Returns false (quietly) whenever it isn't
859
+ * available so the backend falls back to the CDP screencast path:
860
+ * insecure origin, missing API, denied permission, or no frame in time.
861
+ */
862
+ async function startNativeCapture(): Promise<boolean> {
863
+ if (!config.nativeCapture) return false;
864
+ if (captureMode === 'native') return true;
865
+ if (!isCapturing) return false;
866
+
867
+ try {
868
+ // getDisplayMedia is gated on a secure context, and the preview
869
+ // navigates to arbitrary URLs — plain-http targets simply use the
870
+ // fallback path.
871
+ if (!window.isSecureContext) return false;
872
+ // Use the pre-shim implementation the host bridge stashed for us. The
873
+ // public `getDisplayMedia` is relayed to the viewer's browser, so
874
+ // calling it here would prompt them for a capture source on every page.
875
+ const captureTab =
876
+ ((window as any).__clopenNativeGetDisplayMedia as
877
+ | ((options: unknown) => Promise<MediaStream>)
878
+ | undefined) ??
879
+ (navigator.mediaDevices && typeof navigator.mediaDevices.getDisplayMedia === 'function'
880
+ ? navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices)
881
+ : undefined);
882
+ if (!captureTab) return false;
883
+ if (typeof (window as any).MediaStreamTrackProcessor !== 'function') return false;
884
+
885
+ const withTimeout = <T,>(promise: Promise<T>, ms: number): Promise<T | null> =>
886
+ Promise.race([promise, new Promise<null>((resolve) => setTimeout(() => resolve(null), ms))]);
887
+
888
+ const stream = await withTimeout(
889
+ captureTab({
890
+ video: {
891
+ frameRate: { max: Math.max(1, targetFramerate) },
892
+ width: { max: encoderWidth },
893
+ height: { max: encoderHeight }
894
+ },
895
+ audio: false,
896
+ // Chrome-only hints: capture this tab without a picker.
897
+ preferCurrentTab: true,
898
+ selfBrowserSurface: 'include',
899
+ surfaceSwitching: 'exclude',
900
+ systemAudio: 'exclude'
901
+ } as any),
902
+ 2000
903
+ );
904
+
905
+ if (!stream) return false;
906
+
907
+ const track = stream.getVideoTracks()[0];
908
+ if (!track) {
909
+ stream.getTracks().forEach((t) => t.stop());
910
+ return false;
911
+ }
912
+
913
+ const processor = new (window as any).MediaStreamTrackProcessor({ track });
914
+ nativeStream = stream;
915
+ nativeTrack = track;
916
+ nativeReader = processor.readable.getReader();
917
+ captureMode = 'native';
918
+ forceNextKeyframe = true;
919
+
920
+ track.addEventListener('ended', () => {
921
+ // The surface went away (navigation, tab teardown) — drop back
922
+ // to push mode rather than freezing on the last frame.
923
+ stopNativeCapture();
924
+ });
925
+
926
+ readNativeFrames();
927
+ return true;
928
+ } catch (e) {
929
+ stopNativeCapture();
930
+ return false;
931
+ }
932
+ }
933
+
934
+ function stopNativeCapture() {
935
+ captureMode = 'push';
936
+
937
+ if (nativeIdleTimer) {
938
+ clearTimeout(nativeIdleTimer);
939
+ nativeIdleTimer = null;
940
+ }
941
+
942
+ if (nativeReader) {
943
+ try {
944
+ nativeReader.cancel();
945
+ } catch (e) {}
946
+ nativeReader = null;
947
+ }
948
+
949
+ if (nativeTrack) {
950
+ try {
951
+ nativeTrack.stop();
952
+ } catch (e) {}
953
+ nativeTrack = null;
954
+ }
955
+
956
+ if (nativeStream) {
957
+ try {
958
+ nativeStream.getTracks().forEach((t) => t.stop());
959
+ } catch (e) {}
960
+ nativeStream = null;
961
+ }
962
+
963
+ if (lastNativeFrame) {
964
+ try {
965
+ lastNativeFrame.close();
966
+ } catch (e) {}
967
+ lastNativeFrame = null;
968
+ }
969
+ }
970
+
971
+ // ------------------------------------------------------------------
972
+ // Adaptive controls driven by the backend
973
+ // ------------------------------------------------------------------
974
+
975
+ /**
976
+ * Apply a new framerate target. In native mode this is pushed down to the
977
+ * capture track so the compositor stops producing frames we would discard;
978
+ * in push mode the backend enforces it by withholding the screencast ack.
979
+ */
980
+ function setTargetFramerate(fps: number) {
981
+ const next = Math.max(1, Math.min(60, Math.round(fps)));
982
+ if (next === targetFramerate) return;
983
+ targetFramerate = next;
984
+
985
+ if (nativeTrack) {
986
+ try {
987
+ nativeTrack.applyConstraints({ frameRate: { max: next } } as MediaTrackConstraints).catch(() => {});
988
+ } catch (e) {}
989
+ }
990
+ }
991
+
992
+ function reportEncoderStats() {
993
+ const send = (window as any).__sendEncoderStats;
994
+ if (typeof send !== 'function') return;
995
+
996
+ const now = performance.now();
997
+ const windowMs = statsWindowStart > 0 ? now - statsWindowStart : 0;
998
+ statsWindowStart = now;
999
+
1000
+ try {
1001
+ send({
1002
+ captureMode,
1003
+ codec: activeCodec.name,
1004
+ avgFrameCostMs: frameCostSamples > 0 ? frameCostTotalMs / frameCostSamples : 0,
1005
+ encodeQueueMax,
1006
+ bufferedAmount: peakBufferedAmount(),
1007
+ framesAttempted,
1008
+ framesSkippedEncoder,
1009
+ framesSkippedNetwork,
1010
+ // Frames per second the viewer actually receives. Every other
1011
+ // counter can read healthy while this quietly sits at half the
1012
+ // target, so it is the one number worth trusting.
1013
+ measuredFps: windowMs > 0 ? (framesEncodedWindow * 1000) / windowMs : 0,
1014
+ width: encoderWidth,
1015
+ height: encoderHeight
1016
+ });
1017
+ } catch (e) {}
1018
+
1019
+ frameCostSamples = 0;
1020
+ frameCostTotalMs = 0;
1021
+ framesAttempted = 0;
1022
+ framesSkippedEncoder = 0;
1023
+ framesSkippedNetwork = 0;
1024
+ framesEncodedWindow = 0;
1025
+ encodeQueueMax = 0;
1026
+ }
1027
+
440
1028
  // Force the next encoded frame to be a keyframe (client-driven sync point,
441
1029
  // PLI equivalent — used when the client decoder errors or joins mid-stream)
442
1030
  function forceKeyframe() {
443
1031
  forceNextKeyframe = true;
1032
+ // On a still page nothing new will be encoded, so nudge the retained
1033
+ // frame out immediately when we have one.
1034
+ if (captureMode === 'native' && lastNativeFrame && videoEncoder) {
1035
+ try {
1036
+ encodeVideoFrame(lastNativeFrame, true);
1037
+ } catch (e) {}
1038
+ }
444
1039
  }
445
1040
 
446
1041
  // Start streaming
447
- // allowVp9: client decode capability negotiated at stream start
448
- async function startStreaming(allowVp9?: boolean) {
1042
+ async function startStreaming() {
449
1043
  if (isCapturing) return true;
450
1044
 
451
- vp9Allowed = allowVp9 !== false;
452
-
453
1045
  try {
454
- await initPeerConnection();
455
1046
  await initVideoEncoder();
456
1047
 
457
1048
  isCapturing = true;
@@ -461,6 +1052,9 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
461
1052
  // Start tracking cursor changes
462
1053
  startCursorTracking();
463
1054
 
1055
+ if (statsReportTimer) clearInterval(statsReportTimer);
1056
+ statsReportTimer = setInterval(reportEncoderStats, 2000);
1057
+
464
1058
  return true;
465
1059
  } catch (error) {
466
1060
  isCapturing = false;
@@ -478,6 +1072,13 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
478
1072
  topOffRetryTimer = null;
479
1073
  }
480
1074
 
1075
+ if (statsReportTimer) {
1076
+ clearInterval(statsReportTimer);
1077
+ statsReportTimer = null;
1078
+ }
1079
+
1080
+ stopNativeCapture();
1081
+
481
1082
  // Stop cursor tracking
482
1083
  stopCursorTracking();
483
1084
 
@@ -489,42 +1090,41 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
489
1090
  videoEncoder = null;
490
1091
  }
491
1092
 
492
- if (dataChannel) {
493
- dataChannel.close();
494
- dataChannel = null;
495
- }
496
-
497
- if (peerConnection) {
498
- peerConnection.close();
499
- peerConnection = null;
500
- }
1093
+ viewers.forEach((viewer) => {
1094
+ try {
1095
+ viewer.dc?.close();
1096
+ } catch (e) {}
1097
+ try {
1098
+ viewer.pc.close();
1099
+ } catch (e) {}
1100
+ });
1101
+ viewers.clear();
501
1102
  }
502
1103
 
503
- // Create and send offer
504
- async function createOffer() {
505
- if (!peerConnection) {
506
- await initPeerConnection();
507
- }
508
-
1104
+ // Create and send an offer for one viewer
1105
+ async function createOffer(viewerId: string) {
509
1106
  try {
510
- const offer = await peerConnection!.createOffer();
511
- await peerConnection!.setLocalDescription(offer);
1107
+ const viewer = createViewerPeer(viewerId);
1108
+ const offer = await viewer.pc.createOffer();
1109
+ await viewer.pc.setLocalDescription(offer);
512
1110
 
513
1111
  return {
514
1112
  type: offer.type,
515
1113
  sdp: offer.sdp
516
1114
  };
517
1115
  } catch (error) {
1116
+ closePeer(viewerId);
518
1117
  return null;
519
1118
  }
520
1119
  }
521
1120
 
522
- // Handle answer from client
523
- async function handleAnswer(answer: RTCSessionDescriptionInit) {
524
- if (!peerConnection) return false;
1121
+ // Handle answer from a viewer
1122
+ async function handleAnswer(viewerId: string, answer: RTCSessionDescriptionInit) {
1123
+ const viewer = viewers.get(viewerId);
1124
+ if (!viewer) return false;
525
1125
 
526
1126
  try {
527
- await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
1127
+ await viewer.pc.setRemoteDescription(new RTCSessionDescription(answer));
528
1128
  return true;
529
1129
  } catch (error) {
530
1130
  return false;
@@ -532,11 +1132,12 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
532
1132
  }
533
1133
 
534
1134
  // Add ICE candidate (+ loopback variant for VPN compatibility)
535
- async function addIceCandidate(candidate: RTCIceCandidateInit) {
536
- if (!peerConnection) return false;
1135
+ async function addIceCandidate(viewerId: string, candidate: RTCIceCandidateInit) {
1136
+ const viewer = viewers.get(viewerId);
1137
+ if (!viewer) return false;
537
1138
 
538
1139
  try {
539
- await peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
1140
+ await viewer.pc.addIceCandidate(new RTCIceCandidate(candidate));
540
1141
  } catch (error) {
541
1142
  return false;
542
1143
  }
@@ -545,7 +1146,7 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
545
1146
  const loopback = createLoopbackCandidate(candidate);
546
1147
  if (loopback) {
547
1148
  try {
548
- await peerConnection.addIceCandidate(new RTCIceCandidate(loopback as RTCIceCandidateInit));
1149
+ await viewer.pc.addIceCandidate(new RTCIceCandidate(loopback as RTCIceCandidateInit));
549
1150
  } catch {
550
1151
  // Expected to fail if loopback is not applicable
551
1152
  }
@@ -564,23 +1165,33 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
564
1165
  // Flush pending frames
565
1166
  await videoEncoder.flush();
566
1167
 
567
- // Create new codec config with updated dimensions (keeps current codec mode)
568
- const newCodecConfig = buildEncoderConfig(newWidth, newHeight, newBitrate);
1168
+ currentBitrate = newBitrate || currentBitrate;
1169
+ const newCodecConfig = buildEncoderConfig(activeCodec, newWidth, newHeight, currentBitrate);
569
1170
 
570
- // Check if new config is supported
571
1171
  const support = await VideoEncoder.isConfigSupported(newCodecConfig);
572
1172
  if (!support.supported) {
573
1173
  return false;
574
1174
  }
575
1175
 
576
- // Reconfigure encoder with new dimensions
577
- await videoEncoder.configure(newCodecConfig);
1176
+ videoEncoder.configure(newCodecConfig);
578
1177
 
579
- // Update config reference
1178
+ encoderWidth = newWidth;
1179
+ encoderHeight = newHeight;
580
1180
  config.width = newWidth;
581
1181
  config.height = newHeight;
582
- if (newBitrate) {
583
- config.bitrate = newBitrate;
1182
+
1183
+ // Native capture has to be told separately — its frame size comes
1184
+ // from track constraints, not from the encoder.
1185
+ if (nativeTrack) {
1186
+ try {
1187
+ nativeTrack
1188
+ .applyConstraints({
1189
+ width: { max: newWidth },
1190
+ height: { max: newHeight },
1191
+ frameRate: { max: targetFramerate }
1192
+ } as MediaTrackConstraints)
1193
+ .catch(() => {});
1194
+ } catch (e) {}
584
1195
  }
585
1196
 
586
1197
  // Force keyframe after reconfigure (decoder needs a sync point at the new dimensions)
@@ -592,27 +1203,36 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
592
1203
  }
593
1204
  }
594
1205
 
595
- // Get stats
1206
+ // Get stats. Bytes are summed across viewers — that is what actually left
1207
+ // the host — while the connection state reports the healthiest peer, since
1208
+ // one viewer reconnecting doesn't mean the stream is down.
596
1209
  async function getStats() {
597
- if (!peerConnection) return null;
1210
+ const peers = Array.from(viewers.values());
1211
+ if (peers.length === 0) return null;
598
1212
 
599
1213
  try {
600
- const stats = await peerConnection.getStats();
601
1214
  const result = {
602
1215
  videoBytesSent: 0,
603
1216
  audioBytesSent: 0,
604
1217
  videoFramesEncoded: videoFrameCount,
605
1218
  audioFramesEncoded: audioFrameCount,
606
- connectionState: peerConnection.connectionState,
607
- videoCodec: usingQuantizer ? 'vp9' : config.codec,
608
- audioCodec: 'opus' as const
1219
+ connectionState: peers.some((viewer) => viewer.pc.connectionState === 'connected')
1220
+ ? 'connected'
1221
+ : peers[0].pc.connectionState,
1222
+ videoCodec: activeCodec.name,
1223
+ audioCodec: 'opus' as const,
1224
+ captureMode,
1225
+ viewerCount: peers.length
609
1226
  };
610
1227
 
611
- stats.forEach(report => {
612
- if (report.type === 'data-channel') {
613
- result.videoBytesSent = (report as any).bytesSent || 0;
614
- }
615
- });
1228
+ for (const viewer of peers) {
1229
+ const stats = await viewer.pc.getStats();
1230
+ stats.forEach((report) => {
1231
+ if (report.type === 'data-channel') {
1232
+ result.videoBytesSent += (report as any).bytesSent || 0;
1233
+ }
1234
+ });
1235
+ }
616
1236
 
617
1237
  return result;
618
1238
  } catch (error) {
@@ -627,11 +1247,17 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
627
1247
  createOffer,
628
1248
  handleAnswer,
629
1249
  addIceCandidate,
1250
+ closePeer,
1251
+ viewerCount: () => viewers.size,
630
1252
  encodeFrame,
631
1253
  forceKeyframe,
632
1254
  sendAudioChunk,
633
1255
  getStats,
634
1256
  reconfigureEncoder,
1257
+ startNativeCapture,
1258
+ stopNativeCapture,
1259
+ setTargetFramerate,
1260
+ getCaptureMode: () => captureMode,
635
1261
  isActive: () => isCapturing
636
1262
  };
637
1263
  }