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

stream.test.ts

738 lines25.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 close() {
389 this.state = "closed";
390 }
391 decode() {}
392 readonly callbacks: { output: (frame: VideoFrame) => void; error: () => void };
393 constructor(callbacks: { output: (frame: VideoFrame) => void; error: () => void }) {
394 this.callbacks = callbacks;
395 decoders.push(this);
396 }
397 }
398 vi.stubGlobal("VideoDecoder", Decoder);
399 vi.stubGlobal("EncodedVideoChunk", vi.fn());
400 const videoBodies: ReadableStreamDefaultController<Uint8Array>[] = [];
401 const signals: AbortSignal[] = [];
402 const fetch = vi.fn((url: string, init: RequestInit) => {
403 const signal = init.signal!;
404 signals.push(signal);
405 if (!url.includes("stream.avcc")) return Promise.resolve(new Response("prime"));
406 return Promise.resolve(
407 new Response(
408 new ReadableStream<Uint8Array>({
409 start(body) {
410 videoBodies.push(body);
411 signal.addEventListener("abort", () => body.error(new Error("aborted")), {
412 once: true,
413 });
414 },
415 }),
416 ),
417 );
418 });
419 vi.stubGlobal("fetch", fetch);
420 const events = {
421 onStatus: vi.fn(),
422 onScreen: vi.fn(),
423 onUnauthorized: vi.fn(),
424 onMjpegFallback: vi.fn(),
425 onInputConnected: vi.fn(),
426 };
427 const drawImage = vi.fn();
428 const image = new MjpegImage();
429 const client = createDeviceStreamClient(
430 {
431 platform,
432 preferMjpeg,
433 deviceId: "test-device",
434 access: {
435 httpBase: "https://test/api/device-hub",
436 wsBase: "wss://test/api/device-hub",
437 credentials: true,
438 query: {},
439 },
440 },
441 { getContext: () => ({ drawImage }) } as unknown as HTMLCanvasElement,
442 events,
443 );
444 client.setMjpegImage(image as unknown as HTMLImageElement);
445 const imageReady = () => {
446 image.naturalWidth = 400;
447 image.naturalHeight = 800;
448 image.dispatchEvent(new Event("load"));
449 };
450 const decodedFrame = (index = decoders.length - 1) => {
451 const close = vi.fn();
452 decoders[index]!.callbacks.output({
453 displayWidth: 400,
454 displayHeight: 800,
455 close,
456 } as unknown as VideoFrame);
457 return close;
458 };
459 const sps = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0, 0x1f, 0, 0, 1, 0x65]).buffer;
460 return {
461 client,
462 events,
463 image,
464 imageReady,
465 sockets,
466 signals,
467 fetch,
468 videoBodies,
469 decoders,
470 Decoder,
471 drawImage,
472 decodedFrame,
473 sps,
474 };
476​
477describe("shared device stream readiness and recovery", () => {
478 afterEach(() => {
479 vi.useRealTimers();
480 vi.unstubAllGlobals();
481 });
482​
483 it("waits for actual MJPEG dimensions without requiring a multipart load event", async () => {
484 const { client, events, image } = recoveryFixture();
485 client.start();
486 await vi.advanceTimersByTimeAsync(0);
487 expect(image.src).toContain("stream.mjpeg");
488 expect(events.onStatus).not.toHaveBeenCalledWith("streaming", undefined);
489 image.naturalWidth = 400;
490 image.naturalHeight = 800;
491 await vi.advanceTimersByTimeAsync(250);
492 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
493 expect(vi.getTimerCount()).toBe(0);
494 await vi.advanceTimersByTimeAsync(20_000);
495 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
496 client.stop();
497 });
498​
499 it("observes a web image attached after MJPEG fallback has already begun", async () => {
500 const { client, image, imageReady, events } = recoveryFixture();
501 client.setMjpegImage(null);
502 client.start();
503 expect(image.src).toBe("");
504 await vi.advanceTimersByTimeAsync(1000);
505 client.setMjpegImage(image as unknown as HTMLImageElement);
506 imageReady();
507 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
508 client.stop();
509 expect(image.src).toBe("");
510 expect(vi.getTimerCount()).toBe(0);
511 });
512​
513 it("stops input and video on an image error without treating it as expired credentials", async () => {
514 const { client, image, imageReady, sockets, events } = recoveryFixture();
515 client.start();
516 await vi.advanceTimersByTimeAsync(0);
517 sockets[0]!.onopen?.();
518 imageReady();
519 image.dispatchEvent(new Event("error"));
520 expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.stringContaining("Reconnect"));
521 expect(events.onInputConnected).toHaveBeenLastCalledWith(false, expect.any(String));
522 expect(events.onUnauthorized).not.toHaveBeenCalled();
523 expect(sockets[0]!.close).toHaveBeenCalledOnce();
524 expect(image.src).toBe("");
525 client.pressButton("home");
526 expect(sockets[0]!.send).toHaveBeenCalledTimes(1);
527 expect(vi.getTimerCount()).toBe(0);
528 });
529​
530 it.each([
531 ["ios", true],
532 ["ios", false],
533 ["android", false],
534 ] as const)(
535 "bounds missing first frames for %s with preferMjpeg=%s",
536 async (platform, preferMjpeg) => {
537 const { client, events, signals, sockets, image } = recoveryFixture(platform, preferMjpeg);
538 client.start();
539 await vi.advanceTimersByTimeAsync(14_999);
540 expect(events.onStatus.mock.calls.some(([status]) => status === "error")).toBe(false);
541 await vi.advanceTimersByTimeAsync(1);
542 expect(events.onStatus).toHaveBeenLastCalledWith(
543 "error",
544 expect.stringContaining("No video"),
545 );
546 expect(events.onInputConnected).toHaveBeenLastCalledWith(false, expect.any(String));
547 expect(signals.every((signal) => signal.aborted)).toBe(true);
548 expect(sockets[0]!.close).toHaveBeenCalledOnce();
549 expect(image.src).toBe("");
550 expect(vi.getTimerCount()).toBe(0);
551 },
552 );
553​
554 it("does not extend the first-frame deadline each time a socket reconnects", async () => {
555 const { client, sockets, events } = recoveryFixture("android");
556 client.start();
557 sockets[0]!.onopen?.();
558 sockets[0]!.onclose?.({ code: 1000, reason: "restart" });
559 await vi.advanceTimersByTimeAsync(14_999);
560 sockets[1]!.onopen?.();
561 await vi.advanceTimersByTimeAsync(1);
562 expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.stringContaining("No video"));
563 expect(sockets[1]!.close).toHaveBeenCalledOnce();
564 expect(vi.getTimerCount()).toBe(0);
565 });
566​
567 it("gives a manual restart a fresh deadline and ignores queued image events from its old binding", async () => {
568 const { client, image, events } = recoveryFixture();
569 const listeners: EventListener[] = [];
570 const add = image.addEventListener.bind(image);
571 vi.spyOn(image, "addEventListener").mockImplementation((name, callback, options) => {
572 if (typeof callback === "function") listeners.push(callback);
573 add(name, callback, options);
574 });
575 client.start();
576 await vi.advanceTimersByTimeAsync(10_000);
577 client.stop();
578 client.start();
579 events.onStatus.mockClear();
580 for (const listener of listeners.slice(0, 2)) listener(new Event("error"));
581 await vi.advanceTimersByTimeAsync(10_000);
582 expect(events.onStatus).not.toHaveBeenCalled();
583 const replacement = new MjpegImage();
584 client.setMjpegImage(replacement as unknown as HTMLImageElement);
585 replacement.naturalWidth = 400;
586 replacement.naturalHeight = 800;
587 replacement.dispatchEvent(new Event("load"));
588 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
589 client.stop();
590 expect(vi.getTimerCount()).toBe(0);
591 });
592​
593 it("falls back from unsupported iOS H.264 without publishing a terminal error", async () => {
594 const { client, videoBodies, Decoder, events, imageReady } = recoveryFixture("ios", false);
595 Decoder.isConfigSupported.mockResolvedValue({ supported: false });
596 client.start();
597 await vi.advanceTimersByTimeAsync(0);
598 videoBodies[0]!.enqueue(new Uint8Array(envelope(1, [1, 0x64, 0, 0x1f])));
599 await vi.advanceTimersByTimeAsync(0);
600 expect(events.onMjpegFallback).toHaveBeenCalledOnce();
601 expect(events.onStatus.mock.calls.some(([status]) => status === "error")).toBe(false);
602 imageReady();
603 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
604 client.stop();
605 });
606​
607 it("publishes a terminal unsupported-profile error for Android and closes its socket", async () => {
608 const { client, sockets, sps, Decoder, events } = recoveryFixture("android");
609 Decoder.isConfigSupported.mockResolvedValue({ supported: false });
610 client.start();
611 sockets[0]!.onmessage?.({ data: sps });
612 await vi.advanceTimersByTimeAsync(0);
613 expect(events.onStatus).toHaveBeenLastCalledWith(
614 "error",
615 expect.stringContaining("cannot decode"),
616 );
617 expect(sockets[0]!.close).toHaveBeenCalledOnce();
618 expect(events.onMjpegFallback).not.toHaveBeenCalled();
619 expect(vi.getTimerCount()).toBe(0);
620 });
621​
622 it("waits for decoded Android output and bounds a rotation that never produces another frame", async () => {
623 const { client, sockets, sps, events, decodedFrame, drawImage } = recoveryFixture("android");
624 client.start();
625 sockets[0]!.onmessage?.({ data: sps });
626 await vi.advanceTimersByTimeAsync(0);
627 expect(events.onStatus.mock.calls.some(([status]) => status === "streaming")).toBe(false);
628 expect(decodedFrame()).toHaveBeenCalledOnce();
629 expect(drawImage).toHaveBeenCalledOnce();
630 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
631 sockets[0]!.onmessage?.({ data: JSON.stringify({ type: "video-session" }) });
632 await vi.advanceTimersByTimeAsync(15_000);
633 expect(events.onStatus).toHaveBeenLastCalledWith("error", expect.stringContaining("No video"));
634 expect(vi.getTimerCount()).toBe(0);
635 });
636​
637 it("discards decoder support results and output from a previous Android socket", async () => {
638 const { client, sockets, sps, events, Decoder, decoders, decodedFrame, drawImage } =
639 recoveryFixture("android");
640 let resolveSupport!: (support: { supported: boolean }) => void;
641 Decoder.isConfigSupported.mockImplementationOnce(
642 () =>
643 new Promise((resolve) => {
644 resolveSupport = resolve;
645 }),
646 );
647 client.start();
648 sockets[0]!.onmessage?.({ data: sps });
649 client.stop();
650 client.start();
651 resolveSupport({ supported: true });
652 await vi.advanceTimersByTimeAsync(0);
653 expect(decoders).toHaveLength(0);
654 sockets[1]!.onmessage?.({ data: sps });
655 await vi.advanceTimersByTimeAsync(0);
656 client.stop();
657 client.start();
658 events.onStatus.mockClear();
659 expect(decodedFrame()).toHaveBeenCalledOnce();
660 expect(drawImage).not.toHaveBeenCalled();
661 expect(events.onStatus).not.toHaveBeenCalled();
662 client.stop();
663 });
664​
665 it("ignores an old AVCC response rejected after a new attempt is connected", async () => {
666 const { client, fetch, events } = recoveryFixture("ios", false);
667 let resolveResponse!: (response: Response) => void;
668 fetch.mockImplementationOnce(() => Promise.resolve(new Response("prime")));
669 fetch.mockImplementationOnce(
670 () =>
671 new Promise((resolve) => {
672 resolveResponse = resolve;
673 }),
674 );
675 client.start();
676 await vi.advanceTimersByTimeAsync(0);
677 client.stop();
678 client.start();
679 await vi.advanceTimersByTimeAsync(0);
680 events.onStatus.mockClear();
681 resolveResponse(new Response(null, { status: 401 }));
682 await vi.advanceTimersByTimeAsync(0);
683 expect(events.onUnauthorized).not.toHaveBeenCalled();
684 expect(events.onStatus).not.toHaveBeenCalled();
685 client.stop();
686 expect(vi.getTimerCount()).toBe(0);
687 });
688​
689 it("closes a delayed JPEG seed from a stopped AVCC attempt without painting it", async () => {
690 const { client, videoBodies, drawImage, events } = recoveryFixture("ios", false);
691 let resolveBitmap!: (bitmap: ImageBitmap) => void;
692 vi.stubGlobal(
693 "createImageBitmap",
694 () =>
695 new Promise((resolve) => {
696 resolveBitmap = resolve;
697 }),
698 );
699 client.start();
700 await vi.advanceTimersByTimeAsync(0);
701 videoBodies[0]!.enqueue(new Uint8Array(envelope(4, [1])));
702 await vi.advanceTimersByTimeAsync(0);
703 client.stop();
704 client.start();
705 events.onStatus.mockClear();
706 const close = vi.fn();
707 resolveBitmap({ width: 400, height: 800, close } as unknown as ImageBitmap);
708 await vi.advanceTimersByTimeAsync(0);
709 expect(close).toHaveBeenCalledOnce();
710 expect(drawImage).not.toHaveBeenCalled();
711 expect(events.onStatus).not.toHaveBeenCalled();
712 client.stop();
713 });
714});
715​
716it("reports a stalled AVCC body after its initial image instead of leaving a frozen streaming state", async () => {
717 const { client, videoBodies, events, signals } = recoveryFixture("ios", false);
718 const close = vi.fn();
719 vi.stubGlobal("createImageBitmap", () => Promise.resolve({ width: 400, height: 800, close }));
720 try {
721 client.start();
722 await vi.advanceTimersByTimeAsync(0);
723 videoBodies[0]!.enqueue(new Uint8Array(envelope(4, [1])));
724 await vi.advanceTimersByTimeAsync(0);
725 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
726 await vi.advanceTimersByTimeAsync(15_000);
727 expect(events.onStatus).toHaveBeenLastCalledWith(
728 "error",
729 expect.stringContaining("stopped receiving video"),
730 );
731 expect(signals.every((signal) => signal.aborted)).toBe(true);
732 expect(vi.getTimerCount()).toBe(0);
733 } finally {
734 client.stop();
735 vi.useRealTimers();
736 vi.unstubAllGlobals();
737 }
738});