tetanes 0.15.0

A cross-platform NES Emulator written in Rust using wgpu
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
use crate::nes::{
    RunState,
    action::DebugStep,
    audio::{Audio, State as AudioState},
    config::{Config, FrameRate},
    emulation::{replay::Record, rewind::Rewind},
    event::{ConfigEvent, EmulationEvent, NesEvent, NesEventProxy, RendererEvent, UiEvent},
    renderer::{FrameRecycle, gui::MessageType},
};
use anyhow::{Context, anyhow};
use chrono::Local;
use crossbeam::channel;
use egui::ViewportId;
use replay::Replay;
use std::{
    collections::VecDeque,
    io::{self, Read},
    path::{Path, PathBuf},
};
use tetanes_core::{
    apu::Apu,
    bus::Bus,
    common::{NesRegion, ResetKind},
    control_deck::{self, Clocked, ControlDeck, LoadedRom},
    cpu::Cpu,
    ppu,
    time::{Duration, Instant},
    video::Frame,
};
use thingbuf::mpsc::{blocking::Sender as BufSender, errors::TrySendError};
use tracing::{debug, error, trace};
use winit::event::ElementState;

pub mod replay;
pub mod rewind;

#[derive(Debug, Copy, Clone, PartialEq)]
#[must_use]
pub struct FrameStats {
    pub timestamp: Instant,
    pub fps: f32,
    pub fps_min: f32,
    pub frame_time: f32,
    pub frame_time_max: f32,
    pub frame_count: usize,
}

impl Default for FrameStats {
    fn default() -> Self {
        Self {
            timestamp: Instant::now(),
            fps: 0.0,
            fps_min: 0.0,
            frame_time: 0.0,
            frame_time_max: 0.0,
            frame_count: 0,
        }
    }
}

impl FrameStats {
    pub fn new() -> Self {
        Self::default()
    }
}

#[derive(Debug)]
#[must_use]
pub struct FrameTimeDiag {
    frame_count: usize,
    history: VecDeque<f32>,
    sum: f32,
    avg: f32,
    last_update: Instant,
}

impl FrameTimeDiag {
    const MAX_HISTORY: usize = 120;
    const UPDATE_INTERVAL: Duration = Duration::from_millis(300);

    fn new() -> Self {
        Self {
            frame_count: 0,
            history: VecDeque::with_capacity(Self::MAX_HISTORY),
            sum: 0.0,
            avg: 1.0 / 60.0,
            last_update: Instant::now(),
        }
    }

    fn push(&mut self, frame_time: f32) {
        self.frame_count += 1;

        // Ignore the first few frames to allow the average to stabilize
        if frame_time.is_finite() && self.frame_count >= 10 {
            if self.history.len() >= Self::MAX_HISTORY
                && let Some(oldest) = self.history.pop_front()
            {
                self.sum -= oldest;
            }
            self.sum += frame_time;
            self.history.push_back(frame_time);
        }
    }

    fn avg(&mut self) -> f32 {
        if !self.history.is_empty() {
            let now = Instant::now();
            if now > self.last_update + Self::UPDATE_INTERVAL {
                self.last_update = now;
                self.avg = self.sum / self.history.len() as f32;
            }
        }
        self.avg
    }

    fn history(&self) -> impl Iterator<Item = &f32> {
        self.history.iter()
    }

    fn reset(&mut self) {
        self.frame_count = 0;
        self.history.clear();
        self.sum = 0.0;
        self.avg = 1.0 / 60.0;
        self.last_update = Instant::now();
    }
}

fn shutdown(tx: &NesEventProxy, err: impl std::fmt::Display) {
    error!("{err}");
    tx.event(UiEvent::Terminate);
}

#[derive(Debug)]
#[must_use]
enum Threads {
    Single(Box<Single>),
    Multi(Multi),
}

#[derive(Debug)]
#[must_use]
struct Single {
    state: State,
}

#[derive(Debug)]
#[must_use]
struct Multi {
    tx: channel::Sender<NesEvent>,
}

impl Multi {
    fn spawn(
        proxy_tx: NesEventProxy,
        frame_tx: BufSender<Frame, FrameRecycle>,
        cfg: &Config,
    ) -> anyhow::Result<Self> {
        let (tx, rx) = channel::bounded(128);
        // The handle is dropped rather than kept: nothing joins this thread, and it ends itself
        // when the channel disconnects - which is when `Multi`, and so `tx`, is dropped.
        std::thread::Builder::new()
            .name("emulation".into())
            .spawn({
                let cfg = cfg.clone();
                move || Self::main(proxy_tx, rx, frame_tx, &cfg)
            })?;
        Ok(Self { tx })
    }

    fn main(
        tx: NesEventProxy,
        rx: channel::Receiver<NesEvent>,
        frame_tx: BufSender<Frame, FrameRecycle>,
        cfg: &Config,
    ) {
        debug!("emulation thread started");
        let mut state = State::new(tx, frame_tx, cfg); // Has to be created on the thread, since
        loop {
            while let Ok(event) = rx.try_recv() {
                state.on_event(&event);
            }

            // Wait on the channel rather than parking the thread.
            //
            // `unpark` leaves a *sticky* token: unparking a thread that is not currently parked
            // makes its next `park_timeout` return immediately, however long it was asked for. The
            // UI thread unparked on every event and on every redraw, so a compositor delivering a
            // burst - focus-follows-mouse over the window will do it - left this loop unable to
            // sleep at all, spinning through wake-ups while the frame it owed went unclocked.
            // Blocking on the channel wakes exactly once per event and honours the timeout
            // otherwise.
            if let Some(timeout) = state.try_clock_frame() {
                match rx.recv_timeout(timeout) {
                    Ok(event) => state.on_event(&event),
                    Err(channel::RecvTimeoutError::Timeout) => (),
                    Err(channel::RecvTimeoutError::Disconnected) => {
                        debug!("emulation channel disconnected");
                        break;
                    }
                }
            }
        }
    }
}

