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

PreviewFrameWindow.ts

59 lines2.2 KB

1const MAX_FRAMES_IN_FLIGHT = 6;
2const STALE_AFTER_MS = 2_000;
3const FRAME_INTERVAL_MS = 33;
4const FRAMES_TO_SWITCH = 2;
5​
6// Whether a viewer's link is fast: it carries a frame in less time than frames arrive, so
7// several can be unacked without one waiting behind another. An empty message sent ahead of
8// a frame on an idle link returns in the link's latency; what the frame takes beyond that is
9// its transfer time. Any other link gets one frame at a time, as before this existed.
10export const makePreviewFrameWindow = () => {
11 let lastAckAt = Number.NEGATIVE_INFINITY;
12 let latency = Number.POSITIVE_INFINITY;
13 let fast = false;
14 let contrary = 0;
15 const inFlight: Array<{ readonly sentAt: number; readonly probe: boolean }> = [];
16​
17 const forgetStale = (now: number) => {
18 if (now - lastAckAt <= STALE_AFTER_MS) return;
19 latency = Number.POSITIVE_INFINITY;
20 fast = false;
21 contrary = 0;
22 };
23​
24 return {
25 /** An idle link can be measured: send an empty message and report it before the frame. */
26 idle: () => inFlight.length === 0,
27 fast: () => fast,
28 canSend: (now: number) => {
29 forgetStale(now);
30 if (inFlight.length === 0) return true;
31 return fast && inFlight.filter((sent) => !sent.probe).length < MAX_FRAMES_IN_FLIGHT;
32 },
33 sent: (now: number, probe: boolean) => {
34 inFlight.push({ sentAt: now, probe });
35 },
36 /** Which of the sent messages the viewer's ack answers. */
37 acked: (now: number) => {
38 const acked = inFlight.shift();
39 if (acked === undefined) return undefined;
40 forgetStale(now);
41 lastAckAt = now;
42 const roundTrip = now - acked.sentAt;
43 if (acked.probe) {
44 latency = roundTrip;
45 return "probe" as const;
46 }
47 if (!Number.isFinite(latency)) return "frame" as const;
48 // One frame does not decide: a late ack is not a slow link, and an empty message
49 // whose ack was held up until its image arrived makes a slow link look fast.
50 if (roundTrip - latency <= FRAME_INTERVAL_MS === fast) {
51 contrary = 0;
52 } else if (++contrary >= FRAMES_TO_SWITCH) {
53 fast = !fast;
54 contrary = 0;
55 }
56 return "frame" as const;
57 },
58 };
59};