@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
@@ -4,14 +4,18 @@
4
4
  * Handles WebCodecs-based video streaming with WebRTC DataChannel transport.
5
5
  *
6
6
  * Video Architecture (Chrome-Remote-Desktop-style adaptive quality):
7
- * 1. CDP captures JPEG frames via Page.screencastFrame at native viewport resolution
8
- * 2. Direct CDP Runtime.evaluate sends base64 to page (bypasses Puppeteer IPC)
9
- * 3. Page decodes via createImageBitmap, encodes with VideoEncoder —
10
- * preferred VP9 quantizer mode (cheap during motion), VP8 bitrate fallback
11
- * 4. When the page goes still, a lossless PNG screenshot is pushed through the
12
- * encoder near-losslessly (top-off) so text sharpens after motion stops
13
- * 5. Send encoded chunks via reliable ordered RTCDataChannel; latency is
14
- * bounded by source-side frame dropping (bufferedAmount backpressure)
7
+ * 1. Frames are captured at the resolution the viewer can actually display
8
+ * (fit-scale × devicePixelRatio, capped by the host's pixel budget)
9
+ * 2. Capture runs either in-page (getDisplayMedia → VideoFrame, no round-trip)
10
+ * or via CDP screencast, which is ack-gated so Chrome never rasters a frame
11
+ * we would discard
12
+ * 3. The page encodes with VideoEncoder — VP9 quantizer mode, H.264 when the
13
+ * viewer has hardware for it, VP8 as the universal floor
14
+ * 4. When the page goes still, one near-lossless refresh frame is sent so text
15
+ * sharpens after motion stops
16
+ * 5. Encoded chunks travel over a reliable ordered RTCDataChannel; latency is
17
+ * bounded by source-side frame dropping, driven by three independent
18
+ * signals: network buffer, encoder queue, and the viewer's decode queue
15
19
  *
16
20
  * Audio Architecture:
17
21
  * 1. AudioContext interception (handled by BrowserAudioCapture)
@@ -20,34 +24,137 @@
20
24
  *
21
25
  * Client:
22
26
  * - Receives video + audio chunks via DataChannel
23
- * - Decodes with VideoDecoder + AudioDecoder
27
+ * - Decodes with VideoDecoder (off the main thread when the browser allows it)
24
28
  * - Renders video to canvas, plays audio with proper scheduling
25
- *
26
- * Benefits vs Canvas + WebRTC:
27
- * - Lower bandwidth (500-800 Kbps vs 1 Mbps)
28
- * - More control over codec selection
29
- * - Skip canvas rendering overhead
30
- * - DataChannel = lower latency than video track
31
29
  */
32
30
 
33
31
  import { EventEmitter } from 'events';
34
- import type { Page } from 'puppeteer';
35
- import type { BrowserTab, StreamingConfig } from './types';
36
- import { DEFAULT_STREAMING_CONFIG } from './types';
32
+ import type { CDPSession, Page } from 'puppeteer';
33
+ import type {
34
+ BrowserTab,
35
+ ClientCodecSupport,
36
+ ClientDisplayMetrics,
37
+ ClientStreamFeedback,
38
+ StreamingConfig
39
+ } from './types';
40
+ import { DEFAULT_STREAMING_CONFIG, resolveCodecCandidates } from './types';
37
41
  import { videoEncoderScript } from './scripts/video-stream';
38
42
  import { audioCaptureScript } from './scripts/audio-stream';
43
+
44
+ /**
45
+ * Install the audio tap in every frame.
46
+ *
47
+ * `page.evaluate` only reaches the main frame, so a `<video>` or AudioContext
48
+ * inside an iframe — an embedded player, anything served from a CDN origin —
49
+ * was never tapped and the preview played silently. The script's own
50
+ * idempotency guard makes the repeat injections harmless, and it relays its
51
+ * encoded chunks up to the top frame's DataChannel.
52
+ */
53
+ async function injectAudioCaptureIntoAllFrames(
54
+ page: Page,
55
+ audioConfig: StreamingConfig['audio']
56
+ ): Promise<void> {
57
+ await Promise.all(
58
+ page.frames().map(async (frame) => {
59
+ try {
60
+ await frame.evaluate(audioCaptureScript, audioConfig);
61
+ } catch {
62
+ // Detached or navigating; the on-new-document copy covers it.
63
+ }
64
+ })
65
+ );
66
+ }
67
+ import {
68
+ computeBitrate,
69
+ computeCaptureSize,
70
+ getHostCaptureProfile,
71
+ type CaptureProfile,
72
+ type CaptureSize
73
+ } from './capture-profile';
39
74
  import { debug } from '$shared/utils/logger';
40
75
 
76
+ /**
77
+ * Encoder health reported back from the page every couple of seconds.
78
+ * This is the CPU half of the backpressure story — `bufferedAmount` only ever
79
+ * described the network.
80
+ */
81
+ interface EncoderStats {
82
+ captureMode: 'push' | 'native';
83
+ codec: string;
84
+ /** Mean main-thread cost per frame in the page: image decode + encode. */
85
+ avgFrameCostMs: number;
86
+ /** Peak encoder queue depth over the window, not an instantaneous sample. */
87
+ encodeQueueMax: number;
88
+ bufferedAmount: number;
89
+ framesAttempted: number;
90
+ framesSkippedEncoder: number;
91
+ framesSkippedNetwork: number;
92
+ /** Frames per second actually delivered to the viewer over the window. */
93
+ measuredFps: number;
94
+ width: number;
95
+ height: number;
96
+ }
97
+
98
+ /**
99
+ * One connected viewer of a tab.
100
+ *
101
+ * A tab is not watched by "the client" — it can be watched from a laptop and a
102
+ * phone at once through Remote Access, or from two split panels in the same
103
+ * window. Everything that used to live directly on the session and describe a
104
+ * single viewer (its codecs, its screen, its ICE state) belongs here; what the
105
+ * session keeps is the reduction across all of them.
106
+ */
107
+ interface StreamViewer {
108
+ id: string;
109
+ /** Which codecs this viewer can decode. */
110
+ codecSupport: ClientCodecSupport;
111
+ /** Its fit-scale and screen density. */
112
+ display: ClientDisplayMetrics;
113
+ /** Answer received — ICE can be forwarded instead of queued. */
114
+ connected: boolean;
115
+ pendingCandidates: RTCIceCandidateInit[];
116
+ /** Whether this viewer currently has the preview on screen. */
117
+ visible: boolean;
118
+ /** Latest decoder verdict — the ladder follows the worst viewer. */
119
+ decoderSaturated: boolean;
120
+ }
121
+
41
122
  interface VideoStreamSession {
42
123
  sessionId: string;
43
124
  isActive: boolean;
44
- clientConnected: boolean;
125
+ paused: boolean;
45
126
  headlessReady: boolean;
46
- pendingCandidates: RTCIceCandidateInit[];
127
+ viewers: Map<string, StreamViewer>;
47
128
  scriptInjected: boolean; // Track if persistent script was injected
48
129
  scriptsPreInjected: boolean; // Track if scripts were pre-injected during tab creation
49
130
  audioOnNewDocumentInjected: boolean; // Track if evaluateOnNewDocument was registered for audio
50
- allowVp9: boolean; // Client decode capability (negotiated at stream start)
131
+ /** Codecs every viewer can decode — one encoder serves them all. */
132
+ codecSupport: ClientCodecSupport;
133
+ /** Display metrics of the most demanding viewer. */
134
+ display: ClientDisplayMetrics;
135
+ profile: CaptureProfile;
136
+ capture: CaptureSize;
137
+ /** Extra resolution derate applied when the fps floor isn't enough. */
138
+ pixelDerate: number;
139
+ targetFramerate: number;
140
+ captureMode: 'push' | 'native';
141
+ /** Consecutive healthy adaptation windows — gates recovery upward. */
142
+ healthyWindows: number;
143
+ /**
144
+ * Consecutive saturated windows. Degrading on a single report made the
145
+ * ladder a one-way ratchet: any momentary spike stepped the framerate down,
146
+ * and because a degrade resets the recovery counter, one spike every few
147
+ * seconds was enough to walk the stream to its floor and pin it there.
148
+ */
149
+ saturatedWindows: number;
150
+ /** When client feedback last moved the ladder — see applyClientFeedback. */
151
+ lastClientAdaptAt: number;
152
+ /**
153
+ * The tab this session streams. Kept here so adaptation triggered from the
154
+ * page (encoder stats arrive through an exposed binding, with no tab in
155
+ * hand) can still reach the page to change capture geometry.
156
+ */
157
+ tab?: BrowserTab;
51
158
  stats: {
52
159
  videoBytesSent: number;
53
160
  audioBytesSent: number;
@@ -58,19 +165,329 @@ interface VideoStreamSession {
58
165
  }
59
166
 
60
167
  /**
61
- * Scale encoder bitrate with capture resolution to keep bits-per-pixel
62
- * constant. Capture always runs at native viewport size (display fit-scale
63
- * is a CSS-only concern on the frontend), so a fixed bitrate would starve
64
- * larger viewports during motion.
65
- * 0.045 bpp at 1280×800@24fps ≈ 1.1 Mbps (comparable to the previous fixed 1 Mbps).
168
+ * Framerate ladder. Discrete so the stream settles instead of oscillating;
169
+ * clamped per session to the host profile's [minFramerate, maxFramerate].
66
170
  */
67
- const BITS_PER_PIXEL = 0.045;
171
+ const FRAMERATE_LADDER = [6, 8, 10, 12, 15, 18, 20, 24, 30];
68
172
 
69
- function computeBitrate(width: number, height: number, framerate: number): number {
70
- return Math.max(
71
- DEFAULT_STREAMING_CONFIG.video.bitrate,
72
- Math.round(width * height * framerate * BITS_PER_PIXEL)
73
- );
173
+ /**
174
+ * Resolution derates applied only after the framerate floor is reached. Going
175
+ * coarser beats going slower — a sharp slideshow reads worse than a soft but
176
+ * fluid stream — so this is the last resort, not the first.
177
+ */
178
+ const PIXEL_DERATE_LADDER = [1, 0.85, 0.7, 0.55];
179
+
180
+ const DEFAULT_CODEC_SUPPORT: ClientCodecSupport = {
181
+ vp8: true,
182
+ vp9: true,
183
+ avc: false,
184
+ hardware: []
185
+ };
186
+
187
+ /**
188
+ * CDP screencast feeder with ack-gated flow control.
189
+ *
190
+ * `Page.screencastFrame` fires at the compositor rate (up to 60fps) and Chrome
191
+ * withholds the next frame until the current one is acked. Acking immediately
192
+ * and discarding surplus frames downstream — the previous design — meant the
193
+ * renderer still rastered, JPEG-encoded and base64'd every one of them, and
194
+ * the process still parsed them, before we threw half away. Holding the ack
195
+ * for one frame interval moves that throttle to the only place it actually
196
+ * saves work: before the frame is produced.
197
+ */
198
+ class ScreencastFeeder {
199
+ private ackTimer: ReturnType<typeof setTimeout> | null = null;
200
+ private topOffTimer: ReturnType<typeof setTimeout> | null = null;
201
+ private peerObjectId: string | null = null;
202
+ private acquiringPeer = false;
203
+ private capturingTopOff = false;
204
+ private frameSeq = 0;
205
+ private destroyed = false;
206
+ private running = false;
207
+ private lastDispatchAt = 0;
208
+ private lastAckAt = 0;
209
+ private pendingAckId: number | null = null;
210
+
211
+ constructor(
212
+ private readonly cdp: CDPSession,
213
+ private readonly label: string,
214
+ private readonly getSession: () => VideoStreamSession | undefined,
215
+ private readonly getTab: () => BrowserTab | undefined,
216
+ private readonly onInvalidSession: () => void,
217
+ private readonly isValidSession: () => boolean
218
+ ) {
219
+ this.cdp.on('Page.screencastFrame', (event: any) => this.handleFrame(event));
220
+ }
221
+
222
+ /** Milliseconds a frame is held before acking — i.e. the source frame budget. */
223
+ private get frameIntervalMs(): number {
224
+ const fps = this.getSession()?.targetFramerate || DEFAULT_STREAMING_CONFIG.video.framerate;
225
+ return Math.max(16, Math.round(1000 / fps));
226
+ }
227
+
228
+ async start(width: number, height: number, quality: number): Promise<void> {
229
+ if (this.destroyed) return;
230
+
231
+ // Acquire the encoder handle before the first frame so no frame is
232
+ // wasted waiting for it.
233
+ await this.acquirePeerHandle();
234
+
235
+ await this.cdp.send('Page.startScreencast', {
236
+ format: 'jpeg',
237
+ quality,
238
+ maxWidth: width,
239
+ maxHeight: height,
240
+ everyNthFrame: 1
241
+ });
242
+
243
+ this.running = true;
244
+ debug.log('webcodecs', `CDP screencast started for ${this.label} at ${width}x${height} (q${quality})`);
245
+ }
246
+
247
+ async restart(width: number, height: number, quality: number): Promise<void> {
248
+ if (this.destroyed) return;
249
+ this.clearTimers();
250
+ await this.cdp.send('Page.stopScreencast').catch(() => {});
251
+ this.running = false;
252
+ await this.start(width, height, quality);
253
+ }
254
+
255
+ async pause(): Promise<void> {
256
+ if (!this.running) return;
257
+ this.clearTimers();
258
+ this.running = false;
259
+ await this.cdp.send('Page.stopScreencast').catch(() => {});
260
+ }
261
+
262
+ /** Invalidate the cached page handle — the execution context is gone. */
263
+ invalidatePeerHandle(): void {
264
+ this.peerObjectId = null;
265
+ }
266
+
267
+ private async acquirePeerHandle(): Promise<void> {
268
+ if (this.destroyed || this.acquiringPeer || this.peerObjectId) return;
269
+ this.acquiringPeer = true;
270
+ try {
271
+ const result: any = await this.cdp.send('Runtime.evaluate', {
272
+ expression: 'window.__webCodecsPeer',
273
+ returnByValue: false,
274
+ silent: true
275
+ });
276
+ this.peerObjectId = result?.result?.objectId ?? null;
277
+ } catch {
278
+ this.peerObjectId = null;
279
+ } finally {
280
+ this.acquiringPeer = false;
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Hand a frame to the page encoder.
286
+ *
287
+ * The payload travels as a `callFunctionOn` **argument**, not interpolated
288
+ * into a `Runtime.evaluate` expression. Interpolation made V8 parse and
289
+ * compile a fresh source string containing the whole base64 frame on every
290
+ * single frame — hundreds of kilobytes of compilation per frame, for a
291
+ * call that never changes.
292
+ */
293
+ private dispatch(data: string, isTopOff: boolean, mimeType: string): void {
294
+ if (this.destroyed) return;
295
+
296
+ if (!this.peerObjectId) {
297
+ void this.acquirePeerHandle();
298
+ return;
299
+ }
300
+
301
+ this.cdp
302
+ .send('Runtime.callFunctionOn', {
303
+ objectId: this.peerObjectId,
304
+ functionDeclaration: 'function(d,t,m){this.encodeFrame(d,t,m)}',
305
+ arguments: [{ value: data }, { value: isTopOff }, { value: mimeType }],
306
+ returnByValue: false,
307
+ awaitPromise: false,
308
+ silent: true
309
+ } as any)
310
+ .catch(() => {
311
+ // Stale handle (navigation) — the next frame re-acquires it.
312
+ this.peerObjectId = null;
313
+ });
314
+ }
315
+
316
+ private ack(cdpSessionId: number): void {
317
+ this.cdp.send('Page.screencastFrameAck', { sessionId: cdpSessionId }).catch(() => {});
318
+ }
319
+
320
+ private handleFrame(event: any): void {
321
+ this.frameSeq++;
322
+
323
+ // Every frame must be acknowledged exactly once — Chrome counts frames
324
+ // in flight and stops producing once that count sticks. If a previous
325
+ // ack is still held, release it now rather than replacing it.
326
+ this.flushPendingAck();
327
+
328
+ const session = this.getSession();
329
+ const tab = this.getTab();
330
+
331
+ // Ack immediately when we're not consuming — never leave the screencast
332
+ // waiting on an ack that will not come, or it stalls permanently.
333
+ if (this.destroyed || !session?.isActive || session.paused || tab?.isDestroyed) {
334
+ this.ack(event.sessionId);
335
+ return;
336
+ }
337
+
338
+ if (!this.isValidSession()) {
339
+ this.ack(event.sessionId);
340
+ this.onInvalidSession();
341
+ return;
342
+ }
343
+
344
+ // Native capture drives the encoder itself; the screencast should
345
+ // already be stopped, but ack defensively so nothing wedges.
346
+ if (session.captureMode === 'native') {
347
+ this.ack(event.sessionId);
348
+ return;
349
+ }
350
+
351
+ const now = Date.now();
352
+ const interval = this.frameIntervalMs;
353
+
354
+ try {
355
+ // Belt-and-braces rate limit against a source that isn't honouring
356
+ // ack flow control. The margin is loose on purpose: under working
357
+ // flow control frames already arrive one interval apart, and
358
+ // dropping one costs a *whole* extra interval (the next frame is
359
+ // only produced after our ack), which reads as judder.
360
+ if (this.lastDispatchAt > 0 && now - this.lastDispatchAt < interval * 0.6) {
361
+ return;
362
+ }
363
+
364
+ this.lastDispatchAt = now;
365
+ this.dispatch(event.data, false, 'image/jpeg');
366
+ this.scheduleTopOff();
367
+ } finally {
368
+ // Self-calibrating hold. The period the viewer actually sees is
369
+ // `hold + however long the source takes to produce and deliver the
370
+ // next frame`, so holding a full interval on top of that undershoots
371
+ // the target framerate — measurably, and visibly as stutter. Measure
372
+ // the pipeline (last ack → this frame) and hold only the remainder.
373
+ const pipelineMs = this.lastAckAt > 0 ? Math.max(0, now - this.lastAckAt) : 0;
374
+ const hold = Math.max(0, interval - pipelineMs);
375
+
376
+ this.pendingAckId = event.sessionId;
377
+ this.ackTimer = setTimeout(() => {
378
+ this.ackTimer = null;
379
+ this.sendPendingAck();
380
+ }, hold);
381
+ }
382
+ }
383
+
384
+ private flushPendingAck(): void {
385
+ if (!this.ackTimer) return;
386
+ clearTimeout(this.ackTimer);
387
+ this.ackTimer = null;
388
+ this.sendPendingAck();
389
+ }
390
+
391
+ private sendPendingAck(): void {
392
+ if (this.pendingAckId === null) return;
393
+ const id = this.pendingAckId;
394
+ this.pendingAckId = null;
395
+ this.lastAckAt = Date.now();
396
+ this.ack(id);
397
+ }
398
+
399
+ /**
400
+ * Static top-off: screencastFrame only fires on damage, so when no frame
401
+ * arrives for TOP_OFF_DELAY_MS the page has gone still. Capture one
402
+ * high-quality screenshot and encode it near-losslessly so the last
403
+ * (motion-degraded) frame doesn't stay soft on screen. One frame per still
404
+ * period — idle costs nothing.
405
+ */
406
+ scheduleTopOff(): void {
407
+ if (this.destroyed) return;
408
+ if (this.topOffTimer) clearTimeout(this.topOffTimer);
409
+
410
+ // The delay has to clear the gap between two motion frames, or a slow
411
+ // stream looks "still" between every frame and pays for a screenshot
412
+ // plus a near-lossless keyframe in the middle of actual motion.
413
+ const delay = Math.max(BrowserVideoCapture.TOP_OFF_DELAY_MS, this.frameIntervalMs * 2);
414
+
415
+ this.topOffTimer = setTimeout(async () => {
416
+ this.topOffTimer = null;
417
+
418
+ const session = this.getSession();
419
+ const tab = this.getTab();
420
+ if (!session?.isActive || session.paused || tab?.isDestroyed || this.capturingTopOff) return;
421
+ if (session.captureMode === 'native') return; // handled in-page from the retained frame
422
+
423
+ this.capturingTopOff = true;
424
+ const seqAtCapture = this.frameSeq;
425
+
426
+ try {
427
+ const profile = session.profile;
428
+ const viewport = tab?.page?.viewport();
429
+ const params: Record<string, unknown> = {
430
+ format: profile.topOffFormat,
431
+ captureBeyondViewport: false,
432
+ optimizeForSpeed: true
433
+ };
434
+
435
+ if (profile.topOffFormat === 'jpeg') {
436
+ params.quality = profile.topOffQuality;
437
+ }
438
+
439
+ // The refresh frame must arrive at the encoder's geometry, so
440
+ // it is captured through the same scale as the screencast.
441
+ if (viewport && session.capture.scale < 0.999) {
442
+ params.clip = {
443
+ x: 0,
444
+ y: 0,
445
+ width: viewport.width,
446
+ height: viewport.height,
447
+ scale: session.capture.scale
448
+ };
449
+ }
450
+
451
+ const screenshot: any = await this.cdp.send('Page.captureScreenshot', params as any);
452
+
453
+ // Discard if the page moved again while capturing — new
454
+ // screencast frames already rescheduled the top-off.
455
+ if (this.frameSeq !== seqAtCapture || this.destroyed) return;
456
+
457
+ this.dispatch(
458
+ screenshot.data,
459
+ true,
460
+ profile.topOffFormat === 'jpeg' ? 'image/jpeg' : 'image/png'
461
+ );
462
+ } catch {
463
+ // Page may be navigating/closing — top-off is best-effort
464
+ } finally {
465
+ this.capturingTopOff = false;
466
+ }
467
+ }, delay);
468
+ }
469
+
470
+ private clearTimers(): void {
471
+ // Release the held frame before dropping the timer. The screencast is
472
+ // about to be stopped either way, but leaving Chrome's in-flight count
473
+ // non-zero would wedge the next start.
474
+ this.flushPendingAck();
475
+ this.lastDispatchAt = 0;
476
+ this.lastAckAt = 0;
477
+
478
+ if (this.topOffTimer) {
479
+ clearTimeout(this.topOffTimer);
480
+ this.topOffTimer = null;
481
+ }
482
+ }
483
+
484
+ async destroy(): Promise<void> {
485
+ this.destroyed = true;
486
+ this.running = false;
487
+ this.clearTimers();
488
+ await this.cdp.send('Page.stopScreencast').catch(() => {});
489
+ await this.cdp.detach().catch(() => {});
490
+ }
74
491
  }
75
492
 
76
493
  export class BrowserVideoCapture extends EventEmitter {
@@ -80,15 +497,156 @@ export class BrowserVideoCapture extends EventEmitter {
80
497
  * Long enough to skip inter-frame gaps of animations, short enough that
81
498
  * text sharpens almost immediately after scrolling stops.
82
499
  */
83
- private static readonly TOP_OFF_DELAY_MS = 300;
500
+ static readonly TOP_OFF_DELAY_MS = 300;
501
+
502
+ /** Debounce for viewer resize storms before touching the encoder. */
503
+ private static readonly DISPLAY_METRICS_DEBOUNCE_MS = 250;
504
+
505
+ /**
506
+ * Minimum gap between ladder moves driven by viewer feedback. Matches the
507
+ * viewers' own reporting interval, so N viewers still produce one verdict
508
+ * per window rather than N.
509
+ */
510
+ private static readonly CLIENT_ADAPT_INTERVAL_MS = 1500;
84
511
 
85
512
  private sessions = new Map<string, VideoStreamSession>();
513
+ private feeders = new Map<string, ScreencastFeeder>();
86
514
  private preInjectPromises = new Map<string, Promise<boolean>>();
515
+ private displayMetricsTimers = new Map<string, ReturnType<typeof setTimeout>>();
87
516
 
88
517
  constructor() {
89
518
  super();
90
519
  }
91
520
 
521
+ // ------------------------------------------------------------------
522
+ // Session configuration
523
+ // ------------------------------------------------------------------
524
+
525
+ /**
526
+ * Build the per-session video config: capture geometry from the viewer's
527
+ * display metrics, quality ceilings from the host profile, and the codec
528
+ * order from the viewer's decode capabilities.
529
+ */
530
+ private buildVideoConfig(
531
+ videoSession: VideoStreamSession,
532
+ viewport: { width: number; height: number }
533
+ ): StreamingConfig['video'] {
534
+ const profile = videoSession.profile;
535
+
536
+ const derated = {
537
+ ...profile,
538
+ maxPixels: Math.round(profile.maxPixels * videoSession.pixelDerate)
539
+ };
540
+
541
+ videoSession.capture = computeCaptureSize(
542
+ viewport.width,
543
+ viewport.height,
544
+ videoSession.display.scale,
545
+ videoSession.display.dpr,
546
+ derated
547
+ );
548
+
549
+ const { width, height } = videoSession.capture;
550
+
551
+ return {
552
+ ...DEFAULT_STREAMING_CONFIG.video,
553
+ width,
554
+ height,
555
+ framerate: videoSession.targetFramerate,
556
+ minFramerate: profile.minFramerate,
557
+ bitrate: computeBitrate(width, height, videoSession.targetFramerate),
558
+ screenshotQuality: profile.screenshotQuality,
559
+ motionQuantizer: profile.motionQuantizer,
560
+ topOffQuantizer: profile.topOffQuantizer,
561
+ codecCandidates: resolveCodecCandidates(videoSession.codecSupport),
562
+ nativeCapture: isNativeCaptureEnabled()
563
+ };
564
+ }
565
+
566
+ private buildAudioConfig(videoSession: VideoStreamSession): StreamingConfig['audio'] {
567
+ return {
568
+ ...DEFAULT_STREAMING_CONFIG.audio,
569
+ bitrate: videoSession.profile.audioBitrate
570
+ };
571
+ }
572
+
573
+ /**
574
+ * Fold every viewer's capabilities into the one configuration the shared
575
+ * encoder can have.
576
+ *
577
+ * Codecs intersect: a codec only one viewer can decode is useless, because
578
+ * the same encoded chunks go to all of them. Resolution takes the maximum:
579
+ * capturing for the sharpest screen costs the others nothing but a downscale
580
+ * at paint time, whereas capturing for the smallest would leave the sharpest
581
+ * viewer permanently blurry. The host's pixel budget still caps the result.
582
+ */
583
+ private refreshViewerConfig(videoSession: VideoStreamSession): void {
584
+ const viewers = Array.from(videoSession.viewers.values());
585
+ if (viewers.length === 0) return;
586
+
587
+ videoSession.codecSupport = {
588
+ vp8: viewers.every((viewer) => viewer.codecSupport.vp8),
589
+ vp9: viewers.every((viewer) => viewer.codecSupport.vp9),
590
+ avc: viewers.every((viewer) => viewer.codecSupport.avc),
591
+ hardware: (['vp8', 'vp9', 'avc'] as const).filter((codec) =>
592
+ viewers.every((viewer) => viewer.codecSupport.hardware.includes(codec))
593
+ )
594
+ };
595
+
596
+ // Collapsed to a single factor rather than max(scale) × max(dpr): those
597
+ // maxima can come from different viewers, and their product would be a
598
+ // resolution nobody asked for.
599
+ let demand = 0;
600
+ for (const viewer of viewers) {
601
+ const scale = viewer.display.scale && viewer.display.scale > 0 ? viewer.display.scale : 1;
602
+ const dpr = viewer.display.dpr && viewer.display.dpr > 0 ? viewer.display.dpr : 1;
603
+ demand = Math.max(demand, scale * dpr);
604
+ }
605
+
606
+ videoSession.display = demand > 0 ? { scale: Math.min(1, demand), dpr: 1 } : {};
607
+ }
608
+
609
+ /** A stream is only worth pausing once nobody is looking at it. */
610
+ private allViewersHidden(videoSession: VideoStreamSession): boolean {
611
+ if (videoSession.viewers.size === 0) return true;
612
+ return Array.from(videoSession.viewers.values()).every((viewer) => !viewer.visible);
613
+ }
614
+
615
+ private createSessionState(sessionId: string): VideoStreamSession {
616
+ const profile = getHostCaptureProfile();
617
+ return {
618
+ sessionId,
619
+ isActive: false,
620
+ paused: false,
621
+ headlessReady: false,
622
+ viewers: new Map(),
623
+ scriptInjected: false,
624
+ scriptsPreInjected: false,
625
+ audioOnNewDocumentInjected: false,
626
+ codecSupport: { ...DEFAULT_CODEC_SUPPORT },
627
+ display: {},
628
+ profile,
629
+ capture: { width: 0, height: 0, scale: 1 },
630
+ pixelDerate: 1,
631
+ targetFramerate: profile.maxFramerate,
632
+ captureMode: 'push',
633
+ healthyWindows: 0,
634
+ saturatedWindows: 0,
635
+ lastClientAdaptAt: 0,
636
+ stats: {
637
+ videoBytesSent: 0,
638
+ audioBytesSent: 0,
639
+ videoFramesEncoded: 0,
640
+ audioFramesEncoded: 0,
641
+ connectionState: 'new'
642
+ }
643
+ };
644
+ }
645
+
646
+ // ------------------------------------------------------------------
647
+ // Script injection
648
+ // ------------------------------------------------------------------
649
+
92
650
  /**
93
651
  * Pre-inject WebCodecs scripts during tab creation.
94
652
  * This overlaps script injection with frontend processing,
@@ -106,40 +664,12 @@ export class BrowserVideoCapture extends EventEmitter {
106
664
  try {
107
665
  const page = session.page;
108
666
  const viewport = page.viewport()!;
109
- const config = DEFAULT_STREAMING_CONFIG;
110
-
111
- // Capture at native viewport resolution. Capturing below viewport
112
- // size (old behavior: viewport × display fit-scale) forced the
113
- // client to upscale frames, which made the preview blurry.
114
- const videoConfig: StreamingConfig['video'] = {
115
- ...config.video,
116
- width: viewport.width,
117
- height: viewport.height,
118
- bitrate: computeBitrate(viewport.width, viewport.height, config.video.framerate)
119
- };
120
-
121
- // Create session tracking
122
- const videoSession: VideoStreamSession = {
123
- sessionId,
124
- isActive: false,
125
- clientConnected: false,
126
- headlessReady: false,
127
- pendingCandidates: [],
128
- scriptInjected: true,
129
- scriptsPreInjected: false, // Set to true only after injection completes
130
- audioOnNewDocumentInjected: false,
131
- allowVp9: true,
132
- stats: {
133
- videoBytesSent: 0,
134
- audioBytesSent: 0,
135
- videoFramesEncoded: 0,
136
- audioFramesEncoded: 0,
137
- connectionState: 'new'
138
- }
139
- };
667
+
668
+ const videoSession = this.createSessionState(sessionId);
669
+ videoSession.scriptInjected = true;
140
670
  this.sessions.set(sessionId, videoSession);
141
671
 
142
- await this.injectScripts(sessionId, page, videoConfig, config);
672
+ await this.injectScripts(sessionId, page, this.buildVideoConfig(videoSession, viewport), this.buildAudioConfig(videoSession));
143
673
 
144
674
  // Mark as pre-injected only after successful completion
145
675
  videoSession.scriptsPreInjected = true;
@@ -163,34 +693,64 @@ export class BrowserVideoCapture extends EventEmitter {
163
693
  sessionId: string,
164
694
  page: Page,
165
695
  videoConfig: StreamingConfig['video'],
166
- config: StreamingConfig
696
+ audioConfig: StreamingConfig['audio']
167
697
  ): Promise<void> {
168
698
  // Check if bindings exist
169
699
  const bindingsExist = await page.evaluate(() => {
170
700
  return typeof (window as any).__sendIceCandidate === 'function';
171
701
  });
172
702
 
173
- // Expose signaling functions (persists across navigations)
703
+ // Expose signaling functions (persists across navigations).
704
+ //
705
+ // Every one of these is bound to the tab whose page it was injected into.
706
+ // They used to resolve their session by picking the first active one in
707
+ // the whole project, which is correct only while exactly one tab streams:
708
+ // with several open, one page's ICE candidates, connection states, cursor
709
+ // and encoder stats were all attributed to a different tab. The viewer
710
+ // filters those by tab, so its candidates were silently discarded and the
711
+ // connection never completed — and because the first refresh frame is
712
+ // pushed from the `connected` state, a still page also never produced a
713
+ // first frame. That is the "Loading preview…" that never resolves.
174
714
  if (!bindingsExist) {
175
- await page.exposeFunction('__sendIceCandidate', (candidate: RTCIceCandidateInit) => {
176
- const activeSession = Array.from(this.sessions.values()).find(s => s.isActive);
177
- if (!activeSession) return;
178
- this.emit('ice-candidate', { sessionId: activeSession.sessionId, candidate, from: 'headless' });
715
+ await page.exposeFunction('__sendIceCandidate', (viewerId: string, candidate: RTCIceCandidateInit) => {
716
+ this.emit('ice-candidate', { sessionId, viewerId, candidate, from: 'headless' });
179
717
  });
180
718
 
181
- await page.exposeFunction('__sendConnectionState', (state: string) => {
182
- const activeSession = Array.from(this.sessions.values()).find(s => s.isActive);
183
- if (activeSession) {
184
- activeSession.stats.connectionState = state;
185
- this.emit('connection-state', { sessionId: activeSession.sessionId, state });
719
+ await page.exposeFunction('__sendConnectionState', (viewerId: string, state: string) => {
720
+ const videoSession = this.sessions.get(sessionId);
721
+ if (!videoSession) return;
722
+
723
+ videoSession.stats.connectionState = state;
724
+ this.emit('connection-state', { sessionId, viewerId, state });
725
+
726
+ // Capture sources only produce frames on damage, so a viewer
727
+ // that connects to an already-still page would otherwise wait
728
+ // for the first mouse move to see anything. Push one refresh
729
+ // frame as soon as the peer is up.
730
+ if (state === 'connected' && videoSession.tab) {
731
+ void this.requestKeyframe(sessionId, videoSession.tab);
732
+ }
733
+
734
+ if (state === 'closed' || state === 'failed') {
735
+ videoSession.viewers.delete(viewerId);
186
736
  }
187
737
  });
188
738
 
739
+ // A channel that has just opened has no frame to show yet on a still
740
+ // page — see the matching comment in video-stream.ts.
741
+ await page.exposeFunction('__requestRefreshFrame', (viewerId: string) => {
742
+ const videoSession = this.sessions.get(sessionId);
743
+ if (!videoSession?.tab) return;
744
+ debug.log('webcodecs', `Refresh frame requested by viewer ${viewerId} on ${sessionId}`);
745
+ void this.requestKeyframe(sessionId, videoSession.tab);
746
+ });
747
+
189
748
  await page.exposeFunction('__sendCursorChange', (cursor: string) => {
190
- const activeSession = Array.from(this.sessions.values()).find(s => s.isActive);
191
- if (activeSession) {
192
- this.emit('cursor-change', { sessionId: activeSession.sessionId, cursor });
193
- }
749
+ this.emit('cursor-change', { sessionId, cursor });
750
+ });
751
+
752
+ await page.exposeFunction('__sendEncoderStats', (stats: EncoderStats) => {
753
+ this.applyEncoderStats(sessionId, stats);
194
754
  });
195
755
  }
196
756
 
@@ -199,15 +759,124 @@ export class BrowserVideoCapture extends EventEmitter {
199
759
  // The idempotency guard in audioCaptureScript prevents double-injection.
200
760
  const session = this.sessions.get(sessionId);
201
761
  if (session && !session.audioOnNewDocumentInjected) {
202
- await page.evaluateOnNewDocument(audioCaptureScript, config.audio);
762
+ await page.evaluateOnNewDocument(audioCaptureScript, audioConfig);
203
763
  session.audioOnNewDocumentInjected = true;
204
764
  }
205
765
 
206
766
  // Inject video encoder + audio capture scripts into the current page context
207
767
  await page.evaluate(videoEncoderScript, videoConfig);
208
- await page.evaluate(audioCaptureScript, config.audio);
768
+ await injectAudioCaptureIntoAllFrames(page, audioConfig);
769
+ }
770
+
771
+ // ------------------------------------------------------------------
772
+ // Viewers
773
+ // ------------------------------------------------------------------
774
+
775
+ /**
776
+ * Record (or refresh) a viewer and re-derive the shared encoder config.
777
+ */
778
+ private registerViewer(
779
+ videoSession: VideoStreamSession,
780
+ options: {
781
+ viewerId: string;
782
+ codecSupport?: ClientCodecSupport;
783
+ display?: ClientDisplayMetrics;
784
+ }
785
+ ): StreamViewer {
786
+ const existing = videoSession.viewers.get(options.viewerId);
787
+
788
+ const viewer: StreamViewer = existing ?? {
789
+ id: options.viewerId,
790
+ codecSupport: { ...DEFAULT_CODEC_SUPPORT },
791
+ display: {},
792
+ connected: false,
793
+ pendingCandidates: [],
794
+ visible: true,
795
+ decoderSaturated: false
796
+ };
797
+
798
+ if (options.codecSupport) viewer.codecSupport = options.codecSupport;
799
+ if (options.display) viewer.display = { ...viewer.display, ...options.display };
800
+ // A fresh handshake means a fresh peer: whatever ICE was queued for the
801
+ // previous one belongs to a connection that no longer exists.
802
+ viewer.connected = false;
803
+ viewer.pendingCandidates = [];
804
+ viewer.visible = true;
805
+
806
+ videoSession.viewers.set(viewer.id, viewer);
807
+ this.refreshViewerConfig(videoSession);
808
+
809
+ return viewer;
209
810
  }
210
811
 
812
+ /**
813
+ * Add a viewer to a stream that is already running.
814
+ *
815
+ * Nothing about the capture is disturbed — the existing viewers keep their
816
+ * channels. Only the shared geometry is re-derived, in case the newcomer has
817
+ * a sharper screen than anyone already watching.
818
+ */
819
+ private async attachViewer(
820
+ sessionId: string,
821
+ session: BrowserTab,
822
+ options: {
823
+ viewerId: string;
824
+ codecSupport?: ClientCodecSupport;
825
+ display?: ClientDisplayMetrics;
826
+ }
827
+ ): Promise<boolean> {
828
+ const videoSession = this.sessions.get(sessionId);
829
+ if (!videoSession?.isActive) return false;
830
+
831
+ this.registerViewer(videoSession, options);
832
+ videoSession.tab = session;
833
+
834
+ // The stream may have been paused because everyone watching had it off
835
+ // screen; someone is watching again.
836
+ await this.setPaused(sessionId, session, false);
837
+ await this.applyCaptureGeometry(sessionId, session);
838
+ return true;
839
+ }
840
+
841
+ /**
842
+ * Drop a viewer. The capture only stops once the last one is gone —
843
+ * otherwise closing one device's panel would blank every other device.
844
+ * Returns whether the whole stream was torn down.
845
+ */
846
+ async detachViewer(sessionId: string, session: BrowserTab | undefined, viewerId: string): Promise<boolean> {
847
+ const videoSession = this.sessions.get(sessionId);
848
+ if (!videoSession) return false;
849
+
850
+ videoSession.viewers.delete(viewerId);
851
+
852
+ if (session?.page && !session.page.isClosed()) {
853
+ await session.page
854
+ .evaluate((id: string) => {
855
+ (window as any).__webCodecsPeer?.closePeer(id);
856
+ }, viewerId)
857
+ .catch(() => {});
858
+ }
859
+
860
+ if (videoSession.viewers.size > 0) {
861
+ this.refreshViewerConfig(videoSession);
862
+ debug.log(
863
+ 'webcodecs',
864
+ `Viewer ${viewerId} left ${sessionId}, ${videoSession.viewers.size} still watching`
865
+ );
866
+ if (session && this.allViewersHidden(videoSession)) {
867
+ await this.setPaused(sessionId, session, true);
868
+ }
869
+ return false;
870
+ }
871
+
872
+ await this.stopStreaming(sessionId, session);
873
+ return true;
874
+ }
875
+
876
+ // ------------------------------------------------------------------
877
+ // Stream lifecycle
878
+ // ------------------------------------------------------------------
879
+
211
880
  /**
212
881
  * Start video streaming for a session
213
882
  */
@@ -215,9 +884,14 @@ export class BrowserVideoCapture extends EventEmitter {
215
884
  sessionId: string,
216
885
  session: BrowserTab,
217
886
  isValidSession: () => boolean,
218
- allowVp9 = true
887
+ options: {
888
+ viewerId: string;
889
+ codecSupport?: ClientCodecSupport;
890
+ display?: ClientDisplayMetrics;
891
+ }
219
892
  ): Promise<boolean> {
220
- debug.log('webcodecs', `Starting streaming for session ${sessionId} (client vp9: ${allowVp9})`);
893
+ const { viewerId } = options;
894
+ debug.log('webcodecs', `Starting streaming for session ${sessionId} (viewer ${viewerId})`);
221
895
 
222
896
  // Wait for any pending pre-injection to complete
223
897
  const pendingPreInject = this.preInjectPromises.get(sessionId);
@@ -226,13 +900,25 @@ export class BrowserVideoCapture extends EventEmitter {
226
900
  await pendingPreInject.catch(() => {});
227
901
  }
228
902
 
229
- // If session is already actively streaming, stop it for a clean reconnect.
230
- // This ensures the old PeerConnection + DataChannel are torn down and
231
- // a fresh one is created, preventing stale connections where no frames flow.
903
+ // A viewer re-handshaking (its own recovery path) gets a clean restart
904
+ // only when it is the sole viewer — that is the case the recovery logic
905
+ // was written for. Tearing the capture down because a *second* viewer
906
+ // arrived is what made two devices fight over one tab: each new
907
+ // handshake killed the other side's channel, whose health check
908
+ // reconnected and killed this one straight back.
232
909
  const existingSession = this.sessions.get(sessionId);
233
- if (existingSession && existingSession.isActive) {
234
- debug.log('webcodecs', `Session ${sessionId} already active, stopping for clean reconnect`);
235
- await this.stopStreaming(sessionId, session);
910
+ if (existingSession?.isActive) {
911
+ const others = Array.from(existingSession.viewers.keys()).filter((id) => id !== viewerId);
912
+ if (others.length === 0) {
913
+ debug.log('webcodecs', `Session ${sessionId} already active for its only viewer, restarting clean`);
914
+ await this.stopStreaming(sessionId, session);
915
+ } else {
916
+ debug.log(
917
+ 'webcodecs',
918
+ `Session ${sessionId} already streaming to ${others.length} other viewer(s), attaching ${viewerId}`
919
+ );
920
+ return this.attachViewer(sessionId, session, options);
921
+ }
236
922
  }
237
923
 
238
924
  if (!session.page || session.page.isClosed()) {
@@ -243,47 +929,29 @@ export class BrowserVideoCapture extends EventEmitter {
243
929
  try {
244
930
  const page = session.page;
245
931
  const viewport = page.viewport()!;
246
- const config = DEFAULT_STREAMING_CONFIG;
247
932
 
248
933
  // Get or create session tracking
249
934
  let videoSession = this.sessions.get(sessionId);
250
- const isRestart = !!videoSession;
251
-
252
935
  if (!videoSession) {
253
- videoSession = {
254
- sessionId,
255
- isActive: false,
256
- clientConnected: false,
257
- headlessReady: false,
258
- pendingCandidates: [],
259
- scriptInjected: false,
260
- scriptsPreInjected: false,
261
- audioOnNewDocumentInjected: false,
262
- allowVp9,
263
- stats: {
264
- videoBytesSent: 0,
265
- audioBytesSent: 0,
266
- videoFramesEncoded: 0,
267
- audioFramesEncoded: 0,
268
- connectionState: 'new'
269
- }
270
- };
936
+ videoSession = this.createSessionState(sessionId);
271
937
  this.sessions.set(sessionId, videoSession);
272
- } else {
273
- videoSession.allowVp9 = allowVp9;
274
938
  }
275
939
 
276
- // Capture at native viewport resolution (see doPreInject)
277
- const videoConfig: StreamingConfig['video'] = {
278
- ...config.video,
279
- width: viewport.width,
280
- height: viewport.height,
281
- bitrate: computeBitrate(viewport.width, viewport.height, config.video.framerate)
282
- };
283
-
284
- // Skip script injection if already pre-injected during tab creation
285
- if (!videoSession.scriptsPreInjected) {
286
- await this.injectScripts(sessionId, page, videoConfig, config);
940
+ videoSession.tab = session;
941
+ this.registerViewer(videoSession, options);
942
+ videoSession.paused = false;
943
+ videoSession.captureMode = 'push';
944
+ videoSession.healthyWindows = 0;
945
+
946
+ const videoConfig = this.buildVideoConfig(videoSession, viewport);
947
+ const audioConfig = this.buildAudioConfig(videoSession);
948
+
949
+ // The pre-injected script was configured before the viewer's codec
950
+ // support and display metrics were known, so re-inject whenever the
951
+ // handshake carried either.
952
+ const mustReinject = !videoSession.scriptsPreInjected || !!options?.codecSupport || !!options?.display;
953
+ if (mustReinject) {
954
+ await this.injectScripts(sessionId, page, videoConfig, audioConfig);
287
955
  videoSession.scriptInjected = true;
288
956
  } else {
289
957
  debug.log('webcodecs', `Scripts already pre-injected for ${sessionId}, skipping injection`);
@@ -291,13 +959,13 @@ export class BrowserVideoCapture extends EventEmitter {
291
959
 
292
960
  // Single batched call: verify peer + start streaming + init audio
293
961
  // (saves ~60ms of IPC overhead vs 4 separate page.evaluate calls)
294
- const initResult = await page.evaluate(async (clientAllowsVp9) => {
962
+ const initResult = await page.evaluate(async () => {
295
963
  const peer = (window as any).__webCodecsPeer;
296
964
  if (typeof peer?.startStreaming !== 'function') {
297
965
  return { peerExists: false, started: false, audioInitialized: false };
298
966
  }
299
967
 
300
- const started = await peer.startStreaming(clientAllowsVp9);
968
+ const started = await peer.startStreaming();
301
969
  if (!started) {
302
970
  return { peerExists: true, started: false, audioInitialized: false };
303
971
  }
@@ -315,7 +983,7 @@ export class BrowserVideoCapture extends EventEmitter {
315
983
  }
316
984
 
317
985
  return { peerExists: true, started: true, audioInitialized };
318
- }, allowVp9);
986
+ });
319
987
 
320
988
  if (!initResult.peerExists) {
321
989
  debug.error('webcodecs', `Peer script injected but __webCodecsPeer not available`);
@@ -339,190 +1007,510 @@ export class BrowserVideoCapture extends EventEmitter {
339
1007
 
340
1008
  videoSession.headlessReady = true;
341
1009
 
342
- // Setup CDP screencast to feed frames to encoder
343
- await this.setupFrameFeeder(sessionId, session, config, isValidSession);
1010
+ await this.setupCapture(sessionId, session, isValidSession);
344
1011
 
345
- debug.log('webcodecs', `Streaming started for ${sessionId}`);
1012
+ debug.log(
1013
+ 'webcodecs',
1014
+ `Streaming started for ${sessionId} — ${videoSession.capture.width}x${videoSession.capture.height} ` +
1015
+ `@${videoSession.targetFramerate}fps (${videoSession.captureMode}, ${videoSession.profile.tier})`
1016
+ );
346
1017
  return true;
347
1018
  } catch (error) {
348
1019
  debug.error('webcodecs', `Failed to start streaming:`, error);
1020
+ await this.destroyFeeder(sessionId);
349
1021
  this.sessions.delete(sessionId);
350
1022
  throw error;
351
1023
  }
352
1024
  }
353
1025
 
354
1026
  /**
355
- * Setup CDP screencast to feed JPEG frames to VideoEncoder
1027
+ * Bring up a capture source for the session.
1028
+ *
1029
+ * In-page capture is tried first: it hands compositor frames straight to
1030
+ * the encoder, skipping a JPEG encode, a base64 hop through this process,
1031
+ * and a JPEG decode. It needs a secure context, so any page served over
1032
+ * plain http falls back to the CDP screencast — which is why the fallback
1033
+ * is a first-class path and not an error case.
356
1034
  */
357
- private async setupFrameFeeder(
1035
+ private async setupCapture(
358
1036
  sessionId: string,
359
1037
  session: BrowserTab,
360
- config: StreamingConfig,
361
1038
  isValidSession: () => boolean
362
1039
  ): Promise<void> {
363
- const page = session.page;
364
- const viewport = page.viewport()!;
1040
+ const videoSession = this.sessions.get(sessionId);
1041
+ if (!videoSession) return;
365
1042
 
366
- const cdp = await page.createCDPSession();
1043
+ if (await this.tryStartNativeCapture(sessionId, session)) {
1044
+ videoSession.captureMode = 'native';
1045
+ // Native capture drives the encoder itself — a leftover screencast
1046
+ // from a previous page would fight it for the same encoder.
1047
+ await this.destroyFeeder(sessionId);
1048
+ debug.log('webcodecs', `Native in-page capture active for ${sessionId}`);
1049
+ return;
1050
+ }
367
1051
 
368
- let cdpFrameCount = 0;
1052
+ videoSession.captureMode = 'push';
1053
+ await this.setupFrameFeeder(sessionId, session, isValidSession);
1054
+ }
369
1055
 
370
- // Rate-limit encoding to the configured framerate. CDP screencast fires
371
- // at compositor rate (up to 60fps) — encoding every frame wastes CPU on
372
- // the host and bandwidth on the wire without visible benefit.
373
- //
374
- // Trailing edge matters: the LAST frame of a burst must always be
375
- // encoded. Plain dropping left a stale frame on screen until the
376
- // top-off fired (~300ms later), which felt like input lag on every
377
- // click/keystroke.
378
- const minFrameIntervalMs = Math.floor(1000 / config.video.framerate);
379
- let lastEncodeTime = 0;
380
- let pendingFrameData: string | null = null;
381
- let pendingFrameTimer: ReturnType<typeof setTimeout> | null = null;
382
-
383
- const encodeMotionFrame = (frameData: string) => {
384
- lastEncodeTime = Date.now();
385
- // Send frame to encoder via direct CDP (bypasses Puppeteer's
386
- // ExecutionContext lookup, function serialization, Runtime.callFunctionOn
387
- // overhead, and result deserialization). Base64 charset [A-Za-z0-9+/=]
388
- // is safe to embed in a JS double-quoted string literal.
389
- cdp.send('Runtime.evaluate', {
390
- expression: `window.__webCodecsPeer?.encodeFrame("${frameData}")`,
391
- awaitPromise: false,
392
- returnByValue: false
393
- }).catch(() => {});
394
- };
1056
+ private async tryStartNativeCapture(sessionId: string, session: BrowserTab): Promise<boolean> {
1057
+ if (!isNativeCaptureEnabled()) return false;
1058
+ if (!session.page || session.page.isClosed()) return false;
395
1059
 
396
- // Static top-off (Chrome-Remote-Desktop-style): screencastFrame only
397
- // fires on damage, so when no frame arrives for TOP_OFF_DELAY_MS the
398
- // page has gone still. Capture one lossless PNG screenshot and encode
399
- // it near-losslessly so the last (motion-degraded) frame doesn't stay
400
- // blurry on screen. One frame per still period — idle costs nothing.
401
- let topOffTimer: ReturnType<typeof setTimeout> | null = null;
402
- let capturingTopOff = false;
403
-
404
- const scheduleTopOff = () => {
405
- if (topOffTimer) clearTimeout(topOffTimer);
406
- topOffTimer = setTimeout(async () => {
407
- topOffTimer = null;
408
- const videoSession = this.sessions.get(sessionId);
409
- if (!videoSession?.isActive || session.isDestroyed || capturingTopOff) return;
410
-
411
- capturingTopOff = true;
412
- const frameCountAtCapture = cdpFrameCount;
413
- try {
414
- const screenshot = await cdp.send('Page.captureScreenshot', { format: 'png' });
415
-
416
- // Discard if the page moved again while capturing —
417
- // new screencast frames already rescheduled the top-off
418
- if (cdpFrameCount !== frameCountAtCapture) return;
419
-
420
- cdp.send('Runtime.evaluate', {
421
- expression: `window.__webCodecsPeer?.encodeFrame("${screenshot.data}", true)`,
422
- awaitPromise: false,
423
- returnByValue: false
424
- }).catch(() => {});
425
- } catch {
426
- // Page may be navigating/closing — top-off is best-effort
427
- } finally {
428
- capturingTopOff = false;
429
- }
430
- }, BrowserVideoCapture.TOP_OFF_DELAY_MS);
431
- };
1060
+ try {
1061
+ // getDisplayMedia requires transient user activation, which only
1062
+ // CDP's `userGesture` flag can grant to an automated page.
1063
+ const cdp = await session.page.createCDPSession();
1064
+ try {
1065
+ const result: any = await cdp.send('Runtime.evaluate', {
1066
+ expression: 'window.__webCodecsPeer && window.__webCodecsPeer.startNativeCapture()',
1067
+ awaitPromise: true,
1068
+ returnByValue: true,
1069
+ userGesture: true,
1070
+ silent: true,
1071
+ timeout: 4000
1072
+ } as any);
1073
+
1074
+ return result?.result?.value === true;
1075
+ } finally {
1076
+ await cdp.detach().catch(() => {});
1077
+ }
1078
+ } catch (error) {
1079
+ debug.log('webcodecs', `Native capture unavailable for ${sessionId}, using screencast`);
1080
+ return false;
1081
+ }
1082
+ }
432
1083
 
433
- cdp.on('Page.screencastFrame', async (event: any) => {
434
- cdpFrameCount++;
1084
+ /**
1085
+ * Setup CDP screencast to feed frames to VideoEncoder
1086
+ */
1087
+ private async setupFrameFeeder(
1088
+ sessionId: string,
1089
+ session: BrowserTab,
1090
+ isValidSession: () => boolean
1091
+ ): Promise<void> {
1092
+ const videoSession = this.sessions.get(sessionId);
1093
+ if (!videoSession) return;
435
1094
 
436
- const videoSession = this.sessions.get(sessionId);
437
- if (!videoSession?.isActive || session.isDestroyed) {
438
- cdp.send('Page.screencastFrameAck', { sessionId: event.sessionId }).catch(() => {});
439
- return;
1095
+ await this.destroyFeeder(sessionId);
1096
+
1097
+ const cdp = await session.page.createCDPSession();
1098
+ const feeder = new ScreencastFeeder(
1099
+ cdp,
1100
+ sessionId,
1101
+ () => this.sessions.get(sessionId),
1102
+ () => session,
1103
+ () => {
1104
+ void this.stopStreaming(sessionId);
1105
+ },
1106
+ isValidSession
1107
+ );
1108
+
1109
+ this.feeders.set(sessionId, feeder);
1110
+
1111
+ await feeder.start(
1112
+ videoSession.capture.width,
1113
+ videoSession.capture.height,
1114
+ videoSession.profile.screenshotQuality
1115
+ );
1116
+ }
1117
+
1118
+ private async destroyFeeder(sessionId: string): Promise<void> {
1119
+ const feeder = this.feeders.get(sessionId);
1120
+ if (!feeder) return;
1121
+ this.feeders.delete(sessionId);
1122
+ await feeder.destroy();
1123
+ }
1124
+
1125
+ // ------------------------------------------------------------------
1126
+ // Adaptive quality
1127
+ // ------------------------------------------------------------------
1128
+
1129
+ private framerateLadder(profile: CaptureProfile): number[] {
1130
+ const ladder = FRAMERATE_LADDER.filter(
1131
+ (fps) => fps >= profile.minFramerate && fps <= profile.maxFramerate
1132
+ );
1133
+ return ladder.length > 0 ? ladder : [profile.maxFramerate];
1134
+ }
1135
+
1136
+ /**
1137
+ * Fold one health report into the quality ladder.
1138
+ *
1139
+ * Framerate moves first and resolution only after the fps floor is reached,
1140
+ * because a soft-but-fluid stream reads far better than a sharp slideshow.
1141
+ * Recovery requires several consecutive healthy windows so a single quiet
1142
+ * moment doesn't push the stream straight back into saturation.
1143
+ */
1144
+ private adaptQuality(sessionId: string, degrade: boolean): void {
1145
+ const videoSession = this.sessions.get(sessionId);
1146
+ if (!videoSession?.isActive) return;
1147
+
1148
+ const session = videoSession.tab;
1149
+
1150
+ const ladder = this.framerateLadder(videoSession.profile);
1151
+ const fpsIndex = Math.max(0, ladder.indexOf(videoSession.targetFramerate));
1152
+ const derateIndex = Math.max(0, PIXEL_DERATE_LADDER.indexOf(videoSession.pixelDerate));
1153
+
1154
+ let nextFps = videoSession.targetFramerate;
1155
+ let nextDerate = videoSession.pixelDerate;
1156
+
1157
+ if (degrade) {
1158
+ videoSession.healthyWindows = 0;
1159
+ videoSession.saturatedWindows++;
1160
+ // Only act on sustained pressure. A single window can be saturated
1161
+ // by one heavy repaint, and reacting to that is what turned the
1162
+ // ladder into a one-way ratchet.
1163
+ if (videoSession.saturatedWindows < 2) return;
1164
+ videoSession.saturatedWindows = 0;
1165
+
1166
+ if (fpsIndex > 0) {
1167
+ nextFps = ladder[fpsIndex - 1];
1168
+ } else if (derateIndex < PIXEL_DERATE_LADDER.length - 1) {
1169
+ nextDerate = PIXEL_DERATE_LADDER[derateIndex + 1];
1170
+ } else {
1171
+ return; // already at the floor
440
1172
  }
1173
+ } else {
1174
+ videoSession.saturatedWindows = 0;
1175
+ videoSession.healthyWindows++;
1176
+ if (videoSession.healthyWindows < 2) return;
1177
+ videoSession.healthyWindows = 0;
1178
+
1179
+ // Recover framerate before resolution. Stutter is what the eye
1180
+ // objects to first, so smoothness is bought back before sharpness.
1181
+ if (fpsIndex < ladder.length - 1) {
1182
+ nextFps = ladder[fpsIndex + 1];
1183
+ } else if (derateIndex > 0) {
1184
+ nextDerate = PIXEL_DERATE_LADDER[derateIndex - 1];
1185
+ } else {
1186
+ return; // already at the ceiling
1187
+ }
1188
+ }
441
1189
 
442
- if (!isValidSession()) {
443
- this.stopStreaming(sessionId);
444
- return;
1190
+ if (nextFps === videoSession.targetFramerate && nextDerate === videoSession.pixelDerate) return;
1191
+
1192
+ const fpsChanged = nextFps !== videoSession.targetFramerate;
1193
+ const derateChanged = nextDerate !== videoSession.pixelDerate;
1194
+
1195
+ videoSession.targetFramerate = nextFps;
1196
+ videoSession.pixelDerate = nextDerate;
1197
+
1198
+ debug.log(
1199
+ 'webcodecs',
1200
+ `Quality ${degrade ? '↓' : '↑'} for ${sessionId}: ${nextFps}fps, derate ${nextDerate}`
1201
+ );
1202
+
1203
+ if (fpsChanged) {
1204
+ void this.pushTargetFramerate(sessionId, session, nextFps);
1205
+ }
1206
+ if (derateChanged && session) {
1207
+ void this.applyCaptureGeometry(sessionId, session);
1208
+ }
1209
+ }
1210
+
1211
+ private async pushTargetFramerate(
1212
+ sessionId: string,
1213
+ session: BrowserTab | undefined,
1214
+ fps: number
1215
+ ): Promise<void> {
1216
+ if (!session?.page || session.page.isClosed()) return;
1217
+ try {
1218
+ await session.page.evaluate((value: number) => {
1219
+ (window as any).__webCodecsPeer?.setTargetFramerate(value);
1220
+ }, fps);
1221
+ } catch {
1222
+ // Page may be navigating — the next start/navigation re-applies it
1223
+ }
1224
+ }
1225
+
1226
+ /**
1227
+ * Recompute the capture geometry and push it through the whole chain:
1228
+ * the page encoder, and the screencast (or the capture track in native
1229
+ * mode, which `reconfigureEncoder` handles in-page).
1230
+ */
1231
+ private async applyCaptureGeometry(sessionId: string, session: BrowserTab): Promise<boolean> {
1232
+ const videoSession = this.sessions.get(sessionId);
1233
+ if (!videoSession?.isActive || !session.page || session.page.isClosed()) return false;
1234
+
1235
+ const viewport = session.page.viewport();
1236
+ if (!viewport) return false;
1237
+
1238
+ const previous = videoSession.capture;
1239
+ const videoConfig = this.buildVideoConfig(videoSession, viewport);
1240
+ const next = videoSession.capture;
1241
+
1242
+ // Ignore sub-3% changes — reconfiguring costs a keyframe, and a resize
1243
+ // drag would otherwise fire dozens of them. Roll the recomputed value
1244
+ // back so the recorded geometry keeps matching the live encoder (the
1245
+ // top-off clip scale is read from it).
1246
+ if (
1247
+ previous.width > 0 &&
1248
+ Math.abs(next.width - previous.width) / previous.width < 0.03 &&
1249
+ Math.abs(next.height - previous.height) / previous.height < 0.03
1250
+ ) {
1251
+ videoSession.capture = previous;
1252
+ return true;
1253
+ }
1254
+
1255
+ try {
1256
+ const reconfigured = await session.page.evaluate(
1257
+ (params: { width: number; height: number; bitrate: number }) => {
1258
+ const peer = (window as any).__webCodecsPeer;
1259
+ if (!peer?.reconfigureEncoder) return false;
1260
+ return peer.reconfigureEncoder(params.width, params.height, params.bitrate);
1261
+ },
1262
+ { width: next.width, height: next.height, bitrate: videoConfig.bitrate }
1263
+ );
1264
+
1265
+ if (!reconfigured) {
1266
+ debug.warn('webcodecs', `Encoder reconfigure rejected for ${sessionId}`);
445
1267
  }
446
1268
 
447
- // ACK immediately
448
- cdp.send('Page.screencastFrameAck', { sessionId: event.sessionId }).catch(() => {});
449
-
450
- const now = Date.now();
451
- const elapsed = now - lastEncodeTime;
452
-
453
- if (elapsed < minFrameIntervalMs) {
454
- // Too soon — hold the LATEST frame and encode it when the slot
455
- // opens (trailing edge). Newer frames overwrite the pending one.
456
- pendingFrameData = event.data;
457
- if (!pendingFrameTimer) {
458
- pendingFrameTimer = setTimeout(() => {
459
- pendingFrameTimer = null;
460
- if (!pendingFrameData) return;
461
- const frameData = pendingFrameData;
462
- pendingFrameData = null;
463
-
464
- const vs = this.sessions.get(sessionId);
465
- if (!vs?.isActive || session.isDestroyed) return;
466
-
467
- encodeMotionFrame(frameData);
468
- scheduleTopOff();
469
- }, minFrameIntervalMs - elapsed);
470
- }
471
- scheduleTopOff();
472
- return;
1269
+ const feeder = this.feeders.get(sessionId);
1270
+ if (feeder && videoSession.captureMode === 'push') {
1271
+ await feeder.restart(next.width, next.height, videoSession.profile.screenshotQuality);
473
1272
  }
474
1273
 
475
- // This frame supersedes any pending trailing frame
476
- pendingFrameData = null;
1274
+ debug.log(
1275
+ 'webcodecs',
1276
+ `Capture geometry for ${sessionId}: ${next.width}x${next.height} ` +
1277
+ `(viewport ${viewport.width}x${viewport.height}, scale ${next.scale.toFixed(2)})`
1278
+ );
1279
+ return true;
1280
+ } catch (error) {
1281
+ debug.warn('webcodecs', `Failed to apply capture geometry:`, error);
1282
+ return false;
1283
+ }
1284
+ }
477
1285
 
478
- encodeMotionFrame(event.data);
479
- scheduleTopOff();
480
- });
1286
+ /**
1287
+ * Encoder health from the page. Saturation here means this host cannot
1288
+ * produce frames fast enough, which no amount of network headroom fixes.
1289
+ */
1290
+ private applyEncoderStats(sessionId: string, stats: EncoderStats): void {
1291
+ const videoSession = this.sessions.get(sessionId);
1292
+ if (!videoSession?.isActive) return;
1293
+
1294
+ videoSession.captureMode = stats.captureMode || videoSession.captureMode;
1295
+
1296
+ // In-page capture can end on its own — the captured surface goes away
1297
+ // on some navigations — and the page has no way to start a screencast.
1298
+ // Detecting the drop here is what keeps the preview from freezing on
1299
+ // its last frame.
1300
+ if (
1301
+ videoSession.captureMode === 'push' &&
1302
+ !videoSession.paused &&
1303
+ !this.feeders.has(sessionId) &&
1304
+ videoSession.tab
1305
+ ) {
1306
+ debug.warn('webcodecs', `Native capture ended for ${sessionId}, falling back to screencast`);
1307
+ const tab = videoSession.tab;
1308
+ void this.setupFrameFeeder(sessionId, tab, () => !tab.isDestroyed);
1309
+ }
481
1310
 
482
- // Start screencast at native viewport resolution
483
- await cdp.send('Page.startScreencast', {
484
- format: 'jpeg',
485
- quality: config.video.screenshotQuality,
486
- maxWidth: viewport.width,
487
- maxHeight: viewport.height,
488
- everyNthFrame: 1
489
- });
1311
+ const frameBudgetMs = 1000 / Math.max(1, videoSession.targetFramerate);
1312
+ const skipRatio =
1313
+ stats.framesAttempted > 0 ? stats.framesSkippedEncoder / stats.framesAttempted : 0;
490
1314
 
491
- debug.log('webcodecs', `CDP screencast started at ${viewport.width}x${viewport.height}`);
492
- (session as any).__webCodecsCdp = cdp;
493
- (session as any).__webCodecsTopOffCancel = () => {
494
- if (topOffTimer) {
495
- clearTimeout(topOffTimer);
496
- topOffTimer = null;
497
- }
498
- if (pendingFrameTimer) {
499
- clearTimeout(pendingFrameTimer);
500
- pendingFrameTimer = null;
1315
+ // Encoding is only one stage of the frame's journey; once it eats most
1316
+ // of the budget on its own there is nothing left for capture, decode
1317
+ // and paint, and the stream visibly stutters.
1318
+ //
1319
+ // All three signals are deliberately generous. A ratio rather than a
1320
+ // raw count, a window peak rather than a spot sample, and a threshold
1321
+ // above the queue depth that healthy asynchronous encoding produces
1322
+ // anyway — anything tighter reports saturation on an idle host.
1323
+ const encoderSaturated =
1324
+ stats.avgFrameCostMs > frameBudgetMs * 0.8 ||
1325
+ stats.encodeQueueMax >= 4 ||
1326
+ skipRatio > 0.4;
1327
+
1328
+ debug.log(
1329
+ 'webcodecs',
1330
+ `enc ${sessionId}: ${stats.codec}/${stats.captureMode} ${stats.width}x${stats.height} ` +
1331
+ `${(stats.measuredFps ?? 0).toFixed(1)}/${videoSession.targetFramerate}fps ` +
1332
+ `derate=${videoSession.pixelDerate} | ` +
1333
+ `cost=${stats.avgFrameCostMs.toFixed(1)}ms/${frameBudgetMs.toFixed(0)}ms ` +
1334
+ `qMax=${stats.encodeQueueMax} skip=${(skipRatio * 100).toFixed(0)}%` +
1335
+ `${encoderSaturated ? ' SATURATED' : ''}`
1336
+ );
1337
+
1338
+ this.adaptQuality(sessionId, encoderSaturated);
1339
+ }
1340
+
1341
+ /**
1342
+ * Viewer-side health. A phone that cannot decode fast enough shows exactly
1343
+ * the same stutter with an empty network buffer and an idle encoder, so the
1344
+ * decode queue has to close the loop back to the source.
1345
+ */
1346
+ applyClientFeedback(sessionId: string, viewerId: string, feedback: ClientStreamFeedback): void {
1347
+ const videoSession = this.sessions.get(sessionId);
1348
+ const viewer = videoSession?.viewers.get(viewerId);
1349
+ if (!videoSession?.isActive || !viewer) return;
1350
+
1351
+ // Thresholds sit well clear of healthy operation for the same reason as
1352
+ // the encoder ones: decodeQueueSize is a spot sample and dropRatio has
1353
+ // window-boundary skew, so tight limits fire on a stream that is fine.
1354
+ viewer.decoderSaturated =
1355
+ feedback.decodeQueueSize >= 4 ||
1356
+ feedback.dropRatio > 0.4 ||
1357
+ feedback.decodeLatencyMs > 300;
1358
+
1359
+ // Every viewer reports on its own two-second timer, so folding each
1360
+ // report straight into the ladder would step it once per viewer per
1361
+ // window — and a healthy phone would keep cancelling out a struggling
1362
+ // laptop, since a healthy window resets the saturation counter. One
1363
+ // verdict per window, taken from the worst viewer: the stream is shared,
1364
+ // so it can only be as fast as its slowest decoder.
1365
+ const now = Date.now();
1366
+ if (now - videoSession.lastClientAdaptAt < BrowserVideoCapture.CLIENT_ADAPT_INTERVAL_MS) return;
1367
+ videoSession.lastClientAdaptAt = now;
1368
+
1369
+ const anySaturated = Array.from(videoSession.viewers.values()).some(
1370
+ (entry) => entry.decoderSaturated
1371
+ );
1372
+
1373
+ this.adaptQuality(sessionId, anySaturated);
1374
+ }
1375
+
1376
+ /**
1377
+ * Viewer display metrics changed (panel resize, device change, zoom, or a
1378
+ * move to a different-density screen). Debounced because a resize drag
1379
+ * emits a continuous stream of these.
1380
+ */
1381
+ applyDisplayMetrics(
1382
+ sessionId: string,
1383
+ session: BrowserTab,
1384
+ viewerId: string,
1385
+ metrics: ClientDisplayMetrics
1386
+ ): void {
1387
+ const videoSession = this.sessions.get(sessionId);
1388
+ const viewer = videoSession?.viewers.get(viewerId);
1389
+ if (!videoSession || !viewer) return;
1390
+
1391
+ viewer.display = { ...viewer.display, ...metrics };
1392
+ this.refreshViewerConfig(videoSession);
1393
+
1394
+ const existing = this.displayMetricsTimers.get(sessionId);
1395
+ if (existing) clearTimeout(existing);
1396
+
1397
+ this.displayMetricsTimers.set(
1398
+ sessionId,
1399
+ setTimeout(() => {
1400
+ this.displayMetricsTimers.delete(sessionId);
1401
+ void this.applyCaptureGeometry(sessionId, session);
1402
+ }, BrowserVideoCapture.DISPLAY_METRICS_DEBOUNCE_MS)
1403
+ );
1404
+ }
1405
+
1406
+ /**
1407
+ * Pause capture while the viewer can't see it (panel collapsed, browser tab
1408
+ * hidden). An unwatched preview otherwise keeps a headless renderer and an
1409
+ * encoder busy for nothing — the dominant idle cost on a shared VPS.
1410
+ */
1411
+ /**
1412
+ * Record one viewer's visibility and pause only when nobody is watching.
1413
+ *
1414
+ * Visibility is per viewer: collapsing the panel on a laptop must not stop
1415
+ * the capture a phone is still watching.
1416
+ */
1417
+ async setViewerVisibility(
1418
+ sessionId: string,
1419
+ session: BrowserTab,
1420
+ viewerId: string,
1421
+ visible: boolean
1422
+ ): Promise<boolean> {
1423
+ const videoSession = this.sessions.get(sessionId);
1424
+ const viewer = videoSession?.viewers.get(viewerId);
1425
+ if (!videoSession || !viewer) return false;
1426
+
1427
+ viewer.visible = visible;
1428
+ return this.setPaused(sessionId, session, this.allViewersHidden(videoSession));
1429
+ }
1430
+
1431
+ private async setPaused(sessionId: string, session: BrowserTab, paused: boolean): Promise<boolean> {
1432
+ const videoSession = this.sessions.get(sessionId);
1433
+ if (!videoSession?.isActive) return false;
1434
+ if (videoSession.paused === paused) return true;
1435
+
1436
+ videoSession.paused = paused;
1437
+ debug.log('webcodecs', `${paused ? '⏸️ Paused' : '▶️ Resumed'} capture for ${sessionId}`);
1438
+
1439
+ const feeder = this.feeders.get(sessionId);
1440
+
1441
+ if (paused) {
1442
+ if (videoSession.captureMode === 'native') {
1443
+ await session.page
1444
+ ?.evaluate(() => {
1445
+ (window as any).__webCodecsPeer?.stopNativeCapture();
1446
+ })
1447
+ .catch(() => {});
1448
+ videoSession.captureMode = 'push';
501
1449
  }
502
- pendingFrameData = null;
503
- };
1450
+ await feeder?.pause();
1451
+ return true;
1452
+ }
1453
+
1454
+ // Resuming: rebuild whichever source is available — pausing tears the
1455
+ // native track down, so this re-probes rather than assuming the feeder
1456
+ // is still the right source — then force a sync point so the viewer
1457
+ // isn't left staring at the pre-pause frame.
1458
+ if (feeder) {
1459
+ await feeder.restart(
1460
+ videoSession.capture.width,
1461
+ videoSession.capture.height,
1462
+ videoSession.profile.screenshotQuality
1463
+ );
1464
+ } else {
1465
+ await this.setupCapture(sessionId, session, () => !session.isDestroyed);
1466
+ }
1467
+
1468
+ await this.requestKeyframe(sessionId, session);
1469
+ return true;
504
1470
  }
505
1471
 
1472
+ // ------------------------------------------------------------------
1473
+ // Signaling
1474
+ // ------------------------------------------------------------------
1475
+
506
1476
  /**
507
- * Create offer from headless browser
1477
+ * Create an offer for one viewer.
508
1478
  */
509
- async createOffer(sessionId: string, session: BrowserTab): Promise<RTCSessionDescriptionInit | null> {
1479
+ async createOffer(
1480
+ sessionId: string,
1481
+ session: BrowserTab,
1482
+ viewerId: string
1483
+ ): Promise<RTCSessionDescriptionInit | null> {
510
1484
  const videoSession = this.sessions.get(sessionId);
511
1485
  if (!videoSession?.isActive || !session.page) {
512
1486
  return null;
513
1487
  }
514
1488
 
1489
+ // A new offer means a new peer for this viewer, so anything the previous
1490
+ // one had accepted no longer applies: candidates must queue again until
1491
+ // the fresh peer has a remote description. Reconnecting after a page
1492
+ // navigation goes straight through here, and skipping this left the
1493
+ // viewer forwarding candidates into a peer that could not take them yet.
1494
+ //
1495
+ // A viewer reconnecting to a still-running stream arrives here without
1496
+ // going through a handshake, and may have been dropped in between (its
1497
+ // socket closed, its panel was hidden), so it is registered on demand
1498
+ // rather than being refused a peer.
1499
+ const viewer = videoSession.viewers.get(viewerId) ?? this.registerViewer(videoSession, { viewerId });
1500
+ viewer.connected = false;
1501
+ viewer.pendingCandidates = [];
1502
+
515
1503
  const maxRetries = 6;
516
1504
  const retryDelay = 150;
517
1505
 
518
1506
  for (let attempt = 0; attempt < maxRetries; attempt++) {
519
1507
  try {
520
1508
  // Single evaluate: check peer + create offer in one IPC round-trip
521
- const offer = await session.page.evaluate(async () => {
1509
+ const offer = await session.page.evaluate(async (id: string) => {
522
1510
  const peer = (window as any).__webCodecsPeer;
523
1511
  if (typeof peer?.createOffer !== 'function') return null;
524
- return peer.createOffer();
525
- });
1512
+ return peer.createOffer(id);
1513
+ }, viewerId);
526
1514
 
527
1515
  if (offer) return offer;
528
1516
 
@@ -546,26 +1534,31 @@ export class BrowserVideoCapture extends EventEmitter {
546
1534
  async handleAnswer(
547
1535
  sessionId: string,
548
1536
  session: BrowserTab,
1537
+ viewerId: string,
549
1538
  answer: RTCSessionDescriptionInit
550
1539
  ): Promise<boolean> {
551
1540
  const videoSession = this.sessions.get(sessionId);
552
- if (!videoSession?.isActive || !session.page) {
1541
+ const viewer = videoSession?.viewers.get(viewerId);
1542
+ if (!videoSession?.isActive || !viewer || !session.page) {
553
1543
  return false;
554
1544
  }
555
1545
 
556
1546
  try {
557
- const success = await session.page.evaluate((ans) => {
558
- return (window as any).__webCodecsPeer?.handleAnswer(ans);
559
- }, answer);
1547
+ const success = await session.page.evaluate(
1548
+ (params: { id: string; ans: RTCSessionDescriptionInit }) => {
1549
+ return (window as any).__webCodecsPeer?.handleAnswer(params.id, params.ans);
1550
+ },
1551
+ { id: viewerId, ans: answer }
1552
+ );
560
1553
 
561
1554
  if (success) {
562
- videoSession.clientConnected = true;
1555
+ viewer.connected = true;
563
1556
 
564
1557
  // Process pending ICE candidates
565
- for (const candidate of videoSession.pendingCandidates) {
566
- await this.addIceCandidate(sessionId, session, candidate);
1558
+ for (const candidate of viewer.pendingCandidates) {
1559
+ await this.addIceCandidate(sessionId, session, viewerId, candidate);
567
1560
  }
568
- videoSession.pendingCandidates = [];
1561
+ viewer.pendingCandidates = [];
569
1562
  }
570
1563
 
571
1564
  return success;
@@ -576,34 +1569,43 @@ export class BrowserVideoCapture extends EventEmitter {
576
1569
  }
577
1570
 
578
1571
  /**
579
- * Add ICE candidate from client
1572
+ * Add ICE candidate from one viewer
580
1573
  */
581
1574
  async addIceCandidate(
582
1575
  sessionId: string,
583
1576
  session: BrowserTab,
1577
+ viewerId: string,
584
1578
  candidate: RTCIceCandidateInit
585
1579
  ): Promise<boolean> {
586
1580
  const videoSession = this.sessions.get(sessionId);
587
- if (!videoSession?.isActive || !session.page) {
1581
+ const viewer = videoSession?.viewers.get(viewerId);
1582
+ if (!videoSession?.isActive || !viewer || !session.page) {
588
1583
  return false;
589
1584
  }
590
1585
 
591
- // Queue if not connected yet
592
- if (!videoSession.clientConnected) {
593
- videoSession.pendingCandidates.push(candidate);
1586
+ // Queue until this viewer's peer has a remote description
1587
+ if (!viewer.connected) {
1588
+ viewer.pendingCandidates.push(candidate);
594
1589
  return true;
595
1590
  }
596
1591
 
597
1592
  try {
598
- return await session.page.evaluate((cand) => {
599
- return (window as any).__webCodecsPeer?.addIceCandidate(cand);
600
- }, candidate);
1593
+ return await session.page.evaluate(
1594
+ (params: { id: string; cand: RTCIceCandidateInit }) => {
1595
+ return (window as any).__webCodecsPeer?.addIceCandidate(params.id, params.cand);
1596
+ },
1597
+ { id: viewerId, cand: candidate }
1598
+ );
601
1599
  } catch (error) {
602
1600
  debug.error('webcodecs', `Add ICE candidate error:`, error);
603
1601
  return false;
604
1602
  }
605
1603
  }
606
1604
 
1605
+ // ------------------------------------------------------------------
1606
+ // Viewport / refresh / recovery
1607
+ // ------------------------------------------------------------------
1608
+
607
1609
  /**
608
1610
  * Update viewport without reconnection (hot-swap)
609
1611
  */
@@ -615,43 +1617,17 @@ export class BrowserVideoCapture extends EventEmitter {
615
1617
  }
616
1618
 
617
1619
  try {
618
- const page = session.page;
619
- const config = DEFAULT_STREAMING_CONFIG;
620
-
621
1620
  debug.log('webcodecs', `🔄 Hot-swapping viewport to ${width}x${height}`);
622
1621
 
623
- // Step 1: Update viewport via CDP (without page reload)
624
- await page.setViewport({ width, height });
1622
+ // The emulated viewport is what the page lays out against; capture
1623
+ // resolution is derived from it and the viewer's display metrics.
1624
+ await session.page.setViewport({ width, height });
625
1625
 
626
- // Step 2: Reconfigure VideoEncoder with new dimensions and bitrate
627
- const bitrate = computeBitrate(width, height, config.video.framerate);
628
- const reconfigured = await page.evaluate((params) => {
629
- const peer = (window as any).__webCodecsPeer;
630
- if (!peer || !peer.reconfigureEncoder) return false;
631
- return peer.reconfigureEncoder(params.width, params.height, params.bitrate);
632
- }, { width, height, bitrate });
1626
+ // Force a recompute even if the derived size happens to land close
1627
+ // to the previous one — the page content changed shape.
1628
+ videoSession.capture = { width: 0, height: 0, scale: 1 };
633
1629
 
634
- if (!reconfigured) {
635
- debug.error('webcodecs', `Failed to reconfigure encoder`);
636
- return false;
637
- }
638
-
639
- // Step 3: Restart CDP screencast with new dimensions
640
- const cdp = (session as any).__webCodecsCdp;
641
- if (cdp) {
642
- await cdp.send('Page.stopScreencast').catch(() => {});
643
- await cdp.send('Page.startScreencast', {
644
- format: 'jpeg',
645
- quality: config.video.screenshotQuality,
646
- maxWidth: width,
647
- maxHeight: height,
648
- everyNthFrame: 1
649
- });
650
-
651
- debug.log('webcodecs', `✅ Viewport hot-swapped successfully to ${width}x${height}`);
652
- }
653
-
654
- return true;
1630
+ return await this.applyCaptureGeometry(sessionId, session);
655
1631
  } catch (error) {
656
1632
  debug.error('webcodecs', `Failed to update viewport:`, error);
657
1633
  return false;
@@ -659,10 +1635,8 @@ export class BrowserVideoCapture extends EventEmitter {
659
1635
  }
660
1636
 
661
1637
  /**
662
- * Restart the CDP screencast at native viewport resolution.
663
- * Used as a refresh/recovery path when the frontend detects a stuck stream
664
- * (sent as a scale-update action). Display fit-scale no longer affects
665
- * capture resolution, so no encoder reconfiguration is needed.
1638
+ * Restart capture at the current geometry.
1639
+ * Used as a refresh/recovery path when the frontend detects a stuck stream.
666
1640
  */
667
1641
  async refreshScreencast(sessionId: string, session: BrowserTab): Promise<boolean> {
668
1642
  const videoSession = this.sessions.get(sessionId);
@@ -672,24 +1646,17 @@ export class BrowserVideoCapture extends EventEmitter {
672
1646
  }
673
1647
 
674
1648
  try {
675
- const page = session.page;
676
- const viewport = page.viewport()!;
677
- const config = DEFAULT_STREAMING_CONFIG;
678
-
679
- const cdp = (session as any).__webCodecsCdp;
680
- if (cdp) {
681
- await cdp.send('Page.stopScreencast').catch(() => {});
682
- await cdp.send('Page.startScreencast', {
683
- format: 'jpeg',
684
- quality: config.video.screenshotQuality,
685
- maxWidth: viewport.width,
686
- maxHeight: viewport.height,
687
- everyNthFrame: 1
688
- });
689
-
690
- debug.log('webcodecs', `✅ Screencast refreshed at ${viewport.width}x${viewport.height}`);
1649
+ const feeder = this.feeders.get(sessionId);
1650
+ if (feeder) {
1651
+ feeder.invalidatePeerHandle();
1652
+ await feeder.restart(
1653
+ videoSession.capture.width,
1654
+ videoSession.capture.height,
1655
+ videoSession.profile.screenshotQuality
1656
+ );
691
1657
  }
692
1658
 
1659
+ await this.requestKeyframe(sessionId, session);
693
1660
  return true;
694
1661
  } catch (error) {
695
1662
  debug.error('webcodecs', `Failed to refresh screencast:`, error);
@@ -700,9 +1667,9 @@ export class BrowserVideoCapture extends EventEmitter {
700
1667
  /**
701
1668
  * Client-driven keyframe request (PLI equivalent).
702
1669
  * Forces the next encoded frame to be a keyframe AND immediately pushes a
703
- * high-quality screenshot through the encoder — so it works even on still
704
- * pages where no screencast frames are flowing. Called when the frontend
705
- * decoder errors or joins mid-stream and needs a sync point.
1670
+ * high-quality frame through the encoder — so it works even on still pages
1671
+ * where no capture frames are flowing. Called when the frontend decoder
1672
+ * errors or joins mid-stream and needs a sync point.
706
1673
  */
707
1674
  async requestKeyframe(sessionId: string, session: BrowserTab): Promise<boolean> {
708
1675
  const videoSession = this.sessions.get(sessionId);
@@ -711,18 +1678,14 @@ export class BrowserVideoCapture extends EventEmitter {
711
1678
  }
712
1679
 
713
1680
  try {
1681
+ // In native mode `forceKeyframe` re-encodes the retained compositor
1682
+ // frame in-page, so no screenshot is needed at all.
714
1683
  await session.page.evaluate(() => {
715
1684
  (window as any).__webCodecsPeer?.forceKeyframe();
716
1685
  });
717
1686
 
718
- const cdp = (session as any).__webCodecsCdp;
719
- if (cdp) {
720
- const screenshot = await cdp.send('Page.captureScreenshot', { format: 'png' });
721
- cdp.send('Runtime.evaluate', {
722
- expression: `window.__webCodecsPeer?.encodeFrame("${screenshot.data}", true)`,
723
- awaitPromise: false,
724
- returnByValue: false
725
- }).catch(() => {});
1687
+ if (videoSession.captureMode === 'push') {
1688
+ this.feeders.get(sessionId)?.scheduleTopOff();
726
1689
  }
727
1690
 
728
1691
  debug.log('webcodecs', `Keyframe requested for ${sessionId}`);
@@ -734,7 +1697,7 @@ export class BrowserVideoCapture extends EventEmitter {
734
1697
  }
735
1698
 
736
1699
  /**
737
- * Handle navigation - re-inject peer script and restart CDP screencast
1700
+ * Handle navigation - re-inject peer script and restart capture
738
1701
  * Called after page navigation to restore video streaming without full reconnection
739
1702
  */
740
1703
  async handleNavigation(sessionId: string, session: BrowserTab): Promise<boolean> {
@@ -747,30 +1710,24 @@ export class BrowserVideoCapture extends EventEmitter {
747
1710
  try {
748
1711
  const page = session.page;
749
1712
  const viewport = page.viewport()!;
750
- const config = DEFAULT_STREAMING_CONFIG;
751
1713
 
752
- debug.log('webcodecs', `🔄 Handling navigation for ${sessionId} - re-injecting peer script and restarting screencast`);
1714
+ debug.log('webcodecs', `🔄 Handling navigation for ${sessionId} - re-injecting peer script and restarting capture`);
753
1715
 
754
- // Capture at native viewport resolution (see doPreInject)
755
- const videoConfig: StreamingConfig['video'] = {
756
- ...config.video,
757
- width: viewport.width,
758
- height: viewport.height,
759
- bitrate: computeBitrate(viewport.width, viewport.height, config.video.framerate)
760
- };
1716
+ const videoConfig = this.buildVideoConfig(videoSession, viewport);
1717
+ const audioConfig = this.buildAudioConfig(videoSession);
761
1718
 
762
1719
  // Re-inject video encoder and audio capture scripts to new page context
763
1720
  await page.evaluate(videoEncoderScript, videoConfig);
764
- await page.evaluate(audioCaptureScript, config.audio);
1721
+ await injectAudioCaptureIntoAllFrames(page, audioConfig);
765
1722
 
766
1723
  // Single batched call: verify peer + start streaming + init audio
767
- const initResult = await page.evaluate(async (clientAllowsVp9) => {
1724
+ const initResult = await page.evaluate(async () => {
768
1725
  const peer = (window as any).__webCodecsPeer;
769
1726
  if (typeof peer?.startStreaming !== 'function') {
770
1727
  return { peerExists: false, started: false, audioInitialized: false };
771
1728
  }
772
1729
 
773
- const started = await peer.startStreaming(clientAllowsVp9);
1730
+ const started = await peer.startStreaming();
774
1731
  if (!started) {
775
1732
  return { peerExists: true, started: false, audioInitialized: false };
776
1733
  }
@@ -787,7 +1744,7 @@ export class BrowserVideoCapture extends EventEmitter {
787
1744
  }
788
1745
 
789
1746
  return { peerExists: true, started: true, audioInitialized };
790
- }, videoSession.allowVp9);
1747
+ });
791
1748
 
792
1749
  if (!initResult.peerExists) {
793
1750
  debug.error('webcodecs', `Peer script re-injection failed - peer not available`);
@@ -805,23 +1762,9 @@ export class BrowserVideoCapture extends EventEmitter {
805
1762
  debug.warn('webcodecs', 'Audio not available after navigation, continuing with video only');
806
1763
  }
807
1764
 
808
- // Restart CDP screencast
809
- const cdp = (session as any).__webCodecsCdp;
810
- if (cdp) {
811
- // Stop current screencast
812
- await cdp.send('Page.stopScreencast').catch(() => {});
813
-
814
- // Start with current dimensions
815
- await cdp.send('Page.startScreencast', {
816
- format: 'jpeg',
817
- quality: config.video.screenshotQuality,
818
- maxWidth: viewport.width,
819
- maxHeight: viewport.height,
820
- everyNthFrame: 1
821
- });
822
-
823
- debug.log('webcodecs', `✅ Navigation handled - screencast restarted at ${viewport.width}x${viewport.height}`);
824
- }
1765
+ // The old page's encoder handle died with its execution context.
1766
+ videoSession.captureMode = 'push';
1767
+ await this.setupCapture(sessionId, session, () => !session.isDestroyed);
825
1768
 
826
1769
  // Emit event to notify frontend that streaming is ready
827
1770
  this.emit('navigation-streaming-ready', { sessionId });
@@ -844,25 +1787,21 @@ export class BrowserVideoCapture extends EventEmitter {
844
1787
 
845
1788
  videoSession.isActive = false;
846
1789
 
1790
+ const metricsTimer = this.displayMetricsTimers.get(sessionId);
1791
+ if (metricsTimer) {
1792
+ clearTimeout(metricsTimer);
1793
+ this.displayMetricsTimers.delete(sessionId);
1794
+ }
1795
+
1796
+ await this.destroyFeeder(sessionId);
1797
+
847
1798
  if (session?.page && !session.page.isClosed()) {
848
1799
  try {
849
- // Cancel any pending top-off capture
850
- (session as any).__webCodecsTopOffCancel?.();
851
- (session as any).__webCodecsTopOffCancel = null;
852
-
853
1800
  // Stop audio + peer in one IPC round-trip
854
1801
  await session.page.evaluate(() => {
855
1802
  (window as any).__audioEncoder?.stop();
856
1803
  (window as any).__webCodecsPeer?.stopStreaming();
857
1804
  }).catch(() => {});
858
-
859
- // Stop CDP screencast
860
- const cdp = (session as any).__webCodecsCdp;
861
- if (cdp) {
862
- await cdp.send('Page.stopScreencast').catch(() => {});
863
- await cdp.detach().catch(() => {});
864
- (session as any).__webCodecsCdp = null;
865
- }
866
1805
  } catch (error) {
867
1806
  debug.warn('webcodecs', `Error during cleanup: ${error}`);
868
1807
  }
@@ -913,3 +1852,12 @@ export class BrowserVideoCapture extends EventEmitter {
913
1852
  this.sessions.clear();
914
1853
  }
915
1854
  }
1855
+
1856
+ /**
1857
+ * In-page capture is on by default and self-disables wherever it can't work
1858
+ * (insecure origin, missing API). The kill switch exists for hosts where the
1859
+ * probe itself is undesirable.
1860
+ */
1861
+ function isNativeCaptureEnabled(): boolean {
1862
+ return (process.env.CLOPEN_PREVIEW_NATIVE_CAPTURE || '').trim().toLowerCase() !== 'off';
1863
+ }