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)) {
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();
225 return (p.second.time - EmuTime::zero()).toDouble();
229void ReverseManager::status(
TclObject& result)
const
240 return (p.second.time - EmuTime::zero()).toDouble();
244 auto lastEvent = rbegin(history.events);
245 if (lastEvent != rend(history.events) &&
dynamic_cast<const EndLogEvent*
>(lastEvent->get())) {
248 EmuTime le(
isCollecting() && (lastEvent != rend(history.events)) ? (*lastEvent)->getTime() : EmuTime::zero());
249 result.
addDictKeyValue(
"last_event", (le - EmuTime::zero()).toDouble());
252void ReverseManager::debugInfo(TclObject& result)
const
257 size_t totalSize = 0;
258 for (
const auto& [idx, chunk] : history.chunks) {
260 (chunk.time - EmuTime::zero()).toDouble(),
' ',
261 ((chunk.time - EmuTime::zero()).toDouble() / (getCurrentTime() - EmuTime::zero()).toDouble()) * 100,
"%"
262 " (", chunk.size,
")"
263 " (next event index: ", chunk.eventCount,
")\n");
264 totalSize += chunk.size;
266 strAppend(res,
"total size: ", totalSize,
'\n');
270static std::pair<bool, double> parseGoTo(Interpreter& interp, std::span<const TclObject> tokens)
272 bool noVideo =
false;
273 std::array info = {
flagArg(
"-novideo", noVideo)};
274 auto args =
parseTclArgs(interp, tokens.subspan(2), info);
275 if (args.size() != 1)
throw SyntaxError();
276 double time = args[0].getDouble(interp);
277 return {noVideo, time};
280void ReverseManager::goBack(std::span<const TclObject> tokens)
283 auto [noVideo,
t] = parseGoTo(interp, tokens);
285 EmuTime now = getCurrentTime();
286 EmuTime target(EmuTime::dummy());
289 if (d < (now - EmuTime::zero())) {
292 target = EmuTime::zero();
295 target = now + EmuDuration(-
t);
297 goTo(target, noVideo);
300void ReverseManager::goTo(std::span<const TclObject> tokens)
303 auto [noVideo,
t] = parseGoTo(interp, tokens);
305 EmuTime target = EmuTime::zero() + EmuDuration(
t);
306 goTo(target, noVideo);
309void ReverseManager::goTo(EmuTime::param target,
bool noVideo)
312 throw CommandException(
313 "Reverse was not enabled. First execute the 'reverse "
314 "start' command to start collecting data.");
316 goTo(target, noVideo, history,
true);
320static void reportProgress(Reactor& reactor,
const EmuTime& targetTime,
float fraction)
322 double targetTimeDisp = (targetTime - EmuTime::zero()).toDouble();
323 std::ostringstream sstr;
324 sstr <<
"Time warping to " <<
325 int(targetTimeDisp / 60) <<
':' << std::setfill(
'0') <<
326 std::setw(5) << std::setprecision(2) << std::fixed <<
327 std::fmod(targetTimeDisp, 60.0);
328 reactor.getCliComm().printProgress(sstr.str(), fraction);
329 reactor.getDisplay().repaint();
332void ReverseManager::goTo(
333 EmuTime::param target,
bool noVideo, ReverseHistory& hist,
349 assert(!hist.chunks.empty());
350 auto it =
begin(hist.chunks);
351 EmuTime firstTime = it->second.time;
352 EmuTime targetTime =
std::max(target, firstTime);
354 targetTime =
std::min(targetTime, getEndTime(hist));
361 static constexpr double dur2frames = 2.0 * (313.0 * 1368.0) / (3579545.0 * 6.0);
362 EmuDuration preDelta(noVideo ? 0.0 : dur2frames);
363 EmuTime preTarget = ((targetTime - firstTime) > preDelta)
364 ? targetTime - preDelta
369 assert(it->second.time <= preTarget);
370 assert(it !=
end(hist.chunks));
373 }
while (it !=
end(hist.chunks) &&
374 it->second.time <= preTarget);
377 assert(it !=
begin(hist.chunks));
379 ReverseChunk& chunk = it->second;
380 EmuTime snapshotTime = chunk.time;
381 assert(snapshotTime <= preTarget);
392 EmuTime currentTime = getCurrentTime();
393 MSXMotherBoard* newBoard;
396 (currentTime <= preTarget) &&
397 ((snapshotTime <= currentTime) ||
398 ((preTarget - currentTime) < EmuDuration(1.0)))) {
399 newBoard = &motherBoard;
406 newBoard_ = reactor.createEmptyMotherBoard();
407 newBoard = newBoard_.get();
410 newBoard->getMSXCliComm().setSuppressMessages(
true);
411 MemInputArchive in(chunk.savestate.data(),
414 in.serialize(
"machine", *newBoard);
424 if (hist.events.empty() ||
425 !
dynamic_cast<const EndLogEvent*
>(hist.events.back().get())) {
426 hist.events.push_back(
427 std::make_unique<EndLogEvent>(currentTime));
433 auto& newManager = newBoard->getReverseManager();
434 newManager.transferHistory(hist, chunk.eventCount);
437 transferState(*newBoard);
451 auto startMSXTime = newBoard->getCurrentTime();
452 auto lastSnapshotTarget = startMSXTime;
453 bool everShowedProgress =
false;
454 syncNewSnapshot.removeSyncPoint();
456 auto currentTimeNewBoard = newBoard->getCurrentTime();
460 EmuDuration(SNAPSHOT_PERIOD),
461 (preTarget - lastSnapshotTarget) / 2
464 newBoard->fastForward(nextTarget,
true);
466 if (((now - lastProgress) > 1000000) || ((currentTimeNewBoard >= preTarget) && everShowedProgress)) {
467 everShowedProgress =
true;
469 auto fraction = ((currentTimeNewBoard - startMSXTime)).toDouble() / (preTarget - startMSXTime).toDouble();
470 reportProgress(newBoard->getReactor(), targetTime,
float(fraction));
474 if (currentTimeNewBoard >= preTarget)
break;
475 if (currentTimeNewBoard >= nextSnapshotTarget) {
482 newBoard->getReverseManager().takeSnapshot(currentTimeNewBoard);
483 lastSnapshotTarget = nextSnapshotTarget;
487 newBoard->getMSXCliComm().setSuppressMessages(
false);
489 schedule(getCurrentTime());
497 reactor.replaceBoard(motherBoard, std::move(newBoard_));
502 newBoard->fastForward(targetTime,
false);
511 assert(newBoard->getReverseManager().isCollecting());
512 }
catch (MSXException&) {
519void ReverseManager::transferState(MSXMotherBoard& newBoard)
523 auto& newDistributor = newBoard .getStateChangeDistributor();
527 auto& newManager = newBoard.getReverseManager();
528 if (newManager.keyboard && keyboard) {
529 newManager.keyboard->transferHostKeyMatrix(*keyboard);
533 newBoard.getDebugger().transfer(motherBoard.
getDebugger());
536 newManager.reRecordCount = reRecordCount;
543void ReverseManager::saveReplay(
544 Interpreter& interp, std::span<const TclObject> tokens, TclObject& result)
546 const auto& chunks = history.chunks;
547 if (chunks.empty()) {
548 throw CommandException(
"No recording...");
551 std::string_view filenameArg;
552 int maxNofExtraSnapshots = MAX_NOF_SNAPSHOTS;
553 std::array info = {
valueArg(
"-maxnofextrasnapshots", maxNofExtraSnapshots)};
554 auto args =
parseTclArgs(interp, tokens.subspan(2), info);
555 switch (args.size()) {
557 case 1: filenameArg = args[0].getString();
break;
558 default:
throw SyntaxError();
560 if (maxNofExtraSnapshots < 0) {
561 throw CommandException(
"Maximum number of snapshots should be at least 0");
569 replay.reRecordCount = reRecordCount;
573 replay.currentTime = getCurrentTime();
576 auto initialBoard = reactor.createEmptyMotherBoard();
577 MemInputArchive in(
begin(chunks)->second.savestate.data(),
578 begin(chunks)->second.size,
579 begin(chunks)->second.deltaBlocks);
580 in.serialize(
"machine", *initialBoard);
581 replay.motherBoards.push_back(std::move(initialBoard));
583 if (maxNofExtraSnapshots > 0) {
585 const auto& startTime =
begin(chunks)->second.time;
590 const auto& lastChunkTime = rbegin(chunks)->second.time;
591 const auto& endTime = ((startTime + MAX_DIST_1_BEFORE_LAST_SNAPSHOT) < lastChunkTime) ? lastChunkTime - MAX_DIST_1_BEFORE_LAST_SNAPSHOT : lastChunkTime;
592 EmuDuration totalLength = endTime - startTime;
593 EmuDuration partitionLength = totalLength.divRoundUp(maxNofExtraSnapshots);
594 partitionLength =
std::max(MIN_PARTITION_LENGTH, partitionLength);
595 EmuTime nextPartitionEnd = startTime + partitionLength;
596 auto it =
begin(chunks);
597 auto lastAddedIt =
begin(chunks);
598 while (it !=
end(chunks)) {
600 if (it ==
end(chunks) || (it->second.time > nextPartitionEnd)) {
602 assert(it->second.time <= nextPartitionEnd);
603 if (it != lastAddedIt) {
606 MemInputArchive in2(it->second.savestate.data(),
608 it->second.deltaBlocks);
609 in2.serialize(
"machine", *board);
610 replay.motherBoards.push_back(std::move(board));
614 while (it !=
end(chunks) && it->second.time > nextPartitionEnd) {
615 nextPartitionEnd += partitionLength;
619 assert(lastAddedIt == std::prev(
end(chunks)));
623 bool addSentinel = history.events.empty() ||
624 !
dynamic_cast<EndLogEvent*
>(history.events.back().get());
627 history.events.push_back(std::make_unique<EndLogEvent>(
631 XmlOutputArchive out(filename);
632 replay.events = &history.events;
633 out.serialize(
"replay", replay);
635 }
catch (MSXException&) {
637 history.events.pop_back();
647 history.events.pop_back();
650 result =
tmpStrCat(
"Saved replay to ", filename);
653void ReverseManager::loadReplay(
654 Interpreter& interp, std::span<const TclObject> tokens, TclObject& result)
656 bool enableViewOnly =
false;
657 std::optional<TclObject> where;
659 flagArg(
"-viewonly", enableViewOnly),
662 auto arguments =
parseTclArgs(interp, tokens.subspan(2), info);
663 if (arguments.size() != 1)
throw SyntaxError();
667 std::string fileNameArg(arguments[0].getString());
668 std::string filename;
671 filename =
context.resolve(fileNameArg);
672 }
catch (MSXException& ) {
try {
675 }
catch (MSXException& e2) {
try {
679 }
catch (MSXException& ) {
688 replay.events = &events;
690 XmlInputArchive in(filename);
691 in.serialize(
"replay", replay);
692 }
catch (XMLException&
e) {
693 throw CommandException(
"Cannot load replay, bad file format: ",
695 }
catch (MSXException&
e) {
696 throw CommandException(
"Cannot load replay: ",
e.getMessage());
700 auto destination = EmuTime::zero();
701 if (!where || (*where ==
"begin")) {
702 destination = EmuTime::zero();
703 }
else if (*where ==
"end") {
704 destination = EmuTime::infinity();
705 }
else if (*where ==
"savetime") {
706 destination = replay.currentTime;
708 destination += EmuDuration(where->getDouble(interp));
716 assert(!replay.motherBoards.empty());
717 auto& newReverseManager = replay.motherBoards[0]->getReverseManager();
718 auto& newHistory = newReverseManager.history;
720 if (newReverseManager.reRecordCount == 0) {
722 newReverseManager.reRecordCount = replay.reRecordCount;
729 swap(newHistory.events, events);
730 auto& newEvents = newHistory.events;
733 unsigned replayIdx = 0;
734 for (
auto& m : replay.motherBoards) {
735 ReverseChunk newChunk;
736 newChunk.time = m->getCurrentTime();
738 MemOutputArchive out(newHistory.lastDeltaBlocks,
739 newChunk.deltaBlocks,
false);
740 out.serialize(
"machine", *m);
741 newChunk.savestate = out.releaseBuffer(newChunk.size);
745 while (replayIdx < newEvents.size() &&
746 (newEvents[replayIdx]->getTime() < newChunk.time)) {
749 newChunk.eventCount = replayIdx;
751 newHistory.chunks[newHistory.getNextSeqNum(newChunk.time)] =
757 reRecordCount = newReverseManager.reRecordCount;
758 bool noVideo =
false;
759 goTo(destination, noVideo, newHistory,
false);
761 result =
tmpStrCat(
"Loaded replay from ", filename);
764void ReverseManager::transferHistory(ReverseHistory& oldHistory,
765 unsigned oldEventCount)
768 assert(history.chunks.empty());
771 oldHistory.lastDeltaBlocks.clear();
774 history.swap(oldHistory);
778 schedule(getCurrentTime());
782 replayIndex = oldEventCount;
784 assert(replayIndex < history.events.size());
788void ReverseManager::execNewSnapshot()
816 pendingTakeSnapshot =
true;
820void ReverseManager::execInputEvent()
822 const auto&
event = *history.events[replayIndex];
826 }
catch (MSXException&) {
830 if (!
dynamic_cast<const EndLogEvent*
>(&event)) {
834 signalStopReplay(event.getTime());
839int ReverseManager::signalEvent(
const Event& event)
846 if (pendingTakeSnapshot) {
847 pendingTakeSnapshot =
false;
848 takeSnapshot(getCurrentTime());
850 schedule(getCurrentTime());
855unsigned ReverseManager::ReverseHistory::getNextSeqNum(EmuTime::param time)
const
857 if (chunks.empty()) {
860 const auto& startTime =
begin(chunks)->second.time;
861 double duration = (time - startTime).toDouble();
862 return narrow<unsigned>(lrint(duration / SNAPSHOT_PERIOD));
865void ReverseManager::takeSnapshot(EmuTime::param time)
870 unsigned seqNum = history.getNextSeqNum(time);
871 dropOldSnapshots<25>(seqNum);
879 ReverseChunk& newChunk = history.chunks[seqNum];
880 newChunk.deltaBlocks.clear();
881 MemOutputArchive out(history.lastDeltaBlocks, newChunk.deltaBlocks,
true);
882 out.serialize(
"machine", motherBoard);
883 newChunk.time = time;
884 newChunk.savestate = out.releaseBuffer(newChunk.size);
885 newChunk.eventCount = replayIndex;
888void ReverseManager::replayNextEvent()
891 assert(replayIndex < history.events.size());
892 syncInputEvent.setSyncPoint(history.events[replayIndex]->getTime());
895void ReverseManager::signalStopReplay(EmuTime::param time)
907 syncInputEvent.removeSyncPoint();
908 Events& events = history.events;
909 events.erase(
begin(events) + replayIndex,
end(events));
912 return p.second.time > time;
914 history.chunks.erase(it,
end(history.chunks));
918 assert(!isReplaying());
934void ReverseManager::dropOldSnapshots(
unsigned count)
936 unsigned y = (count + N) ^ (count + N + 1);
938 unsigned d2 = 2 * N + 1;
941 if ((y == 0) || (count < d))
return;
942 history.chunks.erase(count - d);
948void ReverseManager::schedule(EmuTime::param time)
950 syncNewSnapshot.setSyncPoint(time + EmuDuration(SNAPSHOT_PERIOD));
956ReverseManager::ReverseCmd::ReverseCmd(CommandController& controller)
957 : Command(controller,
"reverse")
961void ReverseManager::ReverseCmd::execute(std::span<const TclObject> tokens, TclObject& result)
963 checkNumArgs(tokens, AtLeast{2},
"subcommand ?arg ...?");
964 auto& manager =
OUTER(ReverseManager, reverseCmd);
965 auto& interp = getInterpreter();
966 executeSubCommand(tokens[1].getString(),
967 "start", [&]{ manager.start(); },
968 "stop", [&]{ manager.stop(); },
969 "status", [&]{ manager.status(result); },
970 "debug", [&]{ manager.debugInfo(result); },
971 "goback", [&]{ manager.goBack(tokens); },
972 "goto", [&]{ manager.goTo(tokens); },
973 "savereplay", [&]{ manager.saveReplay(interp, tokens, result); },
974 "loadreplay", [&]{ manager.loadReplay(interp, tokens, result); },
976 auto& distributor = manager.motherBoard.getStateChangeDistributor();
977 switch (tokens.size()) {
979 result = distributor.isViewOnlyMode();
982 distributor.setViewOnlyMode(tokens[2].getBoolean(interp));
987 "truncatereplay", [&] {
988 if (manager.isReplaying()) {
989 manager.signalStopReplay(manager.getCurrentTime());
993std::string ReverseManager::ReverseCmd::help(std::span<const TclObject> )
const
995 return "start start collecting reverse data\n"
996 "stop stop collecting\n"
997 "status show various status info on reverse\n"
998 "goback <n> go back <n> seconds in time\n"
999 "goto <time> go to an absolute moment in time\n"
1000 "viewonlymode <bool> switch viewonly mode on or off\n"
1001 "truncatereplay stop replaying and remove all 'future' data\n"
1002 "savereplay [<name>] save the first snapshot and all replay data as a 'replay' (with optional name)\n"
1003 "loadreplay [-goto <begin|end|savetime|<n>>] [-viewonly] <name> load a replay (snapshot and replay data) with given name and start replaying\n";
1006void ReverseManager::ReverseCmd::tabCompletion(std::vector<std::string>& tokens)
const
1008 using namespace std::literals;
1009 if (tokens.size() == 2) {
1010 static constexpr std::array subCommands = {
1011 "start"sv,
"stop"sv,
"status"sv,
"goback"sv,
"goto"sv,
1012 "savereplay"sv,
"loadreplay"sv,
"viewonlymode"sv,
1015 completeString(tokens, subCommands);
1016 }
else if ((tokens.size() == 3) || (tokens[1] ==
"loadreplay")) {
1017 if (tokens[1] ==
one_of(
"loadreplay",
"savereplay")) {
1018 static constexpr std::array cmds = {
"-goto"sv,
"-viewonly"sv};
1020 (tokens[1] ==
"loadreplay") ? cmds : std::span<const std::string_view>{});
1021 }
else if (tokens[1] ==
"viewonlymode") {
1022 static constexpr std::array options = {
"true"sv,
"false"sv};
1023 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=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
std::vector< double > getSnapshotTimes() const
static constexpr std::string_view REPLAY_DIR
bool isViewOnlyMode() const
ReverseManager(MSXMotherBoard &motherBoard)
void unregisterRecorder(ReverseManager &recorder)
void registerRecorder(ReverseManager &recorder)
(Un)registers the given object to receive state change events.
bool isViewOnlyMode() const
void setViewOnlyMode(bool value)
Set viewOnlyMode.
void stopReplay(EmuTime::param time)
Explicitly stop replay.
void distributeReplay(const StateChange &event)
Base class for all external MSX state changing events.
void addListElements(ITER first, ITER last)
void addDictKeyValue(const Key &key, const Value &value)
constexpr vecN< N, T > min(const vecN< N, T > &x, const vecN< N, T > &y)
std::optional< Context > context
constexpr vecN< N, T > max(const vecN< N, T > &x, const vecN< N, T > &y)
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:
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, ImGuiDelayedActionEvent, ImGuiActiveEvent > Event
ArgsInfo valueArg(std::string_view name, T &value)
REGISTER_POLYMORPHIC_CLASS(StateChange, AutofireStateChange, "AutofireStateChange")
std::vector< TclObject > parseTclArgs(Interpreter &interp, std::span< const TclObject > inArgs, std::span< const ArgsInfo > table)
SERIALIZE_CLASS_VERSION(CassettePlayer, 2)
EventType getType(const Event &event)
ArgsInfo flagArg(std::string_view name, bool &flag)
FileContext userDataFileContext(string_view subDir)
auto find_if(InputRange &&range, UnaryPredicate pred)
void swap(openmsx::MemBuffer< T > &l, openmsx::MemBuffer< T > &r) noexcept
constexpr auto transform(Range &&range, UnaryOp op)
#define OUTER(type, member)
auto to_vector(Range &&range) -> std::vector< detail::ToVectorType< T, decltype(std::begin(range))> >
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)