#[derive(Debug)]
#[must_use]
pub struct Emulation {
    threads: Threads,
}

impl Emulation {
    /// Initializes the renderer in a platform-agnostic way.
    pub fn new(
        tx: NesEventProxy,
        frame_tx: BufSender<Frame, FrameRecycle>,
        cfg: &Config,
    ) -> anyhow::Result<Self> {
        let threaded = cfg.emulation.threaded
            && std::thread::available_parallelism().is_ok_and(|count| count.get() > 1);
        let backend = if threaded {
            Threads::Multi(Multi::spawn(tx, frame_tx, cfg)?)
        } else {
            Threads::Single(Box::new(Single {
                state: State::new(tx, frame_tx, cfg),
            }))
        };

        Ok(Self { threads: backend })
    }

    /// Handle event.
    pub fn on_event(&mut self, event: &NesEvent) {
        match &mut self.threads {
            Threads::Single(single) => single.state.on_event(event),
            // Sending is the wake-up: the thread is blocked on this channel, not parked.
            Threads::Multi(Multi { tx, .. }) => {
                if let Err(err) = tx.try_send(event.clone()) {
                    error!("failed to send emulation event: {event:?}. {err:?}");
                }
            }
        }
    }

    pub fn try_clock_frame(&mut self) {
        match &mut self.threads {
            Threads::Single(single) => {
                // The event loop is the clock here, so whatever it reports is not ours to wait on.
                let _ = single.state.try_clock_frame();
            }
            // Multi-threaded emulation paces itself on the wall clock and asks for its own
            // redraws, so a redraw on the UI thread is not a reason to disturb it.
            Threads::Multi(_) => (),
        }
    }

    pub fn terminate(&mut self) {
        match &mut self.threads {
            Threads::Single(_) => (),
            Threads::Multi(Multi { tx, .. }) => {
                if let Err(err) = tx.try_send(NesEvent::Ui(UiEvent::Terminate)) {
                    error!("failed to send termination event. {err:?}");
                }
            }
        }
    }
}

#[derive(Debug)]
#[must_use]
pub struct State {
    tx: NesEventProxy,
    control_deck: ControlDeck,
    audio: Audio,
    frame_tx: BufSender<Frame, FrameRecycle>,
    frame_latency: usize,
    target_frame_duration: Duration,
    /// When the next frame is due.
    ///
    /// An absolute deadline rather than an accumulated remainder: oversleeping one frame is then
    /// corrected on the next rather than accumulating, and nothing has to spin out the last
    /// fraction of a millisecond to stay in step.
    next_frame_time: Instant,
    last_frame_time: Instant,
    /// When the renderer was last asked to draw, so the retry for an unclaimed frame can be
    /// throttled to once a frame.
    last_redraw_request: Instant,
    /// Running estimate of how far the nominal output rate is from what the sound card consumes.
    ///
    /// See [`State::update_audio_rate`].
    audio_rate_bias: f32,
    frame_time_diag: FrameTimeDiag,
    run_state: RunState,
    threaded: bool,
    rewinding: bool,
    rewind: Rewind,
    record: Record,
    replay: Replay,
    save_slot: u8,
    auto_save: bool,
    auto_save_interval: Duration,
    last_auto_save: Instant,
    auto_load: bool,
    /// The last cart that loaded successfully, which is what tells a swap from a first load.
    ///
    /// Not `ControlDeck::loaded_rom`, which a failed load leaves empty: opening a ROM that will not
    /// load between two games would otherwise look like a first load, and the previous game's
    /// cheats would carry into the next one.
    last_rom: Option<String>,
    speed: f32,
    run_ahead: usize,
    show_frame_stats: bool,
}

impl Drop for State {
    fn drop(&mut self) {
        self.unload_rom();
    }
}

impl State {
    /// How many frames of a stall may be repaid before the debt is written off.
    const MAX_CATCHUP_FRAMES: u32 = 3;
    /// Largest fraction the audio output rate may be bent by, `d` in Arntzen (2012).
    ///
    /// The paper finds 0.002..=0.005 satisfactory and this is the top of that range: pacing on
    /// the wall clock is a less precise estimate of the true frame rate than a vsync-driven one,
    /// so it needs the headroom.
    const AUDIO_MAX_DEVIATION: f32 = 0.005;
    /// How fast the base-rate estimate tracks a persistent error, and how far it may go.
    ///
    /// Slow on purpose. The proportional term settles over a few hundred frames, so this has to
    /// be slower still or the two fight; more importantly, it must not mistake a *transient* for
    /// a rate error. At this gain a 60-frame dropout moves the estimate by well under a tenth of
    /// its range and it decays back, while a genuine mismatch is tracked out in ~20 seconds.
    const AUDIO_BIAS_GAIN: f32 = 3e-5;
    const AUDIO_MAX_BIAS: f32 = 0.005;

