openMSX
CassettePlayer.cc
Go to the documentation of this file.
1 // TODO:
2 // - improve consistency when a reset occurs: tape is removed when you were
3 // recording, but it is not removed when you were playing
4 // - specify prefix for auto file name generation when recording (setting?)
5 // - append to existing wav files when recording (record command), but this is
6 // basically a special case (pointer at the end) of:
7 // - (partly) overwrite an existing wav file from any given time index
8 // - seek in cassette images for the next and previous file (using empty space?)
9 // - (partly) overwrite existing wav files with new tape data (not very hi prio)
10 // - handle read-only cassette images (e.g.: CAS images or WAV files with a RO
11 // flag): refuse to go to record mode when those are selected
12 // - smartly auto-set the position of tapes: if you insert an existing WAV
13 // file, it will have the position at the start, assuming PLAY mode by
14 // default. When specifiying record mode at insert (somehow), it should be
15 // at the back.
16 // Alternatively, we could remember the index in tape images by storing the
17 // index in some persistent data file with its SHA1 sum as it was as we last
18 // saw it. When there are write actions to the tape, the hash has to be
19 // recalculated and replaced in the data file. An optimization would be to
20 // first simply check on the length of the file and fall back to SHA1 if that
21 // results in multiple matches.
22 
23 #include "CassettePlayer.hh"
24 #include "Connector.hh"
25 #include "CassettePort.hh"
26 #include "CommandController.hh"
27 #include "DeviceConfig.hh"
28 #include "HardwareConfig.hh"
29 #include "XMLElement.hh"
30 #include "FileContext.hh"
31 #include "FilePool.hh"
32 #include "File.hh"
33 #include "WavImage.hh"
34 #include "CasImage.hh"
35 #include "CliComm.hh"
36 #include "MSXMotherBoard.hh"
37 #include "Reactor.hh"
38 #include "GlobalSettings.hh"
39 #include "CommandException.hh"
40 #include "EventDistributor.hh"
41 #include "FileOperations.hh"
42 #include "WavWriter.hh"
43 #include "TclObject.hh"
44 #include "DynamicClock.hh"
45 #include "EmuDuration.hh"
46 #include "serialize.hh"
47 #include "unreachable.hh"
48 #include <algorithm>
49 #include <cassert>
50 #include <memory>
51 
52 using std::string;
53 using std::vector;
54 
55 namespace openmsx {
56 
57 static const unsigned DUMMY_INPUT_RATE = 44100; // actual rate depends on .cas/.wav file
58 static const unsigned RECORD_FREQ = 44100;
59 static const double OUTPUT_AMP = 60.0;
60 
61 static XMLElement createXML()
62 {
63  XMLElement xml("cassetteplayer");
64  xml.addChild("sound").addChild("volume", "5000");
65  return xml;
66 }
67 
69  : ResampledSoundDevice(hwConf.getMotherBoard(), getName(), getDescription(), 1, DUMMY_INPUT_RATE, false)
70  , syncEndOfTape(hwConf.getMotherBoard().getScheduler())
71  , syncAudioEmu (hwConf.getMotherBoard().getScheduler())
72  , tapePos(EmuTime::zero)
73  , prevSyncTime(EmuTime::zero)
74  , audioPos(0)
75  , motherBoard(hwConf.getMotherBoard())
76  , tapeCommand(
77  motherBoard.getCommandController(),
78  motherBoard.getStateChangeDistributor(),
79  motherBoard.getScheduler())
80  , loadingIndicator(
81  motherBoard.getReactor().getGlobalSettings().getThrottleManager())
82  , autoRunSetting(
83  motherBoard.getCommandController(),
84  "autoruncassettes", "automatically try to run cassettes", true)
85  , sampcnt(0)
86  , state(STOP)
87  , lastOutput(false)
88  , motor(false), motorControl(true)
89  , syncScheduled(false)
90 {
91  removeTape(EmuTime::zero);
92 
93  static XMLElement xml = createXML();
94  registerSound(DeviceConfig(hwConf, xml));
95 
97  OPENMSX_BOOT_EVENT, *this);
98  motherBoard.getMSXCliComm().update(CliComm::HARDWARE, getName(), "add");
99 }
100 
102 {
103  unregisterSound();
104  if (auto* c = getConnector()) {
105  c->unplug(getCurrentTime());
106  }
108  OPENMSX_BOOT_EVENT, *this);
109  motherBoard.getMSXCliComm().update(CliComm::HARDWARE, getName(), "remove");
110 }
111 
112 void CassettePlayer::autoRun()
113 {
114  if (!playImage) return;
115 
116  // try to automatically run the tape, if that's set
117  CassetteImage::FileType type = playImage->getFirstFileType();
118  if (!autoRunSetting.getBoolean() || type == CassetteImage::UNKNOWN) {
119  return;
120  }
121  string instr1, instr2;
122  switch (type) {
124  instr1 = R"(RUN\"CAS:\")";
125  break;
127  instr1 = R"(BLOAD\"CAS:\",R)";
128  break;
130  // Note that CLOAD:RUN won't work: BASIC ignores stuff
131  // after the CLOAD command. That's why it's split in two.
132  instr1 = "CLOAD";
133  instr2 = "RUN";
134  break;
135  default:
136  UNREACHABLE; // Shouldn't be possible
137  }
138  string command = strCat(
139  "namespace eval ::openmsx {\n"
140  " variable auto_run_bp\n"
141 
142  " proc auto_run_cb {args} {\n"
143  " variable auto_run_bp\n"
144  " debug remove_bp $auto_run_bp\n"
145  " unset auto_run_bp\n"
146 
147  // Without the 0.1s delay here, the type command gets messed up
148  // on MSX1 machines for some reason (starting to type too early?)
149  " after time 0.1 \"type [lindex $args 0]\\\\r\"\n"
150 
151  " set next [lrange $args 1 end]\n"
152  " if {[llength $next] == 0} return\n"
153 
154  // H_READ isn't called after CLOAD, but H_MAIN is. However, it's
155  // also called right after H_READ, so we wait a little before
156  // setting up the breakpoint.
157  " set cmd1 \"openmsx::auto_run_cb $next\"\n"
158  " set cmd2 \"set openmsx::auto_run_bp \\[debug set_bp 0xFF0C 1 \\\"$cmd1\\\"\\]\"\n" // H_MAIN
159  " after time 0.2 $cmd2\n"
160  " }\n"
161 
162  " if {[info exists auto_run_bp]} {debug remove_bp $auto_run_bp\n}\n"
163  " set auto_run_bp [debug set_bp 0xFF07 1 {\n" // H_READ
164  " openmsx::auto_run_cb ", instr1, ' ', instr2, "\n"
165  " }]\n"
166 
167  // re-trigger hook(s), needed when already booted in BASIC
168  " type_via_keyboard \'\\r\n"
169  "}");
170  try {
171  motherBoard.getCommandController().executeCommand(command);
172  } catch (CommandException& e) {
173  motherBoard.getMSXCliComm().printWarning(
174  "Error executing loading instruction using command \"",
175  command, "\" for AutoRun: ",
176  e.getMessage(), "\n Please report a bug.");
177  }
178 }
179 
180 string CassettePlayer::getStateString() const
181 {
182  switch (getState()) {
183  case PLAY: return "play";
184  case RECORD: return "record";
185  case STOP: return "stop";
186  }
187  UNREACHABLE; return {};
188 }
189 
190 bool CassettePlayer::isRolling() const
191 {
192  // Is the tape 'rolling'?
193  // is true when:
194  // not in stop mode (there is a tape inserted and not at end-of-tape)
195  // AND [ user forced playing (motorcontrol=off) OR motor enabled by
196  // software (motor=on) ]
197  return (getState() != STOP) && (motor || !motorControl);
198 }
199 
200 double CassettePlayer::getTapePos(EmuTime::param time)
201 {
202  sync(time);
203  return (tapePos - EmuTime::zero).toDouble();
204 }
205 
206 double CassettePlayer::getTapeLength(EmuTime::param time)
207 {
208  if (playImage) {
209  return (playImage->getEndTime() - EmuTime::zero).toDouble();
210  } else if (getState() == RECORD) {
211  return getTapePos(time);
212  } else {
213  return 0.0;
214  }
215 }
216 
217 void CassettePlayer::checkInvariants() const
218 {
219  switch (getState()) {
220  case STOP:
221  assert(!recordImage);
222  if (playImage) {
223  // we're at end-of tape
224  assert(!getImageName().empty());
225  } else {
226  // no tape inserted, imageName may or may not be empty
227  }
228  break;
229  case PLAY:
230  assert(!getImageName().empty());
231  assert(!recordImage);
232  assert(playImage);
233  break;
234  case RECORD:
235  assert(!getImageName().empty());
236  assert(recordImage);
237  assert(!playImage);
238  break;
239  default:
240  UNREACHABLE;
241  }
242 }
243 
244 void CassettePlayer::setState(State newState, const Filename& newImage,
245  EmuTime::param time)
246 {
247  sync(time);
248 
249  // set new state if different from old state
250  State oldState = getState();
251  if (oldState == newState) return;
252 
253  // cannot directly switch from PLAY to RECORD or vice-versa,
254  // (should always go via STOP)
255  assert(!((oldState == PLAY) && (newState == RECORD)));
256  assert(!((oldState == RECORD) && (newState == PLAY)));
257 
258  // stuff for leaving the old state
259  // 'recordImage==nullptr' can happen in case of loadstate.
260  if ((oldState == RECORD) && recordImage) {
261  flushOutput();
262  bool empty = recordImage->isEmpty();
263  recordImage.reset();
264  if (empty) {
265  // delete the created WAV file, as it is useless
266  FileOperations::unlink(getImageName().getResolved()); // ignore errors
267  setImageName(Filename());
268  }
269  }
270 
271  // actually switch state
272  state = newState;
273  setImageName(newImage);
274 
275  // stuff for entering the new state
276  if (newState == RECORD) {
277  partialOut = 0.0;
278  partialInterval = 0.0;
279  lastX = lastOutput ? OUTPUT_AMP : -OUTPUT_AMP;
280  lastY = 0.0;
281  }
282  motherBoard.getMSXCliComm().update(
283  CliComm::STATUS, "cassetteplayer", getStateString());
284 
285  updateLoadingState(time); // sets SP for tape-end detection
286 
287  checkInvariants();
288 }
289 
290 void CassettePlayer::updateLoadingState(EmuTime::param time)
291 {
292  assert(prevSyncTime == time); // sync() must be called
293  // TODO also set loadingIndicator for RECORD?
294  // note: we don't use isRolling()
295  loadingIndicator.update(motor && (getState() == PLAY));
296 
297  syncEndOfTape.removeSyncPoint();
298  if (isRolling() && (getState() == PLAY)) {
299  syncEndOfTape.setSyncPoint(time + (playImage->getEndTime() - tapePos));
300  }
301 }
302 
303 void CassettePlayer::setImageName(const Filename& newImage)
304 {
305  casImage = newImage;
306  motherBoard.getMSXCliComm().update(
307  CliComm::MEDIA, "cassetteplayer", casImage.getResolved());
308 }
309 
310 void CassettePlayer::insertTape(const Filename& filename, EmuTime::param time)
311 {
312  if (!filename.empty()) {
313  FilePool& filePool = motherBoard.getReactor().getFilePool();
314  try {
315  // first try WAV
316  playImage = std::make_unique<WavImage>(filename, filePool);
317  } catch (MSXException& e) {
318  try {
319  // if that fails use CAS
320  playImage = std::make_unique<CasImage>(
321  filename, filePool,
322  motherBoard.getMSXCliComm());
323  } catch (MSXException& e2) {
324  throw MSXException(
325  "Failed to insert WAV image: \"",
326  e.getMessage(),
327  "\" and also failed to insert CAS image: \"",
328  e2.getMessage(), '\"');
329  }
330  }
331  } else {
332  // This is a bit tricky, consider this scenario: we switch from
333  // RECORD->PLAY, but we didn't actually record anything: The
334  // removeTape() call above (indirectly) deletes the empty
335  // recorded wav image and also clears imageName. Now because
336  // the 'filename' parameter is passed by reference, and because
337  // getImageName() returns a reference, this 'filename'
338  // parameter now also is an empty string.
339  }
340 
341  // possibly recreate resampler
342  unsigned inputRate = playImage ? playImage->getFrequency() : 44100;
343  if (inputRate != getInputRate()) {
344  setInputRate(inputRate);
345  createResampler();
346  }
347 
348  // trigger (re-)query of getAmplificationFactorImpl()
349  setSoftwareVolume(1.0f, time);
350 
351  setImageName(filename);
352 }
353 
354 void CassettePlayer::playTape(const Filename& filename, EmuTime::param time)
355 {
356  // Temporally go to STOP state:
357  // RECORD: First close the recorded image. Otherwise it goes wrong
358  // if you switch from RECORD->PLAY on the same image.
359  // PLAY: Go to stop because we temporally violate some invariants
360  // (tapePos can be beyond end-of-tape).
361  setState(STOP, getImageName(), time); // keep current image
362  insertTape(filename, time);
363  rewind(time); // sets PLAY mode
364  autoRun();
365 }
366 
367 void CassettePlayer::rewind(EmuTime::param time)
368 {
369  sync(time); // before tapePos changes
370  assert(getState() != RECORD);
371  tapePos = EmuTime::zero;
372  audioPos = 0;
373 
374  if (getImageName().empty()) {
375  // no image inserted, do nothing
376  assert(getState() == STOP);
377  } else {
378  // keep current image
379  setState(PLAY, getImageName(), time);
380  }
381  updateLoadingState(time);
382 }
383 
384 void CassettePlayer::recordTape(const Filename& filename, EmuTime::param time)
385 {
386  removeTape(time); // flush (possible) previous recording
387  recordImage = std::make_unique<Wav8Writer>(filename, 1, RECORD_FREQ);
388  tapePos = EmuTime::zero;
389  setState(RECORD, filename, time);
390 }
391 
392 void CassettePlayer::removeTape(EmuTime::param time)
393 {
394  sync(time); // before tapePos changes
395  playImage.reset();
396  tapePos = EmuTime::zero;
397  setState(STOP, Filename(), time);
398 }
399 
400 void CassettePlayer::setMotor(bool status, EmuTime::param time)
401 {
402  if (status != motor) {
403  sync(time);
404  motor = status;
405  updateLoadingState(time);
406  }
407 }
408 
409 void CassettePlayer::setMotorControl(bool status, EmuTime::param time)
410 {
411  if (status != motorControl) {
412  sync(time);
413  motorControl = status;
414  updateLoadingState(time);
415  }
416 }
417 
418 int16_t CassettePlayer::readSample(EmuTime::param time)
419 {
420  if (getState() == PLAY) {
421  // playing
422  sync(time);
423  return isRolling() ? playImage->getSampleAt(tapePos) : 0;
424  } else {
425  // record or stop
426  return 0;
427  }
428 }
429 
430 void CassettePlayer::setSignal(bool output, EmuTime::param time)
431 {
432  sync(time);
433  lastOutput = output;
434 }
435 
436 void CassettePlayer::sync(EmuTime::param time)
437 {
438  EmuDuration duration = time - prevSyncTime;
439  prevSyncTime = time;
440 
441  updateTapePosition(duration, time);
442  generateRecordOutput(duration);
443 }
444 
445 void CassettePlayer::updateTapePosition(
446  EmuDuration::param duration, EmuTime::param time)
447 {
448  if (!isRolling() || (getState() != PLAY)) return;
449 
450  tapePos += duration;
451  assert(tapePos <= playImage->getEndTime());
452 
453  // synchronize audio with actual tape position
454  if (!syncScheduled) {
455  // don't sync too often, this improves sound quality
456  syncScheduled = true;
457  syncAudioEmu.setSyncPoint(time + EmuDuration::sec(1));
458  }
459 }
460 
461 void CassettePlayer::generateRecordOutput(EmuDuration::param duration)
462 {
463  if (!recordImage || !isRolling()) return;
464 
465  double out = lastOutput ? OUTPUT_AMP : -OUTPUT_AMP;
466  double samples = duration.toDouble() * RECORD_FREQ;
467  double rest = 1.0 - partialInterval;
468  if (rest <= samples) {
469  // enough to fill next interval
470  partialOut += out * rest;
471  fillBuf(1, int(partialOut));
472  samples -= rest;
473 
474  // fill complete intervals
475  int count = int(samples);
476  if (count > 0) {
477  fillBuf(count, int(out));
478  }
479  samples -= count;
480 
481  // partial last interval
482  partialOut = samples * out;
483  partialInterval = 0.0;
484  } else {
485  partialOut += samples * out;
486  partialInterval += samples;
487  }
488 }
489 
490 void CassettePlayer::fillBuf(size_t length, double x)
491 {
492  assert(recordImage);
493  static const double A = 252.0 / 256.0;
494 
495  double y = lastY + (x - lastX);
496 
497  while (length) {
498  size_t len = std::min(length, BUF_SIZE - sampcnt);
499  for (size_t j = 0; j < len; ++j) {
500  buf[sampcnt++] = int(y) + 128;
501  y *= A;
502  }
503  length -= len;
504  assert(sampcnt <= BUF_SIZE);
505  if (BUF_SIZE == sampcnt) {
506  flushOutput();
507  }
508  }
509  lastY = y;
510  lastX = x;
511 }
512 
513 void CassettePlayer::flushOutput()
514 {
515  try {
516  recordImage->write(buf, 1, unsigned(sampcnt));
517  sampcnt = 0;
518  recordImage->flush(); // update wav header
519  } catch (MSXException& e) {
520  motherBoard.getMSXCliComm().printWarning(
521  "Failed to write to tape: ", e.getMessage());
522  }
523 }
524 
525 
526 const string& CassettePlayer::getName() const
527 {
528  static const string pluggableName("cassetteplayer");
529  return pluggableName;
530 }
531 
533 {
534  // TODO: this description is not entirely accurate, but it is used
535  // as an identifier for this audio device in e.g. Catapult. We should
536  // use another way to identify audio devices A.S.A.P.!
537 
538  return "Cassetteplayer, use to read .cas or .wav files.";
539 }
540 
541 void CassettePlayer::plugHelper(Connector& conn, EmuTime::param time)
542 {
543  sync(time);
544  lastOutput = static_cast<CassettePort&>(conn).lastOut();
545 }
546 
547 void CassettePlayer::unplugHelper(EmuTime::param time)
548 {
549  // note: may not throw exceptions
550  setState(STOP, getImageName(), time); // keep current image
551 }
552 
553 
554 void CassettePlayer::generateChannels(float** buffers, unsigned num)
555 {
556  // Single channel device: replace content of buffers[0] (not add to it).
557  if ((getState() != PLAY) || !isRolling()) {
558  buffers[0] = nullptr;
559  return;
560  }
561  playImage->fillBuffer(audioPos, buffers, num);
562  audioPos += num;
563 }
564 
566 {
567  return playImage ? playImage->getAmplificationFactorImpl() : 1.0f;
568 }
569 
570 int CassettePlayer::signalEvent(const std::shared_ptr<const Event>& event)
571 {
572  if (event->getType() == OPENMSX_BOOT_EVENT) {
573  if (!getImageName().empty()) {
574  // Reinsert tape to make sure everything is reset.
575  try {
576  playTape(getImageName(), getCurrentTime());
577  } catch (MSXException& e) {
578  motherBoard.getMSXCliComm().printWarning(
579  "Failed to insert tape: ", e.getMessage());
580  }
581  }
582  }
583  return 0;
584 }
585 
586 void CassettePlayer::execEndOfTape(EmuTime::param time)
587 {
588  // tape ended
589  sync(time);
590  assert(tapePos == playImage->getEndTime());
591  motherBoard.getMSXCliComm().printWarning(
592  "Tape end reached... stopping. "
593  "You may need to insert another tape image "
594  "that contains side B. (Or you used the wrong "
595  "loading command.)");
596  setState(STOP, getImageName(), time); // keep current image
597 }
598 
599 void CassettePlayer::execSyncAudioEmu(EmuTime::param time)
600 {
601  if (getState() == PLAY) {
602  updateStream(time);
603  sync(time);
604  DynamicClock clk(EmuTime::zero);
605  clk.setFreq(playImage->getFrequency());
606  audioPos = clk.getTicksTill(tapePos);
607  }
608  syncScheduled = false;
609 }
610 
611 
612 // class TapeCommand
613 
614 CassettePlayer::TapeCommand::TapeCommand(
615  CommandController& commandController_,
616  StateChangeDistributor& stateChangeDistributor_,
617  Scheduler& scheduler_)
618  : RecordedCommand(commandController_, stateChangeDistributor_,
619  scheduler_, "cassetteplayer")
620 {
621 }
622 
623 void CassettePlayer::TapeCommand::execute(
624  span<const TclObject> tokens, TclObject& result, EmuTime::param time)
625 {
626  auto& cassettePlayer = OUTER(CassettePlayer, tapeCommand);
627  if (tokens.size() == 1) {
628  // Returning Tcl lists here, similar to the disk commands in
629  // DiskChanger
630  TclObject options = makeTclList(cassettePlayer.getStateString());
631  result.addListElement(getName() + ':',
632  cassettePlayer.getImageName().getResolved(),
633  options);
634 
635  } else if (tokens[1] == "new") {
636  string directory = "taperecordings";
637  string prefix = "openmsx";
638  string extension = ".wav";
640  (tokens.size() == 3) ? tokens[2].getString() : string{},
641  directory, prefix, extension);
642  cassettePlayer.recordTape(Filename(filename), time);
643  result = strCat(
644  "Created new cassette image file: ", filename,
645  ", inserted it and set recording mode.");
646 
647  } else if (tokens[1] == "insert" && tokens.size() == 3) {
648  try {
649  result = "Changing tape";
650  Filename filename(tokens[2].getString().str(), userFileContext());
651  cassettePlayer.playTape(filename, time);
652  } catch (MSXException& e) {
653  throw CommandException(std::move(e).getMessage());
654  }
655 
656  } else if (tokens[1] == "motorcontrol" && tokens.size() == 3) {
657  if (tokens[2] == "on") {
658  cassettePlayer.setMotorControl(true, time);
659  result = "Motor control enabled.";
660  } else if (tokens[2] == "off") {
661  cassettePlayer.setMotorControl(false, time);
662  result = "Motor control disabled.";
663  } else {
664  throw SyntaxError();
665  }
666 
667  } else if (tokens.size() != 2) {
668  throw SyntaxError();
669 
670  } else if (tokens[1] == "motorcontrol") {
671  result = strCat("Motor control is ",
672  (cassettePlayer.motorControl ? "on" : "off"));
673 
674  } else if (tokens[1] == "record") {
675  result = "TODO: implement this... (sorry)";
676 
677  } else if (tokens[1] == "play") {
678  if (cassettePlayer.getState() == CassettePlayer::RECORD) {
679  try {
680  result = "Play mode set, rewinding tape.";
681  cassettePlayer.playTape(
682  cassettePlayer.getImageName(), time);
683  } catch (MSXException& e) {
684  throw CommandException(std::move(e).getMessage());
685  }
686  } else if (cassettePlayer.getState() == CassettePlayer::STOP) {
687  throw CommandException("No tape inserted or tape at end!");
688  } else {
689  // PLAY mode
690  result = "Already in play mode.";
691  }
692 
693  } else if (tokens[1] == "eject") {
694  result = "Tape ejected";
695  cassettePlayer.removeTape(time);
696 
697  } else if (tokens[1] == "rewind") {
698  string r;
699  if (cassettePlayer.getState() == CassettePlayer::RECORD) {
700  try {
701  r = "First stopping recording... ";
702  cassettePlayer.playTape(
703  cassettePlayer.getImageName(), time);
704  } catch (MSXException& e) {
705  throw CommandException(std::move(e).getMessage());
706  }
707  }
708  cassettePlayer.rewind(time);
709  r += "Tape rewound";
710  result = r;
711 
712  } else if (tokens[1] == "getpos") {
713  result = cassettePlayer.getTapePos(time);
714 
715  } else if (tokens[1] == "getlength") {
716  result = cassettePlayer.getTapeLength(time);
717 
718  } else {
719  try {
720  result = "Changing tape";
721  Filename filename(tokens[1].getString().str(), userFileContext());
722  cassettePlayer.playTape(filename, time);
723  } catch (MSXException& e) {
724  throw CommandException(std::move(e).getMessage());
725  }
726  }
727  //if (!cassettePlayer.getConnector()) {
728  // cassettePlayer.cliComm.printWarning("Cassetteplayer not plugged in.");
729  //}
730 }
731 
732 string CassettePlayer::TapeCommand::help(const vector<string>& tokens) const
733 {
734  string helptext;
735  if (tokens.size() >= 2) {
736  if (tokens[1] == "eject") {
737  helptext =
738  "Well, just eject the cassette from the cassette "
739  "player/recorder!";
740  } else if (tokens[1] == "rewind") {
741  helptext =
742  "Indeed, rewind the tape that is currently in the "
743  "cassette player/recorder...";
744  } else if (tokens[1] == "motorcontrol") {
745  helptext =
746  "Setting this to 'off' is equivalent to "
747  "disconnecting the black remote plug from the "
748  "cassette player: it makes the cassette player "
749  "run (if in play mode); the motor signal from the "
750  "MSX will be ignored. Normally this is set to "
751  "'on': the cassetteplayer obeys the motor control "
752  "signal from the MSX.";
753  } else if (tokens[1] == "play") {
754  helptext =
755  "Go to play mode. Only useful if you were in "
756  "record mode (which is currently the only other "
757  "mode available).";
758  } else if (tokens[1] == "new") {
759  helptext =
760  "Create a new cassette image. If the file name is "
761  "omitted, one will be generated in the default "
762  "directory for tape recordings. Implies going to "
763  "record mode (why else do you want a new cassette "
764  "image?).";
765  } else if (tokens[1] == "insert") {
766  helptext =
767  "Inserts the specified cassette image into the "
768  "cassette player, rewinds it and switches to play "
769  "mode.";
770  } else if (tokens[1] == "record") {
771  helptext =
772  "Go to record mode. NOT IMPLEMENTED YET. Will be "
773  "used to be able to resume recording to an "
774  "existing cassette image, previously inserted with "
775  "the insert command.";
776  } else if (tokens[1] == "getpos") {
777  helptext =
778  "Return the position of the tape, in seconds from "
779  "the beginning of the tape.";
780  } else if (tokens[1] == "getlength") {
781  helptext =
782  "Return the length of the tape in seconds.";
783  }
784  } else {
785  helptext =
786  "cassetteplayer eject "
787  ": remove tape from virtual player\n"
788  "cassetteplayer rewind "
789  ": rewind tape in virtual player\n"
790  "cassetteplayer motorcontrol "
791  ": enables or disables motor control (remote)\n"
792  "cassetteplayer play "
793  ": change to play mode (default)\n"
794  "cassetteplayer record "
795  ": change to record mode (NOT IMPLEMENTED YET)\n"
796  "cassetteplayer new [<filename>] "
797  ": create and insert new tape image file and go to record mode\n"
798  "cassetteplayer insert <filename> "
799  ": insert (a different) tape file\n"
800  "cassetteplayer getpos "
801  ": query the position of the tape\n"
802  "cassetteplayer getlength "
803  ": query the total length of the tape\n"
804  "cassetteplayer <filename> "
805  ": insert (a different) tape file\n";
806  }
807  return helptext;
808 }
809 
810 void CassettePlayer::TapeCommand::tabCompletion(vector<string>& tokens) const
811 {
812  if (tokens.size() == 2) {
813  static const char* const cmds[] = {
814  "eject", "rewind", "motorcontrol", "insert", "new",
815  "play", "getpos", "getlength",
816  //"record",
817  };
818  completeFileName(tokens, userFileContext(), cmds);
819  } else if ((tokens.size() == 3) && (tokens[1] == "insert")) {
820  completeFileName(tokens, userFileContext());
821  } else if ((tokens.size() == 3) && (tokens[1] == "motorcontrol")) {
822  static const char* const extra[] = { "on", "off" };
823  completeString(tokens, extra);
824  }
825 }
826 
827 bool CassettePlayer::TapeCommand::needRecord(span<const TclObject> tokens) const
828 {
829  return tokens.size() > 1;
830 }
831 
832 
833 static std::initializer_list<enum_string<CassettePlayer::State>> stateInfo = {
834  { "PLAY", CassettePlayer::PLAY },
835  { "RECORD", CassettePlayer::RECORD },
836  { "STOP", CassettePlayer::STOP }
837 };
839 
840 // version 1: initial version
841 // version 2: added checksum
842 template<typename Archive>
843 void CassettePlayer::serialize(Archive& ar, unsigned version)
844 {
845  if (recordImage) {
846  // buf, sampcnt
847  flushOutput();
848  }
849 
850  ar.serialize("casImage", casImage);
851 
852  Sha1Sum oldChecksum;
853  if (!ar.isLoader() && playImage) {
854  oldChecksum = playImage->getSha1Sum();
855  }
856  if (ar.versionAtLeast(version, 2)) {
857  string oldChecksumStr = oldChecksum.empty()
858  ? string{}
859  : oldChecksum.toString();
860  ar.serialize("checksum", oldChecksumStr);
861  oldChecksum = oldChecksumStr.empty()
862  ? Sha1Sum()
863  : Sha1Sum(oldChecksumStr);
864  }
865 
866  if (ar.isLoader()) {
867  FilePool& filePool = motherBoard.getReactor().getFilePool();
868  auto time = getCurrentTime();
869  removeTape(time);
870  casImage.updateAfterLoadState();
871  if (!oldChecksum.empty() &&
872  !FileOperations::exists(casImage.getResolved())) {
873  auto file = filePool.getFile(FilePool::TAPE, oldChecksum);
874  if (file.is_open()) {
875  casImage.setResolved(file.getURL());
876  }
877  }
878  try {
879  insertTape(casImage, time);
880  } catch (MSXException&) {
881  if (oldChecksum.empty()) {
882  // It's OK if we cannot reinsert an empty
883  // image. One likely scenario for this case is
884  // the following:
885  // - cassetteplayer new myfile.wav
886  // - don't actually start saving to tape yet
887  // - create a savestate and load that state
888  // Because myfile.wav contains no data yet, it
889  // is deleted from the filesystem. So on a
890  // loadstate it won't be found.
891  } else {
892  throw;
893  }
894  }
895 
896  if (playImage && !oldChecksum.empty()) {
897  Sha1Sum newChecksum = playImage->getSha1Sum();
898  if (oldChecksum != newChecksum) {
899  motherBoard.getMSXCliComm().printWarning(
900  "The content of the tape ",
901  casImage.getResolved(),
902  " has changed since the time this "
903  "savestate was created. This might "
904  "result in emulation problems.");
905  }
906  }
907  }
908 
909  // only for RECORD
910  //double lastX;
911  //double lastY;
912  //double partialOut;
913  //double partialInterval;
914  //std::unique_ptr<WavWriter> recordImage;
915 
916  ar.serialize("tapePos", tapePos,
917  "prevSyncTime", prevSyncTime,
918  "audioPos", audioPos,
919  "state", state,
920  "lastOutput", lastOutput,
921  "motor", motor,
922  "motorControl", motorControl);
923 
924  if (ar.isLoader()) {
925  auto time = getCurrentTime();
926  if (playImage && (tapePos > playImage->getEndTime())) {
927  tapePos = playImage->getEndTime();
928  motherBoard.getMSXCliComm().printWarning("Tape position "
929  "beyond tape end! Setting tape position to end. "
930  "This can happen if you load a replay from an "
931  "older openMSX version with a different CAS-to-WAV "
932  "baud rate or when the tape image has been changed "
933  "compared to when the replay was created.");
934  }
935  if (state == RECORD) {
936  // TODO we don't support savestates in RECORD mode yet
937  motherBoard.getMSXCliComm().printWarning(
938  "Restoring a state where the MSX was saving to "
939  "tape is not yet supported. Emulation will "
940  "continue without actually saving.");
941  setState(STOP, getImageName(), time);
942  }
943  if (!playImage && (state == PLAY)) {
944  // This should only happen for manually edited
945  // savestates, though we shouldn't crash on it.
946  setState(STOP, getImageName(), time);
947  }
948  sync(time);
949  updateLoadingState(time);
950  }
951 }
954 
955 } // namespace openmsx
SERIALIZE_ENUM(CassettePlayer::State, stateInfo)
void plugHelper(Connector &connector, EmuTime::param time) override
static EmuDuration sec(unsigned x)
Definition: EmuDuration.hh:37
T length(const vecN< N, T > &x)
Definition: gl_vec.hh:343
void setSoftwareVolume(float volume, EmuTime::param time)
Change the &#39;software volume&#39; of this sound device.
Definition: SoundDevice.cc:141
REGISTER_POLYMORPHIC_INITIALIZER(Pluggable, CassettePlayer, "CassettePlayer")
Represents something you can plug devices into.
Definition: Connector.hh:20
const std::string & getMessage() const &
Definition: MSXException.hh:23
int unlink(const std::string &path)
Call unlink() in a platform-independent manner.
Connector * getConnector() const
Get the connector this Pluggable is plugged into.
Definition: Pluggable.hh:43
string parseCommandFileArgument(string_view argument, string_view directory, string_view prefix, string_view extension)
Helper function for parsing filename arguments in Tcl commands.
void registerEventListener(EventType type, EventListener &listener, Priority priority=OTHER)
Registers a given object to receive certain events.
vecN< N, T > min(const vecN< N, T > &x, const vecN< N, T > &y)
Definition: gl_vec.hh:269
File getFile(FileType fileType, const Sha1Sum &sha1sum)
Search file with the given sha1sum.
Definition: FilePool.cc:302
void unregisterEventListener(EventType type, EventListener &listener)
Unregisters a previously registered event listener.
void unregisterSound()
Unregisters this sound device with the Mixer.
Definition: SoundDevice.cc:131
Definition: span.hh:34
Commands that directly influence the MSX state should send and events so that they can be recorded by...
double toDouble() const
Definition: EmuDuration.hh:47
EventDistributor & getEventDistributor()
Definition: Reactor.hh:81
void updateStream(EmuTime::param time)
Definition: SoundDevice.cc:136
void serialize(Archive &ar, unsigned version)
bool getBoolean() const noexcept
FileContext userFileContext(string_view savePath)
Definition: FileContext.cc:160
CassettePlayer(const HardwareConfig &hwConf)
virtual TclObject executeCommand(const std::string &command, CliConnection *connection=nullptr)=0
Execute the given command.
bool empty() const
Definition: utils/sha1.cc:244
This class represents the result of a sha1 calculation (a 160-bit value).
Definition: sha1.hh:19
void updateAfterLoadState()
After a loadstate we prefer to use the exact same file as before savestate.
Definition: Filename.cc:25
void setInputRate(unsigned sampleRate)
Definition: SoundDevice.hh:108
void update(bool newState)
Called by the device to indicate its loading state may have changed.
Represents a clock with a variable frequency.
Definition: DynamicClock.hh:15
float getAmplificationFactorImpl() const override
Get amplification/attenuation factor for this device.
ALWAYS_INLINE unsigned count(const uint8_t *pIn, const uint8_t *pMatch, const uint8_t *pInLimit)
Definition: lz4.cc:207
void setMotor(bool status, EmuTime::param time) override
Sets the cassette motor relay false = off true = on.
int16_t readSample(EmuTime::param time) override
Read wave data from cassette device.
This class represents a filename.
Definition: Filename.hh:17
void setFreq(unsigned freq)
Change the frequency at which this clock ticks.
Definition: DynamicClock.hh:86
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
void setResolved(const std::string &resolved)
Change the resolved part of this filename E.g.
Definition: Filename.hh:46
CommandController & getCommandController()
void generateChannels(float **buffers, unsigned num) override
Abstract method to generate the actual sound data.
bool exists(string_view filename)
Does this file (directory) exists?
FilePool & getFilePool()
Definition: Reactor.hh:90
void unplugHelper(EmuTime::param time) override
void setSignal(bool output, EmuTime::param time) override
Sets the cassette output signal false = low true = high.
std::string toString() const
Definition: utils/sha1.cc:232
const std::string & getName() const override
Name used to identify this pluggable.
This class implements a (close approximation) of the std::string_view class.
Definition: string_view.hh:16
void addListElement(T t)
Definition: TclObject.hh:121
#define INSTANTIATE_SERIALIZE_METHODS(CLASS)
Definition: serialize.hh:1006
const std::string & getResolved() const
Definition: Filename.hh:27
string getName(KeyCode keyCode)
Translate key code to key name.
Definition: Keys.cc:589
virtual void update(UpdateType type, string_view name, string_view value)=0
std::string strCat(Ts &&...ts)
Definition: strCat.hh:577
string_view getDescription() const override
Description for this pluggable.
#define OUTER(type, member)
Definition: outer.hh:38
unsigned getTicksTill(EmuTime::param e) const
Calculate the number of ticks for this clock until the given time.
Definition: DynamicClock.hh:51
bool empty() const
Convenience method to test for empty filename.
Definition: Filename.cc:38
TclObject makeTclList(Args &&... args)
Definition: TclObject.hh:280
void printWarning(string_view message)
Definition: CliComm.cc:20
unsigned getInputRate() const
Definition: SoundDevice.hh:109
void registerSound(const DeviceConfig &config)
Registers this sound device with the Mixer.
Definition: SoundDevice.cc:90
#define UNREACHABLE
Definition: unreachable.hh:38