37static constexpr double SNAPSHOT_PERIOD = 1.0;
40static constexpr unsigned MAX_NOF_SNAPSHOTS = 10;
43static constexpr auto MIN_PARTITION_LENGTH = EmuDuration(60.0);
46static constexpr auto MAX_DIST_1_BEFORE_LAST_SNAPSHOT = EmuDuration(30.0);
71 template<
typename Archive>
74 if (ar.versionAtLeast(version, 2)) {
78 ar.serialize(
"snapshot", *newBoard);
82 ar.serialize(
"events", *
events);
84 if (ar.versionAtLeast(version, 3)) {
87 assert(Archive::IS_LOADER);
92 if (ar.versionAtLeast(version, 4)) {
102void ReverseManager::ReverseHistory::swap(ReverseHistory& other)
noexcept
104 std::swap(chunks, other.chunks);
105 std::swap(events, other.events);
108void ReverseManager::ReverseHistory::clear()
111 Chunks().swap(chunks);
112 Events().swap(events);
125 template<
typename Archive>
void serialize(Archive& ar,
unsigned )
127 ar.template serializeBase<StateChange>(*
this);
135 : syncNewSnapshot(motherBoard_.getScheduler())
136 , syncInputEvent (motherBoard_.getScheduler())
137 , motherBoard(motherBoard_)
138 , eventDistributor(motherBoard.getReactor().getEventDistributor())
139 , reverseCmd(motherBoard.getCommandController())
155 return replayIndex != history.events.size();
158void ReverseManager::start()
163 takeSnapshot(getCurrentTime());
165 schedule(getCurrentTime());
172void ReverseManager::stop()
176 syncNewSnapshot.removeSyncPoint();
177 syncInputEvent .removeSyncPoint();
181 pendingTakeSnapshot =
false;
183 assert(!pendingTakeSnapshot);
188EmuTime::param ReverseManager::getEndTime(
const ReverseHistory& hist)
const
190 if (!hist.events.empty()) {
191 if (
const auto* ev =
dynamic_cast<const EndLogEvent*
>(
192 hist.events.back().get())) {
194 return ev->getTime();
199 return getCurrentTime();
210 return (b - EmuTime::zero()).toDouble();
215 return (
end - EmuTime::zero()).toDouble();
219 EmuTime current(
isCollecting() ? getCurrentTime() : EmuTime::zero());
220 return (current - EmuTime::zero()).toDouble();
223void ReverseManager::status(
TclObject& result)
const
234 return (p.second.time - EmuTime::zero()).toDouble();
238 auto lastEvent = rbegin(history.events);
239 if (lastEvent != rend(history.events) &&
dynamic_cast<const EndLogEvent*
>(lastEvent->get())) {
242 EmuTime le(
isCollecting() && (lastEvent != rend(history.events)) ? (*lastEvent)->getTime() : EmuTime::zero());
243 result.
addDictKeyValue(
"last_event", (le - EmuTime::zero()).toDouble());
246void ReverseManager::debugInfo(TclObject& result)
const
251 size_t totalSize = 0;
252 for (
const auto& [idx, chunk] : history.chunks) {
254 (chunk.time - EmuTime::zero()).toDouble(),
' ',
255 ((chunk.time - EmuTime::zero()).toDouble() / (getCurrentTime() - EmuTime::zero()).toDouble()) * 100,
"%"
256 " (", chunk.size,
")"
257 " (next event index: ", chunk.eventCount,
")\n");
258 totalSize += chunk.size;
260 strAppend(res,
"total size: ", totalSize,
'\n');
264static std::pair<bool, double> parseGoTo(Interpreter& interp, std::span<const TclObject> tokens)
266 bool noVideo =
false;
267 std::array info = {
flagArg(
"-novideo", noVideo)};
268 auto args =
parseTclArgs(interp, tokens.subspan(2), info);
269 if (args.size() != 1)
throw SyntaxError();
270 double time = args[0].getDouble(interp);
271 return {noVideo, time};
274void ReverseManager::goBack(std::span<const TclObject> tokens)
277 auto [noVideo,
t] = parseGoTo(interp, tokens);
279 EmuTime now = getCurrentTime();
280 EmuTime target(EmuTime::dummy());
283 if (d < (now - EmuTime::zero())) {
286 target = EmuTime::zero();
289 target = now + EmuDuration(-
t);
291 goTo(target, noVideo);
294void ReverseManager::goTo(std::span<const TclObject> tokens)
297 auto [noVideo,
t] = parseGoTo(interp, tokens);
299 EmuTime target = EmuTime::zero() + EmuDuration(
t);
300 goTo(target, noVideo);
303void ReverseManager::goTo(EmuTime::param target,
bool noVideo)
306 throw CommandException(
307 "Reverse was not enabled. First execute the 'reverse "
308 "start' command to start collecting data.");
310 goTo(target, noVideo, history,
true);
314static void reportProgress(Reactor& reactor,
const EmuTime& targetTime,
float fraction)
316 double targetTimeDisp = (targetTime - EmuTime::zero()).toDouble();
317 std::ostringstream sstr;
318 sstr <<
"Time warping to " <<
319 int(targetTimeDisp / 60) <<
':' << std::setfill(
'0') <<
320 std::setw(5) << std::setprecision(2) << std::fixed <<
321 std::fmod(targetTimeDisp, 60.0);
322 reactor.getCliComm().printProgress(sstr.str(), fraction);
323 reactor.getDisplay().repaint();
326void ReverseManager::goTo(
327 EmuTime::param target,
bool noVideo, ReverseHistory& hist,
343 assert(!hist.chunks.empty());
344 auto it =
begin(hist.chunks);
345 EmuTime firstTime = it->second.time;
346 EmuTime targetTime = std::max(target, firstTime);
348 targetTime = std::min(targetTime, getEndTime(hist));
355 static constexpr double dur2frames = 2.0 * (313.0 * 1368.0) / (3579545.0 * 6.0);
356 EmuDuration preDelta(noVideo ? 0.0 : dur2frames);
357 EmuTime preTarget = ((targetTime - firstTime) > preDelta)
358 ? targetTime - preDelta
363 assert(it->second.time <= preTarget);
364 assert(it !=
end(hist.chunks));
367 }
while (it !=
end(hist.chunks) &&
368 it->second.time <= preTarget);
371 assert(it !=
begin(hist.chunks));
373 ReverseChunk& chunk = it->second;
374 EmuTime snapshotTime = chunk.time;
375 assert(snapshotTime <= preTarget);
386 EmuTime currentTime = getCurrentTime();
387 MSXMotherBoard* newBoard;
390 (currentTime <= preTarget) &&
391 ((snapshotTime <= currentTime) ||
392 ((preTarget - currentTime) < EmuDuration(1.0)))) {
393 newBoard = &motherBoard;
400 newBoard_ = reactor.createEmptyMotherBoard();
401 newBoard = newBoard_.get();
404 newBoard->getMSXCliComm().setSuppressMessages(
true);
405 MemInputArchive in(chunk.savestate.data(),
408 in.serialize(
"machine", *newBoard);
418 if (hist.events.empty() ||
419 !
dynamic_cast<const EndLogEvent*
>(hist.events.back().get())) {
420 hist.events.push_back(
421 std::make_unique<EndLogEvent>(currentTime));
427 auto& newManager = newBoard->getReverseManager();
428 newManager.transferHistory(hist, chunk.eventCount);
431 transferState(*newBoard);
445 auto startMSXTime = newBoard->getCurrentTime();
446 auto lastSnapshotTarget = startMSXTime;
447 bool everShowedProgress =
false;
448 syncNewSnapshot.removeSyncPoint();
450 auto currentTimeNewBoard = newBoard->getCurrentTime();
451 auto nextSnapshotTarget = std::min(
453 lastSnapshotTarget + std::max(
454 EmuDuration(SNAPSHOT_PERIOD),
455 (preTarget - lastSnapshotTarget) / 2
457 auto nextTarget = std::min(nextSnapshotTarget, currentTimeNewBoard +
EmuDuration::sec(1));
458 newBoard->fastForward(nextTarget,
true);
460 ((now - lastProgress) > 1000000) || ((currentTimeNewBoard >= preTarget) && everShowedProgress)) {
461 everShowedProgress =
true;
463 auto fraction = (currentTimeNewBoard - startMSXTime).toDouble() / (preTarget - startMSXTime).toDouble();
464 reportProgress(newBoard->getReactor(), targetTime,
float(fraction));
468 if (currentTimeNewBoard >= preTarget)
break;
469 if (currentTimeNewBoard >= nextSnapshotTarget) {
476 newBoard->getReverseManager().takeSnapshot(currentTimeNewBoard);
477 lastSnapshotTarget = nextSnapshotTarget;
481 newBoard->getMSXCliComm().setSuppressMessages(
false);
483 schedule(getCurrentTime());
491 reactor.replaceBoard(motherBoard, std::move(newBoard_));
496 newBoard->fastForward(targetTime,
false);
505 assert(newBoard->getReverseManager().isCollecting());
506 }
catch (MSXException&) {
513void ReverseManager::transferState(MSXMotherBoard& newBoard)
517 auto& newDistributor = newBoard .getStateChangeDistributor();
521 auto& newManager = newBoard.getReverseManager();
522 if (newManager.keyboard && keyboard) {
523 newManager.keyboard->transferHostKeyMatrix(*keyboard);
527 newBoard.getDebugger().transfer(motherBoard.
getDebugger());
530 newManager.reRecordCount = reRecordCount;
537void ReverseManager::saveReplay(
538 Interpreter& interp, std::span<const TclObject> tokens, TclObject& result)
540 const auto& chunks = history.chunks;
541 if (chunks.empty()) {
542 throw CommandException(
"No recording...");
545 std::string_view filenameArg;
546 int maxNofExtraSnapshots = MAX_NOF_SNAPSHOTS;
547 std::array info = {
valueArg(
"-maxnofextrasnapshots", maxNofExtraSnapshots)};
548 auto args =
parseTclArgs(interp, tokens.subspan(2), info);
549 switch (args.size()) {
551 case 1: filenameArg = args[0].getString();
break;
552 default:
throw SyntaxError();
554 if (maxNofExtraSnapshots < 0) {
555 throw CommandException(
"Maximum number of snapshots should be at least 0");
563 replay.reRecordCount = reRecordCount;
567 replay.currentTime = getCurrentTime();
570 auto initialBoard = reactor.createEmptyMotherBoard();
571 MemInputArchive in(
begin(chunks)->second.savestate.data(),
572 begin(chunks)->second.size,
573 begin(chunks)->second.deltaBlocks);
574 in.serialize(
"machine", *initialBoard);
575 replay.motherBoards.push_back(std::move(initialBoard));
577 if (maxNofExtraSnapshots > 0) {
579 const auto& startTime =
begin(chunks)->second.time;
584 const auto& lastChunkTime = rbegin(chunks)->second.time;
585 const auto& endTime = ((startTime + MAX_DIST_1_BEFORE_LAST_SNAPSHOT) < lastChunkTime) ? lastChunkTime - MAX_DIST_1_BEFORE_LAST_SNAPSHOT : lastChunkTime;
586 EmuDuration totalLength = endTime - startTime;
587 EmuDuration partitionLength = totalLength.divRoundUp(maxNofExtraSnapshots);
588 partitionLength = std::max(MIN_PARTITION_LENGTH, partitionLength);
589 EmuTime nextPartitionEnd = startTime + partitionLength;
590 auto it =
begin(chunks);
591 auto lastAddedIt =
begin(chunks);
592 while (it !=
end(chunks)) {
594 if (it ==
end(chunks) || (it->second.time > nextPartitionEnd)) {
596 assert(it->second.time <= nextPartitionEnd);
597 if (it != lastAddedIt) {
600 MemInputArchive in2(it->second.savestate.data(),
602 it->second.deltaBlocks);
603 in2.serialize(
"machine", *board);
604 replay.motherBoards.push_back(std::move(board));
608 while (it !=
end(chunks) && it->second.time > nextPartitionEnd) {
609 nextPartitionEnd += partitionLength;
613 assert(lastAddedIt == std::prev(
end(chunks)));
617 bool addSentinel = history.events.empty() ||
618 !
dynamic_cast<EndLogEvent*
>(history.events.back().get());
621 history.events.push_back(std::make_unique<EndLogEvent>(
625 XmlOutputArchive out(filename);
626 replay.events = &history.events;
627 out.serialize(
"replay", replay);
629 }
catch (MSXException&) {
631 history.events.pop_back();
641 history.events.pop_back();
644 result =
tmpStrCat(
"Saved replay to ", filename);
647void ReverseManager::loadReplay(
648 Interpreter& interp, std::span<const TclObject> tokens, TclObject& result)
650 bool enableViewOnly =
false;
651 std::optional<TclObject> where;
653 flagArg(
"-viewonly", enableViewOnly),
656 auto arguments =
parseTclArgs(interp, tokens.subspan(2), info);
657 if (arguments.size() != 1)
throw SyntaxError();
661 std::string fileNameArg(arguments[0].getString());
662 std::string filename;
665 filename =
context.resolve(fileNameArg);
666 }
catch (MSXException& ) {
try {
669 }
catch (MSXException& e2) {
try {
673 }
catch (MSXException& ) {
682 replay.events = &events;
684 XmlInputArchive in(filename);
685 in.serialize(
"replay", replay);
686 }
catch (XMLException& e) {
687 throw CommandException(
"Cannot load replay, bad file format: ",
689 }
catch (MSXException& e) {
690 throw CommandException(
"Cannot load replay: ",
e.getMessage());
694 auto destination = EmuTime::zero();
695 if (!where || (*where ==
"begin")) {
696 destination = EmuTime::zero();
697 }
else if (*where ==
"end") {
698 destination = EmuTime::infinity();
699 }
else if (*where ==
"savetime") {
700 destination = replay.currentTime;
702 destination += EmuDuration(where->getDouble(interp));
710 assert(!replay.motherBoards.empty());
711 auto& newReverseManager = replay.motherBoards[0]->getReverseManager();
712 auto& newHistory = newReverseManager.history;
714 if (newReverseManager.reRecordCount == 0) {
716 newReverseManager.reRecordCount = replay.reRecordCount;
723 swap(newHistory.events, events);
724 auto& newEvents = newHistory.events;
727 unsigned replayIdx = 0;
728 for (
const auto& m : replay.motherBoards) {
729 ReverseChunk newChunk;
730 newChunk.time = m->getCurrentTime();
732 MemOutputArchive out(newHistory.lastDeltaBlocks,
733 newChunk.deltaBlocks,
false);
734 out.serialize(
"machine", *m);
735 newChunk.savestate = out.releaseBuffer(newChunk.size);
739 while (replayIdx < newEvents.size() &&
740 (newEvents[replayIdx]->getTime() < newChunk.time)) {
743 newChunk.eventCount = replayIdx;
745 newHistory.chunks[newHistory.getNextSeqNum(newChunk.time)] =
751 reRecordCount = newReverseManager.reRecordCount;
752 bool noVideo =
false;
753 goTo(destination, noVideo, newHistory,
false);
755 result =
tmpStrCat(
"Loaded replay from ", filename);
758void ReverseManager::transferHistory(ReverseHistory& oldHistory,
759 unsigned oldEventCount)
762 assert(history.chunks.empty());
765 oldHistory.lastDeltaBlocks.clear();
768 history.swap(oldHistory);
772 schedule(getCurrentTime());
776 replayIndex = oldEventCount;
778 assert(replayIndex < history.events.size());
782void ReverseManager::execNewSnapshot()
810 pendingTakeSnapshot =
true;
814void ReverseManager::execInputEvent()
816 const auto&
event = *history.events[replayIndex];
820 }
catch (MSXException&) {
824 if (!
dynamic_cast<const EndLogEvent*
>(&event)) {
828 signalStopReplay(event.getTime());
833bool ReverseManager::signalEvent(
const Event& event)
840 if (pendingTakeSnapshot) {
841 pendingTakeSnapshot =
false;
842 takeSnapshot(getCurrentTime());
844 schedule(getCurrentTime());
849unsigned ReverseManager::ReverseHistory::getNextSeqNum(EmuTime::param time)
const
851 if (chunks.empty()) {
854 const auto& startTime =
begin(chunks)->second.time;
855 double duration = (time - startTime).toDouble();
856 return narrow<unsigned>(lrint(duration / SNAPSHOT_PERIOD));
859void ReverseManager::takeSnapshot(EmuTime::param time)
864 unsigned seqNum = history.getNextSeqNum(time);
865 dropOldSnapshots<25>(seqNum);
873 ReverseChunk& newChunk = history.chunks[seqNum];
874 newChunk.deltaBlocks.clear();
875 MemOutputArchive out(history.lastDeltaBlocks, newChunk.deltaBlocks,
true);
876 out.serialize(
"machine", motherBoard);
877 newChunk.time = time;
878 newChunk.savestate = out.releaseBuffer(newChunk.size);
879 newChunk.eventCount = replayIndex;
882void ReverseManager::replayNextEvent()
885 assert(replayIndex < history.events.size());
886 syncInputEvent.setSyncPoint(history.events[replayIndex]->getTime());
889void ReverseManager::signalStopReplay(EmuTime::param time)
901 syncInputEvent.removeSyncPoint();
902 Events& events = history.events;
903 events.erase(
begin(events) + replayIndex,
end(events));
906 return p.second.time > time;
908 history.chunks.erase(it,
end(history.chunks));
912 assert(!isReplaying());
928void ReverseManager::dropOldSnapshots(
unsigned count)
930 unsigned y = (count + N) ^ (count + N + 1);
932 unsigned d2 = 2 * N + 1;
935 if ((y == 0) || (count < d))
return;
936 history.chunks.erase(count - d);
942void ReverseManager::schedule(EmuTime::param time)
944 syncNewSnapshot.setSyncPoint(time + EmuDuration(SNAPSHOT_PERIOD));
950ReverseManager::ReverseCmd::ReverseCmd(CommandController& controller)
951 : Command(controller,
"reverse")
955void ReverseManager::ReverseCmd::execute(std::span<const TclObject> tokens, TclObject& result)
957 checkNumArgs(tokens, AtLeast{2},
"subcommand ?arg ...?");
958 auto& manager =
OUTER(ReverseManager, reverseCmd);
959 auto& interp = getInterpreter();
960 executeSubCommand(tokens[1].getString(),
961 "start", [&]{ manager.start(); },
962 "stop", [&]{ manager.stop(); },
963 "status", [&]{ manager.status(result); },
964 "debug", [&]{ manager.debugInfo(result); },
965 "goback", [&]{ manager.goBack(tokens); },
966 "goto", [&]{ manager.goTo(tokens); },
967 "savereplay", [&]{ manager.saveReplay(interp, tokens, result); },
968 "loadreplay", [&]{ manager.loadReplay(interp, tokens, result); },
970 auto& distributor = manager.motherBoard.getStateChangeDistributor();
971 switch (tokens.size()) {
973 result = distributor.isViewOnlyMode();
976 distributor.setViewOnlyMode(tokens[2].getBoolean(interp));
981 "truncatereplay", [&] {
982 if (manager.isReplaying()) {
983 manager.signalStopReplay(manager.getCurrentTime());
987std::string ReverseManager::ReverseCmd::help(std::span<const TclObject> )
const
989 return "start start collecting reverse data\n"
990 "stop stop collecting\n"
991 "status show various status info on reverse\n"
992 "goback <n> go back <n> seconds in time\n"
993 "goto <time> go to an absolute moment in time\n"
994 "viewonlymode <bool> switch viewonly mode on or off\n"
995 "truncatereplay stop replaying and remove all 'future' data\n"
996 "savereplay [<name>] save the first snapshot and all replay data as a 'replay' (with optional name)\n"
997 "loadreplay [-goto <begin|end|savetime|<n>>] [-viewonly] <name> load a replay (snapshot and replay data) with given name and start replaying\n";
1000void ReverseManager::ReverseCmd::tabCompletion(std::vector<std::string>& tokens)
const
1002 using namespace std::literals;
1003 if (tokens.size() == 2) {
1004 static constexpr std::array subCommands = {
1005 "start"sv,
"stop"sv,
"status"sv,
"goback"sv,
"goto"sv,
1006 "savereplay"sv,
"loadreplay"sv,
"viewonlymode"sv,
1009 completeString(tokens, subCommands);
1010 }
else if ((tokens.size() == 3) || (tokens[1] ==
"loadreplay")) {
1011 if (tokens[1] ==
one_of(
"loadreplay",
"savereplay")) {
1012 static constexpr std::array cmds = {
"-goto"sv,
"-viewonly"sv};
1014 (tokens[1] ==
"loadreplay") ? cmds :
std::span<const
std::string_view>{});
1015 }
else if (tokens[1] ==
"viewonlymode") {
1016 static constexpr std::array options = {
"true"sv,
"false"sv};
1017 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()
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)