    fn new(tx: NesEventProxy, frame_tx: BufSender<Frame, FrameRecycle>, cfg: &Config) -> Self {
        let mut control_deck = ControlDeck::with_config(cfg.deck.clone());
        let audio = Audio::new(
            cfg.audio.enabled,
            Apu::DEFAULT_SAMPLE_RATE,
            cfg.audio.latency,
            cfg.audio.buffer_size,
        );
        if cfg.audio.enabled && audio.device().is_none() {
            tx.event(ConfigEvent::AudioEnabled(false));
            tx.event(UiEvent::Message((
                MessageType::Warn,
                "No audio device found.".into(),
            )));
        }
        if Apu::DEFAULT_SAMPLE_RATE != audio.sample_rate {
            control_deck.set_sample_rate(audio.sample_rate);
        }
        let rewind = Rewind::new(
            cfg.emulation.rewind,
            cfg.emulation.rewind_seconds,
            cfg.emulation.rewind_interval,
        );
        let target_frame_duration = FrameRate::from(cfg.deck.region).duration();
        let mut state = Self {
            tx,
            control_deck,
            audio,
            frame_tx,
            frame_latency: 1,
            target_frame_duration,
            next_frame_time: Instant::now(),
            last_frame_time: Instant::now(),
            last_redraw_request: Instant::now(),
            audio_rate_bias: 1.0,
            frame_time_diag: FrameTimeDiag::new(),
            run_state: RunState::AutoPaused,
            threaded: cfg.emulation.threaded
                && std::thread::available_parallelism().is_ok_and(|count| count.get() > 1),
            rewinding: false,
            rewind,
            record: Record::new(),
            replay: Replay::new(),
            save_slot: cfg.emulation.save_slot,
            auto_save: cfg.emulation.auto_save,
            auto_save_interval: cfg.emulation.auto_save_interval,
            last_auto_save: Instant::now(),
            auto_load: cfg.emulation.auto_load,
            last_rom: None,
            speed: cfg.emulation.speed,
            run_ahead: cfg.emulation.run_ahead,
            show_frame_stats: false,
        };
        state.update_region(cfg.deck.region);
        state.update_run_ahead();
        state
    }

    pub(crate) fn add_message<S: ToString>(&mut self, ty: MessageType, msg: S) {
        self.tx.event(UiEvent::Message((ty, msg.to_string())));
    }

    /// Pushes the configured run-ahead down to the deck, disabling it while rewinding, which
    /// replays recorded states and so has no input latency to hide.
    ///
    /// The speed rule is not here: `ControlDeck` applies run-ahead only at 1x on its own, since
    /// speculating past the current frame only means anything when a display frame is one frame.
    const fn update_run_ahead(&mut self) {
        self.control_deck
            .set_run_ahead(if self.rewinding { 0 } else { self.run_ahead });
    }

    /// Start or stop rewinding, keeping run-ahead in step with it.
    const fn set_rewinding(&mut self, rewinding: bool) {
        self.rewinding = rewinding;
        self.update_run_ahead();
    }

    fn write_deck<T>(
        &mut self,
        writer: impl FnOnce(&mut ControlDeck) -> control_deck::Result<T>,
    ) -> Option<T> {
        writer(&mut self.control_deck)
            .map_err(|err| self.on_error(err))
            .ok()
    }

    fn on_error(&mut self, err: impl Into<anyhow::Error>) {
        let err = err.into();
        error!("Emulation error: {err:?}");
        if self.control_deck.cpu_corrupted() {
            let bus = self.control_deck.bus();
            let opcode = bus.peek(bus.cpu.pc.wrapping_sub(1));
            self.tx.event(EmulationEvent::CpuCorrupted {
                instr: Cpu::INSTR_REF[usize::from(opcode)],
            });
        } else {
            self.add_message(MessageType::Error, err);
        }
    }

    /// Handle event.
    fn on_event(&mut self, event: &NesEvent) {
        match event {
            NesEvent::Ui(UiEvent::Terminate) => {
                self.unload_rom();
                debug!("emulation stopped");
            }
            NesEvent::Emulation(event) => self.on_emulation_event(event),
            NesEvent::Config(event) => self.on_config_event(event),
            _ => (),
        }
    }

    /// Handle emulation event.
    fn on_emulation_event(&mut self, event: &EmulationEvent) {
        match event {
            EmulationEvent::AddDebugger(debugger) => {
                self.control_deck.set_debugger(debugger.clone());
            }
            EmulationEvent::RemoveDebugger => {
                self.control_deck.clear_debugger();
            }
            EmulationEvent::AudioRecord(recording) => {
                if self.control_deck.is_running() {
                    self.audio_record(*recording);
                }
            }
            EmulationEvent::CpuCorrupted { .. } => (), // Ignore, as only this module emits this
            // event
            EmulationEvent::DebugStep(step) => {
                if self.control_deck.is_running() {
                    match step {
                        DebugStep::Into => {
                            self.write_deck(|deck| deck.clock_instr());
                            self.send_frame();
                        }
                        DebugStep::Out => {
                            // TODO: track stack frames list on jsr, irq, brk
                            // while stack frame == previous stack frame, clock_instr, send_frame
                            self.send_frame();
                        }
                        DebugStep::Over => {
                            // TODO: track stack frames list on jsr, irq, brk
                            // while stack frame != previous stack frame, clock_instr, send_frame
                            self.send_frame();
                        }
                        DebugStep::Scanline => {
                            if self.write_deck(|deck| deck.clock_scanline()).is_some() {
                                self.send_frame();
                            }
                        }
                        DebugStep::Frame => {
                            // One NES frame, which is what stepping means regardless of the speed
                            // a display frame would clock.
                            if self
                                .write_deck(|deck| deck.clock_frame().map(|_| ()))
                                .is_some()
                            {
                                self.send_frame();
                            }
                        }
                    }
                }
            }
            EmulationEvent::InstantRewind => {
                if self.control_deck.is_running() {
                    self.instant_rewind();
                }
            }
            EmulationEvent::Joypad((player, button, state)) => {
                if self.control_deck.is_running() {
                    let pressed = *state == ElementState::Pressed;
                    let joypad = self.control_deck.joypad_mut(*player);
                    joypad.set_button(*button, pressed);
                    self.record
                        .push(self.control_deck.frame_number(), event.clone());
                }
            }
            EmulationEvent::LoadReplay((name, replay)) => {
                if self.control_deck.is_running() {
                    self.load_replay(name, &mut io::Cursor::new(replay));
                }
            }
            EmulationEvent::LoadReplayPath(path) => {
                if self.control_deck.is_running() {
                    self.load_replay_path(path);
                }
            }
            EmulationEvent::LoadRom((name, rom)) => {
                self.load_rom(name, &mut io::Cursor::new(rom));
            }
            EmulationEvent::LoadRomPath(path) => self.load_rom_path(path),
            EmulationEvent::LoadState(slot) => self.load_state(*slot),
            EmulationEvent::RunState(mode) => self.set_run_state(*mode),
            EmulationEvent::ReplayRecord(recording) => {
                if self.control_deck.is_running() {
                    self.replay_record(*recording);
                }
            }
            EmulationEvent::Reset(kind) => {
                self.frame_time_diag.reset();
                if self.control_deck.is_running() || self.control_deck.cpu_corrupted() {
                    self.control_deck.reset(*kind);
                    match kind {
                        ResetKind::Soft => self.add_message(MessageType::Info, "Reset"),
                        ResetKind::Hard => self.add_message(MessageType::Info, "Power Cycled"),
                    }
                }
            }
            EmulationEvent::RequestFrame => self.send_frame(),
            EmulationEvent::Rewinding(rewind) => {
                if self.control_deck.is_running() {
                    if self.rewind.enabled {
                        self.set_rewinding(*rewind);
                        if self.rewinding {
                            self.add_message(MessageType::Info, "Rewinding...");
                        }
                    } else {
                        self.rewind_disabled();
                    }
                }
            }
            EmulationEvent::SaveState(slot) => self.save_state(*slot, false),
            EmulationEvent::ShowFrameStats(show) => {
                self.frame_time_diag.reset();
                self.show_frame_stats = *show;
            }
            EmulationEvent::Screenshot => {
                if self.control_deck.is_running() {
                    match self.save_screenshot() {
                        Ok(filename) => {
                            self.add_message(
                                MessageType::Info,
                                format!("Screenshot Saved: {}", filename.display()),
                            );
                        }
                        Err(err) => self.on_error(err),
                    }
                }
            }
            EmulationEvent::UnloadRom => self.unload_rom(),
            EmulationEvent::ZapperAim((x, y)) => {
                self.control_deck.aim_zapper(*x, *y);
                self.record
                    .push(self.control_deck.frame_number(), event.clone());
            }
            EmulationEvent::ZapperTrigger => {
                self.control_deck.trigger_zapper();
                self.record
                    .push(self.control_deck.frame_number(), event.clone());
            }
        }
    }

