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