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

stream.ts

1,091 lines36.0 KB

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