Skip to content
TypeScript

feat(device): stream iOS devices that serve WebRTC only (#21841)

Julius Marminge6dc63bd85bf6
diff --git a/apps/mobile/src/features/devices/device-stream.browser.ts b/apps/mobile/src/features/devices/device-stream.browser.ts
index d1ec539b8da..ed2092148d0 100644
--- a/apps/mobile/src/features/devices/device-stream.browser.ts
+++ b/apps/mobile/src/features/devices/device-stream.browser.ts
@@ -140,6 +140,10 @@ export function start(configuration: DeviceStreamConfiguration) {
canvas.style.display = "none";
image.style.display = "block";
},
+ onCanvasVideo: () => {
+ image.style.display = "none";
+ canvas.style.display = "";
+ },
onUnauthorized: unauthorized,
onInputConnected: (connected) => {
inputConnected = connected;
diff --git a/apps/server/src/device/DeviceHubProxy.test.ts b/apps/server/src/device/DeviceHubProxy.test.ts
index bda888b1ea7..53f4a061244 100644
--- a/apps/server/src/device/DeviceHubProxy.test.ts
+++ b/apps/server/src/device/DeviceHubProxy.test.ts
@@ -152,6 +152,21 @@ describe("device hub proxy", () => {
expect(headers[0]).not.toHaveProperty("x-forwarded-proto");
});
+ it("lets a viewer negotiate a WebRTC stream with read scope", async () => {
+ const { handler, requests, headers } = fixture([AuthOrchestrationReadScope]);
+ const offer = await handler(
+ new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/udid-1/webrtc/offer", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: '{"type":"offer"}',
+ }),
+ );
+ expect(offer.status).toBe(200);
+ await offer.text();
+ expect(requests).toEqual(["http://hub.test/vendor/serve-sim/helper/udid-1/webrtc/offer"]);
+ expect(headers[0]?.["content-type"]).toBe("application/json");
+ });
+
it("never forwards the vendor shell endpoint", async () => {
const { handler, requests } = fixture([AuthOrchestrationOperateScope]);
expect(
diff --git a/apps/server/src/device/DeviceHubProxy.ts b/apps/server/src/device/DeviceHubProxy.ts
index 8f3070231a3..a0a8a5f5d0a 100644
--- a/apps/server/src/device/DeviceHubProxy.ts
+++ b/apps/server/src/device/DeviceHubProxy.ts
@@ -28,6 +28,7 @@ const ALLOWED_PATHS: ReadonlyArray<RegExp> = [
/^\/vendor\/serve-sim\/api\/event-log(\/events)?$/,
/^\/vendor\/serve-sim\/helper\/[^/]+\/(stream\.mjpeg|stream\.avcc|config|health|ax|foreground)$/,
/^\/vendor\/serve-sim\/helper\/[^/]+\/panel\/(1|3)\/stream\.avcc$/,
+ /^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/,
/^\/vendor\/serve-sim\/appstate$/,
/^\/vendor\/serve-emu\/api\/(devices|screenshot|stream-mode|stream-settings|accessibility|fold)$/,
/^\/vendor\/serve-emu\/health$/,
@@ -35,6 +36,8 @@ const ALLOWED_PATHS: ReadonlyArray<RegExp> = [
const MUTABLE_PATHS: ReadonlyArray<RegExp> = [
/^\/vendor\/serve-sim\/api\/screenshot$/,
+ // WebRTC signalling: opening and closing a view of the stream, so read scope.
+ /^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/,
/^\/vendor\/serve-emu\/api\/(screenshot|stream-mode|stream-settings)$/,
/^\/vendor\/serve-emu\/api\/fold$/,
];
@@ -120,7 +123,11 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* (
HttpClientRequest.setHeaders(forwardHeaders(request, hubOrigin)),
method === "GET" || method === "HEAD"
? (self) => self
- : HttpClientRequest.bodyStream(request.stream),
+ : // A bare stream body is sent as octet-stream; serve-sim refuses WebRTC
+ // offers that are not application/json.
+ HttpClientRequest.bodyStream(request.stream, {
+ contentType: request.headers["content-type"],
+ }),
);
const response = yield* httpClient.execute(upstreamRequest);
const headers: Record<string, string> = {};
diff --git a/apps/web/src/components/device/DeviceStreamView.tsx b/apps/web/src/components/device/DeviceStreamView.tsx
index 18b70e5421a..8a37cbbbdab 100644
--- a/apps/web/src/components/device/DeviceStreamView.tsx
+++ b/apps/web/src/components/device/DeviceStreamView.tsx
@@ -164,6 +164,7 @@ export function DeviceStreamView(props: {
setMjpegUrl(url);
setMjpegGeneration((generation) => generation + 1);
},
+ onCanvasVideo: () => setMjpegUrl(null),
onInputConnected: (connected, detail) => {
setInputState({ connected, ...(detail ? { detail } : {}) });
if (!connected) setShowRestartNotice(false);
diff --git a/docs/internals/devices.md b/docs/internals/devices.md
index b3b93692886..b57b9dc8d71 100644
--- a/docs/internals/devices.md
+++ b/docs/internals/devices.md
@@ -91,3 +91,10 @@ Simulators encode H.264 High 5.1. Hardware decoders on some machines and all
headless browsers reject that profile, and WebCodecs is secure-context only, so
the viewer probes `isConfigSupported` and falls back to the MJPEG endpoint on
iOS. Android has no MJPEG; there the panel reports that it cannot decode.
+
+serve-sim can also be locked to WebRTC, as on EAS Simulator, and then refuses
+AVCC with a 409 naming the transport. The viewer still asks for AVCC first, so
+hubs that serve it pay nothing, and switches on that 409, or when its MJPEG
+image fails in a browser that has `RTCPeerConnection`. Offers are not trickled:
+serve-sim takes one offer with every candidate. The video element only feeds
+the same canvas sink, so the panel and the mobile WebView keep one surface.
diff --git a/packages/client-runtime/src/device/stream.test.ts b/packages/client-runtime/src/device/stream.test.ts
index 93b786cfed9..be60d8db9b3 100644
--- a/packages/client-runtime/src/device/stream.test.ts
+++ b/packages/client-runtime/src/device/stream.test.ts
@@ -923,3 +923,280 @@ it("reopens a stalled AVCC body without disconnecting input, then receives fresh
vi.unstubAllGlobals();
}
});
+
+describe("WebRTC-only iOS devices", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ function webRtcFixture(options: {
+ webCodecs: boolean;
+ offerStatuses?: number[];
+ /** The fake peer's ICE gathering state; `gathering` never completes. */
+ iceGatheringState?: "complete" | "gathering";
+ }) {
+ vi.useFakeTimers();
+ if (options.webCodecs) {
+ vi.stubGlobal("VideoDecoder", vi.fn());
+ vi.stubGlobal("EncodedVideoChunk", vi.fn());
+ }
+ class FakeSocket {
+ static OPEN = 1;
+ readyState = 1;
+ binaryType = "";
+ onmessage: unknown = null;
+ onclose: unknown = null;
+ onerror: unknown = null;
+ send = vi.fn();
+ close = vi.fn();
+ }
+ vi.stubGlobal("WebSocket", FakeSocket);
+ const peers: FakePeer[] = [];
+ class FakePeer {
+ iceGatheringState = options.iceGatheringState ?? "complete";
+ connectionState = "new";
+ localDescription: { type: string; sdp: string } | null = null;
+ remoteDescription: unknown = null;
+ ontrack: ((event: { streams: unknown[]; track: unknown }) => void) | null = null;
+ onconnectionstatechange: (() => void) | null = null;
+ closed = false;
+ readonly config: unknown;
+ readonly codecPreferences = vi.fn();
+ constructor(config: unknown) {
+ this.config = config;
+ peers.push(this);
+ }
+ addTransceiver() {
+ return { setCodecPreferences: this.codecPreferences };
+ }
+ async createOffer() {
+ return { type: "offer", sdp: "v=0 offer" };
+ }
+ async setLocalDescription(description: { type: string; sdp: string }) {
+ this.localDescription = description;
+ }
+ async setRemoteDescription(description: unknown) {
+ this.remoteDescription = description;
+ }
+ addEventListener() {}
+ removeEventListener() {}
+ close() {
+ this.closed = true;
+ }
+ }
+ vi.stubGlobal("RTCPeerConnection", FakePeer);
+ vi.stubGlobal("RTCRtpReceiver", {
+ getCapabilities: () => ({ codecs: [{ mimeType: "video/VP8" }, { mimeType: "video/H264" }] }),
+ });
+ const frameCallbacks: Array<() => void> = [];
+ const video = {
+ muted: false,
+ playsInline: false,
+ srcObject: null as unknown,
+ videoWidth: 402,
+ videoHeight: 874,
+ style: { cssText: "" },
+ setAttribute: vi.fn(),
+ remove: vi.fn(),
+ play: vi.fn(() => Promise.resolve()),
+ requestVideoFrameCallback: vi.fn((callback: () => void) => {
+ frameCallbacks.push(callback);
+ }),
+ };
+ vi.stubGlobal("document", { createElement: () => video, body: { append: vi.fn() } });
+ const offerStatuses = [...(options.offerStatuses ?? [])];
+ const fetch = vi.fn((url: string) => {
+ const path = new URL(url).pathname;
+ if (path.endsWith("/stream.avcc"))
+ return Promise.resolve(
+ Response.json({ error: "stream_transport_locked", transport: "webrtc" }, { status: 409 }),
+ );
+ if (path.endsWith("/vendor/serve-sim/api"))
+ return Promise.resolve(
+ Response.json({
+ streamSettings: { transport: "webrtc", iceServers: [{ urls: ["stun:stun.test"] }] },
+ }),
+ );
+ if (path.endsWith("/webrtc/offer")) {
+ const status = offerStatuses.shift() ?? 200;
+ return Promise.resolve(
+ status === 200
+ ? Response.json({ type: "answer", sdp: "v=0 answer" })
+ : Response.json({ error: "webrtc_session_busy" }, { status }),
+ );
+ }
+ if (path.endsWith("/webrtc/close"))
+ return Promise.resolve(new Response(null, { status: 204 }));
+ return Promise.resolve(new Response("refused", { status: 409 }));
+ });
+ vi.stubGlobal("fetch", fetch);
+ const presented: Array<[unknown, number, number]> = [];
+ const events = {
+ onStatus: vi.fn(),
+ onScreen: vi.fn(),
+ onUnauthorized: vi.fn(),
+ onMjpegFallback: vi.fn(),
+ onCanvasVideo: vi.fn(),
+ onInputConnected: vi.fn(),
+ };
+ const client = createDeviceStreamClient(
+ {
+ platform: "ios",
+ deviceId: "udid-1",
+ preferMjpeg: !options.webCodecs,
+ access: {
+ httpBase: "https://environment.test/api/device-hub",
+ wsBase: "wss://environment.test/api/device-hub",
+ credentials: false,
+ query: { hostId: "eas" },
+ },
+ },
+ {
+ present: (source, width, height) => {
+ presented.push([source, width, height]);
+ return true;
+ },
+ },
+ events,
+ );
+ const requests = (suffix: string) =>
+ fetch.mock.calls.filter(([url]) => new URL(url).pathname.endsWith(suffix));
+ const bodyOf = (call: unknown[]) =>
+ JSON.parse(String((call[1] as RequestInit | undefined)?.body)) as Record<string, unknown>;
+ const settle = async () => {
+ for (let turn = 0; turn < 20; turn++) await vi.advanceTimersByTimeAsync(0);
+ };
+ return { client, peers, video, frameCallbacks, presented, events, requests, bodyOf, settle };
+ }
+
+ it("switches to WebRTC when serve-sim refuses AVCC and releases the session on stop", async () => {
+ const fixture = webRtcFixture({ webCodecs: true });
+ fixture.client.start();
+ await fixture.settle();
+ expect(fixture.peers).toHaveLength(1);
+ const peer = fixture.peers[0]!;
+ expect(peer.config).toEqual({
+ iceServers: [{ urls: ["stun:stun.test"] }],
+ iceTransportPolicy: "all",
+ });
+ expect(peer.codecPreferences).toHaveBeenCalledWith([
+ { mimeType: "video/H264" },
+ { mimeType: "video/VP8" },
+ ]);
+ const offers = fixture.requests("/helper/udid-1/webrtc/offer");
+ expect(offers).toHaveLength(1);
+ const offer = fixture.bodyOf(offers[0]!);
+ expect(offer).toMatchObject({ type: "offer", sdp: "v=0 offer", codec: "h264" });
+ expect(offer.sessionId).toMatch(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
+ );
+ expect(peer.remoteDescription).toEqual({ type: "answer", sdp: "v=0 answer" });
+
+ peer.ontrack?.({ streams: [{}], track: {} });
+ fixture.frameCallbacks.shift()?.();
+ expect(fixture.presented).toEqual([[fixture.video, 402, 874]]);
+ expect(fixture.events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
+
+ fixture.client.stop();
+ expect(peer.closed).toBe(true);
+ expect(fixture.video.remove).toHaveBeenCalled();
+ const closes = fixture.requests("/helper/udid-1/webrtc/close");
+ expect(closes.map(fixture.bodyOf)).toEqual([{ sessionId: offer.sessionId }]);
+ });
+
+ it("reconnects a WebRTC feed that stops producing frames", async () => {
+ const fixture = webRtcFixture({ webCodecs: true });
+ fixture.client.start();
+ await fixture.settle();
+ const peer = fixture.peers[0]!;
+ peer.ontrack?.({ streams: [{}], track: {} });
+ fixture.frameCallbacks.shift()?.();
+ expect(fixture.events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
+ // Frames keep coming: nothing happens.
+ await vi.advanceTimersByTimeAsync(10_000);
+ fixture.frameCallbacks.shift()?.();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(fixture.peers).toHaveLength(1);
+ expect(peer.closed).toBe(false);
+ // Then none for the first-frame deadline (checked every 5 s): the feed
+ // reconnects through the usual retry path.
+ await vi.advanceTimersByTimeAsync(15_000);
+ expect(peer.closed).toBe(true);
+ expect(fixture.events.onStatus).toHaveBeenLastCalledWith(
+ "connecting",
+ "Device stream stalled. Reconnecting…",
+ );
+ await vi.advanceTimersByTimeAsync(1_000);
+ await fixture.settle();
+ expect(fixture.peers).toHaveLength(2);
+ expect(fixture.peers[1]!.remoteDescription).toEqual({ type: "answer", sdp: "v=0 answer" });
+ fixture.client.stop();
+ });
+
+ it("retries instead of offering when ICE gathering times out without a candidate", async () => {
+ const fixture = webRtcFixture({ webCodecs: true, iceGatheringState: "gathering" });
+ fixture.client.start();
+ await fixture.settle();
+ expect(fixture.peers).toHaveLength(1);
+ expect(fixture.requests("/helper/udid-1/webrtc/offer")).toHaveLength(0);
+ // The gathering deadline passes with no reflexive or relay candidate: no
+ // offer is sent, the attempt is retried with twice the deadline.
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(fixture.peers[0]!.closed).toBe(true);
+ expect(fixture.requests("/helper/udid-1/webrtc/offer")).toHaveLength(0);
+ expect(fixture.events.onStatus).toHaveBeenLastCalledWith(
+ "connecting",
+ "Device stream found no network candidates yet. Retrying…",
+ );
+ await vi.advanceTimersByTimeAsync(1_000);
+ await fixture.settle();
+ expect(fixture.peers).toHaveLength(2);
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(fixture.peers[1]!.closed).toBe(false);
+ // The second deadline, 4 s, is the bound: the offer goes as gathered.
+ await vi.advanceTimersByTimeAsync(3_000);
+ await fixture.settle();
+ expect(fixture.peers).toHaveLength(2);
+ expect(fixture.peers[1]!.closed).toBe(false);
+ expect(fixture.requests("/helper/udid-1/webrtc/offer")).toHaveLength(1);
+ fixture.client.stop();
+ });
+
+ it("retries a WebRTC offer while another viewer is negotiating", async () => {
+ const fixture = webRtcFixture({ webCodecs: true, offerStatuses: [409] });
+ fixture.client.start();
+ await fixture.settle();
+ expect(fixture.peers).toHaveLength(1);
+ expect(fixture.peers[0]!.closed).toBe(true);
+ await vi.advanceTimersByTimeAsync(1_000);
+ await fixture.settle();
+ expect(fixture.peers).toHaveLength(2);
+ expect(fixture.peers[1]!.remoteDescription).toEqual({ type: "answer", sdp: "v=0 answer" });
+ fixture.client.stop();
+ });
+
+ it("moves an MJPEG viewer back to the canvas for a WebRTC-only device", async () => {
+ const fixture = webRtcFixture({ webCodecs: false });
+ const listeners: Record<string, () => void> = {};
+ const image = {
+ naturalWidth: 0,
+ naturalHeight: 0,
+ src: "",
+ addEventListener: (type: string, listener: () => void) => {
+ listeners[type] = listener;
+ },
+ removeEventListener: vi.fn(),
+ removeAttribute: vi.fn(),
+ };
+ fixture.client.start();
+ fixture.client.setMjpegImage(image as unknown as HTMLImageElement);
+ expect(fixture.events.onMjpegFallback).toHaveBeenCalledOnce();
+ listeners.error?.();
+ await fixture.settle();
+ expect(fixture.events.onCanvasVideo).toHaveBeenCalledOnce();
+ expect(fixture.peers).toHaveLength(1);
+ expect(fixture.requests("/helper/udid-1/webrtc/offer")).toHaveLength(1);
+ fixture.client.stop();
+ });
+});
diff --git a/packages/client-runtime/src/device/stream.ts b/packages/client-runtime/src/device/stream.ts
index b9cdcb7a56b..9318c50fe69 100644
--- a/packages/client-runtime/src/device/stream.ts
+++ b/packages/client-runtime/src/device/stream.ts
@@ -57,6 +57,33 @@ const controlReplySchema = Schema.Struct({
});
const decodeScreenConfig = Schema.decodeUnknownOption(screenConfigSchema);
const decodeControlReply = Schema.decodeUnknownOption(controlReplySchema);
+const iceServerSchema = Schema.Struct({
+ urls: Schema.Union([Schema.String, Schema.Array(Schema.String)]),
+ username: Schema.optionalKey(Schema.String),
+ credential: Schema.optionalKey(Schema.String),
+});
+const webRtcSettingsSchema = Schema.Struct({
+ transport: Schema.Literal("webrtc"),
+ iceServers: Schema.optionalKey(Schema.Array(iceServerSchema)),
+ iceTransportPolicy: Schema.optionalKey(Schema.Literals(["all", "relay"])),
+});
+// serve-sim reports its stream settings as `streamSettings` (EAS) or `stream`.
+const serveSimApiSchema = Schema.Struct({
+ streamSettings: Schema.optionalKey(Schema.Unknown),
+ stream: Schema.optionalKey(Schema.Unknown),
+});
+const decodeServeSimApi = Schema.decodeUnknownOption(serveSimApiSchema);
+const decodeWebRtcSettings = Schema.decodeUnknownOption(webRtcSettingsSchema);
+type WebRtcSettings = typeof webRtcSettingsSchema.Type;
+const decodeTransportLocked = Schema.decodeUnknownOption(
+ Schema.Struct({
+ error: Schema.Literal("stream_transport_locked"),
+ transport: Schema.Literal("webrtc"),
+ }),
+);
+const decodeWebRtcAnswer = Schema.decodeUnknownOption(
+ Schema.Struct({ type: Schema.Literal("answer"), sdp: Schema.String }),
+);
export interface DuoPanelSinks {
readonly cover: DeviceFrameSink;
@@ -77,6 +104,11 @@ export interface DeviceStreamEvents {
* and attach it with `setMjpegImage` so the client can observe real frames.
*/
readonly onMjpegFallback: (url: string) => void;
+ /**
+ * The stream moved from MJPEG back to painting the canvas, because the
+ * device serves WebRTC only; the owner should show the canvas again.
+ */
+ readonly onCanvasVideo?: () => void;
readonly onInputConnected: (connected: boolean, detail?: string) => void;
}
@@ -94,6 +126,19 @@ export type DeviceHardwareButton = "home" | "back" | "recents" | "power" | "appS
const RETRY_DELAY_MS = 1_000;
const FIRST_FRAME_TIMEOUT_MS = 15_000;
+// A WebRTC feed that shows no frame for this long is reconnected; checked
+// every WEBRTC_STALL_CHECK_MS, so a transient `disconnected` peer that
+// recovers is left alone.
+const WEBRTC_STALL_TIMEOUT_MS = FIRST_FRAME_TIMEOUT_MS;
+const WEBRTC_STALL_CHECK_MS = 5_000;
+const TRANSPORT_PROBE_TIMEOUT_MS = 5_000;
+// Offers carry every candidate: serve-sim does not accept trickled ICE.
+const ICE_GATHERING_TIMEOUT_MS = 2_000;
+// A gathering cut short without a reflexive or relay candidate is retried
+// with twice the deadline, up to this; then the offer goes as gathered. The
+// whole sequence stays inside the first-frame deadline, which retries do
+// not extend.
+const ICE_GATHERING_MAX_TIMEOUT_MS = 4_000;
const MJPEG_FRAME_CHECK_MS = 250;
const FRAME_DURATION_US = 16_667;
const SEMU_MAGIC = 0x53454d55;
@@ -115,6 +160,15 @@ const IOS_TAG_INPUT_ADMITTED = 0x83;
const encoder = new TextEncoder();
const decoder = new TextDecoder();
+/** serve-sim requires a v4 UUID; `crypto.randomUUID` is missing over plain-HTTP LAN origins. */
+function webRtcSessionId(): string {
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
+ bytes[6] = (bytes[6]! & 0x0f) | 0x40;
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+}
+
const isWebCodecsSupported = (): boolean =>
typeof globalThis !== "undefined" &&
"VideoDecoder" in globalThis &&
@@ -367,6 +421,9 @@ export function createDeviceStreamClient(
let panelSinks: DuoPanelSinks | null = null;
let rotationCursor: DeviceScreenSize["orientation"] | null = null;
let pendingOrientation: { requestId: number } | null = null;
+ let iceGatheringDeadlineMs = ICE_GATHERING_TIMEOUT_MS;
+ let peer: { connection: RTCPeerConnection; sessionId: string; video: HTMLVideoElement } | null =
+ null;
const duoControl = createDuoControl({
send(request) {
if (
@@ -454,7 +511,11 @@ export function createDeviceStreamClient(
}
};
const error = () => {
- if (!released) fail("Could not receive the device stream. Reconnect to try again.");
+ if (released) return;
+ const failure = "Could not receive the device stream. Reconnect to try again.";
+ // An <img> cannot read the 409 that a WebRTC-only serve-sim answers with.
+ if (typeof RTCPeerConnection === "undefined") fail(failure);
+ else void switchToWebRtc(failure, false);
};
image.addEventListener("load", check);
image.addEventListener("error", error);
@@ -646,6 +707,15 @@ export function createDeviceStreamClient(
return;
}
if (response.status === 401 || response.status === 403) return handleUnauthorized();
+ if (response.status === 409 && !target.panelId) {
+ const locked = decodeTransportLocked(await response.json().catch(() => null));
+ if (Option.isSome(locked)) {
+ if (!isCurrent()) return;
+ controller = null;
+ void switchToWebRtc("This browser cannot play this device's WebRTC stream.", true);
+ return;
+ }
+ }
if (target.panelId && [400, 404, 405, 410].includes(response.status)) {
await response.body?.cancel();
setStatus("error", "This Device Hub does not provide fixed Duo display feeds.");
@@ -753,6 +823,213 @@ export function createDeviceStreamClient(
}
};
+ /**
+ * serve-sim can be locked to WebRTC (EAS Simulator always is), and then
+ * refuses AVCC and MJPEG. An unreadable answer keeps the AVCC path.
+ */
+ const probeIosTransport = async (): Promise<WebRtcSettings | null> => {
+ const probe = new AbortController();
+ const timeout = setTimeout(() => probe.abort(), TRANSPORT_PROBE_TIMEOUT_MS);
+ try {
+ const response = await fetch(httpUrl(`/api?device=${device}`), {
+ signal: probe.signal,
+ credentials: access.credentials ? "include" : "same-origin",
+ });
+ if (!response.ok) return null;
+ const api = decodeServeSimApi(await response.json());
+ if (Option.isNone(api)) return null;
+ const settings = decodeWebRtcSettings(api.value.streamSettings ?? api.value.stream);
+ return Option.isSome(settings) ? settings.value : null;
+ } catch {
+ return null;
+ } finally {
+ clearTimeout(timeout);
+ }
+ };
+
+ const closePeer = () => {
+ const current = peer;
+ if (!current) return;
+ peer = null;
+ current.connection.close();
+ current.video.srcObject = null;
+ current.video.remove();
+ // Releases serve-sim's capture session; best effort because the page may be unloading.
+ void fetch(httpUrl(`/helper/${device}/webrtc/close`), {
+ method: "POST",
+ keepalive: true,
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ sessionId: current.sessionId }),
+ credentials: access.credentials ? "include" : "same-origin",
+ }).catch(() => {});
+ };
+
+ const readIosWebRtc = async (settings: WebRtcSettings) => {
+ const lifecycle = generation;
+ const feedGeneration = ++videoGeneration;
+ closePeer();
+ const connection = new RTCPeerConnection({
+ ...(settings.iceServers
+ ? {
+ iceServers: settings.iceServers.map((server) => ({
+ ...server,
+ urls: typeof server.urls === "string" ? server.urls : [...server.urls],
+ })),
+ }
+ : {}),
+ iceTransportPolicy: settings.iceTransportPolicy ?? "all",
+ });
+ // Frames only reach requestVideoFrameCallback from a video that is in the
+ // document; it stays invisible because the sink paints them.
+ const video = document.createElement("video");
+ video.muted = true;
+ video.playsInline = true;
+ video.setAttribute("aria-hidden", "true");
+ video.style.cssText =
+ "position:fixed;width:1px;height:1px;opacity:0;pointer-events:none;left:0;top:0";
+ document.body.append(video);
+ const current = { connection, sessionId: webRtcSessionId(), video };
+ peer = current;
+ const isCurrent = () =>
+ !stopped &&
+ generation === lifecycle &&
+ videoGeneration === feedGeneration &&
+ peer === current;
+ // After the first frame nothing else bounds a feed that stops: the peer
+ // can sit `disconnected` with the last frame on the canvas. A long gap
+ // between frames reconnects through the same path as a failed connection.
+ let checksWithoutFrame = 0;
+ let watchdog: ReturnType<typeof setInterval> | null = null;
+ const clearWatchdog = () => {
+ if (watchdog !== null) clearInterval(watchdog);
+ watchdog = null;
+ };
+ const retry = (detail: string) => {
+ clearWatchdog();
+ if (!isCurrent()) return;
+ closePeer();
+ connecting(detail);
+ scheduleRetry("video", () => void readIosWebRtc(settings));
+ };
+ const presentFrame = () => {
+ if (!isCurrent()) {
+ clearWatchdog();
+ return;
+ }
+ if (video.videoWidth > 0 && video.videoHeight > 0) {
+ paint(video, video.videoWidth, video.videoHeight);
+ checksWithoutFrame = 0;
+ watchdog ??= setInterval(() => {
+ if (!isCurrent()) return clearWatchdog();
+ checksWithoutFrame++;
+ if (checksWithoutFrame * WEBRTC_STALL_CHECK_MS >= WEBRTC_STALL_TIMEOUT_MS) {
+ retry("Device stream stalled. Reconnecting…");
+ }
+ }, WEBRTC_STALL_CHECK_MS);
+ }
+ video.requestVideoFrameCallback(presentFrame);
+ };
+ const transceiver = connection.addTransceiver("video", { direction: "recvonly" });
+ const codecs = RTCRtpReceiver.getCapabilities("video")?.codecs ?? [];
+ if (codecs.length > 0) {
+ // serve-sim encodes H.264; other codecs stay as fallbacks it may refuse.
+ transceiver.setCodecPreferences([
+ ...codecs.filter((codec) => codec.mimeType.toLowerCase() === "video/h264"),
+ ...codecs.filter((codec) => codec.mimeType.toLowerCase() !== "video/h264"),
+ ]);
+ }
+ connection.ontrack = (event) => {
+ if (!isCurrent()) return;
+ iceGatheringDeadlineMs = ICE_GATHERING_TIMEOUT_MS;
+ video.srcObject = event.streams[0] ?? new MediaStream([event.track]);
+ void video.play().catch(() => {});
+ video.requestVideoFrameCallback(presentFrame);
+ };
+ connection.onconnectionstatechange = () => {
+ if (connection.connectionState === "failed")
+ retry("Device stream connection failed. Reconnecting…");
+ };
+ try {
+ await connection.setLocalDescription(await connection.createOffer());
+ const gathered = await new Promise<boolean>((resolve) => {
+ if (connection.iceGatheringState === "complete") return resolve(true);
+ const timer = setTimeout(() => done(false), iceGatheringDeadlineMs);
+ function done(complete: boolean) {
+ clearTimeout(timer);
+ connection.removeEventListener("icegatheringstatechange", changed);
+ resolve(complete);
+ }
+ function changed() {
+ if (connection.iceGatheringState === "complete") done(true);
+ }
+ connection.addEventListener("icegatheringstatechange", changed);
+ });
+ if (!isCurrent()) return;
+ // serve-sim takes the offer's candidates as the whole set; none trickle
+ // later. A simulator in the cloud needs a reflexive or relay candidate,
+ // which STUN and TURN can take longer than the deadline to produce: an
+ // offer cut short without one is retried with a longer deadline, up to
+ // a bound, after which it goes as gathered rather than never.
+ const sdp = connection.localDescription?.sdp ?? "";
+ if (
+ !gathered &&
+ !/^a=candidate:.* typ (?:srflx|relay)\b/m.test(sdp) &&
+ iceGatheringDeadlineMs < ICE_GATHERING_MAX_TIMEOUT_MS
+ ) {
+ iceGatheringDeadlineMs = Math.min(iceGatheringDeadlineMs * 2, ICE_GATHERING_MAX_TIMEOUT_MS);
+ return retry("Device stream found no network candidates yet. Retrying…");
+ }
+ const response = await fetch(httpUrl(`/helper/${device}/webrtc/offer`), {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ type: "offer",
+ sdp: connection.localDescription?.sdp,
+ sessionId: current.sessionId,
+ codec: "h264",
+ }),
+ credentials: access.credentials ? "include" : "same-origin",
+ });
+ if (!isCurrent()) {
+ await response.body?.cancel();
+ return;
+ }
+ if (response.status === 401 || response.status === 403) return handleUnauthorized();
+ // 409: another viewer is still negotiating with this simulator.
+ if (!response.ok) return retry(`Device stream offer failed (${response.status}). Retrying…`);
+ const answer = decodeWebRtcAnswer(await response.json());
+ if (!isCurrent()) return;
+ if (Option.isNone(answer))
+ return retry("Device stream returned an invalid answer. Retrying…");
+ await connection.setRemoteDescription(answer.value);
+ } catch (cause) {
+ retry((cause as Error).message);
+ }
+ };
+
+ /**
+ * Called once AVCC or MJPEG was refused. `locked` means serve-sim already
+ * said it streams WebRTC only, so a missing /api answer still switches.
+ */
+ const switchToWebRtc = async (failure: string, locked: boolean) => {
+ const session = generation;
+ if (typeof RTCPeerConnection === "undefined") return fail(failure);
+ const settings =
+ (await probeIosTransport()) ?? (locked ? { transport: "webrtc" as const } : null);
+ if (stopped || generation !== session) return;
+ if (!settings) return fail(failure);
+ if (mjpeg) {
+ mjpeg = false;
+ releaseImage?.();
+ releaseImage = null;
+ events.onCanvasVideo?.();
+ }
+ // MJPEG may have shown frames already: say the stream is connecting again
+ // rather than leave a blank canvas until the first WebRTC frame.
+ connecting("Switching to WebRTC.");
+ void readIosWebRtc(settings);
+ };
+
const startDuoVideo = (panels: DuoPanelSinks) => {
for (const panel of panelClients) panel.stop();
// Physical handoff elects a native surface. Fixed-panel encoders can keep
@@ -987,6 +1264,7 @@ export function createDeviceStreamClient(
primeController = null;
controller?.abort();
controller = null;
+ closePeer();
const discarded = socket;
socket = null;
discarded?.close();
@@ -1033,6 +1311,7 @@ export function createDeviceStreamClient(
videoGeneration++;
controller?.abort();
controller = null;
+ closePeer();
closeDecoder();
const retry = retryTimers.get("video");
if (retry) clearTimeout(retry);