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