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 the offer's candidates as the whole set; none trickle
973 // later. A simulator in the cloud needs a reflexive or relay candidate,
974 // which STUN and TURN can take longer than the deadline to produce: an
975 // offer cut short without one is retried with a longer deadline, up to
976 // a bound, after which it goes as gathered rather than never.
977 const sdp = connection.localDescription?.sdp ?? "";
978 if (
979 !gathered &&
980 !/^a=candidate:.* typ (?:srflx|relay)\b/m.test(sdp) &&
981 iceGatheringDeadlineMs < ICE_GATHERING_MAX_TIMEOUT_MS
982 ) {
983 iceGatheringDeadlineMs = Math.min(iceGatheringDeadlineMs * 2, ICE_GATHERING_MAX_TIMEOUT_MS);
984 return retry("Device stream found no network candidates yet. Retrying…");
985 }
986 const response = await fetch(httpUrl(`/helper/${device}/webrtc/offer`), {
987 method: "POST",
988 headers: { "content-type": "application/json" },
989 body: JSON.stringify({
990 type: "offer",
991 sdp: connection.localDescription?.sdp,
992 sessionId: current.sessionId,
993 codec: "h264",
994 }),
995 credentials: access.credentials ? "include" : "same-origin",
996 });
997 if (!isCurrent()) {
998 await response.body?.cancel();
999 return;
1000 }
1001 if (response.status === 401 || response.status === 403) return handleUnauthorized();
1002 // 409: another viewer is still negotiating with this simulator.
1003 if (!response.ok) return retry(`Device stream offer failed (${response.status}). Retrying…`);
1004 const answer = decodeWebRtcAnswer(await response.json());
1005 if (!isCurrent()) return;
1006 if (Option.isNone(answer))
1007 return retry("Device stream returned an invalid answer. Retrying…");
1008 await connection.setRemoteDescription(answer.value);
1009 } catch (cause) {
1010 retry((cause as Error).message);
1011 }
1012 };
1013
1014 /**
1015 * Called once AVCC or MJPEG was refused. `locked` means serve-sim already
1016 * said it streams WebRTC only, so a missing /api answer still switches.
1017 */
1018 const switchToWebRtc = async (failure: string, locked: boolean) => {
1019 const session = generation;
1020 if (typeof RTCPeerConnection === "undefined") return fail(failure);
1021 const settings =
1022 (await probeIosTransport()) ?? (locked ? { transport: "webrtc" as const } : null);
1023 if (stopped || generation !== session) return;
1024 if (!settings) return fail(failure);
1025 if (mjpeg) {
1026 mjpeg = false;
1027 releaseImage?.();
1028 releaseImage = null;
1029 events.onCanvasVideo?.();
1030 }
1031 // MJPEG may have shown frames already: say the stream is connecting again
1032 // rather than leave a blank canvas until the first WebRTC frame.
1033 connecting("Switching to WebRTC.");
1034 void readIosWebRtc(settings);
1035 };
1036
1037 const startDuoVideo = (panels: DuoPanelSinks) => {
1038 for (const panel of panelClients) panel.stop();
1039 // Physical handoff elects a native surface. Fixed-panel encoders can keep
1040 // an inactive shutdown frame after election, so this build uses one active
1041 // feed instead of decoding a third stream alongside the two fixed feeds.
1042 const ids = screen?.supportsPhysicalOrientation ? ([null] as const) : ([1, 3] as const);
1043 panelClients = ids.map((id) => {
1044 const output = id === 1 ? panels.cover : panels.inner;
1045 return createDeviceStreamClient(
1046 { ...target, ...(id === null ? {} : { panelId: id }), videoOnly: true },
1047 {
1048 present(source, width, height) {
1049 if (id === null) {
1050 return sink.present(source, width, height);
1051 }
1052 // An inactive native LCD can emit its shutdown black frame. Retain its last useful image.
1053 if (screen?.screenId !== id) return true;
1054 const retained = output.present(source, width, height);
1055 const primary = sink.present(source, width, height);
1056 return retained && primary;
1057 },
1058 },
1059 {
1060 onStatus: (status, detail) => {
1061 if (status === "error") events.onDuoUnavailable?.(detail);
1062 },
1063 onScreen: () => {},
1064 onInputConnected: () => {},
1065 onMjpegFallback: () => {},
1066 onUnauthorized: handleUnauthorized,
1067 },
1068 );
1069 });
1070 for (const panel of panelClients) panel.start();
1071 };
1072
1073 const connectIosInput = async () => {
1074 if (stopped) return;
1075 const session = generation;
1076 await primeIosHelper(session);
1077 if (stopped || generation !== session) return;
1078 const ws = new WebSocket(wsUrl(`/helper/ws?device=${device}`));
1079 ws.binaryType = "arraybuffer";
1080 socket = ws;
1081 iosInputAdmitted = false;
1082 iosInputUnavailable = false;
1083 ws.onmessage = (event) => {
1084 if (stopped || socket !== ws) return;
1085 if (!(event.data instanceof ArrayBuffer)) return;
1086 const bytes = new Uint8Array(event.data);
1087 if (socket !== ws || stopped || bytes.length < 1) return;
1088 if (bytes[0] === IOS_TAG_INPUT_ADMITTED) {
1089 iosInputAdmitted = true;
1090 events.onInputConnected(!iosInputUnavailable);
1091 return;
1092 }
1093 try {
1094 const payload: unknown = JSON.parse(decoder.decode(bytes.subarray(1)));
1095 if (bytes[0] === 0x90) {
1096 const reply = decodeControlReply(payload);
1097 if (Option.isSome(reply)) duoControl.receive(reply.value);
1098 } else if (bytes[0] === IOS_TAG_SCREEN_CONFIG) {
1099 const config = decodeScreenConfig(payload);
1100 if (Option.isSome(config)) {
1101 iosInputUnavailable = config.value.inputUnavailable === true;
1102 events.onInputConnected(
1103 iosInputAdmitted && !iosInputUnavailable,
1104 iosInputUnavailable ? "Simulator input is unavailable" : undefined,
1105 );
1106 const previous = screen;
1107 screen = config.value;
1108 if (screen.hingePose && screen.hingePose !== previous?.hingePose)
1109 rotationCursor = screen.hingePose === "laptop" ? "landscape_left" : "portrait";
1110 else if (screen.orientation !== previous?.orientation)
1111 rotationCursor = screen.orientation;
1112 panelSinks?.onScreen?.(screen);
1113 events.onScreen(screen);
1114 // A surface election can leave an existing decoder on the former
1115 // encoder description. Reopen only video to acquire the elected
1116 // surface's seed and codec configuration; HID and the viewer stay.
1117 if (
1118 panelSinks &&
1119 screen.supportsPhysicalOrientation &&
1120 previous &&
1121 screen.screenId !== previous.screenId
1122 )
1123 startDuoVideo(panelSinks);
1124 if (pendingOrientation) {
1125 const receipt = pendingOrientation;
1126 pendingOrientation = null;
1127 duoControl.receive({
1128 requestId: receipt.requestId,
1129 ok: true,
1130 });
1131 }
1132 }
1133 }
1134 } catch {}
1135 };
1136 ws.onclose = (event) => {
1137 if (socket !== ws) return;
1138 socket = null;
1139 iosInputAdmitted = false;
1140 duoControl.clear();
1141 rotationCursor = null;
1142 if (stopped) return;
1143 events.onInputConnected(
1144 false,
1145 event.reason || (event.code === 1006 ? "input socket refused" : `closed ${event.code}`),
1146 );
1147 // A rejected HTTP upgrade surfaces as 1006, including an expired stream ticket.
1148 if (
1149 event.code === 1008 ||
1150 event.code === 4401 ||
1151 (event.code === 1006 && access.query.wsTicket)
1152 )
1153 return handleUnauthorized();
1154 scheduleRetry("input", () => void connectIosInput());
1155 };
1156 ws.onerror = () => ws.close();
1157 };
1158
1159 const connectAndroid = () => {
1160 if (stopped) return;
1161 const ws = new WebSocket(wsUrl(`/ws?device=${device}&frame-meta=1`));
1162 ws.binaryType = "arraybuffer";
1163 socket = ws;
1164 ws.onopen = () => {
1165 if (stopped || socket !== ws) return;
1166 connecting();
1167 events.onInputConnected(true);
1168 };
1169 ws.onmessage = (event) => {
1170 if (stopped || socket !== ws) return;
1171 if (typeof event.data === "string") {
1172 // The encoder restarts at a new size when the device rotates; the
1173 // next keyframe carries a fresh SPS, so the decoder is rebuilt from it.
1174 if (isVideoSessionMessage(event.data)) {
1175 closeDecoder();
1176 configuring = false;
1177 connecting();
1178 requestKeyframe();
1179 }
1180 return;
1181 }
1182 if (!(event.data instanceof ArrayBuffer)) return;
1183 const packet = parseSemuPacket(event.data);
1184 const needsScan =
1185 packet.isKey === null ||
1186 (packet.isKey && (!videoDecoder || videoDecoder.state !== "configured"));
1187 const scanned = needsScan ? scanAccessUnit(packet.data) : null;
1188 const isKey = packet.isKey ?? scanned?.isKey ?? false;
1189 if (scanned?.sps && (!videoDecoder || videoDecoder.state !== "configured")) {
1190 if (configuring) return;
1191 configuring = true;
1192 const epoch = decoderEpoch;
1193 const isCurrent = () => !stopped && socket === ws;
1194 void configureDecoder({ codec: avcCodecString(scanned.sps) }, isCurrent).then(
1195 (configured) => {
1196 if (!isCurrent() || epoch !== decoderEpoch) return;
1197 configuring = false;
1198 awaitingKeyframe = true;
1199 if (configured) requestKeyframe();
1200 },
1201 );
1202 return;
1203 }
1204 if (!videoDecoder || videoDecoder.state !== "configured") {
1205 if (!isKey) requestKeyframe();
1206 return;
1207 }
1208 decode(isKey, packet.data, packet.timestamp);
1209 };
1210 ws.onclose = (event) => {
1211 if (socket !== ws) return;
1212 socket = null;
1213 closeDecoder();
1214 if (stopped) return;
1215 events.onInputConnected(false, event.reason || `closed ${event.code}`);
1216 if (
1217 event.code === 1008 ||
1218 event.code === 4401 ||
1219 (event.code === 1006 && access.query.wsTicket)
1220 )
1221 return handleUnauthorized();
1222 configuring = false;
1223 connecting(event.reason || undefined);
1224 scheduleRetry("input", connectAndroid);
1225 };
1226 ws.onerror = () => ws.close();
1227 };
1228
1229 const start = () => {
1230 if (!stopped) return;
1231 stopped = false;
1232 generation++;
1233 configuring = false;
1234 iosInputAdmitted = false;
1235 iosInputUnavailable = false;
1236 connecting();
1237 if (platform === "ios") {
1238 if (!target.videoOnly) void connectIosInput();
1239 if (useWebCodecs) void readIosVideo();
1240 else fallBackToMjpeg();
1241 } else if (useWebCodecs) {
1242 connectAndroid();
1243 } else {
1244 fail("This browser cannot decode the Android stream (WebCodecs unavailable).");
1245 }
1246 };
1247
1248 const stop = () => {
1249 if (stopped) return;
1250 stopped = true;
1251 generation++;
1252 videoGeneration++;
1253 duoControl.clear();
1254 rotationCursor = null;
1255 for (const panel of panelClients) panel.stop();
1256 panelClients = [];
1257 panelSinks = null;
1258 mjpeg = false;
1259 clearFrameTimer();
1260 if (videoReadTimer !== null) clearTimeout(videoReadTimer);
1261 videoReadTimer = null;
1262 releaseImage?.();
1263 releaseImage = null;
1264 mjpegImage = null;
1265 for (const timer of retryTimers.values()) clearTimeout(timer);
1266 retryTimers.clear();
1267 primeController?.abort();
1268 primeController = null;
1269 controller?.abort();
1270 controller = null;
1271 closePeer();
1272 const discarded = socket;
1273 socket = null;
1274 discarded?.close();
1275 closeDecoder();
1276 };
1277
1278 const send = (payload: Uint8Array<ArrayBuffer> | string) => {
1279 if (
1280 !stopped &&
1281 (platform !== "ios" || (iosInputAdmitted && !iosInputUnavailable)) &&
1282 socket?.readyState === WebSocket.OPEN
1283 )
1284 socket.send(payload);
1285 };
1286
1287 const rawPoint = (x: number, y: number) => {
1288 // serve-sim streams the raw framebuffer; rotated devices need input
1289 // remapped into that raw space.
1290 if (platform !== "ios" || !screen || screen.width > screen.height) return { x, y };
1291 switch (screen.orientation) {
1292 case "landscape_left":
1293 return { x: y, y: 1 - x };
1294 case "landscape_right":
1295 return { x: 1 - y, y: x };
1296 case "portrait_upside_down":
1297 return { x: 1 - x, y: 1 - y };
1298 default:
1299 return { x, y };
1300 }
1301 };
1302
1303 return {
1304 start,
1305 stop,
1306 setMjpegImage,
1307 controlDuo: duoControl.enqueue,
1308 sendRawTouch: (phase, x, y) => {
1309 if (platform === "ios") send(taggedJson(IOS_MSG_TOUCH, { type: phase, x, y }));
1310 },
1311 setDuoPanels(panels) {
1312 if (platform !== "ios" || target.videoOnly || stopped || panelSinks === panels) return;
1313 if (panels && !screen?.supportsHingeAngle) return;
1314 panelSinks = panels;
1315 videoGeneration++;
1316 controller?.abort();
1317 controller = null;
1318 closePeer();
1319 closeDecoder();
1320 const retry = retryTimers.get("video");
1321 if (retry) clearTimeout(retry);
1322 retryTimers.delete("video");
1323 for (const panel of panelClients) panel.stop();
1324 panelClients = [];
1325 if (!panels) {
1326 if (useWebCodecs) void readIosVideo();
1327 return;
1328 }
1329 startDuoVideo(panels);
1330 },
1331 sendTouch: (phase, x, y) => {
1332 if (platform === "ios") {
1333 send(taggedJson(IOS_MSG_TOUCH, { type: phase, ...rawPoint(x, y) }));
1334 return;
1335 }
1336 const action = phase === "begin" ? "down" : phase === "move" ? "move" : "up";
1337 send(JSON.stringify({ type: "touch", action, x, y }));
1338 },
1339 sendKey: (event, phase) => {
1340 if (platform === "ios") {
1341 const usage = hidUsageForCode(event.code);
1342 if (usage !== null) send(taggedJson(IOS_MSG_KEY, { type: phase, usage }));
1343 return;
1344 }
1345 if (phase !== "down") return;
1346 if (event.key === "Escape") return send(JSON.stringify({ type: "back" }));
1347 const keycode = ANDROID_KEYCODE_BY_KEY[event.key];
1348 if (keycode !== undefined) return send(JSON.stringify({ type: "key", keycode }));
1349 if (event.key.length === 1 && !event.metaKey && !event.ctrlKey) {
1350 send(JSON.stringify({ type: "text", text: event.key }));
1351 }
1352 },
1353 sendText: (text) => {
1354 if (platform !== "android") return;
1355 let chunk = "";
1356 let chunkBytes = 0;
1357 let sentChunks = 0;
1358 for (const character of text) {
1359 const characterBytes = utf8ByteLength(character.codePointAt(0)!);
1360 if (chunkBytes + characterBytes > ANDROID_MAX_TEXT_BYTES) {
1361 send(JSON.stringify({ type: "text", text: chunk }));
1362 if (++sentChunks >= ANDROID_MAX_TEXT_CHUNKS) return;
1363 chunk = "";
1364 chunkBytes = 0;
1365 }
1366 chunk += character;
1367 chunkBytes += characterBytes;
1368 }
1369 if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk }));
1370 },
1371 pressButton: (button) => {
1372 if (platform === "ios") {
1373 const name =
1374 button === "home"
1375 ? "home"
1376 : button === "appSwitcher"
1377 ? "app_switcher"
1378 : button === "power"
1379 ? "lock"
1380 : null;
1381 if (name) send(taggedJson(IOS_MSG_BUTTON, { button: name }));
1382 return;
1383 }
1384 const type = button === "appSwitcher" ? "recents" : button;
1385 if (type === "home" || type === "back" || type === "recents" || type === "power") {
1386 send(JSON.stringify({ type }));
1387 }
1388 },
1389 rotate: () => {
1390 if (platform !== "ios") return;
1391 const current = screen?.supportsHingeAngle
1392 ? (rotationCursor ?? screen.orientation)
1393 : (screen?.orientation ?? "portrait");
1394 const next =
1395 IOS_ORIENTATIONS[(IOS_ORIENTATIONS.indexOf(current) + 1) % IOS_ORIENTATIONS.length]!;
1396 if (screen?.supportsHingeAngle) {
1397 rotationCursor = next;
1398 duoControl.enqueue({ control: "orientation", value: next });
1399 } else send(taggedJson(IOS_MSG_ORIENTATION, { orientation: next }));
1400 },
1401 setOrientation: (orientation) => {
1402 if (platform === "ios") send(taggedJson(IOS_MSG_ORIENTATION, { orientation }));
1403 },
1404 };
1405}