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

stream.test.ts

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