    /// Handle config event.
    fn on_config_event(&mut self, event: &ConfigEvent) {
        match event {
            ConfigEvent::ApuChannelEnabled((channel, enabled)) => {
                let prev_enabled = self.control_deck.apu_channel_enabled(*channel);
                self.control_deck
                    .set_apu_channel_enabled(*channel, *enabled);
                if prev_enabled != *enabled {
                    let enabled_text = if *enabled { "Enabled" } else { "Disabled" };
                    self.add_message(
                        MessageType::Info,
                        format!("{enabled_text} APU Channel {channel:?}"),
                    );
                }
            }
            ConfigEvent::AudioBuffer(buffer_size) => {
                if let Err(err) = self.audio.set_buffer_size(*buffer_size) {
                    self.on_error(err);
                }
            }
            ConfigEvent::AudioEnabled(enabled) => match self.audio.set_enabled(*enabled) {
                Ok(state) => match state {
                    AudioState::Started => self.add_message(MessageType::Info, "Audio Enabled"),
                    AudioState::Disabled | AudioState::Stopped => {
                        self.add_message(MessageType::Info, "Audio Disabled")
                    }
                    AudioState::NoOutputDevice => (),
                },
                Err(err) => self.on_error(err),
            },
            ConfigEvent::AudioLatency(latency) => {
                if let Err(err) = self.audio.set_latency(*latency) {
                    self.on_error(err);
                }
            }
            ConfigEvent::AutoLoad(enabled) => self.auto_load = *enabled,
            ConfigEvent::AutoSave(enabled) => self.auto_save = *enabled,
            ConfigEvent::AutoSaveInterval(interval) => self.auto_save_interval = *interval,
            ConfigEvent::ConcurrentDpad(enabled) => {
                self.control_deck.set_concurrent_dpad(*enabled);
            }
            ConfigEvent::EmulatePpuWarmup(enabled) => {
                self.control_deck.set_emulate_ppu_warmup(*enabled);
            }
            ConfigEvent::FourPlayer(four_player) => {
                self.control_deck.set_four_player(*four_player);
            }
            ConfigEvent::GenieCodeAdded(genie_code) => {
                self.control_deck
                    .bus_mut()
                    .add_genie_code(genie_code.clone());
            }
            ConfigEvent::GenieCodeRemoved(code) => {
                self.control_deck.remove_genie_code(code);
            }
            ConfigEvent::GenieCodeClear => {
                self.control_deck.clear_genie_codes();
            }
            ConfigEvent::RamState(ram_state) => {
                self.control_deck.set_ram_state(*ram_state);
            }
            ConfigEvent::Region(region) => {
                self.control_deck.set_region(*region);
                self.update_region(*region);
            }
            ConfigEvent::RewindEnabled(enabled) => self.rewind.set_enabled(*enabled),
            ConfigEvent::RewindInterval(interval) => self.rewind.set_interval(*interval),
            ConfigEvent::RewindSeconds(seconds) => self.rewind.set_seconds(*seconds),
            ConfigEvent::RunAhead(run_ahead) => {
                self.run_ahead = *run_ahead;
                self.update_run_ahead();
            }
            ConfigEvent::MapperRevisions(revs) => {
                self.control_deck.set_mapper_revisions(*revs);
            }
            ConfigEvent::SaveSlot(slot) => self.save_slot = *slot,
            ConfigEvent::Speed(speed) => {
                self.speed = *speed;
                self.control_deck.set_frame_speed(*speed);
                self.update_run_ahead();
            }
            ConfigEvent::VideoFilter(filter) => self.control_deck.set_filter(*filter),
            ConfigEvent::ZapperConnected(connected) => {
                self.control_deck.connect_zapper(*connected);
            }
            _ => (),
        }
    }

