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

stream.test.ts

436 lines13.6 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 "./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 }
201​
202function recoveryFixture(platform: "ios" | "android" = "ios", preferMjpeg = true) {
203 vi.useFakeTimers();
204 const sockets: Socket[] = [];
205 class Socket {
206 static OPEN = 1;
207 readyState = 1;
208 binaryType = "";
209 onopen: (() => void) | null = null;
210 onmessage: ((event: { data: ArrayBuffer | string }) => void) | null = null;
211 onclose: ((event: { code: number; reason: string }) => void) | null = null;
212 send = vi.fn();
213 close = vi.fn();
214 constructor() {
215 sockets.push(this);
216 }
217 }
218 vi.stubGlobal("WebSocket", Socket);
219 const decoders: Decoder[] = [];
220 class Decoder {
221 static isConfigSupported = vi.fn(async () => ({ supported: true }));
222 state = "unconfigured";
223 decodeQueueSize = 0;
224 configure() {
225 this.state = "configured";
226 }
227 reset = vi.fn(() => {
228 this.state = "unconfigured";
229 this.decodeQueueSize = 0;
230 });
231 close() {
232 this.state = "closed";
233 }
234 decode = vi.fn();
235 readonly callbacks: { output: (frame: VideoFrame) => void; error: () => void };
236 constructor(callbacks: { output: (frame: VideoFrame) => void; error: () => void }) {
237 this.callbacks = callbacks;
238 decoders.push(this);
239 }
240 }
241 vi.stubGlobal("VideoDecoder", Decoder);
242 vi.stubGlobal("EncodedVideoChunk", vi.fn());
243 const videoBodies: ReadableStreamDefaultController<Uint8Array>[] = [];
244 const signals: AbortSignal[] = [];
245 const fetch = vi.fn((url: string, init: RequestInit) => {
246 const signal = init.signal!;
247 signals.push(signal);
248 if (!url.includes("stream.avcc")) return Promise.resolve(new Response("prime"));
249 return Promise.resolve(
250 new Response(
251 new ReadableStream<Uint8Array>({
252 start(body) {
253 videoBodies.push(body);
254 signal.addEventListener("abort", () => body.error(new Error("aborted")), {
255 once: true,
256 });
257 },
258 }),
259 ),
260 );
261 });
262 vi.stubGlobal("fetch", fetch);
263 const events = {
264 onStatus: vi.fn(),
265 onScreen: vi.fn(),
266 onUnauthorized: vi.fn(),
267 onMjpegFallback: vi.fn(),
268 onInputConnected: vi.fn(),
269 };
270 const drawImage = vi.fn();
271 const image = new MjpegImage();
272 const client = createDeviceStreamClient(
273 {
274 platform,
275 preferMjpeg,
276 deviceId: "test-device",
277 access: {
278 httpBase: "https://test/api/device-hub",
279 wsBase: "wss://test/api/device-hub",
280 credentials: true,
281 query: {},
282 },
283 },
284 { getContext: () => ({ drawImage }) } as unknown as HTMLCanvasElement,
285 events,
286 );
287 client.setMjpegImage(image as unknown as HTMLImageElement);
288 const imageReady = () => {
289 image.naturalWidth = 400;
290 image.naturalHeight = 800;
291 image.dispatchEvent(new Event("load"));
292 };
293 const decodedFrame = (index = decoders.length - 1) => {
294 const close = vi.fn();
295 decoders[index]!.callbacks.output({
296 displayWidth: 400,
297 displayHeight: 800,
298 close,
299 } as unknown as VideoFrame);
300 return close;
301 };
302 const sps = new Uint8Array([0, 0, 0, 1, 0x67, 0x64, 0, 0x1f, 0, 0, 1, 0x65]).buffer;
303 return {
304 client,
305 events,
306 image,
307 imageReady,
308 sockets,
309 signals,
310 fetch,
311 videoBodies,
312 decoders,
313 Decoder,
314 drawImage,
315 decodedFrame,
316 sps,
317 };
319​
320describe("shared device stream readiness and recovery", () => {
321 afterEach(() => {
322 vi.useRealTimers();
323 vi.unstubAllGlobals();
324 });
325​
326 it("repairs the hub's fallback configuration without disabling hardware decoding", async () => {
327 const { client, videoBodies, Decoder } = recoveryFixture("ios", false);
328 try {
329 client.start();
330 await vi.advanceTimersByTimeAsync(0);
331 videoBodies[0]!.enqueue(
332 Uint8Array.from(
333 envelope(
334 1,
335 [
336 1, 100, 0, 51, 255, 225, 0, 12, 39, 100, 0, 51, 172, 86, 128, 76, 1, 73, 230, 164, 1,
337 0, 4, 40, 238, 60, 176,
338 ],
339 ),
340 ),
341 );
342 await vi.advanceTimersByTimeAsync(0);
343 expect(Decoder.isConfigSupported).toHaveBeenCalledExactlyOnceWith({
344 codec: "avc1.640033",
345 description: Uint8Array.from([
346 1, 100, 0, 51, 255, 225, 0, 17, 39, 100, 0, 51, 172, 86, 128, 76, 1, 73, 230, 168, 6, 208,
347 68, 35, 80, 1, 0, 4, 40, 238, 60, 176,
348 ]),
349 optimizeForLatency: true,
350 });
351 } finally {
352 client.stop();
353 }
354 });
355​
356 it("does not repaint a delayed JPEG seed over newer decoded video", async () => {
357 const { client, videoBodies, drawImage, decodedFrame } = recoveryFixture("ios", false);
358 let resolveBitmap!: (bitmap: ImageBitmap) => void;
359 vi.stubGlobal(
360 "createImageBitmap",
361 () =>
362 new Promise((resolve) => {
363 resolveBitmap = resolve;
364 }),
365 );
366 client.start();
367 await vi.advanceTimersByTimeAsync(0);
368 videoBodies[0]!.enqueue(
369 new Uint8Array([
370 ...envelope(4, [1]),
371 ...envelope(1, [1, 0x64, 0, 0x1f]),
372 ...envelope(2, [2]),
373 ]),
374 );
375 await vi.advanceTimersByTimeAsync(0);
376 decodedFrame();
377 const close = vi.fn();
378 resolveBitmap({ width: 400, height: 800, close } as unknown as ImageBitmap);
379 await vi.advanceTimersByTimeAsync(0);
380 expect(drawImage).toHaveBeenCalledOnce();
381 expect(close).toHaveBeenCalledOnce();
382 client.stop();
383 });
384​
385 it("discards decoder support results and output from a previous Android socket", async () => {
386 const { client, sockets, sps, events, Decoder, decoders, decodedFrame, drawImage } =
387 recoveryFixture("android");
388 let resolveSupport!: (support: { supported: boolean }) => void;
389 Decoder.isConfigSupported.mockImplementationOnce(
390 () =>
391 new Promise((resolve) => {
392 resolveSupport = resolve;
393 }),
394 );
395 client.start();
396 sockets[0]!.onmessage?.({ data: sps });
397 client.stop();
398 client.start();
399 resolveSupport({ supported: true });
400 await vi.advanceTimersByTimeAsync(0);
401 expect(decoders).toHaveLength(0);
402 sockets[1]!.onmessage?.({ data: sps });
403 await vi.advanceTimersByTimeAsync(0);
404 client.stop();
405 client.start();
406 events.onStatus.mockClear();
407 expect(decodedFrame()).toHaveBeenCalledOnce();
408 expect(drawImage).not.toHaveBeenCalled();
409 expect(events.onStatus).not.toHaveBeenCalled();
410 client.stop();
411 });
412​
413 it("ignores an old AVCC response rejected after a new attempt is connected", async () => {
414 const { client, fetch, events } = recoveryFixture("ios", false);
415 let resolveResponse!: (response: Response) => void;
416 fetch.mockImplementationOnce(() => Promise.resolve(new Response("prime")));
417 fetch.mockImplementationOnce(
418 () =>
419 new Promise((resolve) => {
420 resolveResponse = resolve;
421 }),
422 );
423 client.start();
424 await vi.advanceTimersByTimeAsync(0);
425 client.stop();
426 client.start();
427 await vi.advanceTimersByTimeAsync(0);
428 events.onStatus.mockClear();
429 resolveResponse(new Response(null, { status: 401 }));
430 await vi.advanceTimersByTimeAsync(0);
431 expect(events.onUnauthorized).not.toHaveBeenCalled();
432 expect(events.onStatus).not.toHaveBeenCalled();
433 client.stop();
434 expect(vi.getTimerCount()).toBe(0);
435 });
436});