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

stream.ts

865 lines28.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 an `<img>` instead of the canvas
41 * and attach it with `setMjpegImage` so the client can observe real frames.
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 FIRST_FRAME_TIMEOUT_MS = 15_000;
60const MJPEG_FRAME_CHECK_MS = 250;
61const FRAME_DURATION_US = 16_667;
62const SEMU_MAGIC = 0x53454d55;
63const SEMU_HEADER_BYTES = 16;
64const SEMU_FLAG_KEY = 1;
65const SOFT_DECODE_QUEUE = 8;
66​
67// serve-sim binary WS message tags (browser -> helper).
68const IOS_MSG_TOUCH = 0x03;
69const IOS_MSG_BUTTON = 0x04;
70const IOS_MSG_KEY = 0x06;
71const IOS_MSG_ORIENTATION = 0x07;
72const IOS_MSG_HARDWARE_KEYBOARD = 0x0d;
73// helper -> browser.
74const IOS_TAG_SCREEN_CONFIG = 0x82;
75​
76const encoder = new TextEncoder();
77const decoder = new TextDecoder();
78​
79const isWebCodecsSupported = (): boolean =>
80 typeof globalThis !== "undefined" &&
81 "VideoDecoder" in globalThis &&
82 "EncodedVideoChunk" in globalThis;
83​
84function taggedJson(tag: number, payload: unknown): Uint8Array<ArrayBuffer> {
85 const json = encoder.encode(JSON.stringify(payload));
86 const out = new Uint8Array(1 + json.length);
87 out[0] = tag;
88 out.set(json, 1);
89 return out;
91​
92/** Build the WebCodecs `avc1.PPCCLL` string from an avcC record or an SPS NAL. */
93export function avcCodecString(bytes: Uint8Array): string {
94 if (bytes.length < 4) return "avc1.42E01E";
95 const hex = (byte: number) => byte.toString(16).padStart(2, "0");
96 return `avc1.${hex(bytes[1]!)}${hex(bytes[2]!)}${hex(bytes[3]!)}`;
98​
99/** Split serve-emu's SEMU-framed message into metadata and the Annex-B payload. */
100export function parseSemuPacket(raw: ArrayBuffer): {
101 readonly data: Uint8Array;
102 readonly isKey: boolean | null;
103 readonly timestamp: number | null;
104} {
105 const bytes = new Uint8Array(raw);
106 if (bytes.byteLength > SEMU_HEADER_BYTES) {
107 const view = new DataView(raw, 0, SEMU_HEADER_BYTES);
108 if (view.getUint32(0, false) === SEMU_MAGIC && view.getUint8(4) === 1) {
109 const pts = view.getBigUint64(8, false);
110 return {
111 data: bytes.subarray(SEMU_HEADER_BYTES),
112 isKey: (view.getUint8(5) & SEMU_FLAG_KEY) !== 0,
113 timestamp: pts <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(pts) : null,
114 };
115 }
116 }
117 return { data: bytes, isKey: null, timestamp: null };
119​
120const isVideoSessionMessage = (text: string) => {
121 try {
122 const message = JSON.parse(text) as { type?: unknown };
123 return message.type === "video-session";
124 } catch {
125 return false;
126 }
127};
128​
129/** Walk an Annex-B access unit for its keyframe flag and SPS bytes. */
130export function scanAccessUnit(buf: Uint8Array): { isKey: boolean; sps: Uint8Array | null } {
131 let isKey = false;
132 let sps: Uint8Array | null = null;
133 const len = buf.length;
134 let i = 0;
135 while (i + 2 < len) {
136 if (buf[i] === 0 && buf[i + 1] === 0) {
137 let codeLen = 0;
138 if (buf[i + 2] === 1) codeLen = 3;
139 else if (i + 3 < len && buf[i + 2] === 0 && buf[i + 3] === 1) codeLen = 4;
140 if (codeLen) {
141 const nalType = buf[i + codeLen]! & 0x1f;
142 if (nalType === 7 && !sps) sps = buf.subarray(i + codeLen);
143 if (nalType === 5) isKey = true;
144 i += codeLen + 1;
145 continue;
146 }
147 }
148 i++;
149 }
150 return { isKey, sps };
152​
153export type AvccChunk = {
154 readonly type: "description" | "keyframe" | "delta" | "seed";
155 readonly payload: Uint8Array;
156};
157​
158const AVCC_TAGS: Record<number, AvccChunk["type"] | undefined> = {
159 1: "description",
160 2: "keyframe",
161 3: "delta",
162 4: "seed",
163};
164​
165/** Turns a fragmented AVCC byte stream into complete envelopes. */
166export class AvccDemuxer {
167 private buffer = new Uint8Array(64 * 1024);
168 private length = 0;
169​
170 push(bytes: Uint8Array): AvccChunk[] {
171 if (this.length + bytes.length > this.buffer.length) {
172 let capacity = this.buffer.length;
173 while (capacity < this.length + bytes.length) capacity *= 2;
174 const grown = new Uint8Array(capacity);
175 grown.set(this.buffer.subarray(0, this.length));
176 this.buffer = grown;
177 }
178 this.buffer.set(bytes, this.length);
179 this.length += bytes.length;
180​
181 const chunks: AvccChunk[] = [];
182 let offset = 0;
183 while (this.length - offset >= 4) {
184 const view = new DataView(this.buffer.buffer, this.buffer.byteOffset + offset, 4);
185 const frameLength = view.getUint32(0, false);
186 if (this.length - offset - 4 < frameLength) break;
187 if (frameLength >= 1) {
188 const type = AVCC_TAGS[this.buffer[offset + 4]!];
189 if (type) {
190 chunks.push({ type, payload: this.buffer.slice(offset + 5, offset + 4 + frameLength) });
191 }
192 }
193 offset += 4 + frameLength;
194 }
195 if (offset > 0) {
196 this.buffer.copyWithin(0, offset, this.length);
197 this.length -= offset;
198 }
199 return chunks;
200 }
201​
202 reset(): void {
203 this.length = 0;
204 }
206​
207export interface DeviceStreamClient {
208 readonly start: () => void;
209 readonly stop: () => void;
210 /**
211 * Own the displayed MJPEG image's source and frame/error observation.
212 * `stop()` detaches it; attach a fresh image for each restart.
213 */
214 readonly setMjpegImage: (image: HTMLImageElement | null) => void;
215 /** Normalized 0..1 coordinates in the displayed frame. */
216 readonly sendTouch: (phase: "begin" | "move" | "end", x: number, y: number) => void;
217 readonly sendKey: (event: KeyboardEvent, phase: "down" | "up") => void;
218 readonly pressButton: (button: DeviceHardwareButton) => void;
219 readonly rotate: () => void;
221​
222const HID_USAGE_BY_CODE: Readonly<Record<string, number>> = {
223 Enter: 0x28,
224 Escape: 0x29,
225 Backspace: 0x2a,
226 Tab: 0x2b,
227 Space: 0x2c,
228 Minus: 0x2d,
229 Equal: 0x2e,
230 BracketLeft: 0x2f,
231 BracketRight: 0x30,
232 Backslash: 0x31,
233 Semicolon: 0x33,
234 Quote: 0x34,
235 Backquote: 0x35,
236 Comma: 0x36,
237 Period: 0x37,
238 Slash: 0x38,
239 Delete: 0x4c,
240 ArrowRight: 0x4f,
241 ArrowLeft: 0x50,
242 ArrowDown: 0x51,
243 ArrowUp: 0x52,
244 ControlLeft: 0xe0,
245 ShiftLeft: 0xe1,
246 AltLeft: 0xe2,
247 MetaLeft: 0xe3,
248 ControlRight: 0xe4,
249 ShiftRight: 0xe5,
250 AltRight: 0xe6,
251 MetaRight: 0xe7,
252};
253​
254function hidUsageForCode(code: string): number | null {
255 if (/^Key[A-Z]$/.test(code)) return 0x04 + (code.charCodeAt(3) - 65);
256 if (/^Digit[1-9]$/.test(code)) return 0x1e + (code.charCodeAt(5) - 49);
257 if (code === "Digit0") return 0x27;
258 return HID_USAGE_BY_CODE[code] ?? null;
260​
261const ANDROID_KEYCODE_BY_KEY: Readonly<Record<string, number>> = {
262 ArrowUp: 19,
263 ArrowDown: 20,
264 ArrowLeft: 21,
265 ArrowRight: 22,
266 Tab: 61,
267 Enter: 66,
268 Backspace: 67,
269 Delete: 112,
270 Home: 122,
271 End: 123,
272 PageUp: 92,
273 PageDown: 93,
274};
275​
276const IOS_ORIENTATIONS: ReadonlyArray<DeviceScreenSize["orientation"]> = [
277 "portrait",
278 "landscape_left",
279 "portrait_upside_down",
280 "landscape_right",
281];
282​
283export function createDeviceStreamClient(
284 target: DeviceStreamTarget,
285 canvas: HTMLCanvasElement,
286 events: DeviceStreamEvents,
287): DeviceStreamClient {
288 const { access, platform, deviceId } = target;
289 const vendor = platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
290 const device = encodeURIComponent(deviceId);
291 const httpUrl = (path: string) =>
292 withDeviceHubQuery(`${access.httpBase}${vendor}${path}`, access);
293 const wsUrl = (path: string) => withDeviceHubQuery(`${access.wsBase}${vendor}${path}`, access);
294 const useWebCodecs = isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg);
295​
296 let stopped = true;
297 let socket: WebSocket | null = null;
298 let controller: AbortController | null = null;
299 const retryTimers = new Map<"video" | "input", ReturnType<typeof setTimeout>>();
300 let primeController: AbortController | null = null;
301 let videoDecoder: VideoDecoder | null = null;
302 let timestamp = 0;
303 let awaitingKeyframe = true;
304 let screen: DeviceScreenSize | null = null;
305 let firstFrame = false;
306 let configuring = false;
307 let mjpeg = false;
308 let generation = 0;
309 let decoderEpoch = 0;
310 let frameTimer: ReturnType<typeof setTimeout> | null = null;
311 let videoReadTimer: ReturnType<typeof setTimeout> | null = null;
312 let mjpegImage: HTMLImageElement | null = null;
313 let releaseImage: (() => void) | null = null;
314​
315 const mjpegUrl = () => httpUrl(`/helper/${device}/stream.mjpeg`);
316​
317 const setStatus = (status: DeviceStreamStatus, detail?: string) => {
318 if (!stopped) events.onStatus(status, detail);
319 };
320​
321 const clearFrameTimer = () => {
322 if (frameTimer !== null) clearTimeout(frameTimer);
323 frameTimer = null;
324 };
325​
326 const fail = (detail: string) => {
327 if (stopped) return;
328 stop();
329 events.onInputConnected(false, detail);
330 events.onStatus("error", detail);
331 };
332​
333 const connecting = (detail?: string) => {
334 firstFrame = false;
335 if (frameTimer === null) {
336 frameTimer = setTimeout(
337 () => fail("No video received from the device. Reconnect to try again."),
338 FIRST_FRAME_TIMEOUT_MS,
339 );
340 }
341 setStatus("connecting", detail);
342 };
343​
344 const frameReceived = () => {
345 if (firstFrame) return;
346 firstFrame = true;
347 clearFrameTimer();
348 setStatus("streaming");
349 };
350​
351 const observeMjpegImage = () => {
352 releaseImage?.();
353 releaseImage = null;
354 const image = mjpegImage;
355 if (!image || stopped || !mjpeg) return;
356 let timer: ReturnType<typeof setTimeout> | null = null;
357 let released = false;
358 const check = () => {
359 if (released || stopped) return;
360 if (timer !== null) clearTimeout(timer);
361 timer = null;
362 if (image.naturalWidth > 0 && image.naturalHeight > 0) frameReceived();
363 else {
364 // Multipart images may not emit load until the response ends. Stop checking after the first frame.
365 timer = setTimeout(check, MJPEG_FRAME_CHECK_MS);
366 }
367 };
368 const error = () => {
369 if (!released) fail("Could not receive the device stream. Reconnect to try again.");
370 };
371 image.addEventListener("load", check);
372 image.addEventListener("error", error);
373 releaseImage = () => {
374 released = true;
375 if (timer !== null) clearTimeout(timer);
376 image.removeEventListener("load", check);
377 image.removeEventListener("error", error);
378 image.removeAttribute("src");
379 };
380 image.src = mjpegUrl();
381 check();
382 };
383​
384 const setMjpegImage = (image: HTMLImageElement | null) => {
385 if (mjpegImage === image) return;
386 releaseImage?.();
387 releaseImage = null;
388 mjpegImage = image;
389 observeMjpegImage();
390 };
391​
392 const fallBackToMjpeg = () => {
393 if (stopped || mjpeg) return;
394 mjpeg = true;
395 controller?.abort();
396 controller = null;
397 closeDecoder();
398 connecting();
399 events.onMjpegFallback(mjpegUrl());
400 if (!releaseImage) observeMjpegImage();
401 };
402​
403 const paint = (source: CanvasImageSource, width: number, height: number) => {
404 if (stopped) return;
405 if (canvas.width !== width || canvas.height !== height) {
406 canvas.width = width;
407 canvas.height = height;
408 if (platform === "android") {
409 screen = { width, height, orientation: width > height ? "landscape_left" : "portrait" };
410 events.onScreen(screen);
411 }
412 }
413 const context = canvas.getContext("2d");
414 if (!context) return fail("Could not display the device stream. Reconnect to try again.");
415 context.drawImage(source, 0, 0, width, height);
416 frameReceived();
417 };
418​
419 const closeDecoder = () => {
420 decoderEpoch++;
421 try {
422 videoDecoder?.close();
423 } catch {
424 // Already closed.
425 }
426 videoDecoder = null;
427 awaitingKeyframe = true;
428 };
429​
430 const recoverDecoder = () => {
431 if (platform === "ios") fallBackToMjpeg();
432 else {
433 closeDecoder();
434 connecting("Video decoder restarted.");
435 requestKeyframe();
436 }
437 };
438​
439 const makeDecoder = () => {
440 const decoder = new VideoDecoder({
441 output: (frame) => {
442 try {
443 if (videoDecoder === decoder) paint(frame, frame.displayWidth, frame.displayHeight);
444 } finally {
445 frame.close();
446 }
447 },
448 error: () => {
449 if (stopped || videoDecoder !== decoder) return;
450 recoverDecoder();
451 },
452 });
453 return decoder;
454 };
455​
456 /** iOS can fall back to MJPEG when the stream's H.264 profile is unsupported. */
457 const configureDecoder = async (
458 config: VideoDecoderConfig,
459 isCurrent: () => boolean,
460 ): Promise<boolean> => {
461 const epoch = decoderEpoch;
462 const full: VideoDecoderConfig = { ...config, optimizeForLatency: true };
463 const support = await VideoDecoder.isConfigSupported(full).catch(() => ({ supported: false }));
464 if (!isCurrent() || epoch !== decoderEpoch) return false;
465 if (!support.supported) {
466 if (platform === "android") fail(`This browser cannot decode ${config.codec}.`);
467 return false;
468 }
469 try {
470 if (!videoDecoder || videoDecoder.state === "closed") videoDecoder = makeDecoder();
471 videoDecoder.configure(full);
472 return true;
473 } catch (cause) {
474 if (platform === "android") fail(`Video decoder: ${(cause as Error).message}`);
475 return false;
476 }
477 };
478​
479 const decode = (isKey: boolean, data: Uint8Array, pts?: number | null) => {
480 if (!videoDecoder || videoDecoder.state !== "configured") return;
481 if (awaitingKeyframe) {
482 if (!isKey) return;
483 awaitingKeyframe = false;
484 }
485 if (videoDecoder.decodeQueueSize > SOFT_DECODE_QUEUE) {
486 recoverDecoder();
487 return;
488 }
489 try {
490 videoDecoder.decode(
491 new EncodedVideoChunk({
492 type: isKey ? "key" : "delta",
493 timestamp: pts ?? timestamp,
494 data,
495 }),
496 );
497 timestamp += FRAME_DURATION_US;
498 } catch {
499 recoverDecoder();
500 }
501 };
502​
503 const requestKeyframe = () => {
504 if (platform === "android" && socket?.readyState === WebSocket.OPEN) {
505 socket.send(JSON.stringify({ type: "reset-video", ack: false }));
506 }
507 };
508​
509 const scheduleRetry = (channel: "video" | "input", run: () => void) => {
510 if (stopped || retryTimers.has(channel)) return;
511 retryTimers.set(
512 channel,
513 setTimeout(() => {
514 retryTimers.delete(channel);
515 run();
516 }, RETRY_DELAY_MS),
517 );
518 };
519​
520 const handleUnauthorized = () => {
521 stop();
522 events.onInputConnected(false);
523 events.onUnauthorized();
524 };
525​
526 // iOS video: fetch the AVCC body and demux into the decoder.
527 const readIosVideo = async () => {
528 const demuxer = new AvccDemuxer();
529 const session = generation;
530 const videoController = new AbortController();
531 controller = videoController;
532 const isCurrent = () => !stopped && generation === session && controller === videoController;
533 let retryDetail: string | undefined;
534 try {
535 const response = await fetch(httpUrl(`/helper/${device}/stream.avcc`), {
536 signal: videoController.signal,
537 credentials: access.credentials ? "include" : "same-origin",
538 });
539 if (!isCurrent()) return;
540 if (response.status === 401 || response.status === 403) return handleUnauthorized();
541 if (!response.ok || !response.body) throw new Error(`stream ${response.status}`);
542 const reader = response.body.getReader();
543 for (;;) {
544 // An AVCC body can stay open after its helper stops producing frames.
545 const timer = setTimeout(() => {
546 if (isCurrent()) fail("Device stream stopped receiving video. Reconnect to try again.");
547 }, FIRST_FRAME_TIMEOUT_MS);
548 videoReadTimer = timer;
549 let result: ReadableStreamReadResult<Uint8Array>;
550 try {
551 result = await reader.read();
552 } finally {
553 clearTimeout(timer);
554 if (videoReadTimer === timer) videoReadTimer = null;
555 }
556 const { done, value } = result;
557 if (!isCurrent()) return;
558 if (done) break;
559 for (const chunk of demuxer.push(value)) {
560 switch (chunk.type) {
561 case "seed":
562 void createImageBitmap(new Blob([chunk.payload as BlobPart], { type: "image/jpeg" }))
563 .then((bitmap) => {
564 try {
565 if (isCurrent()) paint(bitmap, bitmap.width, bitmap.height);
566 } finally {
567 bitmap.close();
568 }
569 })
570 .catch(() => {});
571 break;
572 case "description": {
573 awaitingKeyframe = true;
574 const configured = await configureDecoder(
575 { codec: avcCodecString(chunk.payload), description: chunk.payload },
576 isCurrent,
577 );
578 if (!isCurrent()) return;
579 if (!configured) {
580 await reader.cancel().catch(() => {});
581 if (!isCurrent()) return;
582 fallBackToMjpeg();
583 return;
584 }
585 break;
586 }
587 case "keyframe":
588 case "delta":
589 decode(chunk.type === "keyframe", chunk.payload);
590 break;
591 }
592 }
593 }
594 } catch (cause) {
595 if (!isCurrent()) return;
596 retryDetail = (cause as Error).message;
597 }
598 if (isCurrent()) {
599 controller = null;
600 videoController.abort();
601 closeDecoder();
602 connecting(retryDetail);
603 scheduleRetry("video", () => void readIosVideo());
604 }
605 };
606​
607 /**
608 * serve-sim's helper only accepts HID and pushes its screen config once
609 * screen capture is running, and the AVCC stream does not reliably start
610 * it. Touching the MJPEG endpoint does; one aborted request is enough.
611 */
612 const primeIosHelper = async (session: number) => {
613 const controller = new AbortController();
614 primeController = controller;
615 const timeout = setTimeout(() => controller.abort(), 2_000);
616 try {
617 const response = await fetch(httpUrl(`/helper/${device}/stream.mjpeg`), {
618 signal: controller.signal,
619 credentials: access.credentials ? "include" : "same-origin",
620 });
621 if (stopped || generation !== session) return;
622 if (response.status === 401 || response.status === 403) return handleUnauthorized();
623 await response.body?.getReader().read();
624 } catch {
625 // A failed prime just means the socket may take a retry to come up.
626 } finally {
627 clearTimeout(timeout);
628 controller.abort();
629 if (primeController === controller) primeController = null;
630 }
631 };
632​
633 // iOS input socket; also carries the screen config the helper pushes.
634 const connectIosInput = async () => {
635 if (stopped) return;
636 const session = generation;
637 await primeIosHelper(session);
638 if (stopped || generation !== session) return;
639 const ws = new WebSocket(wsUrl(`/helper/ws?device=${device}`));
640 ws.binaryType = "arraybuffer";
641 socket = ws;
642 ws.onopen = () => {
643 if (stopped || socket !== ws) return;
644 ws.send(taggedJson(IOS_MSG_HARDWARE_KEYBOARD, { enabled: false }));
645 events.onInputConnected(true);
646 };
647 ws.onmessage = (event) => {
648 if (stopped || socket !== ws) return;
649 if (!(event.data instanceof ArrayBuffer)) return;
650 const bytes = new Uint8Array(event.data);
651 if (bytes.length < 1 || bytes[0] !== IOS_TAG_SCREEN_CONFIG) return;
652 try {
653 const config = JSON.parse(decoder.decode(bytes.subarray(1))) as DeviceScreenSize;
654 if (config.width > 0 && config.height > 0) {
655 screen = config;
656 events.onScreen(config);
657 }
658 } catch {
659 // Ignore malformed config frames.
660 }
661 };
662 ws.onclose = (event) => {
663 if (socket !== ws) return;
664 socket = null;
665 if (stopped) return;
666 events.onInputConnected(
667 false,
668 event.reason || (event.code === 1006 ? "input socket refused" : `closed ${event.code}`),
669 );
670 // A rejected HTTP upgrade surfaces as 1006, including an expired stream ticket.
671 if (
672 event.code === 1008 ||
673 event.code === 4401 ||
674 (event.code === 1006 && access.query.wsTicket)
675 )
676 return handleUnauthorized();
677 scheduleRetry("input", () => void connectIosInput());
678 };
679 ws.onerror = () => ws.close();
680 };
681​
682 // Android: one socket for video and input.
683 const connectAndroid = () => {
684 if (stopped) return;
685 const ws = new WebSocket(wsUrl(`/ws?device=${device}&frame-meta=1`));
686 ws.binaryType = "arraybuffer";
687 socket = ws;
688 ws.onopen = () => {
689 if (stopped || socket !== ws) return;
690 connecting();
691 events.onInputConnected(true);
692 };
693 ws.onmessage = (event) => {
694 if (stopped || socket !== ws) return;
695 if (typeof event.data === "string") {
696 // The encoder restarts at a new size when the device rotates; the
697 // next keyframe carries a fresh SPS, so the decoder is rebuilt from it.
698 if (isVideoSessionMessage(event.data)) {
699 closeDecoder();
700 configuring = false;
701 connecting();
702 requestKeyframe();
703 }
704 return;
705 }
706 if (!(event.data instanceof ArrayBuffer)) return;
707 const packet = parseSemuPacket(event.data);
708 const needsScan =
709 packet.isKey === null ||
710 (packet.isKey && (!videoDecoder || videoDecoder.state !== "configured"));
711 const scanned = needsScan ? scanAccessUnit(packet.data) : null;
712 const isKey = packet.isKey ?? scanned?.isKey ?? false;
713 if (scanned?.sps && (!videoDecoder || videoDecoder.state !== "configured")) {
714 if (configuring) return;
715 configuring = true;
716 const epoch = decoderEpoch;
717 const isCurrent = () => !stopped && socket === ws;
718 void configureDecoder({ codec: avcCodecString(scanned.sps) }, isCurrent).then(
719 (configured) => {
720 if (!isCurrent() || epoch !== decoderEpoch) return;
721 configuring = false;
722 awaitingKeyframe = true;
723 if (configured) requestKeyframe();
724 },
725 );
726 return;
727 }
728 if (!videoDecoder || videoDecoder.state !== "configured") {
729 if (!isKey) requestKeyframe();
730 return;
731 }
732 decode(isKey, packet.data, packet.timestamp);
733 };
734 ws.onclose = (event) => {
735 if (socket !== ws) return;
736 socket = null;
737 closeDecoder();
738 if (stopped) return;
739 events.onInputConnected(false, event.reason || `closed ${event.code}`);
740 if (
741 event.code === 1008 ||
742 event.code === 4401 ||
743 (event.code === 1006 && access.query.wsTicket)
744 )
745 return handleUnauthorized();
746 configuring = false;
747 connecting(event.reason || undefined);
748 scheduleRetry("input", connectAndroid);
749 };
750 ws.onerror = () => ws.close();
751 };
752​
753 const start = () => {
754 if (!stopped) return;
755 stopped = false;
756 generation++;
757 configuring = false;
758 connecting();
759 if (platform === "ios") {
760 void connectIosInput();
761 if (useWebCodecs) void readIosVideo();
762 else fallBackToMjpeg();
763 } else if (useWebCodecs) {
764 connectAndroid();
765 } else {
766 fail("This browser cannot decode the Android stream (WebCodecs unavailable).");
767 }
768 };
769​
770 const stop = () => {
771 if (stopped) return;
772 stopped = true;
773 generation++;
774 mjpeg = false;
775 clearFrameTimer();
776 if (videoReadTimer !== null) clearTimeout(videoReadTimer);
777 videoReadTimer = null;
778 releaseImage?.();
779 releaseImage = null;
780 mjpegImage = null;
781 for (const timer of retryTimers.values()) clearTimeout(timer);
782 retryTimers.clear();
783 primeController?.abort();
784 primeController = null;
785 controller?.abort();
786 controller = null;
787 const discarded = socket;
788 socket = null;
789 discarded?.close();
790 closeDecoder();
791 };
792​
793 const send = (payload: Uint8Array<ArrayBuffer> | string) => {
794 if (!stopped && socket?.readyState === WebSocket.OPEN) socket.send(payload);
795 };
796​
797 const rawPoint = (x: number, y: number) => {
798 // serve-sim streams the raw framebuffer; rotated devices need input
799 // remapped into that raw space.
800 if (platform !== "ios" || !screen || screen.width > screen.height) return { x, y };
801 switch (screen.orientation) {
802 case "landscape_left":
803 return { x: y, y: 1 - x };
804 case "landscape_right":
805 return { x: 1 - y, y: x };
806 case "portrait_upside_down":
807 return { x: 1 - x, y: 1 - y };
808 default:
809 return { x, y };
810 }
811 };
812​
813 return {
814 start,
815 stop,
816 setMjpegImage,
817 sendTouch: (phase, x, y) => {
818 if (platform === "ios") {
819 send(taggedJson(IOS_MSG_TOUCH, { type: phase, ...rawPoint(x, y) }));
820 return;
821 }
822 const action = phase === "begin" ? "down" : phase === "move" ? "move" : "up";
823 send(JSON.stringify({ type: "touch", action, x, y }));
824 },
825 sendKey: (event, phase) => {
826 if (platform === "ios") {
827 const usage = hidUsageForCode(event.code);
828 if (usage !== null) send(taggedJson(IOS_MSG_KEY, { type: phase, usage }));
829 return;
830 }
831 if (phase !== "down") return;
832 if (event.key === "Escape") return send(JSON.stringify({ type: "back" }));
833 const keycode = ANDROID_KEYCODE_BY_KEY[event.key];
834 if (keycode !== undefined) return send(JSON.stringify({ type: "key", keycode }));
835 if (event.key.length === 1 && !event.metaKey && !event.ctrlKey) {
836 send(JSON.stringify({ type: "text", text: event.key }));
837 }
838 },
839 pressButton: (button) => {
840 if (platform === "ios") {
841 const name =
842 button === "home"
843 ? "home"
844 : button === "appSwitcher"
845 ? "app_switcher"
846 : button === "power"
847 ? "lock"
848 : null;
849 if (name) send(taggedJson(IOS_MSG_BUTTON, { button: name }));
850 return;
851 }
852 const type = button === "appSwitcher" ? "recents" : button;
853 if (type === "home" || type === "back" || type === "recents" || type === "power") {
854 send(JSON.stringify({ type }));
855 }
856 },
857 rotate: () => {
858 if (platform !== "ios") return;
859 const current = screen?.orientation ?? "portrait";
860 const next =
861 IOS_ORIENTATIONS[(IOS_ORIENTATIONS.indexOf(current) + 1) % IOS_ORIENTATIONS.length]!;
862 send(taggedJson(IOS_MSG_ORIENTATION, { orientation: next }));
863 },
864 };