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(
203 platform: "ios" | "android" = "ios",
204 preferMjpeg = true,
205 serveSimOnly = false,
206) {
207 vi.useFakeTimers();
208 const sockets: Socket[] = [];
209 class Socket {
210 static OPEN = 1;
211 readyState = 1;
212 binaryType = "";
213 onopen: (() => void) | null = null;
214 onmessage: ((event: { data: ArrayBuffer | string }) => void) | null = null;
215 onclose: ((event: { code: number; reason: string }) => void) | null = null;
216 send = vi.fn();
217 close = vi.fn();
218 readonly url: string;
219 constructor(url: string) {
220 this.url = url;
221 sockets.push(this);
222 }
223 }
224 vi.stubGlobal("WebSocket", Socket);
225 const decoders: Decoder[] = [];
226 class Decoder {
227 static isConfigSupported = vi.fn(async () => ({ supported: true }));
228 state = "unconfigured";
229 decodeQueueSize = 0;
230 configure() {
231 this.state = "configured";
232 }
233 reset = vi.fn(() => {
234 this.state = "unconfigured";
235 this.decodeQueueSize = 0;
236 });
237 close() {
238 this.state = "closed";
239 }
240 decode = vi.fn();
241 readonly callbacks: { output: (frame: VideoFrame) => void; error: () => void };
242 constructor(callbacks: { output: (frame: VideoFrame) => void; error: () => void }) {
243 this.callbacks = callbacks;
244 decoders.push(this);
245 }
246 }
247 vi.stubGlobal("VideoDecoder", Decoder);
248 vi.stubGlobal("EncodedVideoChunk", vi.fn());
249 const videoBodies: ReadableStreamDefaultController<Uint8Array>[] = [];
250 const signals: AbortSignal[] = [];
251 const fetch = vi.fn((url: string, init: RequestInit) => {
252 const signal = init.signal!;
253 signals.push(signal);
254 if (!url.includes("stream.avcc")) return Promise.resolve(new Response("prime"));
255 return Promise.resolve(
256 new Response(
257 new ReadableStream<Uint8Array>({
258 start(body) {
259 videoBodies.push(body);
260 signal.addEventListener("abort", () => body.error(new Error("aborted")), {
261 once: true,
262 });
263 },
264 }),
265 ),
266 );
267 });
268 vi.stubGlobal("fetch", fetch);
269 const events = {
270 onStatus: vi.fn(),
271 onScreen: vi.fn(),
272 onUnauthorized: vi.fn(),
273 onMjpegFallback: vi.fn(),
274 onInputConnected: vi.fn(),
275 };
276 const drawImage = vi.fn();
277 const image = new MjpegImage();
278 const client = createDeviceStreamClient(
279 {
280 platform,
281 preferMjpeg,
282 serveSimOnly,
283 deviceId: "test-device",
284 access: {
285 httpBase: "https://test/api/device-hub",
286 wsBase: "wss://test/api/device-hub",
287 credentials: true,
288 query: {},
289 },
290 },
291 { getContext: () => ({ drawImage }) } as unknown as HTMLCanvasElement,
292 events,
293 );
294 client.setMjpegImage(image as unknown as HTMLImageElement);
295 const imageReady = () => {
296 image.naturalWidth = 400;
297 image.naturalHeight = 800;
298 image.dispatchEvent(new Event("load"));
299 };
300 const decodedFrame = (index = decoders.length - 1) => {
301 const close = vi.fn();
302 decoders[index]!.callbacks.output({
303 displayWidth: 400,
304 displayHeight: 800,
305 close,
306 } as unknown as VideoFrame);
307 return close;
308 };
309 const sps = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0, 0x1f, 0, 0, 1, 0x65]).buffer;
310 return {
311 client,
312 events,
313 image,
314 imageReady,
315 sockets,
316 signals,
317 fetch,
318 videoBodies,
319 decoders,
320 Decoder,
321 drawImage,
322 decodedFrame,
323 sps,
324 };
325}
326
327describe("shared device stream readiness and recovery", () => {
328 afterEach(() => {
329 vi.useRealTimers();
330 vi.unstubAllGlobals();
331 });
332
333 it("repairs the hub's fallback configuration without disabling hardware decoding", async () => {
334 const { client, videoBodies, Decoder } = recoveryFixture("ios", false);
335 try {
336 client.start();
337 await vi.advanceTimersByTimeAsync(0);
338 videoBodies[0]!.enqueue(
339 Uint8Array.from(
340 envelope(
341 1,
342 [
343 1, 100, 0, 51, 255, 225, 0, 12, 39, 100, 0, 51, 172, 86, 128, 76, 1, 73, 230, 164, 1,
344 0, 4, 40, 238, 60, 176,
345 ],
346 ),
347 ),
348 );
349 await vi.advanceTimersByTimeAsync(0);
350 expect(Decoder.isConfigSupported).toHaveBeenCalledExactlyOnceWith({
351 codec: "avc1.640033",
352 description: Uint8Array.from([
353 1, 100, 0, 51, 255, 225, 0, 17, 39, 100, 0, 51, 172, 86, 128, 76, 1, 73, 230, 168, 6, 208,
354 68, 35, 80, 1, 0, 4, 40, 238, 60, 176,
355 ]),
356 optimizeForLatency: true,
357 });
358 } finally {
359 client.stop();
360 }
361 });
362
363 it("streams and drives a serve-sim-only Android device over serve-sim's AVCC and input socket", async () => {
364 const { client, events, fetch, sockets, videoBodies, decoders } = recoveryFixture(
365 "android",
366 false,
367 true,
368 );
369 client.start();
370 await vi.advanceTimersByTimeAsync(0);
371 // No MJPEG priming: Simlock serves only the AVCC stream and the input socket.
372 expect(fetch.mock.calls.map(([url]) => url)).toEqual([
373 "https://test/api/device-hub/vendor/serve-sim/helper/test-device/stream.avcc",
374 ]);
375 expect(sockets.map((socket) => socket.url)).toEqual([
376 "wss://test/api/device-hub/vendor/serve-sim/helper/ws?device=test-device",
377 ]);
378 // Simlock adds meta (5), keep-alive (6), and lease-end (7) frames to serve-sim's envelopes.
379 videoBodies[0]!.enqueue(
380 new Uint8Array([
381 ...envelope(5, [0x7b, 0x7d]),
382 ...envelope(1, [1, 0x64, 0, 0x1f]),
383 ...envelope(6, []),
384 ...envelope(2, [2]),
385 ...envelope(7, [0x7b, 0x7d]),
386 ]),
387 );
388 await vi.advanceTimersByTimeAsync(0);
389 expect(decoders[0]!.decode).toHaveBeenCalledOnce();
390
391 const input = sockets[0]!;
392 input.onmessage?.({ data: Uint8Array.of(0x83).buffer });
393 input.onmessage?.({
394 data: new Uint8Array([
395 0x82,
396 ...new TextEncoder().encode('{"width":1080,"height":2400,"orientation":"portrait"}'),
397 ]).buffer,
398 });
399 expect(events.onInputConnected).toHaveBeenLastCalledWith(true, undefined);
400 client.sendTouch("begin", 0.25, 0.5);
401 client.pressButton("back");
402 const sent = input.send.mock.calls.map(([payload]) => {
403 const bytes = payload as Uint8Array;
404 return [bytes[0], JSON.parse(new TextDecoder().decode(bytes.subarray(1)))];
405 });
406 expect(sent).toEqual([
407 [0x03, { type: "begin", x: 0.25, y: 0.5 }],
408 [0x04, { button: "back" }],
409 ]);
410 client.stop();
411 });
412
413 it("does not repaint a delayed JPEG seed over newer decoded video", async () => {
414 const { client, videoBodies, drawImage, decodedFrame } = recoveryFixture("ios", false);
415 let resolveBitmap!: (bitmap: ImageBitmap) => void;
416 vi.stubGlobal(
417 "createImageBitmap",
418 () =>
419 new Promise((resolve) => {
420 resolveBitmap = resolve;
421 }),
422 );
423 client.start();
424 await vi.advanceTimersByTimeAsync(0);
425 videoBodies[0]!.enqueue(
426 new Uint8Array([
427 ...envelope(4, [1]),
428 ...envelope(1, [1, 0x64, 0, 0x1f]),
429 ...envelope(2, [2]),
430 ]),
431 );
432 await vi.advanceTimersByTimeAsync(0);
433 decodedFrame();
434 const close = vi.fn();
435 resolveBitmap({ width: 400, height: 800, close } as unknown as ImageBitmap);
436 await vi.advanceTimersByTimeAsync(0);
437 expect(drawImage).toHaveBeenCalledOnce();
438 expect(close).toHaveBeenCalledOnce();
439 client.stop();
440 });
441
442 it("discards decoder support results and output from a previous Android socket", async () => {
443 const { client, sockets, sps, events, Decoder, decoders, decodedFrame, drawImage } =
444 recoveryFixture("android");
445 let resolveSupport!: (support: { supported: boolean }) => void;
446 Decoder.isConfigSupported.mockImplementationOnce(
447 () =>
448 new Promise((resolve) => {
449 resolveSupport = resolve;
450 }),
451 );
452 client.start();
453 sockets[0]!.onmessage?.({ data: sps });
454 client.stop();
455 client.start();
456 resolveSupport({ supported: true });
457 await vi.advanceTimersByTimeAsync(0);
458 expect(decoders).toHaveLength(0);
459 sockets[1]!.onmessage?.({ data: sps });
460 await vi.advanceTimersByTimeAsync(0);
461 client.stop();
462 client.start();
463 events.onStatus.mockClear();
464 expect(decodedFrame()).toHaveBeenCalledOnce();
465 expect(drawImage).not.toHaveBeenCalled();
466 expect(events.onStatus).not.toHaveBeenCalled();
467 client.stop();
468 });
469
470 it("ignores an old AVCC response rejected after a new attempt is connected", async () => {
471 const { client, fetch, events } = recoveryFixture("ios", false);
472 let resolveResponse!: (response: Response) => void;
473 fetch.mockImplementationOnce(() => Promise.resolve(new Response("prime")));
474 fetch.mockImplementationOnce(
475 () =>
476 new Promise((resolve) => {
477 resolveResponse = resolve;
478 }),
479 );
480 client.start();
481 await vi.advanceTimersByTimeAsync(0);
482 client.stop();
483 client.start();
484 await vi.advanceTimersByTimeAsync(0);
485 events.onStatus.mockClear();
486 resolveResponse(new Response(null, { status: 401 }));
487 await vi.advanceTimersByTimeAsync(0);
488 expect(events.onUnauthorized).not.toHaveBeenCalled();
489 expect(events.onStatus).not.toHaveBeenCalled();
490 client.stop();
491 expect(vi.getTimerCount()).toBe(0);
492 });
493});