    fn update_frame_stats(&mut self) {
        if !self.show_frame_stats {
            return;
        }

        self.frame_time_diag
            .push(self.last_frame_time.elapsed().as_secs_f32());
        self.last_frame_time = Instant::now();
        let frame_time = self.frame_time_diag.avg();
        let frame_time_max = self
            .frame_time_diag
            .history()
            .fold(-f32::INFINITY, |a, b| a.max(*b));
        let mut fps = 1.0 / frame_time;
        let mut fps_min = 1.0 / frame_time_max;
        if !fps.is_finite() {
            fps = 0.0;
        }
        if !fps_min.is_finite() {
            fps_min = 0.0;
        }
        self.tx.event(RendererEvent::FrameStats(FrameStats {
            timestamp: Instant::now(),
            fps,
            fps_min,
            frame_time: frame_time * 1000.0,
            frame_time_max: frame_time_max * 1000.0,
            frame_count: self.frame_time_diag.frame_count,
        }));
    }

    fn send_frame(&mut self) {
        match self.frame_tx.try_send_ref() {
            Ok(mut frame) => self.control_deck.frame_buffer_into(frame.as_array_mut()),
            Err(TrySendError::Full(_)) => trace!("dropped frame"),
            Err(_) => shutdown(&self.tx, "failed to get frame"),
        }
    }

    fn set_run_state(&mut self, mode: RunState) {
        if !self.control_deck.cpu_corrupted() {
            self.run_state = mode;
            if self.run_state.paused() {
                if let Some(rom) = self.control_deck.loaded_rom()
                    && let Err(err) = self.record.stop(&rom.name)
                {
                    self.on_error(err);
                }
            } else {
                self.last_auto_save = Instant::now();
                // To avoid having a large dip in frame stats when unpausing
                self.last_frame_time = Instant::now();
            }
            self.audio.pause(self.run_state.paused());
        }
    }

    fn save_state(&mut self, slot: u8, auto: bool) {
        if let Some(rom) = self.control_deck.loaded_rom() {
            let data_dir = Config::save_path(&rom.name, slot);
            match self.control_deck.save_state_path(data_dir) {
                Ok(_) => {
                    if !auto {
                        self.add_message(MessageType::Info, format!("State {slot} Saved"));
                    }
                }
                Err(err) => self.on_error(err),
            }
        }
    }

    fn load_state(&mut self, slot: u8) {
        if let Some(rom) = self.control_deck.loaded_rom() {
            let save_path = Config::save_path(&rom.name, slot);
            match self.control_deck.load_state_path(save_path) {
                Ok(_) => self.add_message(MessageType::Info, format!("State {slot} Loaded")),
                Err(control_deck::Error::NoSaveStateFound) => {
                    self.add_message(MessageType::Warn, format!("State {slot} Not Found"));
                }
                Err(err) => {
                    self.on_error(err);
                }
            }
        }
    }

    fn unload_rom(&mut self) {
        if let Some(rom) = self.control_deck.loaded_rom() {
            if self.auto_save {
                let save_path = Config::save_path(&rom.name, self.save_slot);
                if let Err(err) = self.control_deck.save_state_path(save_path) {
                    self.on_error(err);
                }
            }
            self.replay_record(false);
            self.rewind.clear();
            let _ = self.audio.stop();
            if let Err(err) = self.control_deck.unload_rom() {
                self.on_error(err);
            }
            self.tx.event(RendererEvent::RomUnloaded);
            self.tx.event(RendererEvent::RequestRedraw {
                viewport_id: ViewportId::ROOT,
                when: Instant::now(),
            });
            self.frame_time_diag.reset();
        }
    }

    fn on_load_rom(&mut self, rom: LoadedRom) {
        // A cheat belongs to the cart it was entered for: the same address in another game holds
        // something else entirely, so the codes come out with the cartridge. Only on a *change* -
        // a first load has to keep what `--genie-code` and the config put there for the game about
        // to start, and quitting must not wipe the saved list, which both a plain unload hook and
        // a plain load hook would do.
        let swapped = self.last_rom.as_ref().is_some_and(|name| *name != rom.name);
        self.last_rom = Some(rom.name.clone());
        if swapped && self.control_deck.patches().count() > 0 {
            // Cleared here as well as through the event, so the new game does not run its opening
            // frames under the last one's codes while the event travels to the config and back.
            self.control_deck.clear_genie_codes();
            self.tx.event(ConfigEvent::GenieCodeClear);
            self.add_message(
                MessageType::Info,
                "Cleared Game Genie codes entered for the previous game",
            );
        }
        if self.auto_load {
            let save_path = Config::save_path(&rom.name, self.save_slot);
            if let Err(err) = self.control_deck.load_state_path(save_path)
                && !matches!(err, control_deck::Error::NoSaveStateFound)
            {
                error!("failed to load state: {err:?}");
            }
        }
        if let Err(err) = self.audio.start() {
            self.tx.event(ConfigEvent::AudioEnabled(false));
            self.on_error(err);
        }
        self.tx.event(RendererEvent::RomLoaded(rom));
        self.tx.event(RendererEvent::RequestRedraw {
            viewport_id: ViewportId::ROOT,
            when: Instant::now(),
        });
        self.frame_time_diag.reset();
        self.last_auto_save = Instant::now();
        // To avoid having a large dip in frame stats after loading
        self.last_frame_time = Instant::now();
    }

    fn load_rom_path(&mut self, path: impl AsRef<std::path::Path>) {
        let path = path.as_ref();
        self.unload_rom();
        match self.control_deck.load_rom_path(path) {
            Ok(rom) => self.on_load_rom(rom),
            Err(err) => self.on_error(err),
        }
    }

    fn load_rom(&mut self, name: &str, rom: &mut impl Read) {
        self.unload_rom();
        match self.control_deck.load_rom(name, rom) {
            Ok(rom) => self.on_load_rom(rom),
            Err(err) => self.on_error(err),
        }
    }

