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

duoStream.test.ts

285 lines10.7 KB

1import { afterEach, expect, it, vi } from "vite-plus/test";
2import { createDeviceStreamClient, type DeviceScreenSize } from "./stream.ts";
3afterEach(() => vi.unstubAllGlobals());
4​
5it("switches to fixed authenticated feeds while retaining one HID socket, routes the active panel and rejects superseded decoded output", async () => {
6 const feeds: {
7 url: string;
8 signal: AbortSignal;
9 controller: ReadableStreamDefaultController<Uint8Array>;
10 }[] = [];
11 const outputs: VideoFrameOutputCallback[] = [];
12 const errors: VideoDecoderInit["error"][] = [];
13 let supported = true;
14 let panelHttpStatus = 200;
15 let expected = 0;
16 let decoderReady = () => {};
17 const waitDecoders = (count: number) => {
18 expected = count;
19 return new Promise<void>((resolve) => {
20 decoderReady = resolve;
21 });
22 };
23 class Decoder {
24 static isConfigSupported = async () => ({ supported });
25 static instances: Decoder[] = [];
26 state = "unconfigured";
27 constructor(options: VideoDecoderInit) {
28 outputs.push(options.output);
29 errors.push(options.error);
30 Decoder.instances.push(this);
31 if (outputs.length === expected) decoderReady();
32 }
33 configure() {
34 this.state = "configured";
35 }
36 close() {
37 this.state = "closed";
38 }
39 }
40 let socketReady = () => {};
41 const socketConstructed = new Promise<void>((resolve) => {
42 socketReady = resolve;
43 });
44 class Socket {
45 static OPEN = 1;
46 static instances: Socket[] = [];
47 readyState = 1;
48 binaryType = "arraybuffer";
49 onopen?: () => void;
50 onmessage?: (event: { data: ArrayBuffer }) => void;
51 onclose?: (event: { code: number; reason: string }) => void;
52 send = vi.fn();
53 close = vi.fn();
54 constructor() {
55 Socket.instances.push(this);
56 socketReady();
57 }
58 }
59 vi.stubGlobal("VideoDecoder", Decoder);
60 vi.stubGlobal("EncodedVideoChunk", vi.fn());
61 vi.stubGlobal("WebSocket", Socket);
62 vi.stubGlobal(
63 "fetch",
64 vi.fn(async (url: string, options: { signal: AbortSignal }) => {
65 if (!url.includes("avcc")) return new Response("prime");
66 if (url.includes("/panel/") && panelHttpStatus !== 200)
67 return new Response("unsupported panel", { status: panelHttpStatus });
68 const stream = new ReadableStream<Uint8Array>({
69 start(controller) {
70 feeds.push({ url, signal: options.signal, controller });
71 options.signal.addEventListener("abort", () =>
72 controller.error(new DOMException("Aborted", "AbortError")),
73 );
74 },
75 });
76 return new Response(stream);
77 }),
78 );
79 const present = vi.fn((_source: CanvasImageSource, _width: number, _height: number) => true),
80 cover = vi.fn((_source: CanvasImageSource, _width: number, _height: number) => true),
81 inner = vi.fn((_source: CanvasImageSource, _width: number, _height: number) => true);
82 let panelFailed = () => {};
83 const panelFailure = new Promise<void>((resolve) => {
84 panelFailed = resolve;
85 });
86 const onStatus = vi.fn();
87 const onDuoControl = vi.fn();
88 const onDuoUnavailable = vi.fn((_detail?: string) => panelFailed());
89 const client = createDeviceStreamClient(
90 {
91 platform: "ios",
92 deviceId: "duo",
93 access: {
94 httpBase: "https://t3.test/api/device-hub",
95 wsBase: "wss://t3.test/api/device-hub",
96 credentials: true,
97 query: { hostId: "remote", wsTicket: "ticket" },
98 },
99 },
100 { present },
101 {
102 onStatus,
103 onDuoControl,
104 onDuoUnavailable,
105 onScreen: vi.fn(),
106 onInputConnected: vi.fn(),
107 onUnauthorized: vi.fn(),
108 onMjpegFallback: vi.fn(),
109 },
110 );
111 client.start();
112 await socketConstructed;
113 const ws = Socket.instances[0]!;
114 const config = (
115 id: number,
116 orientation: DeviceScreenSize["orientation"] = "portrait",
117 physical = false,
118 ) => {
119 const json = new TextEncoder().encode(
120 JSON.stringify({
121 width: id === 1 ? 1398 : 2007,
122 height: id === 1 ? 2034 : 2853,
123 orientation,
124 screenId: id,
125 supportsHingeAngle: true,
126 supportsPhysicalOrientation: physical,
127 hingePose: "open",
128 }),
129 );
130 const packet = new Uint8Array(json.length + 1);
131 packet[0] = 0x82;
132 packet.set(json, 1);
133 ws.onmessage?.({ data: packet.buffer });
134 };
135 config(3);
136 const requestedOrientation = () =>
137 JSON.parse(new TextDecoder().decode(ws.send.mock.lastCall?.[0].subarray(1))).orientation;
138 client.rotate();
139 expect(requestedOrientation()).toBe("landscape_left");
140 config(3); // An orientation-locked app keeps its framebuffer orientation after the sensor rotates.
141 expect(onDuoControl.mock.lastCall?.[0].error).toBeNull();
142 client.rotate();
143 expect(requestedOrientation()).toBe("portrait_upside_down");
144 config(3, "portrait_upside_down");
145 client.rotate();
146 expect(requestedOrientation()).toBe("landscape_right");
147 config(3); // An external native orientation change becomes authoritative again.
148 client.rotate();
149 expect(requestedOrientation()).toBe("landscape_left");
150 config(3, "landscape_left");
151 expect(onDuoControl.mock.lastCall?.[0].pending).toBe(false);
152 client.controlDuo({ control: "angle", value: 40 });
153 const angleRequest = JSON.parse(new TextDecoder().decode(ws.send.mock.lastCall?.[0].subarray(1)));
154 const before = ws.send.mock.calls.length;
155 client.controlDuo({ control: "orientation", value: "portrait" });
156 expect(ws.send.mock.calls.length).toBe(before);
157 config(3, "landscape_left"); // The angle's config precedes its receipt; it cannot acknowledge a queued rotation.
158 const reply = new TextEncoder().encode(
159 JSON.stringify({ requestId: angleRequest.requestId, ok: true }),
160 );
161 const receipt = new Uint8Array(reply.length + 1);
162 receipt[0] = 0x90;
163 receipt.set(reply, 1);
164 ws.onmessage?.({ data: receipt.buffer });
165 expect(requestedOrientation()).toBe("portrait");
166 expect(ws.send.mock.lastCall?.[0][0]).toBe(0x07);
167 client.controlDuo({ control: "angle", value: 55 });
168 const orientationSends = ws.send.mock.calls.length;
169 expect(onDuoControl.mock.lastCall?.[0].pending).toBe(true);
170 config(3);
171 expect(ws.send.mock.calls.length).toBe(orientationSends + 1);
172 const after = JSON.parse(new TextDecoder().decode(ws.send.mock.lastCall?.[0].subarray(1)));
173 expect(after.command).toEqual({ control: "angle", value: 55 });
174 const finalReply = new TextEncoder().encode(
175 JSON.stringify({ requestId: after.requestId, ok: true }),
176 );
177 const finalReceipt = new Uint8Array(finalReply.length + 1);
178 finalReceipt[0] = 0x90;
179 finalReceipt.set(finalReply, 1);
180 ws.onmessage?.({ data: finalReceipt.buffer });
181 expect(onDuoControl.mock.lastCall?.[0].pending).toBe(false);
182 const description = new Uint8Array([0, 0, 0, 5, 1, 1, 0x64, 0, 0x1f]);
183 let ready = waitDecoders(1);
184 feeds[0]!.controller.enqueue(description);
185 await ready;
186 client.setDuoPanels({ cover: { present: cover }, inner: { present: inner } });
187 expect(feeds[0]!.signal.aborted).toBe(true);
188 expect(Socket.instances).toHaveLength(1);
189 for (const [index, id] of [
190 [1, 1],
191 [2, 3],
192 ]) {
193 const url = new URL(feeds[index!]!.url);
194 expect(url.pathname.endsWith(`/panel/${id}/stream.avcc`)).toBe(true);
195 expect(url.searchParams.get("hostId")).toBe("remote");
196 expect(url.searchParams.get("wsTicket")).toBe("ticket");
197 }
198 ready = waitDecoders(3);
199 feeds[1]!.controller.enqueue(description);
200 feeds[2]!.controller.enqueue(description);
201 await ready;
202 const frame = {
203 displayWidth: 2007,
204 displayHeight: 2853,
205 close: vi.fn(),
206 } as unknown as VideoFrame;
207 outputs[0]!(frame);
208 expect(present).not.toHaveBeenCalled();
209 outputs[1]!(frame);
210 expect(cover).not.toHaveBeenCalled();
211 outputs[2]!(frame);
212 expect(inner).toHaveBeenCalledOnce();
213 expect(present).toHaveBeenCalledOnce();
214 config(1);
215 outputs[2]!(frame);
216 expect(inner).toHaveBeenCalledOnce();
217 outputs[1]!(frame);
218 expect(cover).toHaveBeenCalledOnce();
219 client.setDuoPanels(null);
220 expect(feeds[1]!.signal.aborted).toBe(true);
221 expect(feeds[2]!.signal.aborted).toBe(true);
222 expect(feeds[3]!.url).not.toContain("/panel/");
223 outputs[1]!(frame);
224 expect(cover).toHaveBeenCalledOnce();
225 ready = waitDecoders(4);
226 feeds[3]!.controller.enqueue(description);
227 await ready;
228 errors[0]!(new DOMException("Late decoder failure"));
229 expect(Decoder.instances[3]!.state).toBe("configured");
230 config(1, "portrait", true);
231 client.setDuoPanels({ cover: { present: cover }, inner: { present: inner } });
232 expect(feeds).toHaveLength(5); // One active feed replaces the two fixed feeds.
233 expect(feeds[4]!.url).not.toContain("/panel/");
234 expect(new URL(feeds[4]!.url).searchParams.get("hostId")).toBe("remote");
235 ready = waitDecoders(5);
236 feeds[4]!.controller.enqueue(description);
237 await ready;
238 const primary = { ...frame, displayWidth: 1398, displayHeight: 2034 } as VideoFrame;
239 const painted = present.mock.calls.length;
240 outputs[4]!(primary);
241 expect(present).toHaveBeenCalledTimes(painted + 1);
242 expect(present.mock.lastCall?.[0]).toBe(primary);
243 expect(cover).toHaveBeenCalledOnce(); // The main sink owns primary texture delivery.
244 config(3, "portrait", true);
245 expect(feeds[4]!.signal.aborted).toBe(true);
246 expect(feeds).toHaveLength(6);
247 ready = waitDecoders(6);
248 feeds[5]!.controller.enqueue(description);
249 await ready;
250 outputs[4]!(primary); // The old elected display cannot paint after handoff.
251 expect(present).toHaveBeenCalledTimes(painted + 1);
252 outputs[5]!(frame);
253 expect(present).toHaveBeenCalledTimes(painted + 2);
254 expect(present.mock.lastCall?.[0]).toBe(frame);
255 config(3, "portrait", true);
256 expect(feeds).toHaveLength(6); // Duplicate native readback does not reconnect.
257 supported = false;
258 client.setDuoPanels(null);
259 client.setDuoPanels({ cover: { present: cover }, inner: { present: inner } });
260 expect(feeds[7]!.url).not.toContain("/panel/");
261 feeds[7]!.controller.enqueue(description);
262 await panelFailure;
263 expect(onDuoUnavailable.mock.lastCall?.[0]).toContain("cannot decode");
264 config(3);
265 const fixedPanelFailure = new Promise<void>((resolve) => {
266 panelFailed = resolve;
267 });
268 client.setDuoPanels({ cover: { present: cover }, inner: { present: inner } });
269 feeds[8]!.controller.enqueue(description);
270 await fixedPanelFailure;
271 expect(onDuoUnavailable).toHaveBeenCalled();
272 expect(onStatus.mock.calls.some(([status]) => status === "error")).toBe(false);
273 panelHttpStatus = 404;
274 const missingPanel = new Promise<void>((resolve) => {
275 panelFailed = resolve;
276 });
277 client.setDuoPanels({ cover: { present: cover }, inner: { present: inner } });
278 await missingPanel;
279 expect(onDuoUnavailable.mock.lastCall?.[0]).toContain("does not provide fixed Duo");
280 expect(Socket.instances).toHaveLength(1);
281 client.stop();
282 expect(feeds[3]!.signal.aborted).toBe(true);
283 expect(ws.close).toHaveBeenCalledOnce();
284 expect(frame.close).toHaveBeenCalledTimes(9);
285});