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 "MSXCliComm.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 RECIP_RECORD_FREQ = 1.0 / RECORD_FREQ;
68static constexpr double OUTPUT_AMP = 60.0;
69
70static std::string_view getCassettePlayerName()
71{
72 return "cassetteplayer";
73}
74
76 : ResampledSoundDevice(hwConf.getMotherBoard(), getCassettePlayerName(), DESCRIPTION, 1, DUMMY_INPUT_RATE, false)
77 , syncEndOfTape(hwConf.getMotherBoard().getScheduler())
78 , syncAudioEmu (hwConf.getMotherBoard().getScheduler())
79 , motherBoard(hwConf.getMotherBoard())
80 , tapeCommand(
81 motherBoard.getCommandController(),
82 motherBoard.getStateChangeDistributor(),
83 motherBoard.getScheduler())
84 , loadingIndicator(
85 motherBoard.getReactor().getGlobalSettings().getThrottleManager())
86 , autoRunSetting(
87 motherBoard.getCommandController(),
88 "autoruncassettes", "automatically try to run cassettes", true)
89{
90 static const XMLElement* xml = [] {
92 XMLElement* result = doc.allocateElement("cassetteplayer");
93 result->setFirstChild(doc.allocateElement("sound"))
94 ->setFirstChild(doc.allocateElement("volume", "5000"));
95 return result;
96 }();
97 registerSound(DeviceConfig(hwConf, *xml));
98
100 EventType::BOOT, *this);
101 motherBoard.registerMediaInfo(getCassettePlayerName(), *this);
102 motherBoard.getMSXCliComm().update(CliComm::HARDWARE, getCassettePlayerName(), "add");
103
104 removeTape(EmuTime::zero());
105}
106
108{
110 if (auto* c = getConnector()) {
111 c->unplug(getCurrentTime());
112 }
114 EventType::BOOT, *this);
115 motherBoard.unregisterMediaInfo(*this);
116 motherBoard.getMSXCliComm().update(CliComm::HARDWARE, getCassettePlayerName(), "remove");
117}
118
120{
121 result.addDictKeyValues("target", getImageName().getResolved(),
122 "state", getStateString(),
123 "position", getTapePos(getCurrentTime()),
124 "length", getTapeLength(getCurrentTime()),
125 "motorcontrol", motorControl);
126}
127
128void CassettePlayer::autoRun()
129{
130 if (!playImage) return;
131 if (motherBoard.getReverseManager().isReplaying()) {
132 // Don't execute the loading commands (keyboard type commands)
133 // when we're replaying a recording. Because the recording
134 // already contains those commands.
135 return;
136 }
137
138 // try to automatically run the tape, if that's set
139 CassetteImage::FileType type = playImage->getFirstFileType();
140 if (!autoRunSetting.getBoolean() || type == CassetteImage::UNKNOWN) {
141 return;
142 }
143 bool is_SVI = motherBoard.getMachineType() == "SVI"; // assume all other are 'MSX*' (might not be correct for 'Coleco')
144 string H_READ = is_SVI ? "0xFE8E" : "0xFF07"; // Hook for Ready
145 string H_MAIN = is_SVI ? "0xFE94" : "0xFF0C"; // Hook for Main Loop
146 string instr1, instr2;
147 switch (type) {
149 instr1 = R"({RUN\"CAS:\"\r})";
150 break;
152 instr1 = R"({BLOAD\"CAS:\",R\r})";
153 break;
155 // Note that CLOAD:RUN won't work: BASIC ignores stuff
156 // after the CLOAD command. That's why it's split in two.
157 instr1 = "{CLOAD\\r}";
158 instr2 = "{RUN\\r}";
159 break;
160 default:
161 UNREACHABLE; // Shouldn't be possible
162 }
163 string command = strCat(
164 "namespace eval ::openmsx {\n"
165 " variable auto_run_bp\n"
166
167 " proc auto_run_cb {args} {\n"
168 " variable auto_run_bp\n"
169 " debug remove_bp $auto_run_bp\n"
170 " unset auto_run_bp\n"
171
172 // Without the 0.2s delay here, the type command gets messed up
173 // on MSX1 machines for some reason (starting to type too early?)
174 // When using 0.1s delay only, the typing works, but still some
175 // things go wrong on some machines with some games (see #1509
176 // for instance)
177 " after time 0.2 \"type [lindex $args 0]\"\n"
178
179 " set next [lrange $args 1 end]\n"
180 " if {[llength $next] == 0} return\n"
181
182 // H_READ is used by some firmwares; we need to hook the
183 // H_MAIN that happens immediately after H_READ.
184 " set cmd \"openmsx::auto_run_cb $next\"\n"
185 " set openmsx::auto_run_bp [debug set_bp ", H_MAIN, " 1 \"$cmd\"]\n"
186 " }\n"
187
188 " if {[info exists auto_run_bp]} {debug remove_bp $auto_run_bp\n}\n"
189 " set auto_run_bp [debug set_bp ", H_READ, " 1 {\n"
190 " openmsx::auto_run_cb {{}} ", instr1, ' ', instr2, "\n"
191 " }]\n"
192
193 // re-trigger hook(s), needed when already booted in BASIC
194 " type_via_keyboard \'\\r\n"
195 "}");
196 try {
197 motherBoard.getCommandController().executeCommand(command);
198 } catch (CommandException& e) {
199 motherBoard.getMSXCliComm().printWarning(
200 "Error executing loading instruction using command \"",
201 command, "\" for AutoRun: ",
202 e.getMessage(), "\n Please report a bug.");
203 }
204}
205
206string CassettePlayer::getStateString() const
207{
208 switch (getState()) {
209 case PLAY: return "play";
210 case RECORD: return "record";
211 case STOP: return "stop";
212 }
214}
215
216bool CassettePlayer::isRolling() const
217{
218 // Is the tape 'rolling'?
219 // is true when:
220 // not in stop mode (there is a tape inserted and not at end-of-tape)
221 // AND [ user forced playing (motorControl=off) OR motor enabled by
222 // software (motor=on) ]
223 return (getState() != STOP) && (motor || !motorControl);
224}
225
226double CassettePlayer::getTapePos(EmuTime::param time)
227{
228 sync(time);
229 if (getState() == RECORD) {
230 // we record 8-bit mono, so bytes == samples
231 return (double(recordImage->getBytes()) + partialInterval) * RECIP_RECORD_FREQ;
232 } else {
233 return (tapePos - EmuTime::zero()).toDouble();
234 }
235}
236
237double CassettePlayer::getTapeLength(EmuTime::param time)
238{
239 if (playImage) {
240 return (playImage->getEndTime() - EmuTime::zero()).toDouble();
241 } else if (getState() == RECORD) {
242 return getTapePos(time);
243 } else {
244 return 0.0;
245 }
246}
247
248void CassettePlayer::checkInvariants() const
249{
250 switch (getState()) {
251 case STOP:
252 assert(!recordImage);
253 if (playImage) {
254 // we're at end-of tape
255 assert(!getImageName().empty());
256 } else {
257 // no tape inserted, imageName may or may not be empty
258 }
259 break;
260 case PLAY:
261 assert(!getImageName().empty());
262 assert(!recordImage);
263 assert(playImage);
264 break;
265 case RECORD:
266 assert(!getImageName().empty());
267 assert(recordImage);
268 assert(!playImage);
269 break;
270 default:
272 }
273}
274
275void CassettePlayer::setState(State newState, const Filename& newImage,
276 EmuTime::param time)
277{
278 sync(time);
279
280 // set new state if different from old state
281 State oldState = getState();
282 if (oldState == newState) return;
283
284 // cannot directly switch from PLAY to RECORD or vice-versa,
285 // (should always go via STOP)
286 assert(!((oldState == PLAY) && (newState == RECORD)));
287 assert(!((oldState == RECORD) && (newState == PLAY)));
288
289 // stuff for leaving the old state
290 // 'recordImage==nullptr' can happen in case of loadstate.
291 if ((oldState == RECORD) && recordImage) {
292 flushOutput();
293 bool empty = recordImage->isEmpty();
294 recordImage.reset();
295 if (empty) {
296 // delete the created WAV file, as it is useless
297 FileOperations::unlink(getImageName().getResolved()); // ignore errors
298 setImageName(Filename());
299 }
300 }
301
302 // actually switch state
303 state = newState;
304 setImageName(newImage);
305
306 // stuff for entering the new state
307 if (newState == RECORD) {
308 partialOut = 0.0;
309 partialInterval = 0.0;
310 lastX = lastOutput ? OUTPUT_AMP : -OUTPUT_AMP;
311 lastY = 0.0;
312 }
313 motherBoard.getMSXCliComm().update(
314 CliComm::STATUS, "cassetteplayer", getStateString());
315
316 updateLoadingState(time); // sets SP for tape-end detection
317
318 checkInvariants();
319}
320
321void CassettePlayer::updateLoadingState(EmuTime::param time)
322{
323 assert(prevSyncTime == time); // sync() must be called
324 // TODO also set loadingIndicator for RECORD?
325 // note: we don't use isRolling()
326 loadingIndicator.update(motor && (getState() == PLAY));
327
328 syncEndOfTape.removeSyncPoint();
329 if (isRolling() && (getState() == PLAY)) {
330 syncEndOfTape.setSyncPoint(time + (playImage->getEndTime() - tapePos));
331 }
332}
333
334void CassettePlayer::setImageName(const Filename& newImage)
335{
336 casImage = newImage;
337 motherBoard.getMSXCliComm().update(
338 CliComm::MEDIA, "cassetteplayer", casImage.getResolved());
339}
340
341void CassettePlayer::insertTape(const Filename& filename, EmuTime::param time)
342{
343 if (!filename.empty()) {
344 FilePool& filePool = motherBoard.getReactor().getFilePool();
345 try {
346 // first try WAV
347 playImage = std::make_unique<WavImage>(filename, filePool);
348 } catch (MSXException& e) {
349 try {
350 // if that fails use CAS
351 playImage = std::make_unique<CasImage>(
352 filename, filePool,
353 motherBoard.getMSXCliComm());
354 } catch (MSXException& e2) {
355 throw MSXException(
356 "Failed to insert WAV image: \"",
357 e.getMessage(),
358 "\" and also failed to insert CAS image: \"",
359 e2.getMessage(), '\"');
360 }
361 }
362 } else {
363 // This is a bit tricky, consider this scenario: we switch from
364 // RECORD->PLAY, but we didn't actually record anything: The
365 // removeTape() call above (indirectly) deletes the empty
366 // recorded wav image and also clears imageName. Now because
367 // the 'filename' parameter is passed by reference, and because
368 // getImageName() returns a reference, this 'filename'
369 // parameter now also is an empty string.
370 }
371
372 // possibly recreate resampler
373 if (unsigned inputRate = playImage ? playImage->getFrequency() : 44100;
374 inputRate != getInputRate()) {
375 setInputRate(inputRate);
377 }
378
379 // trigger (re-)query of getAmplificationFactorImpl()
380 setSoftwareVolume(1.0f, time);
381
382 setImageName(filename);
383}
384
385void CassettePlayer::playTape(const Filename& filename, EmuTime::param time)
386{
387 // Temporally go to STOP state:
388 // RECORD: First close the recorded image. Otherwise it goes wrong
389 // if you switch from RECORD->PLAY on the same image.
390 // PLAY: Go to stop because we temporally violate some invariants
391 // (tapePos can be beyond end-of-tape).
392 setState(STOP, getImageName(), time); // keep current image
393 insertTape(filename, time);
394 rewind(time); // sets PLAY mode
395 autoRun();
396}
397
398void CassettePlayer::rewind(EmuTime::param time)
399{
400 sync(time); // before tapePos changes
401 assert(getState() != RECORD);
402 tapePos = EmuTime::zero();
403 audioPos = 0;
404
405 if (getImageName().empty()) {
406 // no image inserted, do nothing
407 assert(getState() == STOP);
408 } else {
409 // keep current image
410 setState(PLAY, getImageName(), time);
411 }
412 updateLoadingState(time);
413}
414
415void CassettePlayer::recordTape(const Filename& filename, EmuTime::param time)
416{
417 removeTape(time); // flush (possible) previous recording
418 recordImage = std::make_unique<Wav8Writer>(filename, 1, RECORD_FREQ);
419 tapePos = EmuTime::zero();
420 setState(RECORD, filename, time);
421}
422
423void CassettePlayer::removeTape(EmuTime::param time)
424{
425 // first stop with tape still inserted
426 setState(STOP, getImageName(), time);
427 // then remove the tape
428 playImage.reset();
429 tapePos = EmuTime::zero();
430 setImageName({});
431}
432
433void CassettePlayer::setMotor(bool status, EmuTime::param time)
434{
435 if (status != motor) {
436 sync(time);
437 motor = status;
438 updateLoadingState(time);
439 }
440}
441
442void CassettePlayer::setMotorControl(bool status, EmuTime::param time)
443{
444 if (status != motorControl) {
445 sync(time);
446 motorControl = status;
447 updateLoadingState(time);
448 }
449}
450
451int16_t CassettePlayer::readSample(EmuTime::param time)
452{
453 if (getState() == PLAY) {
454 // playing
455 sync(time);
456 return isRolling() ? playImage->getSampleAt(tapePos) : int16_t(0);
457 } else {
458 // record or stop
459 return 0;
460 }
461}
462
463void CassettePlayer::setSignal(bool output, EmuTime::param time)
464{
465 sync(time);
466 lastOutput = output;
467}
468
469void CassettePlayer::sync(EmuTime::param time)
470{
471 EmuDuration duration = time - prevSyncTime;
472 prevSyncTime = time;
473
474 updateTapePosition(duration, time);
475 generateRecordOutput(duration);
476}
477
478void CassettePlayer::updateTapePosition(
479 EmuDuration::param duration, EmuTime::param time)
480{
481 if (!isRolling() || (getState() != PLAY)) return;
482
483 tapePos += duration;
484 assert(tapePos <= playImage->getEndTime());
485
486 // synchronize audio with actual tape position
487 if (!syncScheduled) {
488 // don't sync too often, this improves sound quality
489 syncScheduled = true;
490 syncAudioEmu.setSyncPoint(time + EmuDuration::sec(1));
491 }
492}
493
494void CassettePlayer::generateRecordOutput(EmuDuration::param duration)
495{
496 if (!recordImage || !isRolling()) return;
497
498 double out = lastOutput ? OUTPUT_AMP : -OUTPUT_AMP;
499 double samples = duration.toDouble() * RECORD_FREQ;
500 if (auto rest = 1.0 - partialInterval; 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 auto 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 static 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 prefix = "openmsx";
670 (tokens.size() == 3) ? tokens[2].getString() : string{},
671 TAPE_RECORDING_DIR, prefix, TAPE_RECORDING_EXTENSION);
672 cassettePlayer.recordTape(Filename(filename), time);
673 result = tmpStrCat(
674 "Created new cassette image file: ", filename,
675 ", inserted it and set recording mode.");
676
677 } else if (tokens[1] == "insert" && tokens.size() == 3) {
678 try {
679 result = "Changing tape";
680 Filename filename(tokens[2].getString(), userFileContext());
681 cassettePlayer.playTape(filename, time);
682 } catch (MSXException& e) {
683 throw CommandException(std::move(e).getMessage());
684 }
685
686 } else if (tokens[1] == "motorcontrol" && tokens.size() == 3) {
687 if (tokens[2] == "on") {
688 cassettePlayer.setMotorControl(true, time);
689 result = "Motor control enabled.";
690 } else if (tokens[2] == "off") {
691 cassettePlayer.setMotorControl(false, time);
692 result = "Motor control disabled.";
693 } else {
694 throw SyntaxError();
695 }
696
697 } else if (tokens.size() != 2) {
698 throw SyntaxError();
699
700 } else if (tokens[1] == "motorcontrol") {
701 result = tmpStrCat("Motor control is ",
702 (cassettePlayer.motorControl ? "on" : "off"));
703
704 } else if (tokens[1] == "record") {
705 result = "TODO: implement this... (sorry)";
706
707 } else if (tokens[1] == "play") {
708 if (cassettePlayer.getState() == CassettePlayer::RECORD) {
709 try {
710 result = "Play mode set, rewinding tape.";
711 cassettePlayer.playTape(
712 cassettePlayer.getImageName(), time);
713 } catch (MSXException& e) {
714 throw CommandException(std::move(e).getMessage());
715 }
716 } else if (cassettePlayer.getState() == CassettePlayer::STOP) {
717 throw CommandException("No tape inserted or tape at end!");
718 } else {
719 // PLAY mode
720 result = "Already in play mode.";
721 }
722
723 } else if (tokens[1] == "eject") {
724 result = "Tape ejected";
725 cassettePlayer.removeTape(time);
726
727 } else if (tokens[1] == "rewind") {
728 string r;
729 if (cassettePlayer.getState() == CassettePlayer::RECORD) {
730 try {
731 r = "First stopping recording... ";
732 cassettePlayer.playTape(
733 cassettePlayer.getImageName(), time);
734 } catch (MSXException& e) {
735 throw CommandException(std::move(e).getMessage());
736 }
737 }
738 cassettePlayer.rewind(time);
739 r += "Tape rewound";
740 result = r;
741
742 } else if (tokens[1] == "getpos") {
743 result = cassettePlayer.getTapePos(time);
744
745 } else if (tokens[1] == "getlength") {
746 result = cassettePlayer.getTapeLength(time);
747
748 } else {
749 try {
750 result = "Changing tape";
751 Filename filename(tokens[1].getString(), userFileContext());
752 cassettePlayer.playTape(filename, time);
753 } catch (MSXException& e) {
754 throw CommandException(std::move(e).getMessage());
755 }
756 }
757 //if (!cassettePlayer.getConnector()) {
758 // cassettePlayer.cliComm.printWarning("Cassette player not plugged in.");
759 //}
760}
761
762string CassettePlayer::TapeCommand::help(std::span<const TclObject> tokens) const
763{
764 string helpText;
765 if (tokens.size() >= 2) {
766 if (tokens[1] == "eject") {
767 helpText =
768 "Well, just eject the cassette from the cassette "
769 "player/recorder!";
770 } else if (tokens[1] == "rewind") {
771 helpText =
772 "Indeed, rewind the tape that is currently in the "
773 "cassette player/recorder...";
774 } else if (tokens[1] == "motorcontrol") {
775 helpText =
776 "Setting this to 'off' is equivalent to "
777 "disconnecting the black remote plug from the "
778 "cassette player: it makes the cassette player "
779 "run (if in play mode); the motor signal from the "
780 "MSX will be ignored. Normally this is set to "
781 "'on': the cassetteplayer obeys the motor control "
782 "signal from the MSX.";
783 } else if (tokens[1] == "play") {
784 helpText =
785 "Go to play mode. Only useful if you were in "
786 "record mode (which is currently the only other "
787 "mode available).";
788 } else if (tokens[1] == "new") {
789 helpText =
790 "Create a new cassette image. If the file name is "
791 "omitted, one will be generated in the default "
792 "directory for tape recordings. Implies going to "
793 "record mode (why else do you want a new cassette "
794 "image?).";
795 } else if (tokens[1] == "insert") {
796 helpText =
797 "Inserts the specified cassette image into the "
798 "cassette player, rewinds it and switches to play "
799 "mode.";
800 } else if (tokens[1] == "record") {
801 helpText =
802 "Go to record mode. NOT IMPLEMENTED YET. Will be "
803 "used to be able to resume recording to an "
804 "existing cassette image, previously inserted with "
805 "the insert command.";
806 } else if (tokens[1] == "getpos") {
807 helpText =
808 "Return the position of the tape, in seconds from "
809 "the beginning of the tape.";
810 } else if (tokens[1] == "getlength") {
811 helpText =
812 "Return the length of the tape in seconds.";
813 }
814 } else {
815 helpText =
816 "cassetteplayer eject "
817 ": remove tape from virtual player\n"
818 "cassetteplayer rewind "
819 ": rewind tape in virtual player\n"
820 "cassetteplayer motorcontrol "
821 ": enables or disables motor control (remote)\n"
822 "cassetteplayer play "
823 ": change to play mode (default)\n"
824 "cassetteplayer record "
825 ": change to record mode (NOT IMPLEMENTED YET)\n"
826 "cassetteplayer new [<filename>] "
827 ": create and insert new tape image file and go to record mode\n"
828 "cassetteplayer insert <filename> "
829 ": insert (a different) tape file\n"
830 "cassetteplayer getpos "
831 ": query the position of the tape\n"
832 "cassetteplayer getlength "
833 ": query the total length of the tape\n"
834 "cassetteplayer <filename> "
835 ": insert (a different) tape file\n";
836 }
837 return helpText;
838}
839
840void CassettePlayer::TapeCommand::tabCompletion(std::vector<string>& tokens) const
841{
842 using namespace std::literals;
843 if (tokens.size() == 2) {
844 static constexpr std::array cmds = {
845 "eject"sv, "rewind"sv, "motorcontrol"sv, "insert"sv, "new"sv,
846 "play"sv, "getpos"sv, "getlength"sv,
847 //"record"sv,
848 };
849 completeFileName(tokens, userFileContext(), cmds);
850 } else if ((tokens.size() == 3) && (tokens[1] == "insert")) {
851 completeFileName(tokens, userFileContext());
852 } else if ((tokens.size() == 3) && (tokens[1] == "motorcontrol")) {
853 static constexpr std::array extra = {"on"sv, "off"sv};
854 completeString(tokens, extra);
855 }
856}
857
858bool CassettePlayer::TapeCommand::needRecord(std::span<const TclObject> tokens) const
859{
860 return tokens.size() > 1;
861}
862
863
864static constexpr std::initializer_list<enum_string<CassettePlayer::State>> stateInfo = {
865 { "PLAY", CassettePlayer::PLAY },
866 { "RECORD", CassettePlayer::RECORD },
867 { "STOP", CassettePlayer::STOP }
868};
870
871// version 1: initial version
872// version 2: added checksum
873template<typename Archive>
874void CassettePlayer::serialize(Archive& ar, unsigned version)
875{
876 if (recordImage) {
877 // buf, sampcnt
878 flushOutput();
879 }
880
881 ar.serialize("casImage", casImage);
882
883 Sha1Sum oldChecksum;
884 if constexpr (!Archive::IS_LOADER) {
885 if (playImage) {
886 oldChecksum = playImage->getSha1Sum();
887 }
888 }
889 if (ar.versionAtLeast(version, 2)) {
890 string oldChecksumStr = oldChecksum.empty()
891 ? string{}
892 : oldChecksum.toString();
893 ar.serialize("checksum", oldChecksumStr);
894 oldChecksum = oldChecksumStr.empty()
895 ? Sha1Sum()
896 : Sha1Sum(oldChecksumStr);
897 }
898
899 if constexpr (Archive::IS_LOADER) {
900 FilePool& filePool = motherBoard.getReactor().getFilePool();
901 auto time = getCurrentTime();
902 casImage.updateAfterLoadState();
903 if (!oldChecksum.empty() &&
904 !FileOperations::exists(casImage.getResolved())) {
905 auto file = filePool.getFile(FileType::TAPE, oldChecksum);
906 if (file.is_open()) {
907 casImage.setResolved(file.getURL());
908 }
909 }
910 try {
911 insertTape(casImage, time);
912 } catch (MSXException&) {
913 if (oldChecksum.empty()) {
914 // It's OK if we cannot reinsert an empty
915 // image. One likely scenario for this case is
916 // the following:
917 // - cassetteplayer new myfile.wav
918 // - don't actually start saving to tape yet
919 // - create a savestate and load that state
920 // Because myfile.wav contains no data yet, it
921 // is deleted from the filesystem. So on a
922 // loadstate it won't be found.
923 } else {
924 throw;
925 }
926 }
927
928 if (playImage && !oldChecksum.empty()) {
929 Sha1Sum newChecksum = playImage->getSha1Sum();
930 if (oldChecksum != newChecksum) {
931 motherBoard.getMSXCliComm().printWarning(
932 "The content of the tape ",
933 casImage.getResolved(),
934 " has changed since the time this "
935 "savestate was created. This might "
936 "result in emulation problems.");
937 }
938 }
939 }
940
941 // only for RECORD
942 //double lastX;
943 //double lastY;
944 //double partialOut;
945 //double partialInterval;
946 //std::unique_ptr<WavWriter> recordImage;
947
948 ar.serialize("tapePos", tapePos,
949 "prevSyncTime", prevSyncTime,
950 "audioPos", audioPos,
951 "state", state,
952 "lastOutput", lastOutput,
953 "motor", motor,
954 "motorControl", motorControl);
955
956 if constexpr (Archive::IS_LOADER) {
957 auto time = getCurrentTime();
958 if (playImage && (tapePos > playImage->getEndTime())) {
959 tapePos = playImage->getEndTime();
960 motherBoard.getMSXCliComm().printWarning("Tape position "
961 "beyond tape end! Setting tape position to end. "
962 "This can happen if you load a replay from an "
963 "older openMSX version with a different CAS-to-WAV "
964 "baud rate or when the tape image has been changed "
965 "compared to when the replay was created.");
966 }
967 if (state == RECORD) {
968 // TODO we don't support savestates in RECORD mode yet
969 motherBoard.getMSXCliComm().printWarning(
970 "Restoring a state where the MSX was saving to "
971 "tape is not yet supported. Emulation will "
972 "continue without actually saving.");
973 setState(STOP, getImageName(), time);
974 }
975 if (!playImage && (state == PLAY)) {
976 // This should only happen for manually edited
977 // savestates, though we shouldn't crash on it.
978 setState(STOP, getImageName(), time);
979 }
980 sync(time);
981 updateLoadingState(time);
982 }
983}
986
987} // 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...
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)
const EmuDuration & param
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:58
const std::string & getResolved() const &
Definition Filename.hh:38
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 update(UpdateType type, std::string_view name, std::string_view value) override
Definition MSXCliComm.cc:21
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:86
FilePool & getFilePool()
Definition Reactor.hh:95
This class represents the result of a sha1 calculation (a 160-bit value).
Definition sha1.hh:24
bool empty() const
std::string toString() const
void updateStream(EmuTime::param time)
unsigned getInputRate() const
void setInputRate(unsigned sampleRate)
void setSoftwareVolume(float volume, EmuTime::param time)
Change the 'software volume' of this sound device.
void unregisterSound()
Unregisters this sound device with the Mixer.
void registerSound(const DeviceConfig &config)
Registers this sound device with the Mixer.
void addDictKeyValues(Args &&... args)
Definition TclObject.hh:148
static XMLDocument & getStaticDocument()
XMLElement * setFirstChild(XMLElement *child)
static_string_view
ALWAYS_INLINE unsigned count(const uint8_t *pIn, const uint8_t *pMatch, const uint8_t *pInLimit)
Definition lz4.cc:146
constexpr double e
Definition Math.hh:21
T length(const vecN< N, T > &x)
Definition gl_vec.hh:376
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.
This file implemented 3 utility functions:
Definition Autofire.cc:11
EventType getType(const Event &event)
Definition Event.hh:516
const FileContext & userFileContext()
std::variant< KeyUpEvent, KeyDownEvent, MouseMotionEvent, MouseButtonUpEvent, MouseButtonDownEvent, MouseWheelEvent, JoystickAxisMotionEvent, JoystickHatEvent, JoystickButtonUpEvent, JoystickButtonDownEvent, OsdControlReleaseEvent, OsdControlPressEvent, WindowEvent, TextEvent, FileDropEvent, QuitEvent, FinishFrameEvent, CliCommandEvent, GroupEvent, BootEvent, FrameDrawnEvent, BreakEvent, SwitchRendererEvent, TakeReverseSnapshotEvent, AfterTimedEvent, MachineLoadedEvent, MachineActivatedEvent, MachineDeactivatedEvent, MidiInReaderEvent, MidiInWindowsEvent, MidiInCoreMidiEvent, MidiInCoreMidiVirtualEvent, MidiInALSAEvent, Rs232TesterEvent, Rs232NetEvent, ImGuiDelayedActionEvent, ImGuiActiveEvent > Event
Definition Event.hh:444
std::array< const EDStorage, 4 > A
TclObject makeTclList(Args &&... args)
Definition TclObject.hh:293
#define OUTER(type, member)
Definition outer.hh:42
constexpr auto subspan(Range &&range, size_t offset, size_t count=std::dynamic_extent)
Definition ranges.hh:471
#define INSTANTIATE_SERIALIZE_METHODS(CLASS)
#define SERIALIZE_ENUM(TYPE, INFO)
#define REGISTER_POLYMORPHIC_INITIALIZER(BASE, CLASS, NAME)
std::string strCat()
Definition strCat.hh:703
TemporaryString tmpStrCat(Ts &&... ts)
Definition strCat.hh:742
#define UNREACHABLE
constexpr void repeat(T n, Op op)
Repeat the given operation 'op' 'n' times.
Definition xrange.hh:147