This repository has been archived by the owner on Sep 11, 2023. It is now read-only.
forked from SourMesen/Mesen
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathConsole.cpp
1634 lines (1363 loc) · 42.6 KB
/
Console.cpp
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
#include "stdafx.h"
#include <random>
#include <thread>
#include "Console.h"
#include "CPU.h"
#include "PPU.h"
#include "APU.h"
#include "MemoryManager.h"
#include "AutoSaveManager.h"
#include "BaseMapper.h"
#include "ControlManager.h"
#include "VsControlManager.h"
#include "MapperFactory.h"
#include "Debugger.h"
#include "MessageManager.h"
#include "EmulationSettings.h"
#include "../Utilities/sha1.h"
#include "../Utilities/Timer.h"
#include "../Utilities/FolderUtilities.h"
#include "../Utilities/PlatformUtilities.h"
#include "VirtualFile.h"
#include "HdBuilderPpu.h"
#include "HdPpu.h"
#include "NsfPpu.h"
#include "SoundMixer.h"
#include "NsfMapper.h"
#include "MovieManager.h"
#include "RewindManager.h"
#include "SaveStateManager.h"
#include "HdPackBuilder.h"
#include "HdAudioDevice.h"
#include "FDS.h"
#include "SystemActionManager.h"
#include "FdsSystemActionManager.h"
#include "VsSystemActionManager.h"
#include "FamilyBasicDataRecorder.h"
#include "IBarcodeReader.h"
#include "IBattery.h"
#include "KeyManager.h"
#include "BatteryManager.h"
#include "DebugHud.h"
#include "RomLoader.h"
#include "CheatManager.h"
#include "VideoDecoder.h"
#include "VideoRenderer.h"
#include "DebugHud.h"
#include "NotificationManager.h"
#include "HistoryViewer.h"
#include "ConsolePauseHelper.h"
#include "EventManager.h"
#include "PgoUtilities.h"
Console::Console(shared_ptr<Console> master, EmulationSettings* initialSettings)
{
_master = master;
if(_master) {
//Slave console should use the same settings as the master
_settings = _master->_settings;
} else {
if(initialSettings) {
_settings.reset(new EmulationSettings(*initialSettings));
} else {
_settings.reset(new EmulationSettings());
}
KeyManager::SetSettings(_settings.get());
}
_pauseCounter = 0;
_model = NesModel::NTSC;
}
Console::~Console()
{
MovieManager::Stop();
}
void Console::Init()
{
_notificationManager.reset(new NotificationManager());
_batteryManager.reset(new BatteryManager());
_videoRenderer.reset(new VideoRenderer(shared_from_this()));
_videoDecoder.reset(new VideoDecoder(shared_from_this()));
_saveStateManager.reset(new SaveStateManager(shared_from_this()));
_cheatManager.reset(new CheatManager(shared_from_this()));
_debugHud.reset(new DebugHud());
_soundMixer.reset(new SoundMixer(shared_from_this()));
_soundMixer->SetNesModel(_model);
if(_master) {
_emulationThreadId = _master->_emulationThreadId;
}
}
void Console::Release(bool forShutdown)
{
if(_slave) {
_slave->Release(true);
_slave.reset();
}
if(forShutdown) {
_videoDecoder->StopThread();
_videoRenderer->StopThread();
_videoDecoder.reset();
_videoRenderer.reset();
_debugHud.reset();
_saveStateManager.reset();
_cheatManager.reset();
_soundMixer.reset();
_notificationManager.reset();
}
if(_master) {
_master->_notificationManager->SendNotification(ConsoleNotificationType::VsDualSystemStopped);
}
_rewindManager.reset();
_autoSaveManager.reset();
_hdPackBuilder.reset();
_hdData.reset();
_hdAudioDevice.reset();
_systemActionManager.reset();
_master.reset();
_cpu.reset();
_ppu.reset();
_apu.reset();
_debugger.reset();
_mapper.reset();
_memoryManager.reset();
_controlManager.reset();
}
shared_ptr<BatteryManager> Console::GetBatteryManager()
{
return _batteryManager;
}
shared_ptr<SaveStateManager> Console::GetSaveStateManager()
{
return _saveStateManager;
}
shared_ptr<VideoDecoder> Console::GetVideoDecoder()
{
return _videoDecoder;
}
shared_ptr<VideoRenderer> Console::GetVideoRenderer()
{
return _videoRenderer;
}
shared_ptr<DebugHud> Console::GetDebugHud()
{
return _debugHud;
}
void Console::SaveBatteries()
{
shared_ptr<BaseMapper> mapper = _mapper;
shared_ptr<ControlManager> controlManager = _controlManager;
if(mapper) {
mapper->SaveBattery();
}
if(controlManager) {
shared_ptr<IBattery> device = std::dynamic_pointer_cast<IBattery>(controlManager->GetControlDevice(BaseControlDevice::ExpDevicePort));
if(device) {
device->SaveBattery();
}
}
}
bool Console::LoadMatchingRom(string romName, HashInfo hashInfo)
{
if(_initialized) {
string currentRomFilepath = GetRomPath().GetFilePath();
if(!currentRomFilepath.empty()) {
HashInfo gameHashInfo = GetRomInfo().Hash;
if(gameHashInfo.Crc32 == hashInfo.Crc32 || gameHashInfo.Sha1.compare(hashInfo.Sha1) == 0 || gameHashInfo.PrgChrMd5.compare(hashInfo.PrgChrMd5) == 0) {
//Current game matches, power cycle game and return
PowerCycle();
return true;
}
}
}
string match = FindMatchingRom(romName, hashInfo);
if(!match.empty()) {
return Initialize(match);
}
return false;
}
string Console::FindMatchingRom(string romName, HashInfo hashInfo)
{
if(_initialized) {
VirtualFile currentRom = GetRomPath();
if(currentRom.IsValid() && !GetPatchFile().IsValid()) {
HashInfo gameHashInfo = GetRomInfo().Hash;
if(gameHashInfo.Crc32 == hashInfo.Crc32 || gameHashInfo.Sha1.compare(hashInfo.Sha1) == 0 || gameHashInfo.PrgChrMd5.compare(hashInfo.PrgChrMd5) == 0) {
//Current game matches
return currentRom;
}
}
}
string lcRomname = romName;
std::transform(lcRomname.begin(), lcRomname.end(), lcRomname.begin(), ::tolower);
std::unordered_set<string> validExtensions = { { ".nes", ".fds", "*.unif", "*.unif", "*.nsf", "*.nsfe", "*.7z", "*.zip" } };
vector<string> romFiles;
for(string folder : FolderUtilities::GetKnownGameFolders()) {
vector<string> files = FolderUtilities::GetFilesInFolder(folder, validExtensions, true);
romFiles.insert(romFiles.end(), files.begin(), files.end());
}
if(!romName.empty()) {
//Perform quick search based on file name
string match = RomLoader::FindMatchingRom(romFiles, romName, hashInfo, true);
if(!match.empty()) {
return match;
}
}
//Perform slow CRC32 search for ROM
string match = RomLoader::FindMatchingRom(romFiles, romName, hashInfo, false);
if(!match.empty()) {
return match;
}
return "";
}
bool Console::Initialize(string romFile, string patchFile)
{
VirtualFile rom = romFile;
VirtualFile patch = patchFile;
return Initialize(rom, patch);
}
bool Console::Initialize(VirtualFile &romFile)
{
VirtualFile patchFile;
return Initialize(romFile, patchFile);
}
bool Console::Initialize(VirtualFile &romFile, VirtualFile &patchFile, bool forPowerCycle)
{
if(romFile.IsValid()) {
Pause();
_soundMixer->StopAudio(true);
if(!_romFilepath.empty() && _mapper) {
//Ensure we save any battery file before loading a new game
SaveBatteries();
}
shared_ptr<HdPackData> originalHdPackData = _hdData;
LoadHdPack(romFile, patchFile);
if(patchFile.IsValid()) {
if(romFile.ApplyPatch(patchFile)) {
MessageManager::DisplayMessage("Patch", "ApplyingPatch", patchFile.GetFileName());
} else {
//Patch failed
}
}
_batteryManager->Initialize(FolderUtilities::GetFilename(romFile.GetFileName(), false));
RomData romData;
shared_ptr<BaseMapper> mapper = MapperFactory::InitializeFromFile(shared_from_this(), romFile, romData);
if(mapper) {
bool isDifferentGame = _romFilepath != (string)romFile || _patchFilename != (string)patchFile;
if(_mapper) {
if(isDifferentGame && _ppu->GetFrameCount() > 1) {
//Save current game state before loading another one
_saveStateManager->SaveRecentGame(GetRomInfo().RomName, _romFilepath, _patchFilename);
}
//Send notification only if a game was already running and we successfully loaded the new one
_notificationManager->SendNotification(ConsoleNotificationType::GameStopped, (void*)1);
}
_videoDecoder->StopThread();
if(isDifferentGame) {
_romFilepath = romFile;
_patchFilename = patchFile;
//Changed game, stop all recordings
MovieManager::Stop();
_soundMixer->StopRecording();
StopRecordingHdPack();
}
shared_ptr<BaseMapper> previousMapper = _mapper;
_mapper = mapper;
_memoryManager.reset(new MemoryManager(shared_from_this()));
_cpu.reset(new CPU(shared_from_this()));
_apu.reset(new APU(shared_from_this()));
_mapper->SetConsole(shared_from_this());
_mapper->Initialize(romData);
if(!isDifferentGame && forPowerCycle) {
_mapper->CopyPrgChrRom(previousMapper);
}
if(_slave) {
_slave->Release(false);
_slave.reset();
}
RomInfo romInfo = _mapper->GetRomInfo();
if(!_master && romInfo.VsType == VsSystemType::VsDualSystem) {
_slave.reset(new Console(shared_from_this()));
_slave->Init();
_slave->Initialize(romFile, patchFile);
}
switch(romInfo.System) {
case GameSystem::FDS:
_settings->SetPpuModel(PpuModel::Ppu2C02);
_systemActionManager.reset(new FdsSystemActionManager(shared_from_this(), _mapper));
break;
case GameSystem::VsSystem:
_settings->SetPpuModel(romInfo.VsPpuModel);
_systemActionManager.reset(new VsSystemActionManager(shared_from_this()));
break;
default:
_settings->SetPpuModel(PpuModel::Ppu2C02);
_systemActionManager.reset(new SystemActionManager(shared_from_this())); break;
}
//Temporarely disable battery saves to prevent battery files from being created for the wrong game (for Battle Box & Turbo File)
_batteryManager->SetSaveEnabled(false);
uint32_t pollCounter = 0;
if(_controlManager && !isDifferentGame) {
//When power cycling, poll counter must be preserved to allow movies to playback properly
pollCounter = _controlManager->GetPollCounter();
}
if(romInfo.System == GameSystem::VsSystem) {
_controlManager.reset(new VsControlManager(shared_from_this(), _systemActionManager, _mapper->GetMapperControlDevice()));
} else {
_controlManager.reset(new ControlManager(shared_from_this(), _systemActionManager, _mapper->GetMapperControlDevice()));
}
_controlManager->SetPollCounter(pollCounter);
_controlManager->UpdateControlDevices();
//Re-enable battery saves
_batteryManager->SetSaveEnabled(true);
if(_hdData && (!_hdData->Tiles.empty() || !_hdData->Backgrounds.empty())) {
_ppu.reset(new HdPpu(shared_from_this(), _hdData.get()));
} else if(std::dynamic_pointer_cast<NsfMapper>(_mapper)) {
//Disable most of the PPU for NSFs
_ppu.reset(new NsfPpu(shared_from_this()));
} else {
_ppu.reset(new PPU(shared_from_this()));
}
_memoryManager->SetMapper(_mapper);
_memoryManager->RegisterIODevice(_ppu.get());
_memoryManager->RegisterIODevice(_apu.get());
_memoryManager->RegisterIODevice(_controlManager.get());
_memoryManager->RegisterIODevice(_mapper.get());
if(_hdData && (!_hdData->BgmFilesById.empty() || !_hdData->SfxFilesById.empty())) {
_hdAudioDevice.reset(new HdAudioDevice(shared_from_this(), _hdData.get()));
_memoryManager->RegisterIODevice(_hdAudioDevice.get());
} else {
_hdAudioDevice.reset();
}
_model = NesModel::Auto;
UpdateNesModel(false);
_initialized = true;
if(_debugger) {
//Reset debugger if it was running before
auto lock = _debuggerLock.AcquireSafe();
StopDebugger();
GetDebugger();
}
ResetComponents(false);
//Reset components before creating rewindmanager, otherwise the first save state it takes will be invalid
if(!forPowerCycle) {
KeyManager::UpdateDevices();
_rewindManager.reset(new RewindManager(shared_from_this()));
_notificationManager->RegisterNotificationListener(_rewindManager);
} else {
_rewindManager->Initialize();
}
//Poll controller input after creating rewind manager, to make sure it catches the first frame's input
_controlManager->UpdateInputState();
#ifndef LIBRETRO
//Don't use auto-save manager for libretro
//Only enable auto-save for the master console (VS Dualsystem)
if(IsMaster()) {
_autoSaveManager.reset(new AutoSaveManager(shared_from_this()));
}
#endif
_videoDecoder->StartThread();
FolderUtilities::AddKnownGameFolder(romFile.GetFolderPath());
if(IsMaster()) {
if(!forPowerCycle) {
string modelName = _model == NesModel::PAL ? "PAL" : (_model == NesModel::Dendy ? "Dendy" : "NTSC");
string messageTitle = MessageManager::Localize("GameLoaded") + " (" + modelName + ")";
MessageManager::DisplayMessage(messageTitle, FolderUtilities::GetFilename(GetRomInfo().RomName, false));
}
_settings->ClearFlags(EmulationFlags::ForceMaxSpeed);
if(_slave) {
_notificationManager->SendNotification(ConsoleNotificationType::VsDualSystemStarted);
}
}
//Used by netplay to take save state after UpdateInputState() is called above, to ensure client+server are in sync
if(!_master) {
_notificationManager->SendNotification(ConsoleNotificationType::GameInitCompleted);
}
Resume();
return true;
} else {
_hdData = originalHdPackData;
//Reset battery source to current game if new game failed to load
_batteryManager->Initialize(FolderUtilities::GetFilename(GetRomInfo().RomName, false));
Resume();
}
}
shared_ptr<Debugger> debugger = _debugger;
if(debugger) {
debugger->Resume();
}
MessageManager::DisplayMessage("Error", "CouldNotLoadFile", romFile.GetFileName());
return false;
}
void Console::ProcessCpuClock()
{
_mapper->ProcessEPSMClock();
_mapper->ProcessCpuClock();
_apu->ProcessCpuClock();
}
CPU* Console::GetCpu()
{
return _cpu.get();
}
PPU* Console::GetPpu()
{
return _ppu.get();
}
APU* Console::GetApu()
{
return _apu.get();
}
shared_ptr<SoundMixer> Console::GetSoundMixer()
{
return _soundMixer;
}
shared_ptr<NotificationManager> Console::GetNotificationManager()
{
return _notificationManager;
}
EmulationSettings* Console::GetSettings()
{
return _settings.get();
}
bool Console::IsDualSystem()
{
return _slave != nullptr || _master != nullptr;
}
shared_ptr<Console> Console::GetDualConsole()
{
//When called from the master, returns the slave.
//When called from the slave, returns the master.
//Returns a null pointer when not running a dualsystem game
return _slave ? _slave : _master;
}
bool Console::IsMaster()
{
return !_master;
}
BaseMapper* Console::GetMapper()
{
return _mapper.get();
}
ControlManager* Console::GetControlManager()
{
return _controlManager.get();
}
MemoryManager* Console::GetMemoryManager()
{
return _memoryManager.get();
}
CheatManager* Console::GetCheatManager()
{
return _cheatManager.get();
}
shared_ptr<RewindManager> Console::GetRewindManager()
{
return _rewindManager;
}
HistoryViewer* Console::GetHistoryViewer()
{
return _historyViewer.get();
}
VirtualFile Console::GetRomPath()
{
return static_cast<VirtualFile>(_romFilepath);
}
VirtualFile Console::GetPatchFile()
{
return (VirtualFile)_patchFilename;
}
RomInfo Console::GetRomInfo()
{
return _mapper ? _mapper->GetRomInfo() : (RomInfo {});
}
uint32_t Console::GetFrameCount()
{
return _ppu ? _ppu->GetFrameCount() : 0;
}
uint8_t Console::GetStartingPhase()
{
return _ppu ? _ppu->GetStartingPhase() : 0;
}
NesModel Console::GetModel()
{
return _model;
}
shared_ptr<SystemActionManager> Console::GetSystemActionManager()
{
return _systemActionManager;
}
void Console::PowerCycle()
{
ReloadRom(true);
}
void Console::ReloadRom(bool forPowerCycle)
{
if(_initialized && !_romFilepath.empty()) {
VirtualFile romFile = _romFilepath;
VirtualFile patchFile = _patchFilename;
Initialize(romFile, patchFile, forPowerCycle);
}
}
void Console::Reset(bool softReset)
{
if(_initialized) {
bool needSuspend = softReset ? _systemActionManager->Reset() : _systemActionManager->PowerCycle();
if(needSuspend) {
//Only do this if a reset/power cycle is not already pending - otherwise we'll end up calling Suspend() too many times
//Resume from code break if needed (otherwise reset doesn't happen right away)
shared_ptr<Debugger> debugger = _debugger;
if(debugger) {
debugger->Suspend();
debugger->Run();
}
}
}
}
void Console::ResetComponents(bool softReset)
{
if(_slave) {
//Always reset/power cycle the slave alongside the master CPU
_slave->ResetComponents(softReset);
}
_soundMixer->StopAudio(true);
_debugHud->ClearScreen();
_memoryManager->Reset(softReset);
if(!_settings->CheckFlag(EmulationFlags::DisablePpuReset) || !softReset || IsNsf()) {
_ppu->Reset();
}
_apu->Reset(softReset);
_cpu->Reset(softReset, _model);
_controlManager->Reset(softReset);
_resetRunTimers = true;
//This notification MUST be sent before the UpdateInputState() below to allow MovieRecorder to grab the first frame's worth of inputs
if(!_master) {
_notificationManager->SendNotification(softReset ? ConsoleNotificationType::GameReset : ConsoleNotificationType::GameLoaded);
}
if(softReset) {
shared_ptr<Debugger> debugger = _debugger;
if(debugger) {
debugger->ResetCounters();
debugger->ProcessEvent(EventType::Reset);
debugger->Resume();
}
}
}
void Console::Stop(int stopCode)
{
_stop = true;
_stopCode = stopCode;
shared_ptr<Debugger> debugger = _debugger;
if(debugger) {
debugger->Suspend();
}
_stopLock.Acquire();
_stopLock.Release();
}
void Console::Pause()
{
shared_ptr<Debugger> debugger = _debugger;
if(debugger) {
//Make sure debugger resumes if we try to pause the emu, otherwise we will get deadlocked.
debugger->Suspend();
}
if(_master) {
//When trying to pause/resume the slave, we need to pause/resume the master instead
_master->Pause();
} else {
_pauseCounter++;
_runLock.Acquire();
}
}
void Console::Resume()
{
if(_master) {
//When trying to pause/resume the slave, we need to pause/resume the master instead
_master->Resume();
} else {
_runLock.Release();
_pauseCounter--;
}
shared_ptr<Debugger> debugger = _debugger;
if(debugger) {
//Make sure debugger resumes if we try to pause the emu, otherwise we will get deadlocked.
debugger->Resume();
}
}
void Console::RunSingleFrame()
{
//Used by Libretro
uint32_t lastFrameNumber = _ppu->GetFrameCount();
_emulationThreadId = std::this_thread::get_id();
UpdateNesModel(true);
while(_ppu->GetFrameCount() == lastFrameNumber) {
_cpu->Exec();
if(_slave) {
RunSlaveCpu();
}
}
_settings->DisableOverclocking(_disableOcNextFrame || IsNsf());
_disableOcNextFrame = false;
_systemActionManager->ProcessSystemActions();
_apu->EndFrame();
}
void Console::RunSlaveCpu()
{
int64_t cycleGap;
while(true) {
//Run the slave until it catches up to the master CPU (and take into account the CPU count overflow that occurs every ~20mins)
cycleGap = (int64_t)(_cpu->GetCycleCount() - _slave->_cpu->GetCycleCount());
if(cycleGap > 5 || _ppu->GetFrameCount() > _slave->_ppu->GetFrameCount()) {
_slave->_cpu->Exec();
} else {
break;
}
}
}
void Console::RunFrame()
{
uint32_t frameCount = _ppu->GetFrameCount();
while(_ppu->GetFrameCount() == frameCount) {
_cpu->Exec();
if(_slave) {
RunSlaveCpu();
}
}
}
void Console::Run()
{
Timer clockTimer;
Timer lastFrameTimer;
double frameDurations[60] = {};
uint32_t frameDurationIndex = 0;
double targetTime;
double lastFrameMin = 9999;
double lastFrameMax = 0;
double lastDelay = GetFrameDelay();
_runLock.Acquire();
_stopLock.Acquire();
_emulationThreadId = std::this_thread::get_id();
if(_slave) {
_slave->_emulationThreadId = std::this_thread::get_id();
}
targetTime = lastDelay;
_videoDecoder->StartThread();
PlatformUtilities::DisableScreensaver();
UpdateNesModel(true);
_running = true;
bool crashed = false;
try {
while(true) {
stringstream runAheadState;
bool useRunAhead = _settings->GetRunAheadFrames() > 0 && !_debugger && !IsNsf() && !_rewindManager->IsRewinding() && _settings->GetEmulationSpeed() > 0 && _settings->GetEmulationSpeed() <= 100;
if(useRunAhead) {
RunFrameWithRunAhead(runAheadState);
} else {
RunFrame();
}
_soundMixer->ProcessEndOfFrame();
if(_slave) {
_slave->_soundMixer->ProcessEndOfFrame();
}
if(_historyViewer) {
_historyViewer->ProcessEndOfFrame();
}
_rewindManager->ProcessEndOfFrame();
_settings->DisableOverclocking(_disableOcNextFrame || IsNsf());
_disableOcNextFrame = false;
//Update model (ntsc/pal) and get delay for next frame
UpdateNesModel(true);
double delay = GetFrameDelay();
if(_resetRunTimers || delay != lastDelay || (clockTimer.GetElapsedMS() - targetTime) > 300) {
//Reset the timers, this can happen in 3 scenarios:
//1) Target frame rate changed
//2) The console was reset/power cycled or the emulation was paused (with or without the debugger)
//3) As a satefy net, if we overshoot our target by over 300 milliseconds, the timer is reset, too.
// This can happen when something slows the emulator down severely (or when breaking execution in VS when debugging Mesen itself, etc.)
clockTimer.Reset();
targetTime = 0;
_resetRunTimers = false;
lastDelay = delay;
}
targetTime += delay;
bool displayDebugInfo = _settings->CheckFlag(EmulationFlags::DisplayDebugInfo);
if(displayDebugInfo) {
double lastFrameTime = lastFrameTimer.GetElapsedMS();
lastFrameTimer.Reset();
frameDurations[frameDurationIndex] = lastFrameTime;
frameDurationIndex = (frameDurationIndex + 1) % 60;
DisplayDebugInformation(lastFrameTime, lastFrameMin, lastFrameMax, frameDurations);
if(_slave) {
_slave->DisplayDebugInformation(lastFrameTime, lastFrameMin, lastFrameMax, frameDurations);
}
}
//When sleeping for a long time (e.g <= 25% speed), sleep in small chunks and check to see if we need to stop sleeping between each sleep call
while(targetTime - clockTimer.GetElapsedMS() > 50) {
clockTimer.WaitUntil(clockTimer.GetElapsedMS() + 40);
if(delay != GetFrameDelay() || _stop || _settings->NeedsPause() || _pauseCounter > 0) {
targetTime = 0;
break;
}
}
//Sleep until we're ready to start the next frame
clockTimer.WaitUntil(targetTime);
if(useRunAhead) {
_settings->SetRunAheadFrameFlag(true);
LoadState(runAheadState);
_settings->SetRunAheadFrameFlag(false);
}
if(_pauseCounter > 0) {
//Need to temporarely pause the emu (to save/load a state, etc.)
_runLock.Release();
//Spin wait until we are allowed to start again
while(_pauseCounter > 0) { }
_runLock.Acquire();
}
if(_pauseOnNextFrameRequested) {
//Used by "Run Single Frame" option
_settings->SetFlags(EmulationFlags::Paused);
_pauseOnNextFrameRequested = false;
}
bool pausedRequired = _settings->NeedsPause();
if(pausedRequired && !_stop && !_settings->CheckFlag(EmulationFlags::DebuggerWindowEnabled)) {
_notificationManager->SendNotification(ConsoleNotificationType::GamePaused);
//Prevent audio from looping endlessly while game is paused
_soundMixer->StopAudio();
if(_slave) {
_slave->_soundMixer->StopAudio();
}
_runLock.Release();
PlatformUtilities::EnableScreensaver();
PlatformUtilities::RestoreTimerResolution();
while(pausedRequired && !_stop && !_settings->CheckFlag(EmulationFlags::DebuggerWindowEnabled)) {
//Sleep until emulation is resumed
std::this_thread::sleep_for(std::chrono::duration<int, std::milli>(30));
pausedRequired = _settings->NeedsPause();
_paused = true;
}
_paused = false;
PlatformUtilities::DisableScreensaver();
_runLock.Acquire();
_notificationManager->SendNotification(ConsoleNotificationType::GameResumed);
lastFrameTimer.Reset();
//Reset the timer to avoid speed up after a pause
_resetRunTimers = true;
}
if(_settings->CheckFlag(EmulationFlags::UseHighResolutionTimer)) {
PlatformUtilities::EnableHighResolutionTimer();
} else {
PlatformUtilities::RestoreTimerResolution();
}
_systemActionManager->ProcessSystemActions();
if(_stop) {
_stop = false;
break;
}
}
} catch(const std::runtime_error &ex) {
crashed = true;
_stopCode = -1;
MessageManager::DisplayMessage("Error", "GameCrash", ex.what());
}
_paused = false;
_running = false;
_notificationManager->SendNotification(ConsoleNotificationType::BeforeEmulationStop);
if(!crashed) {
_saveStateManager->SaveRecentGame(GetRomInfo().RomName, _romFilepath, _patchFilename);
}
_videoDecoder->StopThread();
StopRecordingHdPack();
_soundMixer->StopAudio();
MovieManager::Stop();
_soundMixer->StopRecording();
PlatformUtilities::EnableScreensaver();
PlatformUtilities::RestoreTimerResolution();
_settings->ClearFlags(EmulationFlags::ForceMaxSpeed);
_initialized = false;
if(!_romFilepath.empty() && _mapper) {
//Ensure we save any battery file before unloading anything
SaveBatteries();
}
_romFilepath = "";
Release(false);
_stopLock.Release();
_runLock.Release();
_emulationThreadId = std::thread::id();
_notificationManager->SendNotification(ConsoleNotificationType::GameStopped);
_notificationManager->SendNotification(ConsoleNotificationType::EmulationStopped);
}
void Console::RunFrameWithRunAhead(std::stringstream& runAheadState)
{
uint32_t runAheadFrames = _settings->GetRunAheadFrames();
_settings->SetRunAheadFrameFlag(true);
//Run a single frame and save the state (no audio/video)
RunFrame();
SaveState(runAheadState);
while(runAheadFrames > 1) {
//Run extra frames if the requested run ahead frame count is higher than 1
runAheadFrames--;
RunFrame();
}
_apu->EndFrame();
_settings->SetRunAheadFrameFlag(false);
//Run one frame normally (with audio/video output)
RunFrame();
_apu->EndFrame();
}
void Console::ResetRunTimers()
{
_resetRunTimers = true;
}
bool Console::IsRunning()
{
if(_master) {
//For slave CPU, return the master's state
return _master->IsRunning();
} else {
return !_stopLock.IsFree() && _running;
}
}
bool Console::IsExecutionStopped()
{
if(_master) {
//For slave CPU, return the master's state
return _master->IsPaused();
} else {
return _runLock.IsFree() || (!_runLock.IsFree() && _pauseCounter > 0) || !_running;
}
}
bool Console::IsPaused()
{