Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3import {
4 createDeviceStreamClient,
5 AvccDemuxer,
6 avcCodecString,
7 parseSemuPacket,
8 scanAccessUnit,
9} from "./stream.ts";
10
11const envelope = (tag: number, payload: number[]) => {
12 const length = 1 + payload.length;
13 return [
14 (length >>> 24) & 0xff,
15 (length >>> 16) & 0xff,
16 (length >>> 8) & 0xff,
17 length & 0xff,
18 tag,
19 ...payload,
20 ];
21};
22
23describe("AvccDemuxer", () => {
24 it("reassembles envelopes split across reads", () => {
25 const demuxer = new AvccDemuxer();
26 const bytes = new Uint8Array([
27 ...envelope(1, [1, 0x64, 0x00, 0x1f]),
28 ...envelope(2, [9, 9, 9]),
29 ...envelope(0x7f, [0]),
30 ...envelope(3, [4]),
31 ]);
32 const first = demuxer.push(bytes.subarray(0, 7));
33 const rest = demuxer.push(bytes.subarray(7));
34 const chunks = [...first, ...rest];
35 expect(chunks.map((chunk) => chunk.type)).toEqual(["description", "keyframe", "delta"]);
36 expect(Array.from(chunks[0]!.payload)).toEqual([1, 0x64, 0x00, 0x1f]);
37 expect(Array.from(chunks[1]!.payload)).toEqual([9, 9, 9]);
38 });
39
40 it("derives the WebCodecs codec string from the avcC record", () => {
41 expect(avcCodecString(new Uint8Array([1, 0x64, 0x00, 0x1f]))).toBe("avc1.64001f");
42 expect(avcCodecString(new Uint8Array([1]))).toBe("avc1.42E01E");
43 });
44});
45
46describe("native device stream transport", () => {
47 afterEach(() => {
48 vi.useRealTimers();
49 vi.unstubAllGlobals();
50 });
51
52 function setup(platform: "ios" | "android") {
53 vi.useFakeTimers();
54 vi.stubGlobal("VideoDecoder", vi.fn());
55 vi.stubGlobal("EncodedVideoChunk", vi.fn());
56 let resolveOpened!: (socket: FakeSocket) => void;
57 const waitForSocket = () =>
58 new Promise<FakeSocket>((resolve) => {
59 resolveOpened = resolve;
60 });
61 const opened = waitForSocket();
62 class FakeSocket {
63 static OPEN = 1;
64 readyState = 1;
65 binaryType = "";
66 onopen: (() => void) | null = null;
67 onmessage: ((event: { data: ArrayBuffer }) => void) | null = null;
68 onclose: ((event: { code: number; reason: string }) => void) | null = null;
69 send = vi.fn();
70 close = vi.fn();
71 readonly url: string;
72 constructor(url: string) {
73 this.url = url;
74 resolveOpened(this);
75 }
76 }
77 vi.stubGlobal("WebSocket", FakeSocket);
78 const fetch = vi.fn(() => Promise.resolve(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("renews an expired Android ticket when the HTTP upgrade is rejected instead of retrying it forever", async () => {
106 const { client, opened, events } = setup("android");
107 client.start();
108 const socket = await opened;
109 socket.onclose?.({ code: 1006, reason: "" });
110 expect(events.onUnauthorized).toHaveBeenCalledTimes(1);
111 expect(vi.getTimerCount()).toBe(0);
112 client.stop();
113 });
114
115 it.each(["ios", "android"] as const)(
116 "keeps a restarted %s stream connected when the discarded socket closes late",
117 async (platform) => {
118 const { client, opened, waitForSocket, events } = setup(platform);
119 client.start();
120 const discarded = await opened;
121 client.stop();
122 const reopened = waitForSocket();
123 client.start();
124 const replacement = await reopened;
125 replacement.onopen?.();
126 if (platform === "ios") replacement.onmessage?.({ data: Uint8Array.of(0x83).buffer });
127 replacement.send.mockClear();
128 events.onInputConnected.mockClear();
129
130 discarded.onclose?.({ code: 1006, reason: "" });
131
132 expect(events.onUnauthorized).not.toHaveBeenCalled();
133 expect(events.onInputConnected).not.toHaveBeenCalled();
134 expect(replacement.close).not.toHaveBeenCalled();
135 client.pressButton("home");
136 expect(replacement.send).toHaveBeenCalledTimes(1);
137 client.stop();
138 expect(replacement.close).toHaveBeenCalledTimes(1);
139 expect(vi.getTimerCount()).toBe(0);
140 },
141 );
142
143 it.each(["ios", "android"] as const)(
144 "does not renew credentials or reconnect a stopped %s stream",
145 async (platform) => {
146 const { client, opened, events } = setup(platform);
147 client.start();
148 const socket = await opened;
149 events.onInputConnected.mockClear();
150 client.stop();
151 socket.onclose?.({ code: 1006, reason: "" });
152 expect(events.onUnauthorized).not.toHaveBeenCalled();
153 expect(events.onInputConnected).not.toHaveBeenCalled();
154 expect(vi.getTimerCount()).toBe(0);
155 },
156 );
157});
158
159describe("serve-emu frames", () => {
160 it("strips the SEMU header and reads the keyframe flag and timestamp", () => {
161 const buffer = new ArrayBuffer(16 + 3);
162 const view = new DataView(buffer);
163 view.setUint32(0, 0x53454d55);
164 view.setUint8(4, 1);
165 view.setUint8(5, 1);
166 view.setBigUint64(8, 123456n);
167 new Uint8Array(buffer).set([7, 8, 9], 16);
168 const packet = parseSemuPacket(buffer);
169 expect(packet.isKey).toBe(true);
170 expect(packet.timestamp).toBe(123456);
171 expect(Array.from(packet.data)).toEqual([7, 8, 9]);
172 });
173
174 it("treats a frame without the header as raw data", () => {
175 const packet = parseSemuPacket(new Uint8Array([0, 0, 1, 0x65]).buffer);
176 expect(packet.isKey).toBeNull();
177 expect(packet.data.length).toBe(4);
178 });
179
180 it("finds the SPS and IDR NAL units in an Annex-B access unit", () => {
181 const unit = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0x00, 0x1f, 0, 0, 1, 0x65, 0xaa]);
182 const scanned = scanAccessUnit(unit);
183 expect(scanned.isKey).toBe(true);
184 expect(scanned.sps && avcCodecString(scanned.sps)).toBe("avc1.64001f");
185 expect(scanAccessUnit(new Uint8Array([0, 0, 1, 0x41, 0x00])).isKey).toBe(false);
186 });
187});
188
189class MjpegImage extends EventTarget {
190 naturalWidth = 0;
191 naturalHeight = 0;
192 src = "";
193 removeAttribute(name: string) {
194 if (name === "src") {
195 this.src = "";
196 this.naturalWidth = 0;
197 this.naturalHeight = 0;
198 }
199 }
200}
201
202function recoveryFixture(platform: "ios" | "android" = "ios", preferMjpeg = true) {
203 vi.useFakeTimers();
204 const sockets: Socket[] = [];
205 class Socket {
206 static OPEN = 1;
207 readyState = 1;
208 binaryType = "";
209 onopen: (() => void) | null = null;
210 onmessage: ((event: { data: ArrayBuffer | string }) => void) | null = null;
211 onclose: ((event: { code: number; reason: string }) => void) | null = null;
212 send = vi.fn();
213 close = vi.fn();
214 constructor() {
215 sockets.push(this);
216 }
217 }
218 vi.stubGlobal("WebSocket", Socket);
219 const decoders: Decoder[] = [];
220 class Decoder {
221 static isConfigSupported = vi.fn(async () => ({ supported: true }));
222 state = "unconfigured";
223 decodeQueueSize = 0;
224 configure() {
225 this.state = "configured";
226 }
227 reset = vi.fn(() => {
228 this.state = "unconfigured";
229 this.decodeQueueSize = 0;
230 });
231 close() {
232 this.state = "closed";
233 }
234 decode = vi.fn();
235 readonly callbacks: { output: (frame: VideoFrame) => void; error: () => void };
236 constructor(callbacks: { output: (frame: VideoFrame) => void; error: () => void }) {
237 this.callbacks = callbacks;
238 decoders.push(this);
239 }
240 }
241 vi.stubGlobal("VideoDecoder", Decoder);
242 vi.stubGlobal("EncodedVideoChunk", vi.fn());
243 const videoBodies: ReadableStreamDefaultController<Uint8Array>[] = [];
244 const signals: AbortSignal[] = [];
245 const fetch = vi.fn((url: string, init: RequestInit) => {
246 const signal = init.signal!;
247 signals.push(signal);
248 if (!url.includes("stream.avcc")) return Promise.resolve(new Response("prime"));
249 return Promise.resolve(
250 new Response(
251 new ReadableStream<Uint8Array>({
252 start(body) {
253 videoBodies.push(body);
254 signal.addEventListener("abort", () => body.error(new Error("aborted")), {
255 once: true,
256 });
257 },
258 }),
259 ),
260 );
261 });
262 vi.stubGlobal("fetch", fetch);
263 const events = {
264 onStatus: vi.fn(),
265 onScreen: vi.fn(),
266 onUnauthorized: vi.fn(),
267 onMjpegFallback: vi.fn(),
268 onInputConnected: vi.fn(),
269 };
270 const drawImage = vi.fn();
271 const image = new MjpegImage();
272 const client = createDeviceStreamClient(
273 {
274 platform,
275 preferMjpeg,
276 deviceId: "test-device",
277 access: {
278 httpBase: "https://test/api/device-hub",
279 wsBase: "wss://test/api/device-hub",
280 credentials: true,
281 query: {},
282 },
283 },
284 { getContext: () => ({ drawImage }) } as unknown as HTMLCanvasElement,
285 events,
286 );
287 client.setMjpegImage(image as unknown as HTMLImageElement);
288 const imageReady = () => {
289 image.naturalWidth = 400;
290 image.naturalHeight = 800;
291 image.dispatchEvent(new Event("load"));
292 };
293 const decodedFrame = (index = decoders.length - 1) => {
294 const close = vi.fn();
295 decoders[index]!.callbacks.output({
296 displayWidth: 400,
297 displayHeight: 800,
298 close,
299 } as unknown as VideoFrame);
300 return close;
301 };
302 const sps = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0, 0x1f, 0, 0, 1, 0x65]).buffer;
303 return {
304 client,
305 events,
306 image,
307 imageReady,
308 sockets,
309 signals,
310 fetch,
311 videoBodies,
312 decoders,
313 Decoder,
314 drawImage,
315 decodedFrame,
316 sps,
317 };
318}
319
320describe("shared device stream readiness and recovery", () => {
321 afterEach(() => {
322 vi.useRealTimers();
323 vi.unstubAllGlobals();
324 });
325
326 it("does not repaint a delayed JPEG seed over newer decoded video", async () => {
327 const { client, videoBodies, drawImage, decodedFrame } = recoveryFixture("ios", false);
328 let resolveBitmap!: (bitmap: ImageBitmap) => void;
329 vi.stubGlobal(
330 "createImageBitmap",
331 () =>
332 new Promise((resolve) => {
333 resolveBitmap = resolve;
334 }),
335 );
336 client.start();
337 await vi.advanceTimersByTimeAsync(0);
338 videoBodies[0]!.enqueue(
339 new Uint8Array([
340 ...envelope(4, [1]),
341 ...envelope(1, [1, 0x64, 0, 0x1f]),
342 ...envelope(2, [2]),
343 ]),
344 );
345 await vi.advanceTimersByTimeAsync(0);
346 decodedFrame();
347 const close = vi.fn();
348 resolveBitmap({ width: 400, height: 800, close } as unknown as ImageBitmap);
349 await vi.advanceTimersByTimeAsync(0);
350 expect(drawImage).toHaveBeenCalledOnce();
351 expect(close).toHaveBeenCalledOnce();
352 client.stop();
353 });
354
355 it("discards decoder support results and output from a previous Android socket", async () => {
356 const { client, sockets, sps, events, Decoder, decoders, decodedFrame, drawImage } =
357 recoveryFixture("android");
358 let resolveSupport!: (support: { supported: boolean }) => void;
359 Decoder.isConfigSupported.mockImplementationOnce(
360 () =>
361 new Promise((resolve) => {
362 resolveSupport = resolve;
363 }),
364 );
365 client.start();
366 sockets[0]!.onmessage?.({ data: sps });
367 client.stop();
368 client.start();
369 resolveSupport({ supported: true });
370 await vi.advanceTimersByTimeAsync(0);
371 expect(decoders).toHaveLength(0);
372 sockets[1]!.onmessage?.({ data: sps });
373 await vi.advanceTimersByTimeAsync(0);
374 client.stop();
375 client.start();
376 events.onStatus.mockClear();
377 expect(decodedFrame()).toHaveBeenCalledOnce();
378 expect(drawImage).not.toHaveBeenCalled();
379 expect(events.onStatus).not.toHaveBeenCalled();
380 client.stop();
381 });
382
383 it("ignores an old AVCC response rejected after a new attempt is connected", async () => {
384 const { client, fetch, events } = recoveryFixture("ios", false);
385 let resolveResponse!: (response: Response) => void;
386 fetch.mockImplementationOnce(() => Promise.resolve(new Response("prime")));
387 fetch.mockImplementationOnce(
388 () =>
389 new Promise((resolve) => {
390 resolveResponse = resolve;
391 }),
392 );
393 client.start();
394 await vi.advanceTimersByTimeAsync(0);
395 client.stop();
396 client.start();
397 await vi.advanceTimersByTimeAsync(0);
398 events.onStatus.mockClear();
399 resolveResponse(new Response(null, { status: 401 }));
400 await vi.advanceTimersByTimeAsync(0);
401 expect(events.onUnauthorized).not.toHaveBeenCalled();
402 expect(events.onStatus).not.toHaveBeenCalled();
403 client.stop();
404 expect(vi.getTimerCount()).toBe(0);
405 });
406});