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(Response.json({})));
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("/api?")) return Promise.resolve(Response.json({}));
255 if (!url.includes("stream.avcc")) return Promise.resolve(new Response("prime"));
256 return Promise.resolve(
257 new Response(
258 new ReadableStream<Uint8Array>({
259 start(body) {
260 videoBodies.push(body);
261 signal.addEventListener("abort", () => body.error(new Error("aborted")), {
262 once: true,
263 });
264 },
265 }),
266 ),
267 );
268 });
269 vi.stubGlobal("fetch", fetch);
270 const events = {
271 onStatus: vi.fn(),
272 onScreen: vi.fn(),
273 onUnauthorized: vi.fn(),
274 onMjpegFallback: vi.fn(),
275 onInputConnected: vi.fn(),
276 };
277 const drawImage = vi.fn();
278 const image = new MjpegImage();
279 const client = createDeviceStreamClient(
280 {
281 platform,
282 preferMjpeg,
283 serveSimOnly,
284 deviceId: "test-device",
285 access: {
286 httpBase: "https://test/api/device-hub",
287 wsBase: "wss://test/api/device-hub",
288 credentials: true,
289 query: {},
290 },
291 },
292 { getContext: () => ({ drawImage }) } as unknown as HTMLCanvasElement,
293 events,
294 );
295 client.setMjpegImage(image as unknown as HTMLImageElement);
296 const imageReady = () => {
297 image.naturalWidth = 400;
298 image.naturalHeight = 800;
299 image.dispatchEvent(new Event("load"));
300 };
301 const decodedFrame = (index = decoders.length - 1) => {
302 const close = vi.fn();
303 decoders[index]!.callbacks.output({
304 displayWidth: 400,
305 displayHeight: 800,
306 close,
307 } as unknown as VideoFrame);
308 return close;
309 };
310 const sps = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0, 0x1f, 0, 0, 1, 0x65]).buffer;
311 return {
312 client,
313 events,
314 image,
315 imageReady,
316 sockets,
317 signals,
318 fetch,
319 videoBodies,
320 decoders,
321 Decoder,
322 drawImage,
323 decodedFrame,
324 sps,
325 };
326}
327
328describe("shared device stream readiness and recovery", () => {
329 afterEach(() => {
330 vi.useRealTimers();
331 vi.unstubAllGlobals();
332 });
333
334 it("repairs the hub's fallback configuration without disabling hardware decoding", async () => {
335 const { client, videoBodies, Decoder } = recoveryFixture("ios", false);
336 try {
337 client.start();
338 await vi.advanceTimersByTimeAsync(0);
339 videoBodies[0]!.enqueue(
340 Uint8Array.from(
341 envelope(
342 1,
343 [
344 1, 100, 0, 51, 255, 225, 0, 12, 39, 100, 0, 51, 172, 86, 128, 76, 1, 73, 230, 164, 1,
345 0, 4, 40, 238, 60, 176,
346 ],
347 ),
348 ),
349 );
350 await vi.advanceTimersByTimeAsync(0);
351 expect(Decoder.isConfigSupported).toHaveBeenCalledExactlyOnceWith({
352 codec: "avc1.640033",
353 description: Uint8Array.from([
354 1, 100, 0, 51, 255, 225, 0, 17, 39, 100, 0, 51, 172, 86, 128, 76, 1, 73, 230, 168, 6, 208,
355 68, 35, 80, 1, 0, 4, 40, 238, 60, 176,
356 ]),
357 optimizeForLatency: true,
358 });
359 } finally {
360 client.stop();
361 }
362 });
363
364 it("streams and drives a serve-sim-only Android device over serve-sim's AVCC and input socket", async () => {
365 const { client, events, fetch, sockets, videoBodies, decoders } = recoveryFixture(
366 "android",
367 false,
368 true,
369 );
370 client.start();
371 await vi.advanceTimersByTimeAsync(0);
372 // No MJPEG priming: Simlock serves only the AVCC stream and the input socket.
373 expect(fetch.mock.calls.map(([url]) => url)).toEqual([
374 "https://test/api/device-hub/vendor/serve-sim/helper/test-device/stream.avcc",
375 ]);
376 expect(sockets.map((socket) => socket.url)).toEqual([
377 "wss://test/api/device-hub/vendor/serve-sim/helper/ws?device=test-device",
378 ]);
379 // Simlock adds meta (5), keep-alive (6), and lease-end (7) frames to serve-sim's envelopes.
380 videoBodies[0]!.enqueue(
381 new Uint8Array([
382 ...envelope(5, [0x7b, 0x7d]),
383 ...envelope(1, [1, 0x64, 0, 0x1f]),
384 ...envelope(6, []),
385 ...envelope(2, [2]),
386 ...envelope(7, [0x7b, 0x7d]),
387 ]),
388 );
389 await vi.advanceTimersByTimeAsync(0);
390 expect(decoders[0]!.decode).toHaveBeenCalledOnce();
391
392 const input = sockets[0]!;
393 input.onmessage?.({ data: Uint8Array.of(0x83).buffer });
394 input.onmessage?.({
395 data: new Uint8Array([
396 0x82,
397 ...new TextEncoder().encode('{"width":1080,"height":2400,"orientation":"portrait"}'),
398 ]).buffer,
399 });
400 expect(events.onInputConnected).toHaveBeenLastCalledWith(true, undefined);
401 client.sendTouch("begin", 0.25, 0.5);
402 client.pressButton("back");
403 const sent = input.send.mock.calls.map(([payload]) => {
404 const bytes = payload as Uint8Array;
405 return [bytes[0], JSON.parse(new TextDecoder().decode(bytes.subarray(1)))];
406 });
407 expect(sent).toEqual([
408 [0x03, { type: "begin", x: 0.25, y: 0.5 }],
409 [0x04, { button: "back" }],
410 ]);
411 client.stop();
412 });
413
414 it("does not repaint a delayed JPEG seed over newer decoded video", async () => {
415 const { client, videoBodies, drawImage, decodedFrame } = recoveryFixture("ios", false);
416 let resolveBitmap!: (bitmap: ImageBitmap) => void;
417 vi.stubGlobal(
418 "createImageBitmap",
419 () =>
420 new Promise((resolve) => {
421 resolveBitmap = resolve;
422 }),
423 );
424 client.start();
425 await vi.advanceTimersByTimeAsync(0);
426 videoBodies[0]!.enqueue(
427 new Uint8Array([
428 ...envelope(4, [1]),
429 ...envelope(1, [1, 0x64, 0, 0x1f]),
430 ...envelope(2, [2]),
431 ]),
432 );
433 await vi.advanceTimersByTimeAsync(0);
434 decodedFrame();
435 const close = vi.fn();
436 resolveBitmap({ width: 400, height: 800, close } as unknown as ImageBitmap);
437 await vi.advanceTimersByTimeAsync(0);
438 expect(drawImage).toHaveBeenCalledOnce();
439 expect(close).toHaveBeenCalledOnce();
440 client.stop();
441 });
442
443 it("discards decoder support results and output from a previous Android socket", async () => {
444 const { client, sockets, sps, events, Decoder, decoders, decodedFrame, drawImage } =
445 recoveryFixture("android");
446 let resolveSupport!: (support: { supported: boolean }) => void;
447 Decoder.isConfigSupported.mockImplementationOnce(
448 () =>
449 new Promise((resolve) => {
450 resolveSupport = resolve;
451 }),
452 );
453 client.start();
454 await vi.advanceTimersByTimeAsync(0);
455 sockets[0]!.onmessage?.({ data: sps });
456 client.stop();
457 client.start();
458 await vi.advanceTimersByTimeAsync(0);
459 resolveSupport({ supported: true });
460 await vi.advanceTimersByTimeAsync(0);
461 expect(decoders).toHaveLength(0);
462 sockets[1]!.onmessage?.({ data: sps });
463 await vi.advanceTimersByTimeAsync(0);
464 client.stop();
465 client.start();
466 events.onStatus.mockClear();
467 expect(decodedFrame()).toHaveBeenCalledOnce();
468 expect(drawImage).not.toHaveBeenCalled();
469 expect(events.onStatus).not.toHaveBeenCalled();
470 client.stop();
471 });
472
473 it("ignores an old AVCC response rejected after a new attempt is connected", async () => {
474 const { client, fetch, events } = recoveryFixture("ios", false);
475 let resolveResponse!: (response: Response) => void;
476 fetch.mockImplementationOnce(() => Promise.resolve(new Response("prime")));
477 fetch.mockImplementationOnce(
478 () =>
479 new Promise((resolve) => {
480 resolveResponse = resolve;
481 }),
482 );
483 client.start();
484 await vi.advanceTimersByTimeAsync(0);
485 client.stop();
486 client.start();
487 await vi.advanceTimersByTimeAsync(0);
488 events.onStatus.mockClear();
489 resolveResponse(new Response(null, { status: 401 }));
490 await vi.advanceTimersByTimeAsync(0);
491 expect(events.onUnauthorized).not.toHaveBeenCalled();
492 expect(events.onStatus).not.toHaveBeenCalled();
493 client.stop();
494 expect(vi.getTimerCount()).toBe(0);
495 });
496});
497
498describe("Android WebRTC device streams", () => {
499 afterEach(() => {
500 vi.useRealTimers();
501 vi.unstubAllGlobals();
502 });
503
504 function setup() {
505 vi.useFakeTimers();
506 const sockets: Socket[] = [];
507 class Socket {
508 static OPEN = 1;
509 readyState = 1;
510 binaryType = "";
511 onopen: (() => void) | null = null;
512 onmessage: ((event: { data: string }) => void) | null = null;
513 onclose: ((event: { code: number; reason: string }) => void) | null = null;
514 send = vi.fn();
515 close = vi.fn();
516 readonly url: string;
517 constructor(url: string) {
518 this.url = url;
519 sockets.push(this);
520 }
521 }
522 const videos: Video[] = [];
523 class Video {
524 muted = false;
525 playsInline = false;
526 style = { cssText: "" };
527 srcObject: unknown = null;
528 videoWidth = 400;
529 videoHeight = 800;
530 setAttribute = vi.fn();
531 remove = vi.fn();
532 play = vi.fn(async () => {});
533 callback: (() => void) | null = null;
534 requestVideoFrameCallback(callback: () => void) {
535 this.callback = callback;
536 return 0;
537 }
538 constructor() {
539 videos.push(this);
540 }
541 }
542 const peers: Peer[] = [];
543 class Peer {
544 iceGatheringState = "complete";
545 connectionState = "connected";
546 localDescription = { type: "offer", sdp: "offer-sdp" };
547 ontrack: ((event: { streams: unknown[]; track: unknown }) => void) | null = null;
548 onconnectionstatechange: (() => void) | null = null;
549 close = vi.fn();
550 createOffer = vi.fn(async () => this.localDescription);
551 setLocalDescription = vi.fn(async () => {});
552 setRemoteDescription = vi.fn(async () => {});
553 addTransceiver = vi.fn(() => ({ setCodecPreferences: vi.fn() }));
554 addEventListener = vi.fn();
555 removeEventListener = vi.fn();
556 constructor() {
557 peers.push(this);
558 }
559 }
560 vi.stubGlobal("WebSocket", Socket);
561 vi.stubGlobal("RTCPeerConnection", Peer);
562 vi.stubGlobal("RTCRtpReceiver", { getCapabilities: () => ({ codecs: [] }) });
563 vi.stubGlobal("document", { createElement: () => new Video(), body: { append: vi.fn() } });
564 const fetch = vi.fn((url: string, _init?: RequestInit) =>
565 Promise.resolve(
566 url.includes("/api?")
567 ? Response.json({ serial: "emulator-5554", stream: { transport: "webrtc" } })
568 : Response.json({ type: "answer", sdp: "answer-sdp" }),
569 ),
570 );
571 vi.stubGlobal("fetch", fetch);
572 const events = {
573 onStatus: vi.fn(),
574 onScreen: vi.fn(),
575 onUnauthorized: vi.fn(),
576 onMjpegFallback: vi.fn(),
577 onInputConnected: vi.fn(),
578 };
579 const present = vi.fn(() => true);
580 const client = createDeviceStreamClient(
581 {
582 platform: "android",
583 deviceId: "session-1",
584 access: {
585 httpBase: "https://test/api/device-hub",
586 wsBase: "wss://test/api/device-hub",
587 credentials: true,
588 query: { hostId: "eas" },
589 },
590 },
591 { present },
592 events,
593 );
594 return { client, events, fetch, peers, videos, sockets, present };
595 }
596
597 it("streams over WebRTC when serve-emu advertises it, with input that reconnects on its own", async () => {
598 const { client, events, fetch, peers, videos, sockets, present } = setup();
599 client.start();
600 await vi.advanceTimersByTimeAsync(0);
601 expect(fetch.mock.calls.map(([url]) => url)).toEqual([
602 "https://test/api/device-hub/vendor/serve-emu/api?device=session-1&hostId=eas",
603 "https://test/api/device-hub/vendor/serve-emu/webrtc/offer?device=session-1&hostId=eas",
604 ]);
605 expect(peers[0]?.setRemoteDescription).toHaveBeenCalledWith({
606 type: "answer",
607 sdp: "answer-sdp",
608 });
609 peers[0]?.ontrack?.({ streams: [{}], track: {} });
610 videos[0]?.callback?.();
611 expect(present).toHaveBeenCalledWith(videos[0], 400, 800);
612 expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
613
614 expect(sockets.map((socket) => socket.url)).toEqual([
615 "wss://test/api/device-hub/vendor/serve-emu/ws?device=session-1&video=0&hostId=eas",
616 ]);
617 sockets[0]!.onopen?.();
618 client.pressButton("back");
619 expect(sockets[0]!.send).toHaveBeenCalledWith(JSON.stringify({ type: "back" }));
620 events.onStatus.mockClear();
621 sockets[0]!.onclose?.({ code: 1001, reason: "going away" });
622 await vi.advanceTimersByTimeAsync(1_000);
623 expect(sockets[1]?.url).toContain("video=0");
624 expect(peers).toHaveLength(1);
625 expect(peers[0]?.close).not.toHaveBeenCalled();
626 expect(events.onStatus).not.toHaveBeenCalled();
627 client.stop();
628 });
629});