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
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
use crate::nes::{
RunState,
action::DebugStep,
audio::{Audio, State as AudioState},
config::{Config, FrameRate},
debug::{Marks, Session},
emulation::{replay::Record, rewind::Rewind},
event::{
ConfigEvent, DebugEvent, DebugRequest, DebugWrite, EmulationEvent, NesEvent, NesEventProxy,
RendererEvent, UiEvent,
},
renderer::{
FrameRecycle,
gui::{
MessageType,
debugger::{AddressSpace, CpuSnapshot},
},
},
};
use anyhow::{Context, anyhow};
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::ResetKind,
control_deck::{self, Clocked, ControlDeck, LoadedRom},
cpu::{Cpu, IrqFlags},
debug::{Access, Breakpoint, CodeMap, RunTo, expr::Expr},
input::{ExpansionDevice, Player, PortDevice},
mapper::MapperOps,
memory::{PRG_PAGES, Page},
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 {
/// When this frame was measured, so samples can be plotted against a real time axis.
pub timestamp: Instant,
/// Frames per second, averaged over the sample window.
pub fps: f32,
/// The lowest frames per second in the sample window.
pub fps_min: f32,
/// Milliseconds per frame, averaged over the sample window.
pub frame_time: f32,
/// The longest frame in the sample window, in milliseconds.
pub frame_time_max: f32,
/// This frame alone, in milliseconds. The averages above hide the hitches a plot is for.
pub frame_time_raw: f32,
/// Frames emulated since stats were last reset.
pub frame_count: usize,
/// Frames emulated but never drawn, because the renderer had not claimed the previous one.
pub dropped_frames: 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_time_raw: 0.0,
frame_count: 0,
dropped_frames: 0,
}
}
}
impl FrameStats {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Debug)]
#[must_use]
pub struct FrameTimeDiag {
frame_count: usize,
dropped_frames: 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);
/// Frames to measure before reporting anything, so the average settles.
///
/// The first interval after a reset is also a fraction of a frame rather than a whole one,
/// and plotted it reads as a dip to zero.
const WARMUP: usize = 10;
fn new() -> Self {
Self {
frame_count: 0,
dropped_frames: 0,
history: VecDeque::with_capacity(Self::MAX_HISTORY),
sum: 0.0,
avg: 1.0 / 60.0,
last_update: Instant::now(),
}
}
const fn is_warm(&self) -> bool {
self.frame_count >= Self::WARMUP
}
fn push(&mut self, frame_time: f32) {
self.frame_count += 1;
if frame_time.is_finite() && self.is_warm() {
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()
}
const fn drop_frame(&mut self) {
self.dropped_frames += 1;
}
fn reset(&mut self) {
self.frame_count = 0;
self.dropped_frames = 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);
}
/// Whether an armed breakpoint stops the console where it now stands.
///
/// The one condition every way of running the console asks, so a step reaches a breakpoint the
/// same way a resume does. Reads and writes are caught on the bus and left in `access_hit`.
/// Execution is checked here, between instructions, since a fetch and an operand read look alike
/// on the bus.
fn breaks_here(bus: &Bus, breakpoints: &[Breakpoint], run_to: Option<RunTo>) -> bool {
run_to.is_some_and(|run_to| run_to.reached(bus))
|| bus.access_hit.is_some()
|| breakpoints
.iter()
.any(|breakpoint| breakpoint.breaks && breakpoint.fires(bus, bus.cpu.pc, Access::EXEC))
}
#[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 honors 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,
/// What the Debugger wants each frame, if it is open.
debug_request: Option<DebugRequest>,
/// The PRG mapping the address space was last captured as, so the capture is skipped when the
/// board has not bank switched since.
debug_pages: Option<[Page; PRG_PAGES]>,
/// The code map generation the address space was last captured at, so the capture is also
/// redone when execution has revealed an instruction the last one collapsed as unknown.
debug_generation: Option<u64>,
/// Where PC was for the last address space sent, which anchors a row in it.
debug_pc: Option<u16>,
/// What the code map recorded before the debugger closed, kept so that reopening it does not
/// start over. Only recording stops. The marks stay true for as long as the cart is loaded.
debug_code_map: Option<CodeMap>,
/// What the Debugger's window has set on the loaded ROM, as the session file keeps it.
///
/// Kept here rather than in the window because this side owns the code map, and one file has
/// both. Replaced whenever the window sends a change.
debug_marks: Marks,
/// A one-shot stop asked alongside the breakpoints, dropped as it is reached.
///
/// What "run to here" and "run to the next interrupt" both arm. It forces the same
/// instruction-at-a-time path an armed breakpoint does, so a resume with one pending is as
/// slow as one with a breakpoint, and as brief.
debug_run_to: Option<RunTo>,
/// Addresses to stop the console at, empty unless the Debugger has armed some.
///
/// Checking them means clocking the console an instruction at a time, so an empty list is what
/// keeps a console with no breakpoints on the frame-at-a-time path.
debug_breakpoints: Vec<Breakpoint>,
/// The expressions the Watches pane wants, in the order it lists them. Empty while the pane
/// is closed, so a closed pane evaluates nothing.
debug_watches: Vec<Option<Expr>>,
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,
/// Frame-time accounting for `--bench`, absent in normal play.
bench: Option<Bench>,
}
impl Drop for State {
fn drop(&mut self) {
self.unload_rom();
}
}
/// Frame-time accounting for `--bench`.
///
/// Records the wall interval between finished frames, which is throughput rather than the cost of
/// any one frame: threaded, that is the emulation thread's own rate, and single-threaded it is
/// emulation plus render plus present, because the event loop does all three in turn.
#[derive(Debug)]
#[must_use]
struct Bench {
/// Untimed frames still owed before the clock starts, so the measurement is not of boot.
warmup: u32,
/// Timed frames still owed.
remaining: u32,
/// Interval of each timed frame, in milliseconds.
intervals: Vec<f32>,
/// When the previous frame finished, or `None` before the first timed frame.
last: Option<Instant>,
}
impl Bench {
/// Frames clocked before timing starts. Matches `clock_frame`'s default so the two benchmarks
/// are measuring the same part of the run.
const WARMUP_FRAMES: u32 = 120;
fn new(frames: u32) -> Self {
Self {
warmup: Self::WARMUP_FRAMES,
remaining: frames,
intervals: Vec::with_capacity(frames as usize),
last: None,
}
}
/// Records a finished frame, returning true once the last timed frame is in.
fn frame_done(&mut self) -> bool {
if self.warmup > 0 {
self.warmup -= 1;
return false;
}
let now = Instant::now();
// The first timed frame only starts the clock: an interval needs two endpoints, and the
// one before it is the last warmup frame, which was not measured.
if let Some(last) = self.last.replace(now) {
self.intervals.push((now - last).as_secs_f32() * 1000.0);
self.remaining -= 1;
}
self.remaining == 0
}
/// Prints the same statistics `clock_frame` reports, so the two can be read side by side.
fn report(&self, threaded: bool) {
let n = self.intervals.len() as f32;
if n == 0.0 {
println!("no frames were timed");
return;
}
let mean = self.intervals.iter().sum::<f32>() / n;
let var = self
.intervals
.iter()
.map(|t| (t - mean).powi(2))
.sum::<f32>()
/ n;
let stddev = var.sqrt();
let (min, max) = self
.intervals
.iter()
.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), t| {
(lo.min(*t), hi.max(*t))
});
let scope = if threaded {
"emulation thread"
} else {
"emulation + render"
};
println!("\n=== RESULTS ({scope}) ===");
println!(
"{:>10} {:>10} {:>8} {:>10} {:>10}",
"ms/frame", "stddev", "cv", "min", "max"
);
println!(
"{mean:>10.3} {stddev:>10.4} {:>7.2}% {min:>10.3} {max:>10.3}",
100.0 * stddev / mean
);
}
}
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,
debug_request: None,
debug_pages: None,
debug_generation: None,
debug_pc: None,
debug_code_map: None,
debug_marks: Marks::default(),
debug_run_to: None,
debug_breakpoints: Vec::new(),
debug_watches: Vec::new(),
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,
bench: cfg.emulation.bench.map(Bench::new),
};
state.update_region();
state.update_run_ahead();
state.sync_devices(cfg.deck.ports, cfg.deck.expansion);
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::DebugSubscribe(request) => {
let resubscribing = self.debug_request.is_some() && request.is_some();
// Executed instructions can only be collected as they run, so recording starts
// when the pane asking for them opens. Only a change in how many lines it asks
// for touches the ring, since every pane toggle re-subscribes and attaching again
// would start it over.
let previous_lines = self
.debug_request
.map_or(0, |request| request.history_lines);
self.debug_request = *request;
let history_lines = request.map_or(0, |request| request.history_lines);
if history_lines != previous_lines {
self.control_deck
.set_pc_history((history_lines > 0).then(|| usize::from(history_lines)));
}
// Calls are recorded as they are made, on the same terms, so the pane opening is
// what starts the stack. Attaching again would throw away the frames execution is
// already inside.
let call_stack = request.is_some_and(|request| request.call_stack);
if call_stack != self.control_deck.call_stack().is_some() {
self.control_deck.set_call_stack(call_stack);
}
// Which bytes are instructions is marked by running them, so the map starts here
// too. A first subscription starts empty until the game runs, leaving the
// disassembly one large unknown block plus whatever PC points at. Closing the
// debugger stops the recording but keeps the marks, so reopening it does not start
// over.
if request.is_some() {
// Attaching again would hand `None` back and start a fresh map, throwing away
// every mark the session has made.
if !resubscribing {
let recorded = self.debug_code_map.take();
self.control_deck.attach_code_map(recorded);
}
} else {
self.debug_code_map = self.control_deck.detach_code_map();
// Nothing would report a stop with the Debugger closed, so the console would
// sit paused with no way to see why. The list itself is the Debugger's, and
// comes back when it reopens.
self.debug_breakpoints.clear();
self.control_deck.set_breakpoints([]);
}
// A fresh subscription has nothing to compare against, so ensure an updated address
// space is sent.
self.debug_pages = None;
self.debug_generation = None;
self.send_address_space();
self.send_debug_snapshot();
}
EmulationEvent::DebugWatches(watches) => {
self.debug_watches.clone_from(watches);
// Answered now rather than on the next frame. A watch is usually typed at a
// breakpoint, where a paused console clocks nothing and would leave it blank.
self.send_debug_snapshot();
}
EmulationEvent::DebugWrite(write) => self.debug_write(*write),
EmulationEvent::DebugRunTo(run_to) => {
self.debug_run_to = *run_to;
// Cleared as the waiting starts, so an interrupt taken before this was armed does
// not stop the console the moment it resumes.
self.control_deck.clear_interrupt();
if run_to.is_some() {
self.set_run_state(RunState::Running);
}
}
EmulationEvent::DebugMarks(marks) => {
// A name gets a row of its own above what it names, so the address space is
// rebuilt when one changes. Neither the page table nor the code map moved, which
// is all `send_address_space` watches on its own.
let relabelled = self.debug_marks.labels != marks.labels;
self.debug_marks = (**marks).clone();
if relabelled {
self.debug_pages = None;
self.send_address_space();
// Answered with a snapshot as well, the way a typed-over register is. A change
// made by hand has to show on the frame it was made, and a paused console
// clocks none of its own to carry it.
self.send_debug_snapshot();
}
}
EmulationEvent::DebugBreakpoints(breakpoints) => {
self.debug_breakpoints.clone_from(breakpoints);
// Reads and writes are caught on the bus, execution between instructions, so the
// console is told only the half it can see.
self.control_deck.set_breakpoints(
breakpoints
.iter()
.filter(|breakpoint| {
// Execution stops between instructions, so the deck sees it only for
// the breakpoints that record instead of stopping.
let bus_side = if breakpoint.breaks {
Access::READ | Access::WRITE
} else {
Access::all()
};
breakpoint.access.intersects(bus_side)
})
.map(|breakpoint| Breakpoint {
access: if breakpoint.breaks {
breakpoint.access & (Access::READ | Access::WRITE)
} else {
breakpoint.access
},
..breakpoint.clone()
}),
);
}
EmulationEvent::AddDebugger(debugger) => {
// Answer with a snapshot before installing it, so a viewer that opens a view while
// the console is stopped fills from that rather than waiting for a dot the
// stopped console never reaches.
(debugger.callback)(self.control_deck.bus());
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() {
// Cloned so the step can drive the console while the condition still reads
// the armed set. At most `Breakpoints::MAX` `Copy` structs, and only on a
// step.
let breakpoints = self.debug_breakpoints.clone();
// Asked by a step too, so a step that reaches what a resume was waiting for
// stops on it the same way.
let run_to = self.debug_run_to;
let stopped = match step {
// A step of exactly one instruction lands where it was asked to, so
// announcing a breakpoint at the address it was aimed at says nothing.
// What it read or wrote on the way is still worth reporting.
DebugStep::Into => {
self.write_deck(|deck| deck.clock_instr()).map(|()| false)
}
DebugStep::Out => {
// Waiting on the stack pointer alone stops in the middle of returning
// from a subroutine, where it pulls saved registers back off the
// stack. The stack frame has not been left until the return address
// itself is pulled, which only a return instruction does.
let sp = self.control_deck.bus().cpu.sp;
Some(self.step_until(&breakpoints, |deck, opcode| {
matches!(opcode, Cpu::RTS | Cpu::RTI) && deck.bus().cpu.sp > sp
}))
}
DebugStep::Over => {
// Only a jump has anything to step over.
let &Cpu { pc, sp, .. } = &self.control_deck.bus().cpu;
let is_jsr = self.control_deck.bus().peek(pc) == Cpu::JSR;
self.write_deck(|deck| deck.clock_instr()).map(|()| {
is_jsr
// The stack pointer is below where the call left it, and the
// only thing that brings it back up to `sp` is pulling that
// return address.
&& self.step_until(&breakpoints, |deck, _| {
deck.bus().cpu.sp >= sp
})
})
}
DebugStep::Scanline => self.write_deck(|deck| {
deck.clock_scanline_until(|bus| breaks_here(bus, &breakpoints, run_to))
}),
DebugStep::Frame => {
// One NES frame, which stepping means regardless of the speed a
// display frame would clock.
self.write_deck(|deck| {
deck.clock_frame_until(|bus| breaks_here(bus, &breakpoints, run_to))
.map(|clocked| clocked == Clocked::Stopped)
})
}
};
if let Some(stopped) = stopped {
// A step that reached a breakpoint reports it the way a running console
// does, so the message and the window focus are the same either way. An
// access is caught part way through an instruction, which a step of any
// size can make.
if stopped || self.control_deck.bus().access_hit.is_some() {
self.on_breakpoint(self.control_deck.bus().cpu.pc);
} else {
self.send_frame();
}
}
// A step can cross a bank switch, which moves every instruction after it.
self.send_address_space();
}
}
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());
// A paused console sends no frame snapshots, so the Input pane would otherwise
// keep drawing the buttons as they were before the click.
self.send_debug_snapshot();
}
}
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::PowerPad((button, state)) => {
if self.control_deck.is_running() {
let pressed = *state == ElementState::Pressed;
self.control_deck
.power_pad_mut()
.set_button(*button, pressed);
self.record
.push(self.control_deck.frame_number(), event.clone());
// As for a joypad button, so the Input pane's mat follows a click while paused.
self.send_debug_snapshot();
}
}
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.reset_frame_stats();
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.reset_frame_stats();
self.show_frame_stats = *show;
}
EmulationEvent::ResetFrameStats => self.reset_frame_stats(),
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(),
// Both send a snapshot so the Input pane's Zapper row follows them while paused.
EmulationEvent::ZapperAim((x, y)) => {
self.control_deck.aim_zapper(*x, *y);
self.record
.push(self.control_deck.frame_number(), event.clone());
self.send_debug_snapshot();
}
EmulationEvent::ZapperTrigger => {
self.control_deck.trigger_zapper();
self.record
.push(self.control_deck.frame_number(), event.clone());
self.send_debug_snapshot();
}
}
}
/// What the deck has plugged into ports 1 and 2.
const fn ports(&self) -> [PortDevice; 2] {
[
self.control_deck.port_device(Player::One),
self.control_deck.port_device(Player::Two),
]
}
/// Sends the config a [`ConfigEvent`] for each of `ports` and `expansion` that differs from
/// what the deck has plugged in. The deck allows one mat, so plugging in one undoes the other.
// The event comes back here once more, and is a no-op then because the deck already holds it.
fn sync_devices(&self, ports: [PortDevice; 2], expansion: ExpansionDevice) {
let actual = self.ports();
if actual != ports {
self.tx.event(ConfigEvent::Ports(actual));
}
let actual = self.control_deck.expansion_device();
if actual != expansion {
self.tx.event(ConfigEvent::Expansion(actual));
}
}
/// 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);
}
// Each of these changes what the debugger's Input pane draws, and a paused console
// sends no frame snapshots to show it.
ConfigEvent::FourPlayer(four_player) => {
self.control_deck.set_four_player(*four_player);
self.send_debug_snapshot();
}
ConfigEvent::Ports([one, two]) => {
let expansion = self.control_deck.expansion_device();
self.control_deck.set_port_device(Player::One, *one);
self.control_deck.set_port_device(Player::Two, *two);
self.sync_devices(self.ports(), expansion);
self.send_debug_snapshot();
}
ConfigEvent::Expansion(expansion) => {
let ports = self.ports();
self.control_deck.set_expansion_device(*expansion);
self.sync_devices(ports, *expansion);
self.send_debug_snapshot();
}
ConfigEvent::GenieCodeAdded(genie_code) => {
self.control_deck.add_patch(genie_code.into());
}
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();
}
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),
_ => (),
}
}
/// Counts a frame against `--bench`, reporting and shutting down once the last one is in.
fn update_bench(&mut self) {
let threaded = self.threaded;
if let Some(bench) = &mut self.bench
&& bench.frame_done()
{
bench.report(threaded);
self.tx.event(UiEvent::Terminate);
}
}
/// Starts the frame time history over, without the gap since it was last measured.
///
/// Whatever stalled or idled in between is not a frame time, and left in it would be both the
/// window's maximum and the whole scale of its plot.
fn reset_frame_stats(&mut self) {
self.frame_time_diag.reset();
self.last_frame_time = Instant::now();
}
fn update_frame_stats(&mut self) {
if !self.show_frame_stats {
return;
}
let frame_time_raw = self.last_frame_time.elapsed().as_secs_f32();
self.frame_time_diag.push(frame_time_raw);
self.last_frame_time = Instant::now();
if !self.frame_time_diag.is_warm() {
return;
}
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_time_raw: frame_time_raw * 1000.0,
frame_count: self.frame_time_diag.frame_count,
dropped_frames: self.frame_time_diag.dropped_frames,
}));
}
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");
self.frame_time_diag.drop_frame();
}
Err(_) => shutdown(&self.tx, "failed to get frame"),
}
self.send_debug_snapshot();
}
/// Clock instructions until `done` or an armed breakpoint, or until a default budget is spent,
/// reporting whether a breakpoint stopped it.
///
/// Bounded by budget because a subroutine that never returns - a crash, or a wait loop - would
/// otherwise never finish, and on the single-threaded backend would block the UI thread. The
/// budget is a few seconds of emulated time, far longer than any subroutine worth stepping
/// over.
fn step_until(
&mut self,
breakpoints: &[Breakpoint],
done: impl Fn(&ControlDeck, u8) -> bool,
) -> bool {
const BUDGET: usize = 5_000_000;
for _ in 0..BUDGET {
let pc = self.control_deck.bus().cpu.pc;
let opcode = self.control_deck.bus().peek(pc);
if self.write_deck(|deck| deck.clock_instr()).is_none() {
return false;
}
// Asked before `done`, so a step that both returns and lands on a breakpoint reports
// the breakpoint. Either way the console stops in the same place.
if breaks_here(self.control_deck.bus(), breakpoints, self.debug_run_to) {
return true;
}
if done(&self.control_deck, opcode) {
return false;
}
}
self.add_message(
MessageType::Warn,
"Step timed out - the subroutine has not returned.",
);
false
}
/// Send the Debugger a snapshot, if it's open.
fn send_debug_snapshot(&mut self) {
if let Some(request) = &self.debug_request {
let mut snapshot = CpuSnapshot::capture(self.control_deck.bus(), request);
snapshot.access_log = self.control_deck.drain_access_log();
// Evaluated here rather than in `capture`, since the expressions belong to the window
// and the console is only asked to read them.
let bus = self.control_deck.bus();
snapshot.watches = self
.debug_watches
.iter()
.map(|watch| watch.as_ref().map(|expr| expr.eval(bus)))
.collect();
self.tx.event(DebugEvent::Cpu(Box::new(snapshot)));
}
}
/// Apply what the Debugger typed over, and show the console it left behind.
///
/// The address space is a function of the bytes and of PC, which anchors a row and starts the
/// forward decode, so a write to either has to rebuild it. Forgetting what the last send was
/// built from forces that, since neither moves the page table or the code map that
/// [`State::send_address_space`] otherwise watches.
fn debug_write(&mut self, write: DebugWrite) {
let bus = self.control_deck.bus_mut();
match write {
DebugWrite::Pc(pc) => bus.cpu.pc = pc,
DebugWrite::Acc(acc) => bus.cpu.acc = acc,
DebugWrite::X(x) => bus.cpu.x = x,
DebugWrite::Y(y) => bus.cpu.y = y,
DebugWrite::Sp(sp) => bus.cpu.sp = sp,
DebugWrite::Status(status) => bus.cpu.status = status,
// The CPU polls these every cycle, so a change is seen before the next instruction
// ends, the way a source changing on its own would be.
DebugWrite::Nmi(pending) => bus.cpu.irq_flags.set(IrqFlags::NMI, pending),
// The CPU reads the line only where `mapper_ops` has `IRQ`, and `Mapper` asserts that a
// board without it never raises one.
DebugWrite::CartIrq(pending) => {
if bus.mapper_ops.contains(MapperOps::IRQ) {
bus.mapper.set_irq_pending(pending);
}
}
DebugWrite::FrameIrq(pending) => bus.apu.frame_counter.irq_pending = pending,
DebugWrite::DmcIrq(pending) => bus.apu.dmc.irq_pending = pending,
DebugWrite::Memory { addr, val } => {
bus.poke(addr, val);
}
}
self.debug_pages = None;
self.send_address_space();
self.send_debug_snapshot();
}
/// Send the address space if anything it is built from has changed since the last send.
///
/// PC is one of those things: it anchors a row and seeds the forward decode, so a jump into
/// the middle of a routine that has already run leaves no row starting where the console now
/// is, and nothing to draw the highlight on.
///
/// Only called when the console is stopped - opening the debugger, stepping, pausing.
fn send_address_space(&mut self) {
if self.debug_request.is_none() {
return;
}
let pages = *self.control_deck.bus().memory.prg_pages();
let generation = self.control_deck.code_map().map(CodeMap::generation);
let pc = self.control_deck.bus().cpu.pc;
if self.debug_pages == Some(pages)
&& self.debug_generation == generation
&& self.debug_pc == Some(pc)
{
return;
}
self.debug_pages = Some(pages);
self.debug_generation = generation;
self.debug_pc = Some(pc);
let address_space =
AddressSpace::capture(self.control_deck.bus(), &self.debug_marks.labels);
self.tx
.event(DebugEvent::AddressSpace(Box::new(address_space)));
}
/// Stop the console at a breakpoint and tell the UI which one it was.
fn on_breakpoint(&mut self, addr: u16) {
// Stopped here rather than by asking the UI to pause us: that request would have to go
// round the event loop, and on the threaded backend the console would run on - past the
// breakpoint by however many frames the round trip took - before it arrived.
self.set_run_state(RunState::ManuallyPaused);
// Half a frame's worth of pixels, which the console has drawn at this point.
self.send_frame();
// One shot, so what was waited for is dropped as it arrives and a resume runs on. Taken
// before the report, which names what the console reached.
let run_to = self
.debug_run_to
.take()
.filter(|run_to| run_to.reached(self.control_deck.bus()));
// An access is caught part way through an instruction and reported at the boundary after
// it, so it names what was touched rather than where PC now sits.
match (run_to, self.control_deck.take_access_hit()) {
(Some(run_to), _) => self.tx.event(DebugEvent::RanTo(run_to, addr)),
(None, Some(hit)) => self.tx.event(DebugEvent::AccessBreak(hit)),
(None, None) => self.tx.event(DebugEvent::Breakpoint(addr)),
}
}
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);
}
self.send_address_space();
self.send_debug_snapshot();
} 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.update_region();
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) {
// Taken by value, since everything below writes through the console the name came from.
if let Some(name) = self.control_deck.loaded_rom().map(|rom| rom.name.clone()) {
if self.auto_save {
let save_path = Config::save_path(&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();
self.save_debug_session(&name);
// Marks and breakpoint offsets both index this cart's memory. Both load paths come
// through here, so neither can outlive the cart it describes. The window keeps the
// breakpoints it can and resends them.
self.debug_code_map = None;
self.debug_marks = Marks::default();
self.debug_breakpoints.clear();
self.control_deck.set_breakpoints([]);
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.reset_frame_stats();
}
}
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:?}");
}
}
// After the auto-load, since a state is restored with the region it was recorded at.
self.update_region();
if let Err(err) = self.audio.start() {
self.tx.event(ConfigEvent::AudioEnabled(false));
self.on_error(err);
}
self.load_debug_session(&rom.name);
self.tx.event(RendererEvent::RomLoaded(rom));
self.tx.event(RendererEvent::RequestRedraw {
viewport_id: ViewportId::ROOT,
when: Instant::now(),
});
self.reset_frame_stats();
self.last_auto_save = Instant::now();
}
/// Read what an earlier session left for this ROM, and hand the window its half.
///
/// A Debugger already watching takes the code map straight away. One that is not leaves it
/// in `debug_code_map`, where a map kept across a closed window waits too, and the next
/// subscription puts it on.
fn load_debug_session(&mut self, name: &str) {
let mut session = Session::load(name);
session.accept(&self.control_deck.bus().memory);
self.debug_marks = session.marks;
if self.debug_request.is_some() {
// Put on straight away for a Debugger that is already watching. Only a fresh
// subscription attaches what is waiting, and this cart came up with an empty map that
// would otherwise stand until the window was closed and opened again.
self.control_deck.attach_code_map(session.code_map);
self.debug_code_map = None;
} else {
self.debug_code_map = session.code_map;
}
// Ahead of the rows, so the window has the names before the capture that puts them in
// arrives and an operand is never drawn against names it does not have yet.
self.tx
.event(DebugEvent::Marks(Box::new(self.debug_marks.clone())));
// The rows are a function of the names, and neither the page table nor the code map
// generation says a name changed, so the rebuild is asked for rather than noticed.
self.debug_pages = None;
self.send_address_space();
self.send_debug_snapshot();
}
/// Write what this session has learned about `name`, code map and window marks together.
///
/// The map is read back off the console when the Debugger is open, since that is where it
/// lives while it is recording.
fn save_debug_session(&mut self, name: &str) {
let code_map = self
.control_deck
.code_map()
.cloned()
.or_else(|| self.debug_code_map.clone());
let session = Session {
code_map,
marks: self.debug_marks.clone(),
};
if let Err(err) = session.save(name) {
error!("failed to save debug session: {err:?}");
}
}
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.update_region();
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),
}
}
/// Pace frames at the rate of the region the console is running, which a load can change.
//
// The deck's region, not the configured one: a config of `Auto` resolves to the cart's region
// only inside the deck, and `FrameRate::from(Auto)` is 60 Hz. Pacing a PAL cart at 60 Hz
// produces 20% more audio than the card consumes, far past what rate control can absorb, so
// the buffer sits full and the sound lags the picture.
fn update_region(&mut self) {
self.target_frame_duration = FrameRate::from(self.control_deck.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(
jiff::ZonedDateTime::now()
.strftime("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 if self.bench.is_some() {
// Benchmarking measures how fast frames *can* be produced, so the frame clock that
// normally holds them to the region's rate does not apply. Only the running check
// above still does: a paused benchmark would spin without producing frames.
None
} 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, and
/// reports the breakpoint it stopped at if it reached one.
///
/// 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<Option<u16>> {
loop {
// Only a breakpoint that stops needs the check between instructions. One that records
// is caught on the bus, and an `access_hit` is only ever set by one that stops, so a
// list of recording breakpoints alone keeps the frame-at-a-time path. A pending
// one-shot is asked between instructions too, so it leaves that path the same way,
// and a console with neither never takes it.
let frame = self.control_deck.frame_number();
let clocked = if self.debug_run_to.is_none()
&& !self.debug_breakpoints.iter().any(|b| b.breaks)
{
self.control_deck.clock_frame()?
} else {
let breakpoints = &self.debug_breakpoints;
let run_to = self.debug_run_to;
self.control_deck
.clock_frame_until(|bus| breaks_here(bus, breakpoints, run_to))?
};
// A stop usually lands part way through a frame, where there is nothing to snapshot.
// It can also land on the instruction that ends one, and that frame is finished and
// worth a snapshot however the call reported it, or rewind gets a hole wherever a
// breakpoint happens to sit on a frame boundary.
let clocked_a_frame =
clocked != Clocked::Idle && self.control_deck.frame_number() != frame;
if clocked_a_frame && let Err(err) = self.rewind.push(&self.control_deck) {
self.rewind.set_enabled(false);
self.on_error(err);
}
if clocked == Clocked::Stopped {
return Ok(Some(self.control_deck.bus().cpu.pc));
}
if clocked != Clocked::Continue {
return Ok(None);
}
}
}
/// 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 {
// Stop rewinding if a restore fails
if self.rewind.pop(&mut self.control_deck) {
// A rewind frame excludes the frame buffer, so render it by clocking the frame
// Below 1x speed, clocking may not produce a frame so clock until one is 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;
}
}
}
self.send_frame();
self.update_frame_stats();
} else {
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(Some(addr)) => self.on_breakpoint(addr),
Ok(None) => {
self.audio.process(self.control_deck.audio_samples());
self.update_audio_rate();
self.send_frame();
self.update_frame_stats();
self.update_bench();
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::*;
use tetanes_core::{
cart::Cart,
common::ResetKind,
debug::{FrameKind, expr::Expr},
mapper::Nrom,
};
/// A console with a cart in, for the breakpoint conditions to read.
fn bus() -> Bus {
let mut bus = Bus::default();
let mut cart = Cart::empty();
*cart.mapper_mut() = Nrom::load(&mut cart).unwrap();
bus.load_cart(cart);
bus.reset(ResetKind::Hard);
bus
}
/// A one-shot is asked beside the breakpoints, so a console with none still stops on it.
#[test]
fn a_one_shot_stops_where_no_breakpoint_does() {
let mut bus = bus();
bus.cpu.pc = 0xC000;
assert!(!breaks_here(&bus, &[], None), "nothing armed at all");
assert!(
breaks_here(&bus, &[], Some(RunTo::Address(0xC000))),
"the address the console is sitting on"
);
assert!(
!breaks_here(&bus, &[], Some(RunTo::Address(0xC001))),
"and not the one after it"
);
}
/// An interrupt is read from what the console recorded taking a vector, not from PC: a
/// handler's first address can be jumped to like any other.
#[test]
fn a_one_shot_on_an_interrupt_reads_the_vector_that_was_taken() {
let mut bus = bus();
assert!(!breaks_here(&bus, &[], Some(RunTo::Interrupt)), "none yet");
bus.interrupt_taken = Some(FrameKind::Irq);
assert!(breaks_here(&bus, &[], Some(RunTo::Irq)));
assert!(breaks_here(&bus, &[], Some(RunTo::Interrupt)));
assert!(
!breaks_here(&bus, &[], Some(RunTo::Nmi)),
"the other vector does not answer for it"
);
bus.interrupt_taken = Some(FrameKind::Nmi);
assert!(breaks_here(&bus, &[], Some(RunTo::Nmi)));
assert!(!breaks_here(&bus, &[], Some(RunTo::Irq)));
}
/// A breakpoint on `addr` that stops before it executes, the shape a gutter click makes.
fn execute(addr: u16, condition: Option<&str>) -> Breakpoint {
Breakpoint {
start: addr,
end: addr,
offset: None,
access: Access::EXEC,
breaks: true,
condition: condition.map(|text| Expr::parse(text).expect("parses")),
}
}
/// Execution is the one access the bus cannot catch, so it is checked here rather than in
/// `Breakpoints::check`. Asking a narrower question here than that does would make a
/// condition hold on a read and be ignored on the instruction that made it.
#[test]
fn an_execution_breakpoint_honors_its_condition() {
let mut bus = bus();
bus.cpu.pc = 0xC000;
let breakpoints = [execute(0xC000, Some("a == 0x42"))];
bus.cpu.acc = 0x01;
assert!(!breaks_here(&bus, &breakpoints, None));
bus.cpu.acc = 0x42;
assert!(breaks_here(&bus, &breakpoints, None));
}
/// A range breakpoint asks its condition at every address it covers, not only at the one it
/// starts on.
#[test]
fn a_range_breakpoint_honors_its_condition_across_the_range() {
let mut bus = bus();
let breakpoints = [Breakpoint {
end: 0x7FFF,
..execute(0x6000, Some("a == 0xFF"))
}];
for pc in [0x6000, 0x6500, 0x7FFF] {
bus.cpu.pc = pc;
bus.cpu.acc = 0x01;
assert!(
!breaks_here(&bus, &breakpoints, None),
"${pc:04X} with a = $01"
);
bus.cpu.acc = 0xFF;
assert!(
breaks_here(&bus, &breakpoints, None),
"${pc:04X} with a = $FF"
);
}
}
#[test]
fn an_execution_breakpoint_with_no_condition_stops_wherever_it_covers() {
let mut bus = bus();
bus.cpu.pc = 0xC000;
assert!(breaks_here(&bus, &[execute(0xC000, None)], None));
assert!(!breaks_here(&bus, &[execute(0xC001, None)], None));
}
/// 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-center 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
);
}
}