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