Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3import {
4 createDeviceStreamClient,
5 AvccDemuxer,
6 avcCodecString,
7 parseSemuPacket,
8 scanAccessUnit,
9} from "./stream.ts";
10
11const envelope = (tag: number, payload: number[]) => {
12 const length = 1 + payload.length;
13 return [
14 (length >>> 24) & 0xff,
15 (length >>> 16) & 0xff,
16 (length >>> 8) & 0xff,
17 length & 0xff,
18 tag,
19 ...payload,
20 ];
21};
22
23describe("AvccDemuxer", () => {
24 it("reassembles envelopes split across reads", () => {
25 const demuxer = new AvccDemuxer();
26 const bytes = new Uint8Array([
27 ...envelope(1, [1, 0x64, 0x00, 0x1f]),
28 ...envelope(2, [9, 9, 9]),
29 ...envelope(0x7f, [0]),
30 ...envelope(3, [4]),
31 ]);
32 const first = demuxer.push(bytes.subarray(0, 7));
33 const rest = demuxer.push(bytes.subarray(7));
34 const chunks = [...first, ...rest];
35 expect(chunks.map((chunk) => chunk.type)).toEqual(["description", "keyframe", "delta"]);
36 expect(Array.from(chunks[0]!.payload)).toEqual([1, 0x64, 0x00, 0x1f]);
37 expect(Array.from(chunks[1]!.payload)).toEqual([9, 9, 9]);
38 });
39
40 it("derives the WebCodecs codec string from the avcC record", () => {
41 expect(avcCodecString(new Uint8Array([1, 0x64, 0x00, 0x1f]))).toBe("avc1.64001f");
42 expect(avcCodecString(new Uint8Array([1]))).toBe("avc1.42E01E");
43 });
44});
45
46describe("native device stream transport", () => {
47 afterEach(() => {
48 vi.useRealTimers();
49 vi.unstubAllGlobals();
50 });
51
52 function setup(platform: "ios" | "android") {
53 vi.useFakeTimers();
54 vi.stubGlobal("VideoDecoder", vi.fn());
55 vi.stubGlobal("EncodedVideoChunk", vi.fn());
56 let resolveOpened!: (socket: FakeSocket) => void;
57 const waitForSocket = () =>
58 new Promise<FakeSocket>((resolve) => {
59 resolveOpened = resolve;
60 });
61 const opened = waitForSocket();
62 class FakeSocket {
63 static OPEN = 1;
64 readyState = 1;
65 binaryType = "";
66 onopen: (() => void) | null = null;
67 onmessage: ((event: { data: ArrayBuffer }) => void) | null = null;
68 onclose: ((event: { code: number; reason: string }) => void) | null = null;
69 send = vi.fn();
70 close = vi.fn();
71 readonly url: string;
72 constructor(url: string) {
73 this.url = url;
74 resolveOpened(this);
75 }
76 }
77 vi.stubGlobal("WebSocket", FakeSocket);
78 const fetch = vi.fn(() => Promise.resolve(Response.json({})));
79 vi.stubGlobal("fetch", fetch);
80 const events = {
81 onStatus: vi.fn(),
82 onScreen: vi.fn(),
83 onUnauthorized: vi.fn(),
84 onMjpegFallback: vi.fn(),
85 onInputConnected: vi.fn(),
86 };
87 const client = createDeviceStreamClient(
88 {
89 platform,
90 deviceId: "test device",
91 preferMjpeg: platform === "ios",
92 access: {
93 httpBase: "https://environment.test/api/device-hub",
94 wsBase: "wss://environment.test/api/device-hub",
95 credentials: false,
96 query: { wsTicket: "stream-ticket", hostId: "ssh-host" },
97 },
98 },
99 { getContext: () => null } as unknown as HTMLCanvasElement,
100 events,
101 );
102 return { client, opened, waitForSocket, events, fetch };
103 }
104
105 it("renews an expired Android ticket when the HTTP upgrade is rejected instead of retrying it forever", async () => {
106 const { client, opened, events } = setup("android");
107 client.start();
108 const socket = await opened;
109 socket.onclose?.({ code: 1006, reason: "" });
110 expect(events.onUnauthorized).toHaveBeenCalledTimes(1);
111 expect(vi.getTimerCount()).toBe(0);
112 client.stop();
113 });
114
115 it.each(["ios", "android"] as const)(
116 "keeps a restarted %s stream connected when the discarded socket closes late",
117 async (platform) => {
118 const { client, opened, waitForSocket, events } = setup(platform);
119 client.start();
120 const discarded = await opened;
121 client.stop();
122 const reopened = waitForSocket();
123 client.start();
124 const replacement = await reopened;
125 replacement.onopen?.();
126 if (platform === "ios") replacement.onmessage?.({ data: Uint8Array.of(0x83).buffer });
127 replacement.send.mockClear();
128 events.onInputConnected.mockClear();
129
130 discarded.onclose?.({ code: 1006, reason: "" });
131
132 expect(events.onUnauthorized).not.toHaveBeenCalled();
133 expect(events.onInputConnected).not.toHaveBeenCalled();
134 expect(replacement.close).not.toHaveBeenCalled();
135 client.pressButton("home");
136 expect(replacement.send).toHaveBeenCalledTimes(1);
137 client.stop();
138 expect(replacement.close).toHaveBeenCalledTimes(1);
139 expect(vi.getTimerCount()).toBe(0);
140 },
141 );
142
143 it.each([
144 ["ios", { button: "home" }, { button: "app_switcher" }],
145 ["android", { type: "home" }, { type: "recents" }],
146 ] as const)(
147 "opens the %s app switcher on a double-tapped home button",
148 async (platform, home, switcher) => {
149 const { client, opened } = setup(platform);
150 client.start();
151 const socket = await opened;
152 socket.onopen?.();
153 if (platform === "ios") socket.onmessage?.({ data: Uint8Array.of(0x83).buffer });
154 socket.send.mockClear();
155
156 client.pressButton("home");
157 client.pressButton("home");
158 client.pressButton("home");
159 vi.advanceTimersByTime(1000);
160 client.pressButton("home");
161
162 const sent = socket.send.mock.calls.map(([payload]) =>
163 JSON.parse(
164 typeof payload === "string" ? payload : new TextDecoder().decode(payload.subarray(1)),
165 ),
166 );
167 expect(sent).toEqual([home, switcher, home, home]);
168 client.stop();
169 },
170 );
171
172 it.each(["ios", "android"] as const)(
173 "does not renew credentials or reconnect a stopped %s stream",
174 async (platform) => {
175 const { client, opened, events } = setup(platform);
176 client.start();
177 const socket = await opened;
178 events.onInputConnected.mockClear();
179 client.stop();
180 socket.onclose?.({ code: 1006, reason: "" });
181 expect(events.onUnauthorized).not.toHaveBeenCalled();
182 expect(events.onInputConnected).not.toHaveBeenCalled();
183 expect(vi.getTimerCount()).toBe(0);
184 },
185 );
186});
187
188describe("iOS keypad protocol", () => {
189 afterEach(() => vi.unstubAllGlobals());
190
191 it("encodes keypad presses and releases as HID key packets", async () => {
192 const packets: Uint8Array[] = [];
193 let opened!: (socket: Socket) => void;
194 const connected = new Promise<Socket>((resolve) => {
195 opened = resolve;
196 });
197 class Socket {
198 static OPEN = 1;
199 readyState = 1;
200 binaryType = "";
201 onmessage: ((event: { data: ArrayBuffer }) => void) | null = null;
202 constructor() {
203 opened(this);
204 }
205 send(packet: Uint8Array) {
206 packets.push(packet);
207 }
208 close() {}
209 }
210 vi.stubGlobal("WebSocket", Socket);
211 vi.stubGlobal("fetch", async () => new Response("frame"));
212 const client = createDeviceStreamClient(
213 {
214 platform: "ios",
215 deviceId: "keypad-device",
216 preferMjpeg: true,
217 access: {
218 httpBase: "https://device.test",
219 wsBase: "wss://device.test",
220 credentials: false,
221 query: {},
222 },
223 },
224 { getContext: () => null } as unknown as HTMLCanvasElement,
225 {
226 onStatus() {},
227 onScreen() {},
228 onUnauthorized() {},
229 onMjpegFallback() {},
230 onInputConnected() {},
231 },
232 );
233 try {
234 client.start();
235 const socket = await connected;
236 socket.onmessage?.({ data: Uint8Array.of(0x83).buffer });
237 const keys = [
238 ["NumpadDivide", 0x54],
239 ["NumpadMultiply", 0x55],
240 ["NumpadSubtract", 0x56],
241 ["NumpadAdd", 0x57],
242 ["NumpadEnter", 0x58],
243 ["Numpad1", 0x59],
244 ["Numpad2", 0x5a],
245 ["Numpad3", 0x5b],
246 ["Numpad4", 0x5c],
247 ["Numpad5", 0x5d],
248 ["Numpad6", 0x5e],
249 ["Numpad7", 0x5f],
250 ["Numpad8", 0x60],
251 ["Numpad9", 0x61],
252 ["Numpad0", 0x62],
253 ["NumpadDecimal", 0x63],
254 ["NumpadEqual", 0x67],
255 ["Digit1", 0x1e],
256 ["Enter", 0x28],
257 ] as const;
258 for (const [code] of keys) {
259 for (const phase of ["down", "up"] as const) {
260 client.sendKey({ code } as KeyboardEvent, phase);
261 }
262 }
263 const decoder = new TextDecoder();
264 expect(
265 packets.map((packet) => [packet[0], JSON.parse(decoder.decode(packet.subarray(1)))]),
266 ).toEqual(
267 keys.flatMap(([, usage]) => [
268 [0x06, { type: "down", usage }],
269 [0x06, { type: "up", usage }],
270 ]),
271 );
272 } finally {
273 client.stop();
274 }
275 });
276});
277
278describe("serve-emu frames", () => {
279 it("strips the SEMU header and reads the keyframe flag and timestamp", () => {
280 const buffer = new ArrayBuffer(16 + 3);
281 const view = new DataView(buffer);
282 view.setUint32(0, 0x53454d55);
283 view.setUint8(4, 1);
284 view.setUint8(5, 1);
285 view.setBigUint64(8, 123456n);
286 new Uint8Array(buffer).set([7, 8, 9], 16);
287 const packet = parseSemuPacket(buffer);
288 expect(packet.isKey).toBe(true);
289 expect(packet.timestamp).toBe(123456);
290 expect(Array.from(packet.data)).toEqual([7, 8, 9]);
291 });
292
293 it("treats a frame without the header as raw data", () => {
294 const packet = parseSemuPacket(new Uint8Array([0, 0, 1, 0x65]).buffer);
295 expect(packet.isKey).toBeNull();
296 expect(packet.data.length).toBe(4);
297 });
298
299 it("finds the SPS and IDR NAL units in an Annex-B access unit", () => {
300 const unit = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0x00, 0x1f, 0, 0, 1, 0x65, 0xaa]);
301 const scanned = scanAccessUnit(unit);
302 expect(scanned.isKey).toBe(true);
303 expect(scanned.sps && avcCodecString(scanned.sps)).toBe("avc1.64001f");
304 expect(scanAccessUnit(new Uint8Array([0, 0, 1, 0x41, 0x00])).isKey).toBe(false);
305 });
306});
307
308class MjpegImage extends EventTarget {
309 naturalWidth = 0;
310 naturalHeight = 0;
311 src = "";
312 removeAttribute(name: string) {
313 if (name === "src") {
314 this.src = "";
315 this.naturalWidth = 0;
316 this.naturalHeight = 0;
317 }
318 }
319}
320
321function recoveryFixture(
322 platform: "ios" | "android" = "ios",
323 preferMjpeg = true,
324 serveSimOnly = false,
325) {
326 vi.useFakeTimers();
327 const sockets: Socket[] = [];
328 class Socket {
329 static OPEN = 1;
330 readyState = 1;
331 binaryType = "";
332 onopen: (() => void) | null = null;
333 onmessage: ((event: { data: ArrayBuffer | string }) => void) | null = null;
334 onclose: ((event: { code: number; reason: string }) => void) | null = null;
335 send = vi.fn();
336 close = vi.fn();
337 readonly url: string;
338 constructor(url: string) {
339 this.url = url;
340 sockets.push(this);
341 }
342 }
343 vi.stubGlobal("WebSocket", Socket);
344 const decoders: Decoder[] = [];
345 class Decoder {
346 static isConfigSupported = vi.fn(async () => ({ supported: true }));
347 state = "unconfigured";
348 decodeQueueSize = 0;
349 configure() {
350 this.state = "configured";
351 }
352 reset = vi.fn(() => {
353 this.state = "unconfigured";
354 this.decodeQueueSize = 0;
355 });
356 close() {
357 this.state = "closed";
358 }
359 decode = vi.fn();
360 readonly callbacks: { output: (frame: VideoFrame) => void; error: () => void };
361 constructor(callbacks: { output: (frame: VideoFrame) => void; error: () => void }) {
362 this.callbacks = callbacks;
363 decoders.push(this);
364 }
365 }
366 vi.stubGlobal("VideoDecoder", Decoder);
367 vi.stubGlobal("EncodedVideoChunk", vi.fn());
368 const videoBodies: ReadableStreamDefaultController<Uint8Array>[] = [];
369 const signals: AbortSignal[] = [];
370 const fetch = vi.fn((url: string, init: RequestInit) => {
371 const signal = init.signal!;
372 signals.push(signal);
373 if (url.includes("/api?")) return Promise.resolve(Response.json({}));
374 if (!url.includes("stream.avcc")) return Promise.resolve(new Response("prime"));
375 return Promise.resolve(
376 new Response(
377 new ReadableStream<Uint8Array>({
378 start(body) {
379 videoBodies.push(body);
380 signal.addEventListener("abort", () => body.error(new Error("aborted")), {
381 once: true,
382 });
383 },
384 }),
385 ),
386 );
387 });
388 vi.stubGlobal("fetch", fetch);
389 const events = {
390 onStatus: vi.fn(),
391 onScreen: vi.fn(),
392 onUnauthorized: vi.fn(),
393 onMjpegFallback: vi.fn(),
394 onInputConnected: vi.fn(),
395 };
396 const drawImage = vi.fn();
397 const image = new MjpegImage();
398 const client = createDeviceStreamClient(
399 {
400 platform,
401 preferMjpeg,
402 serveSimOnly,
403 deviceId: "test-device",
404 access: {
405 httpBase: "https://test/api/device-hub",
406 wsBase: "wss://test/api/device-hub",
407 credentials: true,
408 query: {},
409 },
410 },
411 { getContext: () => ({ drawImage }) } as unknown as HTMLCanvasElement,
412 events,
413 );
414 client.setMjpegImage(image as unknown as HTMLImageElement);
415 const imageReady = () => {
416 image.naturalWidth = 400;
417 image.naturalHeight = 800;
418 image.dispatchEvent(new Event("load"));
419 };
420 const decodedFrame = (index = decoders.length - 1) => {
421 const close = vi.fn();
422 decoders[index]!.callbacks.output({
423 displayWidth: 400,
424 displayHeight: 800,
425 close,
426 } as unknown as VideoFrame);
427 return close;
428 };
429 const sps = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0, 0x1f, 0, 0, 1, 0x65]).buffer;
430 return {
431 client,
432 events,
433 image,
434 imageReady,
435 sockets,
436 signals,
437 fetch,
438 videoBodies,
439 decoders,
440 Decoder,
441 drawImage,
442 decodedFrame,
443 sps,
444 };
445}
446
447describe("shared device stream readiness and recovery", () => {
448 afterEach(() => {
449 vi.useRealTimers();
450 vi.unstubAllGlobals();
451 });
452
453 it("streams and drives a serve-sim-only Android device over serve-sim's AVCC and input socket", async () => {
454 const { client, events, fetch, sockets, videoBodies, decoders } = recoveryFixture(
455 "android",
456 false,
457 true,
458 );
459 client.start();
460 await vi.advanceTimersByTimeAsync(0);
461 // No MJPEG priming: Simlock serves only the AVCC stream and the input socket.
462 expect(fetch.mock.calls.map(([url]) => url)).toEqual([
463 "https://test/api/device-hub/vendor/serve-sim/helper/test-device/stream.avcc",
464 ]);
465 expect(sockets.map((socket) => socket.url)).toEqual([
466 "wss://test/api/device-hub/vendor/serve-sim/helper/ws?device=test-device",
467 ]);
468 // Simlock adds meta (5), keep-alive (6), and lease-end (7) frames to serve-sim's envelopes.
469 videoBodies[0]!.enqueue(
470 new Uint8Array([
471 ...envelope(5, [0x7b, 0x7d]),
472 ...envelope(1, [1, 0x64, 0, 0x1f]),
473 ...envelope(6, []),
474 ...envelope(2, [2]),
475 ...envelope(7, [0x7b, 0x7d]),
476 ]),
477 );
478 await vi.advanceTimersByTimeAsync(0);
479 expect(decoders[0]!.decode).toHaveBeenCalledOnce();
480
481 const input = sockets[0]!;
482 input.onmessage?.({ data: Uint8Array.of(0x83).buffer });
483 input.onmessage?.({
484 data: new Uint8Array([
485 0x82,
486 ...new TextEncoder().encode('{"width":1080,"height":2400,"orientation":"portrait"}'),
487 ]).buffer,
488 });
489 expect(events.onInputConnected).toHaveBeenLastCalledWith(true, undefined);
490 client.sendTouch("begin", 0.25, 0.5);
491 client.pressButton("back");
492 const sent = input.send.mock.calls.map(([payload]) => {
493 const bytes = payload as Uint8Array;
494 return [bytes[0], JSON.parse(new TextDecoder().decode(bytes.subarray(1)))];
495 });
496 expect(sent).toEqual([
497 [0x03, { type: "begin", x: 0.25, y: 0.5 }],
498 [0x04, { button: "back" }],
499 ]);
500 client.stop();
501 });
502
503 it("stops retrying a Simlock lease that ended and keeps its reason", async () => {
504 const { client, events, fetch, sockets, videoBodies } = recoveryFixture("ios", false, true);
505 client.start();
506 await vi.advanceTimersByTimeAsync(0);
507 const reason = [...new TextEncoder().encode('{"reason":"expired"}')];
508 videoBodies[0]!.enqueue(new Uint8Array([...envelope(4, [1]), ...envelope(7, reason)]));
509 videoBodies[0]!.close();
510 sockets[0]!.onclose?.({ code: 4001, reason: "expired" });
511 await vi.advanceTimersByTimeAsync(5_000);
512 expect(fetch.mock.calls.filter(([url]) => url.includes("stream.avcc"))).toHaveLength(1);
513 expect(sockets).toHaveLength(1);
514 expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.stringContaining("expired"));
515 client.stop();
516 });
517
518 it("bounds the restarted AVCC feed by the first-frame window when Duo panels are cleared", async () => {
519 const { client, events, fetch, sockets, videoBodies, decodedFrame } = recoveryFixture(
520 "ios",
521 false,
522 );
523 client.start();
524 await vi.advanceTimersByTimeAsync(0);
525 videoBodies[0]!.enqueue(
526 new Uint8Array([...envelope(1, [1, 0x64, 0, 0x1f]), ...envelope(2, [2])]),
527 );
528 await vi.advanceTimersByTimeAsync(0);
529 sockets[0]!.onmessage?.({
530 data: new Uint8Array([
531 0x82,
532 ...new TextEncoder().encode(
533 '{"width":400,"height":800,"orientation":"portrait","supportsHingeAngle":true}',
534 ),
535 ]).buffer,
536 });
537 decodedFrame();
538 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
539 const panel = { present: vi.fn(() => true) };
540 client.setDuoPanels({ cover: panel, inner: panel } as unknown as Parameters<
541 typeof client.setDuoPanels
542 >[0]);
543 await vi.advanceTimersByTimeAsync(0);
544 // The restarted feed's response headers never arrive.
545 fetch.mockImplementation(() => new Promise<Response>(() => {}));
546 client.setDuoPanels(null);
547 expect(events.onStatus).toHaveBeenLastCalledWith("connecting", undefined);
548 await vi.advanceTimersByTimeAsync(15_000);
549 expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.any(String));
550 });
551
552 it("does not repaint a delayed JPEG seed over newer decoded video", async () => {
553 const { client, videoBodies, drawImage, decodedFrame } = recoveryFixture("ios", false);
554 let resolveBitmap!: (bitmap: ImageBitmap) => void;
555 vi.stubGlobal(
556 "createImageBitmap",
557 () =>
558 new Promise((resolve) => {
559 resolveBitmap = resolve;
560 }),
561 );
562 client.start();
563 await vi.advanceTimersByTimeAsync(0);
564 videoBodies[0]!.enqueue(
565 new Uint8Array([
566 ...envelope(4, [1]),
567 ...envelope(1, [1, 0x64, 0, 0x1f]),
568 ...envelope(2, [2]),
569 ]),
570 );
571 await vi.advanceTimersByTimeAsync(0);
572 decodedFrame();
573 const close = vi.fn();
574 resolveBitmap({ width: 400, height: 800, close } as unknown as ImageBitmap);
575 await vi.advanceTimersByTimeAsync(0);
576 expect(drawImage).toHaveBeenCalledOnce();
577 expect(close).toHaveBeenCalledOnce();
578 client.stop();
579 });
580
581 it("discards decoder support results and output from a previous Android socket", async () => {
582 const { client, sockets, sps, events, Decoder, decoders, decodedFrame, drawImage } =
583 recoveryFixture("android");
584 let resolveSupport!: (support: { supported: boolean }) => void;
585 Decoder.isConfigSupported.mockImplementationOnce(
586 () =>
587 new Promise((resolve) => {
588 resolveSupport = resolve;
589 }),
590 );
591 client.start();
592 await vi.advanceTimersByTimeAsync(0);
593 sockets[0]!.onmessage?.({ data: sps });
594 client.stop();
595 client.start();
596 await vi.advanceTimersByTimeAsync(0);
597 resolveSupport({ supported: true });
598 await vi.advanceTimersByTimeAsync(0);
599 expect(decoders).toHaveLength(0);
600 sockets[1]!.onmessage?.({ data: sps });
601 await vi.advanceTimersByTimeAsync(0);
602 client.stop();
603 client.start();
604 events.onStatus.mockClear();
605 expect(decodedFrame()).toHaveBeenCalledOnce();
606 expect(drawImage).not.toHaveBeenCalled();
607 expect(events.onStatus).not.toHaveBeenCalled();
608 client.stop();
609 });
610
611 it("ignores an old AVCC response rejected after a new attempt is connected", async () => {
612 const { client, fetch, events } = recoveryFixture("ios", false);
613 let resolveResponse!: (response: Response) => void;
614 fetch.mockImplementationOnce(() => Promise.resolve(new Response("prime")));
615 fetch.mockImplementationOnce(
616 () =>
617 new Promise((resolve) => {
618 resolveResponse = resolve;
619 }),
620 );
621 client.start();
622 await vi.advanceTimersByTimeAsync(0);
623 client.stop();
624 client.start();
625 await vi.advanceTimersByTimeAsync(0);
626 events.onStatus.mockClear();
627 resolveResponse(new Response(null, { status: 401 }));
628 await vi.advanceTimersByTimeAsync(0);
629 expect(events.onUnauthorized).not.toHaveBeenCalled();
630 expect(events.onStatus).not.toHaveBeenCalled();
631 client.stop();
632 expect(vi.getTimerCount()).toBe(0);
633 });
634});
635
636describe("WebRTC device streams", () => {
637 afterEach(() => {
638 vi.useRealTimers();
639 vi.unstubAllGlobals();
640 });
641
642 function setup(
643 platform: "ios" | "android" = "android",
644 stream: unknown = { transport: "webrtc" },
645 ) {
646 vi.useFakeTimers();
647 // The iOS cases model an Android WebView on a plain-http origin: no WebCodecs.
648 expect("VideoDecoder" in globalThis).toBe(false);
649 const sockets: Socket[] = [];
650 class Socket {
651 static OPEN = 1;
652 readyState = 1;
653 binaryType = "";
654 onopen: (() => void) | null = null;
655 onmessage: ((event: { data: string }) => void) | null = null;
656 onclose: ((event: { code: number; reason: string }) => void) | null = null;
657 send = vi.fn();
658 close = vi.fn();
659 readonly url: string;
660 constructor(url: string) {
661 this.url = url;
662 sockets.push(this);
663 }
664 }
665 const videos: Video[] = [];
666 class Video {
667 muted = false;
668 playsInline = false;
669 style = { cssText: "" };
670 srcObject: unknown = null;
671 videoWidth = 400;
672 videoHeight = 800;
673 setAttribute = vi.fn();
674 remove = vi.fn();
675 play = vi.fn(async () => {});
676 callback: (() => void) | null = null;
677 requestVideoFrameCallback(callback: () => void) {
678 this.callback = callback;
679 return 0;
680 }
681 constructor() {
682 videos.push(this);
683 }
684 }
685 const peers: Peer[] = [];
686 class Peer {
687 iceGatheringState = "complete";
688 connectionState = "connected";
689 localDescription = { type: "offer", sdp: "offer-sdp" };
690 ontrack: ((event: { streams: unknown[]; track: unknown }) => void) | null = null;
691 onconnectionstatechange: (() => void) | null = null;
692 close = vi.fn();
693 createOffer = vi.fn(async () => this.localDescription);
694 setLocalDescription = vi.fn(async () => {});
695 setRemoteDescription = vi.fn(async () => {});
696 addTransceiver = vi.fn(() => ({ setCodecPreferences: vi.fn() }));
697 addEventListener = vi.fn();
698 removeEventListener = vi.fn();
699 readonly config: unknown;
700 constructor(config: unknown) {
701 this.config = config;
702 peers.push(this);
703 }
704 }
705 vi.stubGlobal("WebSocket", Socket);
706 vi.stubGlobal("RTCPeerConnection", Peer);
707 vi.stubGlobal("RTCRtpReceiver", { getCapabilities: () => ({ codecs: [] }) });
708 vi.stubGlobal("document", { createElement: () => new Video(), body: { append: vi.fn() } });
709 const fetch = vi.fn((url: string, _init?: RequestInit) =>
710 Promise.resolve(
711 url.includes("/api?")
712 ? Response.json({ serial: "emulator-5554", stream })
713 : Response.json({ type: "answer", sdp: "answer-sdp" }),
714 ),
715 );
716 vi.stubGlobal("fetch", fetch);
717 const events = {
718 onStatus: vi.fn(),
719 onScreen: vi.fn(),
720 onUnauthorized: vi.fn(),
721 onMjpegFallback: vi.fn(),
722 onCanvasVideo: vi.fn(),
723 onInputConnected: vi.fn(),
724 };
725 const present = vi.fn(() => true);
726 const client = createDeviceStreamClient(
727 {
728 platform,
729 deviceId: "session-1",
730 access: {
731 httpBase: "https://test/api/device-hub",
732 wsBase: "wss://test/api/device-hub",
733 credentials: true,
734 query: { hostId: "eas" },
735 },
736 },
737 { present },
738 events,
739 );
740 const image = new MjpegImage();
741 client.setMjpegImage(image as unknown as HTMLImageElement);
742 return { client, events, fetch, peers, videos, sockets, present, image };
743 }
744
745 const serveSim = "https://test/api/device-hub/vendor/serve-sim";
746 const mjpegUrl = `${serveSim}/helper/session-1/stream.mjpeg?hostId=eas`;
747
748 it("streams over WebRTC when serve-emu advertises it, with input that reconnects on its own", async () => {
749 const { client, events, fetch, peers, videos, sockets, present } = setup();
750 client.start();
751 await vi.advanceTimersByTimeAsync(0);
752 expect(fetch.mock.calls.map(([url]) => url)).toEqual([
753 "https://test/api/device-hub/vendor/serve-emu/api?device=session-1&hostId=eas",
754 "https://test/api/device-hub/vendor/serve-emu/webrtc/offer?device=session-1&hostId=eas",
755 ]);
756 expect(peers[0]?.setRemoteDescription).toHaveBeenCalledWith({
757 type: "answer",
758 sdp: "answer-sdp",
759 });
760 peers[0]?.ontrack?.({ streams: [{}], track: {} });
761 videos[0]?.callback?.();
762 expect(present).toHaveBeenCalledWith(videos[0], 400, 800);
763 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
764
765 expect(sockets.map((socket) => socket.url)).toEqual([
766 "wss://test/api/device-hub/vendor/serve-emu/ws?device=session-1&video=0&hostId=eas",
767 ]);
768 sockets[0]!.onopen?.();
769 client.pressButton("back");
770 expect(sockets[0]!.send).toHaveBeenCalledWith(JSON.stringify({ type: "back" }));
771 events.onStatus.mockClear();
772 sockets[0]!.onclose?.({ code: 1001, reason: "going away" });
773 await vi.advanceTimersByTimeAsync(1_000);
774 expect(sockets[1]?.url).toContain("video=0");
775 expect(peers).toHaveLength(1);
776 expect(peers[0]?.close).not.toHaveBeenCalled();
777 expect(events.onStatus).not.toHaveBeenCalled();
778 client.stop();
779 });
780
781 it("streams an iOS simulator over WebRTC instead of MJPEG when WebCodecs is missing", async () => {
782 // T3 Code's own device hub reports "http" and still answers WebRTC offers.
783 const iceServers = [{ urls: "turn:turn.test:3478", username: "u", credential: "c" }];
784 const { client, events, fetch, peers, videos, present, image } = setup("ios", {
785 transport: "http",
786 h264Fps: 60,
787 iceServers,
788 iceTransportPolicy: "relay",
789 });
790 client.start();
791 await vi.advanceTimersByTimeAsync(0);
792 expect(fetch.mock.calls.map(([url]) => url)).toEqual([
793 // The input socket primes serve-sim's capture with one aborted MJPEG request.
794 mjpegUrl,
795 `${serveSim}/api?device=session-1&hostId=eas`,
796 `${serveSim}/helper/session-1/webrtc/offer?hostId=eas`,
797 ]);
798 expect(peers[0]?.config).toEqual({ iceServers, iceTransportPolicy: "relay" });
799 peers[0]?.ontrack?.({ streams: [{}], track: {} });
800 videos[0]?.callback?.();
801 expect(present).toHaveBeenCalledWith(videos[0], 400, 800);
802 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
803 expect(events.onMjpegFallback).not.toHaveBeenCalled();
804 expect(image.src).toBe("");
805 client.stop();
806 });
807
808 it("drops to MJPEG at once when serve-sim refuses the iOS WebRTC offer", async () => {
809 const { client, events, fetch, peers, image } = setup("ios", null);
810 fetch.mockImplementation((url: string) =>
811 Promise.resolve(
812 url.includes("/webrtc/offer")
813 ? new Response(null, { status: 404 })
814 : Response.json({ serial: "sim" }),
815 ),
816 );
817 client.start();
818 await vi.advanceTimersByTimeAsync(0);
819 expect(peers).toHaveLength(1);
820 expect(peers[0]?.close).toHaveBeenCalled();
821 expect(events.onMjpegFallback).toHaveBeenCalledWith(mjpegUrl);
822 expect(image.src).toBe(mjpegUrl);
823 client.stop();
824 });
825
826 it("falls back to MJPEG once when an iOS WebRTC attempt shows no video", async () => {
827 const stream = { transport: "http" };
828 const { client, events, peers, image } = setup("ios", stream);
829 const imageReady = () => {
830 image.naturalWidth = 400;
831 image.naturalHeight = 800;
832 image.dispatchEvent(new Event("load"));
833 };
834 client.start();
835 await vi.advanceTimersByTimeAsync(0);
836 peers[0]!.connectionState = "failed";
837 peers[0]!.onconnectionstatechange?.();
838 await vi.advanceTimersByTimeAsync(7_000);
839 expect(events.onMjpegFallback).not.toHaveBeenCalled();
840 await vi.advanceTimersByTimeAsync(1_000);
841 expect(events.onMjpegFallback).toHaveBeenCalledWith(mjpegUrl);
842 expect(image.src).toBe(mjpegUrl);
843 expect(peers.every((peer) => peer.close.mock.calls.length > 0)).toBe(true);
844 imageReady();
845 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
846 const attempts = peers.length;
847 await vi.advanceTimersByTimeAsync(30_000);
848 expect(peers).toHaveLength(attempts);
849 expect(events.onStatus).not.toHaveBeenCalledWith("error", expect.anything());
850
851 // A refused MJPEG image switches to WebRTC, which then fails instead of bouncing back.
852 stream.transport = "webrtc";
853 image.dispatchEvent(new Event("error"));
854 await vi.advanceTimersByTimeAsync(15_000);
855 expect(peers).toHaveLength(attempts + 1);
856 expect(events.onMjpegFallback).toHaveBeenCalledOnce();
857 expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.any(String));
858 client.stop();
859 });
860
861 it("keeps an iOS host that reports WebRTC on WebRTC for the full first-frame window", async () => {
862 const { client, events, peers } = setup("ios");
863 client.start();
864 await vi.advanceTimersByTimeAsync(0);
865 peers[0]!.connectionState = "failed";
866 peers[0]!.onconnectionstatechange?.();
867 await vi.advanceTimersByTimeAsync(14_000);
868 expect(peers.length).toBeGreaterThan(1);
869 expect(events.onStatus).not.toHaveBeenCalledWith("error", expect.anything());
870 await vi.advanceTimersByTimeAsync(1_000);
871 expect(events.onMjpegFallback).not.toHaveBeenCalled();
872 expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.any(String));
873 client.stop();
874 });
875
876 it("gives WebRTC and then MJPEG a full window each after the probe times out", async () => {
877 const { client, events, fetch, peers, image } = setup("ios");
878 fetch.mockImplementation((url: string, init?: RequestInit) =>
879 url.includes("/api?")
880 ? new Promise<Response>((_resolve, reject) =>
881 init?.signal?.addEventListener("abort", () =>
882 reject(new DOMException("aborted", "AbortError")),
883 ),
884 )
885 : Promise.resolve(Response.json({ type: "answer", sdp: "answer-sdp" })),
886 );
887 client.start();
888 await vi.advanceTimersByTimeAsync(5_000);
889 expect(peers).toHaveLength(1);
890 await vi.advanceTimersByTimeAsync(7_000);
891 expect(events.onMjpegFallback).not.toHaveBeenCalled();
892 await vi.advanceTimersByTimeAsync(1_000);
893 expect(events.onMjpegFallback).toHaveBeenCalledWith(mjpegUrl);
894 await vi.advanceTimersByTimeAsync(14_000);
895 expect(events.onStatus).not.toHaveBeenCalledWith("error", expect.anything());
896 image.naturalWidth = 400;
897 image.naturalHeight = 800;
898 image.dispatchEvent(new Event("load"));
899 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
900 client.stop();
901 });
902
903 it("shows the WebRTC canvas again when a restart follows an MJPEG fallback", async () => {
904 const { client, events, peers, videos, present } = setup("ios", { transport: "http" });
905 client.start();
906 await vi.advanceTimersByTimeAsync(0);
907 peers[0]!.connectionState = "failed";
908 peers[0]!.onconnectionstatechange?.();
909 await vi.advanceTimersByTimeAsync(15_000);
910 expect(events.onMjpegFallback).toHaveBeenCalledWith(mjpegUrl);
911 client.stop();
912 events.onCanvasVideo.mockClear();
913 client.start();
914 await vi.advanceTimersByTimeAsync(0);
915 expect(events.onCanvasVideo).toHaveBeenCalledOnce();
916 const video = videos.at(-1)!;
917 peers.at(-1)!.ontrack?.({ streams: [{}], track: {} });
918 video.callback?.();
919 expect(present).toHaveBeenLastCalledWith(video, 400, 800);
920 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
921 client.stop();
922 });
923
924 it.each(["http", "webrtc"])(
925 "restarts the iOS WebRTC feed when Duo panels are cleared without WebCodecs (%s host)",
926 async (transport) => {
927 const { client, events, fetch, sockets, peers, videos, present } = setup("ios", {
928 transport,
929 });
930 client.start();
931 await vi.advanceTimersByTimeAsync(0);
932 // A screen config (tag 0x82) with a hinge lets the viewer enter Duo.
933 const sendScreen = (supportsPhysicalOrientation: boolean) => {
934 const config = new TextEncoder().encode(
935 JSON.stringify({
936 width: 400,
937 height: 800,
938 orientation: "portrait",
939 supportsHingeAngle: true,
940 supportsPhysicalOrientation,
941 }),
942 );
943 const message = new Uint8Array(1 + config.length);
944 message[0] = 0x82;
945 message.set(config, 1);
946 sockets[0]!.onmessage?.({ data: message.buffer } as unknown as { data: string });
947 };
948 sendScreen(false);
949 const panel = { present: vi.fn(() => true) };
950 const panels = { cover: panel, inner: panel } as unknown as Parameters<
951 typeof client.setDuoPanels
952 >[0];
953 client.setDuoPanels(panels);
954 const mainOffer = `${serveSim}/helper/session-1/webrtc/offer?hostId=eas`;
955 const offers = () => fetch.mock.calls.filter(([url]) => url === mainOffer).length;
956 const before = offers();
957 client.setDuoPanels(null);
958 await vi.advanceTimersByTimeAsync(0);
959 expect(offers()).toBe(before + 1);
960 present.mockClear();
961 peers.at(-1)!.ontrack?.({ streams: [{}], track: {} });
962 videos.at(-1)!.callback?.();
963 expect(present).toHaveBeenCalledWith(videos.at(-1), 400, 800);
964
965 // Panels installed again while the restart probes /api keep the main feed closed.
966 client.setDuoPanels(panels);
967 client.setDuoPanels(null);
968 client.setDuoPanels(panels);
969 await vi.advanceTimersByTimeAsync(0);
970 expect(offers()).toBe(before + 1);
971
972 // Panels installed again before the restarted feed's first frame keep the Duo feed streaming.
973 client.setDuoPanels(null);
974 await vi.advanceTimersByTimeAsync(0);
975 expect(offers()).toBe(before + 2);
976 sendScreen(true);
977 client.setDuoPanels(panels);
978 await vi.advanceTimersByTimeAsync(0);
979 peers.at(-1)!.ontrack?.({ streams: [{}], track: {} });
980 for (let i = 0; i < 4; i++) {
981 present.mockClear();
982 videos.at(-1)!.callback?.();
983 expect(present).toHaveBeenCalledWith(videos.at(-1), 400, 800);
984 await vi.advanceTimersByTimeAsync(5_000);
985 }
986 expect(events.onMjpegFallback).not.toHaveBeenCalled();
987 expect(events.onStatus).not.toHaveBeenCalledWith("error", expect.anything());
988 // Duo's frames are the viewer's frames, so the status does not stay connecting.
989 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
990 client.stop();
991 },
992 );
993});