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