39static constexpr double SNAPSHOT_PERIOD = 1.0;
42static constexpr unsigned MAX_NOF_SNAPSHOTS = 10;
45static constexpr auto MIN_PARTITION_LENGTH = EmuDuration(60.0);
48static constexpr auto MAX_DIST_1_BEFORE_LAST_SNAPSHOT = EmuDuration(30.0);
73 template<
typename Archive>
76 if (ar.versionAtLeast(version, 2)) {
80 ar.serialize(
"snapshot", *newBoard);
84 ar.serialize(
"events", *
events);
86 if (ar.versionAtLeast(version, 3)) {
89 assert(Archive::IS_LOADER);
94 if (ar.versionAtLeast(version, 4)) {
104void ReverseManager::ReverseHistory::swap(ReverseHistory& other)
noexcept
106 std::swap(chunks, other.chunks);
107 std::swap(events, other.events);
110void ReverseManager::ReverseHistory::clear()
113 Chunks().swap(chunks);
114 Events().swap(events);
127 template<
typename Archive>
void serialize(Archive& ar,
unsigned )
129 ar.template serializeBase<StateChange>(*
this);
137 : syncNewSnapshot(motherBoard_.getScheduler())
138 , syncInputEvent (motherBoard_.getScheduler())
139 , motherBoard(motherBoard_)
140 , eventDistributor(motherBoard.getReactor().getEventDistributor())
141 , reverseCmd(motherBoard.getCommandController())
157 return replayIndex != history.events.size();
160void ReverseManager::start()
165 takeSnapshot(getCurrentTime());
167 schedule(getCurrentTime());
174void ReverseManager::stop()
178 syncNewSnapshot.removeSyncPoint();
179 syncInputEvent .removeSyncPoint();
183 pendingTakeSnapshot =
false;
185 assert(!pendingTakeSnapshot);
190EmuTime::param ReverseManager::getEndTime(
const ReverseHistory& hist)
const
192 if (!hist.events.empty()) {
193 if (
const auto* ev =
dynamic_cast<const EndLogEvent*
>(
194 hist.events.back().get())) {
196 return ev->getTime();
201 return getCurrentTime();
212 return (b - EmuTime::zero()).toDouble();
217 return (
end - EmuTime::zero()).toDouble();
221 EmuTime current(
isCollecting() ? getCurrentTime() : EmuTime::zero());
222 return (current - EmuTime::zero()).toDouble();
225void ReverseManager::status(
TclObject& result)
const
236 return (p.second.time - EmuTime::zero()).toDouble();
240 auto lastEvent = rbegin(history.events);
241 if (lastEvent != rend(history.events) &&
dynamic_cast<const EndLogEvent*
>(lastEvent->get())) {
244 EmuTime le(
isCollecting() && (lastEvent != rend(history.events)) ? (*lastEvent)->getTime() : EmuTime::zero());
245 result.
addDictKeyValue(
"last_event", (le - EmuTime::zero()).toDouble());
248void ReverseManager::debugInfo(TclObject& result)
const
253 size_t totalSize = 0;
254 for (
const auto& [idx, chunk] : history.chunks) {
256 (chunk.time - EmuTime::zero()).toDouble(),
' ',
257 ((chunk.time - EmuTime::zero()).toDouble() / (getCurrentTime() - EmuTime::zero()).toDouble()) * 100,
"%"
258 " (", chunk.savestate.size(),
")"
259 " (next event index: ", chunk.eventCount,
")\n");
260 totalSize += chunk.savestate.size();
262 strAppend(res,
"total size: ", totalSize,
'\n');
266static std::pair<bool, double> parseGoTo(Interpreter& interp, std::span<const TclObject> tokens)
268 bool noVideo =
false;
269 std::array info = {
flagArg(
"-novideo", noVideo)};
270 auto args =
parseTclArgs(interp, tokens.subspan(2), info);
271 if (args.size() != 1)
throw SyntaxError();
272 double time = args[0].getDouble(interp);
273 return {noVideo, time};
276void ReverseManager::goBack(std::span<const TclObject> tokens)
279 auto [noVideo,
t] = parseGoTo(interp, tokens);
281 EmuTime now = getCurrentTime();
282 EmuTime target(EmuTime::dummy());
285 if (d < (now - EmuTime::zero())) {
288 target = EmuTime::zero();
291 target = now + EmuDuration(-
t);
293 goTo(target, noVideo);
296void ReverseManager::goTo(std::span<const TclObject> tokens)
299 auto [noVideo,
t] = parseGoTo(interp, tokens);
301 EmuTime target = EmuTime::zero() + EmuDuration(
t);
302 goTo(target, noVideo);
305void ReverseManager::goTo(EmuTime::param target,
bool noVideo)
308 throw CommandException(
309 "Reverse was not enabled. First execute the 'reverse "
310 "start' command to start collecting data.");
312 goTo(target, noVideo, history,
true);
316static void reportProgress(Reactor& reactor,
const EmuTime& targetTime,
float fraction)
318 double targetTimeDisp = (targetTime - EmuTime::zero()).toDouble();
319 std::ostringstream sstr;
320 sstr <<
"Time warping to " <<
321 int(targetTimeDisp / 60) <<
':' << std::setfill(
'0') <<
322 std::setw(5) << std::setprecision(2) << std::fixed <<
323 std::fmod(targetTimeDisp, 60.0);
324 reactor.getCliComm().printProgress(sstr.str(), fraction);
325 reactor.getDisplay().repaint();
328void ReverseManager::goTo(
329 EmuTime::param target,
bool noVideo, ReverseHistory& hist,
345 assert(!hist.chunks.empty());
346 auto it =
begin(hist.chunks);
347 EmuTime firstTime = it->second.time;
348 EmuTime targetTime = std::max(target, firstTime);
350 targetTime = std::min(targetTime, getEndTime(hist));
357 static constexpr double dur2frames = 2.0 * (313.0 * 1368.0) / (3579545.0 * 6.0);
358 EmuDuration preDelta(noVideo ? 0.0 : dur2frames);
359 EmuTime preTarget = ((targetTime - firstTime) > preDelta)
360 ? targetTime - preDelta
365 assert(it->second.time <= preTarget);
366 assert(it !=
end(hist.chunks));
369 }
while (it !=
end(hist.chunks) &&
370 it->second.time <= preTarget);
373 assert(it !=
begin(hist.chunks));
375 ReverseChunk& chunk = it->second;
376 EmuTime snapshotTime = chunk.time;
377 assert(snapshotTime <= preTarget);
388 EmuTime currentTime = getCurrentTime();
389 MSXMotherBoard* newBoard;
392 (currentTime <= preTarget) &&
393 ((snapshotTime <= currentTime) ||
394 ((preTarget - currentTime) < EmuDuration(1.0)))) {
395 newBoard = &motherBoard;
402 newBoard_ = reactor.createEmptyMotherBoard();
403 newBoard = newBoard_.get();
406 newBoard->getMSXCliComm().setSuppressMessages(
true);
407 MemInputArchive in(chunk.savestate,
409 in.serialize(
"machine", *newBoard);
419 if (hist.events.empty() ||
420 !
dynamic_cast<const EndLogEvent*
>(hist.events.back().get())) {
421 hist.events.push_back(
422 std::make_unique<EndLogEvent>(currentTime));
428 auto& newManager = newBoard->getReverseManager();
429 newManager.transferHistory(hist, chunk.eventCount);
432 transferState(*newBoard);
446 auto startMSXTime = newBoard->getCurrentTime();
447 auto lastSnapshotTarget = startMSXTime;
448 bool everShowedProgress =
false;
449 syncNewSnapshot.removeSyncPoint();
451 auto currentTimeNewBoard = newBoard->getCurrentTime();
452 auto nextSnapshotTarget = std::min(
454 lastSnapshotTarget + std::max(
455 EmuDuration(SNAPSHOT_PERIOD),
456 (preTarget - lastSnapshotTarget) / 2
458 auto nextTarget = std::min(nextSnapshotTarget, currentTimeNewBoard +
EmuDuration::sec(1));
459 newBoard->fastForward(nextTarget,
true);
461 ((now - lastProgress) > 1000000) || ((currentTimeNewBoard >= preTarget) && everShowedProgress)) {
462 everShowedProgress =
true;
464 auto fraction = (currentTimeNewBoard - startMSXTime).toDouble() / (preTarget - startMSXTime).toDouble();
465 reportProgress(newBoard->getReactor(), targetTime,
float(fraction));
469 if (currentTimeNewBoard >= preTarget)
break;
470 if (currentTimeNewBoard >= nextSnapshotTarget) {
477 newBoard->getReverseManager().takeSnapshot(currentTimeNewBoard);
478 lastSnapshotTarget = nextSnapshotTarget;
482 newBoard->getMSXCliComm().setSuppressMessages(
false);
484 schedule(getCurrentTime());
492 reactor.replaceBoard(motherBoard, std::move(newBoard_));
497 newBoard->fastForward(targetTime,
false);
506 assert(newBoard->getReverseManager().isCollecting());
507 }
catch (MSXException&) {
514void ReverseManager::transferState(MSXMotherBoard& newBoard)
518 auto& newDistributor = newBoard .getStateChangeDistributor();
522 auto& newManager = newBoard.getReverseManager();
523 if (
auto* newKeyb = newManager.motherBoard.getKeyboard()) {
524 if (
const auto* oldKeyb = motherBoard.
getKeyboard()) {
525 newKeyb->transferHostKeyMatrix(*oldKeyb);
530 newBoard.getDebugger().transfer(motherBoard.
getDebugger());
533 newManager.reRecordCount = reRecordCount;
540void ReverseManager::saveReplay(
541 Interpreter& interp, std::span<const TclObject> tokens, TclObject& result)
543 const auto& chunks = history.chunks;
544 if (chunks.empty()) {
545 throw CommandException(
"No recording...");
548 std::string_view filenameArg;
549 int maxNofExtraSnapshots = MAX_NOF_SNAPSHOTS;
550 std::array info = {
valueArg(
"-maxnofextrasnapshots", maxNofExtraSnapshots)};
551 auto args =
parseTclArgs(interp, tokens.subspan(2), info);
552 switch (args.size()) {
554 case 1: filenameArg = args[0].getString();
break;
555 default:
throw SyntaxError();
557 if (maxNofExtraSnapshots < 0) {
558 throw CommandException(
"Maximum number of snapshots should be at least 0");
566 replay.reRecordCount = reRecordCount;
570 replay.currentTime = getCurrentTime();
573 auto initialBoard = reactor.createEmptyMotherBoard();
574 MemInputArchive in(
begin(chunks)->second.savestate,
575 begin(chunks)->second.deltaBlocks);
576 in.serialize(
"machine", *initialBoard);
577 replay.motherBoards.push_back(std::move(initialBoard));
579 if (maxNofExtraSnapshots > 0) {
581 const auto& startTime =
begin(chunks)->second.time;
586 const auto& lastChunkTime = rbegin(chunks)->second.time;
587 const auto& endTime = ((startTime + MAX_DIST_1_BEFORE_LAST_SNAPSHOT) < lastChunkTime) ? lastChunkTime - MAX_DIST_1_BEFORE_LAST_SNAPSHOT : lastChunkTime;
588 EmuDuration totalLength = endTime - startTime;
589 EmuDuration partitionLength = totalLength.divRoundUp(maxNofExtraSnapshots);
590 partitionLength = std::max(MIN_PARTITION_LENGTH, partitionLength);
591 EmuTime nextPartitionEnd = startTime + partitionLength;
592 auto it =
begin(chunks);
593 auto lastAddedIt =
begin(chunks);
594 while (it !=
end(chunks)) {
596 if (it ==
end(chunks) || (it->second.time > nextPartitionEnd)) {
598 assert(it->second.time <= nextPartitionEnd);
599 if (it != lastAddedIt) {
602 MemInputArchive in2(it->second.savestate,
603 it->second.deltaBlocks);
604 in2.serialize(
"machine", *board);
605 replay.motherBoards.push_back(std::move(board));
609 while (it !=
end(chunks) && it->second.time > nextPartitionEnd) {
610 nextPartitionEnd += partitionLength;
614 assert(lastAddedIt == std::prev(
end(chunks)));
618 bool addSentinel = history.events.empty() ||
619 !
dynamic_cast<EndLogEvent*
>(history.events.back().get());
622 history.events.push_back(std::make_unique<EndLogEvent>(
626 XmlOutputArchive out(filename);
627 replay.events = &history.events;
628 out.serialize(
"replay", replay);
630 }
catch (MSXException&) {
632 history.events.pop_back();
642 history.events.pop_back();
645 result =
tmpStrCat(
"Saved replay to ", filename);
648void ReverseManager::loadReplay(
649 Interpreter& interp, std::span<const TclObject> tokens, TclObject& result)
651 bool enableViewOnly =
false;
652 std::optional<TclObject> where;
654 flagArg(
"-viewonly", enableViewOnly),
657 auto arguments =
parseTclArgs(interp, tokens.subspan(2), info);
658 if (arguments.size() != 1)
throw SyntaxError();
662 std::string fileNameArg(arguments[0].getString());
663 std::string filename;
666 filename =
context.resolve(fileNameArg);
667 }
catch (MSXException& ) {
try {
670 }
catch (MSXException& e2) {
try {
674 }
catch (MSXException& ) {
683 replay.events = &events;
685 XmlInputArchive in(filename);
686 in.serialize(
"replay", replay);
687 }
catch (XMLException& e) {
688 throw CommandException(
"Cannot load replay, bad file format: ",
690 }
catch (MSXException& e) {
691 throw CommandException(
"Cannot load replay: ",
e.getMessage());
695 auto destination = EmuTime::zero();
696 if (!where || (*where ==
"begin")) {
697 destination = EmuTime::zero();
698 }
else if (*where ==
"end") {
699 destination = EmuTime::infinity();
700 }
else if (*where ==
"savetime") {
701 destination = replay.currentTime;
703 destination += EmuDuration(where->getDouble(interp));
711 assert(!replay.motherBoards.empty());
712 auto& newReverseManager = replay.motherBoards[0]->getReverseManager();
713 auto& newHistory = newReverseManager.history;
715 if (newReverseManager.reRecordCount == 0) {
717 newReverseManager.reRecordCount = replay.reRecordCount;
724 swap(newHistory.events, events);
725 auto& newEvents = newHistory.events;
728 unsigned replayIdx = 0;
729 for (
const auto& m : replay.motherBoards) {
730 ReverseChunk newChunk;
731 newChunk.time = m->getCurrentTime();
733 MemOutputArchive out(newHistory.lastDeltaBlocks,
734 newChunk.deltaBlocks,
false);
735 out.serialize(
"machine", *m);
736 newChunk.savestate = std::move(out).releaseBuffer();
740 while (replayIdx < newEvents.size() &&
741 (newEvents[replayIdx]->getTime() < newChunk.time)) {
744 newChunk.eventCount = replayIdx;
746 newHistory.chunks[newHistory.getNextSeqNum(newChunk.time)] =
752 reRecordCount = newReverseManager.reRecordCount;
753 bool noVideo =
false;
754 goTo(destination, noVideo, newHistory,
false);
756 result =
tmpStrCat(
"Loaded replay from ", filename);
759void ReverseManager::transferHistory(ReverseHistory& oldHistory,
760 unsigned oldEventCount)
763 assert(history.chunks.empty());
766 oldHistory.lastDeltaBlocks.clear();
769 history.swap(oldHistory);
773 schedule(getCurrentTime());
777 replayIndex = oldEventCount;
779 assert(replayIndex < history.events.size());
783void ReverseManager::execNewSnapshot()
811 pendingTakeSnapshot =
true;
815void ReverseManager::execInputEvent()
817 const auto&
event = *history.events[replayIndex];
821 }
catch (MSXException&) {
825 if (!
dynamic_cast<const EndLogEvent*
>(&event)) {
829 signalStopReplay(event.getTime());
834bool ReverseManager::signalEvent(
const Event& event)
841 if (pendingTakeSnapshot) {
842 pendingTakeSnapshot =
false;
843 takeSnapshot(getCurrentTime());
845 schedule(getCurrentTime());
850unsigned ReverseManager::ReverseHistory::getNextSeqNum(EmuTime::param time)
const
852 if (chunks.empty()) {
855 const auto& startTime =
begin(chunks)->second.time;
856 double duration = (time - startTime).toDouble();
857 return narrow<unsigned>(lrint(duration / SNAPSHOT_PERIOD));
860void ReverseManager::takeSnapshot(EmuTime::param time)
865 unsigned seqNum = history.getNextSeqNum(time);
866 dropOldSnapshots<25>(seqNum);
874 ReverseChunk& newChunk = history.chunks[seqNum];
875 newChunk.deltaBlocks.clear();
876 MemOutputArchive out(history.lastDeltaBlocks, newChunk.deltaBlocks,
true);
877 out.serialize(
"machine", motherBoard);
878 newChunk.time = time;
879 newChunk.savestate = std::move(out).releaseBuffer();
880 newChunk.eventCount = replayIndex;
883void ReverseManager::replayNextEvent()
886 assert(replayIndex < history.events.size());
887 syncInputEvent.setSyncPoint(history.events[replayIndex]->getTime());
890void ReverseManager::signalStopReplay(EmuTime::param time)
902 syncInputEvent.removeSyncPoint();
903 Events& events = history.events;
904 events.erase(
begin(events) + replayIndex,
end(events));
907 return p.second.time > time;
909 history.chunks.erase(it,
end(history.chunks));
913 assert(!isReplaying());
929void ReverseManager::dropOldSnapshots(
unsigned count)
931 unsigned y = (count + N) ^ (count + N + 1);
933 unsigned d2 = 2 * N + 1;
936 if ((y == 0) || (count < d))
return;
937 history.chunks.erase(count - d);
943void ReverseManager::schedule(EmuTime::param time)
945 syncNewSnapshot.setSyncPoint(time + EmuDuration(SNAPSHOT_PERIOD));
951ReverseManager::ReverseCmd::ReverseCmd(CommandController& controller)
952 : Command(controller,
"reverse")
956void ReverseManager::ReverseCmd::execute(std::span<const TclObject> tokens, TclObject& result)
958 checkNumArgs(tokens, AtLeast{2},
"subcommand ?arg ...?");
959 auto& manager =
OUTER(ReverseManager, reverseCmd);
960 auto& interp = getInterpreter();
961 executeSubCommand(tokens[1].getString(),
962 "start", [&]{ manager.start(); },
963 "stop", [&]{ manager.stop(); },
964 "status", [&]{ manager.status(result); },
965 "debug", [&]{ manager.debugInfo(result); },
966 "goback", [&]{ manager.goBack(tokens); },
967 "goto", [&]{ manager.goTo(tokens); },
968 "savereplay", [&]{ manager.saveReplay(interp, tokens, result); },
969 "loadreplay", [&]{ manager.loadReplay(interp, tokens, result); },
971 auto& distributor = manager.motherBoard.getStateChangeDistributor();
972 switch (tokens.size()) {
974 result = distributor.isViewOnlyMode();
977 distributor.setViewOnlyMode(tokens[2].getBoolean(interp));
982 "truncatereplay", [&] {
983 if (manager.isReplaying()) {
984 manager.signalStopReplay(manager.getCurrentTime());
988std::string ReverseManager::ReverseCmd::help(std::span<const TclObject> )
const
990 return "start start collecting reverse data\n"
991 "stop stop collecting\n"
992 "status show various status info on reverse\n"
993 "goback <n> go back <n> seconds in time\n"
994 "goto <time> go to an absolute moment in time\n"
995 "viewonlymode <bool> switch viewonly mode on or off\n"
996 "truncatereplay stop replaying and remove all 'future' data\n"
997 "savereplay [<name>] save the first snapshot and all replay data as a 'replay' (with optional name)\n"
998 "loadreplay [-goto <begin|end|savetime|<n>>] [-viewonly] <name> load a replay (snapshot and replay data) with given name and start replaying\n";
1001void ReverseManager::ReverseCmd::tabCompletion(std::vector<std::string>& tokens)
const
1003 using namespace std::literals;
1004 if (tokens.size() == 2) {
1005 static constexpr std::array subCommands = {
1006 "start"sv,
"stop"sv,
"status"sv,
"goback"sv,
"goto"sv,
1007 "savereplay"sv,
"loadreplay"sv,
"viewonlymode"sv,
1010 completeString(tokens, subCommands);
1011 }
else if ((tokens.size() == 3) || (tokens[1] ==
"loadreplay")) {
1012 if (tokens[1] ==
one_of(
"loadreplay",
"savereplay")) {
1013 static constexpr std::array cmds = {
"-goto"sv,
"-viewonly"sv};
1015 (tokens[1] ==
"loadreplay") ? cmds :
std::span<const
std::string_view>{});
1016 }
else if (tokens[1] ==
"viewonlymode") {
1017 static constexpr std::array options = {
"true"sv,
"false"sv};
1018 completeString(tokens, options);
static constexpr EmuDuration sec(unsigned x)
void serialize(Archive &ar, unsigned)
EndLogEvent(EmuTime::param time_)
void unregisterEventListener(EventType type, EventListener &listener)
Unregisters a previously registered event listener.
void distributeEvent(Event &&event)
Schedule the given event for delivery.
void registerEventListener(EventType type, EventListener &listener, Priority priority=Priority::OTHER)
Registers a given object to receive certain events.
void setSuppressMessages(bool enable)
void transferSettings(const MSXCommandController &from)
Transfer setting values from one machine to another, used for during 'reverse'.
void mute()
TODO This methods (un)mute the sound.
StateChangeDistributor & getStateChangeDistributor()
Keyboard * getKeyboard() const
MSXCliComm & getMSXCliComm()
MSXCommandController & getMSXCommandController()
Contains the main loop of openMSX.
std::shared_ptr< MSXMotherBoard > Board
Board createEmptyMotherBoard()
Interpreter & getInterpreter()
bool isCollecting() const
double getCurrent() const
void stopReplay(EmuTime::param time) noexcept
static constexpr std::string_view REPLAY_DIR
bool isViewOnlyMode() const
static constexpr std::string_view REPLAY_EXTENSION
ReverseManager(MSXMotherBoard &motherBoard)
void unregisterRecorder(ReverseManager &recorder)
void registerRecorder(ReverseManager &recorder)
(Un)registers the given object to receive state change events.
void distributeReplay(const StateChange &event) const
bool isViewOnlyMode() const
void setViewOnlyMode(bool value)
Set viewOnlyMode.
void stopReplay(EmuTime::param time)
Explicitly stop replay.
Base class for all external MSX state changing events.
void addListElements(ITER first, ITER last)
void addDictKeyValue(const Key &key, const Value &value)
std::optional< Context > context
string parseCommandFileArgument(string_view argument, string_view directory, string_view prefix, string_view extension)
Helper function for parsing filename arguments in Tcl commands.
uint64_t getTime()
Get current (real) time in us.
This file implemented 3 utility functions:
ArgsInfo valueArg(std::string_view name, T &value)
std::vector< TclObject > parseTclArgs(Interpreter &interp, std::span< const TclObject > inArgs, std::span< const ArgsInfo > table)
EventType getType(const Event &event)
std::variant< KeyUpEvent, KeyDownEvent, MouseMotionEvent, MouseButtonUpEvent, MouseButtonDownEvent, MouseWheelEvent, JoystickAxisMotionEvent, JoystickHatEvent, JoystickButtonUpEvent, JoystickButtonDownEvent, OsdControlReleaseEvent, OsdControlPressEvent, WindowEvent, TextEvent, FileDropEvent, QuitEvent, FinishFrameEvent, CliCommandEvent, GroupEvent, BootEvent, FrameDrawnEvent, BreakEvent, SwitchRendererEvent, TakeReverseSnapshotEvent, AfterTimedEvent, MachineLoadedEvent, MachineActivatedEvent, MachineDeactivatedEvent, MidiInReaderEvent, MidiInWindowsEvent, MidiInCoreMidiEvent, MidiInCoreMidiVirtualEvent, MidiInALSAEvent, Rs232TesterEvent, Rs232NetEvent, ImGuiDelayedActionEvent, ImGuiActiveEvent > Event
ArgsInfo flagArg(std::string_view name, bool &flag)
FileContext userDataFileContext(string_view subDir)
auto find_if(InputRange &&range, UnaryPredicate pred)
constexpr auto transform(Range &&range, UnaryOp op)
#define OUTER(type, member)
TemporaryString tmpStrCat(Ts &&... ts)
void strAppend(std::string &result, Ts &&...ts)
std::vector< Reactor::Board > motherBoards
void serialize(Archive &ar, unsigned version)
Replay(Reactor &reactor_)
ReverseManager::Events * events
constexpr auto begin(const zstring_view &x)
constexpr auto end(const zstring_view &x)