Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

deviceStream.test.ts

345 lines11.4 KB

1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2​
3import {
4 createDeviceStreamClient,
5 AvccDemuxer,
6 avcCodecString,
7 parseSemuPacket,
8 scanAccessUnit,
9} from "@t3tools/client-runtime/device/stream";
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});