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