Open History to see the last commit
1// @effect-diagnostics globalFetch:off globalTimers:off - This browser and WebView transport runs without an Effect runtime.
2/* oxlint-disable unicorn/prefer-add-event-listener -- Each client owns its sockets and their handlers. */
3
4import {
5 createDuoControl,
6 type DuoCommand,
7 type DuoControlState,
8 type DuoPose,
9} from "./duoControl.ts";
10import * as Schema from "effect/Schema";
11import * as Option from "effect/Option";
12import { createCanvasFrameSink, type DeviceFrameSink } from "./frame.ts";
13import { 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;
29}
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);
60
61export interface DuoPanelSinks {
62 readonly cover: DeviceFrameSink;
63 readonly inner: DeviceFrameSink;
64 /** Invalidate captured input synchronously, before React can commit the new layout. */
65 readonly onScreen?: (screen: DeviceScreenSize) => void;
66}
67
68export interface DeviceStreamEvents {
69 readonly onDuoControl?: (state: DuoControlState) => void;
70 readonly onDuoUnavailable?: (detail?: string) => void;
71 readonly onStatus: (status: DeviceStreamStatus, detail?: string) => void;
72 readonly onScreen: (screen: DeviceScreenSize) => void;
73 readonly onUnauthorized: () => void;
74 /**
75 * H.264 cannot be decoded here (no WebCodecs, or the simulator's profile is
76 * unsupported); the owner should show an `<img>` instead of the canvas
77 * and attach it with `setMjpegImage` so the client can observe real frames.
78 */
79 readonly onMjpegFallback: (url: string) => void;
80 readonly onInputConnected: (connected: boolean, detail?: string) => void;
81}
82
83export interface DeviceStreamTarget {
84 readonly platform: DevicePlatform;
85 readonly deviceId: string;
86 readonly access: DeviceHubAccess;
87 /** Native iOS WebViews can use MJPEG without cross-origin fetch or secure-context support. */
88 readonly preferMjpeg?: boolean;
89 readonly panelId?: 1 | 3;
90 readonly videoOnly?: boolean;
91}
92
93export type DeviceHardwareButton = "home" | "back" | "recents" | "power" | "appSwitcher";
94
95const RETRY_DELAY_MS = 1_000;
96const FIRST_FRAME_TIMEOUT_MS = 15_000;
97const MJPEG_FRAME_CHECK_MS = 250;
98const FRAME_DURATION_US = 16_667;
99const SEMU_MAGIC = 0x53454d55;
100const SEMU_HEADER_BYTES = 16;
101const SEMU_FLAG_KEY = 1;
102const SOFT_DECODE_QUEUE = 8;
103// expo-device-hub 0.15.3 serve-emu input.js MAX_TEXT_BYTES limits packets to 300 UTF-8 bytes.
104const ANDROID_MAX_TEXT_BYTES = 300;
105// The pinned hub queue depth is 128; the client does not read queue rejections.
106const ANDROID_MAX_TEXT_CHUNKS = 64;
107
108const IOS_MSG_TOUCH = 0x03;
109const IOS_MSG_BUTTON = 0x04;
110const IOS_MSG_KEY = 0x06;
111const IOS_MSG_ORIENTATION = 0x07;
112const IOS_TAG_SCREEN_CONFIG = 0x82;
113const IOS_TAG_INPUT_ADMITTED = 0x83;
114
115const encoder = new TextEncoder();
116const decoder = new TextDecoder();
117
118const isWebCodecsSupported = (): boolean =>
119 typeof globalThis !== "undefined" &&
120 "VideoDecoder" in globalThis &&
121 "EncodedVideoChunk" in globalThis;
122
123function utf8ByteLength(codePoint: number): number {
124 if (codePoint <= 0x7f) return 1;
125 if (codePoint <= 0x7ff) return 2;
126 if (codePoint <= 0xffff) return 3;
127 return 4;
128}
129
130function taggedJson(tag: number, payload: unknown): Uint8Array<ArrayBuffer> {
131 const json = encoder.encode(JSON.stringify(payload));
132 const out = new Uint8Array(1 + json.length);
133 out[0] = tag;
134 out.set(json, 1);
135 return out;
136}
137
138export function avcCodecString(bytes: Uint8Array): string {
139 if (bytes.length < 4) return "avc1.42E01E";
140 const hex = (byte: number) => byte.toString(16).padStart(2, "0");
141 return `avc1.${hex(bytes[1]!)}${hex(bytes[2]!)}${hex(bytes[3]!)}`;
142}
143
144export function parseSemuPacket(raw: ArrayBuffer): {
145 readonly data: Uint8Array;
146 readonly isKey: boolean | null;
147 readonly timestamp: number | null;
148} {
149 const bytes = new Uint8Array(raw);
150 if (bytes.byteLength > SEMU_HEADER_BYTES) {
151 const view = new DataView(raw, 0, SEMU_HEADER_BYTES);
152 if (view.getUint32(0, false) === SEMU_MAGIC && view.getUint8(4) === 1) {
153 const pts = view.getBigUint64(8, false);
154 return {
155 data: bytes.subarray(SEMU_HEADER_BYTES),
156 isKey: (view.getUint8(5) & SEMU_FLAG_KEY) !== 0,
157 timestamp: pts <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(pts) : null,
158 };
159 }
160 }
161 return { data: bytes, isKey: null, timestamp: null };
162}
163
164const isVideoSessionMessage = (text: string) => {
165 try {
166 const message = JSON.parse(text) as { type?: unknown };
167 return message.type === "video-session";
168 } catch {
169 return false;
170 }
171};
172
173export function scanAccessUnit(buf: Uint8Array): { isKey: boolean; sps: Uint8Array | null } {
174 let isKey = false;
175 let sps: Uint8Array | null = null;
176 const len = buf.length;
177 let i = 0;
178 while (i + 2 < len) {
179 if (buf[i] === 0 && buf[i + 1] === 0) {
180 let codeLen = 0;
181 if (buf[i + 2] === 1) codeLen = 3;
182 else if (i + 3 < len && buf[i + 2] === 0 && buf[i + 3] === 1) codeLen = 4;
183 if (codeLen) {
184 const nalType = buf[i + codeLen]! & 0x1f;
185 if (nalType === 7 && !sps) sps = buf.subarray(i + codeLen);
186 if (nalType === 5) isKey = true;
187 i += codeLen + 1;
188 continue;
189 }
190 }
191 i++;
192 }
193 return { isKey, sps };
194}
195
196export type AvccChunk = {
197 readonly type: "description" | "keyframe" | "delta" | "seed";
198 readonly payload: Uint8Array;
199};
200
201const AVCC_TAGS: Record<number, AvccChunk["type"] | undefined> = {
202 1: "description",
203 2: "keyframe",
204 3: "delta",
205 4: "seed",
206};
207
208export class AvccDemuxer {
209 private buffer = new Uint8Array(64 * 1024);
210 private length = 0;
211
212 push(bytes: Uint8Array): AvccChunk[] {
213 if (this.length + bytes.length > this.buffer.length) {
214 let capacity = this.buffer.length;
215 while (capacity < this.length + bytes.length) capacity *= 2;
216 const grown = new Uint8Array(capacity);
217 grown.set(this.buffer.subarray(0, this.length));
218 this.buffer = grown;
219 }
220 this.buffer.set(bytes, this.length);
221 this.length += bytes.length;
222
223 const chunks: AvccChunk[] = [];
224 let offset = 0;
225 while (this.length - offset >= 4) {
226 const view = new DataView(this.buffer.buffer, this.buffer.byteOffset + offset, 4);
227 const frameLength = view.getUint32(0, false);
228 if (this.length - offset - 4 < frameLength) break;
229 if (frameLength >= 1) {
230 const type = AVCC_TAGS[this.buffer[offset + 4]!];
231 if (type) {
232 chunks.push({ type, payload: this.buffer.slice(offset + 5, offset + 4 + frameLength) });
233 }
234 }
235 offset += 4 + frameLength;
236 }
237 if (offset > 0) {
238 this.buffer.copyWithin(0, offset, this.length);
239 this.length -= offset;
240 }
241 return chunks;
242 }
243
244 reset(): void {
245 this.length = 0;
246 }
247}
248
249export interface DeviceStreamClient {
250 readonly start: () => void;
251 readonly stop: () => void;
252 /**
253 * `stop()` detaches it; attach a fresh image for each restart.
254 */
255 readonly setMjpegImage: (image: HTMLImageElement | null) => void;
256 /** Normalized 0..1 coordinates in the displayed frame. */
257 readonly sendTouch: (phase: "begin" | "move" | "end", x: number, y: number) => void;
258 readonly sendKey: (event: KeyboardEvent, phase: "down" | "up") => void;
259 /** Android only: iOS input is HID key codes, which cannot carry arbitrary text. */
260 readonly sendText: (text: string) => void;
261 readonly pressButton: (button: DeviceHardwareButton) => void;
262 readonly rotate: () => void;
263 readonly setOrientation: (orientation: DeviceScreenSize["orientation"]) => void;
264 readonly controlDuo: (command: DuoCommand) => void;
265 readonly setDuoPanels: (panels: DuoPanelSinks | null) => void;
266 readonly sendRawTouch: (phase: "begin" | "move" | "end", x: number, y: number) => void;
267}
268
269const HID_USAGE_BY_CODE: Readonly<Record<string, number>> = {
270 Enter: 0x28,
271 Escape: 0x29,
272 Backspace: 0x2a,
273 Tab: 0x2b,
274 Space: 0x2c,
275 Minus: 0x2d,
276 Equal: 0x2e,
277 BracketLeft: 0x2f,
278 BracketRight: 0x30,
279 Backslash: 0x31,
280 Semicolon: 0x33,
281 Quote: 0x34,
282 Backquote: 0x35,
283 Comma: 0x36,
284 Period: 0x37,
285 Slash: 0x38,
286 Delete: 0x4c,
287 ArrowRight: 0x4f,
288 ArrowLeft: 0x50,
289 ArrowDown: 0x51,
290 ArrowUp: 0x52,
291 ControlLeft: 0xe0,
292 ShiftLeft: 0xe1,
293 AltLeft: 0xe2,
294 MetaLeft: 0xe3,
295 ControlRight: 0xe4,
296 ShiftRight: 0xe5,
297 AltRight: 0xe6,
298 MetaRight: 0xe7,
299};
300
301function hidUsageForCode(code: string): number | null {
302 if (/^Key[A-Z]$/.test(code)) return 0x04 + (code.charCodeAt(3) - 65);
303 if (/^Digit[1-9]$/.test(code)) return 0x1e + (code.charCodeAt(5) - 49);
304 if (code === "Digit0") return 0x27;
305 return HID_USAGE_BY_CODE[code] ?? null;
306}
307
308const ANDROID_KEYCODE_BY_KEY: Readonly<Record<string, number>> = {
309 ArrowUp: 19,
310 ArrowDown: 20,
311 ArrowLeft: 21,
312 ArrowRight: 22,
313 Tab: 61,
314 Enter: 66,
315 Backspace: 67,
316 Delete: 112,
317 Home: 122,
318 End: 123,
319 PageUp: 92,
320 PageDown: 93,
321};
322
323const IOS_ORIENTATIONS: ReadonlyArray<DeviceScreenSize["orientation"]> = [
324 "portrait",
325 "landscape_left",
326 "portrait_upside_down",
327 "landscape_right",
328];
329
330export function createDeviceStreamClient(
331 target: DeviceStreamTarget,
332 output: HTMLCanvasElement | DeviceFrameSink,
333 events: DeviceStreamEvents,
334): DeviceStreamClient {
335 const { access, platform, deviceId } = target;
336 const sink = "present" in output ? output : createCanvasFrameSink(output);
337 const vendor = platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
338 const device = encodeURIComponent(deviceId);
339 const httpUrl = (path: string) =>
340 withDeviceHubQuery(`${access.httpBase}${vendor}${path}`, access);
341 const wsUrl = (path: string) => withDeviceHubQuery(`${access.wsBase}${vendor}${path}`, access);
342 const useWebCodecs = isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg);
343
344 let stopped = true;
345 let socket: WebSocket | null = null;
346 let controller: AbortController | null = null;
347 const retryTimers = new Map<"video" | "input", ReturnType<typeof setTimeout>>();
348 let primeController: AbortController | null = null;
349 let videoDecoder: VideoDecoder | null = null;
350 let decodedVideoGeneration: number | null = null;
351 let iosInputAdmitted = false;
352 let iosInputUnavailable = false;
353 let timestamp = 0;
354 let awaitingKeyframe = true;
355 let screen: DeviceScreenSize | null = null;
356 let firstFrame = false;
357 let configuring = false;
358 let mjpeg = false;
359 let generation = 0;
360 let decoderEpoch = 0;
361 let frameTimer: ReturnType<typeof setTimeout> | null = null;
362 let videoReadTimer: ReturnType<typeof setTimeout> | null = null;
363 let mjpegImage: HTMLImageElement | null = null;
364 let releaseImage: (() => void) | null = null;
365 let videoGeneration = 0;
366 let panelClients: DeviceStreamClient[] = [];
367 let panelSinks: DuoPanelSinks | null = null;
368 let rotationCursor: DeviceScreenSize["orientation"] | null = null;
369 let pendingOrientation: { requestId: number } | null = null;
370 const duoControl = createDuoControl({
371 send(request) {
372 if (
373 !iosInputAdmitted ||
374 iosInputUnavailable ||
375 socket?.readyState !== WebSocket.OPEN ||
376 !screen?.supportsHingeAngle
377 )
378 return false;
379 if (request.command.control === "physical" && !screen.supportsPhysicalOrientation)
380 return false;
381 try {
382 pendingOrientation = null;
383 if (request.command.control === "orientation") {
384 const value = request.command.value;
385 pendingOrientation = { requestId: request.requestId };
386 rotationCursor = value;
387 // Upstream serializes orientation with hinge commands, then broadcasts config.
388 // An orientation-locked app can keep its framebuffer orientation after the sensor rotates.
389 socket.send(taggedJson(IOS_MSG_ORIENTATION, { orientation: value }));
390 } else socket.send(taggedJson(0x10, request));
391 return true;
392 } catch {
393 return false;
394 }
395 },
396 onChange(state) {
397 if (!state.pending) pendingOrientation = null;
398 events.onDuoControl?.(state);
399 },
400 });
401 const videoPath = `/helper/${device}${target.panelId ? `/panel/${target.panelId}` : ""}/stream.avcc`;
402
403 const mjpegUrl = () => httpUrl(`/helper/${device}/stream.mjpeg`);
404
405 const setStatus = (status: DeviceStreamStatus, detail?: string) => {
406 if (!stopped) events.onStatus(status, detail);
407 };
408
409 const clearFrameTimer = () => {
410 if (frameTimer !== null) clearTimeout(frameTimer);
411 frameTimer = null;
412 };
413
414 const fail = (detail: string) => {
415 if (stopped) return;
416 stop();
417 events.onInputConnected(false, detail);
418 events.onStatus("error", detail);
419 };
420
421 const connecting = (detail?: string) => {
422 firstFrame = false;
423 if (frameTimer === null) {
424 frameTimer = setTimeout(
425 () => fail("No video received from the device. Reconnect to try again."),
426 FIRST_FRAME_TIMEOUT_MS,
427 );
428 }
429 setStatus("connecting", detail);
430 };
431
432 const frameReceived = () => {
433 if (firstFrame) return;
434 firstFrame = true;
435 clearFrameTimer();
436 setStatus("streaming");
437 };
438
439 const observeMjpegImage = () => {
440 releaseImage?.();
441 releaseImage = null;
442 const image = mjpegImage;
443 if (!image || stopped || !mjpeg) return;
444 let timer: ReturnType<typeof setTimeout> | null = null;
445 let released = false;
446 const check = () => {
447 if (released || stopped) return;
448 if (timer !== null) clearTimeout(timer);
449 timer = null;
450 if (image.naturalWidth > 0 && image.naturalHeight > 0) frameReceived();
451 else {
452 // Multipart images may not emit load until the response ends.
453 timer = setTimeout(check, MJPEG_FRAME_CHECK_MS);
454 }
455 };
456 const error = () => {
457 if (!released) fail("Could not receive the device stream. Reconnect to try again.");
458 };
459 image.addEventListener("load", check);
460 image.addEventListener("error", error);
461 releaseImage = () => {
462 released = true;
463 if (timer !== null) clearTimeout(timer);
464 image.removeEventListener("load", check);
465 image.removeEventListener("error", error);
466 image.removeAttribute("src");
467 };
468 image.src = mjpegUrl();
469 check();
470 };
471
472 const setMjpegImage = (image: HTMLImageElement | null) => {
473 if (mjpegImage === image) return;
474 releaseImage?.();
475 releaseImage = null;
476 mjpegImage = image;
477 observeMjpegImage();
478 };
479
480 const fallBackToMjpeg = () => {
481 if (stopped || mjpeg) return;
482 mjpeg = true;
483 controller?.abort();
484 controller = null;
485 closeDecoder();
486 connecting();
487 events.onMjpegFallback(mjpegUrl());
488 if (!releaseImage) observeMjpegImage();
489 };
490
491 const paint = (source: CanvasImageSource, width: number, height: number) => {
492 if (stopped) return;
493 if (platform === "android" && (screen?.width !== width || screen.height !== height)) {
494 screen = { width, height, orientation: width > height ? "landscape_left" : "portrait" };
495 events.onScreen(screen);
496 }
497 if (!sink.present(source, width, height)) {
498 fail("Could not display the device stream. Reconnect to try again.");
499 return;
500 }
501 frameReceived();
502 };
503
504 const closeDecoder = () => {
505 decoderEpoch++;
506 try {
507 videoDecoder?.close();
508 } catch {}
509 videoDecoder = null;
510 awaitingKeyframe = true;
511 };
512
513 const recoverDecoder = () => {
514 if (platform === "ios") fallBackToMjpeg();
515 else {
516 closeDecoder();
517 connecting("Video decoder restarted.");
518 requestKeyframe();
519 }
520 };
521
522 const makeDecoder = () => {
523 const feedGeneration = videoGeneration;
524 const decoder = new VideoDecoder({
525 output: (frame) => {
526 try {
527 if (
528 videoDecoder === decoder &&
529 (platform !== "ios" || feedGeneration === videoGeneration)
530 ) {
531 decodedVideoGeneration = feedGeneration;
532 paint(frame, frame.displayWidth, frame.displayHeight);
533 }
534 } finally {
535 frame.close();
536 }
537 },
538 error: () => {
539 if (
540 stopped ||
541 videoDecoder !== decoder ||
542 (platform === "ios" && feedGeneration !== videoGeneration)
543 )
544 return;
545 recoverDecoder();
546 },
547 });
548 return decoder;
549 };
550
551 const configureDecoder = async (
552 config: VideoDecoderConfig,
553 isCurrent = () => !stopped,
554 ): Promise<boolean> => {
555 const epoch = decoderEpoch;
556 const full: VideoDecoderConfig = { ...config, optimizeForLatency: true };
557 const support = await VideoDecoder.isConfigSupported(full).catch(() => ({ supported: false }));
558 if (!isCurrent() || epoch !== decoderEpoch) return false;
559 if (!support.supported) {
560 if (platform === "android") fail(`This browser cannot decode ${config.codec}.`);
561 return false;
562 }
563 try {
564 if (!videoDecoder || videoDecoder.state === "closed") videoDecoder = makeDecoder();
565 videoDecoder.configure(full);
566 return true;
567 } catch (cause) {
568 if (platform === "android") fail(`Video decoder: ${(cause as Error).message}`);
569 return false;
570 }
571 };
572
573 const decode = (isKey: boolean, data: Uint8Array, pts?: number | null) => {
574 if (!videoDecoder || videoDecoder.state !== "configured") return;
575 if (awaitingKeyframe) {
576 if (!isKey) return;
577 awaitingKeyframe = false;
578 }
579 if (videoDecoder.decodeQueueSize > SOFT_DECODE_QUEUE) {
580 if (platform !== "ios") {
581 recoverDecoder();
582 return;
583 }
584 // Native IDRs are spaced by frame count, so an idle simulator may take
585 // minutes to produce one. A new AVCC subscription forces a fresh IDR.
586 controller?.abort();
587 closeDecoder();
588 return;
589 }
590 try {
591 videoDecoder.decode(
592 new EncodedVideoChunk({
593 type: isKey ? "key" : "delta",
594 timestamp: pts ?? timestamp,
595 data,
596 }),
597 );
598 timestamp += FRAME_DURATION_US;
599 } catch {
600 recoverDecoder();
601 }
602 };
603
604 const requestKeyframe = () => {
605 if (platform === "android" && socket?.readyState === WebSocket.OPEN) {
606 socket.send(JSON.stringify({ type: "reset-video", ack: false }));
607 }
608 };
609
610 const scheduleRetry = (channel: "video" | "input", run: () => void) => {
611 if (stopped || retryTimers.has(channel)) return;
612 retryTimers.set(
613 channel,
614 setTimeout(() => {
615 retryTimers.delete(channel);
616 run();
617 }, RETRY_DELAY_MS),
618 );
619 };
620
621 const handleUnauthorized = () => {
622 stop();
623 events.onInputConnected(false);
624 events.onUnauthorized();
625 };
626
627 const readIosVideo = async () => {
628 const lifecycle = generation;
629 const feedGeneration = ++videoGeneration;
630 const demuxer = new AvccDemuxer();
631 const videoController = new AbortController();
632 controller = videoController;
633 const isCurrent = () =>
634 !stopped &&
635 generation === lifecycle &&
636 videoGeneration === feedGeneration &&
637 controller === videoController;
638 let retryDetail: string | undefined;
639 try {
640 const response = await fetch(httpUrl(videoPath), {
641 signal: videoController.signal,
642 credentials: access.credentials ? "include" : "same-origin",
643 });
644 if (!isCurrent()) {
645 await response.body?.cancel();
646 return;
647 }
648 if (response.status === 401 || response.status === 403) return handleUnauthorized();
649 if (target.panelId && [400, 404, 405, 410].includes(response.status)) {
650 await response.body?.cancel();
651 setStatus("error", "This Device Hub does not provide fixed Duo display feeds.");
652 return;
653 }
654 if (!response.ok || !response.body) throw new Error(`stream ${response.status}`);
655 const reader = response.body.getReader();
656 for (;;) {
657 // An AVCC body can stay open after its helper stops producing frames.
658 const timer = setTimeout(() => {
659 if (!isCurrent()) return;
660 retryDetail = "Device stream stopped receiving video. Reconnecting…";
661 videoController.abort();
662 }, FIRST_FRAME_TIMEOUT_MS);
663 videoReadTimer = timer;
664 let result: ReadableStreamReadResult<Uint8Array>;
665 try {
666 result = await reader.read();
667 } finally {
668 clearTimeout(timer);
669 if (videoReadTimer === timer) videoReadTimer = null;
670 }
671 const { done, value } = result;
672 if (!isCurrent()) return;
673 if (done) break;
674 for (const chunk of demuxer.push(value)) {
675 if (videoController.signal.aborted) break;
676 switch (chunk.type) {
677 case "seed":
678 void createImageBitmap(new Blob([chunk.payload as BlobPart], { type: "image/jpeg" }))
679 .then((bitmap) => {
680 try {
681 if (isCurrent() && decodedVideoGeneration !== feedGeneration)
682 paint(bitmap, bitmap.width, bitmap.height);
683 } finally {
684 bitmap.close();
685 }
686 })
687 .catch(() => {});
688 break;
689 case "description": {
690 awaitingKeyframe = true;
691 const configured = await configureDecoder(
692 { codec: avcCodecString(chunk.payload), description: chunk.payload },
693 isCurrent,
694 );
695 if (!isCurrent()) return;
696 if (!configured) {
697 await reader.cancel().catch(() => {});
698 if (!isCurrent()) return;
699 if (target.videoOnly)
700 setStatus(
701 "error",
702 `This browser cannot decode the Duo panel's ${avcCodecString(chunk.payload)} stream.`,
703 );
704 else fallBackToMjpeg();
705 return;
706 }
707 break;
708 }
709 case "keyframe":
710 case "delta":
711 decode(chunk.type === "keyframe", chunk.payload);
712 break;
713 }
714 }
715 }
716 } catch (cause) {
717 if (!isCurrent()) return;
718 retryDetail ??= videoController.signal.aborted
719 ? "Video decoder fell behind. Reconnecting…"
720 : (cause as Error).message;
721 }
722 if (isCurrent()) {
723 controller = null;
724 videoController.abort();
725 closeDecoder();
726 connecting(retryDetail);
727 scheduleRetry("video", () => void readIosVideo());
728 }
729 };
730
731 /**
732 * serve-sim's helper only accepts HID and pushes its screen config once
733 * screen capture is running, and the AVCC stream does not reliably start
734 * it. Touching the MJPEG endpoint does; one aborted request is enough.
735 */
736 const primeIosHelper = async (session: number) => {
737 const controller = new AbortController();
738 primeController = controller;
739 const timeout = setTimeout(() => controller.abort(), 2_000);
740 try {
741 const response = await fetch(httpUrl(`/helper/${device}/stream.mjpeg`), {
742 signal: controller.signal,
743 credentials: access.credentials ? "include" : "same-origin",
744 });
745 if (stopped || generation !== session) return;
746 if (response.status === 401 || response.status === 403) return handleUnauthorized();
747 await response.body?.getReader().read();
748 } catch {
749 } finally {
750 clearTimeout(timeout);
751 controller.abort();
752 if (primeController === controller) primeController = null;
753 }
754 };
755
756 const startDuoVideo = (panels: DuoPanelSinks) => {
757 for (const panel of panelClients) panel.stop();
758 // Physical handoff elects a native surface. Fixed-panel encoders can keep
759 // an inactive shutdown frame after election, so this build uses one active
760 // feed instead of decoding a third stream alongside the two fixed feeds.
761 const ids = screen?.supportsPhysicalOrientation ? ([null] as const) : ([1, 3] as const);
762 panelClients = ids.map((id) => {
763 const output = id === 1 ? panels.cover : panels.inner;
764 return createDeviceStreamClient(
765 { ...target, ...(id === null ? {} : { panelId: id }), videoOnly: true },
766 {
767 present(source, width, height) {
768 if (id === null) {
769 return sink.present(source, width, height);
770 }
771 // An inactive native LCD can emit its shutdown black frame. Retain its last useful image.
772 if (screen?.screenId !== id) return true;
773 const retained = output.present(source, width, height);
774 const primary = sink.present(source, width, height);
775 return retained && primary;
776 },
777 },
778 {
779 onStatus: (status, detail) => {
780 if (status === "error") events.onDuoUnavailable?.(detail);
781 },
782 onScreen: () => {},
783 onInputConnected: () => {},
784 onMjpegFallback: () => {},
785 onUnauthorized: handleUnauthorized,
786 },
787 );
788 });
789 for (const panel of panelClients) panel.start();
790 };
791
792 const connectIosInput = async () => {
793 if (stopped) return;
794 const session = generation;
795 await primeIosHelper(session);
796 if (stopped || generation !== session) return;
797 const ws = new WebSocket(wsUrl(`/helper/ws?device=${device}`));
798 ws.binaryType = "arraybuffer";
799 socket = ws;
800 iosInputAdmitted = false;
801 iosInputUnavailable = false;
802 ws.onmessage = (event) => {
803 if (stopped || socket !== ws) return;
804 if (!(event.data instanceof ArrayBuffer)) return;
805 const bytes = new Uint8Array(event.data);
806 if (socket !== ws || stopped || bytes.length < 1) return;
807 if (bytes[0] === IOS_TAG_INPUT_ADMITTED) {
808 iosInputAdmitted = true;
809 events.onInputConnected(!iosInputUnavailable);
810 return;
811 }
812 try {
813 const payload: unknown = JSON.parse(decoder.decode(bytes.subarray(1)));
814 if (bytes[0] === 0x90) {
815 const reply = decodeControlReply(payload);
816 if (Option.isSome(reply)) duoControl.receive(reply.value);
817 } else if (bytes[0] === IOS_TAG_SCREEN_CONFIG) {
818 const config = decodeScreenConfig(payload);
819 if (Option.isSome(config)) {
820 iosInputUnavailable = config.value.inputUnavailable === true;
821 events.onInputConnected(
822 iosInputAdmitted && !iosInputUnavailable,
823 iosInputUnavailable ? "Simulator input is unavailable" : undefined,
824 );
825 const previous = screen;
826 screen = config.value;
827 if (screen.hingePose && screen.hingePose !== previous?.hingePose)
828 rotationCursor = screen.hingePose === "laptop" ? "landscape_left" : "portrait";
829 else if (screen.orientation !== previous?.orientation)
830 rotationCursor = screen.orientation;
831 panelSinks?.onScreen?.(screen);
832 events.onScreen(screen);
833 // A surface election can leave an existing decoder on the former
834 // encoder description. Reopen only video to acquire the elected
835 // surface's seed and codec configuration; HID and the viewer stay.
836 if (
837 panelSinks &&
838 screen.supportsPhysicalOrientation &&
839 previous &&
840 screen.screenId !== previous.screenId
841 )
842 startDuoVideo(panelSinks);
843 if (pendingOrientation) {
844 const receipt = pendingOrientation;
845 pendingOrientation = null;
846 duoControl.receive({
847 requestId: receipt.requestId,
848 ok: true,
849 });
850 }
851 }
852 }
853 } catch {}
854 };
855 ws.onclose = (event) => {
856 if (socket !== ws) return;
857 socket = null;
858 iosInputAdmitted = false;
859 duoControl.clear();
860 rotationCursor = null;
861 if (stopped) return;
862 events.onInputConnected(
863 false,
864 event.reason || (event.code === 1006 ? "input socket refused" : `closed ${event.code}`),
865 );
866 // A rejected HTTP upgrade surfaces as 1006, including an expired stream ticket.
867 if (
868 event.code === 1008 ||
869 event.code === 4401 ||
870 (event.code === 1006 && access.query.wsTicket)
871 )
872 return handleUnauthorized();
873 scheduleRetry("input", () => void connectIosInput());
874 };
875 ws.onerror = () => ws.close();
876 };
877
878 const connectAndroid = () => {
879 if (stopped) return;
880 const ws = new WebSocket(wsUrl(`/ws?device=${device}&frame-meta=1`));
881 ws.binaryType = "arraybuffer";
882 socket = ws;
883 ws.onopen = () => {
884 if (stopped || socket !== ws) return;
885 connecting();
886 events.onInputConnected(true);
887 };
888 ws.onmessage = (event) => {
889 if (stopped || socket !== ws) return;
890 if (typeof event.data === "string") {
891 // The encoder restarts at a new size when the device rotates; the
892 // next keyframe carries a fresh SPS, so the decoder is rebuilt from it.
893 if (isVideoSessionMessage(event.data)) {
894 closeDecoder();
895 configuring = false;
896 connecting();
897 requestKeyframe();
898 }
899 return;
900 }
901 if (!(event.data instanceof ArrayBuffer)) return;
902 const packet = parseSemuPacket(event.data);
903 const needsScan =
904 packet.isKey === null ||
905 (packet.isKey && (!videoDecoder || videoDecoder.state !== "configured"));
906 const scanned = needsScan ? scanAccessUnit(packet.data) : null;
907 const isKey = packet.isKey ?? scanned?.isKey ?? false;
908 if (scanned?.sps && (!videoDecoder || videoDecoder.state !== "configured")) {
909 if (configuring) return;
910 configuring = true;
911 const epoch = decoderEpoch;
912 const isCurrent = () => !stopped && socket === ws;
913 void configureDecoder({ codec: avcCodecString(scanned.sps) }, isCurrent).then(
914 (configured) => {
915 if (!isCurrent() || epoch !== decoderEpoch) return;
916 configuring = false;
917 awaitingKeyframe = true;
918 if (configured) requestKeyframe();
919 },
920 );
921 return;
922 }
923 if (!videoDecoder || videoDecoder.state !== "configured") {
924 if (!isKey) requestKeyframe();
925 return;
926 }
927 decode(isKey, packet.data, packet.timestamp);
928 };
929 ws.onclose = (event) => {
930 if (socket !== ws) return;
931 socket = null;
932 closeDecoder();
933 if (stopped) return;
934 events.onInputConnected(false, event.reason || `closed ${event.code}`);
935 if (
936 event.code === 1008 ||
937 event.code === 4401 ||
938 (event.code === 1006 && access.query.wsTicket)
939 )
940 return handleUnauthorized();
941 configuring = false;
942 connecting(event.reason || undefined);
943 scheduleRetry("input", connectAndroid);
944 };
945 ws.onerror = () => ws.close();
946 };
947
948 const start = () => {
949 if (!stopped) return;
950 stopped = false;
951 generation++;
952 configuring = false;
953 iosInputAdmitted = false;
954 iosInputUnavailable = false;
955 connecting();
956 if (platform === "ios") {
957 if (!target.videoOnly) void connectIosInput();
958 if (useWebCodecs) void readIosVideo();
959 else fallBackToMjpeg();
960 } else if (useWebCodecs) {
961 connectAndroid();
962 } else {
963 fail("This browser cannot decode the Android stream (WebCodecs unavailable).");
964 }
965 };
966
967 const stop = () => {
968 if (stopped) return;
969 stopped = true;
970 generation++;
971 videoGeneration++;
972 duoControl.clear();
973 rotationCursor = null;
974 for (const panel of panelClients) panel.stop();
975 panelClients = [];
976 panelSinks = null;
977 mjpeg = false;
978 clearFrameTimer();
979 if (videoReadTimer !== null) clearTimeout(videoReadTimer);
980 videoReadTimer = null;
981 releaseImage?.();
982 releaseImage = null;
983 mjpegImage = null;
984 for (const timer of retryTimers.values()) clearTimeout(timer);
985 retryTimers.clear();
986 primeController?.abort();
987 primeController = null;
988 controller?.abort();
989 controller = null;
990 const discarded = socket;
991 socket = null;
992 discarded?.close();
993 closeDecoder();
994 };
995
996 const send = (payload: Uint8Array<ArrayBuffer> | string) => {
997 if (
998 !stopped &&
999 (platform !== "ios" || (iosInputAdmitted && !iosInputUnavailable)) &&
1000 socket?.readyState === WebSocket.OPEN
1001 )
1002 socket.send(payload);
1003 };
1004
1005 const rawPoint = (x: number, y: number) => {
1006 // serve-sim streams the raw framebuffer; rotated devices need input
1007 // remapped into that raw space.
1008 if (platform !== "ios" || !screen || screen.width > screen.height) return { x, y };
1009 switch (screen.orientation) {
1010 case "landscape_left":
1011 return { x: y, y: 1 - x };
1012 case "landscape_right":
1013 return { x: 1 - y, y: x };
1014 case "portrait_upside_down":
1015 return { x: 1 - x, y: 1 - y };
1016 default:
1017 return { x, y };
1018 }
1019 };
1020
1021 return {
1022 start,
1023 stop,
1024 setMjpegImage,
1025 controlDuo: duoControl.enqueue,
1026 sendRawTouch: (phase, x, y) => {
1027 if (platform === "ios") send(taggedJson(IOS_MSG_TOUCH, { type: phase, x, y }));
1028 },
1029 setDuoPanels(panels) {
1030 if (platform !== "ios" || target.videoOnly || stopped || panelSinks === panels) return;
1031 if (panels && !screen?.supportsHingeAngle) return;
1032 panelSinks = panels;
1033 videoGeneration++;
1034 controller?.abort();
1035 controller = null;
1036 closeDecoder();
1037 const retry = retryTimers.get("video");
1038 if (retry) clearTimeout(retry);
1039 retryTimers.delete("video");
1040 for (const panel of panelClients) panel.stop();
1041 panelClients = [];
1042 if (!panels) {
1043 if (useWebCodecs) void readIosVideo();
1044 return;
1045 }
1046 startDuoVideo(panels);
1047 },
1048 sendTouch: (phase, x, y) => {
1049 if (platform === "ios") {
1050 send(taggedJson(IOS_MSG_TOUCH, { type: phase, ...rawPoint(x, y) }));
1051 return;
1052 }
1053 const action = phase === "begin" ? "down" : phase === "move" ? "move" : "up";
1054 send(JSON.stringify({ type: "touch", action, x, y }));
1055 },
1056 sendKey: (event, phase) => {
1057 if (platform === "ios") {
1058 const usage = hidUsageForCode(event.code);
1059 if (usage !== null) send(taggedJson(IOS_MSG_KEY, { type: phase, usage }));
1060 return;
1061 }
1062 if (phase !== "down") return;
1063 if (event.key === "Escape") return send(JSON.stringify({ type: "back" }));
1064 const keycode = ANDROID_KEYCODE_BY_KEY[event.key];
1065 if (keycode !== undefined) return send(JSON.stringify({ type: "key", keycode }));
1066 if (event.key.length === 1 && !event.metaKey && !event.ctrlKey) {
1067 send(JSON.stringify({ type: "text", text: event.key }));
1068 }
1069 },
1070 sendText: (text) => {
1071 if (platform !== "android") return;
1072 let chunk = "";
1073 let chunkBytes = 0;
1074 let sentChunks = 0;
1075 for (const character of text) {
1076 const characterBytes = utf8ByteLength(character.codePointAt(0)!);
1077 if (chunkBytes + characterBytes > ANDROID_MAX_TEXT_BYTES) {
1078 send(JSON.stringify({ type: "text", text: chunk }));
1079 if (++sentChunks >= ANDROID_MAX_TEXT_CHUNKS) return;
1080 chunk = "";
1081 chunkBytes = 0;
1082 }
1083 chunk += character;
1084 chunkBytes += characterBytes;
1085 }
1086 if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk }));
1087 },
1088 pressButton: (button) => {
1089 if (platform === "ios") {
1090 const name =
1091 button === "home"
1092 ? "home"
1093 : button === "appSwitcher"
1094 ? "app_switcher"
1095 : button === "power"
1096 ? "lock"
1097 : null;
1098 if (name) send(taggedJson(IOS_MSG_BUTTON, { button: name }));
1099 return;
1100 }
1101 const type = button === "appSwitcher" ? "recents" : button;
1102 if (type === "home" || type === "back" || type === "recents" || type === "power") {
1103 send(JSON.stringify({ type }));
1104 }
1105 },
1106 rotate: () => {
1107 if (platform !== "ios") return;
1108 const current = screen?.supportsHingeAngle
1109 ? (rotationCursor ?? screen.orientation)
1110 : (screen?.orientation ?? "portrait");
1111 const next =
1112 IOS_ORIENTATIONS[(IOS_ORIENTATIONS.indexOf(current) + 1) % IOS_ORIENTATIONS.length]!;
1113 if (screen?.supportsHingeAngle) {
1114 rotationCursor = next;
1115 duoControl.enqueue({ control: "orientation", value: next });
1116 } else send(taggedJson(IOS_MSG_ORIENTATION, { orientation: next }));
1117 },
1118 setOrientation: (orientation) => {
1119 if (platform === "ios") send(taggedJson(IOS_MSG_ORIENTATION, { orientation }));
1120 },
1121 };
1122}