Open History to see the last commit
1// @effect-diagnostics globalFetch:off globalTimers:off - This browser and WebView transport runs without an Effect runtime.
2/* oxlint-disable unicorn/prefer-add-event-listener -- Each client owns its sockets and their handlers. */
3
4import {
5 createDuoControl,
6 type DuoCommand,
7 type DuoControlState,
8 type DuoPose,
9} from "./duoControl.ts";
10import * as Schema from "effect/Schema";
11import * as Option from "effect/Option";
12import { createCanvasFrameSink, type DeviceFrameSink } from "./frame.ts";
13import { type DeviceHubAccess, withDeviceHubQuery } from "./hubAccess.ts";
14import type { DevicePlatform } from "@t3tools/contracts";
15
16export type DeviceStreamStatus = "connecting" | "streaming" | "error";
17
18export interface DeviceScreenSize {
19 readonly width: number;
20 readonly height: number;
21 readonly orientation: "portrait" | "portrait_upside_down" | "landscape_left" | "landscape_right";
22 readonly screenId?: number;
23 readonly supportsHingeAngle?: boolean;
24 readonly supportsPhysicalOrientation?: boolean;
25 readonly hingeAngle?: number;
26 readonly hingePose?: DuoPose | null;
27 readonly tableMode?: boolean;
28 readonly tableModeAvailable?: boolean;
29}
30
31const screenConfigSchema = Schema.Struct({
32 width: Schema.Finite.check(Schema.isGreaterThan(0)),
33 height: Schema.Finite.check(Schema.isGreaterThan(0)),
34 orientation: Schema.Literals([
35 "portrait",
36 "portrait_upside_down",
37 "landscape_left",
38 "landscape_right",
39 ]),
40 inputUnavailable: Schema.optionalKey(Schema.Boolean),
41 screenId: Schema.optionalKey(Schema.Number),
42 supportsHingeAngle: Schema.optionalKey(Schema.Boolean),
43 supportsPhysicalOrientation: Schema.optionalKey(Schema.Boolean),
44 hingeAngle: Schema.optionalKey(
45 Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 180 })),
46 ),
47 hingePose: Schema.optionalKey(
48 Schema.NullOr(Schema.Literals(["closed", "book", "open", "laptop", "tent"])),
49 ),
50 tableMode: Schema.optionalKey(Schema.Boolean),
51 tableModeAvailable: Schema.optionalKey(Schema.Boolean),
52});
53const controlReplySchema = Schema.Struct({
54 requestId: Schema.Int,
55 ok: Schema.Boolean,
56 error: Schema.optionalKey(Schema.String),
57});
58const decodeScreenConfig = Schema.decodeUnknownOption(screenConfigSchema);
59const decodeControlReply = Schema.decodeUnknownOption(controlReplySchema);
60const iceServerSchema = Schema.Struct({
61 urls: Schema.Union([Schema.String, Schema.Array(Schema.String)]),
62 username: Schema.optionalKey(Schema.String),
63 credential: Schema.optionalKey(Schema.String),
64});
65const webRtcSettingsSchema = Schema.Struct({
66 transport: Schema.Literal("webrtc"),
67 iceServers: Schema.optionalKey(Schema.Array(iceServerSchema)),
68 iceTransportPolicy: Schema.optionalKey(Schema.Literals(["all", "relay"])),
69});
70// serve-sim reports its stream settings as `streamSettings` (EAS) or `stream`.
71const serveSimApiSchema = Schema.Struct({
72 streamSettings: Schema.optionalKey(Schema.Unknown),
73 stream: Schema.optionalKey(Schema.Unknown),
74});
75const decodeServeSimApi = Schema.decodeUnknownOption(serveSimApiSchema);
76const decodeWebRtcSettings = Schema.decodeUnknownOption(webRtcSettingsSchema);
77type WebRtcSettings = typeof webRtcSettingsSchema.Type;
78const decodeTransportLocked = Schema.decodeUnknownOption(
79 Schema.Struct({
80 error: Schema.Literal("stream_transport_locked"),
81 transport: Schema.Literal("webrtc"),
82 }),
83);
84const decodeWebRtcAnswer = Schema.decodeUnknownOption(
85 Schema.Struct({ type: Schema.Literal("answer"), sdp: Schema.String }),
86);
87
88export interface DuoPanelSinks {
89 readonly cover: DeviceFrameSink;
90 readonly inner: DeviceFrameSink;
91 /** Invalidate captured input synchronously, before React can commit the new layout. */
92 readonly onScreen?: (screen: DeviceScreenSize) => void;
93}
94
95export interface DeviceStreamEvents {
96 readonly onDuoControl?: (state: DuoControlState) => void;
97 readonly onDuoUnavailable?: (detail?: string) => void;
98 readonly onStatus: (status: DeviceStreamStatus, detail?: string) => void;
99 readonly onScreen: (screen: DeviceScreenSize) => void;
100 readonly onUnauthorized: () => void;
101 /**
102 * H.264 cannot be decoded here (no WebCodecs, or the simulator's profile is
103 * unsupported); the owner should show an `<img>` instead of the canvas
104 * and attach it with `setMjpegImage` so the client can observe real frames.
105 */
106 readonly onMjpegFallback: (url: string) => void;
107 /**
108 * The stream moved from MJPEG back to painting the canvas, because the
109 * device serves WebRTC only; the owner should show the canvas again.
110 */
111 readonly onCanvasVideo?: () => void;
112 readonly onInputConnected: (connected: boolean, detail?: string) => void;
113}
114
115export interface DeviceStreamTarget {
116 readonly platform: DevicePlatform;
117 readonly deviceId: string;
118 readonly access: DeviceHubAccess;
119 /** Native iOS WebViews can use MJPEG without cross-origin fetch or secure-context support. */
120 readonly preferMjpeg?: boolean;
121 readonly panelId?: 1 | 3;
122 readonly videoOnly?: boolean;
123}
124
125export type DeviceHardwareButton = "home" | "back" | "recents" | "power" | "appSwitcher";
126
127const RETRY_DELAY_MS = 1_000;
128const FIRST_FRAME_TIMEOUT_MS = 15_000;
129// A WebRTC feed that shows no frame for this long is reconnected; checked
130// every WEBRTC_STALL_CHECK_MS, so a transient `disconnected` peer that
131// recovers is left alone.
132const WEBRTC_STALL_TIMEOUT_MS = FIRST_FRAME_TIMEOUT_MS;
133const WEBRTC_STALL_CHECK_MS = 5_000;
134const TRANSPORT_PROBE_TIMEOUT_MS = 5_000;
135// Offers carry every candidate: serve-sim does not accept trickled ICE.
136const ICE_GATHERING_TIMEOUT_MS = 2_000;
137// A gathering cut short without a reflexive or relay candidate is retried
138// with twice the deadline, up to this; then the offer goes as gathered. The
139// whole sequence stays inside the first-frame deadline, which retries do
140// not extend.
141const ICE_GATHERING_MAX_TIMEOUT_MS = 4_000;
142const MJPEG_FRAME_CHECK_MS = 250;
143const FRAME_DURATION_US = 16_667;
144const SEMU_MAGIC = 0x53454d55;
145const SEMU_HEADER_BYTES = 16;
146const SEMU_FLAG_KEY = 1;
147const SOFT_DECODE_QUEUE = 8;
148// expo-device-hub 0.15.3 serve-emu input.js MAX_TEXT_BYTES limits packets to 300 UTF-8 bytes.
149const ANDROID_MAX_TEXT_BYTES = 300;
150// The pinned hub queue depth is 128; the client does not read queue rejections.
151const ANDROID_MAX_TEXT_CHUNKS = 64;
152
153const IOS_MSG_TOUCH = 0x03;
154const IOS_MSG_BUTTON = 0x04;
155const IOS_MSG_KEY = 0x06;
156const IOS_MSG_ORIENTATION = 0x07;
157const IOS_TAG_SCREEN_CONFIG = 0x82;
158const IOS_TAG_INPUT_ADMITTED = 0x83;
159
160const encoder = new TextEncoder();
161const decoder = new TextDecoder();
162
163/** serve-sim requires a v4 UUID; `crypto.randomUUID` is missing over plain-HTTP LAN origins. */
164function webRtcSessionId(): string {
165 const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
166 bytes[6] = (bytes[6]! & 0x0f) | 0x40;
167 bytes[8] = (bytes[8]! & 0x3f) | 0x80;
168 const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
169 return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
170}
171
172const isWebCodecsSupported = (): boolean =>
173 typeof globalThis !== "undefined" &&
174 "VideoDecoder" in globalThis &&
175 "EncodedVideoChunk" in globalThis;
176
177function utf8ByteLength(codePoint: number): number {
178 if (codePoint <= 0x7f) return 1;
179 if (codePoint <= 0x7ff) return 2;
180 if (codePoint <= 0xffff) return 3;
181 return 4;
182}
183
184function taggedJson(tag: number, payload: unknown): Uint8Array<ArrayBuffer> {
185 const json = encoder.encode(JSON.stringify(payload));
186 const out = new Uint8Array(1 + json.length);
187 out[0] = tag;
188 out.set(json, 1);
189 return out;
190}
191
192export function avcCodecString(bytes: Uint8Array): string {
193 if (bytes.length < 4) return "avc1.42E01E";
194 const hex = (byte: number) => byte.toString(16).padStart(2, "0");
195 return `avc1.${hex(bytes[1]!)}${hex(bytes[2]!)}${hex(bytes[3]!)}`;
196}
197
198export function parseSemuPacket(raw: ArrayBuffer): {
199 readonly data: Uint8Array;
200 readonly isKey: boolean | null;
201 readonly timestamp: number | null;
202} {
203 const bytes = new Uint8Array(raw);
204 if (bytes.byteLength > SEMU_HEADER_BYTES) {
205 const view = new DataView(raw, 0, SEMU_HEADER_BYTES);
206 if (view.getUint32(0, false) === SEMU_MAGIC && view.getUint8(4) === 1) {
207 const pts = view.getBigUint64(8, false);
208 return {
209 data: bytes.subarray(SEMU_HEADER_BYTES),
210 isKey: (view.getUint8(5) & SEMU_FLAG_KEY) !== 0,
211 timestamp: pts <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(pts) : null,
212 };
213 }
214 }
215 return { data: bytes, isKey: null, timestamp: null };
216}
217
218const isVideoSessionMessage = (text: string) => {
219 try {
220 const message = JSON.parse(text) as { type?: unknown };
221 return message.type === "video-session";
222 } catch {
223 return false;
224 }
225};
226
227export function scanAccessUnit(buf: Uint8Array): { isKey: boolean; sps: Uint8Array | null } {
228 let isKey = false;
229 let sps: Uint8Array | null = null;
230 const len = buf.length;
231 let i = 0;
232 while (i + 2 < len) {
233 if (buf[i] === 0 && buf[i + 1] === 0) {
234 let codeLen = 0;
235 if (buf[i + 2] === 1) codeLen = 3;
236 else if (i + 3 < len && buf[i + 2] === 0 && buf[i + 3] === 1) codeLen = 4;
237 if (codeLen) {
238 const nalType = buf[i + codeLen]! & 0x1f;
239 if (nalType === 7 && !sps) sps = buf.subarray(i + codeLen);
240 if (nalType === 5) isKey = true;
241 i += codeLen + 1;
242 continue;
243 }
244 }
245 i++;
246 }
247 return { isKey, sps };
248}
249
250export type AvccChunk = {
251 readonly type: "description" | "keyframe" | "delta" | "seed";
252 readonly payload: Uint8Array;
253};
254
255const AVCC_TAGS: Record<number, AvccChunk["type"] | undefined> = {
256 1: "description",
257 2: "keyframe",
258 3: "delta",
259 4: "seed",
260};
261
262export class AvccDemuxer {
263 private buffer = new Uint8Array(64 * 1024);
264 private length = 0;
265
266 push(bytes: Uint8Array): AvccChunk[] {
267 if (this.length + bytes.length > this.buffer.length) {
268 let capacity = this.buffer.length;
269 while (capacity < this.length + bytes.length) capacity *= 2;
270 const grown = new Uint8Array(capacity);
271 grown.set(this.buffer.subarray(0, this.length));
272 this.buffer = grown;
273 }
274 this.buffer.set(bytes, this.length);
275 this.length += bytes.length;
276
277 const chunks: AvccChunk[] = [];
278 let offset = 0;
279 while (this.length - offset >= 4) {
280 const view = new DataView(this.buffer.buffer, this.buffer.byteOffset + offset, 4);
281 const frameLength = view.getUint32(0, false);
282 if (this.length - offset - 4 < frameLength) break;
283 if (frameLength >= 1) {
284 const type = AVCC_TAGS[this.buffer[offset + 4]!];
285 if (type) {
286 chunks.push({ type, payload: this.buffer.slice(offset + 5, offset + 4 + frameLength) });
287 }
288 }
289 offset += 4 + frameLength;
290 }
291 if (offset > 0) {
292 this.buffer.copyWithin(0, offset, this.length);
293 this.length -= offset;
294 }
295 return chunks;
296 }
297
298 reset(): void {
299 this.length = 0;
300 }
301}
302
303export interface DeviceStreamClient {
304 readonly start: () => void;
305 readonly stop: () => void;
306 /**
307 * `stop()` detaches it; attach a fresh image for each restart.
308 */
309 readonly setMjpegImage: (image: HTMLImageElement | null) => void;
310 /** Normalized 0..1 coordinates in the displayed frame. */
311 readonly sendTouch: (phase: "begin" | "move" | "end", x: number, y: number) => void;
312 readonly sendKey: (event: KeyboardEvent, phase: "down" | "up") => void;
313 /** Android only: iOS input is HID key codes, which cannot carry arbitrary text. */
314 readonly sendText: (text: string) => void;
315 readonly pressButton: (button: DeviceHardwareButton) => void;
316 readonly rotate: () => void;
317 readonly setOrientation: (orientation: DeviceScreenSize["orientation"]) => void;
318 readonly controlDuo: (command: DuoCommand) => void;
319 readonly setDuoPanels: (panels: DuoPanelSinks | null) => void;
320 readonly sendRawTouch: (phase: "begin" | "move" | "end", x: number, y: number) => void;
321}
322
323const HID_USAGE_BY_CODE: Readonly<Record<string, number>> = {
324 Enter: 0x28,
325 Escape: 0x29,
326 Backspace: 0x2a,
327 Tab: 0x2b,
328 Space: 0x2c,
329 Minus: 0x2d,
330 Equal: 0x2e,
331 BracketLeft: 0x2f,
332 BracketRight: 0x30,
333 Backslash: 0x31,
334 Semicolon: 0x33,
335 Quote: 0x34,
336 Backquote: 0x35,
337 Comma: 0x36,
338 Period: 0x37,
339 Slash: 0x38,
340 Delete: 0x4c,
341 ArrowRight: 0x4f,
342 ArrowLeft: 0x50,
343 ArrowDown: 0x51,
344 ArrowUp: 0x52,
345 ControlLeft: 0xe0,
346 ShiftLeft: 0xe1,
347 AltLeft: 0xe2,
348 MetaLeft: 0xe3,
349 ControlRight: 0xe4,
350 ShiftRight: 0xe5,
351 AltRight: 0xe6,
352 MetaRight: 0xe7,
353};
354
355function hidUsageForCode(code: string): number | null {
356 if (/^Key[A-Z]$/.test(code)) return 0x04 + (code.charCodeAt(3) - 65);
357 if (/^Digit[1-9]$/.test(code)) return 0x1e + (code.charCodeAt(5) - 49);
358 if (code === "Digit0") return 0x27;
359 return HID_USAGE_BY_CODE[code] ?? null;
360}
361
362const ANDROID_KEYCODE_BY_KEY: Readonly<Record<string, number>> = {
363 ArrowUp: 19,
364 ArrowDown: 20,
365 ArrowLeft: 21,
366 ArrowRight: 22,
367 Tab: 61,
368 Enter: 66,
369 Backspace: 67,
370 Delete: 112,
371 Home: 122,
372 End: 123,
373 PageUp: 92,
374 PageDown: 93,
375};
376
377const IOS_ORIENTATIONS: ReadonlyArray<DeviceScreenSize["orientation"]> = [
378 "portrait",
379 "landscape_left",
380 "portrait_upside_down",
381 "landscape_right",
382];
383
384export function createDeviceStreamClient(
385 target: DeviceStreamTarget,
386 output: HTMLCanvasElement | DeviceFrameSink,
387 events: DeviceStreamEvents,
388): DeviceStreamClient {
389 const { access, platform, deviceId } = target;
390 const sink = "present" in output ? output : createCanvasFrameSink(output);
391 const vendor = platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
392 const device = encodeURIComponent(deviceId);
393 const httpUrl = (path: string) =>
394 withDeviceHubQuery(`${access.httpBase}${vendor}${path}`, access);
395 const wsUrl = (path: string) => withDeviceHubQuery(`${access.wsBase}${vendor}${path}`, access);
396 const useWebCodecs = isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg);
397
398 let stopped = true;
399 let socket: WebSocket | null = null;
400 let controller: AbortController | null = null;
401 const retryTimers = new Map<"video" | "input", ReturnType<typeof setTimeout>>();
402 let primeController: AbortController | null = null;
403 let videoDecoder: VideoDecoder | null = null;
404 let decodedVideoGeneration: number | null = null;
405 let iosInputAdmitted = false;
406 let iosInputUnavailable = false;
407 let timestamp = 0;
408 let awaitingKeyframe = true;
409 let screen: DeviceScreenSize | null = null;
410 let firstFrame = false;
411 let configuring = false;
412 let mjpeg = false;
413 let generation = 0;
414 let decoderEpoch = 0;
415 let frameTimer: ReturnType<typeof setTimeout> | null = null;
416 let videoReadTimer: ReturnType<typeof setTimeout> | null = null;
417 let mjpegImage: HTMLImageElement | null = null;
418 let releaseImage: (() => void) | null = null;
419 let videoGeneration = 0;
420 let panelClients: DeviceStreamClient[] = [];
421 let panelSinks: DuoPanelSinks | null = null;
422 let rotationCursor: DeviceScreenSize["orientation"] | null = null;
423 let pendingOrientation: { requestId: number } | null = null;
424 let iceGatheringDeadlineMs = ICE_GATHERING_TIMEOUT_MS;
425 let peer: { connection: RTCPeerConnection; sessionId: string; video: HTMLVideoElement } | null =
426 null;
427 const duoControl = createDuoControl({
428 send(request) {
429 if (
430 !iosInputAdmitted ||
431 iosInputUnavailable ||
432 socket?.readyState !== WebSocket.OPEN ||
433 !screen?.supportsHingeAngle
434 )
435 return false;
436 if (request.command.control === "physical" && !screen.supportsPhysicalOrientation)
437 return false;
438 try {
439 pendingOrientation = null;
440 if (request.command.control === "orientation") {
441 const value = request.command.value;
442 pendingOrientation = { requestId: request.requestId };
443 rotationCursor = value;
444 // Upstream serializes orientation with hinge commands, then broadcasts config.
445 // An orientation-locked app can keep its framebuffer orientation after the sensor rotates.
446 socket.send(taggedJson(IOS_MSG_ORIENTATION, { orientation: value }));
447 } else socket.send(taggedJson(0x10, request));
448 return true;
449 } catch {
450 return false;
451 }
452 },
453 onChange(state) {
454 if (!state.pending) pendingOrientation = null;
455 events.onDuoControl?.(state);
456 },
457 });
458 const videoPath = `/helper/${device}${target.panelId ? `/panel/${target.panelId}` : ""}/stream.avcc`;
459
460 const mjpegUrl = () => httpUrl(`/helper/${device}/stream.mjpeg`);
461
462 const setStatus = (status: DeviceStreamStatus, detail?: string) => {
463 if (!stopped) events.onStatus(status, detail);
464 };
465
466 const clearFrameTimer = () => {
467 if (frameTimer !== null) clearTimeout(frameTimer);
468 frameTimer = null;
469 };
470
471 const fail = (detail: string) => {
472 if (stopped) return;
473 stop();
474 events.onInputConnected(false, detail);
475 events.onStatus("error", detail);
476 };
477
478 const connecting = (detail?: string) => {
479 firstFrame = false;
480 if (frameTimer === null) {
481 frameTimer = setTimeout(
482 () => fail("No video received from the device. Reconnect to try again."),
483 FIRST_FRAME_TIMEOUT_MS,
484 );
485 }
486 setStatus("connecting", detail);
487 };
488
489 const frameReceived = () => {
490 if (firstFrame) return;
491 firstFrame = true;
492 clearFrameTimer();
493 setStatus("streaming");
494 };
495
496 const observeMjpegImage = () => {
497 releaseImage?.();
498 releaseImage = null;
499 const image = mjpegImage;
500 if (!image || stopped || !mjpeg) return;
501 let timer: ReturnType<typeof setTimeout> | null = null;
502 let released = false;
503 const check = () => {
504 if (released || stopped) return;
505 if (timer !== null) clearTimeout(timer);
506 timer = null;
507 if (image.naturalWidth > 0 && image.naturalHeight > 0) frameReceived();
508 else {
509 // Multipart images may not emit load until the response ends.
510 timer = setTimeout(check, MJPEG_FRAME_CHECK_MS);
511 }
512 };
513 const error = () => {
514 if (released) return;
515 const failure = "Could not receive the device stream. Reconnect to try again.";
516 // An <img> cannot read the 409 that a WebRTC-only serve-sim answers with.
517 if (typeof RTCPeerConnection === "undefined") fail(failure);
518 else void switchToWebRtc(failure, false);
519 };
520 image.addEventListener("load", check);
521 image.addEventListener("error", error);
522 releaseImage = () => {
523 released = true;
524 if (timer !== null) clearTimeout(timer);
525 image.removeEventListener("load", check);
526 image.removeEventListener("error", error);
527 image.removeAttribute("src");
528 };
529 image.src = mjpegUrl();
530 check();
531 };
532
533 const setMjpegImage = (image: HTMLImageElement | null) => {
534 if (mjpegImage === image) return;
535 releaseImage?.();
536 releaseImage = null;
537 mjpegImage = image;
538 observeMjpegImage();
539 };
540
541 const fallBackToMjpeg = () => {
542 if (stopped || mjpeg) return;
543 mjpeg = true;
544 controller?.abort();
545 controller = null;
546 closeDecoder();
547 connecting();
548 events.onMjpegFallback(mjpegUrl());
549 if (!releaseImage) observeMjpegImage();
550 };
551
552 const paint = (source: CanvasImageSource, width: number, height: number) => {
553 if (stopped) return;
554 if (platform === "android" && (screen?.width !== width || screen.height !== height)) {
555 screen = { width, height, orientation: width > height ? "landscape_left" : "portrait" };
556 events.onScreen(screen);
557 }
558 if (!sink.present(source, width, height)) {
559 fail("Could not display the device stream. Reconnect to try again.");
560 return;
561 }
562 frameReceived();
563 };
564
565 const closeDecoder = () => {
566 decoderEpoch++;
567 try {
568 videoDecoder?.close();
569 } catch {}
570 videoDecoder = null;
571 awaitingKeyframe = true;
572 };
573
574 const recoverDecoder = () => {
575 if (platform === "ios") fallBackToMjpeg();
576 else {
577 closeDecoder();
578 connecting("Video decoder restarted.");
579 requestKeyframe();
580 }
581 };
582
583 const makeDecoder = () => {
584 const feedGeneration = videoGeneration;
585 const decoder = new VideoDecoder({
586 output: (frame) => {
587 try {
588 if (
589 videoDecoder === decoder &&
590 (platform !== "ios" || feedGeneration === videoGeneration)
591 ) {
592 decodedVideoGeneration = feedGeneration;
593 paint(frame, frame.displayWidth, frame.displayHeight);
594 }
595 } finally {
596 frame.close();
597 }
598 },
599 error: () => {
600 if (
601 stopped ||
602 videoDecoder !== decoder ||
603 (platform === "ios" && feedGeneration !== videoGeneration)
604 )
605 return;
606 recoverDecoder();
607 },
608 });
609 return decoder;
610 };
611
612 const configureDecoder = async (
613 config: VideoDecoderConfig,
614 isCurrent = () => !stopped,
615 ): Promise<boolean> => {
616 const epoch = decoderEpoch;
617 const full: VideoDecoderConfig = { ...config, optimizeForLatency: true };
618 const support = await VideoDecoder.isConfigSupported(full).catch(() => ({ supported: false }));
619 if (!isCurrent() || epoch !== decoderEpoch) return false;
620 if (!support.supported) {
621 if (platform === "android") fail(`This browser cannot decode ${config.codec}.`);
622 return false;
623 }
624 try {
625 if (!videoDecoder || videoDecoder.state === "closed") videoDecoder = makeDecoder();
626 videoDecoder.configure(full);
627 return true;
628 } catch (cause) {
629 if (platform === "android") fail(`Video decoder: ${(cause as Error).message}`);
630 return false;
631 }
632 };
633
634 const decode = (isKey: boolean, data: Uint8Array, pts?: number | null) => {
635 if (!videoDecoder || videoDecoder.state !== "configured") return;
636 if (awaitingKeyframe) {
637 if (!isKey) return;
638 awaitingKeyframe = false;
639 }
640 if (videoDecoder.decodeQueueSize > SOFT_DECODE_QUEUE) {
641 if (platform !== "ios") {
642 recoverDecoder();
643 return;
644 }
645 // Native IDRs are spaced by frame count, so an idle simulator may take
646 // minutes to produce one. A new AVCC subscription forces a fresh IDR.
647 controller?.abort();
648 closeDecoder();
649 return;
650 }
651 try {
652 videoDecoder.decode(
653 new EncodedVideoChunk({
654 type: isKey ? "key" : "delta",
655 timestamp: pts ?? timestamp,
656 data,
657 }),
658 );
659 timestamp += FRAME_DURATION_US;
660 } catch {
661 recoverDecoder();
662 }
663 };
664
665 const requestKeyframe = () => {
666 if (platform === "android" && socket?.readyState === WebSocket.OPEN) {
667 socket.send(JSON.stringify({ type: "reset-video", ack: false }));
668 }
669 };
670
671 const scheduleRetry = (channel: "video" | "input", run: () => void) => {
672 if (stopped || retryTimers.has(channel)) return;
673 retryTimers.set(
674 channel,
675 setTimeout(() => {
676 retryTimers.delete(channel);
677 run();
678 }, RETRY_DELAY_MS),
679 );
680 };
681
682 const handleUnauthorized = () => {
683 stop();
684 events.onInputConnected(false);
685 events.onUnauthorized();
686 };
687
688 const readIosVideo = async () => {
689 const lifecycle = generation;
690 const feedGeneration = ++videoGeneration;
691 const demuxer = new AvccDemuxer();
692 const videoController = new AbortController();
693 controller = videoController;
694 const isCurrent = () =>
695 !stopped &&
696 generation === lifecycle &&
697 videoGeneration === feedGeneration &&
698 controller === videoController;
699 let retryDetail: string | undefined;
700 try {
701 const response = await fetch(httpUrl(videoPath), {
702 signal: videoController.signal,
703 credentials: access.credentials ? "include" : "same-origin",
704 });
705 if (!isCurrent()) {
706 await response.body?.cancel();
707 return;
708 }
709 if (response.status === 401 || response.status === 403) return handleUnauthorized();
710 if (response.status === 409 && !target.panelId) {
711 const locked = decodeTransportLocked(await response.json().catch(() => null));
712 if (Option.isSome(locked)) {
713 if (!isCurrent()) return;
714 controller = null;
715 void switchToWebRtc("This browser cannot play this device's WebRTC stream.", true);
716 return;
717 }
718 }
719 if (target.panelId && [400, 404, 405, 410].includes(response.status)) {
720 await response.body?.cancel();
721 setStatus("error", "This Device Hub does not provide fixed Duo display feeds.");
722 return;
723 }
724 if (!response.ok || !response.body) throw new Error(`stream ${response.status}`);
725 const reader = response.body.getReader();
726 for (;;) {
727 // An AVCC body can stay open after its helper stops producing frames.
728 const timer = setTimeout(() => {
729 if (!isCurrent()) return;
730 retryDetail = "Device stream stopped receiving video. Reconnecting…";
731 videoController.abort();
732 }, FIRST_FRAME_TIMEOUT_MS);
733 videoReadTimer = timer;
734 let result: ReadableStreamReadResult<Uint8Array>;
735 try {
736 result = await reader.read();
737 } finally {
738 clearTimeout(timer);
739 if (videoReadTimer === timer) videoReadTimer = null;
740 }
741 const { done, value } = result;
742 if (!isCurrent()) return;
743 if (done) break;
744 for (const chunk of demuxer.push(value)) {
745 if (videoController.signal.aborted) break;
746 switch (chunk.type) {
747 case "seed":
748 void createImageBitmap(new Blob([chunk.payload as BlobPart], { type: "image/jpeg" }))
749 .then((bitmap) => {
750 try {
751 if (isCurrent() && decodedVideoGeneration !== feedGeneration)
752 paint(bitmap, bitmap.width, bitmap.height);
753 } finally {
754 bitmap.close();
755 }
756 })
757 .catch(() => {});
758 break;
759 case "description": {
760 awaitingKeyframe = true;
761 const configured = await configureDecoder(
762 { codec: avcCodecString(chunk.payload), description: chunk.payload },
763 isCurrent,
764 );
765 if (!isCurrent()) return;
766 if (!configured) {
767 await reader.cancel().catch(() => {});
768 if (!isCurrent()) return;
769 if (target.videoOnly)
770 setStatus(
771 "error",
772 `This browser cannot decode the Duo panel's ${avcCodecString(chunk.payload)} stream.`,
773 );
774 else fallBackToMjpeg();
775 return;
776 }
777 break;
778 }
779 case "keyframe":
780 case "delta":
781 decode(chunk.type === "keyframe", chunk.payload);
782 break;
783 }
784 }
785 }
786 } catch (cause) {
787 if (!isCurrent()) return;
788 retryDetail ??= videoController.signal.aborted
789 ? "Video decoder fell behind. Reconnecting…"
790 : (cause as Error).message;
791 }
792 if (isCurrent()) {
793 controller = null;
794 videoController.abort();
795 closeDecoder();
796 connecting(retryDetail);
797 scheduleRetry("video", () => void readIosVideo());
798 }
799 };
800
801 /**
802 * serve-sim's helper only accepts HID and pushes its screen config once
803 * screen capture is running, and the AVCC stream does not reliably start
804 * it. Touching the MJPEG endpoint does; one aborted request is enough.
805 */
806 const primeIosHelper = async (session: number) => {
807 const controller = new AbortController();
808 primeController = controller;
809 const timeout = setTimeout(() => controller.abort(), 2_000);
810 try {
811 const response = await fetch(httpUrl(`/helper/${device}/stream.mjpeg`), {
812 signal: controller.signal,
813 credentials: access.credentials ? "include" : "same-origin",
814 });
815 if (stopped || generation !== session) return;
816 if (response.status === 401 || response.status === 403) return handleUnauthorized();
817 await response.body?.getReader().read();
818 } catch {
819 } finally {
820 clearTimeout(timeout);
821 controller.abort();
822 if (primeController === controller) primeController = null;
823 }
824 };
825
826 /**
827 * serve-sim can be locked to WebRTC (EAS Simulator always is), and then
828 * refuses AVCC and MJPEG. An unreadable answer keeps the AVCC path.
829 */
830 const probeIosTransport = async (): Promise<WebRtcSettings | null> => {
831 const probe = new AbortController();
832 const timeout = setTimeout(() => probe.abort(), TRANSPORT_PROBE_TIMEOUT_MS);
833 try {
834 const response = await fetch(httpUrl(`/api?device=${device}`), {
835 signal: probe.signal,
836 credentials: access.credentials ? "include" : "same-origin",
837 });
838 if (!response.ok) return null;
839 const api = decodeServeSimApi(await response.json());
840 if (Option.isNone(api)) return null;
841 const settings = decodeWebRtcSettings(api.value.streamSettings ?? api.value.stream);
842 return Option.isSome(settings) ? settings.value : null;
843 } catch {
844 return null;
845 } finally {
846 clearTimeout(timeout);
847 }
848 };
849
850 const closePeer = () => {
851 const current = peer;
852 if (!current) return;
853 peer = null;
854 current.connection.close();
855 current.video.srcObject = null;
856 current.video.remove();
857 // Releases serve-sim's capture session; best effort because the page may be unloading.
858 void fetch(httpUrl(`/helper/${device}/webrtc/close`), {
859 method: "POST",
860 keepalive: true,
861 headers: { "content-type": "application/json" },
862 body: JSON.stringify({ sessionId: current.sessionId }),
863 credentials: access.credentials ? "include" : "same-origin",
864 }).catch(() => {});
865 };
866
867 const readIosWebRtc = async (settings: WebRtcSettings) => {
868 const lifecycle = generation;
869 const feedGeneration = ++videoGeneration;
870 closePeer();
871 const connection = new RTCPeerConnection({
872 ...(settings.iceServers
873 ? {
874 iceServers: settings.iceServers.map((server) => ({
875 ...server,
876 urls: typeof server.urls === "string" ? server.urls : [...server.urls],
877 })),
878 }
879 : {}),
880 iceTransportPolicy: settings.iceTransportPolicy ?? "all",
881 });
882 // Frames only reach requestVideoFrameCallback from a video that is in the
883 // document; it stays invisible because the sink paints them.
884 const video = document.createElement("video");
885 video.muted = true;
886 video.playsInline = true;
887 video.setAttribute("aria-hidden", "true");
888 video.style.cssText =
889 "position:fixed;width:1px;height:1px;opacity:0;pointer-events:none;left:0;top:0";
890 document.body.append(video);
891 const current = { connection, sessionId: webRtcSessionId(), video };
892 peer = current;
893 const isCurrent = () =>
894 !stopped &&
895 generation === lifecycle &&
896 videoGeneration === feedGeneration &&
897 peer === current;
898 // After the first frame nothing else bounds a feed that stops: the peer
899 // can sit `disconnected` with the last frame on the canvas. A long gap
900 // between frames reconnects through the same path as a failed connection.
901 let checksWithoutFrame = 0;
902 let watchdog: ReturnType<typeof setInterval> | null = null;
903 const clearWatchdog = () => {
904 if (watchdog !== null) clearInterval(watchdog);
905 watchdog = null;
906 };
907 const retry = (detail: string) => {
908 clearWatchdog();
909 if (!isCurrent()) return;
910 closePeer();
911 connecting(detail);
912 scheduleRetry("video", () => void readIosWebRtc(settings));
913 };
914 const presentFrame = () => {
915 if (!isCurrent()) {
916 clearWatchdog();
917 return;
918 }
919 if (video.videoWidth > 0 && video.videoHeight > 0) {
920 paint(video, video.videoWidth, video.videoHeight);
921 checksWithoutFrame = 0;
922 watchdog ??= setInterval(() => {
923 if (!isCurrent()) return clearWatchdog();
924 checksWithoutFrame++;
925 if (checksWithoutFrame * WEBRTC_STALL_CHECK_MS >= WEBRTC_STALL_TIMEOUT_MS) {
926 retry("Device stream stalled. Reconnecting…");
927 }
928 }, WEBRTC_STALL_CHECK_MS);
929 }
930 video.requestVideoFrameCallback(presentFrame);
931 };
932 const transceiver = connection.addTransceiver("video", { direction: "recvonly" });
933 const codecs = RTCRtpReceiver.getCapabilities("video")?.codecs ?? [];
934 if (codecs.length > 0) {
935 // serve-sim encodes H.264; other codecs stay as fallbacks it may refuse.
936 transceiver.setCodecPreferences([
937 ...codecs.filter((codec) => codec.mimeType.toLowerCase() === "video/h264"),
938 ...codecs.filter((codec) => codec.mimeType.toLowerCase() !== "video/h264"),
939 ]);
940 }
941 connection.ontrack = (event) => {
942 if (!isCurrent()) return;
943 iceGatheringDeadlineMs = ICE_GATHERING_TIMEOUT_MS;
944 video.srcObject = event.streams[0] ?? new MediaStream([event.track]);
945 void video.play().catch(() => {});
946 video.requestVideoFrameCallback(presentFrame);
947 };
948 connection.onconnectionstatechange = () => {
949 if (connection.connectionState === "failed")
950 retry("Device stream connection failed. Reconnecting…");
951 };
952 try {
953 await connection.setLocalDescription(await connection.createOffer());
954 const gathered = await new Promise<boolean>((resolve) => {
955 if (connection.iceGatheringState === "complete") return resolve(true);
956 const timer = setTimeout(() => done(false), iceGatheringDeadlineMs);
957 function done(complete: boolean) {
958 clearTimeout(timer);
959 connection.removeEventListener("icegatheringstatechange", changed);
960 resolve(complete);
961 }
962 function changed() {
963 if (connection.iceGatheringState === "complete") done(true);
964 }
965 connection.addEventListener("icegatheringstatechange", changed);
966 });
967 if (!isCurrent()) return;
968 // serve-sim takes the offer's candidates as the whole set; none trickle
969 // later. A simulator in the cloud needs a reflexive or relay candidate,
970 // which STUN and TURN can take longer than the deadline to produce: an
971 // offer cut short without one is retried with a longer deadline, up to
972 // a bound, after which it goes as gathered rather than never.
973 const sdp = connection.localDescription?.sdp ?? "";
974 if (
975 !gathered &&
976 !/^a=candidate:.* typ (?:srflx|relay)\b/m.test(sdp) &&
977 iceGatheringDeadlineMs < ICE_GATHERING_MAX_TIMEOUT_MS
978 ) {
979 iceGatheringDeadlineMs = Math.min(iceGatheringDeadlineMs * 2, ICE_GATHERING_MAX_TIMEOUT_MS);
980 return retry("Device stream found no network candidates yet. Retrying…");
981 }
982 const response = await fetch(httpUrl(`/helper/${device}/webrtc/offer`), {
983 method: "POST",
984 headers: { "content-type": "application/json" },
985 body: JSON.stringify({
986 type: "offer",
987 sdp: connection.localDescription?.sdp,
988 sessionId: current.sessionId,
989 codec: "h264",
990 }),
991 credentials: access.credentials ? "include" : "same-origin",
992 });
993 if (!isCurrent()) {
994 await response.body?.cancel();
995 return;
996 }
997 if (response.status === 401 || response.status === 403) return handleUnauthorized();
998 // 409: another viewer is still negotiating with this simulator.
999 if (!response.ok) return retry(`Device stream offer failed (${response.status}). Retrying…`);
1000 const answer = decodeWebRtcAnswer(await response.json());
1001 if (!isCurrent()) return;
1002 if (Option.isNone(answer))
1003 return retry("Device stream returned an invalid answer. Retrying…");
1004 await connection.setRemoteDescription(answer.value);
1005 } catch (cause) {
1006 retry((cause as Error).message);
1007 }
1008 };
1009
1010 /**
1011 * Called once AVCC or MJPEG was refused. `locked` means serve-sim already
1012 * said it streams WebRTC only, so a missing /api answer still switches.
1013 */
1014 const switchToWebRtc = async (failure: string, locked: boolean) => {
1015 const session = generation;
1016 if (typeof RTCPeerConnection === "undefined") return fail(failure);
1017 const settings =
1018 (await probeIosTransport()) ?? (locked ? { transport: "webrtc" as const } : null);
1019 if (stopped || generation !== session) return;
1020 if (!settings) return fail(failure);
1021 if (mjpeg) {
1022 mjpeg = false;
1023 releaseImage?.();
1024 releaseImage = null;
1025 events.onCanvasVideo?.();
1026 }
1027 // MJPEG may have shown frames already: say the stream is connecting again
1028 // rather than leave a blank canvas until the first WebRTC frame.
1029 connecting("Switching to WebRTC.");
1030 void readIosWebRtc(settings);
1031 };
1032
1033 const startDuoVideo = (panels: DuoPanelSinks) => {
1034 for (const panel of panelClients) panel.stop();
1035 // Physical handoff elects a native surface. Fixed-panel encoders can keep
1036 // an inactive shutdown frame after election, so this build uses one active
1037 // feed instead of decoding a third stream alongside the two fixed feeds.
1038 const ids = screen?.supportsPhysicalOrientation ? ([null] as const) : ([1, 3] as const);
1039 panelClients = ids.map((id) => {
1040 const output = id === 1 ? panels.cover : panels.inner;
1041 return createDeviceStreamClient(
1042 { ...target, ...(id === null ? {} : { panelId: id }), videoOnly: true },
1043 {
1044 present(source, width, height) {
1045 if (id === null) {
1046 return sink.present(source, width, height);
1047 }
1048 // An inactive native LCD can emit its shutdown black frame. Retain its last useful image.
1049 if (screen?.screenId !== id) return true;
1050 const retained = output.present(source, width, height);
1051 const primary = sink.present(source, width, height);
1052 return retained && primary;
1053 },
1054 },
1055 {
1056 onStatus: (status, detail) => {
1057 if (status === "error") events.onDuoUnavailable?.(detail);
1058 },
1059 onScreen: () => {},
1060 onInputConnected: () => {},
1061 onMjpegFallback: () => {},
1062 onUnauthorized: handleUnauthorized,
1063 },
1064 );
1065 });
1066 for (const panel of panelClients) panel.start();
1067 };
1068
1069 const connectIosInput = async () => {
1070 if (stopped) return;
1071 const session = generation;
1072 await primeIosHelper(session);
1073 if (stopped || generation !== session) return;
1074 const ws = new WebSocket(wsUrl(`/helper/ws?device=${device}`));
1075 ws.binaryType = "arraybuffer";
1076 socket = ws;
1077 iosInputAdmitted = false;
1078 iosInputUnavailable = false;
1079 ws.onmessage = (event) => {
1080 if (stopped || socket !== ws) return;
1081 if (!(event.data instanceof ArrayBuffer)) return;
1082 const bytes = new Uint8Array(event.data);
1083 if (socket !== ws || stopped || bytes.length < 1) return;
1084 if (bytes[0] === IOS_TAG_INPUT_ADMITTED) {
1085 iosInputAdmitted = true;
1086 events.onInputConnected(!iosInputUnavailable);
1087 return;
1088 }
1089 try {
1090 const payload: unknown = JSON.parse(decoder.decode(bytes.subarray(1)));
1091 if (bytes[0] === 0x90) {
1092 const reply = decodeControlReply(payload);
1093 if (Option.isSome(reply)) duoControl.receive(reply.value);
1094 } else if (bytes[0] === IOS_TAG_SCREEN_CONFIG) {
1095 const config = decodeScreenConfig(payload);
1096 if (Option.isSome(config)) {
1097 iosInputUnavailable = config.value.inputUnavailable === true;
1098 events.onInputConnected(
1099 iosInputAdmitted && !iosInputUnavailable,
1100 iosInputUnavailable ? "Simulator input is unavailable" : undefined,
1101 );
1102 const previous = screen;
1103 screen = config.value;
1104 if (screen.hingePose && screen.hingePose !== previous?.hingePose)
1105 rotationCursor = screen.hingePose === "laptop" ? "landscape_left" : "portrait";
1106 else if (screen.orientation !== previous?.orientation)
1107 rotationCursor = screen.orientation;
1108 panelSinks?.onScreen?.(screen);
1109 events.onScreen(screen);
1110 // A surface election can leave an existing decoder on the former
1111 // encoder description. Reopen only video to acquire the elected
1112 // surface's seed and codec configuration; HID and the viewer stay.
1113 if (
1114 panelSinks &&
1115 screen.supportsPhysicalOrientation &&
1116 previous &&
1117 screen.screenId !== previous.screenId
1118 )
1119 startDuoVideo(panelSinks);
1120 if (pendingOrientation) {
1121 const receipt = pendingOrientation;
1122 pendingOrientation = null;
1123 duoControl.receive({
1124 requestId: receipt.requestId,
1125 ok: true,
1126 });
1127 }
1128 }
1129 }
1130 } catch {}
1131 };
1132 ws.onclose = (event) => {
1133 if (socket !== ws) return;
1134 socket = null;
1135 iosInputAdmitted = false;
1136 duoControl.clear();
1137 rotationCursor = null;
1138 if (stopped) return;
1139 events.onInputConnected(
1140 false,
1141 event.reason || (event.code === 1006 ? "input socket refused" : `closed ${event.code}`),
1142 );
1143 // A rejected HTTP upgrade surfaces as 1006, including an expired stream ticket.
1144 if (
1145 event.code === 1008 ||
1146 event.code === 4401 ||
1147 (event.code === 1006 && access.query.wsTicket)
1148 )
1149 return handleUnauthorized();
1150 scheduleRetry("input", () => void connectIosInput());
1151 };
1152 ws.onerror = () => ws.close();
1153 };
1154
1155 const connectAndroid = () => {
1156 if (stopped) return;
1157 const ws = new WebSocket(wsUrl(`/ws?device=${device}&frame-meta=1`));
1158 ws.binaryType = "arraybuffer";
1159 socket = ws;
1160 ws.onopen = () => {
1161 if (stopped || socket !== ws) return;
1162 connecting();
1163 events.onInputConnected(true);
1164 };
1165 ws.onmessage = (event) => {
1166 if (stopped || socket !== ws) return;
1167 if (typeof event.data === "string") {
1168 // The encoder restarts at a new size when the device rotates; the
1169 // next keyframe carries a fresh SPS, so the decoder is rebuilt from it.
1170 if (isVideoSessionMessage(event.data)) {
1171 closeDecoder();
1172 configuring = false;
1173 connecting();
1174 requestKeyframe();
1175 }
1176 return;
1177 }
1178 if (!(event.data instanceof ArrayBuffer)) return;
1179 const packet = parseSemuPacket(event.data);
1180 const needsScan =
1181 packet.isKey === null ||
1182 (packet.isKey && (!videoDecoder || videoDecoder.state !== "configured"));
1183 const scanned = needsScan ? scanAccessUnit(packet.data) : null;
1184 const isKey = packet.isKey ?? scanned?.isKey ?? false;
1185 if (scanned?.sps && (!videoDecoder || videoDecoder.state !== "configured")) {
1186 if (configuring) return;
1187 configuring = true;
1188 const epoch = decoderEpoch;
1189 const isCurrent = () => !stopped && socket === ws;
1190 void configureDecoder({ codec: avcCodecString(scanned.sps) }, isCurrent).then(
1191 (configured) => {
1192 if (!isCurrent() || epoch !== decoderEpoch) return;
1193 configuring = false;
1194 awaitingKeyframe = true;
1195 if (configured) requestKeyframe();
1196 },
1197 );
1198 return;
1199 }
1200 if (!videoDecoder || videoDecoder.state !== "configured") {
1201 if (!isKey) requestKeyframe();
1202 return;
1203 }
1204 decode(isKey, packet.data, packet.timestamp);
1205 };
1206 ws.onclose = (event) => {
1207 if (socket !== ws) return;
1208 socket = null;
1209 closeDecoder();
1210 if (stopped) return;
1211 events.onInputConnected(false, event.reason || `closed ${event.code}`);
1212 if (
1213 event.code === 1008 ||
1214 event.code === 4401 ||
1215 (event.code === 1006 && access.query.wsTicket)
1216 )
1217 return handleUnauthorized();
1218 configuring = false;
1219 connecting(event.reason || undefined);
1220 scheduleRetry("input", connectAndroid);
1221 };
1222 ws.onerror = () => ws.close();
1223 };
1224
1225 const start = () => {
1226 if (!stopped) return;
1227 stopped = false;
1228 generation++;
1229 configuring = false;
1230 iosInputAdmitted = false;
1231 iosInputUnavailable = false;
1232 connecting();
1233 if (platform === "ios") {
1234 if (!target.videoOnly) void connectIosInput();
1235 if (useWebCodecs) void readIosVideo();
1236 else fallBackToMjpeg();
1237 } else if (useWebCodecs) {
1238 connectAndroid();
1239 } else {
1240 fail("This browser cannot decode the Android stream (WebCodecs unavailable).");
1241 }
1242 };
1243
1244 const stop = () => {
1245 if (stopped) return;
1246 stopped = true;
1247 generation++;
1248 videoGeneration++;
1249 duoControl.clear();
1250 rotationCursor = null;
1251 for (const panel of panelClients) panel.stop();
1252 panelClients = [];
1253 panelSinks = null;
1254 mjpeg = false;
1255 clearFrameTimer();
1256 if (videoReadTimer !== null) clearTimeout(videoReadTimer);
1257 videoReadTimer = null;
1258 releaseImage?.();
1259 releaseImage = null;
1260 mjpegImage = null;
1261 for (const timer of retryTimers.values()) clearTimeout(timer);
1262 retryTimers.clear();
1263 primeController?.abort();
1264 primeController = null;
1265 controller?.abort();
1266 controller = null;
1267 closePeer();
1268 const discarded = socket;
1269 socket = null;
1270 discarded?.close();
1271 closeDecoder();
1272 };
1273
1274 const send = (payload: Uint8Array<ArrayBuffer> | string) => {
1275 if (
1276 !stopped &&
1277 (platform !== "ios" || (iosInputAdmitted && !iosInputUnavailable)) &&
1278 socket?.readyState === WebSocket.OPEN
1279 )
1280 socket.send(payload);
1281 };
1282
1283 const rawPoint = (x: number, y: number) => {
1284 // serve-sim streams the raw framebuffer; rotated devices need input
1285 // remapped into that raw space.
1286 if (platform !== "ios" || !screen || screen.width > screen.height) return { x, y };
1287 switch (screen.orientation) {
1288 case "landscape_left":
1289 return { x: y, y: 1 - x };
1290 case "landscape_right":
1291 return { x: 1 - y, y: x };
1292 case "portrait_upside_down":
1293 return { x: 1 - x, y: 1 - y };
1294 default:
1295 return { x, y };
1296 }
1297 };
1298
1299 return {
1300 start,
1301 stop,
1302 setMjpegImage,
1303 controlDuo: duoControl.enqueue,
1304 sendRawTouch: (phase, x, y) => {
1305 if (platform === "ios") send(taggedJson(IOS_MSG_TOUCH, { type: phase, x, y }));
1306 },
1307 setDuoPanels(panels) {
1308 if (platform !== "ios" || target.videoOnly || stopped || panelSinks === panels) return;
1309 if (panels && !screen?.supportsHingeAngle) return;
1310 panelSinks = panels;
1311 videoGeneration++;
1312 controller?.abort();
1313 controller = null;
1314 closePeer();
1315 closeDecoder();
1316 const retry = retryTimers.get("video");
1317 if (retry) clearTimeout(retry);
1318 retryTimers.delete("video");
1319 for (const panel of panelClients) panel.stop();
1320 panelClients = [];
1321 if (!panels) {
1322 if (useWebCodecs) void readIosVideo();
1323 return;
1324 }
1325 startDuoVideo(panels);
1326 },
1327 sendTouch: (phase, x, y) => {
1328 if (platform === "ios") {
1329 send(taggedJson(IOS_MSG_TOUCH, { type: phase, ...rawPoint(x, y) }));
1330 return;
1331 }
1332 const action = phase === "begin" ? "down" : phase === "move" ? "move" : "up";
1333 send(JSON.stringify({ type: "touch", action, x, y }));
1334 },
1335 sendKey: (event, phase) => {
1336 if (platform === "ios") {
1337 const usage = hidUsageForCode(event.code);
1338 if (usage !== null) send(taggedJson(IOS_MSG_KEY, { type: phase, usage }));
1339 return;
1340 }
1341 if (phase !== "down") return;
1342 if (event.key === "Escape") return send(JSON.stringify({ type: "back" }));
1343 const keycode = ANDROID_KEYCODE_BY_KEY[event.key];
1344 if (keycode !== undefined) return send(JSON.stringify({ type: "key", keycode }));
1345 if (event.key.length === 1 && !event.metaKey && !event.ctrlKey) {
1346 send(JSON.stringify({ type: "text", text: event.key }));
1347 }
1348 },
1349 sendText: (text) => {
1350 if (platform !== "android") return;
1351 let chunk = "";
1352 let chunkBytes = 0;
1353 let sentChunks = 0;
1354 for (const character of text) {
1355 const characterBytes = utf8ByteLength(character.codePointAt(0)!);
1356 if (chunkBytes + characterBytes > ANDROID_MAX_TEXT_BYTES) {
1357 send(JSON.stringify({ type: "text", text: chunk }));
1358 if (++sentChunks >= ANDROID_MAX_TEXT_CHUNKS) return;
1359 chunk = "";
1360 chunkBytes = 0;
1361 }
1362 chunk += character;
1363 chunkBytes += characterBytes;
1364 }
1365 if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk }));
1366 },
1367 pressButton: (button) => {
1368 if (platform === "ios") {
1369 const name =
1370 button === "home"
1371 ? "home"
1372 : button === "appSwitcher"
1373 ? "app_switcher"
1374 : button === "power"
1375 ? "lock"
1376 : null;
1377 if (name) send(taggedJson(IOS_MSG_BUTTON, { button: name }));
1378 return;
1379 }
1380 const type = button === "appSwitcher" ? "recents" : button;
1381 if (type === "home" || type === "back" || type === "recents" || type === "power") {
1382 send(JSON.stringify({ type }));
1383 }
1384 },
1385 rotate: () => {
1386 if (platform !== "ios") return;
1387 const current = screen?.supportsHingeAngle
1388 ? (rotationCursor ?? screen.orientation)
1389 : (screen?.orientation ?? "portrait");
1390 const next =
1391 IOS_ORIENTATIONS[(IOS_ORIENTATIONS.indexOf(current) + 1) % IOS_ORIENTATIONS.length]!;
1392 if (screen?.supportsHingeAngle) {
1393 rotationCursor = next;
1394 duoControl.enqueue({ control: "orientation", value: next });
1395 } else send(taggedJson(IOS_MSG_ORIENTATION, { orientation: next }));
1396 },
1397 setOrientation: (orientation) => {
1398 if (platform === "ios") send(taggedJson(IOS_MSG_ORIENTATION, { orientation }));
1399 },
1400 };
1401}