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

stream.ts

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