    fn on_load_replay(&mut self, start: Bus, name: impl AsRef<str>) {
        self.add_message(
            MessageType::Info,
            format!("Loaded Replay Recording {:?}", name.as_ref()),
        );
        if let Err(err) = self.control_deck.load_bus(start) {
            self.on_error(anyhow::Error::from(err));
            return;
        }
        self.tx.event(RendererEvent::ReplayLoaded);
        self.tx.event(RendererEvent::RequestRedraw {
            viewport_id: ViewportId::ROOT,
            when: Instant::now(),
        });
    }

    fn load_replay_path(&mut self, path: impl AsRef<Path>) {
        let path = path.as_ref();
        match self.replay.load_path(path) {
            Ok(start) => self.on_load_replay(start, path.to_string_lossy()),
            Err(err) => self.on_error(err),
        }
    }

    fn load_replay(&mut self, name: &str, replay: &mut impl Read) {
        match self.replay.load(replay) {
            Ok(start) => self.on_load_replay(start, name),
            Err(err) => self.on_error(err),
        }
    }

    fn update_region(&mut self, region: NesRegion) {
        self.target_frame_duration = FrameRate::from(region).duration();
        self.frame_latency = (self.audio.latency.as_secs_f32()
            / self.target_frame_duration.as_secs_f32())
        .ceil() as usize;
    }

    fn audio_record(&mut self, recording: bool) {
        if self.control_deck.is_running() {
            if !recording && self.audio.is_recording() {
                match self.audio.stop_recording() {
                    Ok(Some(filename)) => {
                        self.add_message(
                            MessageType::Info,
                            format!("Saved Replay Recording {filename:?}"),
                        );
                    }
                    Err(err) => self.on_error(err),
                    _ => (),
                }
            } else if recording && let Err(err) = self.audio.start_recording() {
                self.on_error(err);
            }
        }
    }

    fn replay_record(&mut self, recording: bool) {
        if self.control_deck.is_running() {
            if recording {
                self.record.start(self.control_deck.bus().clone());
            } else if let Some(rom) = self.control_deck.loaded_rom() {
                match self.record.stop(&rom.name) {
                    Ok(Some(filename)) => {
                        self.add_message(
                            MessageType::Info,
                            format!("Saved Replay Recording {filename:?}"),
                        );
                    }
                    Err(err) => self.on_error(err),
                    _ => (),
                }
            }
        }
    }

    fn save_screenshot(&mut self) -> anyhow::Result<PathBuf> {
        let picture_dir = Config::default_picture_dir();
        let filename = picture_dir
            .join(
                Local::now()
                    .format("screenshot_%Y-%m-%d_at_%H_%M_%S")
                    .to_string(),
            )
            .with_extension("png");
        let image = image::ImageBuffer::<image::Rgba<u8>, &[u8]>::from_raw(
            u32::from(ppu::size::WIDTH),
            u32::from(ppu::size::HEIGHT),
            self.control_deck.frame_buffer(),
        )
        .ok_or_else(|| anyhow!("failed to create image buffer"))?;

        if !picture_dir.exists() {
            std::fs::create_dir_all(&picture_dir)
                .with_context(|| format!("failed to create screenshot dir: {picture_dir:?}"))?;
        }

        // TODO: provide wasm download
        image
            .save(&filename)
            .map(|_| filename.clone())
            .with_context(|| format!("failed to save screenshot: {filename:?}"))
    }

    /// Dynamic rate control: hold the audio buffer at half full by nudging the output rate.
    ///
    /// The emulator clocks frames on the wall clock and the sound card consumes on its own, and
    /// the two never agree exactly - a 60.0988 Hz console, a 60 Hz-ish display and a 48 kHz-ish
    /// card all have their own tolerances. Left alone the audio buffer drifts to one end and
    /// either underruns or forces the emulator to wait, and waiting only trades the audio glitch
    /// for a video one.
    ///
    /// Instead, ask the APU for slightly more or fewer samples per frame:
    ///
    /// ```text
    /// ratio = 1 + d * (1 - 2 * level)
    /// ```
    ///
    /// where `level` is how full the buffer is, 0.0 to 1.0. Below half full the ratio rises and
    /// the buffer fills; above half it falls and the buffer drains, so the buffer converges on
    /// half full - the point with the most room either side for jitter. The buffer is sized at
    /// twice the configured latency, so half full *is* the latency the user asked for.
    ///
    /// From Arntzen, "Dynamic Rate Control for Retro Game Emulators" (2012), which is what
    /// RetroArch implements. The pitch shift this costs is bounded by `d` and in practice runs an
    /// order of magnitude under it - the paper measures 0.062% deviation for `d = 0.005` - which
    /// is comfortably below both the audible threshold and the tolerance of the card's own
    /// oscillator.
    fn update_audio_rate(&mut self) {
        // `None` while paused or stopped, when nothing is being queued and the level means
        // nothing. Leave the ratio where it is rather than winding it to an extreme.
        let Some(level) = self.audio.buffer_level() else {
            return;
        };

        // Track out whatever the nominal rate is persistently wrong by - the paper's section 2.5,
        // "updating ratio estimate". The proportional term alone can only hold a standing error by
        // sitting away from its setpoint, and a buffer parked away from half full has less cushion
        // than the user asked for on the side it has drifted toward.
        //
        // There is always a standing error to absorb: the frame rate paced on here is a rounded
        // integer, 60 rather than the NTSC console's 60.0988, which is 0.2% before the display's
        // real refresh and the card's real sample rate are counted.
        self.audio_rate_bias = (self.audio_rate_bias + Self::AUDIO_BIAS_GAIN * (0.5 - level))
            .clamp(1.0 - Self::AUDIO_MAX_BIAS, 1.0 + Self::AUDIO_MAX_BIAS);

        let ratio = self.audio_rate_bias * Self::audio_rate_ratio(level);
        trace!(
            "audio buffer {level:.3} full, bias {:.5}, rate ratio {ratio:.5}",
            self.audio_rate_bias
        );
        self.control_deck.set_audio_sample_ratio(ratio);
    }

