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