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

stream.ts

1,434 lines50.5 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; serve-emu advertises WebRTC the same way. An
840 * unreadable answer keeps the default path.
841 */
842 const probeWebRtc = async (): Promise<WebRtcSettings | null> => {
843 const probe = new AbortController();
844 const timeout = setTimeout(() => probe.abort(), TRANSPORT_PROBE_TIMEOUT_MS);
845 try {
846 const response = await fetch(httpUrl(`/api?device=${device}`), {
847 signal: probe.signal,
848 credentials: access.credentials ? "include" : "same-origin",
849 });
850 if (!response.ok) return null;
851 const api = decodeServeSimApi(await response.json());
852 if (Option.isNone(api)) return null;
853 const settings = decodeWebRtcSettings(api.value.streamSettings ?? api.value.stream);
854 return Option.isSome(settings) ? settings.value : null;
855 } catch {
856 return null;
857 } finally {
858 clearTimeout(timeout);
859 }
860 };
861​
862 const webRtcUrl = (action: "offer" | "close") =>
863 httpUrl(avcc ? `/helper/${device}/webrtc/${action}` : `/webrtc/${action}?device=${device}`);
864​
865 const closePeer = () => {
866 const current = peer;
867 if (!current) return;
868 peer = null;
869 current.connection.close();
870 current.video.srcObject = null;
871 current.video.remove();
872 // Releases the capture session; best effort because the page may be unloading.
873 void fetch(webRtcUrl("close"), {
874 method: "POST",
875 keepalive: true,
876 headers: { "content-type": "application/json" },
877 body: JSON.stringify({ sessionId: current.sessionId }),
878 credentials: access.credentials ? "include" : "same-origin",
879 }).catch(() => {});
880 };
881​
882 const readWebRtc = async (settings: WebRtcSettings) => {
883 const lifecycle = generation;
884 const feedGeneration = ++videoGeneration;
885 closePeer();
886 const connection = new RTCPeerConnection({
887 ...(settings.iceServers
888 ? {
889 iceServers: settings.iceServers.map((server) => ({
890 ...server,
891 urls: typeof server.urls === "string" ? server.urls : [...server.urls],
892 })),
893 }
894 : {}),
895 iceTransportPolicy: settings.iceTransportPolicy ?? "all",
896 });
897 // Frames only reach requestVideoFrameCallback from a video that is in the
898 // document; it stays invisible because the sink paints them.
899 const video = document.createElement("video");
900 video.muted = true;
901 video.playsInline = true;
902 video.setAttribute("aria-hidden", "true");
903 video.style.cssText =
904 "position:fixed;width:1px;height:1px;opacity:0;pointer-events:none;left:0;top:0";
905 document.body.append(video);
906 const current = { connection, sessionId: webRtcSessionId(), video };
907 peer = current;
908 const isCurrent = () =>
909 !stopped &&
910 generation === lifecycle &&
911 videoGeneration === feedGeneration &&
912 peer === current;
913 // After the first frame nothing else bounds a feed that stops: the peer
914 // can sit `disconnected` with the last frame on the canvas. A long gap
915 // between frames reconnects through the same path as a failed connection.
916 let checksWithoutFrame = 0;
917 let watchdog: ReturnType<typeof setInterval> | null = null;
918 const clearWatchdog = () => {
919 if (watchdog !== null) clearInterval(watchdog);
920 watchdog = null;
921 };
922 const retry = (detail: string) => {
923 clearWatchdog();
924 if (!isCurrent()) return;
925 closePeer();
926 connecting(detail);
927 scheduleRetry("video", () => void readWebRtc(settings));
928 };
929 const presentFrame = () => {
930 if (!isCurrent()) {
931 clearWatchdog();
932 return;
933 }
934 if (video.videoWidth > 0 && video.videoHeight > 0) {
935 paint(video, video.videoWidth, video.videoHeight);
936 checksWithoutFrame = 0;
937 watchdog ??= setInterval(() => {
938 if (!isCurrent()) return clearWatchdog();
939 checksWithoutFrame++;
940 if (checksWithoutFrame * WEBRTC_STALL_CHECK_MS >= WEBRTC_STALL_TIMEOUT_MS) {
941 retry("Device stream stalled. Reconnecting…");
942 }
943 }, WEBRTC_STALL_CHECK_MS);
944 }
945 video.requestVideoFrameCallback(presentFrame);
946 };
947 const transceiver = connection.addTransceiver("video", { direction: "recvonly" });
948 const codecs = RTCRtpReceiver.getCapabilities("video")?.codecs ?? [];
949 if (codecs.length > 0) {
950 // serve-sim encodes H.264; other codecs stay as fallbacks it may refuse.
951 transceiver.setCodecPreferences([
952 ...codecs.filter((codec) => codec.mimeType.toLowerCase() === "video/h264"),
953 ...codecs.filter((codec) => codec.mimeType.toLowerCase() !== "video/h264"),
954 ]);
955 }
956 connection.ontrack = (event) => {
957 if (!isCurrent()) return;
958 iceGatheringDeadlineMs = ICE_GATHERING_TIMEOUT_MS;
959 video.srcObject = event.streams[0] ?? new MediaStream([event.track]);
960 void video.play().catch(() => {});
961 video.requestVideoFrameCallback(presentFrame);
962 };
963 connection.onconnectionstatechange = () => {
964 if (connection.connectionState === "failed")
965 retry("Device stream connection failed. Reconnecting…");
966 };
967 try {
968 await connection.setLocalDescription(await connection.createOffer());
969 const gathered = await new Promise<boolean>((resolve) => {
970 if (connection.iceGatheringState === "complete") return resolve(true);
971 const timer = setTimeout(() => done(false), iceGatheringDeadlineMs);
972 function done(complete: boolean) {
973 clearTimeout(timer);
974 connection.removeEventListener("icegatheringstatechange", changed);
975 resolve(complete);
976 }
977 function changed() {
978 if (connection.iceGatheringState === "complete") done(true);
979 }
980 connection.addEventListener("icegatheringstatechange", changed);
981 });
982 if (!isCurrent()) return;
983 // serve-sim takes all candidates in the offer; later candidates never trickle.
984 // Cloud simulators need a reflexive or relay candidate, so retry incomplete offers with
985 // longer deadlines up to the bound, then send what was gathered.
986 const sdp = connection.localDescription?.sdp ?? "";
987 if (
988 !gathered &&
989 !/^a=candidate:.* typ (?:srflx|relay)\b/m.test(sdp) &&
990 iceGatheringDeadlineMs < ICE_GATHERING_MAX_TIMEOUT_MS
991 ) {
992 iceGatheringDeadlineMs = Math.min(iceGatheringDeadlineMs * 2, ICE_GATHERING_MAX_TIMEOUT_MS);
993 return retry("Device stream found no network candidates yet. Retrying…");
994 }
995 const response = await fetch(webRtcUrl("offer"), {
996 method: "POST",
997 headers: { "content-type": "application/json" },
998 body: JSON.stringify({
999 type: "offer",
1000 sdp: connection.localDescription?.sdp,
1001 sessionId: current.sessionId,
1002 codec: "h264",
1003 }),
1004 credentials: access.credentials ? "include" : "same-origin",
1005 });
1006 if (!isCurrent()) {
1007 await response.body?.cancel();
1008 return;
1010 if (response.status === 401 || response.status === 403) return handleUnauthorized();
1011 // 409: another viewer is still negotiating with this simulator.
1012 if (!response.ok) return retry(`Device stream offer failed (${response.status}). Retrying…`);
1013 const answer = decodeWebRtcAnswer(await response.json());
1014 if (!isCurrent()) return;
1015 if (Option.isNone(answer))
1016 return retry("Device stream returned an invalid answer. Retrying…");
1017 await connection.setRemoteDescription(answer.value);
1018 } catch (cause) {
1019 retry((cause as Error).message);
1021 };
1022​
1023 /**
1024 * Called once AVCC or MJPEG was refused. `locked` means serve-sim already
1025 * said it streams WebRTC only, so a missing /api answer still switches.
1026 */
1027 const switchToWebRtc = async (failure: string, locked: boolean) => {
1028 const session = generation;
1029 if (typeof RTCPeerConnection === "undefined") return fail(failure);
1030 const settings = (await probeWebRtc()) ?? (locked ? { transport: "webrtc" as const } : null);
1031 if (stopped || generation !== session) return;
1032 if (!settings) return fail(failure);
1033 if (mjpeg) {
1034 mjpeg = false;
1035 releaseImage?.();
1036 releaseImage = null;
1037 events.onCanvasVideo?.();
1039 // MJPEG may have shown frames already: say the stream is connecting again
1040 // rather than leave a blank canvas until the first WebRTC frame.
1041 connecting("Switching to WebRTC.");
1042 void readWebRtc(settings);
1043 };
1044​
1045 const startDuoVideo = (panels: DuoPanelSinks) => {
1046 for (const panel of panelClients) panel.stop();
1047 // Physical handoff elects a native surface. Fixed-panel encoders can keep
1048 // an inactive shutdown frame after election, so this build uses one active
1049 // feed instead of decoding a third stream alongside the two fixed feeds.
1050 const ids = screen?.supportsPhysicalOrientation ? ([null] as const) : ([1, 3] as const);
1051 panelClients = ids.map((id) => {
1052 const output = id === 1 ? panels.cover : panels.inner;
1053 return createDeviceStreamClient(
1054 { ...target, ...(id === null ? {} : { panelId: id }), videoOnly: true },
1056 present(source, width, height) {
1057 if (id === null) {
1058 return sink.present(source, width, height);
1060 // An inactive native LCD can emit its shutdown black frame. Retain its last useful image.
1061 if (screen?.screenId !== id) return true;
1062 const retained = output.present(source, width, height);
1063 const primary = sink.present(source, width, height);
1064 return retained && primary;
1065 },
1066 },
1068 onStatus: (status, detail) => {
1069 if (status === "error") events.onDuoUnavailable?.(detail);
1070 },
1071 onScreen: () => {},
1072 onInputConnected: () => {},
1073 onMjpegFallback: () => {},
1074 onUnauthorized: handleUnauthorized,
1075 },
1076 );
1077 });
1078 for (const panel of panelClients) panel.start();
1079 };
1080​
1081 const connectIosInput = async () => {
1082 if (stopped) return;
1083 const session = generation;
1084 if (!serveSimOnly) await primeIosHelper(session);
1085 if (stopped || generation !== session) return;
1086 const ws = new WebSocket(wsUrl(`/helper/ws?device=${device}`));
1087 ws.binaryType = "arraybuffer";
1088 socket = ws;
1089 iosInputAdmitted = false;
1090 iosInputUnavailable = false;
1091 ws.onmessage = (event) => {
1092 if (stopped || socket !== ws) return;
1093 if (!(event.data instanceof ArrayBuffer)) return;
1094 const bytes = new Uint8Array(event.data);
1095 if (socket !== ws || stopped || bytes.length < 1) return;
1096 if (bytes[0] === IOS_TAG_INPUT_ADMITTED) {
1097 iosInputAdmitted = true;
1098 events.onInputConnected(!iosInputUnavailable);
1099 return;
1101 try {
1102 const payload: unknown = JSON.parse(decoder.decode(bytes.subarray(1)));
1103 if (bytes[0] === 0x90) {
1104 const reply = decodeControlReply(payload);
1105 if (Option.isSome(reply)) duoControl.receive(reply.value);
1106 } else if (bytes[0] === IOS_TAG_SCREEN_CONFIG) {
1107 const config = decodeScreenConfig(payload);
1108 if (Option.isSome(config)) {
1109 iosInputUnavailable = config.value.inputUnavailable === true;
1110 events.onInputConnected(
1111 iosInputAdmitted && !iosInputUnavailable,
1112 iosInputUnavailable ? "Simulator input is unavailable" : undefined,
1113 );
1114 const previous = screen;
1115 screen = config.value;
1116 if (screen.hingePose && screen.hingePose !== previous?.hingePose)
1117 rotationCursor = screen.hingePose === "laptop" ? "landscape_left" : "portrait";
1118 else if (screen.orientation !== previous?.orientation)
1119 rotationCursor = screen.orientation;
1120 panelSinks?.onScreen?.(screen);
1121 events.onScreen(screen);
1122 // A surface election can leave an existing decoder on the former
1123 // encoder description. Reopen only video to acquire the elected
1124 // surface's seed and codec configuration; HID and the viewer stay.
1125 if (
1126 panelSinks &&
1127 screen.supportsPhysicalOrientation &&
1128 previous &&
1129 screen.screenId !== previous.screenId
1131 startDuoVideo(panelSinks);
1132 if (pendingOrientation) {
1133 const receipt = pendingOrientation;
1134 pendingOrientation = null;
1135 duoControl.receive({
1136 requestId: receipt.requestId,
1137 ok: true,
1138 });
1142 } catch {}
1143 };
1144 ws.onclose = (event) => {
1145 if (socket !== ws) return;
1146 socket = null;
1147 iosInputAdmitted = false;
1148 duoControl.clear();
1149 rotationCursor = null;
1150 if (stopped) return;
1151 events.onInputConnected(
1152 false,
1153 event.reason || (event.code === 1006 ? "input socket refused" : `closed ${event.code}`),
1154 );
1155 // A rejected HTTP upgrade surfaces as 1006, including an expired stream ticket.
1156 if (
1157 event.code === 1008 ||
1158 event.code === 4401 ||
1159 (event.code === 1006 && access.query.wsTicket)
1161 return handleUnauthorized();
1162 scheduleRetry("input", () => void connectIosInput());
1163 };
1164 ws.onerror = () => ws.close();
1165 };
1166​
1167 /** `inputOnly` keeps a socket for input beside a WebRTC feed, so its reconnects leave video alone. */
1168 const connectAndroid = (inputOnly = false) => {
1169 if (stopped) return;
1170 const ws = new WebSocket(
1171 wsUrl(`/ws?device=${device}&${inputOnly ? "video=0" : "frame-meta=1"}`),
1172 );
1173 ws.binaryType = "arraybuffer";
1174 socket = ws;
1175 ws.onopen = () => {
1176 if (stopped || socket !== ws) return;
1177 if (!inputOnly) connecting();
1178 events.onInputConnected(true);
1179 };
1180 ws.onmessage = (event) => {
1181 if (stopped || socket !== ws || inputOnly) return;
1182 if (typeof event.data === "string") {
1183 // The encoder restarts at a new size when the device rotates; the
1184 // next keyframe carries a fresh SPS, so the decoder is rebuilt from it.
1185 if (isVideoSessionMessage(event.data)) {
1186 closeDecoder();
1187 configuring = false;
1188 connecting();
1189 requestKeyframe();
1191 return;
1193 if (!(event.data instanceof ArrayBuffer)) return;
1194 const packet = parseSemuPacket(event.data);
1195 const needsScan =
1196 packet.isKey === null ||
1197 (packet.isKey && (!videoDecoder || videoDecoder.state !== "configured"));
1198 const scanned = needsScan ? scanAccessUnit(packet.data) : null;
1199 const isKey = packet.isKey ?? scanned?.isKey ?? false;
1200 if (scanned?.sps && (!videoDecoder || videoDecoder.state !== "configured")) {
1201 if (configuring) return;
1202 configuring = true;
1203 const epoch = decoderEpoch;
1204 const isCurrent = () => !stopped && socket === ws;
1205 void configureDecoder({ codec: avcCodecString(scanned.sps) }, isCurrent).then(
1206 (configured) => {
1207 if (!isCurrent() || epoch !== decoderEpoch) return;
1208 configuring = false;
1209 awaitingKeyframe = true;
1210 if (configured) requestKeyframe();
1211 },
1212 );
1213 return;
1215 if (!videoDecoder || videoDecoder.state !== "configured") {
1216 if (!isKey) requestKeyframe();
1217 return;
1219 decode(isKey, packet.data, packet.timestamp);
1220 };
1221 ws.onclose = (event) => {
1222 if (socket !== ws) return;
1223 socket = null;
1224 closeDecoder();
1225 if (stopped) return;
1226 events.onInputConnected(false, event.reason || `closed ${event.code}`);
1227 if (
1228 event.code === 1008 ||
1229 event.code === 4401 ||
1230 (event.code === 1006 && access.query.wsTicket)
1232 return handleUnauthorized();
1233 if (!inputOnly) {
1234 configuring = false;
1235 connecting(event.reason || undefined);
1237 // A full socket re-probes, so one failed /api read does not pin SEMU on a WebRTC host.
1238 scheduleRetry("input", () => (inputOnly ? connectAndroid(true) : void startAndroid()));
1239 };
1240 ws.onerror = () => ws.close();
1241 };
1242​
1243 const startAndroid = async () => {
1244 const session = generation;
1245 const settings = await probeWebRtc();
1246 if (stopped || generation !== session) return;
1247 if (settings) {
1248 if (typeof RTCPeerConnection === "undefined")
1249 return fail("This browser cannot receive the device's WebRTC stream.");
1250 if (!target.videoOnly) connectAndroid(true);
1251 void readWebRtc(settings);
1252 } else if (useWebCodecs) connectAndroid();
1253 else fail("This browser cannot decode the Android stream (WebCodecs unavailable).");
1254 };
1255​
1256 const start = () => {
1257 if (!stopped) return;
1258 stopped = false;
1259 generation++;
1260 configuring = false;
1261 iosInputAdmitted = false;
1262 iosInputUnavailable = false;
1263 connecting();
1264 if (serveSimOnly) {
1265 if (!target.videoOnly) void connectIosInput();
1266 if (useWebCodecs) void readIosVideo();
1267 else fail("This browser cannot decode this device's stream (WebCodecs unavailable).");
1268 } else if (platform === "ios") {
1269 if (!target.videoOnly) void connectIosInput();
1270 if (useWebCodecs) void readIosVideo();
1271 else fallBackToMjpeg();
1272 } else void startAndroid();
1273 };
1274​
1275 const stop = () => {
1276 if (stopped) return;
1277 stopped = true;
1278 generation++;
1279 videoGeneration++;
1280 duoControl.clear();
1281 rotationCursor = null;
1282 for (const panel of panelClients) panel.stop();
1283 panelClients = [];
1284 panelSinks = null;
1285 mjpeg = false;
1286 clearFrameTimer();
1287 if (videoReadTimer !== null) clearTimeout(videoReadTimer);
1288 videoReadTimer = null;
1289 releaseImage?.();
1290 releaseImage = null;
1291 mjpegImage = null;
1292 for (const timer of retryTimers.values()) clearTimeout(timer);
1293 retryTimers.clear();
1294 primeController?.abort();
1295 primeController = null;
1296 controller?.abort();
1297 controller = null;
1298 closePeer();
1299 const discarded = socket;
1300 socket = null;
1301 discarded?.close();
1302 closeDecoder();
1303 };
1304​
1305 const send = (payload: Uint8Array<ArrayBuffer> | string) => {
1306 if (
1307 !stopped &&
1308 (!avcc || (iosInputAdmitted && !iosInputUnavailable)) &&
1309 socket?.readyState === WebSocket.OPEN
1311 socket.send(payload);
1312 };
1313​
1314 const rawPoint = (x: number, y: number) => {
1315 // serve-sim streams the raw framebuffer; rotated devices need input
1316 // remapped into that raw space.
1317 if (platform !== "ios" || !screen || screen.width > screen.height) return { x, y };
1318 switch (screen.orientation) {
1319 case "landscape_left":
1320 return { x: y, y: 1 - x };
1321 case "landscape_right":
1322 return { x: 1 - y, y: x };
1323 case "portrait_upside_down":
1324 return { x: 1 - x, y: 1 - y };
1325 default:
1326 return { x, y };
1328 };
1329​
1330 return {
1331 start,
1332 stop,
1333 setMjpegImage,
1334 controlDuo: duoControl.enqueue,
1335 sendRawTouch: (phase, x, y) => {
1336 if (platform === "ios") send(taggedJson(IOS_MSG_TOUCH, { type: phase, x, y }));
1337 },
1338 setDuoPanels(panels) {
1339 if (platform !== "ios" || target.videoOnly || stopped || panelSinks === panels) return;
1340 if (panels && !screen?.supportsHingeAngle) return;
1341 panelSinks = panels;
1342 videoGeneration++;
1343 controller?.abort();
1344 controller = null;
1345 closePeer();
1346 closeDecoder();
1347 const retry = retryTimers.get("video");
1348 if (retry) clearTimeout(retry);
1349 retryTimers.delete("video");
1350 for (const panel of panelClients) panel.stop();
1351 panelClients = [];
1352 if (!panels) {
1353 if (useWebCodecs) void readIosVideo();
1354 return;
1356 startDuoVideo(panels);
1357 },
1358 sendTouch: (phase, x, y) => {
1359 if (avcc) {
1360 send(taggedJson(IOS_MSG_TOUCH, { type: phase, ...rawPoint(x, y) }));
1361 return;
1363 const action = phase === "begin" ? "down" : phase === "move" ? "move" : "up";
1364 send(JSON.stringify({ type: "touch", action, x, y }));
1365 },
1366 sendKey: (event, phase) => {
1367 if (avcc) {
1368 const usage = hidUsageForCode(event.code);
1369 if (usage !== null) send(taggedJson(IOS_MSG_KEY, { type: phase, usage }));
1370 return;
1372 if (phase !== "down") return;
1373 if (event.key === "Escape") return send(JSON.stringify({ type: "back" }));
1374 const keycode = ANDROID_KEYCODE_BY_KEY[event.key];
1375 if (keycode !== undefined) return send(JSON.stringify({ type: "key", keycode }));
1376 if (event.key.length === 1 && !event.metaKey && !event.ctrlKey) {
1377 send(JSON.stringify({ type: "text", text: event.key }));
1379 },
1380 sendText: (text) => {
1381 if (avcc) return;
1382 let chunk = "";
1383 let chunkBytes = 0;
1384 let sentChunks = 0;
1385 for (const character of text) {
1386 const characterBytes = utf8ByteLength(character.codePointAt(0)!);
1387 if (chunkBytes + characterBytes > ANDROID_MAX_TEXT_BYTES) {
1388 send(JSON.stringify({ type: "text", text: chunk }));
1389 if (++sentChunks >= ANDROID_MAX_TEXT_CHUNKS) return;
1390 chunk = "";
1391 chunkBytes = 0;
1393 chunk += character;
1394 chunkBytes += characterBytes;
1396 if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk }));
1397 },
1398 pressButton: (button) => {
1399 if (avcc) {
1400 const name =
1401 button === "home"
1402 ? "home"
1403 : button === "appSwitcher" || button === "recents"
1404 ? "app_switcher"
1405 : button === "power"
1406 ? "lock"
1407 : button === "back" && platform === "android"
1408 ? "back"
1409 : null;
1410 if (name) send(taggedJson(IOS_MSG_BUTTON, { button: name }));
1411 return;
1413 const type = button === "appSwitcher" ? "recents" : button;
1414 if (type === "home" || type === "back" || type === "recents" || type === "power") {
1415 send(JSON.stringify({ type }));
1417 },
1418 rotate: () => {
1419 if (platform !== "ios") return;
1420 const current = screen?.supportsHingeAngle
1421 ? (rotationCursor ?? screen.orientation)
1422 : (screen?.orientation ?? "portrait");
1423 const next =
1424 IOS_ORIENTATIONS[(IOS_ORIENTATIONS.indexOf(current) + 1) % IOS_ORIENTATIONS.length]!;
1425 if (screen?.supportsHingeAngle) {
1426 rotationCursor = next;
1427 duoControl.enqueue({ control: "orientation", value: next });
1428 } else send(taggedJson(IOS_MSG_ORIENTATION, { orientation: next }));
1429 },
1430 setOrientation: (orientation) => {
1431 if (platform === "ios") send(taggedJson(IOS_MSG_ORIENTATION, { orientation }));
1432 },
1433 };