    /// The output-rate multiplier that steers a buffer at `level` back toward half full.
    ///
    /// Split out from [`State::update_audio_rate`] so the control law can be tested without an
    /// audio device.
    fn audio_rate_ratio(level: f32) -> f32 {
        1.0 + Self::AUDIO_MAX_DEVIATION * (1.0 - 2.0 * level)
    }

    fn park_duration(&self) -> Option<Duration> {
        let park_epsilon = Duration::from_millis(1);
        // Park if we're paused, occluded, or not running
        let duration = if self.run_state.paused() || !self.control_deck.is_running() {
            Some(self.target_frame_duration - park_epsilon)
        } else {
            // A steady wall clock, whatever audio is doing. `update_audio_rate` holds the audio
            // queue at its target by bending pitch imperceptibly; gating frame timing on that
            // queue instead lets the sound card's buffer quantum decide when frames appear, and
            // leaves an empty queue meaning no rate limit at all.
            let now = Instant::now();
            (now < self.next_frame_time).then(|| self.next_frame_time - now)
        };
        duration.map(|duration| {
            // Parking thread is only required for Multi-threaded emulation to save CPU cycles.
            if self.threaded {
                duration
            } else {
                Duration::ZERO
            }
        })
    }

    /// Clocks the NES frames this display frame owes, snapshotting each one for rewind.
    ///
    /// The emulation speed decides how many that is - two at 2x, none every other display frame at
    /// 0.5x - and taking them one at a time is what keeps the rewind buffer evenly spaced in game
    /// time. Recording per display frame instead made a fast-forwarded stretch rewind at the speed
    /// it was recorded at.
    fn clock_display_frame(&mut self) -> control_deck::Result<()> {
        loop {
            let clocked = self.control_deck.clock_frame()?;
            if clocked != Clocked::Idle
                && let Err(err) = self.rewind.push(self.control_deck.bus())
            {
                self.rewind.set_enabled(false);
                self.on_error(err);
            }
            if clocked != Clocked::Continue {
                return Ok(());
            }
        }
    }

    /// Clock a display frame if one is due, or report how long until the next one is.
    ///
    /// `Some(duration)` means nothing was clocked and there is that long to wait; the caller
    /// decides how, since only it knows what else it might be woken for.
    fn try_clock_frame(&mut self) -> Option<Duration> {
        // If any frames are still pending, ask the renderer again - but at most once a frame.
        //
        // This is a retry, not the request: the request itself goes out when a frame is produced,
        // at the bottom of this function. Each retry is a cross-thread event-loop wakeup and this
        // loop can iterate far faster than a frame, so unthrottled the two threads wake each other
        // in a loop and neither gets on with its work.
        if !self.frame_tx.is_empty()
            && self.last_redraw_request.elapsed() >= self.target_frame_duration
        {
            self.request_redraw();
        }

        if let Some(wait) = self.park_duration() {
            return Some(wait);
        }

        if self.rewinding {
            match self.rewind.pop() {
                Some(bus) => {
                    // A mismatched state cannot happen while rewinding the running game, but
                    // stopping beats replaying a broken console.
                    if let Err(err) = self.control_deck.load_bus(bus) {
                        error!("failed to rewind: {err:?}");
                        self.set_rewinding(false);
                        return None;
                    }
                    // A snapshot carries no pixels, so render them: clocking the restored state
                    // produces the frame after the one it was taken on, which is a uniform
                    // one-frame offset across a rewind and costs a frame of emulation on a path
                    // that has a whole frame to spend. Audio is deliberately left undrained -
                    // rewinding is silent, and the next clock clears what this one produced.
                    //
                    // Below 1x a display frame does not always owe an NES frame, and a call that
                    // owes none clocks nothing - which would ship the blank buffer the snapshot
                    // restored. Keep asking until one is actually rendered.
                    loop {
                        match self.control_deck.clock_frame() {
                            Ok(Clocked::Idle) => continue,
                            Ok(_) => break,
                            Err(err) => {
                                error!("failed to render a rewound frame: {err:?}");
                                self.set_rewinding(false);
                                return None;
                            }
                        }
                    }
                    // One frame, not a display frame's worth: a rewind steps back one snapshot per
                    // display frame however fast the game was running when it was recorded.
                    self.send_frame();
                    self.update_frame_stats();
                }
                None => self.set_rewinding(false),
            }
        } else {
            if let Some(event) = self.replay.next(self.control_deck.frame_number()) {
                self.on_emulation_event(&event);
            }

            match self.clock_display_frame() {
                Ok(()) => {
                    self.audio.process(self.control_deck.audio_samples());
                    self.update_audio_rate();
                    match self.frame_tx.try_send_ref() {
                        Ok(mut frame) => self.control_deck.frame_buffer_into(frame.as_array_mut()),
                        Err(TrySendError::Full(_)) => debug!("dropped frame"),
                        Err(_) => shutdown(&self.tx, "failed to get frame"),
                    }
                    self.update_frame_stats();
                    if self.auto_save && self.last_auto_save.elapsed() > self.auto_save_interval {
                        self.last_auto_save = Instant::now();
                        self.save_state(self.save_slot, true);
                    }
                }
                Err(err) => self.on_error(err),
            }
        }

        self.advance_deadline();
        // Request to draw this frame
        self.request_redraw();
        None
    }

    /// Move the frame deadline on by one, resynchronising if it is already far in the past.
    ///
    /// Frames owed after a stall are worth repaying up to a point: they are audio the buffer is
    /// short of, and rate control can only refill it by half a percent a frame. Past that point
    /// repaying becomes a sprint through everything missed, so the debt is written off and the
    /// clock restarts from now.
    fn advance_deadline(&mut self) {
        self.next_frame_time += self.target_frame_duration;
        let now = Instant::now();
        if now.saturating_duration_since(self.next_frame_time)
            > Self::MAX_CATCHUP_FRAMES * self.target_frame_duration
        {
            self.next_frame_time = now + self.target_frame_duration;
        }
    }

