openMSX
ReverseManager.cc
Go to the documentation of this file.
1 #include "ReverseManager.hh"
2 #include "MSXMotherBoard.hh"
3 #include "EventDistributor.hh"
5 #include "Keyboard.hh"
6 #include "Debugger.hh"
7 #include "EventDelay.hh"
8 #include "MSXMixer.hh"
10 #include "XMLException.hh"
11 #include "TclObject.hh"
12 #include "FileOperations.hh"
13 #include "FileContext.hh"
14 #include "StateChange.hh"
15 #include "Reactor.hh"
16 #include "Command.hh"
17 #include "CommandException.hh"
18 #include "MemBuffer.hh"
19 #include "StringOp.hh"
20 #include "serialize.hh"
21 #include "serialize_stl.hh"
22 #include "memory.hh"
23 #include "xrange.hh"
24 #include <functional>
25 #include <cassert>
26 
27 using std::string;
28 using std::vector;
29 using std::shared_ptr;
30 using std::move;
31 
32 namespace openmsx {
33 
34 // Time between two snapshots (in seconds)
35 static const double SNAPSHOT_PERIOD = 1.0;
36 
37 // Max number of snapshots in a replay
38 static const unsigned MAX_NOF_SNAPSHOTS = 10;
39 
40 // Min distance between snapshots in replay (in seconds)
41 static const EmuDuration MIN_PARTITION_LENGTH = EmuDuration(60.0);
42 
43 static const char* const REPLAY_DIR = "replays";
44 
45 // A replay is a struct that contains a vector of motherboards and an MSX event
46 // log. Those combined are a replay, because you can replay the events from an
47 // existing motherboard state: the vector has to have at least one motherboard
48 // (the initial state), but can have optionally more motherboards, which are
49 // merely in-between snapshots, so it is quicker to jump to a later time in the
50 // event log.
51 
52 struct Replay
53 {
54  Replay(Reactor& reactor_)
55  : reactor(reactor_), currentTime(EmuTime::dummy()) {}
56 
58 
59  ReverseManager::Events* events;
60  std::vector<Reactor::Board> motherBoards;
62  // this is the amount of times the reverse goto command was used, which
63  // is interesting for the TAS community (see tasvideos.org). It's an
64  // indication of the effort it took to create the replay. Note that
65  // there is no way to verify this number.
66  unsigned reRecordCount;
67 
68  template<typename Archive>
69  void serialize(Archive& ar, unsigned version)
70  {
71  if (ar.versionAtLeast(version, 2)) {
72  ar.serializeWithID("snapshots", motherBoards, std::ref(reactor));
73  } else {
75  ar.serialize("snapshot", *newBoard);
76  motherBoards.push_back(move(newBoard));
77  }
78 
79  ar.serialize("events", *events);
80 
81  if (ar.versionAtLeast(version, 3)) {
82  ar.serialize("currentTime", currentTime);
83  } else {
84  assert(ar.isLoader());
85  assert(!events->empty());
86  currentTime = events->back()->getTime();
87  }
88 
89  if (ar.versionAtLeast(version, 4)) {
90  ar.serialize("reRecordCount", reRecordCount);
91  }
92  }
93 };
94 SERIALIZE_CLASS_VERSION(Replay, 4);
95 
96 class ReverseCmd final : public Command
97 {
98 public:
99  ReverseCmd(ReverseManager& manager, CommandController& controller);
100  void execute(array_ref<TclObject> tokens, TclObject& result) override;
101  string help(const vector<string>& tokens) const override;
102  void tabCompletion(vector<string>& tokens) const override;
103 private:
104  ReverseManager& manager;
105 };
106 
107 
108 // struct ReverseHistory
109 
110 void ReverseManager::ReverseHistory::swap(ReverseHistory& other)
111 {
112  std::swap(chunks, other.chunks);
113  std::swap(events, other.events);
114 }
115 
116 void ReverseManager::ReverseHistory::clear()
117 {
118  // clear() and free storage capacity
119  Chunks().swap(chunks);
120  Events().swap(events);
121 }
122 
123 
124 // struct ReverseChunk
125 
126 ReverseManager::ReverseChunk::ReverseChunk()
127  : time(EmuTime::zero)
128 {
129 }
130 
131 ReverseManager::ReverseChunk::ReverseChunk(ReverseChunk&& rhs)
132  : time (move(rhs.time))
133  , savestate (move(rhs.savestate))
134  , eventCount(move(rhs.eventCount))
135 {
136 }
137 
138 ReverseManager::ReverseChunk& ReverseManager::ReverseChunk::operator=(
139  ReverseChunk&& rhs)
140 {
141  time = move(rhs.time);
142  savestate = move(rhs.savestate);
143  eventCount = move(rhs.eventCount);
144  return *this;
145 }
146 
147 
148 class EndLogEvent final : public StateChange
149 {
150 public:
151  EndLogEvent() {} // for serialize
153  : StateChange(time)
154  {
155  }
156 
157  template<typename Archive> void serialize(Archive& ar, unsigned /*version*/)
158  {
159  ar.template serializeBase<StateChange>(*this);
160  }
161 };
162 REGISTER_POLYMORPHIC_CLASS(StateChange, EndLogEvent, "EndLog");
163 
164 // class ReverseManager
165 
166 enum SyncType {
169 };
170 
172  : Schedulable(motherBoard_.getScheduler())
173  , motherBoard(motherBoard_)
174  , eventDistributor(motherBoard.getReactor().getEventDistributor())
175  , reverseCmd(make_unique<ReverseCmd>(
176  *this, motherBoard.getCommandController()))
177  , keyboard(nullptr)
178  , eventDelay(nullptr)
179  , replayIndex(0)
180  , collecting(false)
181  , pendingTakeSnapshot(false)
182  , reRecordCount(0)
183 {
184  eventDistributor.registerEventListener(OPENMSX_TAKE_REVERSE_SNAPSHOT, *this);
185 
186  assert(!isCollecting());
187  assert(!isReplaying());
188 }
189 
191 {
192  stop();
194 }
195 
196 bool ReverseManager::isReplaying() const
197 {
198  return replayIndex != history.events.size();
199 }
200 
201 void ReverseManager::start()
202 {
203  if (!isCollecting()) {
204  // create first snapshot
205  collecting = true;
206  takeSnapshot(getCurrentTime());
207  // start recording events
208  motherBoard.getStateChangeDistributor().registerRecorder(*this);
209  }
210  assert(isCollecting());
211 }
212 
213 void ReverseManager::stop()
214 {
215  if (isCollecting()) {
216  motherBoard.getStateChangeDistributor().unregisterRecorder(*this);
217  removeSyncPoint(NEW_SNAPSHOT); // don't schedule new snapshot takings
218  removeSyncPoint(INPUT_EVENT); // stop any pending replay actions
219  history.clear();
220  replayIndex = 0;
221  collecting = false;
222  pendingTakeSnapshot = false;
223  }
224  assert(!pendingTakeSnapshot);
225  assert(!isCollecting());
226  assert(!isReplaying());
227 }
228 
229 EmuTime::param ReverseManager::getEndTime(const ReverseHistory& history) const
230 {
231  if (!history.events.empty()) {
232  if (auto* ev = dynamic_cast<const EndLogEvent*>(
233  history.events.back().get())) {
234  // last log element is EndLogEvent, use that
235  return ev->getTime();
236  }
237  }
238  // otherwise use current time
239  assert(!isReplaying());
240  return getCurrentTime();
241 }
242 
243 void ReverseManager::status(TclObject& result) const
244 {
245  result.addListElement("status");
246  if (!isCollecting()) {
247  result.addListElement("disabled");
248  } else if (isReplaying()) {
249  result.addListElement("replaying");
250  } else {
251  result.addListElement("enabled");
252  }
253 
254  result.addListElement("begin");
255  EmuTime b(isCollecting() ? begin(history.chunks)->second.time
256  : EmuTime::zero);
257  result.addListElement((b - EmuTime::zero).toDouble());
258 
259  result.addListElement("end");
260  EmuTime end(isCollecting() ? getEndTime(history) : EmuTime::zero);
261  result.addListElement((end - EmuTime::zero).toDouble());
262 
263  result.addListElement("current");
264  EmuTime current(isCollecting() ? getCurrentTime() : EmuTime::zero);
265  result.addListElement((current - EmuTime::zero).toDouble());
266 
267  result.addListElement("snapshots");
268  TclObject snapshots;
269  for (auto& p : history.chunks) {
270  EmuTime time = p.second.time;
271  snapshots.addListElement((time - EmuTime::zero).toDouble());
272  }
273  result.addListElement(snapshots);
274 }
275 
276 void ReverseManager::debugInfo(TclObject& result) const
277 {
278  // TODO this is useful during development, but for the end user this
279  // information means nothing. We should remove this later.
280  StringOp::Builder res;
281  size_t totalSize = 0;
282  for (auto& p : history.chunks) {
283  auto& chunk = p.second;
284  res << p.first << ' '
285  << (chunk.time - EmuTime::zero).toDouble() << ' '
286  << ((chunk.time - EmuTime::zero).toDouble() / (getCurrentTime() - EmuTime::zero).toDouble()) * 100 << '%'
287  << " (" << chunk.savestate.size() << ')'
288  << " (next event index: " << chunk.eventCount << ")\n";
289  totalSize += chunk.savestate.size();
290  }
291  res << "total size: " << totalSize << '\n';
292  result.setString(string(res));
293 }
294 
295 static void parseGoTo(Interpreter& interp, array_ref<TclObject> tokens,
296  bool& novideo, double& time)
297 {
298  novideo = false;
299  bool hasTime = false;
300  for (auto i : xrange(size_t(2), tokens.size())) {
301  if (tokens[i].getString() == "-novideo") {
302  novideo = true;
303  } else {
304  time = tokens[i].getDouble(interp);
305  hasTime = true;
306  }
307  }
308  if (!hasTime) {
309  throw SyntaxError();
310  }
311 }
312 
313 void ReverseManager::goBack(array_ref<TclObject> tokens)
314 {
315  bool novideo;
316  double t;
317  auto& interp = motherBoard.getReactor().getInterpreter();
318  parseGoTo(interp, tokens, novideo, t);
319 
320  EmuTime now = getCurrentTime();
321  EmuTime target(EmuTime::dummy());
322  if (t >= 0) {
323  EmuDuration d(t);
324  if (d < (now - EmuTime::zero)) {
325  target = now - d;
326  } else {
327  target = EmuTime::zero;
328  }
329  } else {
330  target = now + EmuDuration(-t);
331  }
332  goTo(target, novideo);
333 }
334 
335 void ReverseManager::goTo(array_ref<TclObject> tokens)
336 {
337  bool novideo;
338  double t;
339  auto& interp = motherBoard.getReactor().getInterpreter();
340  parseGoTo(interp, tokens, novideo, t);
341 
342  EmuTime target = EmuTime::zero + EmuDuration(t);
343  goTo(target, novideo);
344 }
345 
346 void ReverseManager::goTo(EmuTime::param target, bool novideo)
347 {
348  if (!isCollecting()) {
349  throw CommandException(
350  "Reverse was not enabled. First execute the 'reverse "
351  "start' command to start collecting data.");
352  }
353  goTo(target, novideo, history, true); // move in current time-line
354 }
355 
356 void ReverseManager::goTo(
357  EmuTime::param target, bool novideo, ReverseHistory& history,
358  bool sameTimeLine)
359 {
360  auto& mixer = motherBoard.getMSXMixer();
361  try {
362  // The call to MSXMotherBoard::fastForward() below may take
363  // some time to execute. The DirectX sound driver has a problem
364  // (not easily fixable) that it keeps on looping the sound
365  // buffer on buffer underruns (the SDL driver plays silence on
366  // underrun). At the end of this function we will switch to a
367  // different active MSXMotherBoard. So we can as well now
368  // already mute the current MSXMotherBoard.
369  mixer.mute();
370 
371  // -- Locate destination snapshot --
372  // We can't go back further in the past than the first snapshot.
373  assert(!history.chunks.empty());
374  auto it = begin(history.chunks);
375  EmuTime firstTime = it->second.time;
376  EmuTime targetTime = std::max(target, firstTime);
377  // Also don't go further into the future than 'end time'.
378  targetTime = std::min(targetTime, getEndTime(history));
379 
380  // Duration of 2 PAL frames. Possible improvement is to use the
381  // actual refresh rate (PAL/NTSC). But it should be the refresh
382  // rate of the active video chip (v99x8/v9990) at the target
383  // time. This is quite complex to get and the difference between
384  // 2 PAL and 2 NTSC frames isn't that big.
385  double dur2frames = 2.0 * (313.0 * 1368.0) / (3579545.0 * 6.0);
386  EmuDuration preDelta(novideo ? 0.0 : dur2frames);
387  EmuTime preTarget = ((targetTime - firstTime) > preDelta)
388  ? targetTime - preDelta
389  : firstTime;
390 
391  // find oldest snapshot that is not newer than requested time
392  // TODO ATM we do a linear search, could be improved to do a binary search.
393  assert(it->second.time <= preTarget); // first one is not newer
394  assert(it != end(history.chunks)); // there are snapshots
395  do {
396  ++it;
397  } while (it != end(history.chunks) &&
398  it->second.time <= preTarget);
399  // We found the first one that's newer, previous one is last
400  // one that's not newer (thus older or equal).
401  assert(it != begin(history.chunks));
402  --it;
403  EmuTime snapshotTime = it->second.time;
404  assert(snapshotTime <= preTarget);
405 
406  // IF current time is before the wanted time AND either
407  // - current time is closer than the closest (earlier) snapshot
408  // - OR current time is close enough (I arbitrarily choose 1s)
409  // THEN it's cheaper to start from the current position (and
410  // emulated forward) than to start from a snapshot
411  // THOUGH only when we're currently in the same time-line
412  // e.g. OK for a 'reverse goto' command, but not for a
413  // 'reverse loadreplay' command.
414  auto& reactor = motherBoard.getReactor();
415  EmuTime currentTime = getCurrentTime();
416  MSXMotherBoard* newBoard;
417  Reactor::Board newBoard_; // either nullptr or the same as newBoard
418  if (sameTimeLine &&
419  (currentTime <= preTarget) &&
420  ((snapshotTime <= currentTime) ||
421  ((preTarget - currentTime) < EmuDuration(1.0)))) {
422  newBoard = &motherBoard; // use current board
423  } else {
424  // Note: we don't (anymore) erase future snapshots
425  // -- restore old snapshot --
426  newBoard_ = reactor.createEmptyMotherBoard();
427  newBoard = newBoard_.get();
428  MemInputArchive in(it->second.savestate.data(),
429  it->second.savestate.size());
430  in.serialize("machine", *newBoard);
431 
432  if (eventDelay) {
433  // Handle all events that are scheduled, but not yet
434  // distributed. This makes sure no events get lost
435  // (important to keep host/msx keyboard in sync).
436  eventDelay->flush();
437  }
438 
439  // terminate replay log with EndLogEvent (if not there already)
440  if (history.events.empty() ||
441  !dynamic_cast<const EndLogEvent*>(history.events.back().get())) {
442  history.events.push_back(
443  std::make_shared<EndLogEvent>(currentTime));
444  }
445 
446  // Transfer history to the new ReverseManager.
447  // Also we should stop collecting in this ReverseManager,
448  // and start collecting in the new one.
449  auto& newManager = newBoard->getReverseManager();
450  newManager.transferHistory(history, it->second.eventCount);
451 
452  // transfer (or copy) state from old to new machine
453  transferState(*newBoard);
454 
455  // In case of load-replay it's possible we are not collecting,
456  // but calling stop() anyway is ok.
457  stop();
458  }
459 
460  // -- goto correct time within snapshot --
461  // fast forward 2 frames before target time
462  newBoard->fastForward(preTarget, true);
463 
464  // switch to the new MSXMotherBoard
465  // Note: this deletes the current MSXMotherBoard and
466  // ReverseManager. So we can't access those objects anymore.
467  bool unmute = true;
468  if (newBoard_) {
469  unmute = false;
470  reactor.replaceBoard(motherBoard, move(newBoard_));
471  }
472 
473  // Fast forward to actual target time with board activated.
474  // This makes sure the video output gets rendered.
475  newBoard->fastForward(targetTime, false);
476 
477  // In case we didn't actually create a new board, don't leave
478  // the (old) board muted.
479  if (unmute) {
480  mixer.unmute();
481  }
482 
483  //assert(!isCollecting()); // can't access 'this->' members anymore!
484  assert(newBoard->getReverseManager().isCollecting());
485  } catch (MSXException&) {
486  // Make sure mixer doesn't stay muted in case of error.
487  mixer.unmute();
488  throw;
489  }
490 }
491 
492 void ReverseManager::transferState(MSXMotherBoard& newBoard)
493 {
494  // Transfer viewonly mode
495  const auto& oldDistributor = motherBoard.getStateChangeDistributor();
496  auto& newDistributor = newBoard .getStateChangeDistributor();
497  newDistributor.setViewOnlyMode(oldDistributor.isViewOnlyMode());
498 
499  // transfer keyboard state
500  auto& newManager = newBoard.getReverseManager();
501  if (newManager.keyboard && keyboard) {
502  newManager.keyboard->transferHostKeyMatrix(*keyboard);
503  }
504 
505  // transfer watchpoints
506  newBoard.getDebugger().transfer(motherBoard.getDebugger());
507 
508  // copy rerecord count
509  newManager.reRecordCount = reRecordCount;
510 
511  // transfer settings
512  const auto& oldController = motherBoard.getMSXCommandController();
513  newBoard.getMSXCommandController().transferSettings(oldController);
514 }
515 
516 void ReverseManager::saveReplay(array_ref<TclObject> tokens, TclObject& result)
517 {
518  const auto& chunks = history.chunks;
519  if (chunks.empty()) {
520  throw CommandException("No recording...");
521  }
522 
523  string filename;
524  switch (tokens.size()) {
525  case 2:
526  // nothing
527  break;
528  case 3:
529  filename = tokens[2].getString().str();
530  break;
531  default:
532  throw SyntaxError();
533  }
535  filename, REPLAY_DIR, "openmsx", ".omr");
536 
537  auto& reactor = motherBoard.getReactor();
538  Replay replay(reactor);
539  replay.reRecordCount = reRecordCount;
540 
541  // store current time (possibly somewhere in the middle of the timeline)
542  // so that on load we can go back there
543  replay.currentTime = getCurrentTime();
544 
545  // restore first snapshot to be able to serialize it to a file
546  auto initialBoard = reactor.createEmptyMotherBoard();
547  MemInputArchive in(begin(chunks)->second.savestate.data(),
548  begin(chunks)->second.savestate.size());
549  in.serialize("machine", *initialBoard);
550  replay.motherBoards.push_back(move(initialBoard));
551 
552  // determine which extra snapshots to put in the replay
553  const auto& startTime = begin(chunks)->second.time;
554  const auto& endTime = chunks.rbegin()->second.time;
555  EmuDuration totalLength = endTime - startTime;
556  EmuDuration partitionLength = totalLength.divRoundUp(MAX_NOF_SNAPSHOTS);
557  partitionLength = std::max(MIN_PARTITION_LENGTH, partitionLength);
558  EmuTime nextPartitionEnd = startTime + partitionLength;
559  auto it = begin(chunks);
560  auto lastAddedIt = begin(chunks); // already added
561  while (it != end(chunks)) {
562  ++it;
563  if (it == end(chunks) || (it->second.time > nextPartitionEnd)) {
564  --it;
565  assert(it->second.time <= nextPartitionEnd);
566  if (it != lastAddedIt) {
567  // this is a new one, add it to the list of snapshots
568  Reactor::Board board = reactor.createEmptyMotherBoard();
569  MemInputArchive in(it->second.savestate.data(),
570  it->second.savestate.size());
571  in.serialize("machine", *board);
572  replay.motherBoards.push_back(move(board));
573  lastAddedIt = it;
574  }
575  ++it;
576  while (it != end(chunks) && it->second.time > nextPartitionEnd) {
577  nextPartitionEnd += partitionLength;
578  }
579  }
580  }
581  assert(lastAddedIt == --end(chunks)); // last snapshot must be included
582 
583  // add sentinel when there isn't one yet
584  bool addSentinel = history.events.empty() ||
585  !dynamic_cast<EndLogEvent*>(history.events.back().get());
586  if (addSentinel) {
588  history.events.push_back(std::make_shared<EndLogEvent>(
589  getCurrentTime()));
590  }
591  try {
592  XmlOutputArchive out(filename);
593  replay.events = &history.events;
594  out.serialize("replay", replay);
595  } catch (MSXException&) {
596  if (addSentinel) {
597  history.events.pop_back();
598  }
599  throw;
600  }
601 
602  if (addSentinel) {
603  // Is there a cleaner way to only add the sentinel in the log?
604  // I mean avoid changing/restoring the current log. We could
605  // make a copy and work on that, but that seems much less
606  // efficient.
607  history.events.pop_back();
608  }
609 
610  result.setString("Saved replay to " + filename);
611 }
612 
613 void ReverseManager::loadReplay(
614  Interpreter& interp, array_ref<TclObject> tokens, TclObject& result)
615 {
616  if (tokens.size() < 3) throw SyntaxError();
617 
618  vector<string> arguments;
619  const TclObject* whereArg = nullptr;
620  bool enableViewOnly = false;
621 
622  for (size_t i = 2; i < tokens.size(); ++i) {
623  string_ref token = tokens[i].getString();
624  if (token == "-viewonly") {
625  enableViewOnly = true;
626  } else if (token == "-goto") {
627  if (++i == tokens.size()) {
628  throw CommandException("Missing argument");
629  }
630  whereArg = &tokens[i];
631  } else {
632  arguments.push_back(token.str());
633  }
634  }
635 
636  if (arguments.size() != 1) throw SyntaxError();
637 
638  // resolve the filename
639  UserDataFileContext context(REPLAY_DIR);
640  string fileNameArg = arguments[0];
641  string filename;
642  try {
643  // Try filename as typed by user.
644  filename = context.resolve(fileNameArg);
645  } catch (MSXException& /*e1*/) { try {
646  // Not found, try adding '.omr'.
647  filename = context.resolve(fileNameArg + ".omr");
648  } catch (MSXException& e2) { try {
649  // Again not found, try adding '.gz'.
650  // (this is for backwards compatibility).
651  filename = context.resolve(fileNameArg + ".gz");
652  } catch (MSXException& /*e3*/) {
653  // Show error message that includes the default extension.
654  throw e2;
655  }}}
656 
657  // restore replay
658  auto& reactor = motherBoard.getReactor();
659  Replay replay(reactor);
660  Events events;
661  replay.events = &events;
662  try {
663  XmlInputArchive in(filename);
664  in.serialize("replay", replay);
665  } catch (XMLException& e) {
666  throw CommandException("Cannot load replay, bad file format: " + e.getMessage());
667  } catch (MSXException& e) {
668  throw CommandException("Cannot load replay: " + e.getMessage());
669  }
670 
671  // get destination time index
672  auto destination = EmuTime::zero;
673  string_ref where = whereArg ? whereArg->getString() : "begin";
674  if (where == "begin") {
675  destination = EmuTime::zero;
676  } else if (where == "end") {
677  destination = EmuTime::infinity;
678  } else if (where == "savetime") {
679  destination = replay.currentTime;
680  } else {
681  destination += EmuDuration(whereArg->getDouble(interp));
682  }
683 
684  // OK, we are going to be actually changing states now
685 
686  // now we can change the view only mode
687  motherBoard.getStateChangeDistributor().setViewOnlyMode(enableViewOnly);
688 
689  assert(!replay.motherBoards.empty());
690  auto& newReverseManager = replay.motherBoards[0]->getReverseManager();
691  auto& newHistory = newReverseManager.history;
692 
693  if (newReverseManager.reRecordCount == 0) {
694  // serialize Replay version >= 4
695  newReverseManager.reRecordCount = replay.reRecordCount;
696  } else {
697  // newReverseManager.reRecordCount is initialized via
698  // call from MSXMotherBoard to setReRecordCount()
699  }
700 
701  // Restore event log
702  swap(newHistory.events, events);
703  auto& newEvents = newHistory.events;
704 
705  // Restore snapshots
706  unsigned replayIndex = 0;
707  for (auto& m : replay.motherBoards) {
708  ReverseChunk newChunk;
709  newChunk.time = m->getCurrentTime();
710 
711  MemOutputArchive out;
712  out.serialize("machine", *m);
713  newChunk.savestate = out.releaseBuffer();
714 
715  // update replayIndex
716  // TODO: should we use <= instead??
717  while (replayIndex < newEvents.size() &&
718  (newEvents[replayIndex]->getTime() < newChunk.time)) {
719  replayIndex++;
720  }
721  newChunk.eventCount = replayIndex;
722 
723  newHistory.chunks[newHistory.getNextSeqNum(newChunk.time)] =
724  move(newChunk);
725  }
726 
727  // Note: untill this point we didn't make any changes to the current
728  // ReverseManager/MSXMotherBoard yet
729  reRecordCount = newReverseManager.reRecordCount;
730  bool novideo = false;
731  goTo(destination, novideo, newHistory, false); // move to different time-line
732 
733  result.setString("Loaded replay from " + filename);
734 }
735 
736 void ReverseManager::transferHistory(ReverseHistory& oldHistory,
737  unsigned oldEventCount)
738 {
739  assert(!isCollecting());
740  assert(history.chunks.empty());
741 
742  // actual history transfer
743  history.swap(oldHistory);
744 
745  // resume collecting (and event recording)
746  collecting = true;
747  schedule(getCurrentTime());
748  motherBoard.getStateChangeDistributor().registerRecorder(*this);
749 
750  // start replaying events
751  replayIndex = oldEventCount;
752  // replay log contains at least the EndLogEvent
753  assert(replayIndex < history.events.size());
754  replayNextEvent();
755 }
756 
757 void ReverseManager::executeUntil(EmuTime::param /*time*/, int userData)
758 {
759  switch (userData) {
760  case NEW_SNAPSHOT:
761  // During record we should take regular snapshots, and 'now'
762  // it's been a while since the last snapshot. But 'now' can be
763  // in the middle of a CPU instruction (1). However the CPU
764  // emulation code cannot handle taking snapshots at arbitrary
765  // moments in EmuTime (2)(3)(4). So instead we send out an
766  // event that indicates we want to take a snapshot (5).
767  // (1) Schedulables are executed at the exact requested
768  // EmuTime, even in the middle of a Z80 instruction.
769  // (2) The CPU code serializes all registers, current time and
770  // various other status info, but not enough info to be
771  // able to resume in the middle of an instruction.
772  // (3) Only the CPU has this limitation of not being able to
773  // take a snapshot at any EmuTime, all other devices can.
774  // This is because in our emulation model the CPU 'drives
775  // time forward'. It's the only device code that can be
776  // interrupted by other emulation code (via Schedulables).
777  // (4) In the past we had a CPU core that could execute/resume
778  // partial instructions (search SVN history). Though it was
779  // much more complex and it also ran slower than the
780  // current code.
781  // (5) Events are delivered from the Reactor code. That code
782  // only runs when the CPU code has exited (meaning no
783  // longer active in any stackframe). So it's executed right
784  // after the CPU has finished the current instruction. And
785  // that's OK, we only require regular snapshots here, they
786  // should not be *exactly* equally far apart in time.
787  pendingTakeSnapshot = true;
788  eventDistributor.distributeEvent(
789  std::make_shared<SimpleEvent>(OPENMSX_TAKE_REVERSE_SNAPSHOT));
790  break;
791  case INPUT_EVENT:
792  auto event = history.events[replayIndex];
793  try {
794  // deliver current event at current time
795  motherBoard.getStateChangeDistributor().distributeReplay(event);
796  } catch (MSXException&) {
797  // can throw in case we replay a command that fails
798  // ignore
799  }
800  if (!dynamic_cast<const EndLogEvent*>(event.get())) {
801  ++replayIndex;
802  replayNextEvent();
803  } else {
804  assert(!isReplaying()); // stopped by replay of EndLogEvent
805  }
806  break;
807  }
808 }
809 
810 int ReverseManager::signalEvent(const shared_ptr<const Event>& event)
811 {
812  (void)event;
813  assert(event->getType() == OPENMSX_TAKE_REVERSE_SNAPSHOT);
814 
815  // This event is send to all MSX machines, make sure it's actually this
816  // machine that requested the snapshot.
817  if (pendingTakeSnapshot) {
818  pendingTakeSnapshot = false;
819  takeSnapshot(getCurrentTime());
820  }
821  return 0;
822 }
823 
824 unsigned ReverseManager::ReverseHistory::getNextSeqNum(EmuTime::param time) const
825 {
826  if (chunks.empty()) {
827  return 1;
828  }
829  const auto& startTime = begin(chunks)->second.time;
830  double duration = (time - startTime).toDouble();
831  return unsigned(duration / SNAPSHOT_PERIOD + 0.5) + 1;
832 }
833 
834 void ReverseManager::takeSnapshot(EmuTime::param time)
835 {
836  // (possibly) drop old snapshots
837  // TODO does snapshot pruning still happen correctly (often enough)
838  // when going back/forward in time?
839  unsigned seqNum = history.getNextSeqNum(time);
840  dropOldSnapshots<25>(seqNum);
841 
842  // During replay we might already have a snapshot with the current
843  // sequence number, though this snapshot does not necessarily have the
844  // exact same EmuTime (because we don't (re)start taking snapshots at
845  // the same moment in time).
846 
847  // actually create new snapshot
848  MemOutputArchive out;
849  out.serialize("machine", motherBoard);
850  ReverseChunk& newChunk = history.chunks[seqNum];
851  newChunk.time = time;
852  newChunk.savestate = out.releaseBuffer();
853  newChunk.eventCount = replayIndex;
854 
855  // schedule creation of next snapshot
856  schedule(getCurrentTime());
857 }
858 
859 void ReverseManager::replayNextEvent()
860 {
861  // schedule next event at its own time
862  assert(replayIndex < history.events.size());
863  setSyncPoint(history.events[replayIndex]->getTime(), INPUT_EVENT);
864 }
865 
866 void ReverseManager::signalStateChange(const shared_ptr<StateChange>& event)
867 {
868  if (isReplaying()) {
869  // this is an event we just replayed
870  assert(event == history.events[replayIndex]);
871  if (dynamic_cast<EndLogEvent*>(event.get())) {
872  signalStopReplay(event->getTime());
873  } else {
874  // ignore all other events
875  }
876  } else {
877  // record event
878  history.events.push_back(event);
879  ++replayIndex;
880  assert(!isReplaying());
881  }
882 }
883 
884 void ReverseManager::signalStopReplay(EmuTime::param time)
885 {
886  motherBoard.getStateChangeDistributor().stopReplay(time);
887  // this is needed to prevent a reRecordCount increase
888  // due to this action ending the replay
889  reRecordCount--;
890 }
891 
892 void ReverseManager::stopReplay(EmuTime::param time)
893 {
894  if (isReplaying()) {
895  // if we're replaying, stop it and erase remainder of event log
897  Events& events = history.events;
898  events.erase(begin(events) + replayIndex, end(events));
899  // search snapshots that are newer than 'time' and erase them
900  auto it = find_if(begin(history.chunks), end(history.chunks),
901  [&](Chunks::value_type& p) { return p.second.time > time; });
902  history.chunks.erase(it, end(history.chunks));
903  // this also means someone is changing history, record that
904  reRecordCount++;
905  }
906  assert(!isReplaying());
907 }
908 
909 /* Should be called each time a new snapshot is added.
910  * This function will erase zero or more earlier snapshots so that there are
911  * more snapshots of recent history and less of distant history. It has the
912  * following properties:
913  * - the very oldest snapshot is never deleted
914  * - it keeps the N or N+1 most recent snapshots (snapshot distance = 1)
915  * - then it keeps N or N+1 with snapshot distance 2
916  * - then N or N+1 with snapshot distance 4
917  * - ... and so on
918  * @param count The index of the just added (or about to be added) element.
919  * First element should have index 1.
920  */
921 template<unsigned N>
922 void ReverseManager::dropOldSnapshots(unsigned count)
923 {
924  unsigned y = (count + N - 1) ^ (count + N);
925  unsigned d = N;
926  unsigned d2 = 2 * N + 1;
927  while (true) {
928  y >>= 1;
929  if ((y == 0) || (count <= d)) return;
930  history.chunks.erase(count - d);
931  d += d2;
932  d2 *= 2;
933  }
934 }
935 
936 void ReverseManager::schedule(EmuTime::param time)
937 {
938  setSyncPoint(time + EmuDuration(SNAPSHOT_PERIOD), NEW_SNAPSHOT);
939 }
940 
941 
942 // class ReverseCmd
943 
945  : Command(controller, "reverse")
946  , manager(manager_)
947 {
948 }
949 
951 {
952  if (tokens.size() < 2) {
953  throw CommandException("Missing subcommand");
954  }
955  auto& interp = getInterpreter();
956  string_ref subcommand = tokens[1].getString();
957  if (subcommand == "start") {
958  manager.start();
959  } else if (subcommand == "stop") {
960  manager.stop();
961  } else if (subcommand == "status") {
962  manager.status(result);
963  } else if (subcommand == "debug") {
964  manager.debugInfo(result);
965  } else if (subcommand == "goback") {
966  manager.goBack(tokens);
967  } else if (subcommand == "goto") {
968  manager.goTo(tokens);
969  } else if (subcommand == "savereplay") {
970  return manager.saveReplay(tokens, result);
971  } else if (subcommand == "loadreplay") {
972  return manager.loadReplay(interp, tokens, result);
973  } else if (subcommand == "viewonlymode") {
974  auto& distributor = manager.motherBoard.getStateChangeDistributor();
975  switch (tokens.size()) {
976  case 2:
977  result.setString(distributor.isViewOnlyMode() ? "true" : "false");
978  break;
979  case 3:
980  distributor.setViewOnlyMode(tokens[2].getBoolean(interp));
981  break;
982  default:
983  throw SyntaxError();
984  }
985  } else if (subcommand == "truncatereplay") {
986  if (manager.isReplaying()) {
987  manager.signalStopReplay(manager.getCurrentTime());
988  }
989  } else {
990  throw CommandException("Invalid subcommand: " + subcommand);
991  }
992 }
993 
994 string ReverseCmd::help(const vector<string>& /*tokens*/) const
995 {
996  return "start start collecting reverse data\n"
997  "stop stop collecting\n"
998  "status show various status info on reverse\n"
999  "goback <n> go back <n> seconds in time\n"
1000  "goto <time> go to an absolute moment in time\n"
1001  "viewonlymode <bool> switch viewonly mode on or off\n"
1002  "truncatereplay stop replaying and remove all 'future' data\n"
1003  "savereplay [<name>] save the first snapshot and all replay data as a 'replay' (with optional name)\n"
1004  "loadreplay [-goto <begin|end|savetime|<n>>] [-viewonly] <name> load a replay (snapshot and replay data) with given name and start replaying\n";
1005 }
1006 
1007 void ReverseCmd::tabCompletion(vector<string>& tokens) const
1008 {
1009  if (tokens.size() == 2) {
1010  static const char* const subCommands[] = {
1011  "start", "stop", "status", "goback", "goto",
1012  "savereplay", "loadreplay", "viewonlymode",
1013  "truncatereplay",
1014  };
1015  completeString(tokens, subCommands);
1016  } else if ((tokens.size() == 3) || (tokens[1] == "loadreplay")) {
1017  if (tokens[1] == "loadreplay" || tokens[1] == "savereplay") {
1018  std::vector<const char*> cmds;
1019  if (tokens[1] == "loadreplay") {
1020  cmds = { "-goto", "-viewonly" };
1021  }
1022  UserDataFileContext context(REPLAY_DIR);
1023  completeFileName(tokens, context, cmds);
1024  } else if (tokens[1] == "viewonlymode") {
1025  static const char* const options[] = { "true", "false" };
1026  completeString(tokens, options);
1027  }
1028  }
1029 }
1030 
1031 } // namespace openmsx
void transferSettings(const MSXCommandController &from)
Transfer setting values from one machine to another, used for during 'reverse'.
Contains the main loop of openMSX.
Definition: Reactor.hh:62
void mute()
TODO This methods (un)mute the sound.
Definition: MSXMixer.cc:724
string_ref::const_iterator end(const string_ref &x)
Definition: string_ref.hh:135
string help(const vector< string > &tokens) const override
Print help for this command.
size_type size() const
Definition: array_ref.hh:61
std::string str() const
Definition: string_ref.cc:10
static param dummy()
Definition: EmuTime.hh:21
void registerEventListener(EventType type, EventListener &listener, Priority priority=OTHER)
Registers a given object to receive certain events.
void execute(array_ref< TclObject > tokens, TclObject &result) override
Execute this command.
void unregisterEventListener(EventType type, EventListener &listener)
Unregisters a previously registered event listener.
void tabCompletion(vector< string > &tokens) const override
Attempt tab completion for this command.
void distributeEvent(const EventPtr &event)
Schedule the given event for delivery.
EndLogEvent(EmuTime::param time)
void setSyncPoint(EmuTime::param timestamp, int userData=0)
Definition: Schedulable.cc:25
This class implements a subset of the proposal for std::string_ref (proposed for the next c++ standar...
Definition: string_ref.hh:18
Used to schedule 'taking reverse snapshots' between Z80 instructions.
Definition: Event.hh:43
unsigned reRecordCount
void stopReplay(EmuTime::param time)
Explicitly stop replay.
void unregisterRecorder(StateChangeRecorder &recorder)
static void completeFileName(std::vector< std::string > &tokens, const FileContext &context, const RANGE &extra)
Definition: Completer.hh:102
bool removeSyncPoint(int userData=0)
Definition: Schedulable.cc:30
Every class that wants to get scheduled at some point must inherit from this class.
Definition: Schedulable.hh:16
void registerRecorder(StateChangeRecorder &recorder)
(Un)registers the given object to receive state change events.
REGISTER_POLYMORPHIC_CLASS(DiskContainer, NowindRomDisk,"NowindRomDisk")
This class implements a subset of the proposal for std::array_ref (proposed for the next c++ standard...
Definition: array_ref.hh:19
std::unique_ptr< Context > context
Definition: GLContext.cc:9
SERIALIZE_CLASS_VERSION(CassettePlayer, 2)
void distributeReplay(const EventPtr &event)
ReverseManager::Events * events
ReverseManager(MSXMotherBoard &motherBoard)
string parseCommandFileArgument(string_ref argument, string_ref directory, string_ref prefix, string_ref extension)
Helper function for parsing filename arguments in Tcl commands.
static const EmuTime infinity
Definition: EmuTime.hh:58
std::unique_ptr< MSXMotherBoard > Board
Definition: Reactor.hh:106
EmuTime::param getCurrentTime() const
Convenience method: This is the same as getScheduler().getCurrentTime().
Definition: Schedulable.cc:51
const EmuTime & param
Definition: EmuTime.hh:20
Interpreter & getInterpreter() const
Definition: Command.cc:47
ReverseCmd(ReverseManager &manager, CommandController &controller)
void serialize(Archive &ar, unsigned version)
eventDistributor(eventDistributor_)
StateChangeDistributor & getStateChangeDistributor()
Replay(Reactor &reactor_)
static const EmuTime zero
Definition: EmuTime.hh:57
MSXCommandController & getMSXCommandController()
static void completeString(std::vector< std::string > &tokens, const RANGE &possibleValues, bool caseSensitive=true)
Definition: Completer.hh:88
void setString(string_ref value)
Definition: TclObject.cc:55
Base class for all external MSX state changing events.
Definition: StateChange.hh:14
void serialize(Archive &ar, unsigned version)
std::vector< Reactor::Board > motherBoards
Board createEmptyMotherBoard()
Definition: Reactor.cc:361
void serialize(Archive &ar, unsigned)
string_ref::const_iterator begin(const string_ref &x)
Definition: string_ref.hh:134
std::unique_ptr< T > make_unique()
Definition: memory.hh:27
XRange< T > xrange(T e)
Definition: xrange.hh:98
void setViewOnlyMode(bool value)
Set viewOnlyMode.
Interpreter & getInterpreter()
Definition: Reactor.cc:273