Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

stream.ts

1,402 lines48.8 KB

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