Skip to main content

saturnus_host/protocol/
pacing.rs

1//! Pacing against the wall clock (`web/protocol.md`, "Pacing"): while the
2//! CPU computes or keys are queued, passes run emulated time equal to the
3//! elapsed wall time times the speed, dropping what a pass cannot fit into
4//! its budget; while it sleeps in SHUTDN with nothing queued, the loop
5//! asks to be woken at its next timer event, then runs all the time that
6//! passed at 1x (at most [`MAX_BEHIND_MS`]), owing what does not fit the
7//! wake's budget to the next passes.
8//!
9//! [`Loop`] holds that state; it runs a [`Core`] and reads a [`Clock`],
10//! and its only output besides the machine's progress is the time it
11//! wants to be called again ([`Loop::due`]).
12
13use super::Clock;
14use crate::{Emulator, Result};
15
16/// Most emulated time a wake catches up, in ms: 12 hours. Idle time is
17/// cheap (the core jumps over SHUTDN; only the ROM's timer ticks run: an
18/// idle 48SX hour took 2 ms, 12 hours 9 ms), but owed time the ROM spends
19/// awake (an alarm, a running program) is computed for real at the pass
20/// budget; the bound keeps a computer that slept for days from paying that
21/// off for minutes afterwards.
22pub const MAX_BEHIND_MS: f64 = 12.0 * 3600.0 * 1000.0;
23
24/// Longest delay a wake asks for, in ms (a browser timer's limit).
25const MAX_DELAY_MS: f64 = 2_147_483_647.0;
26
27/// How a host's pacing is tuned: the rules are the same everywhere, the
28/// periods and budgets suit the host's timers. Defined here once for every
29/// host ([`Pacing::WORKER`], [`Pacing::NATIVE`]).
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub struct Pacing {
32    /// Period of the passes while the CPU computes, in ms.
33    pub pass_ms: f64,
34    /// Wall time one pass may spend emulating at 1x, 2x and 4x.
35    pub pass_budget_ms: f64,
36    /// Wall time one pass may spend emulating at "Max".
37    pub max_budget_ms: f64,
38    /// Emulated ms one pass at "Max" may run at most.
39    pub max_emulated_ms: f64,
40    /// Longest stretch of wall time one pass makes up for.
41    pub max_wall_ms: f64,
42    /// Wall time one wake may spend catching up.
43    pub wake_budget_ms: f64,
44    /// The same while the page is hidden, where no frame waits for it.
45    pub hidden_wake_budget_ms: f64,
46    /// Shortest time between two `frame` events from passes (0: every
47    /// pass may send one).
48    pub frame_ms: f64,
49    /// Wall time one turn of a send may take before the host serves
50    /// other messages.
51    pub typing_tick_ms: f64,
52    /// Whether a hidden page stops the passes of a computing machine (as
53    /// it stops animation frames); a native window keeps computing.
54    pub pauses_when_hidden: bool,
55    /// How early a host's timer may fire and still count as due, in ms (a
56    /// browser truncates timer delays to whole milliseconds).
57    pub timer_slack_ms: f64,
58}
59
60impl Pacing {
61    /// The Web Worker's: passes on a ~60 Hz timer, as animation frames
62    /// were, each its own frame.
63    pub const WORKER: Pacing = Pacing {
64        pass_ms: 1000.0 / 60.0,
65        pass_budget_ms: 22.0,
66        max_budget_ms: 11.0,
67        max_emulated_ms: 1000.0,
68        max_wall_ms: 100.0,
69        wake_budget_ms: 22.0,
70        hidden_wake_budget_ms: 200.0,
71        frame_ms: 0.0,
72        typing_tick_ms: 40.0,
73        pauses_when_hidden: true,
74        timer_slack_ms: 1.0,
75    };
76
77    /// The native machine thread's (the desktop app, `saturnus run`):
78    /// passes every millisecond, so the serial bridge between them sees
79    /// the UART at its pace, and frames at most every 16 ms.
80    pub const NATIVE: Pacing = Pacing {
81        pass_ms: 1.0,
82        pass_budget_ms: 4.0,
83        max_budget_ms: 11.0,
84        max_emulated_ms: 1000.0,
85        max_wall_ms: 100.0,
86        wake_budget_ms: 22.0,
87        hidden_wake_budget_ms: 22.0,
88        frame_ms: 16.0,
89        typing_tick_ms: 16.0,
90        pauses_when_hidden: false,
91        timer_slack_ms: 0.0,
92    };
93}
94
95/// The speed setting (`setSpeed`).
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
97pub enum Speed {
98    /// Real time.
99    #[default]
100    One,
101    /// Twice real time.
102    Two,
103    /// Four times real time.
104    Four,
105    /// As fast as the host can while staying responsive.
106    Max,
107}
108
109impl Speed {
110    /// The protocol's name: `"1"`, `"2"`, `"4"` or `"max"`; anything else
111    /// is real time.
112    pub fn parse(s: &str) -> Speed {
113        match s {
114            "2" => Speed::Two,
115            "4" => Speed::Four,
116            "max" => Speed::Max,
117            _ => Speed::One,
118        }
119    }
120
121    /// The protocol's name.
122    pub fn name(self) -> &'static str {
123        match self {
124            Speed::One => "1",
125            Speed::Two => "2",
126            Speed::Four => "4",
127            Speed::Max => "max",
128        }
129    }
130
131    /// Emulated time per wall time while computing (1 at "Max", whose
132    /// passes are bounded by budget instead).
133    fn factor(self) -> f64 {
134        match self {
135            Speed::One | Speed::Max => 1.0,
136            Speed::Two => 2.0,
137            Speed::Four => 4.0,
138        }
139    }
140}
141
142impl serde::Serialize for Speed {
143    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
144        s.serialize_str(self.name())
145    }
146}
147
148/// What the loop does (the `loop` field of `status` and `stats`).
149#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
150#[serde(rename_all = "lowercase")]
151pub enum LoopState {
152    /// Passes run (the CPU computes or keys are queued).
153    Frame,
154    /// The CPU sleeps until a timer event.
155    Sleep,
156    /// Nothing runs (no machine, paused, halted, hidden while computing,
157    /// or a send drives the machine).
158    Stopped,
159}
160
161/// The machine as the loop sees it.
162pub(crate) trait Core {
163    /// One slice of at most `left_ms` emulated ms, feeding the key queue
164    /// if `keys`; the emulated ms run (more than zero).
165    fn run_slice(&mut self, left_ms: f64, keys: bool) -> Result<f64>;
166    /// Emulated ms the CPU sleeps before its next event; `None` while it
167    /// computes.
168    fn idle_ms(&self) -> Option<f64>;
169    /// Keys are down or queued.
170    fn keys_busy(&self) -> bool;
171    /// A key the user pressed is still down.
172    fn keys_held(&self) -> bool;
173    /// CPU cycles since power-on.
174    fn cycles(&self) -> u64;
175    /// The user memory's change counter.
176    fn memory_changes(&self) -> Result<u64>;
177}
178
179impl Core for Emulator {
180    fn run_slice(&mut self, left_ms: f64, keys: bool) -> Result<f64> {
181        Emulator::run_slice(self, left_ms, keys)
182    }
183    fn idle_ms(&self) -> Option<f64> {
184        Emulator::idle_ms(self)
185    }
186    fn keys_busy(&self) -> bool {
187        Emulator::keys_busy(self)
188    }
189    fn keys_held(&self) -> bool {
190        Emulator::keys_held(self)
191    }
192    fn cycles(&self) -> u64 {
193        self.machine().cycles()
194    }
195    fn memory_changes(&self) -> Result<u64> {
196        Emulator::memory_changes(self)
197    }
198}
199
200/// The CPU sleeps in SHUTDN with no keys queued.
201pub(crate) fn asleep(core: &impl Core) -> bool {
202    core.idle_ms().is_some() && !core.keys_busy()
203}
204
205/// The timer the loop waits for.
206#[derive(Clone, Copy, Debug, PartialEq)]
207enum Timer {
208    /// The next pass, at this time.
209    Pass(f64),
210    /// The wake from a sleep, at this time.
211    Wake(f64),
212}
213
214/// The run loop's state.
215#[derive(Clone, Debug)]
216pub(crate) struct Loop {
217    pub pacing: Pacing,
218    /// The machine runs (a ROM is booted, not paused, not halted).
219    pub running: bool,
220    pub speed: Speed,
221    /// The page is hidden (only if [`Pacing::pauses_when_hidden`]).
222    pub hidden: bool,
223    timer: Option<Timer>,
224    /// Wall clock up to which the passes accounted for emulated time.
225    last_pass: Option<f64>,
226    /// Wall clock up to which emulated time is accounted for while asleep.
227    slept_at: f64,
228    /// Emulated ms owed to wall time: what a wake could not catch up
229    /// within its budget. Passes and further wakes run it off first.
230    behind_ms: f64,
231    /// Wall ms spent emulating.
232    pub work_ms: f64,
233    /// Passes run.
234    pub ticks: u64,
235    /// Wakes from a sleep.
236    pub wakes: u64,
237}
238
239impl Loop {
240    pub fn new(pacing: Pacing) -> Loop {
241        Loop {
242            pacing,
243            running: false,
244            speed: Speed::One,
245            hidden: false,
246            timer: None,
247            last_pass: None,
248            slept_at: 0.0,
249            behind_ms: 0.0,
250            work_ms: 0.0,
251            ticks: 0,
252            wakes: 0,
253        }
254    }
255
256    /// When the loop wants [`Loop::fire`] called, on the host's clock.
257    pub fn due(&self) -> Option<f64> {
258        match self.timer {
259            Some(Timer::Pass(t) | Timer::Wake(t)) => Some(t),
260            None => None,
261        }
262    }
263
264    pub fn state(&self) -> LoopState {
265        match self.timer {
266            Some(Timer::Pass(_)) => LoopState::Frame,
267            Some(Timer::Wake(_)) => LoopState::Sleep,
268            None => LoopState::Stopped,
269        }
270    }
271
272    /// Passes are due (the loop does not stop between them).
273    pub fn passing(&self) -> bool {
274        matches!(self.timer, Some(Timer::Pass(_)))
275    }
276
277    /// The CPU sleeps on a wake timer.
278    pub fn sleeping(&self) -> bool {
279        matches!(self.timer, Some(Timer::Wake(_)))
280    }
281
282    /// Passes stop while the page is hidden.
283    fn held(&self) -> bool {
284        self.hidden && self.pacing.pauses_when_hidden
285    }
286
287    /// Emulated ms owed to the wall clock at `now`: unpaid, plus the
288    /// current sleep.
289    pub fn owed_ms(&self, now: f64) -> f64 {
290        self.behind_ms
291            + if self.sleeping() {
292                now - self.slept_at
293            } else {
294                0.0
295            }
296    }
297
298    /// Emulated ms a wake or pass could not catch up yet.
299    pub fn behind_ms(&self) -> f64 {
300        self.behind_ms
301    }
302
303    /// Stop: no timer, nothing owed.
304    pub fn stop(&mut self) {
305        self.timer = None;
306        self.last_pass = None;
307        self.behind_ms = 0.0;
308    }
309
310    /// Start after [`Loop::stop`]: a pass at once, or (hidden) the sleep
311    /// or nothing.
312    pub fn start(&mut self, core: &impl Core, now: f64) {
313        if !self.running {
314            return;
315        }
316        if self.held() {
317            self.schedule(core, now);
318        } else {
319            self.timer = Some(Timer::Pass(now));
320        }
321    }
322
323    /// The page was hidden or shown; `idle` means the loop may start (no
324    /// send drives the machine).
325    pub fn set_hidden(&mut self, hidden: bool, core: Option<&impl Core>, idle: bool, now: f64) {
326        if !self.pacing.pauses_when_hidden {
327            return;
328        }
329        self.hidden = hidden;
330        if let Some(core) = core
331            && !hidden
332            && self.running
333            && self.timer.is_none()
334            && idle
335        {
336            self.schedule(core, now);
337        }
338    }
339
340    /// How fast queued keys run against the wall clock now
341    /// ([`crate::clock::Pace`]): the speed, at most the pass's budget
342    /// over its period of wall time; at "Max" what a pass may run per
343    /// period.
344    pub fn clock_pace(&self) -> crate::clock::Pace {
345        let p = &self.pacing;
346        let (speed, budget) = if self.speed == Speed::Max {
347            (p.max_emulated_ms / p.pass_ms, p.max_budget_ms)
348        } else {
349            (self.speed.factor(), p.pass_budget_ms)
350        };
351        crate::clock::Pace {
352            speed,
353            share: (budget / p.pass_ms).min(1.0),
354            pass_ms: if self.speed == Speed::Max {
355                p.max_emulated_ms
356            } else {
357                p.pass_ms * speed
358            },
359        }
360    }
361
362    /// Run whichever timer is due at `now`; an error is a halted CPU.
363    pub fn fire(&mut self, core: &mut impl Core, clock: &dyn Clock, now: f64) -> Result<()> {
364        let slack = self.pacing.timer_slack_ms;
365        match self.timer {
366            Some(Timer::Pass(t)) if t <= now + slack => self.pass(core, clock),
367            Some(Timer::Wake(t)) if t <= now + slack => self.wake(core, clock),
368            _ => Ok(()),
369        }
370    }
371
372    /// Run `ms` emulated ms in slices, feeding the keys if `keys`, within
373    /// `budget_ms` of wall time, and only until the CPU sleeps with nothing
374    /// queued if `until_sleep`; returns the emulated ms left unrun.
375    fn run_slices(
376        &mut self,
377        core: &mut impl Core,
378        clock: &dyn Clock,
379        ms: f64,
380        budget_ms: f64,
381        keys: bool,
382        until_sleep: bool,
383    ) -> Result<f64> {
384        let start = clock.now_ms();
385        let mut left = ms;
386        let result = (|| {
387            // Checked before each slice: a pass that starts asleep runs
388            // nothing.
389            while left > 0.0 && !(until_sleep && asleep(core)) {
390                left -= core.run_slice(left, keys)?;
391                if clock.now_ms() - start > budget_ms {
392                    break;
393                }
394            }
395            Ok(())
396        })();
397        self.work_ms += clock.now_ms() - start;
398        result.map(|()| left.max(0.0))
399    }
400
401    /// One pass while the CPU computes: time owed from a sleep first (wall
402    /// time, at 1x), kept until paid; then the pass's own share at the
403    /// speed until the CPU sleeps. What does not fit the budget is
404    /// dropped; the wall time a sleep left over is the sleep's, at 1x.
405    fn pass(&mut self, core: &mut impl Core, clock: &dyn Clock) -> Result<()> {
406        self.timer = None;
407        let t = clock.now_ms();
408        let wall = self
409            .last_pass
410            .map_or(0.0, |l| (t - l).clamp(0.0, self.pacing.max_wall_ms));
411        self.last_pass = Some(t);
412        if !self.running {
413            return Ok(());
414        }
415        self.ticks += 1;
416        // A key held by the user runs at 1x whatever the speed, so a tap
417        // is as short as on the calculator.
418        let speed = if core.keys_held() {
419            Speed::One
420        } else {
421            self.speed
422        };
423        let max = speed == Speed::Max;
424        let budget = if max {
425            self.pacing.max_budget_ms
426        } else {
427            self.pacing.pass_budget_ms
428        };
429        self.behind_ms = self.run_slices(core, clock, self.behind_ms, budget, true, false)?;
430        if self.behind_ms == 0.0 {
431            let factor = speed.factor();
432            let own = if max {
433                self.pacing.max_emulated_ms
434            } else {
435                wall * factor
436            };
437            let rest = (budget - (clock.now_ms() - t)).max(0.0);
438            let left = self.run_slices(core, clock, own, rest, true, true)?;
439            if !max && asleep(core) {
440                self.last_pass = Some(t - left / factor);
441            }
442        }
443        self.schedule(core, clock.now_ms());
444        Ok(())
445    }
446
447    /// Keep passing while the CPU computes or keys are queued; once it
448    /// sleeps with nothing to do, set the wake timer for its next timer
449    /// event instead, so an idle machine costs nothing. Time still owed
450    /// brings the wake forward to now.
451    pub fn schedule(&mut self, core: &impl Core, now: f64) {
452        if !self.running {
453            return;
454        }
455        match core.idle_ms() {
456            Some(idle) if !core.keys_busy() => {
457                // The last pass or wake accounted for wall time up to
458                // `last_pass`. Scheduled again while already asleep (a
459                // poke), the sleep keeps its start, or its time is lost.
460                if !(self.sleeping() && self.last_pass.is_none()) {
461                    self.slept_at = self.last_pass.unwrap_or(now);
462                }
463                self.last_pass = None;
464                // Asleep, emulated time runs at 1x at any speed.
465                let delay = if self.behind_ms > 0.0 {
466                    0.0
467                } else {
468                    idle.min(MAX_DELAY_MS) + 1.0
469                };
470                self.timer = Some(Timer::Wake(now + delay));
471            }
472            _ => {
473                if !self.passing() && !self.held() {
474                    let due = self
475                        .last_pass
476                        .map_or(now, |l| (l + self.pacing.pass_ms).max(now));
477                    self.timer = Some(Timer::Pass(due));
478                }
479            }
480        }
481    }
482
483    /// Leave the sleep: run all the emulated time that passed meanwhile
484    /// (cheap while the CPU sleeps), however late the timer fired. What
485    /// does not fit the budget, as when the ROM wakes up and computes,
486    /// stays owed for the next pass or wake. Nothing if not asleep.
487    pub fn wake(&mut self, core: &mut impl Core, clock: &dyn Clock) -> Result<()> {
488        if !self.running || !self.sleeping() {
489            return Ok(());
490        }
491        self.timer = None;
492        self.wakes += 1;
493        let now = clock.now_ms();
494        self.behind_ms = (self.behind_ms + (now - self.slept_at)).min(MAX_BEHIND_MS);
495        let budget = if self.hidden {
496            self.pacing.hidden_wake_budget_ms
497        } else {
498            self.pacing.wake_budget_ms
499        };
500        // A key that woke the machine goes down after the time that passed.
501        self.behind_ms = self.run_slices(core, clock, self.behind_ms, budget, false, false)?;
502        self.last_pass = Some(now);
503        // The ROM may have woken for a timer event and redrawn (the
504        // clock), then gone back to sleep: sleep on without a pass.
505        self.schedule(core, clock.now_ms());
506        Ok(())
507    }
508}