    fn request_redraw(&mut self) {
        self.last_redraw_request = Instant::now();
        self.tx.event(RendererEvent::RequestRedraw {
            viewport_id: ViewportId::ROOT,
            when: Instant::now(),
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Simulate the closed loop: each frame the emulator pushes `produced * ratio` samples and the
    /// sound card takes `consumed`, both as a fraction of buffer capacity.
    ///
    /// Returns the buffer level over time, starting from `start`.
    fn simulate(start: f32, produced: f32, consumed: f32, frames: usize) -> Vec<f32> {
        let mut level = start;
        let mut bias = 1.0f32;
        let mut levels = Vec::with_capacity(frames);
        for _ in 0..frames {
            level += produced * bias * State::audio_rate_ratio(level) - consumed;
            level = level.clamp(0.0, 1.0);
            bias = (bias + State::AUDIO_BIAS_GAIN * (0.5 - level))
                .clamp(1.0 - State::AUDIO_MAX_BIAS, 1.0 + State::AUDIO_MAX_BIAS);
            levels.push(level);
        }
        levels
    }

    /// The control law's setpoint is a half-full buffer, which is where the configured latency
    /// sits and where there is the most room either side for jitter.
    #[test]
    fn the_audio_rate_ratio_steers_toward_a_half_full_buffer() {
        assert_eq!(
            State::audio_rate_ratio(0.5),
            1.0,
            "a half-full buffer needs no correction"
        );
        assert!(
            State::audio_rate_ratio(0.0) > 1.0,
            "an empty buffer must ask for more samples"
        );
        assert!(
            State::audio_rate_ratio(1.0) < 1.0,
            "a full buffer must ask for fewer"
        );

        // Monotonic, so there is exactly one setpoint and no oscillation between two.
        let mut previous = f32::INFINITY;
        for step in 0..=100 {
            let ratio = State::audio_rate_ratio(step as f32 / 100.0);
            assert!(ratio < previous, "must fall with level, at {step}");
            previous = ratio;
        }
    }

    /// The pitch shift is what this method costs, and the whole argument for it is that the cost
    /// is inaudible. Bound it explicitly rather than trusting the constant not to be edited.
    #[test]
    fn the_audio_rate_ratio_never_bends_pitch_audibly() {
        for step in 0..=100 {
            let deviation = (State::audio_rate_ratio(step as f32 / 100.0) - 1.0).abs();
            assert!(
                deviation <= State::AUDIO_MAX_DEVIATION,
                "level {step} bends pitch by {deviation}"
            );
        }
        // A semitone is ~5.9%, and the smallest interval anyone reliably hears is far above 0.5%.
        const { assert!(State::AUDIO_MAX_DEVIATION <= 0.005) };
    }

    /// A buffer starting far from the setpoint has to come back to it and stay, or the method
    /// buys nothing: the point is that the buffer neither underruns nor fills.
    #[test]
    fn a_drained_or_flooded_buffer_converges() {
        // One frame of a 60 Hz console against a 100 ms buffer is ~1/6th of capacity.
        let rate = 1.0 / 6.0;
        for start in [0.0, 0.1, 0.5, 0.9, 1.0] {
            let levels = simulate(start, rate, rate, 20_000);
            let settled = levels[levels.len() - 1];
            assert!(
                (settled - 0.5).abs() < 0.01,
                "started at {start}, settled at {settled}"
            );
            // And without ever hitting an end on the way, which is what an underrun sounds like.
            let lowest = levels.iter().copied().fold(f32::INFINITY, f32::min);
            assert!(lowest > 0.0, "started at {start}, drained to {lowest}");
        }
    }

    /// A nominal rate that is persistently wrong - a rounded frame rate, a sound card that is not
    /// quite at its stated rate - is what the base-rate estimate exists for. The buffer has to end
    /// up back at half full, not merely somewhere safe: sitting off-centre is sitting with less
    /// cushion than the user asked for, and that is what a hitch then falls through.
    #[test]
    fn a_persistent_rate_error_is_tracked_out_rather_than_absorbed_by_the_buffer() {
        let rate = 1.0 / 6.0;
        // Spanning the real one measured on this machine (~0.27%, from pacing a 60.0988 Hz
        // console at a rounded 60 fps) in both directions.
        for drift in [1.004, 1.002, 1.0, 0.998, 0.996] {
            for start in [0.0, 0.5, 1.0] {
                let levels = simulate(start, rate, rate * drift, 40_000);
                let settled = levels[levels.len() - 1];
                assert!(
                    (settled - 0.5).abs() < 0.02,
                    "drift {drift} from {start} settled at {settled}"
                );
                let highest = levels.iter().copied().fold(0.0f32, f32::max);
                assert!(
                    highest < 1.0,
                    "drift {drift} from {start} filled the buffer"
                );
            }
        }
    }

    /// The estimate must not mistake a dropout for a rate error. A hitch is transient and the
    /// buffer refills on its own; winding the base rate out to its limit every time one happened
    /// would leave the pitch bent long after the cause had gone.
    #[test]
    fn a_transient_dropout_barely_moves_the_base_rate_estimate() {
        // Sixty frames - a full second - of the buffer sitting far below its setpoint.
        let mut bias = 1.0f32;
        for _ in 0..60 {
            bias = (bias + State::AUDIO_BIAS_GAIN * (0.5 - 0.05))
                .clamp(1.0 - State::AUDIO_MAX_BIAS, 1.0 + State::AUDIO_MAX_BIAS);
        }
        let moved = (bias - 1.0).abs();
        assert!(
            moved < State::AUDIO_MAX_BIAS / 4.0,
            "a one-second dropout moved the estimate by {moved}, most of its {} range",
            State::AUDIO_MAX_BIAS
        );
    }
}