forked from dolphin-emu/dolphin
/
State.cpp
835 lines (707 loc) · 24.8 KB
/
State.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
// Copyright 2008 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "Core/State.h"
#include <atomic>
#include <condition_variable>
#include <filesystem>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include <fmt/format.h>
#include <lz4.h>
#include "Common/ChunkFile.h"
#include "Common/CommonTypes.h"
#include "Common/Event.h"
#include "Common/FileUtil.h"
#include "Common/IOFile.h"
#include "Common/MsgHandler.h"
#include "Common/Thread.h"
#include "Common/Timer.h"
#include "Common/Version.h"
#include "Common/WorkQueueThread.h"
#include "Core/ConfigManager.h"
#include "Core/Core.h"
#include "Core/CoreTiming.h"
#include "Core/GeckoCode.h"
#include "Core/HW/HW.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/Wiimote.h"
#include "Core/Host.h"
#include "Core/Movie.h"
#include "Core/NetPlayClient.h"
#include "Core/PowerPC/PowerPC.h"
#include "Core/System.h"
#include "VideoCommon/FrameDumpFFMpeg.h"
#include "VideoCommon/OnScreenDisplay.h"
#include "VideoCommon/VideoBackendBase.h"
namespace State
{
static AfterLoadCallbackFunc s_on_after_load_callback;
// Temporary undo state buffer
static std::vector<u8> s_undo_load_buffer;
static std::mutex s_undo_load_buffer_mutex;
static std::mutex s_load_or_save_in_progress_mutex;
struct CompressAndDumpState_args
{
std::vector<u8> buffer_vector;
std::string filename;
std::shared_ptr<Common::Event> state_write_done_event;
};
// Protects against simultaneous reads and writes to the final savestate location from multiple
// threads.
static std::mutex s_save_thread_mutex;
// Queue for compressing and writing savestates to disk.
static Common::WorkQueueThread<CompressAndDumpState_args> s_save_thread;
// Keeps track of savestate writes that are currently happening, so we don't load a state while
// another one is still saving. This is particularly important so if you save to a slot and then
// immediately load from the same one, you don't accidentally load the state that's still at that
// file path before the write is done.
static std::mutex s_state_writes_in_queue_mutex;
static size_t s_state_writes_in_queue;
static std::condition_variable s_state_write_queue_is_empty;
// Don't forget to increase this after doing changes on the savestate system
constexpr u32 STATE_VERSION = 163; // Last changed in PR 12217
// Maps savestate versions to Dolphin versions.
// Versions after 42 don't need to be added to this list,
// because they save the exact Dolphin version to savestates.
static const std::map<u32, std::pair<std::string, std::string>> s_old_versions = {
// The 16 -> 17 change modified the size of StateHeader,
// so versions older than that can't even be decompressed anymore
{17, {"3.5-1311", "3.5-1364"}}, {18, {"3.5-1366", "3.5-1371"}}, {19, {"3.5-1372", "3.5-1408"}},
{20, {"3.5-1409", "4.0-704"}}, {21, {"4.0-705", "4.0-889"}}, {22, {"4.0-905", "4.0-1871"}},
{23, {"4.0-1873", "4.0-1900"}}, {24, {"4.0-1902", "4.0-1919"}}, {25, {"4.0-1921", "4.0-1936"}},
{26, {"4.0-1939", "4.0-1959"}}, {27, {"4.0-1961", "4.0-2018"}}, {28, {"4.0-2020", "4.0-2291"}},
{29, {"4.0-2293", "4.0-2360"}}, {30, {"4.0-2362", "4.0-2628"}}, {31, {"4.0-2632", "4.0-3331"}},
{32, {"4.0-3334", "4.0-3340"}}, {33, {"4.0-3342", "4.0-3373"}}, {34, {"4.0-3376", "4.0-3402"}},
{35, {"4.0-3409", "4.0-3603"}}, {36, {"4.0-3610", "4.0-4480"}}, {37, {"4.0-4484", "4.0-4943"}},
{38, {"4.0-4963", "4.0-5267"}}, {39, {"4.0-5279", "4.0-5525"}}, {40, {"4.0-5531", "4.0-5809"}},
{41, {"4.0-5811", "4.0-5923"}}, {42, {"4.0-5925", "4.0-5946"}}};
enum
{
STATE_NONE = 0,
STATE_SAVE = 1,
STATE_LOAD = 2,
};
static bool s_use_compression = true;
void EnableCompression(bool compression)
{
s_use_compression = compression;
}
// Returns true if state version matches current Dolphin state version, false otherwise.
static bool DoStateVersion(PointerWrap& p, std::string* version_created_by)
{
u32 version = STATE_VERSION;
{
static const u32 COOKIE_BASE = 0xBAADBABE;
u32 cookie = version + COOKIE_BASE;
p.Do(cookie);
version = cookie - COOKIE_BASE;
}
*version_created_by = Common::GetScmRevStr();
if (version > 42)
p.Do(*version_created_by);
else
version_created_by->clear();
if (version != STATE_VERSION)
{
if (version_created_by->empty() && s_old_versions.count(version))
{
// The savestate is from an old version that doesn't
// save the Dolphin version number to savestates, but
// by looking up the savestate version number, it is possible
// to know approximately which Dolphin version was used.
std::pair<std::string, std::string> version_range = s_old_versions.find(version)->second;
std::string oldest_version = version_range.first;
std::string newest_version = version_range.second;
*version_created_by = "Dolphin " + oldest_version + " - " + newest_version;
}
return false;
}
p.DoMarker("Version");
return true;
}
static void DoState(PointerWrap& p)
{
std::string version_created_by;
if (!DoStateVersion(p, &version_created_by))
{
const std::string message =
version_created_by.empty() ?
"This savestate was created using an incompatible version of Dolphin" :
"This savestate was created using the incompatible version " + version_created_by;
Core::DisplayMessage(message, OSD::Duration::NORMAL);
p.SetMeasureMode();
return;
}
bool is_wii = SConfig::GetInstance().bWii || SConfig::GetInstance().m_is_mios;
const bool is_wii_currently = is_wii;
p.Do(is_wii);
if (is_wii != is_wii_currently)
{
OSD::AddMessage(fmt::format("Cannot load a savestate created under {} mode in {} mode",
is_wii ? "Wii" : "GC", is_wii_currently ? "Wii" : "GC"),
OSD::Duration::NORMAL, OSD::Color::RED);
p.SetMeasureMode();
return;
}
// Check to make sure the emulated memory sizes are the same as the savestate
auto& system = Core::System::GetInstance();
auto& memory = system.GetMemory();
u32 state_mem1_size = memory.GetRamSizeReal();
u32 state_mem2_size = memory.GetExRamSizeReal();
p.Do(state_mem1_size);
p.Do(state_mem2_size);
if (state_mem1_size != memory.GetRamSizeReal() || state_mem2_size != memory.GetExRamSizeReal())
{
OSD::AddMessage(fmt::format("Memory size mismatch!\n"
"Current | MEM1 {:08X} ({:3}MB) MEM2 {:08X} ({:3}MB)\n"
"State | MEM1 {:08X} ({:3}MB) MEM2 {:08X} ({:3}MB)",
memory.GetRamSizeReal(), memory.GetRamSizeReal() / 0x100000U,
memory.GetExRamSizeReal(), memory.GetExRamSizeReal() / 0x100000U,
state_mem1_size, state_mem1_size / 0x100000U, state_mem2_size,
state_mem2_size / 0x100000U));
p.SetMeasureMode();
return;
}
// Movie must be done before the video backend, because the window is redrawn in the video backend
// state load, and the frame number must be up-to-date.
Movie::DoState(p);
p.DoMarker("Movie");
// Begin with video backend, so that it gets a chance to clear its caches and writeback modified
// things to RAM
g_video_backend->DoState(p);
p.DoMarker("video_backend");
// CoreTiming needs to be restored before restoring Hardware because
// the controller code might need to schedule an event if the controller has changed.
system.GetCoreTiming().DoState(p);
p.DoMarker("CoreTiming");
// HW needs to be restored before PowerPC because the data cache might need to be flushed.
HW::DoState(system, p);
p.DoMarker("HW");
system.GetPowerPC().DoState(p);
p.DoMarker("PowerPC");
if (SConfig::GetInstance().bWii)
Wiimote::DoState(p);
p.DoMarker("Wiimote");
Gecko::DoState(p);
p.DoMarker("Gecko");
}
void LoadFromBuffer(std::vector<u8>& buffer)
{
if (NetPlay::IsNetPlayRunning())
{
OSD::AddMessage("Loading savestates is disabled in Netplay to prevent desyncs");
return;
}
Core::RunOnCPUThread(
[&] {
u8* ptr = buffer.data();
PointerWrap p(&ptr, buffer.size(), PointerWrap::Mode::Read);
DoState(p);
},
true);
}
void SaveToBuffer(std::vector<u8>& buffer)
{
Core::RunOnCPUThread(
[&] {
u8* ptr = nullptr;
PointerWrap p_measure(&ptr, 0, PointerWrap::Mode::Measure);
DoState(p_measure);
const size_t buffer_size = reinterpret_cast<size_t>(ptr);
buffer.resize(buffer_size);
ptr = buffer.data();
PointerWrap p(&ptr, buffer_size, PointerWrap::Mode::Write);
DoState(p);
},
true);
}
// return state number not in map
static int GetEmptySlot(std::map<double, int> m)
{
for (int i = 1; i <= (int)NUM_STATES; i++)
{
bool found = false;
for (auto& p : m)
{
if (p.second == i)
{
found = true;
break;
}
}
if (!found)
return i;
}
return -1;
}
// Arbitrarily chosen value (38 years) that is subtracted in GetSystemTimeAsDouble()
// to increase sub-second precision of the resulting double timestamp
static constexpr int DOUBLE_TIME_OFFSET = (38 * 365 * 24 * 60 * 60);
static double GetSystemTimeAsDouble()
{
const auto since_epoch = std::chrono::system_clock::now().time_since_epoch();
const auto since_double_time_epoch = since_epoch - std::chrono::seconds(DOUBLE_TIME_OFFSET);
return std::chrono::duration_cast<std::chrono::duration<double>>(since_double_time_epoch).count();
}
static std::string SystemTimeAsDoubleToString(double time)
{
// revert adjustments from GetSystemTimeAsDouble() to get a normal Unix timestamp again
time_t seconds = (time_t)time + DOUBLE_TIME_OFFSET;
tm* localTime = localtime(&seconds);
#ifdef _WIN32
wchar_t tmp[32] = {};
wcsftime(tmp, std::size(tmp), L"%x %X", localTime);
return WStringToUTF8(tmp);
#else
char tmp[32] = {};
strftime(tmp, sizeof(tmp), "%x %X", localTime);
return tmp;
#endif
}
static std::string MakeStateFilename(int number);
// read state timestamps
static std::map<double, int> GetSavedStates()
{
StateHeader header;
std::map<double, int> m;
for (int i = 1; i <= (int)NUM_STATES; i++)
{
std::string filename = MakeStateFilename(i);
if (File::Exists(filename))
{
if (ReadHeader(filename, header))
{
double d = GetSystemTimeAsDouble() - header.time;
// increase time until unique value is obtained
while (m.find(d) != m.end())
d += .001;
m.emplace(d, i);
}
}
}
return m;
}
static int CompressBufferToFile(const u8* raw_buffer, u32 max_bytes_to_compress, File::IOFile& f)
{
int bytes_to_compress =
static_cast<int>(std::min((u32)LZ4_MAX_INPUT_SIZE, max_bytes_to_compress));
int compressed_buffer_size = LZ4_compressBound(bytes_to_compress);
auto compressed_buffer = std::make_unique<char[]>(compressed_buffer_size);
int compressed_len = LZ4_compress_default((char*)raw_buffer, compressed_buffer.get(),
bytes_to_compress, compressed_buffer_size);
if (compressed_len == 0)
PanicAlertFmtT("Internal LZ4 Error - compression failed");
// The size of the data to write is 'compressed_len'
f.WriteArray(&compressed_len, 1);
f.WriteBytes(compressed_buffer.get(), compressed_len);
return bytes_to_compress;
}
static void CompressAndDumpState(CompressAndDumpState_args& save_args)
{
const u8* const buffer_data = save_args.buffer_vector.data();
const size_t buffer_size = save_args.buffer_vector.size();
const std::string& filename = save_args.filename;
// Find free temporary filename.
// TODO: The file exists check and the actual opening of the file should be atomic, we don't have
// functions for that.
std::string temp_filename;
size_t temp_counter = static_cast<size_t>(Common::CurrentThreadId());
do
{
temp_filename = fmt::format("{}{}.tmp", filename, temp_counter);
++temp_counter;
} while (File::Exists(temp_filename));
File::IOFile f(temp_filename, "wb");
if (!f)
{
Core::DisplayMessage("Could not save state", 2000);
return;
}
// Setting up the header
StateHeader header{};
SConfig::GetInstance().GetGameID().copy(header.gameID, std::size(header.gameID));
header.size = s_use_compression ? (u32)buffer_size : 0;
header.time = GetSystemTimeAsDouble();
f.WriteArray(&header, 1);
if (header.size != 0) // non-zero header size means the state is compressed
{
u32 total_bytes_compressed = 0;
while (true)
{
int bytes_compressed = CompressBufferToFile(buffer_data + total_bytes_compressed,
header.size - total_bytes_compressed, f);
total_bytes_compressed += bytes_compressed;
if (total_bytes_compressed == header.size)
break;
}
}
else // uncompressed
{
f.WriteBytes(buffer_data, buffer_size);
}
const std::string last_state_filename = File::GetUserPath(D_STATESAVES_IDX) + "lastState.sav";
const std::string last_state_dtmname = last_state_filename + ".dtm";
const std::string dtmname = filename + ".dtm";
{
std::lock_guard lk(s_save_thread_mutex);
// Backup existing state (overwriting an existing backup, if any).
if (File::Exists(filename))
{
if (File::Exists(last_state_filename))
File::Delete((last_state_filename));
if (File::Exists(last_state_dtmname))
File::Delete((last_state_dtmname));
if (!File::Rename(filename, last_state_filename))
{
Core::DisplayMessage("Failed to move previous state to state undo backup", 1000);
}
else if (File::Exists(dtmname))
{
if (!File::Rename(dtmname, last_state_dtmname))
Core::DisplayMessage("Failed to move previous state's dtm to state undo backup", 1000);
}
}
if ((Movie::IsMovieActive()) && !Movie::IsJustStartingRecordingInputFromSaveState())
Movie::SaveRecording(dtmname);
else if (!Movie::IsMovieActive())
File::Delete(dtmname);
// Move written state to final location.
// TODO: This should also be atomic. This is possible on all systems, but needs a special
// implementation of IOFile on Windows.
f.Close();
File::Rename(temp_filename, filename);
}
std::filesystem::path tempfilename(filename);
Core::DisplayMessage(fmt::format("Saved State to {}", tempfilename.filename().string()), 2000);
Host_UpdateMainFrame();
}
void SaveAs(const std::string& filename, bool wait)
{
std::unique_lock lk(s_load_or_save_in_progress_mutex, std::try_to_lock);
if (!lk)
return;
Core::RunOnCPUThread(
[&] {
{
std::lock_guard lk_(s_state_writes_in_queue_mutex);
++s_state_writes_in_queue;
}
// Measure the size of the buffer.
u8* ptr = nullptr;
PointerWrap p_measure(&ptr, 0, PointerWrap::Mode::Measure);
DoState(p_measure);
const size_t buffer_size = reinterpret_cast<size_t>(ptr);
// Then actually do the write.
std::vector<u8> current_buffer;
current_buffer.resize(buffer_size);
ptr = current_buffer.data();
PointerWrap p(&ptr, buffer_size, PointerWrap::Mode::Write);
DoState(p);
if (p.IsWriteMode())
{
Core::DisplayMessage("Saving State...", 1000);
std::shared_ptr<Common::Event> sync_event;
CompressAndDumpState_args save_args;
save_args.buffer_vector = std::move(current_buffer);
save_args.filename = filename;
if (wait)
{
sync_event = std::make_shared<Common::Event>();
save_args.state_write_done_event = sync_event;
}
s_save_thread.EmplaceItem(std::move(save_args));
if (sync_event)
sync_event->Wait();
}
else
{
// someone aborted the save by changing the mode?
{
// Note: The worker thread takes care of this in the other branch.
std::lock_guard lk_(s_state_writes_in_queue_mutex);
if (--s_state_writes_in_queue == 0)
s_state_write_queue_is_empty.notify_all();
}
Core::DisplayMessage("Unable to save: Internal DoState Error", 4000);
}
},
true);
}
bool ReadHeader(const std::string& filename, StateHeader& header)
{
// ensure that the savestate write thread isn't moving around states while we do this
std::lock_guard lk(s_save_thread_mutex);
File::IOFile f(filename, "rb");
return f.ReadArray(&header, 1);
}
std::string GetInfoStringOfSlot(int slot, bool translate)
{
std::string filename = MakeStateFilename(slot);
if (!File::Exists(filename))
return translate ? Common::GetStringT("Empty") : "Empty";
State::StateHeader header;
if (!ReadHeader(filename, header))
return translate ? Common::GetStringT("Unknown") : "Unknown";
return SystemTimeAsDoubleToString(header.time);
}
u64 GetUnixTimeOfSlot(int slot)
{
State::StateHeader header;
if (!ReadHeader(MakeStateFilename(slot), header))
return 0;
constexpr u64 MS_PER_SEC = 1000;
return static_cast<u64>(header.time * MS_PER_SEC) + (DOUBLE_TIME_OFFSET * MS_PER_SEC);
}
static int DecompressBufferFromFile(const u8* raw_buffer, u32 max_bytes, File::IOFile& f)
{
u32 compressed_data_len;
f.ReadArray(&compressed_data_len, 1);
auto compressed_data = std::make_unique<char[]>(compressed_data_len);
f.ReadBytes(compressed_data.get(), compressed_data_len);
// We need to specify the output buffer's size for safety. This may exceed the positive bound
// of int, causing the buffer size to be interpreted as a negative value.
u32 max_decompress_size = std::min((u32)LZ4_MAX_INPUT_SIZE, max_bytes);
int bytes_read = LZ4_decompress_safe(compressed_data.get(), (char*)raw_buffer,
compressed_data_len, max_decompress_size);
if (bytes_read < 0)
{
PanicAlertFmtT("Internal LZ4 Error - decompression failed ({0}, {1}, {2}) \n"
"Try loading the state again",
bytes_read, compressed_data_len, max_decompress_size);
}
return bytes_read;
}
static void LoadFileStateData(const std::string& filename, std::vector<u8>& ret_data)
{
File::IOFile f;
{
// If a state is currently saving, wait for that to end or time out.
std::unique_lock lk(s_state_writes_in_queue_mutex);
if (s_state_writes_in_queue != 0)
{
if (!s_state_write_queue_is_empty.wait_for(lk, std::chrono::seconds(3),
[]() { return s_state_writes_in_queue == 0; }))
{
Core::DisplayMessage(
"A previous state saving operation is still in progress, cancelling load.", 2000);
return;
}
}
f.Open(filename, "rb");
}
StateHeader header;
if (!f.ReadArray(&header, 1))
{
Core::DisplayMessage("State not found", 2000);
return;
}
if (strncmp(SConfig::GetInstance().GetGameID().c_str(), header.gameID, 6))
{
Core::DisplayMessage(fmt::format("State belongs to a different game (ID {})",
std::string_view{header.gameID, std::size(header.gameID)}),
2000);
return;
}
std::vector<u8> buffer;
if (header.size != 0) // non-zero size means the state is compressed
{
Core::DisplayMessage("Decompressing State...", 500);
buffer.resize(header.size);
u32 total_bytes_read = 0;
while (true)
{
int bytes_read = DecompressBufferFromFile(buffer.data() + total_bytes_read,
header.size - total_bytes_read, f);
if (bytes_read < 0)
return;
total_bytes_read += bytes_read;
if (total_bytes_read == header.size)
break;
}
}
else // uncompressed
{
const auto size = static_cast<size_t>(f.GetSize() - sizeof(StateHeader));
buffer.resize(size);
if (!f.ReadBytes(&buffer[0], size))
{
PanicAlertFmt("Error reading bytes: {0}", size);
return;
}
}
// all good
ret_data.swap(buffer);
}
void LoadAs(const std::string& filename)
{
if (!Core::IsRunning())
return;
if (NetPlay::IsNetPlayRunning())
{
OSD::AddMessage("Loading savestates is disabled in Netplay to prevent desyncs");
return;
}
std::unique_lock lk(s_load_or_save_in_progress_mutex, std::try_to_lock);
if (!lk)
return;
Core::RunOnCPUThread(
[&] {
// Save temp buffer for undo load state
if (!Movie::IsJustStartingRecordingInputFromSaveState())
{
std::lock_guard lk2(s_undo_load_buffer_mutex);
SaveToBuffer(s_undo_load_buffer);
const std::string dtmpath = File::GetUserPath(D_STATESAVES_IDX) + "undo.dtm";
if (Movie::IsMovieActive())
Movie::SaveRecording(dtmpath);
else if (File::Exists(dtmpath))
File::Delete(dtmpath);
}
bool loaded = false;
bool loadedSuccessfully = false;
// brackets here are so buffer gets freed ASAP
{
std::vector<u8> buffer;
LoadFileStateData(filename, buffer);
if (!buffer.empty())
{
u8* ptr = buffer.data();
PointerWrap p(&ptr, buffer.size(), PointerWrap::Mode::Read);
DoState(p);
loaded = true;
loadedSuccessfully = p.IsReadMode();
}
}
if (loaded)
{
if (loadedSuccessfully)
{
std::filesystem::path tempfilename(filename);
Core::DisplayMessage(
fmt::format("Loaded State from {}", tempfilename.filename().string()), 2000);
if (File::Exists(filename + ".dtm"))
Movie::LoadInput(filename + ".dtm");
else if (!Movie::IsJustStartingRecordingInputFromSaveState() &&
!Movie::IsJustStartingPlayingInputFromSaveState())
Movie::EndPlayInput(false);
}
else
{
Core::DisplayMessage("The savestate could not be loaded", OSD::Duration::NORMAL);
// since we could be in an inconsistent state now (and might crash or whatever), undo.
UndoLoadState();
}
}
if (s_on_after_load_callback)
s_on_after_load_callback();
},
true);
}
void SetOnAfterLoadCallback(AfterLoadCallbackFunc callback)
{
s_on_after_load_callback = std::move(callback);
}
void Init()
{
s_save_thread.Reset("Savestate Worker", [](CompressAndDumpState_args args) {
CompressAndDumpState(args);
{
std::lock_guard lk(s_state_writes_in_queue_mutex);
if (--s_state_writes_in_queue == 0)
s_state_write_queue_is_empty.notify_all();
}
if (args.state_write_done_event)
args.state_write_done_event->Set();
});
}
void Shutdown()
{
s_save_thread.Shutdown();
// swapping with an empty vector, rather than clear()ing
// this gives a better guarantee to free the allocated memory right NOW (as opposed to, actually,
// never)
{
std::lock_guard lk(s_undo_load_buffer_mutex);
std::vector<u8>().swap(s_undo_load_buffer);
}
}
static std::string MakeStateFilename(int number)
{
return fmt::format("{}{}.s{:02d}", File::GetUserPath(D_STATESAVES_IDX),
SConfig::GetInstance().GetGameID(), number);
}
void Save(int slot, bool wait)
{
SaveAs(MakeStateFilename(slot), wait);
}
void Load(int slot)
{
LoadAs(MakeStateFilename(slot));
}
void LoadLastSaved(int i)
{
std::map<double, int> savedStates = GetSavedStates();
if (i > (int)savedStates.size())
Core::DisplayMessage("State doesn't exist", 2000);
else
{
std::map<double, int>::iterator it = savedStates.begin();
std::advance(it, i - 1);
Load(it->second);
}
}
// must wait for state to be written because it must know if all slots are taken
void SaveFirstSaved()
{
std::map<double, int> savedStates = GetSavedStates();
// save to an empty slot
if (savedStates.size() < NUM_STATES)
Save(GetEmptySlot(savedStates), true);
// overwrite the oldest state
else
{
std::map<double, int>::iterator it = savedStates.begin();
std::advance(it, savedStates.size() - 1);
Save(it->second, true);
}
}
// Load the last state before loading the state
void UndoLoadState()
{
std::lock_guard lk(s_undo_load_buffer_mutex);
if (!s_undo_load_buffer.empty())
{
if (Movie::IsMovieActive())
{
const std::string dtmpath = File::GetUserPath(D_STATESAVES_IDX) + "undo.dtm";
if (File::Exists(dtmpath))
{
LoadFromBuffer(s_undo_load_buffer);
Movie::LoadInput(dtmpath);
}
else
{
PanicAlertFmtT("No undo.dtm found, aborting undo load state to prevent movie desyncs");
}
}
else
{
LoadFromBuffer(s_undo_load_buffer);
}
}
else
{
PanicAlertFmtT("There is nothing to undo!");
}
}
// Load the state that the last save state overwritten on
void UndoSaveState()
{
LoadAs(File::GetUserPath(D_STATESAVES_IDX) + "lastState.sav");
}
} // namespace State