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

stream.ts

1,416 lines49.6 KB

1// @effect-diagnostics globalFetch:off globalTimers:off - This browser and WebView transport runs without an Effect runtime.
2​
3import {
4 createDuoControl,
5 type DuoCommand,
6 type DuoControlState,
7 type DuoPose,
8} from "./duoControl.ts";
9import * as Schema from "effect/Schema";
10import * as Option from "effect/Option";
11import { createCanvasFrameSink, type DeviceFrameSink } from "./frame.ts";
12import { simulatorAvcConfig } from "./avcConfig.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;
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);
60const iceServerSchema = Schema.Struct({
61 urls: Schema.Union([Schema.String, Schema.Array(Schema.String)]),
62 username: Schema.optionalKey(Schema.String),
63 credential: Schema.optionalKey(Schema.String),
64});
65const webRtcSettingsSchema = Schema.Struct({
66 transport: Schema.Literal("webrtc"),
67 iceServers: Schema.optionalKey(Schema.Array(iceServerSchema)),
68 iceTransportPolicy: Schema.optionalKey(Schema.Literals(["all", "relay"])),
69});
70// serve-sim reports its stream settings as `streamSettings` (EAS) or `stream`.
71const serveSimApiSchema = Schema.Struct({
72 streamSettings: Schema.optionalKey(Schema.Unknown),
73 stream: Schema.optionalKey(Schema.Unknown),
74});
75const decodeServeSimApi = Schema.decodeUnknownOption(serveSimApiSchema);
76const decodeWebRtcSettings = Schema.decodeUnknownOption(webRtcSettingsSchema);
77type WebRtcSettings = typeof webRtcSettingsSchema.Type;
78const decodeTransportLocked = Schema.decodeUnknownOption(
79 Schema.Struct({
80 error: Schema.Literal("stream_transport_locked"),
81 transport: Schema.Literal("webrtc"),
82 }),
83);
84const decodeWebRtcAnswer = Schema.decodeUnknownOption(
85 Schema.Struct({ type: Schema.Literal("answer"), sdp: Schema.String }),
86);
87​
88export interface DuoPanelSinks {
89 readonly cover: DeviceFrameSink;
90 readonly inner: DeviceFrameSink;
91 /** Invalidate captured input synchronously, before React can commit the new layout. */
92 readonly onScreen?: (screen: DeviceScreenSize) => void;
94​
95export interface DeviceStreamEvents {
96 readonly onDuoControl?: (state: DuoControlState) => void;
97 readonly onDuoUnavailable?: (detail?: string) => void;
98 readonly onStatus: (status: DeviceStreamStatus, detail?: string) => void;
99 readonly onScreen: (screen: DeviceScreenSize) => void;
100 readonly onUnauthorized: () => void;
101 /**
102 * H.264 cannot be decoded here (no WebCodecs, or the simulator's profile is
103 * unsupported); the owner should show an `<img>` instead of the canvas
104 * and attach it with `setMjpegImage` so the client can observe real frames.
105 */
106 readonly onMjpegFallback: (url: string) => void;
107 /**
108 * The stream moved from MJPEG back to painting the canvas, because the
109 * device serves WebRTC only; the owner should show the canvas again.
110 */
111 readonly onCanvasVideo?: () => void;
112 readonly onInputConnected: (connected: boolean, detail?: string) => void;
114​
115export interface DeviceStreamTarget {
116 readonly platform: DevicePlatform;
117 readonly deviceId: string;
118 readonly access: DeviceHubAccess;
119 /** Native iOS WebViews can use MJPEG without cross-origin fetch or secure-context support. */
120 readonly preferMjpeg?: boolean;
121 readonly panelId?: 1 | 3;
122 readonly videoOnly?: boolean;
123 /** The host speaks only serve-sim's AVCC stream and input socket, on both platforms (Simlock). */
124 readonly serveSimOnly?: boolean;
126​
127export type DeviceHardwareButton = "home" | "back" | "recents" | "power" | "appSwitcher";
128​
129const RETRY_DELAY_MS = 1_000;
130const FIRST_FRAME_TIMEOUT_MS = 15_000;
131// A WebRTC feed that shows no frame for this long is reconnected; checked
132// every WEBRTC_STALL_CHECK_MS, so a transient `disconnected` peer that
133// recovers is left alone.
134const WEBRTC_STALL_TIMEOUT_MS = FIRST_FRAME_TIMEOUT_MS;
135const WEBRTC_STALL_CHECK_MS = 5_000;
136const TRANSPORT_PROBE_TIMEOUT_MS = 5_000;
137// Offers carry every candidate: serve-sim does not accept trickled ICE.
138const ICE_GATHERING_TIMEOUT_MS = 2_000;
139// A gathering cut short without a reflexive or relay candidate is retried
140// with twice the deadline, up to this; then the offer goes as gathered. The
141// whole sequence stays inside the first-frame deadline, which retries do
142// not extend.
143const ICE_GATHERING_MAX_TIMEOUT_MS = 4_000;
144const MJPEG_FRAME_CHECK_MS = 250;
145const FRAME_DURATION_US = 16_667;
146const SEMU_MAGIC = 0x53454d55;
147const SEMU_HEADER_BYTES = 16;
148const SEMU_FLAG_KEY = 1;
149const SOFT_DECODE_QUEUE = 8;
150// expo-device-hub 0.15.3 serve-emu input.js MAX_TEXT_BYTES limits packets to 300 UTF-8 bytes.
151const ANDROID_MAX_TEXT_BYTES = 300;
152// The pinned hub queue depth is 128; the client does not read queue rejections.
153const ANDROID_MAX_TEXT_CHUNKS = 64;
154​
155const IOS_MSG_TOUCH = 0x03;
156const IOS_MSG_BUTTON = 0x04;
157const IOS_MSG_KEY = 0x06;
158const IOS_MSG_ORIENTATION = 0x07;
159const IOS_TAG_SCREEN_CONFIG = 0x82;
160const IOS_TAG_INPUT_ADMITTED = 0x83;
161​
162const encoder = new TextEncoder();
163const decoder = new TextDecoder();
164​
165/** serve-sim requires a v4 UUID; `crypto.randomUUID` is missing over plain-HTTP LAN origins. */
166function webRtcSessionId(): string {
167 const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
168 bytes[6] = (bytes[6]! & 0x0f) | 0x40;
169 bytes[8] = (bytes[8]! & 0x3f) | 0x80;
170 const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
171 return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
173​
174const isWebCodecsSupported = (): boolean =>
175 typeof globalThis !== "undefined" &&
176 "VideoDecoder" in globalThis &&
177 "EncodedVideoChunk" in globalThis;
178​
179function utf8ByteLength(codePoint: number): number {
180 if (codePoint <= 0x7f) return 1;
181 if (codePoint <= 0x7ff) return 2;
182 if (codePoint <= 0xffff) return 3;
183 return 4;
185​
186function taggedJson(tag: number, payload: unknown): Uint8Array<ArrayBuffer> {
187 const json = encoder.encode(JSON.stringify(payload));
188 const out = new Uint8Array(1 + json.length);
189 out[0] = tag;
190 out.set(json, 1);
191 return out;
193​
194export function avcCodecString(bytes: Uint8Array): string {
195 if (bytes.length < 4) return "avc1.42E01E";
196 const hex = (byte: number) => byte.toString(16).padStart(2, "0");
197 return `avc1.${hex(bytes[1]!)}${hex(bytes[2]!)}${hex(bytes[3]!)}`;
199​
200export function parseSemuPacket(raw: ArrayBuffer): {
201 readonly data: Uint8Array;
202 readonly isKey: boolean | null;
203 readonly timestamp: number | null;
204} {
205 const bytes = new Uint8Array(raw);
206 if (bytes.byteLength > SEMU_HEADER_BYTES) {
207 const view = new DataView(raw, 0, SEMU_HEADER_BYTES);
208 if (view.getUint32(0, false) === SEMU_MAGIC && view.getUint8(4) === 1) {
209 const pts = view.getBigUint64(8, false);
210 return {
211 data: bytes.subarray(SEMU_HEADER_BYTES),
212 isKey: (view.getUint8(5) & SEMU_FLAG_KEY) !== 0,
213 timestamp: pts <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(pts) : null,
214 };
215 }
216 }
217 return { data: bytes, isKey: null, timestamp: null };
219​
220const isVideoSessionMessage = (text: string) => {
221 try {
222 const message = JSON.parse(text) as { type?: unknown };
223 return message.type === "video-session";
224 } catch {
225 return false;
226 }
227};
228​
229export function scanAccessUnit(buf: Uint8Array): { isKey: boolean; sps: Uint8Array | null } {
230 let isKey = false;
231 let sps: Uint8Array | null = null;
232 const len = buf.length;
233 let i = 0;
234 while (i + 2 < len) {
235 if (buf[i] === 0 && buf[i + 1] === 0) {
236 let codeLen = 0;
237 if (buf[i + 2] === 1) codeLen = 3;
238 else if (i + 3 < len && buf[i + 2] === 0 && buf[i + 3] === 1) codeLen = 4;
239 if (codeLen) {
240 const nalType = buf[i + codeLen]! & 0x1f;
241 if (nalType === 7 && !sps) sps = buf.subarray(i + codeLen);
242 if (nalType === 5) isKey = true;
243 i += codeLen + 1;
244 continue;
245 }
246 }
247 i++;
248 }
249 return { isKey, sps };
251​
252export type AvccChunk = {
253 readonly type: "description" | "keyframe" | "delta" | "seed";
254 readonly payload: Uint8Array;
255};
256​
257const AVCC_TAGS: Record<number, AvccChunk["type"] | undefined> = {
258 1: "description",
259 2: "keyframe",
260 3: "delta",
261 4: "seed",
262};
263​
264export class AvccDemuxer {
265 private buffer = new Uint8Array(64 * 1024);
266 private length = 0;
267​
268 push(bytes: Uint8Array): AvccChunk[] {
269 if (this.length + bytes.length > this.buffer.length) {
270 let capacity = this.buffer.length;
271 while (capacity < this.length + bytes.length) capacity *= 2;
272 const grown = new Uint8Array(capacity);
273 grown.set(this.buffer.subarray(0, this.length));
274 this.buffer = grown;
275 }
276 this.buffer.set(bytes, this.length);
277 this.length += bytes.length;
278​
279 const chunks: AvccChunk[] = [];
280 let offset = 0;
281 while (this.length - offset >= 4) {
282 const view = new DataView(this.buffer.buffer, this.buffer.byteOffset + offset, 4);
283 const frameLength = view.getUint32(0, false);
284 if (this.length - offset - 4 < frameLength) break;
285 if (frameLength >= 1) {
286 const type = AVCC_TAGS[this.buffer[offset + 4]!];
287 if (type) {
288 chunks.push({ type, payload: this.buffer.slice(offset + 5, offset + 4 + frameLength) });
289 }
290 }
291 offset += 4 + frameLength;
292 }
293 if (offset > 0) {
294 this.buffer.copyWithin(0, offset, this.length);
295 this.length -= offset;
296 }
297 return chunks;
298 }
299​
300 reset(): void {
301 this.length = 0;
302 }
304​
305export interface DeviceStreamClient {
306 readonly start: () => void;
307 readonly stop: () => void;
308 /**
309 * `stop()` detaches it; attach a fresh image for each restart.
310 */
311 readonly setMjpegImage: (image: HTMLImageElement | null) => void;
312 /** Normalized 0..1 coordinates in the displayed frame. */
313 readonly sendTouch: (phase: "begin" | "move" | "end", x: number, y: number) => void;
314 readonly sendKey: (event: KeyboardEvent, phase: "down" | "up") => void;
315 /** Android only: iOS input is HID key codes, which cannot carry arbitrary text. */
316 readonly sendText: (text: string) => void;
317 readonly pressButton: (button: DeviceHardwareButton) => void;
318 readonly rotate: () => void;
319 readonly setOrientation: (orientation: DeviceScreenSize["orientation"]) => void;
320 readonly controlDuo: (command: DuoCommand) => void;
321 readonly setDuoPanels: (panels: DuoPanelSinks | null) => void;
322 readonly sendRawTouch: (phase: "begin" | "move" | "end", x: number, y: number) => void;
324​
325const HID_USAGE_BY_CODE: Readonly<Record<string, number>> = {
326 Enter: 0x28,
327 Escape: 0x29,
328 Backspace: 0x2a,
329 Tab: 0x2b,
330 Space: 0x2c,
331 Minus: 0x2d,
332 Equal: 0x2e,
333 BracketLeft: 0x2f,
334 BracketRight: 0x30,
335 Backslash: 0x31,
336 Semicolon: 0x33,
337 Quote: 0x34,
338 Backquote: 0x35,
339 Comma: 0x36,
340 Period: 0x37,
341 Slash: 0x38,
342 Delete: 0x4c,
343 ArrowRight: 0x4f,
344 ArrowLeft: 0x50,
345 ArrowDown: 0x51,
346 ArrowUp: 0x52,
347 ControlLeft: 0xe0,
348 ShiftLeft: 0xe1,
349 AltLeft: 0xe2,
350 MetaLeft: 0xe3,
351 ControlRight: 0xe4,
352 ShiftRight: 0xe5,
353 AltRight: 0xe6,
354 MetaRight: 0xe7,
355};
356​
357function hidUsageForCode(code: string): number | null {
358 if (/^Key[A-Z]$/.test(code)) return 0x04 + (code.charCodeAt(3) - 65);
359 if (/^Digit[1-9]$/.test(code)) return 0x1e + (code.charCodeAt(5) - 49);
360 if (code === "Digit0") return 0x27;
361 return HID_USAGE_BY_CODE[code] ?? null;
363​
364const ANDROID_KEYCODE_BY_KEY: Readonly<Record<string, number>> = {
365 ArrowUp: 19,
366 ArrowDown: 20,
367 ArrowLeft: 21,
368 ArrowRight: 22,
369 Tab: 61,
370 Enter: 66,
371 Backspace: 67,
372 Delete: 112,
373 Home: 122,
374 End: 123,
375 PageUp: 92,
376 PageDown: 93,
377};
378​
379const IOS_ORIENTATIONS: ReadonlyArray<DeviceScreenSize["orientation"]> = [
380 "portrait",
381 "landscape_left",
382 "portrait_upside_down",
383 "landscape_right",
384];
385​
386export function createDeviceStreamClient(
387 target: DeviceStreamTarget,
388 output: HTMLCanvasElement | DeviceFrameSink,
389 events: DeviceStreamEvents,
390): DeviceStreamClient {
391 const { access, platform, deviceId } = target;
392 const sink = "present" in output ? output : createCanvasFrameSink(output);
393 // Android normally streams over serve-emu's socket; a serve-sim-only host serves it like iOS.
394 const serveSimOnly = target.serveSimOnly === true;
395 const avcc = platform === "ios" || serveSimOnly;
396 const vendor = avcc ? "/vendor/serve-sim" : "/vendor/serve-emu";
397 const device = encodeURIComponent(deviceId);
398 const httpUrl = (path: string) =>
399 withDeviceHubQuery(`${access.httpBase}${vendor}${path}`, access);
400 const wsUrl = (path: string) => withDeviceHubQuery(`${access.wsBase}${vendor}${path}`, access);
401 const useWebCodecs =
402 isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg && !serveSimOnly);
403​
404 let stopped = true;
405 let socket: WebSocket | null = null;
406 let controller: AbortController | null = null;
407 const retryTimers = new Map<"video" | "input", ReturnType<typeof setTimeout>>();
408 let primeController: AbortController | null = null;
409 let videoDecoder: VideoDecoder | null = null;
410 let decodedVideoGeneration: number | null = null;
411 let iosInputAdmitted = false;
412 let iosInputUnavailable = false;
413 let timestamp = 0;
414 let awaitingKeyframe = true;
415 let screen: DeviceScreenSize | null = null;
416 let firstFrame = false;
417 let configuring = false;
418 let mjpeg = false;
419 let generation = 0;
420 let decoderEpoch = 0;
421 let frameTimer: ReturnType<typeof setTimeout> | null = null;
422 let videoReadTimer: ReturnType<typeof setTimeout> | null = null;
423 let mjpegImage: HTMLImageElement | null = null;
424 let releaseImage: (() => void) | null = null;
425 let videoGeneration = 0;
426 let panelClients: DeviceStreamClient[] = [];
427 let panelSinks: DuoPanelSinks | null = null;
428 let rotationCursor: DeviceScreenSize["orientation"] | null = null;
429 let pendingOrientation: { requestId: number } | null = null;
430 let iceGatheringDeadlineMs = ICE_GATHERING_TIMEOUT_MS;
431 let peer: { connection: RTCPeerConnection; sessionId: string; video: HTMLVideoElement } | null =
432 null;
433 const duoControl = createDuoControl({
434 send(request) {
435 if (
436 !iosInputAdmitted ||
437 iosInputUnavailable ||
438 socket?.readyState !== WebSocket.OPEN ||
439 !screen?.supportsHingeAngle
440 )
441 return false;
442 if (request.command.control === "physical" && !screen.supportsPhysicalOrientation)
443 return false;
444 try {
445 pendingOrientation = null;
446 if (request.command.control === "orientation") {
447 const value = request.command.value;
448 pendingOrientation = { requestId: request.requestId };
449 rotationCursor = value;
450 // Upstream serializes orientation with hinge commands, then broadcasts config.
451 // An orientation-locked app can keep its framebuffer orientation after the sensor rotates.
452 socket.send(taggedJson(IOS_MSG_ORIENTATION, { orientation: value }));
453 } else socket.send(taggedJson(0x10, request));
454 return true;
455 } catch {
456 return false;
457 }
458 },
459 onChange(state) {
460 if (!state.pending) pendingOrientation = null;
461 events.onDuoControl?.(state);
462 },
463 });
464 const videoPath = `/helper/${device}${target.panelId ? `/panel/${target.panelId}` : ""}/stream.avcc`;
465​
466 const mjpegUrl = () => httpUrl(`/helper/${device}/stream.mjpeg`);
467​
468 const setStatus = (status: DeviceStreamStatus, detail?: string) => {
469 if (!stopped) events.onStatus(status, detail);
470 };
471​
472 const clearFrameTimer = () => {
473 if (frameTimer !== null) clearTimeout(frameTimer);
474 frameTimer = null;
475 };
476​
477 const fail = (detail: string) => {
478 if (stopped) return;
479 stop();
480 events.onInputConnected(false, detail);
481 events.onStatus("error", detail);
482 };
483​
484 const connecting = (detail?: string) => {
485 firstFrame = false;
486 if (frameTimer === null) {
487 frameTimer = setTimeout(
488 () => fail("No video received from the device. Reconnect to try again."),
489 FIRST_FRAME_TIMEOUT_MS,
490 );
491 }
492 setStatus("connecting", detail);
493 };
494​
495 const frameReceived = () => {
496 if (firstFrame) return;
497 firstFrame = true;
498 clearFrameTimer();
499 setStatus("streaming");
500 };
501​
502 const observeMjpegImage = () => {
503 releaseImage?.();
504 releaseImage = null;
505 const image = mjpegImage;
506 if (!image || stopped || !mjpeg) return;
507 let timer: ReturnType<typeof setTimeout> | null = null;
508 let released = false;
509 const check = () => {
510 if (released || stopped) return;
511 if (timer !== null) clearTimeout(timer);
512 timer = null;
513 if (image.naturalWidth > 0 && image.naturalHeight > 0) frameReceived();
514 else {
515 // Multipart images may not emit load until the response ends.
516 timer = setTimeout(check, MJPEG_FRAME_CHECK_MS);
517 }
518 };
519 const error = () => {
520 if (released) return;
521 const failure = "Could not receive the device stream. Reconnect to try again.";
522 // An <img> cannot read the 409 that a WebRTC-only serve-sim answers with.
523 if (typeof RTCPeerConnection === "undefined") fail(failure);
524 else void switchToWebRtc(failure, false);
525 };
526 image.addEventListener("load", check);
527 image.addEventListener("error", error);
528 releaseImage = () => {
529 released = true;
530 if (timer !== null) clearTimeout(timer);
531 image.removeEventListener("load", check);
532 image.removeEventListener("error", error);
533 image.removeAttribute("src");
534 };
535 image.src = mjpegUrl();
536 check();
537 };
538​
539 const setMjpegImage = (image: HTMLImageElement | null) => {
540 if (mjpegImage === image) return;
541 releaseImage?.();
542 releaseImage = null;
543 mjpegImage = image;
544 observeMjpegImage();
545 };
546​
547 const fallBackToMjpeg = () => {
548 if (stopped || mjpeg) return;
549 mjpeg = true;
550 controller?.abort();
551 controller = null;
552 closeDecoder();
553 connecting();
554 events.onMjpegFallback(mjpegUrl());
555 if (!releaseImage) observeMjpegImage();
556 };
557​
558 const paint = (source: CanvasImageSource, width: number, height: number) => {
559 if (stopped) return;
560 if (!avcc && (screen?.width !== width || screen.height !== height)) {
561 screen = { width, height, orientation: width > height ? "landscape_left" : "portrait" };
562 events.onScreen(screen);
563 }
564 if (!sink.present(source, width, height)) {
565 fail("Could not display the device stream. Reconnect to try again.");
566 return;
567 }
568 frameReceived();
569 };
570​
571 const closeDecoder = () => {
572 decoderEpoch++;
573 try {
574 videoDecoder?.close();
575 } catch {}
576 videoDecoder = null;
577 awaitingKeyframe = true;
578 };
579​
580 const recoverDecoder = () => {
581 if (serveSimOnly) {
582 // A new AVCC request starts a fresh capture with a keyframe; there is no MJPEG.
583 closeDecoder();
584 controller?.abort();
585 } else if (platform === "ios") fallBackToMjpeg();
586 else {
587 closeDecoder();
588 connecting("Video decoder restarted.");
589 requestKeyframe();
590 }
591 };
592​
593 const makeDecoder = () => {
594 const feedGeneration = videoGeneration;
595 const decoder = new VideoDecoder({
596 output: (frame) => {
597 try {
598 if (videoDecoder === decoder && (!avcc || feedGeneration === videoGeneration)) {
599 decodedVideoGeneration = feedGeneration;
600 paint(frame, frame.displayWidth, frame.displayHeight);
601 }
602 } finally {
603 frame.close();
604 }
605 },
606 error: () => {
607 if (stopped || videoDecoder !== decoder || (avcc && feedGeneration !== videoGeneration))
608 return;
609 recoverDecoder();
610 },
611 });
612 return decoder;
613 };
614​
615 const configureDecoder = async (
616 config: VideoDecoderConfig,
617 isCurrent = () => !stopped,
618 ): Promise<boolean> => {
619 const epoch = decoderEpoch;
620 const full: VideoDecoderConfig = { ...config, optimizeForLatency: true };
621 const support = await VideoDecoder.isConfigSupported(full).catch(() => ({ supported: false }));
622 if (!isCurrent() || epoch !== decoderEpoch) return false;
623 if (!support.supported) {
624 if (platform === "android") fail(`This browser cannot decode ${config.codec}.`);
625 return false;
626 }
627 try {
628 if (!videoDecoder || videoDecoder.state === "closed") videoDecoder = makeDecoder();
629 videoDecoder.configure(full);
630 return true;
631 } catch (cause) {
632 if (platform === "android") fail(`Video decoder: ${(cause as Error).message}`);
633 return false;
634 }
635 };
636​
637 const decode = (isKey: boolean, data: Uint8Array, pts?: number | null) => {
638 if (!videoDecoder || videoDecoder.state !== "configured") return;
639 if (awaitingKeyframe) {
640 if (!isKey) return;
641 awaitingKeyframe = false;
642 }
643 if (videoDecoder.decodeQueueSize > SOFT_DECODE_QUEUE) {
644 if (!avcc) {
645 recoverDecoder();
646 return;
647 }
648 // Native IDRs are spaced by frame count, so an idle simulator may take
649 // minutes to produce one. A new AVCC subscription forces a fresh IDR.
650 controller?.abort();
651 closeDecoder();
652 return;
653 }
654 try {
655 videoDecoder.decode(
656 new EncodedVideoChunk({
657 type: isKey ? "key" : "delta",
658 timestamp: pts ?? timestamp,
659 data,
660 }),
661 );
662 timestamp += FRAME_DURATION_US;
663 } catch {
664 recoverDecoder();
665 }
666 };
667​
668 const requestKeyframe = () => {
669 if (platform === "android" && socket?.readyState === WebSocket.OPEN) {
670 socket.send(JSON.stringify({ type: "reset-video", ack: false }));
671 }
672 };
673​
674 const scheduleRetry = (channel: "video" | "input", run: () => void) => {
675 if (stopped || retryTimers.has(channel)) return;
676 retryTimers.set(
677 channel,
678 setTimeout(() => {
679 retryTimers.delete(channel);
680 run();
681 }, RETRY_DELAY_MS),
682 );
683 };
684​
685 const handleUnauthorized = () => {
686 stop();
687 events.onInputConnected(false);
688 events.onUnauthorized();
689 };
690​
691 const readIosVideo = async () => {
692 const lifecycle = generation;
693 const feedGeneration = ++videoGeneration;
694 const demuxer = new AvccDemuxer();
695 const videoController = new AbortController();
696 controller = videoController;
697 const isCurrent = () =>
698 !stopped &&
699 generation === lifecycle &&
700 videoGeneration === feedGeneration &&
701 controller === videoController;
702 let retryDetail: string | undefined;
703 try {
704 const response = await fetch(httpUrl(videoPath), {
705 signal: videoController.signal,
706 credentials: access.credentials ? "include" : "same-origin",
707 });
708 if (!isCurrent()) {
709 await response.body?.cancel();
710 return;
711 }
712 if (response.status === 401 || response.status === 403) return handleUnauthorized();
713 if (response.status === 409 && !target.panelId) {
714 const locked = decodeTransportLocked(await response.json().catch(() => null));
715 if (Option.isSome(locked)) {
716 if (!isCurrent()) return;
717 controller = null;
718 void switchToWebRtc("This browser cannot play this device's WebRTC stream.", true);
719 return;
720 }
721 }
722 if (target.panelId && [400, 404, 405, 410].includes(response.status)) {
723 await response.body?.cancel();
724 setStatus("error", "This Device Hub does not provide fixed Duo display feeds.");
725 return;
726 }
727 if (!response.ok || !response.body) throw new Error(`stream ${response.status}`);
728 const reader = response.body.getReader();
729 for (;;) {
730 // An AVCC body can stay open after its helper stops producing frames.
731 const timer = setTimeout(() => {
732 if (!isCurrent()) return;
733 retryDetail = "Device stream stopped receiving video. Reconnecting…";
734 videoController.abort();
735 }, FIRST_FRAME_TIMEOUT_MS);
736 videoReadTimer = timer;
737 let result: ReadableStreamReadResult<Uint8Array>;
738 try {
739 result = await reader.read();
740 } finally {
741 clearTimeout(timer);
742 if (videoReadTimer === timer) videoReadTimer = null;
743 }
744 const { done, value } = result;
745 if (!isCurrent()) return;
746 if (done) break;
747 for (const chunk of demuxer.push(value)) {
748 if (videoController.signal.aborted) break;
749 switch (chunk.type) {
750 case "seed":
751 void createImageBitmap(new Blob([chunk.payload as BlobPart], { type: "image/jpeg" }))
752 .then((bitmap) => {
753 try {
754 if (isCurrent() && decodedVideoGeneration !== feedGeneration)
755 paint(bitmap, bitmap.width, bitmap.height);
756 } finally {
757 bitmap.close();
758 }
759 })
760 .catch(() => {});
761 break;
762 case "description": {
763 awaitingKeyframe = true;
764 const configured = await configureDecoder(
765 {
766 codec: avcCodecString(chunk.payload),
767 description: simulatorAvcConfig(chunk.payload),
768 },
769 isCurrent,
770 );
771 if (!isCurrent()) return;
772 if (!configured) {
773 await reader.cancel().catch(() => {});
774 if (!isCurrent()) return;
775 if (serveSimOnly)
776 setStatus(
777 "error",
778 `This browser cannot decode this device's ${avcCodecString(chunk.payload)} stream.`,
779 );
780 else if (target.videoOnly)
781 setStatus(
782 "error",
783 `This browser cannot decode the Duo panel's ${avcCodecString(chunk.payload)} stream.`,
784 );
785 else fallBackToMjpeg();
786 return;
787 }
788 break;
789 }
790 case "keyframe":
791 case "delta":
792 decode(chunk.type === "keyframe", chunk.payload);
793 break;
794 }
795 }
796 }
797 } catch (cause) {
798 if (!isCurrent()) return;
799 retryDetail ??= videoController.signal.aborted
800 ? "Video decoder fell behind. Reconnecting…"
801 : (cause as Error).message;
802 }
803 if (isCurrent()) {
804 controller = null;
805 videoController.abort();
806 closeDecoder();
807 connecting(retryDetail);
808 scheduleRetry("video", () => void readIosVideo());
809 }
810 };
811​
812 /**
813 * serve-sim's helper only accepts HID and pushes its screen config once
814 * screen capture is running, and the AVCC stream does not reliably start
815 * it. Touching the MJPEG endpoint does; one aborted request is enough.
816 */
817 const primeIosHelper = async (session: number) => {
818 const controller = new AbortController();
819 primeController = controller;
820 const timeout = setTimeout(() => controller.abort(), 2_000);
821 try {
822 const response = await fetch(httpUrl(`/helper/${device}/stream.mjpeg`), {
823 signal: controller.signal,
824 credentials: access.credentials ? "include" : "same-origin",
825 });
826 if (stopped || generation !== session) return;
827 if (response.status === 401 || response.status === 403) return handleUnauthorized();
828 await response.body?.getReader().read();
829 } catch {
830 } finally {
831 clearTimeout(timeout);
832 controller.abort();
833 if (primeController === controller) primeController = null;
834 }
835 };
836​
837 /**
838 * serve-sim can be locked to WebRTC (EAS Simulator always is), and then
839 * refuses AVCC and MJPEG. An unreadable answer keeps the AVCC path.
840 */
841 const probeIosTransport = async (): Promise<WebRtcSettings | null> => {
842 const probe = new AbortController();
843 const timeout = setTimeout(() => probe.abort(), TRANSPORT_PROBE_TIMEOUT_MS);
844 try {
845 const response = await fetch(httpUrl(`/api?device=${device}`), {
846 signal: probe.signal,
847 credentials: access.credentials ? "include" : "same-origin",
848 });
849 if (!response.ok) return null;
850 const api = decodeServeSimApi(await response.json());
851 if (Option.isNone(api)) return null;
852 const settings = decodeWebRtcSettings(api.value.streamSettings ?? api.value.stream);
853 return Option.isSome(settings) ? settings.value : null;
854 } catch {
855 return null;
856 } finally {
857 clearTimeout(timeout);
858 }
859 };
860​
861 const closePeer = () => {
862 const current = peer;
863 if (!current) return;
864 peer = null;
865 current.connection.close();
866 current.video.srcObject = null;
867 current.video.remove();
868 // Releases serve-sim's capture session; best effort because the page may be unloading.
869 void fetch(httpUrl(`/helper/${device}/webrtc/close`), {
870 method: "POST",
871 keepalive: true,
872 headers: { "content-type": "application/json" },
873 body: JSON.stringify({ sessionId: current.sessionId }),
874 credentials: access.credentials ? "include" : "same-origin",
875 }).catch(() => {});
876 };
877​
878 const readIosWebRtc = async (settings: WebRtcSettings) => {
879 const lifecycle = generation;
880 const feedGeneration = ++videoGeneration;
881 closePeer();
882 const connection = new RTCPeerConnection({
883 ...(settings.iceServers
884 ? {
885 iceServers: settings.iceServers.map((server) => ({
886 ...server,
887 urls: typeof server.urls === "string" ? server.urls : [...server.urls],
888 })),
889 }
890 : {}),
891 iceTransportPolicy: settings.iceTransportPolicy ?? "all",
892 });
893 // Frames only reach requestVideoFrameCallback from a video that is in the
894 // document; it stays invisible because the sink paints them.
895 const video = document.createElement("video");
896 video.muted = true;
897 video.playsInline = true;
898 video.setAttribute("aria-hidden", "true");
899 video.style.cssText =
900 "position:fixed;width:1px;height:1px;opacity:0;pointer-events:none;left:0;top:0";
901 document.body.append(video);
902 const current = { connection, sessionId: webRtcSessionId(), video };
903 peer = current;
904 const isCurrent = () =>
905 !stopped &&
906 generation === lifecycle &&
907 videoGeneration === feedGeneration &&
908 peer === current;
909 // After the first frame nothing else bounds a feed that stops: the peer
910 // can sit `disconnected` with the last frame on the canvas. A long gap
911 // between frames reconnects through the same path as a failed connection.
912 let checksWithoutFrame = 0;
913 let watchdog: ReturnType<typeof setInterval> | null = null;
914 const clearWatchdog = () => {
915 if (watchdog !== null) clearInterval(watchdog);
916 watchdog = null;
917 };
918 const retry = (detail: string) => {
919 clearWatchdog();
920 if (!isCurrent()) return;
921 closePeer();
922 connecting(detail);
923 scheduleRetry("video", () => void readIosWebRtc(settings));
924 };
925 const presentFrame = () => {
926 if (!isCurrent()) {
927 clearWatchdog();
928 return;
929 }
930 if (video.videoWidth > 0 && video.videoHeight > 0) {
931 paint(video, video.videoWidth, video.videoHeight);
932 checksWithoutFrame = 0;
933 watchdog ??= setInterval(() => {
934 if (!isCurrent()) return clearWatchdog();
935 checksWithoutFrame++;
936 if (checksWithoutFrame * WEBRTC_STALL_CHECK_MS >= WEBRTC_STALL_TIMEOUT_MS) {
937 retry("Device stream stalled. Reconnecting…");
938 }
939 }, WEBRTC_STALL_CHECK_MS);
940 }
941 video.requestVideoFrameCallback(presentFrame);
942 };
943 const transceiver = connection.addTransceiver("video", { direction: "recvonly" });
944 const codecs = RTCRtpReceiver.getCapabilities("video")?.codecs ?? [];
945 if (codecs.length > 0) {
946 // serve-sim encodes H.264; other codecs stay as fallbacks it may refuse.
947 transceiver.setCodecPreferences([
948 ...codecs.filter((codec) => codec.mimeType.toLowerCase() === "video/h264"),
949 ...codecs.filter((codec) => codec.mimeType.toLowerCase() !== "video/h264"),
950 ]);
951 }
952 connection.ontrack = (event) => {
953 if (!isCurrent()) return;
954 iceGatheringDeadlineMs = ICE_GATHERING_TIMEOUT_MS;
955 video.srcObject = event.streams[0] ?? new MediaStream([event.track]);
956 void video.play().catch(() => {});
957 video.requestVideoFrameCallback(presentFrame);
958 };
959 connection.onconnectionstatechange = () => {
960 if (connection.connectionState === "failed")
961 retry("Device stream connection failed. Reconnecting…");
962 };
963 try {
964 await connection.setLocalDescription(await connection.createOffer());
965 const gathered = await new Promise<boolean>((resolve) => {
966 if (connection.iceGatheringState === "complete") return resolve(true);
967 const timer = setTimeout(() => done(false), iceGatheringDeadlineMs);
968 function done(complete: boolean) {
969 clearTimeout(timer);
970 connection.removeEventListener("icegatheringstatechange", changed);
971 resolve(complete);
972 }
973 function changed() {
974 if (connection.iceGatheringState === "complete") done(true);
975 }
976 connection.addEventListener("icegatheringstatechange", changed);
977 });
978 if (!isCurrent()) return;
979 // serve-sim takes all candidates in the offer; later candidates never trickle.
980 // Cloud simulators need a reflexive or relay candidate, so retry incomplete offers with
981 // longer deadlines up to the bound, then send what was gathered.
982 const sdp = connection.localDescription?.sdp ?? "";
983 if (
984 !gathered &&
985 !/^a=candidate:.* typ (?:srflx|relay)\b/m.test(sdp) &&
986 iceGatheringDeadlineMs < ICE_GATHERING_MAX_TIMEOUT_MS
987 ) {
988 iceGatheringDeadlineMs = Math.min(iceGatheringDeadlineMs * 2, ICE_GATHERING_MAX_TIMEOUT_MS);
989 return retry("Device stream found no network candidates yet. Retrying…");
990 }
991 const response = await fetch(httpUrl(`/helper/${device}/webrtc/offer`), {
992 method: "POST",
993 headers: { "content-type": "application/json" },
994 body: JSON.stringify({
995 type: "offer",
996 sdp: connection.localDescription?.sdp,
997 sessionId: current.sessionId,
998 codec: "h264",
999 }),
1000 credentials: access.credentials ? "include" : "same-origin",
1001 });
1002 if (!isCurrent()) {
1003 await response.body?.cancel();
1004 return;
1006 if (response.status === 401 || response.status === 403) return handleUnauthorized();
1007 // 409: another viewer is still negotiating with this simulator.
1008 if (!response.ok) return retry(`Device stream offer failed (${response.status}). Retrying…`);
1009 const answer = decodeWebRtcAnswer(await response.json());
1010 if (!isCurrent()) return;
1011 if (Option.isNone(answer))
1012 return retry("Device stream returned an invalid answer. Retrying…");
1013 await connection.setRemoteDescription(answer.value);
1014 } catch (cause) {
1015 retry((cause as Error).message);
1017 };
1018​
1019 /**
1020 * Called once AVCC or MJPEG was refused. `locked` means serve-sim already
1021 * said it streams WebRTC only, so a missing /api answer still switches.
1022 */
1023 const switchToWebRtc = async (failure: string, locked: boolean) => {
1024 const session = generation;
1025 if (typeof RTCPeerConnection === "undefined") return fail(failure);
1026 const settings =
1027 (await probeIosTransport()) ?? (locked ? { transport: "webrtc" as const } : null);
1028 if (stopped || generation !== session) return;
1029 if (!settings) return fail(failure);
1030 if (mjpeg) {
1031 mjpeg = false;
1032 releaseImage?.();
1033 releaseImage = null;
1034 events.onCanvasVideo?.();
1036 // MJPEG may have shown frames already: say the stream is connecting again
1037 // rather than leave a blank canvas until the first WebRTC frame.
1038 connecting("Switching to WebRTC.");
1039 void readIosWebRtc(settings);
1040 };
1041​
1042 const startDuoVideo = (panels: DuoPanelSinks) => {
1043 for (const panel of panelClients) panel.stop();
1044 // Physical handoff elects a native surface. Fixed-panel encoders can keep
1045 // an inactive shutdown frame after election, so this build uses one active
1046 // feed instead of decoding a third stream alongside the two fixed feeds.
1047 const ids = screen?.supportsPhysicalOrientation ? ([null] as const) : ([1, 3] as const);
1048 panelClients = ids.map((id) => {
1049 const output = id === 1 ? panels.cover : panels.inner;
1050 return createDeviceStreamClient(
1051 { ...target, ...(id === null ? {} : { panelId: id }), videoOnly: true },
1053 present(source, width, height) {
1054 if (id === null) {
1055 return sink.present(source, width, height);
1057 // An inactive native LCD can emit its shutdown black frame. Retain its last useful image.
1058 if (screen?.screenId !== id) return true;
1059 const retained = output.present(source, width, height);
1060 const primary = sink.present(source, width, height);
1061 return retained && primary;
1062 },
1063 },
1065 onStatus: (status, detail) => {
1066 if (status === "error") events.onDuoUnavailable?.(detail);
1067 },
1068 onScreen: () => {},
1069 onInputConnected: () => {},
1070 onMjpegFallback: () => {},
1071 onUnauthorized: handleUnauthorized,
1072 },
1073 );
1074 });
1075 for (const panel of panelClients) panel.start();
1076 };
1077​
1078 const connectIosInput = async () => {
1079 if (stopped) return;
1080 const session = generation;
1081 if (!serveSimOnly) await primeIosHelper(session);
1082 if (stopped || generation !== session) return;
1083 const ws = new WebSocket(wsUrl(`/helper/ws?device=${device}`));
1084 ws.binaryType = "arraybuffer";
1085 socket = ws;
1086 iosInputAdmitted = false;
1087 iosInputUnavailable = false;
1088 ws.onmessage = (event) => {
1089 if (stopped || socket !== ws) return;
1090 if (!(event.data instanceof ArrayBuffer)) return;
1091 const bytes = new Uint8Array(event.data);
1092 if (socket !== ws || stopped || bytes.length < 1) return;
1093 if (bytes[0] === IOS_TAG_INPUT_ADMITTED) {
1094 iosInputAdmitted = true;
1095 events.onInputConnected(!iosInputUnavailable);
1096 return;
1098 try {
1099 const payload: unknown = JSON.parse(decoder.decode(bytes.subarray(1)));
1100 if (bytes[0] === 0x90) {
1101 const reply = decodeControlReply(payload);
1102 if (Option.isSome(reply)) duoControl.receive(reply.value);
1103 } else if (bytes[0] === IOS_TAG_SCREEN_CONFIG) {
1104 const config = decodeScreenConfig(payload);
1105 if (Option.isSome(config)) {
1106 iosInputUnavailable = config.value.inputUnavailable === true;
1107 events.onInputConnected(
1108 iosInputAdmitted && !iosInputUnavailable,
1109 iosInputUnavailable ? "Simulator input is unavailable" : undefined,
1110 );
1111 const previous = screen;
1112 screen = config.value;
1113 if (screen.hingePose && screen.hingePose !== previous?.hingePose)
1114 rotationCursor = screen.hingePose === "laptop" ? "landscape_left" : "portrait";
1115 else if (screen.orientation !== previous?.orientation)
1116 rotationCursor = screen.orientation;
1117 panelSinks?.onScreen?.(screen);
1118 events.onScreen(screen);
1119 // A surface election can leave an existing decoder on the former
1120 // encoder description. Reopen only video to acquire the elected
1121 // surface's seed and codec configuration; HID and the viewer stay.
1122 if (
1123 panelSinks &&
1124 screen.supportsPhysicalOrientation &&
1125 previous &&
1126 screen.screenId !== previous.screenId
1128 startDuoVideo(panelSinks);
1129 if (pendingOrientation) {
1130 const receipt = pendingOrientation;
1131 pendingOrientation = null;
1132 duoControl.receive({
1133 requestId: receipt.requestId,
1134 ok: true,
1135 });
1139 } catch {}
1140 };
1141 ws.onclose = (event) => {
1142 if (socket !== ws) return;
1143 socket = null;
1144 iosInputAdmitted = false;
1145 duoControl.clear();
1146 rotationCursor = null;
1147 if (stopped) return;
1148 events.onInputConnected(
1149 false,
1150 event.reason || (event.code === 1006 ? "input socket refused" : `closed ${event.code}`),
1151 );
1152 // A rejected HTTP upgrade surfaces as 1006, including an expired stream ticket.
1153 if (
1154 event.code === 1008 ||
1155 event.code === 4401 ||
1156 (event.code === 1006 && access.query.wsTicket)
1158 return handleUnauthorized();
1159 scheduleRetry("input", () => void connectIosInput());
1160 };
1161 ws.onerror = () => ws.close();
1162 };
1163​
1164 const connectAndroid = () => {
1165 if (stopped) return;
1166 const ws = new WebSocket(wsUrl(`/ws?device=${device}&frame-meta=1`));
1167 ws.binaryType = "arraybuffer";
1168 socket = ws;
1169 ws.onopen = () => {
1170 if (stopped || socket !== ws) return;
1171 connecting();
1172 events.onInputConnected(true);
1173 };
1174 ws.onmessage = (event) => {
1175 if (stopped || socket !== ws) return;
1176 if (typeof event.data === "string") {
1177 // The encoder restarts at a new size when the device rotates; the
1178 // next keyframe carries a fresh SPS, so the decoder is rebuilt from it.
1179 if (isVideoSessionMessage(event.data)) {
1180 closeDecoder();
1181 configuring = false;
1182 connecting();
1183 requestKeyframe();
1185 return;
1187 if (!(event.data instanceof ArrayBuffer)) return;
1188 const packet = parseSemuPacket(event.data);
1189 const needsScan =
1190 packet.isKey === null ||
1191 (packet.isKey && (!videoDecoder || videoDecoder.state !== "configured"));
1192 const scanned = needsScan ? scanAccessUnit(packet.data) : null;
1193 const isKey = packet.isKey ?? scanned?.isKey ?? false;
1194 if (scanned?.sps && (!videoDecoder || videoDecoder.state !== "configured")) {
1195 if (configuring) return;
1196 configuring = true;
1197 const epoch = decoderEpoch;
1198 const isCurrent = () => !stopped && socket === ws;
1199 void configureDecoder({ codec: avcCodecString(scanned.sps) }, isCurrent).then(
1200 (configured) => {
1201 if (!isCurrent() || epoch !== decoderEpoch) return;
1202 configuring = false;
1203 awaitingKeyframe = true;
1204 if (configured) requestKeyframe();
1205 },
1206 );
1207 return;
1209 if (!videoDecoder || videoDecoder.state !== "configured") {
1210 if (!isKey) requestKeyframe();
1211 return;
1213 decode(isKey, packet.data, packet.timestamp);
1214 };
1215 ws.onclose = (event) => {
1216 if (socket !== ws) return;
1217 socket = null;
1218 closeDecoder();
1219 if (stopped) return;
1220 events.onInputConnected(false, event.reason || `closed ${event.code}`);
1221 if (
1222 event.code === 1008 ||
1223 event.code === 4401 ||
1224 (event.code === 1006 && access.query.wsTicket)
1226 return handleUnauthorized();
1227 configuring = false;
1228 connecting(event.reason || undefined);
1229 scheduleRetry("input", connectAndroid);
1230 };
1231 ws.onerror = () => ws.close();
1232 };
1233​
1234 const start = () => {
1235 if (!stopped) return;
1236 stopped = false;
1237 generation++;
1238 configuring = false;
1239 iosInputAdmitted = false;
1240 iosInputUnavailable = false;
1241 connecting();
1242 if (serveSimOnly) {
1243 if (!target.videoOnly) void connectIosInput();
1244 if (useWebCodecs) void readIosVideo();
1245 else fail("This browser cannot decode this device's stream (WebCodecs unavailable).");
1246 } else if (platform === "ios") {
1247 if (!target.videoOnly) void connectIosInput();
1248 if (useWebCodecs) void readIosVideo();
1249 else fallBackToMjpeg();
1250 } else if (useWebCodecs) {
1251 connectAndroid();
1252 } else {
1253 fail("This browser cannot decode the Android stream (WebCodecs unavailable).");
1255 };
1256​
1257 const stop = () => {
1258 if (stopped) return;
1259 stopped = true;
1260 generation++;
1261 videoGeneration++;
1262 duoControl.clear();
1263 rotationCursor = null;
1264 for (const panel of panelClients) panel.stop();
1265 panelClients = [];
1266 panelSinks = null;
1267 mjpeg = false;
1268 clearFrameTimer();
1269 if (videoReadTimer !== null) clearTimeout(videoReadTimer);
1270 videoReadTimer = null;
1271 releaseImage?.();
1272 releaseImage = null;
1273 mjpegImage = null;
1274 for (const timer of retryTimers.values()) clearTimeout(timer);
1275 retryTimers.clear();
1276 primeController?.abort();
1277 primeController = null;
1278 controller?.abort();
1279 controller = null;
1280 closePeer();
1281 const discarded = socket;
1282 socket = null;
1283 discarded?.close();
1284 closeDecoder();
1285 };
1286​
1287 const send = (payload: Uint8Array<ArrayBuffer> | string) => {
1288 if (
1289 !stopped &&
1290 (!avcc || (iosInputAdmitted && !iosInputUnavailable)) &&
1291 socket?.readyState === WebSocket.OPEN
1293 socket.send(payload);
1294 };
1295​
1296 const rawPoint = (x: number, y: number) => {
1297 // serve-sim streams the raw framebuffer; rotated devices need input
1298 // remapped into that raw space.
1299 if (platform !== "ios" || !screen || screen.width > screen.height) return { x, y };
1300 switch (screen.orientation) {
1301 case "landscape_left":
1302 return { x: y, y: 1 - x };
1303 case "landscape_right":
1304 return { x: 1 - y, y: x };
1305 case "portrait_upside_down":
1306 return { x: 1 - x, y: 1 - y };
1307 default:
1308 return { x, y };
1310 };
1311​
1312 return {
1313 start,
1314 stop,
1315 setMjpegImage,
1316 controlDuo: duoControl.enqueue,
1317 sendRawTouch: (phase, x, y) => {
1318 if (platform === "ios") send(taggedJson(IOS_MSG_TOUCH, { type: phase, x, y }));
1319 },
1320 setDuoPanels(panels) {
1321 if (platform !== "ios" || target.videoOnly || stopped || panelSinks === panels) return;
1322 if (panels && !screen?.supportsHingeAngle) return;
1323 panelSinks = panels;
1324 videoGeneration++;
1325 controller?.abort();
1326 controller = null;
1327 closePeer();
1328 closeDecoder();
1329 const retry = retryTimers.get("video");
1330 if (retry) clearTimeout(retry);
1331 retryTimers.delete("video");
1332 for (const panel of panelClients) panel.stop();
1333 panelClients = [];
1334 if (!panels) {
1335 if (useWebCodecs) void readIosVideo();
1336 return;
1338 startDuoVideo(panels);
1339 },
1340 sendTouch: (phase, x, y) => {
1341 if (avcc) {
1342 send(taggedJson(IOS_MSG_TOUCH, { type: phase, ...rawPoint(x, y) }));
1343 return;
1345 const action = phase === "begin" ? "down" : phase === "move" ? "move" : "up";
1346 send(JSON.stringify({ type: "touch", action, x, y }));
1347 },
1348 sendKey: (event, phase) => {
1349 if (avcc) {
1350 const usage = hidUsageForCode(event.code);
1351 if (usage !== null) send(taggedJson(IOS_MSG_KEY, { type: phase, usage }));
1352 return;
1354 if (phase !== "down") return;
1355 if (event.key === "Escape") return send(JSON.stringify({ type: "back" }));
1356 const keycode = ANDROID_KEYCODE_BY_KEY[event.key];
1357 if (keycode !== undefined) return send(JSON.stringify({ type: "key", keycode }));
1358 if (event.key.length === 1 && !event.metaKey && !event.ctrlKey) {
1359 send(JSON.stringify({ type: "text", text: event.key }));
1361 },
1362 sendText: (text) => {
1363 if (avcc) return;
1364 let chunk = "";
1365 let chunkBytes = 0;
1366 let sentChunks = 0;
1367 for (const character of text) {
1368 const characterBytes = utf8ByteLength(character.codePointAt(0)!);
1369 if (chunkBytes + characterBytes > ANDROID_MAX_TEXT_BYTES) {
1370 send(JSON.stringify({ type: "text", text: chunk }));
1371 if (++sentChunks >= ANDROID_MAX_TEXT_CHUNKS) return;
1372 chunk = "";
1373 chunkBytes = 0;
1375 chunk += character;
1376 chunkBytes += characterBytes;
1378 if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk }));
1379 },
1380 pressButton: (button) => {
1381 if (avcc) {
1382 const name =
1383 button === "home"
1384 ? "home"
1385 : button === "appSwitcher" || button === "recents"
1386 ? "app_switcher"
1387 : button === "power"
1388 ? "lock"
1389 : button === "back" && platform === "android"
1390 ? "back"
1391 : null;
1392 if (name) send(taggedJson(IOS_MSG_BUTTON, { button: name }));
1393 return;
1395 const type = button === "appSwitcher" ? "recents" : button;
1396 if (type === "home" || type === "back" || type === "recents" || type === "power") {
1397 send(JSON.stringify({ type }));
1399 },
1400 rotate: () => {
1401 if (platform !== "ios") return;
1402 const current = screen?.supportsHingeAngle
1403 ? (rotationCursor ?? screen.orientation)
1404 : (screen?.orientation ?? "portrait");
1405 const next =
1406 IOS_ORIENTATIONS[(IOS_ORIENTATIONS.indexOf(current) + 1) % IOS_ORIENTATIONS.length]!;
1407 if (screen?.supportsHingeAngle) {
1408 rotationCursor = next;
1409 duoControl.enqueue({ control: "orientation", value: next });
1410 } else send(taggedJson(IOS_MSG_ORIENTATION, { orientation: next }));
1411 },
1412 setOrientation: (orientation) => {
1413 if (platform === "ios") send(taggedJson(IOS_MSG_ORIENTATION, { orientation }));
1414 },
1415 };