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

stream.test.ts

925 lines32.8 KB

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(new Response("frame")));
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("uses authenticated iOS MJPEG and forwards controls without a cross-origin video fetch", async () => {
106 const { client, opened, events, fetch } = setup("ios");
107 client.start();
108 const socket = await opened;
109 const imageUrl = new URL(events.onMjpegFallback.mock.calls[0]![0] as string);
110 expect(imageUrl.pathname).toContain("test%20device/stream.mjpeg");
111 expect(imageUrl.searchParams.get("wsTicket")).toBe("stream-ticket");
112 expect(imageUrl.searchParams.get("hostId")).toBe("ssh-host");
113 expect(fetch).toHaveBeenCalledTimes(1);
114 socket.onopen?.();
115 expect(socket.send).not.toHaveBeenCalled();
116 socket.onmessage?.({ data: Uint8Array.of(0x83).buffer });
117 client.sendText("hello");
118 expect(socket.send).not.toHaveBeenCalled();
119 client.setOrientation("landscape_right");
120 client.pressButton("home");
121 client.sendTouch("begin", 0.25, 0.75);
122 const messages = socket.send.mock.calls.map(([bytes]) => {
123 const packet = bytes as Uint8Array;
124 return {
125 tag: packet[0],
126 body: JSON.parse(new TextDecoder().decode(packet.subarray(1))) as unknown,
127 };
128 });
129 expect(messages).toEqual([
130 { tag: 0x07, body: { orientation: "landscape_right" } },
131 { tag: 0x04, body: { button: "home" } },
132 { tag: 0x03, body: { type: "begin", x: 0.25, y: 0.75 } },
133 ]);
134 client.stop();
135 expect(socket.close).toHaveBeenCalledTimes(1);
136 expect(vi.getTimerCount()).toBe(0);
137 });
138​
139 it("forwards Android gestures and device controls through the ticketed host socket", async () => {
140 const { client, opened } = setup("android");
141 client.start();
142 const socket = await opened;
143 const url = new URL(socket.url);
144 expect(url.searchParams.get("device")).toBe("test device");
145 expect(url.searchParams.get("wsTicket")).toBe("stream-ticket");
146 expect(url.searchParams.get("hostId")).toBe("ssh-host");
147 client.sendTouch("begin", 0.2, 0.8);
148 client.sendTouch("move", 0.2, 0.4);
149 client.sendTouch("end", 0.2, 0.1);
150 client.setOrientation("landscape_right");
151 client.pressButton("home");
152 client.pressButton("appSwitcher");
153 const prefix = "a".repeat(299);
154 client.sendText(`${prefix}ä`);
155 expect(
156 socket.send.mock.calls.map(([message]) => JSON.parse(message as string) as unknown),
157 ).toEqual([
158 { type: "touch", action: "down", x: 0.2, y: 0.8 },
159 { type: "touch", action: "move", x: 0.2, y: 0.4 },
160 { type: "touch", action: "up", x: 0.2, y: 0.1 },
161 { type: "home" },
162 { type: "recents" },
163 { type: "text", text: prefix },
164 { type: "text", text: "ä" },
165 ]);
166 client.stop();
167 expect(socket.close).toHaveBeenCalledTimes(1);
168 });
169​
170 it("renews an expired Android ticket when the HTTP upgrade is rejected instead of retrying it forever", async () => {
171 const { client, opened, events } = setup("android");
172 client.start();
173 const socket = await opened;
174 socket.onclose?.({ code: 1006, reason: "" });
175 expect(events.onUnauthorized).toHaveBeenCalledTimes(1);
176 expect(vi.getTimerCount()).toBe(0);
177 client.stop();
178 });
179​
180 it.each(["ios", "android"] as const)(
181 "keeps a restarted %s stream connected when the discarded socket closes late",
182 async (platform) => {
183 const { client, opened, waitForSocket, events } = setup(platform);
184 client.start();
185 const discarded = await opened;
186 client.stop();
187 const reopened = waitForSocket();
188 client.start();
189 const replacement = await reopened;
190 replacement.onopen?.();
191 if (platform === "ios") replacement.onmessage?.({ data: Uint8Array.of(0x83).buffer });
192 replacement.send.mockClear();
193 events.onInputConnected.mockClear();
194​
195 discarded.onclose?.({ code: 1006, reason: "" });
196​
197 expect(events.onUnauthorized).not.toHaveBeenCalled();
198 expect(events.onInputConnected).not.toHaveBeenCalled();
199 expect(replacement.close).not.toHaveBeenCalled();
200 client.pressButton("home");
201 expect(replacement.send).toHaveBeenCalledTimes(1);
202 client.stop();
203 expect(replacement.close).toHaveBeenCalledTimes(1);
204 expect(vi.getTimerCount()).toBe(0);
205 },
206 );
207​
208 it.each(["ios", "android"] as const)(
209 "does not renew credentials or reconnect a stopped %s stream",
210 async (platform) => {
211 const { client, opened, events } = setup(platform);
212 client.start();
213 const socket = await opened;
214 events.onInputConnected.mockClear();
215 client.stop();
216 socket.onclose?.({ code: 1006, reason: "" });
217 expect(events.onUnauthorized).not.toHaveBeenCalled();
218 expect(events.onInputConnected).not.toHaveBeenCalled();
219 expect(vi.getTimerCount()).toBe(0);
220 },
221 );
222});
223​
224describe("serve-emu frames", () => {
225 it("strips the SEMU header and reads the keyframe flag and timestamp", () => {
226 const buffer = new ArrayBuffer(16 + 3);
227 const view = new DataView(buffer);
228 view.setUint32(0, 0x53454d55);
229 view.setUint8(4, 1);
230 view.setUint8(5, 1);
231 view.setBigUint64(8, 123456n);
232 new Uint8Array(buffer).set([7, 8, 9], 16);
233 const packet = parseSemuPacket(buffer);
234 expect(packet.isKey).toBe(true);
235 expect(packet.timestamp).toBe(123456);
236 expect(Array.from(packet.data)).toEqual([7, 8, 9]);
237 });
238​
239 it("treats a frame without the header as raw data", () => {
240 const packet = parseSemuPacket(new Uint8Array([0, 0, 1, 0x65]).buffer);
241 expect(packet.isKey).toBeNull();
242 expect(packet.data.length).toBe(4);
243 });
244​
245 it("finds the SPS and IDR NAL units in an Annex-B access unit", () => {
246 const unit = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0x00, 0x1f, 0, 0, 1, 0x65, 0xaa]);
247 const scanned = scanAccessUnit(unit);
248 expect(scanned.isKey).toBe(true);
249 expect(scanned.sps && avcCodecString(scanned.sps)).toBe("avc1.64001f");
250 expect(scanAccessUnit(new Uint8Array([0, 0, 1, 0x41, 0x00])).isKey).toBe(false);
251 });
252});
253​
254describe("iOS input startup", () => {
255 afterEach(() => {
256 vi.useRealTimers();
257 vi.unstubAllGlobals();
258 });
259​
260 const setup = () => {
261 vi.useFakeTimers();
262 const sockets: FakeSocket[] = [];
263 class FakeSocket {
264 static OPEN = 1;
265 readyState = 1;
266 binaryType = "";
267 onopen: (() => void) | null = null;
268 onmessage: ((event: { data: ArrayBuffer }) => void) | null = null;
269 onclose: ((event: { code: number; reason: string }) => void) | null = null;
270 send = vi.fn();
271 close = vi.fn();
272 constructor() {
273 sockets.push(this);
274 }
275 }
276 vi.stubGlobal("WebSocket", FakeSocket);
277 const signals: AbortSignal[] = [];
278 vi.stubGlobal(
279 "fetch",
280 vi.fn((_url, init: RequestInit) => {
281 const signal = init.signal!;
282 signals.push(signal);
283 return Promise.resolve(
284 new Response(
285 new ReadableStream({
286 start(controller) {
287 signal.addEventListener("abort", () => controller.error(new Error("aborted")));
288 },
289 }),
290 ),
291 );
292 }),
293 );
294 const client = createDeviceStreamClient(
295 {
296 platform: "ios",
297 deviceId: "test-device",
298 access: {
299 httpBase: "http://test/api/device-hub",
300 wsBase: "ws://test/api/device-hub",
301 credentials: true,
302 query: {},
303 },
304 },
305 { getContext: () => null } as unknown as HTMLCanvasElement,
306 {
307 onStatus: vi.fn(),
308 onScreen: vi.fn(),
309 onUnauthorized: vi.fn(),
310 onMjpegFallback: vi.fn(),
311 onInputConnected: vi.fn(),
312 },
313 );
314 return { client, sockets, signals };
315 };
316​
317 it("connects input when the MJPEG prime never produces a frame", async () => {
318 const { client, sockets, signals } = setup();
319 client.start();
320 await vi.advanceTimersByTimeAsync(2_000);
321 expect(signals[0]?.aborted).toBe(true);
322 expect(sockets).toHaveLength(1);
323 client.stop();
324 });
325​
326 it("aborts priming immediately when hidden without opening a socket later", async () => {
327 const { client, sockets, signals } = setup();
328 client.start();
329 await vi.advanceTimersByTimeAsync(0);
330 client.stop();
331 expect(signals[0]?.aborted).toBe(true);
332 await vi.advanceTimersByTimeAsync(2_000);
333 expect(sockets).toHaveLength(0);
334 });
335​
336 it.each([
337 ["landscape_left", 0.7, 1 - 0.2],
338 ["landscape_right", 1 - 0.7, 0.2],
339 ])("maps %s touches back to the raw iOS framebuffer", async (orientation, x, y) => {
340 const { client, sockets } = setup();
341 client.start();
342 await vi.advanceTimersByTimeAsync(2_000);
343 const socket = sockets[0]!;
344 const json = new TextEncoder().encode(JSON.stringify({ width: 400, height: 800, orientation }));
345 const packet = new Uint8Array(1 + json.length);
346 packet[0] = 0x82;
347 packet.set(json, 1);
348 socket.onmessage?.({ data: packet.buffer });
349 socket.onmessage?.({ data: Uint8Array.of(0x83).buffer });
350 client.sendTouch("begin", 0.2, 0.7);
351 const sent = socket.send.mock.calls[0]![0] as Uint8Array;
352 expect(JSON.parse(new TextDecoder().decode(sent.subarray(1)))).toEqual({
353 type: "begin",
354 x,
355 y,
356 });
357 client.stop();
358 });
359});
360​
361class MjpegImage extends EventTarget {
362 naturalWidth = 0;
363 naturalHeight = 0;
364 src = "";
365 removeAttribute(name: string) {
366 if (name === "src") {
367 this.src = "";
368 this.naturalWidth = 0;
369 this.naturalHeight = 0;
370 }
371 }
373​
374function recoveryFixture(platform: "ios" | "android" = "ios", preferMjpeg = true) {
375 vi.useFakeTimers();
376 const sockets: Socket[] = [];
377 class Socket {
378 static OPEN = 1;
379 readyState = 1;
380 binaryType = "";
381 onopen: (() => void) | null = null;
382 onmessage: ((event: { data: ArrayBuffer | string }) => void) | null = null;
383 onclose: ((event: { code: number; reason: string }) => void) | null = null;
384 send = vi.fn();
385 close = vi.fn();
386 constructor() {
387 sockets.push(this);
388 }
389 }
390 vi.stubGlobal("WebSocket", Socket);
391 const decoders: Decoder[] = [];
392 class Decoder {
393 static isConfigSupported = vi.fn(async () => ({ supported: true }));
394 state = "unconfigured";
395 decodeQueueSize = 0;
396 configure() {
397 this.state = "configured";
398 }
399 reset = vi.fn(() => {
400 this.state = "unconfigured";
401 this.decodeQueueSize = 0;
402 });
403 close() {
404 this.state = "closed";
405 }
406 decode = vi.fn();
407 readonly callbacks: { output: (frame: VideoFrame) => void; error: () => void };
408 constructor(callbacks: { output: (frame: VideoFrame) => void; error: () => void }) {
409 this.callbacks = callbacks;
410 decoders.push(this);
411 }
412 }
413 vi.stubGlobal("VideoDecoder", Decoder);
414 vi.stubGlobal("EncodedVideoChunk", vi.fn());
415 const videoBodies: ReadableStreamDefaultController<Uint8Array>[] = [];
416 const signals: AbortSignal[] = [];
417 const fetch = vi.fn((url: string, init: RequestInit) => {
418 const signal = init.signal!;
419 signals.push(signal);
420 if (!url.includes("stream.avcc")) return Promise.resolve(new Response("prime"));
421 return Promise.resolve(
422 new Response(
423 new ReadableStream<Uint8Array>({
424 start(body) {
425 videoBodies.push(body);
426 signal.addEventListener("abort", () => body.error(new Error("aborted")), {
427 once: true,
428 });
429 },
430 }),
431 ),
432 );
433 });
434 vi.stubGlobal("fetch", fetch);
435 const events = {
436 onStatus: vi.fn(),
437 onScreen: vi.fn(),
438 onUnauthorized: vi.fn(),
439 onMjpegFallback: vi.fn(),
440 onInputConnected: vi.fn(),
441 };
442 const drawImage = vi.fn();
443 const image = new MjpegImage();
444 const client = createDeviceStreamClient(
445 {
446 platform,
447 preferMjpeg,
448 deviceId: "test-device",
449 access: {
450 httpBase: "https://test/api/device-hub",
451 wsBase: "wss://test/api/device-hub",
452 credentials: true,
453 query: {},
454 },
455 },
456 { getContext: () => ({ drawImage }) } as unknown as HTMLCanvasElement,
457 events,
458 );
459 client.setMjpegImage(image as unknown as HTMLImageElement);
460 const imageReady = () => {
461 image.naturalWidth = 400;
462 image.naturalHeight = 800;
463 image.dispatchEvent(new Event("load"));
464 };
465 const decodedFrame = (index = decoders.length - 1) => {
466 const close = vi.fn();
467 decoders[index]!.callbacks.output({
468 displayWidth: 400,
469 displayHeight: 800,
470 close,
471 } as unknown as VideoFrame);
472 return close;
473 };
474 const sps = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0, 0x1f, 0, 0, 1, 0x65]).buffer;
475 return {
476 client,
477 events,
478 image,
479 imageReady,
480 sockets,
481 signals,
482 fetch,
483 videoBodies,
484 decoders,
485 Decoder,
486 drawImage,
487 decodedFrame,
488 sps,
489 };
491​
492describe("shared device stream readiness and recovery", () => {
493 afterEach(() => {
494 vi.useRealTimers();
495 vi.unstubAllGlobals();
496 });
497​
498 it("waits for iOS input admission and respects native input loss and recovery", async () => {
499 const { client, sockets, events } = recoveryFixture();
500 client.start();
501 await vi.advanceTimersByTimeAsync(0);
502 const socket = sockets[0]!;
503 socket.onopen?.();
504 expect(events.onInputConnected).not.toHaveBeenCalledWith(true);
505 socket.onmessage?.({ data: new Uint8Array([0x83]).buffer });
506 expect(events.onInputConnected).toHaveBeenLastCalledWith(true);
507 const config = (inputUnavailable: boolean) => {
508 const json = new TextEncoder().encode(
509 JSON.stringify({ width: 400, height: 800, orientation: "portrait", inputUnavailable }),
510 );
511 const packet = new Uint8Array(1 + json.length);
512 packet[0] = 0x82;
513 packet.set(json, 1);
514 socket.onmessage?.({ data: packet.buffer });
515 };
516 config(true);
517 expect(events.onInputConnected).toHaveBeenLastCalledWith(
518 false,
519 "Simulator input is unavailable",
520 );
521 socket.send.mockClear();
522 client.sendTouch("begin", 0.2, 0.3);
523 client.pressButton("home");
524 expect(socket.send).not.toHaveBeenCalled();
525 config(false);
526 expect(events.onInputConnected).toHaveBeenLastCalledWith(true, undefined);
527 client.sendTouch("begin", 0.2, 0.3);
528 expect(socket.send).toHaveBeenCalledOnce();
529 client.stop();
530 expect(vi.getTimerCount()).toBe(0);
531 });
532​
533 it("requires admission on each iOS socket and does not mistake config for admission", async () => {
534 const { client, sockets, events, imageReady } = recoveryFixture();
535 client.start();
536 await vi.advanceTimersByTimeAsync(0);
537 imageReady();
538 const config = (socket: (typeof sockets)[number], unavailable: boolean) => {
539 const json = new TextEncoder().encode(
540 JSON.stringify({
541 width: 400,
542 height: 800,
543 orientation: "portrait",
544 inputUnavailable: unavailable,
545 supportsHingeAngle: true,
546 }),
547 );
548 socket.onmessage?.({ data: Uint8Array.of(0x82, ...json).buffer });
549 };
550 const controls = () => {
551 client.sendTouch("begin", 0.2, 0.3);
552 client.pressButton("home");
553 client.sendKey({ code: "KeyA" } as KeyboardEvent, "down");
554 client.setOrientation("landscape_left");
555 client.controlDuo({ control: "angle", value: 90 });
556 };
557 const first = sockets[0]!;
558 config(first, false);
559 controls();
560 expect(first.send).not.toHaveBeenCalled();
561 expect(events.onInputConnected).not.toHaveBeenCalledWith(true, undefined);
562 config(first, true);
563 first.onmessage?.({ data: Uint8Array.of(0x83).buffer });
564 controls();
565 expect(first.send).not.toHaveBeenCalled();
566 expect(events.onInputConnected).toHaveBeenLastCalledWith(false);
567 config(first, false);
568 client.pressButton("home");
569 expect(first.send).toHaveBeenCalled();
570 first.onclose?.({ code: 1013, reason: "retry" });
571 await vi.advanceTimersByTimeAsync(1_000);
572 const replacement = sockets[1]!;
573 config(replacement, false);
574 controls();
575 expect(replacement.send).not.toHaveBeenCalled();
576 first.onmessage?.({ data: Uint8Array.of(0x83).buffer });
577 expect(events.onInputConnected).toHaveBeenLastCalledWith(false, undefined);
578 replacement.onmessage?.({ data: Uint8Array.of(0x83).buffer });
579 client.pressButton("home");
580 expect(replacement.send).toHaveBeenCalledOnce();
581 client.stop();
582 expect(vi.getTimerCount()).toBe(0);
583 });
584​
585 it("reopens a backlogged iOS feed for a fresh keyframe while keeping input connected", async () => {
586 const { client, videoBodies, decoders, events, decodedFrame, signals, sockets, drawImage } =
587 recoveryFixture("ios", false);
588 client.start();
589 await vi.advanceTimersByTimeAsync(0);
590 const socket = sockets[0]!;
591 socket.onmessage?.({ data: Uint8Array.of(0x83).buffer });
592 const body = videoBodies[0]!;
593 body.enqueue(new Uint8Array([...envelope(1, [1, 0x64, 0, 0x1f]), ...envelope(2, [1])]));
594 await vi.advanceTimersByTimeAsync(0);
595 decodedFrame();
596 const decoder = decoders[0]!;
597 decoder.decodeQueueSize = 9;
598 body.enqueue(new Uint8Array([...envelope(3, [2]), ...envelope(3, [3])]));
599 await vi.advanceTimersByTimeAsync(0);
600 expect(signals[1]!.aborted).toBe(true);
601 expect(decoder.state).toBe("closed");
602 expect(events.onStatus).toHaveBeenLastCalledWith(
603 "connecting",
604 expect.stringContaining("fell behind"),
605 );
606 expect(socket.close).not.toHaveBeenCalled();
607 client.sendTouch("begin", 0.2, 0.3);
608 expect(socket.send).toHaveBeenCalledOnce();
609 await vi.advanceTimersByTimeAsync(1_000);
610 expect(videoBodies).toHaveLength(2);
611 videoBodies[1]!.enqueue(
612 new Uint8Array([...envelope(1, [1, 0x64, 0, 0x1f]), ...envelope(2, [4])]),
613 );
614 await vi.advanceTimersByTimeAsync(0);
615 expect(decoders[1]!.decode).toHaveBeenCalledOnce();
616 drawImage.mockClear();
617 decodedFrame(0);
618 expect(drawImage).not.toHaveBeenCalled();
619 decodedFrame();
620 expect(drawImage).toHaveBeenCalledOnce();
621 expect(events.onMjpegFallback).not.toHaveBeenCalled();
622 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
623 expect(events.onInputConnected).toHaveBeenLastCalledWith(true);
624 client.stop();
625 expect(vi.getTimerCount()).toBe(0);
626 });
627​
628 it("does not repaint a delayed JPEG seed over newer decoded video", async () => {
629 const { client, videoBodies, drawImage, decodedFrame } = recoveryFixture("ios", false);
630 let resolveBitmap!: (bitmap: ImageBitmap) => void;
631 vi.stubGlobal(
632 "createImageBitmap",
633 () =>
634 new Promise((resolve) => {
635 resolveBitmap = resolve;
636 }),
637 );
638 client.start();
639 await vi.advanceTimersByTimeAsync(0);
640 videoBodies[0]!.enqueue(
641 new Uint8Array([
642 ...envelope(4, [1]),
643 ...envelope(1, [1, 0x64, 0, 0x1f]),
644 ...envelope(2, [2]),
645 ]),
646 );
647 await vi.advanceTimersByTimeAsync(0);
648 decodedFrame();
649 const close = vi.fn();
650 resolveBitmap({ width: 400, height: 800, close } as unknown as ImageBitmap);
651 await vi.advanceTimersByTimeAsync(0);
652 expect(drawImage).toHaveBeenCalledOnce();
653 expect(close).toHaveBeenCalledOnce();
654 client.stop();
655 });
656​
657 it("waits for actual MJPEG dimensions without requiring a multipart load event", async () => {
658 const { client, events, image } = recoveryFixture();
659 client.start();
660 await vi.advanceTimersByTimeAsync(0);
661 expect(image.src).toContain("stream.mjpeg");
662 expect(events.onStatus).not.toHaveBeenCalledWith("streaming", undefined);
663 image.naturalWidth = 400;
664 image.naturalHeight = 800;
665 await vi.advanceTimersByTimeAsync(250);
666 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
667 expect(vi.getTimerCount()).toBe(0);
668 await vi.advanceTimersByTimeAsync(20_000);
669 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
670 client.stop();
671 });
672​
673 it("observes a web image attached after MJPEG fallback has already begun", async () => {
674 const { client, image, imageReady, events } = recoveryFixture();
675 client.setMjpegImage(null);
676 client.start();
677 expect(image.src).toBe("");
678 await vi.advanceTimersByTimeAsync(1000);
679 client.setMjpegImage(image as unknown as HTMLImageElement);
680 imageReady();
681 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
682 client.stop();
683 expect(image.src).toBe("");
684 expect(vi.getTimerCount()).toBe(0);
685 });
686​
687 it("stops input and video on an image error without treating it as expired credentials", async () => {
688 const { client, image, imageReady, sockets, events } = recoveryFixture();
689 client.start();
690 await vi.advanceTimersByTimeAsync(0);
691 sockets[0]!.onopen?.();
692 imageReady();
693 image.dispatchEvent(new Event("error"));
694 expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.stringContaining("Reconnect"));
695 expect(events.onInputConnected).toHaveBeenLastCalledWith(false, expect.any(String));
696 expect(events.onUnauthorized).not.toHaveBeenCalled();
697 expect(sockets[0]!.close).toHaveBeenCalledOnce();
698 expect(image.src).toBe("");
699 client.pressButton("home");
700 expect(sockets[0]!.send).not.toHaveBeenCalled();
701 expect(vi.getTimerCount()).toBe(0);
702 });
703​
704 it.each([
705 ["ios", true],
706 ["ios", false],
707 ["android", false],
708 ] as const)(
709 "bounds missing first frames for %s with preferMjpeg=%s",
710 async (platform, preferMjpeg) => {
711 const { client, events, signals, sockets, image } = recoveryFixture(platform, preferMjpeg);
712 client.start();
713 await vi.advanceTimersByTimeAsync(14_999);
714 expect(events.onStatus.mock.calls.some(([status]) => status === "error")).toBe(false);
715 await vi.advanceTimersByTimeAsync(1);
716 expect(events.onStatus).toHaveBeenLastCalledWith(
717 "error",
718 expect.stringContaining("No video"),
719 );
720 expect(events.onInputConnected).toHaveBeenLastCalledWith(false, expect.any(String));
721 expect(signals.every((signal) => signal.aborted)).toBe(true);
722 expect(sockets[0]!.close).toHaveBeenCalledOnce();
723 expect(image.src).toBe("");
724 expect(vi.getTimerCount()).toBe(0);
725 },
726 );
727​
728 it("does not extend the first-frame deadline each time a socket reconnects", async () => {
729 const { client, sockets, events } = recoveryFixture("android");
730 client.start();
731 sockets[0]!.onopen?.();
732 sockets[0]!.onclose?.({ code: 1000, reason: "restart" });
733 await vi.advanceTimersByTimeAsync(14_999);
734 sockets[1]!.onopen?.();
735 await vi.advanceTimersByTimeAsync(1);
736 expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.stringContaining("No video"));
737 expect(sockets[1]!.close).toHaveBeenCalledOnce();
738 expect(vi.getTimerCount()).toBe(0);
739 });
740​
741 it("gives a manual restart a fresh deadline and ignores queued image events from its old binding", async () => {
742 const { client, image, events } = recoveryFixture();
743 const listeners: EventListener[] = [];
744 const add = image.addEventListener.bind(image);
745 vi.spyOn(image, "addEventListener").mockImplementation((name, callback, options) => {
746 if (typeof callback === "function") listeners.push(callback);
747 add(name, callback, options);
748 });
749 client.start();
750 await vi.advanceTimersByTimeAsync(10_000);
751 client.stop();
752 client.start();
753 events.onStatus.mockClear();
754 for (const listener of listeners.slice(0, 2)) listener(new Event("error"));
755 await vi.advanceTimersByTimeAsync(10_000);
756 expect(events.onStatus).not.toHaveBeenCalled();
757 const replacement = new MjpegImage();
758 client.setMjpegImage(replacement as unknown as HTMLImageElement);
759 replacement.naturalWidth = 400;
760 replacement.naturalHeight = 800;
761 replacement.dispatchEvent(new Event("load"));
762 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
763 client.stop();
764 expect(vi.getTimerCount()).toBe(0);
765 });
766​
767 it("falls back from unsupported iOS H.264 without publishing a terminal error", async () => {
768 const { client, videoBodies, Decoder, events, imageReady } = recoveryFixture("ios", false);
769 Decoder.isConfigSupported.mockResolvedValue({ supported: false });
770 client.start();
771 await vi.advanceTimersByTimeAsync(0);
772 videoBodies[0]!.enqueue(new Uint8Array(envelope(1, [1, 0x64, 0, 0x1f])));
773 await vi.advanceTimersByTimeAsync(0);
774 expect(events.onMjpegFallback).toHaveBeenCalledOnce();
775 expect(events.onStatus.mock.calls.some(([status]) => status === "error")).toBe(false);
776 imageReady();
777 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
778 client.stop();
779 });
780​
781 it("publishes a terminal unsupported-profile error for Android and closes its socket", async () => {
782 const { client, sockets, sps, Decoder, events } = recoveryFixture("android");
783 Decoder.isConfigSupported.mockResolvedValue({ supported: false });
784 client.start();
785 sockets[0]!.onmessage?.({ data: sps });
786 await vi.advanceTimersByTimeAsync(0);
787 expect(events.onStatus).toHaveBeenLastCalledWith(
788 "error",
789 expect.stringContaining("cannot decode"),
790 );
791 expect(sockets[0]!.close).toHaveBeenCalledOnce();
792 expect(events.onMjpegFallback).not.toHaveBeenCalled();
793 expect(vi.getTimerCount()).toBe(0);
794 });
795​
796 it("waits for decoded Android output and bounds a rotation that never produces another frame", async () => {
797 const { client, sockets, sps, events, decodedFrame, drawImage } = recoveryFixture("android");
798 client.start();
799 sockets[0]!.onmessage?.({ data: sps });
800 await vi.advanceTimersByTimeAsync(0);
801 expect(events.onStatus.mock.calls.some(([status]) => status === "streaming")).toBe(false);
802 expect(decodedFrame()).toHaveBeenCalledOnce();
803 expect(drawImage).toHaveBeenCalledOnce();
804 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
805 sockets[0]!.onmessage?.({ data: JSON.stringify({ type: "video-session" }) });
806 await vi.advanceTimersByTimeAsync(15_000);
807 expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.stringContaining("No video"));
808 expect(vi.getTimerCount()).toBe(0);
809 });
810​
811 it("discards decoder support results and output from a previous Android socket", async () => {
812 const { client, sockets, sps, events, Decoder, decoders, decodedFrame, drawImage } =
813 recoveryFixture("android");
814 let resolveSupport!: (support: { supported: boolean }) => void;
815 Decoder.isConfigSupported.mockImplementationOnce(
816 () =>
817 new Promise((resolve) => {
818 resolveSupport = resolve;
819 }),
820 );
821 client.start();
822 sockets[0]!.onmessage?.({ data: sps });
823 client.stop();
824 client.start();
825 resolveSupport({ supported: true });
826 await vi.advanceTimersByTimeAsync(0);
827 expect(decoders).toHaveLength(0);
828 sockets[1]!.onmessage?.({ data: sps });
829 await vi.advanceTimersByTimeAsync(0);
830 client.stop();
831 client.start();
832 events.onStatus.mockClear();
833 expect(decodedFrame()).toHaveBeenCalledOnce();
834 expect(drawImage).not.toHaveBeenCalled();
835 expect(events.onStatus).not.toHaveBeenCalled();
836 client.stop();
837 });
838​
839 it("ignores an old AVCC response rejected after a new attempt is connected", async () => {
840 const { client, fetch, events } = recoveryFixture("ios", false);
841 let resolveResponse!: (response: Response) => void;
842 fetch.mockImplementationOnce(() => Promise.resolve(new Response("prime")));
843 fetch.mockImplementationOnce(
844 () =>
845 new Promise((resolve) => {
846 resolveResponse = resolve;
847 }),
848 );
849 client.start();
850 await vi.advanceTimersByTimeAsync(0);
851 client.stop();
852 client.start();
853 await vi.advanceTimersByTimeAsync(0);
854 events.onStatus.mockClear();
855 resolveResponse(new Response(null, { status: 401 }));
856 await vi.advanceTimersByTimeAsync(0);
857 expect(events.onUnauthorized).not.toHaveBeenCalled();
858 expect(events.onStatus).not.toHaveBeenCalled();
859 client.stop();
860 expect(vi.getTimerCount()).toBe(0);
861 });
862​
863 it("closes a delayed JPEG seed from a stopped AVCC attempt without painting it", async () => {
864 const { client, videoBodies, drawImage, events } = recoveryFixture("ios", false);
865 let resolveBitmap!: (bitmap: ImageBitmap) => void;
866 vi.stubGlobal(
867 "createImageBitmap",
868 () =>
869 new Promise((resolve) => {
870 resolveBitmap = resolve;
871 }),
872 );
873 client.start();
874 await vi.advanceTimersByTimeAsync(0);
875 videoBodies[0]!.enqueue(new Uint8Array(envelope(4, [1])));
876 await vi.advanceTimersByTimeAsync(0);
877 client.stop();
878 client.start();
879 events.onStatus.mockClear();
880 const close = vi.fn();
881 resolveBitmap({ width: 400, height: 800, close } as unknown as ImageBitmap);
882 await vi.advanceTimersByTimeAsync(0);
883 expect(close).toHaveBeenCalledOnce();
884 expect(drawImage).not.toHaveBeenCalled();
885 expect(events.onStatus).not.toHaveBeenCalled();
886 client.stop();
887 });
888});
889​
890it("reopens a stalled AVCC body without disconnecting input, then receives fresh video", async () => {
891 const { client, videoBodies, events, signals, sockets, decodedFrame } = recoveryFixture(
892 "ios",
893 false,
894 );
895 const close = vi.fn();
896 vi.stubGlobal("createImageBitmap", () => Promise.resolve({ width: 400, height: 800, close }));
897 try {
898 client.start();
899 await vi.advanceTimersByTimeAsync(0);
900 sockets[0]!.onmessage?.({ data: new Uint8Array([0x83]).buffer });
901 videoBodies[0]!.enqueue(new Uint8Array(envelope(4, [1])));
902 await vi.advanceTimersByTimeAsync(0);
903 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
904 await vi.advanceTimersByTimeAsync(15_000);
905 expect(events.onStatus).toHaveBeenLastCalledWith(
906 "connecting",
907 expect.stringContaining("stopped receiving video"),
908 );
909 expect(signals[1]!.aborted).toBe(true);
910 expect(sockets[0]!.close).not.toHaveBeenCalled();
911 expect(events.onInputConnected).toHaveBeenLastCalledWith(true);
912 await vi.advanceTimersByTimeAsync(1_000);
913 expect(videoBodies).toHaveLength(2);
914 videoBodies[1]!.enqueue(new Uint8Array(envelope(1, [1, 0x64, 0, 0x1f])));
915 await vi.advanceTimersByTimeAsync(0);
916 decodedFrame();
917 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
918 client.stop();
919 expect(vi.getTimerCount()).toBe(0);
920 } finally {
921 client.stop();
922 vi.useRealTimers();
923 vi.unstubAllGlobals();
924 }
925});