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

stream.ts

712 lines23.1 KB

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​
4/**
5 * Framework-free client for expo-device-hub's per-device streams, reached
6 * through the T3 proxy. One class handles both platforms because the hub
7 * vendors two servers with different wire formats:
8 *
9 * - iOS (serve-sim): video is an HTTP `stream.avcc` body of length-prefixed
10 * envelopes (`u32be length, u8 tag, payload`; tag 1 avcC description,
11 * 2 keyframe, 3 delta, 4 JPEG seed) decoded with WebCodecs; input goes over
12 * `helper/ws?device=<udid>` as `[tag][json]` packets. When WebCodecs is
13 * unavailable (plain-http remote origins) the MJPEG endpoint is used as an
14 * `<img>` source instead.
15 * - Android (serve-emu): one WebSocket at `ws?device=<serial>&frame-meta=1`
16 * carries H.264 access units prefixed with a 16-byte "SEMU" header
17 * (magic, version, key flag, pts) and accepts JSON gestures upstream.
18 *
19 * The decoder only runs while frames arrive and the viewer is attached; a
20 * hidden panel calls `stop()` so an idle device costs nothing on the GPU.
21 */
22import { type DeviceHubAccess, withDeviceHubQuery } from "./hubAccess.ts";
23import type { DevicePlatform } from "@t3tools/contracts";
24​
25export type DeviceStreamStatus = "connecting" | "streaming" | "error";
26​
27export interface DeviceScreenSize {
28 readonly width: number;
29 readonly height: number;
30 readonly orientation: "portrait" | "portrait_upside_down" | "landscape_left" | "landscape_right";
32​
33export interface DeviceStreamEvents {
34 readonly onStatus: (status: DeviceStreamStatus, detail?: string) => void;
35 readonly onScreen: (screen: DeviceScreenSize) => void;
36 /** The proxy rejected the credential; the owner should refresh access and reconnect. */
37 readonly onUnauthorized: () => void;
38 /**
39 * H.264 cannot be decoded here (no WebCodecs, or the simulator's profile is
40 * unsupported); the owner should show this MJPEG URL in an `<img>` instead of
41 * the canvas.
42 */
43 readonly onMjpegFallback: (url: string) => void;
44 /** Whether touches and keys can currently reach the device. */
45 readonly onInputConnected: (connected: boolean, detail?: string) => void;
47​
48export interface DeviceStreamTarget {
49 readonly platform: DevicePlatform;
50 readonly deviceId: string;
51 readonly access: DeviceHubAccess;
52 /** Native iOS WebViews can use MJPEG without cross-origin fetch or secure-context support. */
53 readonly preferMjpeg?: boolean;
55​
56export type DeviceHardwareButton = "home" | "back" | "recents" | "power" | "appSwitcher";
57​
58const RETRY_DELAY_MS = 1_000;
59const FRAME_DURATION_US = 16_667;
60const SEMU_MAGIC = 0x53454d55;
61const SEMU_HEADER_BYTES = 16;
62const SEMU_FLAG_KEY = 1;
63const SOFT_DECODE_QUEUE = 8;
64​
65// serve-sim binary WS message tags (browser -> helper).
66const IOS_MSG_TOUCH = 0x03;
67const IOS_MSG_BUTTON = 0x04;
68const IOS_MSG_KEY = 0x06;
69const IOS_MSG_ORIENTATION = 0x07;
70const IOS_MSG_HARDWARE_KEYBOARD = 0x0d;
71// helper -> browser.
72const IOS_TAG_SCREEN_CONFIG = 0x82;
73​
74const encoder = new TextEncoder();
75const decoder = new TextDecoder();
76​
77const isWebCodecsSupported = (): boolean =>
78 typeof globalThis !== "undefined" &&
79 "VideoDecoder" in globalThis &&
80 "EncodedVideoChunk" in globalThis;
81​
82function taggedJson(tag: number, payload: unknown): Uint8Array<ArrayBuffer> {
83 const json = encoder.encode(JSON.stringify(payload));
84 const out = new Uint8Array(1 + json.length);
85 out[0] = tag;
86 out.set(json, 1);
87 return out;
89​
90/** Build the WebCodecs `avc1.PPCCLL` string from an avcC record or an SPS NAL. */
91export function avcCodecString(bytes: Uint8Array): string {
92 if (bytes.length < 4) return "avc1.42E01E";
93 const hex = (byte: number) => byte.toString(16).padStart(2, "0");
94 return `avc1.${hex(bytes[1]!)}${hex(bytes[2]!)}${hex(bytes[3]!)}`;
96​
97/** Split serve-emu's SEMU-framed message into metadata and the Annex-B payload. */
98export function parseSemuPacket(raw: ArrayBuffer): {
99 readonly data: Uint8Array;
100 readonly isKey: boolean | null;
101 readonly timestamp: number | null;
102} {
103 const bytes = new Uint8Array(raw);
104 if (bytes.byteLength > SEMU_HEADER_BYTES) {
105 const view = new DataView(raw, 0, SEMU_HEADER_BYTES);
106 if (view.getUint32(0, false) === SEMU_MAGIC && view.getUint8(4) === 1) {
107 const pts = view.getBigUint64(8, false);
108 return {
109 data: bytes.subarray(SEMU_HEADER_BYTES),
110 isKey: (view.getUint8(5) & SEMU_FLAG_KEY) !== 0,
111 timestamp: pts <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(pts) : null,
112 };
113 }
114 }
115 return { data: bytes, isKey: null, timestamp: null };
117​
118const isVideoSessionMessage = (text: string) => {
119 try {
120 const message = JSON.parse(text) as { type?: unknown };
121 return message.type === "video-session";
122 } catch {
123 return false;
124 }
125};
126​
127/** Walk an Annex-B access unit for its keyframe flag and SPS bytes. */
128export function scanAccessUnit(buf: Uint8Array): { isKey: boolean; sps: Uint8Array | null } {
129 let isKey = false;
130 let sps: Uint8Array | null = null;
131 const len = buf.length;
132 let i = 0;
133 while (i + 2 < len) {
134 if (buf[i] === 0 && buf[i + 1] === 0) {
135 let codeLen = 0;
136 if (buf[i + 2] === 1) codeLen = 3;
137 else if (i + 3 < len && buf[i + 2] === 0 && buf[i + 3] === 1) codeLen = 4;
138 if (codeLen) {
139 const nalType = buf[i + codeLen]! & 0x1f;
140 if (nalType === 7 && !sps) sps = buf.subarray(i + codeLen);
141 if (nalType === 5) isKey = true;
142 i += codeLen + 1;
143 continue;
144 }
145 }
146 i++;
147 }
148 return { isKey, sps };
150​
151export type AvccChunk = {
152 readonly type: "description" | "keyframe" | "delta" | "seed";
153 readonly payload: Uint8Array;
154};
155​
156const AVCC_TAGS: Record<number, AvccChunk["type"] | undefined> = {
157 1: "description",
158 2: "keyframe",
159 3: "delta",
160 4: "seed",
161};
162​
163/** Turns a fragmented AVCC byte stream into complete envelopes. */
164export class AvccDemuxer {
165 private buffer = new Uint8Array(64 * 1024);
166 private length = 0;
167​
168 push(bytes: Uint8Array): AvccChunk[] {
169 if (this.length + bytes.length > this.buffer.length) {
170 let capacity = this.buffer.length;
171 while (capacity < this.length + bytes.length) capacity *= 2;
172 const grown = new Uint8Array(capacity);
173 grown.set(this.buffer.subarray(0, this.length));
174 this.buffer = grown;
175 }
176 this.buffer.set(bytes, this.length);
177 this.length += bytes.length;
178​
179 const chunks: AvccChunk[] = [];
180 let offset = 0;
181 while (this.length - offset >= 4) {
182 const view = new DataView(this.buffer.buffer, this.buffer.byteOffset + offset, 4);
183 const frameLength = view.getUint32(0, false);
184 if (this.length - offset - 4 < frameLength) break;
185 if (frameLength >= 1) {
186 const type = AVCC_TAGS[this.buffer[offset + 4]!];
187 if (type) {
188 chunks.push({ type, payload: this.buffer.slice(offset + 5, offset + 4 + frameLength) });
189 }
190 }
191 offset += 4 + frameLength;
192 }
193 if (offset > 0) {
194 this.buffer.copyWithin(0, offset, this.length);
195 this.length -= offset;
196 }
197 return chunks;
198 }
199​
200 reset(): void {
201 this.length = 0;
202 }
204​
205export interface DeviceStreamClient {
206 readonly start: () => void;
207 readonly stop: () => void;
208 /** Normalized 0..1 coordinates in the displayed frame. */
209 readonly sendTouch: (phase: "begin" | "move" | "end", x: number, y: number) => void;
210 readonly sendKey: (event: KeyboardEvent, phase: "down" | "up") => void;
211 readonly pressButton: (button: DeviceHardwareButton) => void;
212 readonly rotate: () => void;
214​
215const HID_USAGE_BY_CODE: Readonly<Record<string, number>> = {
216 Enter: 0x28,
217 Escape: 0x29,
218 Backspace: 0x2a,
219 Tab: 0x2b,
220 Space: 0x2c,
221 Minus: 0x2d,
222 Equal: 0x2e,
223 BracketLeft: 0x2f,
224 BracketRight: 0x30,
225 Backslash: 0x31,
226 Semicolon: 0x33,
227 Quote: 0x34,
228 Backquote: 0x35,
229 Comma: 0x36,
230 Period: 0x37,
231 Slash: 0x38,
232 Delete: 0x4c,
233 ArrowRight: 0x4f,
234 ArrowLeft: 0x50,
235 ArrowDown: 0x51,
236 ArrowUp: 0x52,
237 ControlLeft: 0xe0,
238 ShiftLeft: 0xe1,
239 AltLeft: 0xe2,
240 MetaLeft: 0xe3,
241 ControlRight: 0xe4,
242 ShiftRight: 0xe5,
243 AltRight: 0xe6,
244 MetaRight: 0xe7,
245};
246​
247function hidUsageForCode(code: string): number | null {
248 if (/^Key[A-Z]$/.test(code)) return 0x04 + (code.charCodeAt(3) - 65);
249 if (/^Digit[1-9]$/.test(code)) return 0x1e + (code.charCodeAt(5) - 49);
250 if (code === "Digit0") return 0x27;
251 return HID_USAGE_BY_CODE[code] ?? null;
253​
254const ANDROID_KEYCODE_BY_KEY: Readonly<Record<string, number>> = {
255 ArrowUp: 19,
256 ArrowDown: 20,
257 ArrowLeft: 21,
258 ArrowRight: 22,
259 Tab: 61,
260 Enter: 66,
261 Backspace: 67,
262 Delete: 112,
263 Home: 122,
264 End: 123,
265 PageUp: 92,
266 PageDown: 93,
267};
268​
269const IOS_ORIENTATIONS: ReadonlyArray<DeviceScreenSize["orientation"]> = [
270 "portrait",
271 "landscape_left",
272 "portrait_upside_down",
273 "landscape_right",
274];
275​
276export function createDeviceStreamClient(
277 target: DeviceStreamTarget,
278 canvas: HTMLCanvasElement,
279 events: DeviceStreamEvents,
280): DeviceStreamClient {
281 const { access, platform, deviceId } = target;
282 const vendor = platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
283 const device = encodeURIComponent(deviceId);
284 const httpUrl = (path: string) =>
285 withDeviceHubQuery(`${access.httpBase}${vendor}${path}`, access);
286 const wsUrl = (path: string) => withDeviceHubQuery(`${access.wsBase}${vendor}${path}`, access);
287 const useWebCodecs = isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg);
288​
289 let stopped = true;
290 let socket: WebSocket | null = null;
291 let controller: AbortController | null = null;
292 const retryTimers = new Map<"video" | "input", ReturnType<typeof setTimeout>>();
293 let primeController: AbortController | null = null;
294 let videoDecoder: VideoDecoder | null = null;
295 let timestamp = 0;
296 let awaitingKeyframe = true;
297 let screen: DeviceScreenSize | null = null;
298 let firstFrame = false;
299 let configuring = false;
300 let mjpeg = false;
301​
302 const mjpegUrl = () => httpUrl(`/helper/${device}/stream.mjpeg`);
303​
304 const fallBackToMjpeg = () => {
305 if (stopped || mjpeg) return;
306 mjpeg = true;
307 closeDecoder();
308 events.onMjpegFallback(mjpegUrl());
309 setStatus("streaming");
310 };
311​
312 const setStatus = (status: DeviceStreamStatus, detail?: string) => {
313 if (!stopped) events.onStatus(status, detail);
314 };
315​
316 const paint = (source: CanvasImageSource, width: number, height: number) => {
317 if (stopped) return;
318 if (canvas.width !== width || canvas.height !== height) {
319 canvas.width = width;
320 canvas.height = height;
321 if (platform === "android") {
322 screen = { width, height, orientation: width > height ? "landscape_left" : "portrait" };
323 events.onScreen(screen);
324 }
325 }
326 canvas.getContext("2d")?.drawImage(source, 0, 0, width, height);
327 if (!firstFrame) {
328 firstFrame = true;
329 setStatus("streaming");
330 }
331 };
332​
333 const closeDecoder = () => {
334 try {
335 videoDecoder?.close();
336 } catch {
337 // Already closed.
338 }
339 videoDecoder = null;
340 awaitingKeyframe = true;
341 };
342​
343 const makeDecoder = () =>
344 new VideoDecoder({
345 output: (frame) => {
346 try {
347 paint(frame, frame.displayWidth, frame.displayHeight);
348 } finally {
349 frame.close();
350 }
351 },
352 error: () => {
353 closeDecoder();
354 requestKeyframe();
355 },
356 });
357​
358 /**
359 * Resolves false when this browser cannot decode the stream's profile
360 * (simulators encode High 5.1, which headless and some hardware decoders
361 * reject). iOS then falls back to MJPEG; Android has no MJPEG.
362 */
363 const configureDecoder = async (config: VideoDecoderConfig): Promise<boolean> => {
364 const full: VideoDecoderConfig = { ...config, optimizeForLatency: true };
365 const support = await VideoDecoder.isConfigSupported(full).catch(() => ({ supported: false }));
366 if (stopped) return false;
367 if (!support.supported) {
368 setStatus("error", `This browser cannot decode ${config.codec}.`);
369 return false;
370 }
371 if (!videoDecoder || videoDecoder.state === "closed") videoDecoder = makeDecoder();
372 try {
373 videoDecoder.configure(full);
374 return true;
375 } catch (cause) {
376 setStatus("error", `Video decoder: ${(cause as Error).message}`);
377 return false;
378 }
379 };
380​
381 const decode = (isKey: boolean, data: Uint8Array, pts?: number | null) => {
382 if (!videoDecoder || videoDecoder.state !== "configured") return;
383 if (awaitingKeyframe) {
384 if (!isKey) return;
385 awaitingKeyframe = false;
386 }
387 if (videoDecoder.decodeQueueSize > SOFT_DECODE_QUEUE) {
388 closeDecoder();
389 requestKeyframe();
390 return;
391 }
392 try {
393 videoDecoder.decode(
394 new EncodedVideoChunk({
395 type: isKey ? "key" : "delta",
396 timestamp: pts ?? timestamp,
397 data,
398 }),
399 );
400 timestamp += FRAME_DURATION_US;
401 } catch {
402 closeDecoder();
403 requestKeyframe();
404 }
405 };
406​
407 const requestKeyframe = () => {
408 if (platform === "android" && socket?.readyState === WebSocket.OPEN) {
409 socket.send(JSON.stringify({ type: "reset-video", ack: false }));
410 }
411 };
412​
413 const scheduleRetry = (channel: "video" | "input", run: () => void) => {
414 if (stopped || retryTimers.has(channel)) return;
415 retryTimers.set(
416 channel,
417 setTimeout(() => {
418 retryTimers.delete(channel);
419 run();
420 }, RETRY_DELAY_MS),
421 );
422 };
423​
424 const handleUnauthorized = () => {
425 stop();
426 events.onUnauthorized();
427 };
428​
429 // iOS video: fetch the AVCC body and demux into the decoder.
430 const readIosVideo = async () => {
431 const demuxer = new AvccDemuxer();
432 controller = new AbortController();
433 try {
434 const response = await fetch(httpUrl(`/helper/${device}/stream.avcc`), {
435 signal: controller.signal,
436 credentials: access.credentials ? "include" : "same-origin",
437 });
438 if (response.status === 401 || response.status === 403) return handleUnauthorized();
439 if (!response.ok || !response.body) throw new Error(`stream ${response.status}`);
440 const reader = response.body.getReader();
441 for (;;) {
442 const { done, value } = await reader.read();
443 if (done || stopped) break;
444 for (const chunk of demuxer.push(value)) {
445 switch (chunk.type) {
446 case "seed":
447 void createImageBitmap(new Blob([chunk.payload as BlobPart], { type: "image/jpeg" }))
448 .then((bitmap) => {
449 paint(bitmap, bitmap.width, bitmap.height);
450 bitmap.close();
451 })
452 .catch(() => {});
453 break;
454 case "description": {
455 awaitingKeyframe = true;
456 const configured = await configureDecoder({
457 codec: avcCodecString(chunk.payload),
458 description: chunk.payload,
459 });
460 if (!configured) {
461 await reader.cancel().catch(() => {});
462 fallBackToMjpeg();
463 return;
464 }
465 break;
466 }
467 case "keyframe":
468 case "delta":
469 decode(chunk.type === "keyframe", chunk.payload);
470 break;
471 }
472 }
473 }
474 } catch (cause) {
475 if (stopped) return;
476 setStatus("connecting", (cause as Error).message);
477 }
478 if (!stopped) scheduleRetry("video", () => void readIosVideo());
479 };
480​
481 /**
482 * serve-sim's helper only accepts HID and pushes its screen config once
483 * screen capture is running, and the AVCC stream does not reliably start
484 * it. Touching the MJPEG endpoint does; one aborted request is enough.
485 */
486 const primeIosHelper = async () => {
487 const controller = new AbortController();
488 primeController = controller;
489 const timeout = setTimeout(() => controller.abort(), 2_000);
490 try {
491 const response = await fetch(httpUrl(`/helper/${device}/stream.mjpeg`), {
492 signal: controller.signal,
493 credentials: access.credentials ? "include" : "same-origin",
494 });
495 if (response.status === 401 || response.status === 403) return handleUnauthorized();
496 await response.body?.getReader().read();
497 } catch {
498 // A failed prime just means the socket may take a retry to come up.
499 } finally {
500 clearTimeout(timeout);
501 controller.abort();
502 if (primeController === controller) primeController = null;
503 }
504 };
505​
506 // iOS input socket; also carries the screen config the helper pushes.
507 const connectIosInput = async () => {
508 if (stopped) return;
509 await primeIosHelper();
510 if (stopped) return;
511 const ws = new WebSocket(wsUrl(`/helper/ws?device=${device}`));
512 ws.binaryType = "arraybuffer";
513 socket = ws;
514 ws.onopen = () => {
515 ws.send(taggedJson(IOS_MSG_HARDWARE_KEYBOARD, { enabled: false }));
516 events.onInputConnected(true);
517 };
518 ws.onmessage = (event) => {
519 if (!(event.data instanceof ArrayBuffer)) return;
520 const bytes = new Uint8Array(event.data);
521 if (bytes.length < 1 || bytes[0] !== IOS_TAG_SCREEN_CONFIG) return;
522 try {
523 const config = JSON.parse(decoder.decode(bytes.subarray(1))) as DeviceScreenSize;
524 if (config.width > 0 && config.height > 0) {
525 screen = config;
526 events.onScreen(config);
527 }
528 } catch {
529 // Ignore malformed config frames.
530 }
531 };
532 ws.onclose = (event) => {
533 if (socket !== ws) return;
534 socket = null;
535 if (stopped) return;
536 events.onInputConnected(
537 false,
538 event.reason || (event.code === 1006 ? "input socket refused" : `closed ${event.code}`),
539 );
540 // A rejected HTTP upgrade surfaces as 1006, including an expired stream ticket.
541 if (
542 event.code === 1008 ||
543 event.code === 4401 ||
544 (event.code === 1006 && access.query.wsTicket)
545 )
546 return handleUnauthorized();
547 scheduleRetry("input", () => void connectIosInput());
548 };
549 ws.onerror = () => ws.close();
550 };
551​
552 // Android: one socket for video and input.
553 const connectAndroid = () => {
554 if (stopped) return;
555 const ws = new WebSocket(wsUrl(`/ws?device=${device}&frame-meta=1`));
556 ws.binaryType = "arraybuffer";
557 socket = ws;
558 ws.onopen = () => {
559 setStatus("connecting");
560 events.onInputConnected(true);
561 };
562 ws.onmessage = (event) => {
563 if (typeof event.data === "string") {
564 // The encoder restarts at a new size when the device rotates; the
565 // next keyframe carries a fresh SPS, so the decoder is rebuilt from it.
566 if (isVideoSessionMessage(event.data)) closeDecoder();
567 return;
568 }
569 if (!(event.data instanceof ArrayBuffer)) return;
570 const packet = parseSemuPacket(event.data);
571 const needsScan =
572 packet.isKey === null ||
573 (packet.isKey && (!videoDecoder || videoDecoder.state !== "configured"));
574 const scanned = needsScan ? scanAccessUnit(packet.data) : null;
575 const isKey = packet.isKey ?? scanned?.isKey ?? false;
576 if (scanned?.sps && (!videoDecoder || videoDecoder.state !== "configured")) {
577 if (configuring) return;
578 configuring = true;
579 void configureDecoder({ codec: avcCodecString(scanned.sps) }).then((configured) => {
580 configuring = false;
581 awaitingKeyframe = true;
582 if (configured) requestKeyframe();
583 });
584 return;
585 }
586 if (!videoDecoder || videoDecoder.state !== "configured") {
587 if (!isKey) requestKeyframe();
588 return;
589 }
590 decode(isKey, packet.data, packet.timestamp);
591 };
592 ws.onclose = (event) => {
593 if (socket !== ws) return;
594 socket = null;
595 closeDecoder();
596 if (stopped) return;
597 events.onInputConnected(false, event.reason || `closed ${event.code}`);
598 if (
599 event.code === 1008 ||
600 event.code === 4401 ||
601 (event.code === 1006 && access.query.wsTicket)
602 )
603 return handleUnauthorized();
604 setStatus("connecting", event.reason || undefined);
605 scheduleRetry("input", connectAndroid);
606 };
607 ws.onerror = () => ws.close();
608 };
609​
610 const start = () => {
611 if (!stopped) return;
612 stopped = false;
613 firstFrame = false;
614 events.onStatus("connecting");
615 if (platform === "ios") {
616 void connectIosInput();
617 if (useWebCodecs) void readIosVideo();
618 else fallBackToMjpeg();
619 } else if (useWebCodecs) {
620 connectAndroid();
621 } else {
622 setStatus("error", "This browser cannot decode the Android stream (WebCodecs unavailable).");
623 }
624 };
625​
626 const stop = () => {
627 if (stopped) return;
628 stopped = true;
629 mjpeg = false;
630 for (const timer of retryTimers.values()) clearTimeout(timer);
631 retryTimers.clear();
632 primeController?.abort();
633 primeController = null;
634 controller?.abort();
635 controller = null;
636 socket?.close();
637 socket = null;
638 closeDecoder();
639 };
640​
641 const send = (payload: Uint8Array<ArrayBuffer> | string) => {
642 if (socket?.readyState === WebSocket.OPEN) socket.send(payload);
643 };
644​
645 const rawPoint = (x: number, y: number) => {
646 // serve-sim streams the raw framebuffer; rotated devices need input
647 // remapped into that raw space.
648 if (platform !== "ios" || !screen || screen.width > screen.height) return { x, y };
649 switch (screen.orientation) {
650 case "landscape_left":
651 return { x: y, y: 1 - x };
652 case "landscape_right":
653 return { x: 1 - y, y: x };
654 case "portrait_upside_down":
655 return { x: 1 - x, y: 1 - y };
656 default:
657 return { x, y };
658 }
659 };
660​
661 return {
662 start,
663 stop,
664 sendTouch: (phase, x, y) => {
665 if (platform === "ios") {
666 send(taggedJson(IOS_MSG_TOUCH, { type: phase, ...rawPoint(x, y) }));
667 return;
668 }
669 const action = phase === "begin" ? "down" : phase === "move" ? "move" : "up";
670 send(JSON.stringify({ type: "touch", action, x, y }));
671 },
672 sendKey: (event, phase) => {
673 if (platform === "ios") {
674 const usage = hidUsageForCode(event.code);
675 if (usage !== null) send(taggedJson(IOS_MSG_KEY, { type: phase, usage }));
676 return;
677 }
678 if (phase !== "down") return;
679 if (event.key === "Escape") return send(JSON.stringify({ type: "back" }));
680 const keycode = ANDROID_KEYCODE_BY_KEY[event.key];
681 if (keycode !== undefined) return send(JSON.stringify({ type: "key", keycode }));
682 if (event.key.length === 1 && !event.metaKey && !event.ctrlKey) {
683 send(JSON.stringify({ type: "text", text: event.key }));
684 }
685 },
686 pressButton: (button) => {
687 if (platform === "ios") {
688 const name =
689 button === "home"
690 ? "home"
691 : button === "appSwitcher"
692 ? "app_switcher"
693 : button === "power"
694 ? "lock"
695 : null;
696 if (name) send(taggedJson(IOS_MSG_BUTTON, { button: name }));
697 return;
698 }
699 const type = button === "appSwitcher" ? "recents" : button;
700 if (type === "home" || type === "back" || type === "recents" || type === "power") {
701 send(JSON.stringify({ type }));
702 }
703 },
704 rotate: () => {
705 if (platform !== "ios") return;
706 const current = screen?.orientation ?? "portrait";
707 const next =
708 IOS_ORIENTATIONS[(IOS_ORIENTATIONS.indexOf(current) + 1) % IOS_ORIENTATIONS.length]!;
709 send(taggedJson(IOS_MSG_ORIENTATION, { orientation: next }));
710 },
711 };