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 "./deviceStream";
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("serve-emu frames", () => {
47 it("strips the SEMU header and reads the keyframe flag and timestamp", () => {
48 const buffer = new ArrayBuffer(16 + 3);
49 const view = new DataView(buffer);
50 view.setUint32(0, 0x53454d55);
51 view.setUint8(4, 1);
52 view.setUint8(5, 1);
53 view.setBigUint64(8, 123456n);
54 new Uint8Array(buffer).set([7, 8, 9], 16);
55 const packet = parseSemuPacket(buffer);
56 expect(packet.isKey).toBe(true);
57 expect(packet.timestamp).toBe(123456);
58 expect(Array.from(packet.data)).toEqual([7, 8, 9]);
59 });
60
61 it("treats a frame without the header as raw data", () => {
62 const packet = parseSemuPacket(new Uint8Array([0, 0, 1, 0x65]).buffer);
63 expect(packet.isKey).toBeNull();
64 expect(packet.data.length).toBe(4);
65 });
66
67 it("finds the SPS and IDR NAL units in an Annex-B access unit", () => {
68 const unit = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0x00, 0x1f, 0, 0, 1, 0x65, 0xaa]);
69 const scanned = scanAccessUnit(unit);
70 expect(scanned.isKey).toBe(true);
71 expect(scanned.sps && avcCodecString(scanned.sps)).toBe("avc1.64001f");
72 expect(scanAccessUnit(new Uint8Array([0, 0, 1, 0x41, 0x00])).isKey).toBe(false);
73 });
74});
75
76describe("iOS input startup", () => {
77 afterEach(() => {
78 vi.useRealTimers();
79 vi.unstubAllGlobals();
80 });
81
82 const setup = () => {
83 vi.useFakeTimers();
84 const sockets: FakeSocket[] = [];
85 class FakeSocket {
86 static OPEN = 1;
87 readyState = 1;
88 binaryType = "";
89 onopen: (() => void) | null = null;
90 onmessage: ((event: { data: ArrayBuffer }) => void) | null = null;
91 onclose: ((event: { code: number; reason: string }) => void) | null = null;
92 send = vi.fn();
93 close = vi.fn();
94 constructor() {
95 sockets.push(this);
96 }
97 }
98 vi.stubGlobal("WebSocket", FakeSocket);
99 const signals: AbortSignal[] = [];
100 vi.stubGlobal(
101 "fetch",
102 vi.fn((_url, init: RequestInit) => {
103 const signal = init.signal!;
104 signals.push(signal);
105 return Promise.resolve(
106 new Response(
107 new ReadableStream({
108 start(controller) {
109 signal.addEventListener("abort", () => controller.error(new Error("aborted")));
110 },
111 }),
112 ),
113 );
114 }),
115 );
116 const client = createDeviceStreamClient(
117 {
118 platform: "ios",
119 deviceId: "test-device",
120 access: {
121 httpBase: "http://test/api/device-hub",
122 wsBase: "ws://test/api/device-hub",
123 credentials: true,
124 query: {},
125 },
126 },
127 { getContext: () => null } as unknown as HTMLCanvasElement,
128 {
129 onStatus: vi.fn(),
130 onScreen: vi.fn(),
131 onUnauthorized: vi.fn(),
132 onMjpegFallback: vi.fn(),
133 onInputConnected: vi.fn(),
134 },
135 );
136 return { client, sockets, signals };
137 };
138
139 it("connects input when the MJPEG prime never produces a frame", async () => {
140 const { client, sockets, signals } = setup();
141 client.start();
142 await vi.advanceTimersByTimeAsync(2_000);
143 expect(signals[0]?.aborted).toBe(true);
144 expect(sockets).toHaveLength(1);
145 client.stop();
146 });
147
148 it("aborts priming immediately when hidden without opening a socket later", async () => {
149 const { client, sockets, signals } = setup();
150 client.start();
151 await vi.advanceTimersByTimeAsync(0);
152 client.stop();
153 expect(signals[0]?.aborted).toBe(true);
154 await vi.advanceTimersByTimeAsync(2_000);
155 expect(sockets).toHaveLength(0);
156 });
157
158 it.each([
159 ["landscape_left", 0.7, 1 - 0.2],
160 ["landscape_right", 1 - 0.7, 0.2],
161 ])("maps %s touches back to the raw iOS framebuffer", async (orientation, x, y) => {
162 const { client, sockets } = setup();
163 client.start();
164 await vi.advanceTimersByTimeAsync(2_000);
165 const socket = sockets[0]!;
166 const json = new TextEncoder().encode(JSON.stringify({ width: 400, height: 800, orientation }));
167 const packet = new Uint8Array(1 + json.length);
168 packet[0] = 0x82;
169 packet.set(json, 1);
170 socket.onmessage?.({ data: packet.buffer });
171 client.sendTouch("begin", 0.2, 0.7);
172 const sent = socket.send.mock.calls[0]![0] as Uint8Array;
173 expect(JSON.parse(new TextDecoder().decode(sent.subarray(1)))).toEqual({
174 type: "begin",
175 x,
176 y,
177 });
178 client.stop();
179 });
180});