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