text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_TVF_H
#define MT32EMU_TVF_H
#include "globals.h"
#include "Types.h"
#include "Structures.h"
namespace MT32Emu {
class LA32Ramp;
class Partial;
class TVF {
private:
const Partial * const partial;
LA32Ramp *cutoffModifierRamp;
const TimbreParam::PartialParam *partialParam;
Bit8u baseCutoff;
int keyTimeSubtraction;
unsigned int levelMult;
Bit8u target;
unsigned int phase;
void startRamp(Bit8u newTarget, Bit8u newIncrement, int newPhase);
void nextPhase();
public:
TVF(const Partial *partial, LA32Ramp *cutoffModifierRamp);
void reset(const TimbreParam::PartialParam *partialParam, Bit32u basePitch);
// Returns the base cutoff (without envelope modification).
// The base cutoff is calculated when reset() is called and remains static
// for the lifetime of the partial.
// Barring bugs, the number returned is confirmed accurate
// (based on specs from Mok).
Bit8u getBaseCutoff() const;
void handleInterrupt();
void startDecay();
}; // class TVF
} // namespace MT32Emu
#endif // #ifndef MT32EMU_TVF_H
``` | /content/code_sandbox/src/sound/munt/TVF.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 370 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstdio>
#include <cstring>
#include "internals.h"
#include "Part.h"
#include "Partial.h"
#include "PartialManager.h"
#include "Poly.h"
#include "Synth.h"
namespace MT32Emu {
static const Bit8u PartialStruct[13] = {
0, 0, 2, 2, 1, 3,
3, 0, 3, 0, 2, 1, 3
};
static const Bit8u PartialMixStruct[13] = {
0, 1, 0, 1, 1, 0,
1, 3, 3, 2, 2, 2, 2
};
RhythmPart::RhythmPart(Synth *useSynth, unsigned int usePartNum): Part(useSynth, usePartNum) {
strcpy(name, "Rhythm");
rhythmTemp = &synth->mt32ram.rhythmTemp[0];
refresh();
}
Part::Part(Synth *useSynth, unsigned int usePartNum) {
synth = useSynth;
partNum = usePartNum;
patchCache[0].dirty = true;
holdpedal = false;
patchTemp = &synth->mt32ram.patchTemp[partNum];
if (usePartNum == 8) {
// Nasty hack for rhythm
timbreTemp = NULL;
} else {
snprintf(name, sizeof(name), "Part %d", partNum + 1);
timbreTemp = &synth->mt32ram.timbreTemp[partNum];
}
currentInstr[0] = 0;
currentInstr[10] = 0;
volumeOverride = 255;
modulation = 0;
expression = 100;
pitchBend = 0;
activePartialCount = 0;
activeNonReleasingPolyCount = 0;
memset(patchCache, 0, sizeof(patchCache));
}
Part::~Part() {
while (!activePolys.isEmpty()) {
delete activePolys.takeFirst();
}
}
void Part::setDataEntryMSB(unsigned char midiDataEntryMSB) {
if (nrpn) {
// The last RPN-related control change was for an NRPN,
// which the real synths don't support.
return;
}
if (rpn != 0) {
// The RPN has been set to something other than 0,
// which is the only RPN that these synths support
return;
}
patchTemp->patch.benderRange = midiDataEntryMSB > 24 ? 24 : midiDataEntryMSB;
updatePitchBenderRange();
}
void Part::setNRPN() {
nrpn = true;
}
void Part::setRPNLSB(unsigned char midiRPNLSB) {
nrpn = false;
rpn = (rpn & 0xFF00) | midiRPNLSB;
}
void Part::setRPNMSB(unsigned char midiRPNMSB) {
nrpn = false;
rpn = (rpn & 0x00FF) | (midiRPNMSB << 8);
}
void Part::setHoldPedal(bool pressed) {
if (holdpedal && !pressed) {
holdpedal = false;
stopPedalHold();
} else {
holdpedal = pressed;
}
}
Bit32s Part::getPitchBend() const {
return pitchBend;
}
void Part::setBend(unsigned int midiBend) {
// CONFIRMED:
pitchBend = ((signed(midiBend) - 8192) * pitchBenderRange) >> 14; // PORTABILITY NOTE: Assumes arithmetic shift
}
Bit8u Part::getModulation() const {
return modulation;
}
void Part::setModulation(unsigned int midiModulation) {
modulation = Bit8u(midiModulation);
}
void Part::resetAllControllers() {
modulation = 0;
expression = 100;
pitchBend = 0;
setHoldPedal(false);
}
void Part::reset() {
resetAllControllers();
allSoundOff();
rpn = 0xFFFF;
}
void RhythmPart::refresh() {
// (Re-)cache all the mapped timbres ahead of time
for (unsigned int drumNum = 0; drumNum < synth->controlROMMap->rhythmSettingsCount; drumNum++) {
int drumTimbreNum = rhythmTemp[drumNum].timbre;
if (drumTimbreNum >= 127) { // 94 on MT-32
continue;
}
PatchCache *cache = drumCache[drumNum];
backupCacheToPartials(cache);
for (int t = 0; t < 4; t++) {
// Common parameters, stored redundantly
cache[t].dirty = true;
cache[t].reverb = rhythmTemp[drumNum].reverbSwitch > 0;
}
}
updatePitchBenderRange();
}
void Part::refresh() {
backupCacheToPartials(patchCache);
for (int t = 0; t < 4; t++) {
// Common parameters, stored redundantly
patchCache[t].dirty = true;
patchCache[t].reverb = patchTemp->patch.reverbSwitch > 0;
}
memcpy(currentInstr, timbreTemp->common.name, 10);
synth->newTimbreSet(partNum);
updatePitchBenderRange();
}
const char *Part::getCurrentInstr() const {
return ¤tInstr[0];
}
void RhythmPart::refreshTimbre(unsigned int absTimbreNum) {
for (int m = 0; m < 85; m++) {
if (rhythmTemp[m].timbre == absTimbreNum - 128) {
drumCache[m][0].dirty = true;
}
}
}
void Part::refreshTimbre(unsigned int absTimbreNum) {
if (getAbsTimbreNum() == absTimbreNum) {
memcpy(currentInstr, timbreTemp->common.name, 10);
patchCache[0].dirty = true;
}
}
void Part::setPatch(const PatchParam *patch) {
patchTemp->patch = *patch;
}
void RhythmPart::setTimbre(TimbreParam * /*timbre*/) {
synth->printDebug("%s: Attempted to call setTimbre() - doesn't make sense for rhythm", name);
}
void Part::setTimbre(TimbreParam *timbre) {
*timbreTemp = *timbre;
}
unsigned int RhythmPart::getAbsTimbreNum() const {
synth->printDebug("%s: Attempted to call getAbsTimbreNum() - doesn't make sense for rhythm", name);
return 0;
}
unsigned int Part::getAbsTimbreNum() const {
return (patchTemp->patch.timbreGroup * 64) + patchTemp->patch.timbreNum;
}
#if MT32EMU_MONITOR_MIDI > 0
void RhythmPart::setProgram(unsigned int patchNum) {
synth->printDebug("%s: Attempt to set program (%d) on rhythm is invalid", name, patchNum);
}
#else
void RhythmPart::setProgram(unsigned int) { }
#endif
void Part::setProgram(unsigned int patchNum) {
setPatch(&synth->mt32ram.patches[patchNum]);
holdpedal = false;
allSoundOff();
setTimbre(&synth->mt32ram.timbres[getAbsTimbreNum()].timbre);
refresh();
}
void Part::updatePitchBenderRange() {
pitchBenderRange = patchTemp->patch.benderRange * 683;
}
void Part::backupCacheToPartials(PatchCache cache[4]) {
// check if any partials are still playing with the old patch cache
// if so then duplicate the cached data from the part to the partial so that
// we can change the part's cache without affecting the partial.
// We delay this until now to avoid a copy operation with every note played
for (Poly *poly = activePolys.getFirst(); poly != NULL; poly = poly->getNext()) {
poly->backupCacheToPartials(cache);
}
}
void Part::cacheTimbre(PatchCache cache[4], const TimbreParam *timbre) {
backupCacheToPartials(cache);
int partialCount = 0;
for (int t = 0; t < 4; t++) {
if (((timbre->common.partialMute >> t) & 0x1) == 1) {
cache[t].playPartial = true;
partialCount++;
} else {
cache[t].playPartial = false;
continue;
}
// Calculate and cache common parameters
cache[t].srcPartial = timbre->partial[t];
cache[t].pcm = timbre->partial[t].wg.pcmWave;
switch (t) {
case 0:
cache[t].PCMPartial = (PartialStruct[int(timbre->common.partialStructure12)] & 0x2) ? true : false;
cache[t].structureMix = PartialMixStruct[int(timbre->common.partialStructure12)];
cache[t].structurePosition = 0;
cache[t].structurePair = 1;
break;
case 1:
cache[t].PCMPartial = (PartialStruct[int(timbre->common.partialStructure12)] & 0x1) ? true : false;
cache[t].structureMix = PartialMixStruct[int(timbre->common.partialStructure12)];
cache[t].structurePosition = 1;
cache[t].structurePair = 0;
break;
case 2:
cache[t].PCMPartial = (PartialStruct[int(timbre->common.partialStructure34)] & 0x2) ? true : false;
cache[t].structureMix = PartialMixStruct[int(timbre->common.partialStructure34)];
cache[t].structurePosition = 0;
cache[t].structurePair = 3;
break;
case 3:
cache[t].PCMPartial = (PartialStruct[int(timbre->common.partialStructure34)] & 0x1) ? true : false;
cache[t].structureMix = PartialMixStruct[int(timbre->common.partialStructure34)];
cache[t].structurePosition = 1;
cache[t].structurePair = 2;
break;
default:
break;
}
cache[t].partialParam = &timbre->partial[t];
cache[t].waveform = timbre->partial[t].wg.waveform;
}
for (int t = 0; t < 4; t++) {
// Common parameters, stored redundantly
cache[t].dirty = false;
cache[t].partialCount = partialCount;
cache[t].sustain = (timbre->common.noSustain == 0);
}
//synth->printDebug("Res 1: %d 2: %d 3: %d 4: %d", cache[0].waveform, cache[1].waveform, cache[2].waveform, cache[3].waveform);
#if MT32EMU_MONITOR_INSTRUMENTS > 0
synth->printDebug("%s (%s): Recached timbre", name, currentInstr);
for (int i = 0; i < 4; i++) {
synth->printDebug(" %d: play=%s, pcm=%s (%d), wave=%d", i, cache[i].playPartial ? "YES" : "NO", cache[i].PCMPartial ? "YES" : "NO", timbre->partial[i].wg.pcmWave, timbre->partial[i].wg.waveform);
}
#endif
}
const char *Part::getName() const {
return name;
}
void Part::setVolume(unsigned int midiVolume) {
// CONFIRMED: This calculation matches the table used in the control ROM
patchTemp->outputLevel = Bit8u(midiVolume * 100 / 127);
//synth->printDebug("%s (%s): Set volume to %d", name, currentInstr, midiVolume);
}
Bit8u Part::getVolume() const {
return volumeOverride <= 100 ? volumeOverride : patchTemp->outputLevel;
}
void Part::setVolumeOverride(Bit8u volume) {
volumeOverride = volume;
// When volume is 0, we want the part to stop producing any sound at all.
// For that to achieve, we have to actually stop processing NoteOn MIDI messages; merely
// returning 0 volume is not enough - the output may still be generated at a very low level.
// But first, we have to stop all the currently playing polys. This behaviour may also help
// with performance issues, because parts muted this way barely consume CPU resources.
if (volume == 0) allSoundOff();
}
Bit8u Part::getVolumeOverride() const {
return volumeOverride;
}
Bit8u Part::getExpression() const {
return expression;
}
void Part::setExpression(unsigned int midiExpression) {
// CONFIRMED: This calculation matches the table used in the control ROM
expression = Bit8u(midiExpression * 100 / 127);
}
void RhythmPart::setPan(unsigned int midiPan) {
// CONFIRMED: This does change patchTemp, but has no actual effect on playback.
#if MT32EMU_MONITOR_MIDI > 0
synth->printDebug("%s: Pointlessly setting pan (%d) on rhythm part", name, midiPan);
#endif
Part::setPan(midiPan);
}
void Part::setPan(unsigned int midiPan) {
// NOTE: Panning is inverted compared to GM.
if (synth->controlROMFeatures->quirkPanMult) {
// MT-32: Divide by 9
patchTemp->panpot = Bit8u(midiPan / 9);
} else {
// CM-32L: Divide by 8.5
patchTemp->panpot = Bit8u((midiPan << 3) / 68);
}
//synth->printDebug("%s (%s): Set pan to %d", name, currentInstr, panpot);
}
/**
* Applies key shift to a MIDI key and converts it into an internal key value in the range 12-108.
*/
unsigned int Part::midiKeyToKey(unsigned int midiKey) {
if (synth->controlROMFeatures->quirkKeyShift) {
// NOTE: On MT-32 GEN0, key isn't adjusted, and keyShift is applied further in TVP, unlike newer units:
return midiKey;
}
int key = midiKey + patchTemp->patch.keyShift;
if (key < 36) {
// After keyShift is applied, key < 36, so move up by octaves
while (key < 36) {
key += 12;
}
} else if (key > 132) {
// After keyShift is applied, key > 132, so move down by octaves
while (key > 132) {
key -= 12;
}
}
key -= 24;
return key;
}
void RhythmPart::noteOn(unsigned int midiKey, unsigned int velocity) {
if (midiKey < 24 || midiKey > 108) { /*> 87 on MT-32)*/
synth->printDebug("%s: Attempted to play invalid key %d (velocity %d)", name, midiKey, velocity);
return;
}
synth->rhythmNotePlayed();
unsigned int key = midiKey;
unsigned int drumNum = key - 24;
int drumTimbreNum = rhythmTemp[drumNum].timbre;
const int drumTimbreCount = 64 + synth->controlROMMap->timbreRCount; // 94 on MT-32, 128 on LAPC-I/CM32-L
if (drumTimbreNum == 127 || drumTimbreNum >= drumTimbreCount) { // timbre #127 is OFF, no sense to play it
synth->printDebug("%s: Attempted to play unmapped key %d (velocity %d)", name, midiKey, velocity);
return;
}
// CONFIRMED: Two special cases described by Mok
if (drumTimbreNum == 64 + 6) {
noteOff(0);
key = 1;
} else if (drumTimbreNum == 64 + 7) {
// This noteOff(0) is not performed on MT-32, only LAPC-I
noteOff(0);
key = 0;
}
int absTimbreNum = drumTimbreNum + 128;
TimbreParam *timbre = &synth->mt32ram.timbres[absTimbreNum].timbre;
memcpy(currentInstr, timbre->common.name, 10);
if (drumCache[drumNum][0].dirty) {
cacheTimbre(drumCache[drumNum], timbre);
}
#if MT32EMU_MONITOR_INSTRUMENTS > 0
synth->printDebug("%s (%s): Start poly (drum %d, timbre %d): midiKey %u, key %u, velo %u, mod %u, exp %u, bend %u", name, currentInstr, drumNum, absTimbreNum, midiKey, key, velocity, modulation, expression, pitchBend);
#if MT32EMU_MONITOR_INSTRUMENTS > 1
// According to info from Mok, keyShift does not appear to affect anything on rhythm part on LAPC-I, but may do on MT-32 - needs investigation
synth->printDebug(" Patch: (timbreGroup %u), (timbreNum %u), (keyShift %u), fineTune %u, benderRange %u, assignMode %u, (reverbSwitch %u)", patchTemp->patch.timbreGroup, patchTemp->patch.timbreNum, patchTemp->patch.keyShift, patchTemp->patch.fineTune, patchTemp->patch.benderRange, patchTemp->patch.assignMode, patchTemp->patch.reverbSwitch);
synth->printDebug(" PatchTemp: outputLevel %u, (panpot %u)", patchTemp->outputLevel, patchTemp->panpot);
synth->printDebug(" RhythmTemp: timbre %u, outputLevel %u, panpot %u, reverbSwitch %u", rhythmTemp[drumNum].timbre, rhythmTemp[drumNum].outputLevel, rhythmTemp[drumNum].panpot, rhythmTemp[drumNum].reverbSwitch);
#endif
#endif
playPoly(drumCache[drumNum], &rhythmTemp[drumNum], midiKey, key, velocity);
}
void Part::noteOn(unsigned int midiKey, unsigned int velocity) {
unsigned int key = midiKeyToKey(midiKey);
if (patchCache[0].dirty) {
cacheTimbre(patchCache, timbreTemp);
}
#if MT32EMU_MONITOR_INSTRUMENTS > 0
synth->printDebug("%s (%s): Start poly: midiKey %u, key %u, velo %u, mod %u, exp %u, bend %u", name, currentInstr, midiKey, key, velocity, modulation, expression, pitchBend);
#if MT32EMU_MONITOR_INSTRUMENTS > 1
synth->printDebug(" Patch: timbreGroup %u, timbreNum %u, keyShift %u, fineTune %u, benderRange %u, assignMode %u, reverbSwitch %u", patchTemp->patch.timbreGroup, patchTemp->patch.timbreNum, patchTemp->patch.keyShift, patchTemp->patch.fineTune, patchTemp->patch.benderRange, patchTemp->patch.assignMode, patchTemp->patch.reverbSwitch);
synth->printDebug(" PatchTemp: outputLevel %u, panpot %u", patchTemp->outputLevel, patchTemp->panpot);
#endif
#endif
playPoly(patchCache, NULL, midiKey, key, velocity);
}
bool Part::abortFirstPoly(unsigned int key) {
for (Poly *poly = activePolys.getFirst(); poly != NULL; poly = poly->getNext()) {
if (poly->getKey() == key) {
return poly->startAbort();
}
}
return false;
}
bool Part::abortFirstPoly(PolyState polyState) {
for (Poly *poly = activePolys.getFirst(); poly != NULL; poly = poly->getNext()) {
if (poly->getState() == polyState) {
return poly->startAbort();
}
}
return false;
}
bool Part::abortFirstPolyPreferHeld() {
if (abortFirstPoly(POLY_Held)) {
return true;
}
return abortFirstPoly();
}
bool Part::abortFirstPoly() {
if (activePolys.isEmpty()) {
return false;
}
return activePolys.getFirst()->startAbort();
}
void Part::playPoly(const PatchCache cache[4], const MemParams::RhythmTemp *rhythmTemp, unsigned int midiKey, unsigned int key, unsigned int velocity) {
// CONFIRMED: Even in single-assign mode, we don't abort playing polys if the timbre to play is completely muted.
unsigned int needPartials = cache[0].partialCount;
if (needPartials == 0) {
synth->printDebug("%s (%s): Completely muted instrument", name, currentInstr);
return;
}
if ((patchTemp->patch.assignMode & 2) == 0) {
// Single-assign mode
abortFirstPoly(key);
if (synth->isAbortingPoly()) return;
}
if (!synth->partialManager->freePartials(needPartials, partNum)) {
#if MT32EMU_MONITOR_PARTIALS > 0
synth->printDebug("%s (%s): Insufficient free partials to play key %d (velocity %d); needed=%d, free=%d, assignMode=%d", name, currentInstr, midiKey, velocity, needPartials, synth->partialManager->getFreePartialCount(), patchTemp->patch.assignMode);
synth->printPartialUsage();
#endif
return;
}
if (synth->isAbortingPoly()) return;
Poly *poly = synth->partialManager->assignPolyToPart(this);
if (poly == NULL) {
synth->printDebug("%s (%s): No free poly to play key %d (velocity %d)", name, currentInstr, midiKey, velocity);
return;
}
if (patchTemp->patch.assignMode & 1) {
// Priority to data first received
activePolys.prepend(poly);
} else {
activePolys.append(poly);
}
Partial *partials[4];
for (int x = 0; x < 4; x++) {
if (cache[x].playPartial) {
partials[x] = synth->partialManager->allocPartial(partNum);
activePartialCount++;
} else {
partials[x] = NULL;
}
}
poly->reset(key, velocity, cache[0].sustain, partials);
for (int x = 0; x < 4; x++) {
if (partials[x] != NULL) {
#if MT32EMU_MONITOR_PARTIALS > 2
synth->printDebug("%s (%s): Allocated partial %d", name, currentInstr, partials[x]->debugGetPartialNum());
#endif
partials[x]->startPartial(this, poly, &cache[x], rhythmTemp, partials[cache[x].structurePair]);
}
}
#if MT32EMU_MONITOR_PARTIALS > 1
synth->printPartialUsage();
#endif
synth->reportHandler->onPolyStateChanged(Bit8u(partNum));
}
void Part::allNotesOff() {
// The MIDI specification states - and Mok confirms - that all notes off (0x7B)
// should treat the hold pedal as usual.
for (Poly *poly = activePolys.getFirst(); poly != NULL; poly = poly->getNext()) {
// FIXME: This has special handling of key 0 in NoteOff that Mok has not yet confirmed applies to AllNotesOff.
// if (poly->canSustain() || poly->getKey() == 0) {
// FIXME: The real devices are found to be ignoring non-sustaining polys while processing AllNotesOff. Need to be confirmed.
if (poly->canSustain()) {
poly->noteOff(holdpedal);
}
}
}
void Part::allSoundOff() {
// MIDI "All sound off" (0x78) should release notes immediately regardless of the hold pedal.
// This controller is not actually implemented by the synths, though (according to the docs and Mok) -
// we're only using this method internally.
for (Poly *poly = activePolys.getFirst(); poly != NULL; poly = poly->getNext()) {
poly->startDecay();
}
}
void Part::stopPedalHold() {
for (Poly *poly = activePolys.getFirst(); poly != NULL; poly = poly->getNext()) {
poly->stopPedalHold();
}
}
void RhythmPart::noteOff(unsigned int midiKey) {
stopNote(midiKey);
}
void Part::noteOff(unsigned int midiKey) {
stopNote(midiKeyToKey(midiKey));
}
void Part::stopNote(unsigned int key) {
#if MT32EMU_MONITOR_INSTRUMENTS > 0
synth->printDebug("%s (%s): stopping key %d", name, currentInstr, key);
#endif
for (Poly *poly = activePolys.getFirst(); poly != NULL; poly = poly->getNext()) {
// Generally, non-sustaining instruments ignore note off. They die away eventually anyway.
// Key 0 (only used by special cases on rhythm part) reacts to note off even if non-sustaining or pedal held.
if (poly->getKey() == key && (poly->canSustain() || key == 0)) {
if (poly->noteOff(holdpedal && key != 0)) {
break;
}
}
}
}
const MemParams::PatchTemp *Part::getPatchTemp() const {
return patchTemp;
}
unsigned int Part::getActivePartialCount() const {
return activePartialCount;
}
const Poly *Part::getFirstActivePoly() const {
return activePolys.getFirst();
}
unsigned int Part::getActiveNonReleasingPartialCount() const {
unsigned int activeNonReleasingPartialCount = 0;
for (Poly *poly = activePolys.getFirst(); poly != NULL; poly = poly->getNext()) {
if (poly->getState() != POLY_Releasing) {
activeNonReleasingPartialCount += poly->getActivePartialCount();
}
}
return activeNonReleasingPartialCount;
}
Synth *Part::getSynth() const {
return synth;
}
void Part::partialDeactivated(Poly *poly) {
activePartialCount--;
if (!poly->isActive()) {
activePolys.remove(poly);
synth->partialManager->polyFreed(poly);
synth->reportHandler->onPolyStateChanged(Bit8u(partNum));
}
}
void RhythmPart::polyStateChanged(PolyState, PolyState) {}
void Part::polyStateChanged(PolyState oldState, PolyState newState) {
switch (newState) {
case POLY_Playing:
if (activeNonReleasingPolyCount++ == 0) synth->voicePartStateChanged(partNum, true);
break;
case POLY_Releasing:
case POLY_Inactive:
if (oldState == POLY_Playing || oldState == POLY_Held) {
if (--activeNonReleasingPolyCount == 0) synth->voicePartStateChanged(partNum, false);
}
break;
default:
break;
}
#ifdef MT32EMU_TRACE_POLY_STATE_CHANGES
synth->printDebug("Part %d: Changed poly state %d->%d, activeNonReleasingPolyCount=%d", partNum, oldState, newState, activeNonReleasingPolyCount);
#endif
}
PolyList::PolyList() : firstPoly(NULL), lastPoly(NULL) {}
bool PolyList::isEmpty() const {
#ifdef MT32EMU_POLY_LIST_DEBUG
if ((firstPoly == NULL || lastPoly == NULL) && firstPoly != lastPoly) {
printf("PolyList: desynchronised firstPoly & lastPoly pointers\n");
}
#endif
return firstPoly == NULL && lastPoly == NULL;
}
Poly *PolyList::getFirst() const {
return firstPoly;
}
Poly *PolyList::getLast() const {
return lastPoly;
}
void PolyList::prepend(Poly *poly) {
#ifdef MT32EMU_POLY_LIST_DEBUG
if (poly->getNext() != NULL) {
printf("PolyList: Non-NULL next field in a Poly being prepended is ignored\n");
}
#endif
poly->setNext(firstPoly);
firstPoly = poly;
if (lastPoly == NULL) {
lastPoly = poly;
}
}
void PolyList::append(Poly *poly) {
#ifdef MT32EMU_POLY_LIST_DEBUG
if (poly->getNext() != NULL) {
printf("PolyList: Non-NULL next field in a Poly being appended is ignored\n");
}
#endif
poly->setNext(NULL);
if (lastPoly != NULL) {
#ifdef MT32EMU_POLY_LIST_DEBUG
if (lastPoly->getNext() != NULL) {
printf("PolyList: Non-NULL next field in the lastPoly\n");
}
#endif
lastPoly->setNext(poly);
}
lastPoly = poly;
if (firstPoly == NULL) {
firstPoly = poly;
}
}
Poly *PolyList::takeFirst() {
Poly *oldFirst = firstPoly;
firstPoly = oldFirst->getNext();
if (firstPoly == NULL) {
#ifdef MT32EMU_POLY_LIST_DEBUG
if (lastPoly != oldFirst) {
printf("PolyList: firstPoly != lastPoly in a list with a single Poly\n");
}
#endif
lastPoly = NULL;
}
oldFirst->setNext(NULL);
return oldFirst;
}
void PolyList::remove(Poly * const polyToRemove) {
if (polyToRemove == firstPoly) {
takeFirst();
return;
}
for (Poly *poly = firstPoly; poly != NULL; poly = poly->getNext()) {
if (poly->getNext() == polyToRemove) {
if (polyToRemove == lastPoly) {
#ifdef MT32EMU_POLY_LIST_DEBUG
if (lastPoly->getNext() != NULL) {
printf("PolyList: Non-NULL next field in the lastPoly\n");
}
#endif
lastPoly = poly;
}
poly->setNext(polyToRemove->getNext());
polyToRemove->setNext(NULL);
break;
}
}
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/Part.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 6,849 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstddef>
#include <cstring>
#include "internals.h"
#include "PartialManager.h"
#include "Part.h"
#include "Partial.h"
#include "Poly.h"
#include "Synth.h"
namespace MT32Emu {
PartialManager::PartialManager(Synth *useSynth, Part **useParts) {
synth = useSynth;
parts = useParts;
inactivePartialCount = synth->getPartialCount();
partialTable = new Partial *[inactivePartialCount];
inactivePartials = new int[inactivePartialCount];
freePolys = new Poly *[synth->getPartialCount()];
firstFreePolyIndex = 0;
for (unsigned int i = 0; i < synth->getPartialCount(); i++) {
partialTable[i] = new Partial(synth, i);
inactivePartials[i] = inactivePartialCount - i - 1;
freePolys[i] = new Poly();
}
}
PartialManager::~PartialManager(void) {
for (unsigned int i = 0; i < synth->getPartialCount(); i++) {
delete partialTable[i];
if (freePolys[i] != NULL) delete freePolys[i];
}
delete[] partialTable;
delete[] inactivePartials;
delete[] freePolys;
}
void PartialManager::clearAlreadyOutputed() {
for (unsigned int i = 0; i < synth->getPartialCount(); i++) {
partialTable[i]->alreadyOutputed = false;
}
}
bool PartialManager::shouldReverb(int i) {
return partialTable[i]->shouldReverb();
}
bool PartialManager::produceOutput(int i, IntSample *leftBuf, IntSample *rightBuf, Bit32u bufferLength) {
return partialTable[i]->produceOutput(leftBuf, rightBuf, bufferLength);
}
bool PartialManager::produceOutput(int i, FloatSample *leftBuf, FloatSample *rightBuf, Bit32u bufferLength) {
return partialTable[i]->produceOutput(leftBuf, rightBuf, bufferLength);
}
void PartialManager::deactivateAll() {
for (unsigned int i = 0; i < synth->getPartialCount(); i++) {
partialTable[i]->deactivate();
}
}
unsigned int PartialManager::setReserve(Bit8u *rset) {
unsigned int pr = 0;
for (int x = 0; x <= 8; x++) {
numReservedPartialsForPart[x] = rset[x];
pr += rset[x];
}
return pr;
}
Partial *PartialManager::allocPartial(int partNum) {
if (inactivePartialCount > 0) {
Partial *partial = partialTable[inactivePartials[--inactivePartialCount]];
partial->activate(partNum);
return partial;
}
synth->printDebug("PartialManager Error: No inactive partials to allocate for part %d, current partial state:\n", partNum);
for (Bit32u i = 0; i < synth->getPartialCount(); i++) {
const Partial *partial = partialTable[i];
synth->printDebug("[Partial %d]: activation=%d, owner part=%d\n", i, partial->isActive(), partial->getOwnerPart());
}
return NULL;
}
unsigned int PartialManager::getFreePartialCount() {
return inactivePartialCount;
}
// This function is solely used to gather data for debug output at the moment.
void PartialManager::getPerPartPartialUsage(unsigned int perPartPartialUsage[9]) {
memset(perPartPartialUsage, 0, 9 * sizeof(unsigned int));
for (unsigned int i = 0; i < synth->getPartialCount(); i++) {
if (partialTable[i]->isActive()) {
perPartPartialUsage[partialTable[i]->getOwnerPart()]++;
}
}
}
// Finds the lowest-priority part that is exceeding its reserved partial allocation and has a poly
// in POLY_Releasing, then kills its first releasing poly.
// Parts with higher priority than minPart are not checked.
// Assumes that getFreePartials() has been called to make numReservedPartialsForPart up-to-date.
bool PartialManager::abortFirstReleasingPolyWhereReserveExceeded(int minPart) {
if (minPart == 8) {
// Rhythm is highest priority
minPart = -1;
}
for (int partNum = 7; partNum >= minPart; partNum--) {
int usePartNum = partNum == -1 ? 8 : partNum;
if (parts[usePartNum]->getActivePartialCount() > numReservedPartialsForPart[usePartNum]) {
// This part has exceeded its reserved partial count.
// If it has any releasing polys, kill its first one and we're done.
if (parts[usePartNum]->abortFirstPoly(POLY_Releasing)) {
return true;
}
}
}
return false;
}
// Finds the lowest-priority part that is exceeding its reserved partial allocation and has a poly, then kills
// its first poly in POLY_Held - or failing that, its first poly in any state.
// Parts with higher priority than minPart are not checked.
// Assumes that getFreePartials() has been called to make numReservedPartialsForPart up-to-date.
bool PartialManager::abortFirstPolyPreferHeldWhereReserveExceeded(int minPart) {
if (minPart == 8) {
// Rhythm is highest priority
minPart = -1;
}
for (int partNum = 7; partNum >= minPart; partNum--) {
int usePartNum = partNum == -1 ? 8 : partNum;
if (parts[usePartNum]->getActivePartialCount() > numReservedPartialsForPart[usePartNum]) {
// This part has exceeded its reserved partial count.
// If it has any polys, kill its first (preferably held) one and we're done.
if (parts[usePartNum]->abortFirstPolyPreferHeld()) {
return true;
}
}
}
return false;
}
bool PartialManager::freePartials(unsigned int needed, int partNum) {
// CONFIRMED: Barring bugs, this matches the real LAPC-I according to information from Mok.
// BUG: There's a bug in the LAPC-I implementation:
// When allocating for rhythm part, or when allocating for a part that is using fewer partials than it has reserved,
// held and playing polys on the rhythm part can potentially be aborted before releasing polys on the rhythm part.
// This bug isn't present on MT-32.
// I consider this to be a bug because I think that playing polys should always have priority over held polys,
// and held polys should always have priority over releasing polys.
// NOTE: This code generally aborts polys in parts (according to certain conditions) in the following order:
// 7, 6, 5, 4, 3, 2, 1, 0, 8 (rhythm)
// (from lowest priority, meaning most likely to have polys aborted, to highest priority, meaning least likely)
if (needed == 0) {
return true;
}
// Note that calling getFreePartialCount() also ensures that numReservedPartialsPerPart is up-to-date
if (getFreePartialCount() >= needed) {
return true;
}
// Note: These #ifdefs are temporary until we have proper "quirk" configuration.
// Also, the MT-32 version isn't properly confirmed yet.
#ifdef MT32EMU_QUIRK_FREE_PARTIALS_MT32
// On MT-32, we bail out before even killing releasing partials if the allocating part has exceeded its reserve and is configured for priority-to-earlier-polys.
if (parts[partNum]->getActiveNonReleasingPartialCount() + needed > numReservedPartialsForPart[partNum] && (synth->getPart(partNum)->getPatchTemp()->patch.assignMode & 1)) {
return false;
}
#endif
for (;;) {
#ifdef MT32EMU_QUIRK_FREE_PARTIALS_MT32
// Abort releasing polys in parts that have exceeded their partial reservation (working backwards from part 7, with rhythm last)
if (!abortFirstReleasingPolyWhereReserveExceeded(-1)) {
break;
}
#else
// Abort releasing polys in non-rhythm parts that have exceeded their partial reservation (working backwards from part 7)
if (!abortFirstReleasingPolyWhereReserveExceeded(0)) {
break;
}
#endif
if (synth->isAbortingPoly() || getFreePartialCount() >= needed) {
return true;
}
}
if (parts[partNum]->getActiveNonReleasingPartialCount() + needed > numReservedPartialsForPart[partNum]) {
// With the new partials we're freeing for, we would end up using more partials than we have reserved.
if (synth->getPart(partNum)->getPatchTemp()->patch.assignMode & 1) {
// Priority is given to earlier polys, so just give up
return false;
}
// Only abort held polys in the target part and parts that have a lower priority
// (higher part number = lower priority, except for rhythm, which has the highest priority).
for (;;) {
if (!abortFirstPolyPreferHeldWhereReserveExceeded(partNum)) {
break;
}
if (synth->isAbortingPoly() || getFreePartialCount() >= needed) {
return true;
}
}
if (needed > numReservedPartialsForPart[partNum]) {
return false;
}
} else {
// At this point, we're certain that we've reserved enough partials to play our poly.
// Check all parts from lowest to highest priority to see whether they've exceeded their
// reserve, and abort their polys until until we have enough free partials or they're within
// their reserve allocation.
for (;;) {
if (!abortFirstPolyPreferHeldWhereReserveExceeded(-1)) {
break;
}
if (synth->isAbortingPoly() || getFreePartialCount() >= needed) {
return true;
}
}
}
// Abort polys in the target part until there are enough free partials for the new one
for (;;) {
if (!parts[partNum]->abortFirstPolyPreferHeld()) {
break;
}
if (synth->isAbortingPoly() || getFreePartialCount() >= needed) {
return true;
}
}
// Aww, not enough partials for you.
return false;
}
const Partial *PartialManager::getPartial(unsigned int partialNum) const {
if (partialNum > synth->getPartialCount() - 1) {
return NULL;
}
return partialTable[partialNum];
}
Poly *PartialManager::assignPolyToPart(Part *part) {
if (firstFreePolyIndex < synth->getPartialCount()) {
Poly *poly = freePolys[firstFreePolyIndex];
freePolys[firstFreePolyIndex] = NULL;
firstFreePolyIndex++;
poly->setPart(part);
return poly;
}
return NULL;
}
void PartialManager::polyFreed(Poly *poly) {
if (0 == firstFreePolyIndex) {
synth->printDebug("PartialManager Error: Cannot return freed poly, currently active polys:\n");
for (Bit32u partNum = 0; partNum < 9; partNum++) {
const Poly *activePoly = synth->getPart(partNum)->getFirstActivePoly();
Bit32u polyCount = 0;
while (activePoly != NULL) {
activePoly = activePoly->getNext();
polyCount++;
}
synth->printDebug("Part: %i, active poly count: %i\n", partNum, polyCount);
}
} else {
firstFreePolyIndex--;
freePolys[firstFreePolyIndex] = poly;
}
poly->setPart(NULL);
}
void PartialManager::partialDeactivated(int partialIndex) {
if (inactivePartialCount < synth->getPartialCount()) {
inactivePartials[inactivePartialCount++] = partialIndex;
return;
}
synth->printDebug("PartialManager Error: Cannot return deactivated partial %d, current partial state:\n", partialIndex);
for (Bit32u i = 0; i < synth->getPartialCount(); i++) {
const Partial *partial = partialTable[i];
synth->printDebug("[Partial %d]: activation=%d, owner part=%d\n", i, partial->isActive(), partial->getOwnerPart());
}
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/PartialManager.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,879 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_MT32EMU_H
#define MT32EMU_MT32EMU_H
#include "config.h"
/* API Configuration */
/* 0: Use full-featured C++ API. Well suitable when the library is to be linked statically.
* When the library is shared, ABI compatibility may be an issue. Therefore, it should
* only be used within a project comprising of several modules to share the library code.
* 1: Use C-compatible API. Make the library looks as a regular C library with well-defined ABI.
* This is also crucial when the library is to be linked with modules in a different
* language, either statically or dynamically.
* 2: Use plugin-like API via C-interface wrapped in a C++ class. This is mainly intended
* for a shared library being dynamically loaded in run-time. To get access to all the library
* services, a client application only needs to bind with a single factory function.
* 3: Use optimised C++ API compatible with the plugin API (type 2). The facade class also wraps
* the C functions but they are invoked directly. This enables the compiler to generate better
* code for the library when linked statically yet being consistent with the plugin-like API.
*/
#ifdef MT32EMU_API_TYPE
# if MT32EMU_API_TYPE == 0 && (MT32EMU_EXPORTS_TYPE == 1 || MT32EMU_EXPORTS_TYPE == 2)
# error Incompatible setting MT32EMU_API_TYPE=0
# elif MT32EMU_API_TYPE == 1 && (MT32EMU_EXPORTS_TYPE == 0 || MT32EMU_EXPORTS_TYPE == 2)
# error Incompatible setting MT32EMU_API_TYPE=1
# elif MT32EMU_API_TYPE == 2 && (MT32EMU_EXPORTS_TYPE == 0)
# error Incompatible setting MT32EMU_API_TYPE=2
# elif MT32EMU_API_TYPE == 3 && (MT32EMU_EXPORTS_TYPE == 0 || MT32EMU_EXPORTS_TYPE == 2)
# error Incompatible setting MT32EMU_API_TYPE=3
# endif
#else /* #ifdef MT32EMU_API_TYPE */
# if 0 < MT32EMU_EXPORTS_TYPE && MT32EMU_EXPORTS_TYPE < 3
# define MT32EMU_API_TYPE MT32EMU_EXPORTS_TYPE
# else
# define MT32EMU_API_TYPE 0
# endif
#endif /* #ifdef MT32EMU_API_TYPE */
#include "globals.h"
#if !defined(__cplusplus) || MT32EMU_API_TYPE == 1
#include "c_interface/c_interface.h"
#elif MT32EMU_API_TYPE == 2 || MT32EMU_API_TYPE == 3
#include "c_interface/cpp_interface.h"
#else /* #if !defined(__cplusplus) || MT32EMU_API_TYPE == 1 */
#include "Types.h"
#include "File.h"
#include "FileStream.h"
#include "ROMInfo.h"
#include "Synth.h"
#include "MidiStreamParser.h"
#include "SampleRateConverter.h"
#if MT32EMU_RUNTIME_VERSION_CHECK == 1
#include "VersionTagging.h"
#endif
#endif /* #if !defined(__cplusplus) || MT32EMU_API_TYPE == 1 */
#if MT32EMU_RUNTIME_VERSION_CHECK == 2
#include "VersionTagging.h"
#endif
#endif /* #ifndef MT32EMU_MT32EMU_H */
``` | /content/code_sandbox/src/sound/munt/mt32emu.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 810 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_MMATH_H
#define MT32EMU_MMATH_H
#include <cmath>
namespace MT32Emu {
// Mathematical constants
const double DOUBLE_PI = 3.141592653589793;
const double DOUBLE_LN_10 = 2.302585092994046;
const float FLOAT_PI = 3.1415927f;
const float FLOAT_2PI = 6.2831853f;
const float FLOAT_LN_2 = 0.6931472f;
const float FLOAT_LN_10 = 2.3025851f;
static inline float POWF(float x, float y) {
return pow(x, y);
}
static inline float EXPF(float x) {
return exp(x);
}
static inline float EXP2F(float x) {
#ifdef __APPLE__
// on OSX exp2f() is 1.59 times faster than "exp() and the multiplication with FLOAT_LN_2"
return exp2f(x);
#else
return exp(FLOAT_LN_2 * x);
#endif
}
static inline float EXP10F(float x) {
return exp(FLOAT_LN_10 * x);
}
static inline float LOGF(float x) {
return log(x);
}
static inline float LOG2F(float x) {
return log(x) / FLOAT_LN_2;
}
static inline float LOG10F(float x) {
return log10(x);
}
} // namespace MT32Emu
#endif // #ifndef MT32EMU_MMATH_H
``` | /content/code_sandbox/src/sound/munt/mmath.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 404 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_FILE_STREAM_H
#define MT32EMU_FILE_STREAM_H
#include <fstream>
#include "globals.h"
#include "Types.h"
#include "File.h"
namespace MT32Emu {
class FileStream : public AbstractFile {
public:
MT32EMU_EXPORT FileStream();
MT32EMU_EXPORT ~FileStream();
MT32EMU_EXPORT size_t getSize();
MT32EMU_EXPORT const Bit8u *getData();
MT32EMU_EXPORT bool open(const char *filename);
MT32EMU_EXPORT void close();
private:
std::ifstream &ifsp;
const Bit8u *data;
size_t size;
};
} // namespace MT32Emu
#endif // #ifndef MT32EMU_FILE_STREAM_H
``` | /content/code_sandbox/src/sound/munt/FileStream.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 238 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_PARTIAL_H
#define MT32EMU_PARTIAL_H
#include "globals.h"
#include "internals.h"
#include "Types.h"
#include "Structures.h"
#include "LA32Ramp.h"
#include "LA32WaveGenerator.h"
#include "LA32FloatWaveGenerator.h"
namespace MT32Emu {
class Part;
class Poly;
class Synth;
class TVA;
class TVF;
class TVP;
struct ControlROMPCMStruct;
// A partial represents one of up to four waveform generators currently playing within a poly.
class Partial {
private:
Synth *synth;
const int partialIndex; // Index of this Partial in the global partial table
// Number of the sample currently being rendered by produceOutput(), or 0 if no run is in progress
// This is only kept available for debugging purposes.
Bit32u sampleNum;
// Actually, LA-32 receives only 3 bits as a pan setting, but we abuse these to emulate
// the inverted partial mixing as well. Also we double the values (making them correspond
// to the panpot range) to enable NicePanning mode, with respect to MoK.
Bit32s leftPanValue, rightPanValue;
int ownerPart; // -1 if unassigned
int mixType;
int structurePosition; // 0 or 1 of a structure pair
// Only used for PCM partials
int pcmNum;
// FIXME: Give this a better name (e.g. pcmWaveInfo)
PCMWaveEntry *pcmWave;
// Final pulse width value, with velfollow applied, matching what is sent to the LA32.
// Range: 0-255
int pulseWidthVal;
Poly *poly;
Partial *pair;
TVA *tva;
TVP *tvp;
TVF *tvf;
LA32Ramp ampRamp;
LA32Ramp cutoffModifierRamp;
// TODO: This should be owned by PartialPair
LA32PartialPair *la32Pair;
const bool floatMode;
const PatchCache *patchCache;
PatchCache cachebackup;
Bit32u getAmpValue();
Bit32u getCutoffValue();
template <class Sample, class LA32PairImpl>
bool doProduceOutput(Sample *leftBuf, Sample *rightBuf, Bit32u length, LA32PairImpl *la32PairImpl);
bool canProduceOutput();
template <class LA32PairImpl>
bool generateNextSample(LA32PairImpl *la32PairImpl);
void produceAndMixSample(IntSample *&leftBuf, IntSample *&rightBuf, LA32IntPartialPair *la32IntPair);
void produceAndMixSample(FloatSample *&leftBuf, FloatSample *&rightBuf, LA32FloatPartialPair *la32FloatPair);
public:
bool alreadyOutputed;
Partial(Synth *synth, int debugPartialNum);
~Partial();
int debugGetPartialNum() const;
Bit32u debugGetSampleNum() const;
int getOwnerPart() const;
const Poly *getPoly() const;
bool isActive() const;
void activate(int part);
void deactivate(void);
void startPartial(const Part *part, Poly *usePoly, const PatchCache *useCache, const MemParams::RhythmTemp *rhythmTemp, Partial *pairPartial);
void startAbort();
void startDecayAll();
bool shouldReverb();
bool isRingModulatingNoMix() const;
bool hasRingModulatingSlave() const;
bool isRingModulatingSlave() const;
bool isPCM() const;
const ControlROMPCMStruct *getControlROMPCMStruct() const;
Synth *getSynth() const;
TVA *getTVA() const;
void backupCache(const PatchCache &cache);
// Returns true only if data written to buffer
// These functions produce processed stereo samples
// made from combining this single partial with its pair, if it has one.
bool produceOutput(IntSample *leftBuf, IntSample *rightBuf, Bit32u length);
bool produceOutput(FloatSample *leftBuf, FloatSample *rightBuf, Bit32u length);
}; // class Partial
} // namespace MT32Emu
#endif // #ifndef MT32EMU_PARTIAL_H
``` | /content/code_sandbox/src/sound/munt/Partial.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 985 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_PARTIALMANAGER_H
#define MT32EMU_PARTIALMANAGER_H
#include "globals.h"
#include "internals.h"
#include "Types.h"
namespace MT32Emu {
class Part;
class Partial;
class Poly;
class Synth;
class PartialManager {
private:
Synth *synth;
Part **parts;
Poly **freePolys;
Partial **partialTable;
Bit8u numReservedPartialsForPart[9];
Bit32u firstFreePolyIndex;
int *inactivePartials; // Holds indices of inactive Partials in the Partial table
Bit32u inactivePartialCount;
bool abortFirstReleasingPolyWhereReserveExceeded(int minPart);
bool abortFirstPolyPreferHeldWhereReserveExceeded(int minPart);
public:
PartialManager(Synth *synth, Part **parts);
~PartialManager();
Partial *allocPartial(int partNum);
unsigned int getFreePartialCount();
void getPerPartPartialUsage(unsigned int perPartPartialUsage[9]);
bool freePartials(unsigned int needed, int partNum);
unsigned int setReserve(Bit8u *rset);
void deactivateAll();
bool produceOutput(int i, IntSample *leftBuf, IntSample *rightBuf, Bit32u bufferLength);
bool produceOutput(int i, FloatSample *leftBuf, FloatSample *rightBuf, Bit32u bufferLength);
bool shouldReverb(int i);
void clearAlreadyOutputed();
const Partial *getPartial(unsigned int partialNum) const;
Poly *assignPolyToPart(Part *part);
void polyFreed(Poly *poly);
void partialDeactivated(int partialIndex);
}; // class PartialManager
} // namespace MT32Emu
#endif // #ifndef MT32EMU_PARTIALMANAGER_H
``` | /content/code_sandbox/src/sound/munt/PartialManager.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 465 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_SAMPLE_RATE_CONVERTER_H
#define MT32EMU_SAMPLE_RATE_CONVERTER_H
#include "globals.h"
#include "Types.h"
#include "Enumerations.h"
namespace MT32Emu {
class Synth;
/* SampleRateConverter class allows to convert the synthesiser output to any desired sample rate.
* It processes the completely mixed stereo output signal as it passes the analogue circuit emulation,
* so emulating the synthesiser output signal passing further through an ADC.
* Several conversion quality options are provided which allow to trade-off the conversion speed vs. the passband width.
* All the options except FASTEST guarantee full suppression of the aliasing noise in terms of the 16-bit integer samples.
*/
class MT32EMU_EXPORT SampleRateConverter {
public:
// Returns the value of AnalogOutputMode for which the output signal may retain its full frequency spectrum
// at the sample rate specified by the targetSampleRate argument.
static AnalogOutputMode getBestAnalogOutputMode(double targetSampleRate);
// Returns the sample rate supported by the sample rate conversion implementation currently in effect
// that is closest to the one specified by the desiredSampleRate argument.
static double getSupportedOutputSampleRate(double desiredSampleRate);
// Creates a SampleRateConverter instance that converts output signal from the synth to the given sample rate
// with the specified conversion quality.
SampleRateConverter(Synth &synth, double targetSampleRate, SamplerateConversionQuality quality);
~SampleRateConverter();
// Fills the provided output buffer with the results of the sample rate conversion.
// The input samples are automatically retrieved from the synth as necessary.
void getOutputSamples(MT32Emu::Bit16s *buffer, unsigned int length);
// Fills the provided output buffer with the results of the sample rate conversion.
// The input samples are automatically retrieved from the synth as necessary.
void getOutputSamples(float *buffer, unsigned int length);
// Returns the number of samples produced at the internal synth sample rate (32000 Hz)
// that correspond to the number of samples at the target sample rate.
// Intended to facilitate audio time synchronisation.
double convertOutputToSynthTimestamp(double outputTimestamp) const;
// Returns the number of samples produced at the target sample rate
// that correspond to the number of samples at the internal synth sample rate (32000 Hz).
// Intended to facilitate audio time synchronisation.
double convertSynthToOutputTimestamp(double synthTimestamp) const;
private:
const double synthInternalToTargetSampleRateRatio;
const bool useSynthDelegate;
void * const srcDelegate;
}; // class SampleRateConverter
} // namespace MT32Emu
#endif // MT32EMU_SAMPLE_RATE_CONVERTER_H
``` | /content/code_sandbox/src/sound/munt/SampleRateConverter.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 659 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_TABLES_H
#define MT32EMU_TABLES_H
#include "globals.h"
#include "Types.h"
namespace MT32Emu {
class Tables {
private:
Tables();
Tables(Tables &);
~Tables() {}
public:
static const Tables &getInstance();
// Constant LUTs
// CONFIRMED: This is used to convert several parameters to amp-modifying values in the TVA envelope:
// - PatchTemp.outputLevel
// - RhythmTemp.outlevel
// - PartialParam.tva.level
// - expression
// It's used to determine how much to subtract from the amp envelope's target value
Bit8u levelToAmpSubtraction[101];
// CONFIRMED: ...
Bit8u envLogarithmicTime[256];
// CONFIRMED: ...
Bit8u masterVolToAmpSubtraction[101];
// CONFIRMED:
Bit8u pulseWidth100To255[101];
Bit16u exp9[512];
Bit16u logsin9[512];
const Bit8u *resAmpDecayFactor;
}; // class Tables
} // namespace MT32Emu
#endif // #ifndef MT32EMU_TABLES_H
``` | /content/code_sandbox/src/sound/munt/Tables.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 357 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
/*
* This class emulates the calculations performed by the 8095 microcontroller in order to configure the LA-32's amplitude ramp for a single partial at each stage of its TVA envelope.
* Unless we introduced bugs, it should be pretty much 100% accurate according to Mok's specifications.
*/
#include "internals.h"
#include "TVA.h"
#include "Part.h"
#include "Partial.h"
#include "Poly.h"
#include "Synth.h"
#include "Tables.h"
namespace MT32Emu {
// CONFIRMED: Matches a table in ROM - haven't got around to coming up with a formula for it yet.
static Bit8u biasLevelToAmpSubtractionCoeff[13] = {255, 187, 137, 100, 74, 54, 40, 29, 21, 15, 10, 5, 0};
TVA::TVA(const Partial *usePartial, LA32Ramp *useAmpRamp) :
partial(usePartial), ampRamp(useAmpRamp), system(&usePartial->getSynth()->mt32ram.system), phase(TVA_PHASE_DEAD) {
}
void TVA::startRamp(Bit8u newTarget, Bit8u newIncrement, int newPhase) {
target = newTarget;
phase = newPhase;
ampRamp->startRamp(newTarget, newIncrement);
#if MT32EMU_MONITOR_TVA >= 1
partial->getSynth()->printDebug("[+%lu] [Partial %d] TVA,ramp,%x,%s%x,%d", partial->debugGetSampleNum(), partial->debugGetPartialNum(), newTarget, (newIncrement & 0x80) ? "-" : "+", (newIncrement & 0x7F), newPhase);
#endif
}
void TVA::end(int newPhase) {
phase = newPhase;
playing = false;
#if MT32EMU_MONITOR_TVA >= 1
partial->getSynth()->printDebug("[+%lu] [Partial %d] TVA,end,%d", partial->debugGetSampleNum(), partial->debugGetPartialNum(), newPhase);
#endif
}
static int multBias(Bit8u biasLevel, int bias) {
return (bias * biasLevelToAmpSubtractionCoeff[biasLevel]) >> 5;
}
static int calcBiasAmpSubtraction(Bit8u biasPoint, Bit8u biasLevel, int key) {
if ((biasPoint & 0x40) == 0) {
int bias = biasPoint + 33 - key;
if (bias > 0) {
return multBias(biasLevel, bias);
}
} else {
int bias = biasPoint - 31 - key;
if (bias < 0) {
bias = -bias;
return multBias(biasLevel, bias);
}
}
return 0;
}
static int calcBiasAmpSubtractions(const TimbreParam::PartialParam *partialParam, int key) {
int biasAmpSubtraction1 = calcBiasAmpSubtraction(partialParam->tva.biasPoint1, partialParam->tva.biasLevel1, key);
if (biasAmpSubtraction1 > 255) {
return 255;
}
int biasAmpSubtraction2 = calcBiasAmpSubtraction(partialParam->tva.biasPoint2, partialParam->tva.biasLevel2, key);
if (biasAmpSubtraction2 > 255) {
return 255;
}
int biasAmpSubtraction = biasAmpSubtraction1 + biasAmpSubtraction2;
if (biasAmpSubtraction > 255) {
return 255;
}
return biasAmpSubtraction;
}
static int calcVeloAmpSubtraction(Bit8u veloSensitivity, unsigned int velocity) {
// FIXME:KG: Better variable names
int velocityMult = veloSensitivity - 50;
int absVelocityMult = velocityMult < 0 ? -velocityMult : velocityMult;
velocityMult = signed(unsigned(velocityMult * (signed(velocity) - 64)) << 2);
return absVelocityMult - (velocityMult >> 8); // PORTABILITY NOTE: Assumes arithmetic shift
}
static int calcBasicAmp(const Tables *tables, const Partial *partial, const MemParams::System *system, const TimbreParam::PartialParam *partialParam, Bit8u partVolume, const MemParams::RhythmTemp *rhythmTemp, int biasAmpSubtraction, int veloAmpSubtraction, Bit8u expression, bool hasRingModQuirk) {
int amp = 155;
if (!(hasRingModQuirk ? partial->isRingModulatingNoMix() : partial->isRingModulatingSlave())) {
amp -= tables->masterVolToAmpSubtraction[system->masterVol];
if (amp < 0) {
return 0;
}
amp -= tables->levelToAmpSubtraction[partVolume];
if (amp < 0) {
return 0;
}
amp -= tables->levelToAmpSubtraction[expression];
if (amp < 0) {
return 0;
}
if (rhythmTemp != NULL) {
amp -= tables->levelToAmpSubtraction[rhythmTemp->outputLevel];
if (amp < 0) {
return 0;
}
}
}
amp -= biasAmpSubtraction;
if (amp < 0) {
return 0;
}
amp -= tables->levelToAmpSubtraction[partialParam->tva.level];
if (amp < 0) {
return 0;
}
amp -= veloAmpSubtraction;
if (amp < 0) {
return 0;
}
if (amp > 155) {
amp = 155;
}
amp -= partialParam->tvf.resonance >> 1;
if (amp < 0) {
return 0;
}
return amp;
}
static int calcKeyTimeSubtraction(Bit8u envTimeKeyfollow, int key) {
if (envTimeKeyfollow == 0) {
return 0;
}
return (key - 60) >> (5 - envTimeKeyfollow); // PORTABILITY NOTE: Assumes arithmetic shift
}
void TVA::reset(const Part *newPart, const TimbreParam::PartialParam *newPartialParam, const MemParams::RhythmTemp *newRhythmTemp) {
part = newPart;
partialParam = newPartialParam;
rhythmTemp = newRhythmTemp;
playing = true;
const Tables *tables = &Tables::getInstance();
int key = partial->getPoly()->getKey();
int velocity = partial->getPoly()->getVelocity();
keyTimeSubtraction = calcKeyTimeSubtraction(partialParam->tva.envTimeKeyfollow, key);
biasAmpSubtraction = calcBiasAmpSubtractions(partialParam, key);
veloAmpSubtraction = calcVeloAmpSubtraction(partialParam->tva.veloSensitivity, velocity);
int newTarget = calcBasicAmp(tables, partial, system, partialParam, part->getVolume(), newRhythmTemp, biasAmpSubtraction, veloAmpSubtraction, part->getExpression(), partial->getSynth()->controlROMFeatures->quirkRingModulationNoMix);
int newPhase;
if (partialParam->tva.envTime[0] == 0) {
// Initially go to the TVA_PHASE_ATTACK target amp, and spend the next phase going from there to the TVA_PHASE_2 target amp
// Note that this means that velocity never affects time for this partial.
newTarget += partialParam->tva.envLevel[0];
newPhase = TVA_PHASE_ATTACK; // The first target used in nextPhase() will be TVA_PHASE_2
} else {
// Initially go to the base amp determined by TVA level, part volume, etc., and spend the next phase going from there to the full TVA_PHASE_ATTACK target amp.
newPhase = TVA_PHASE_BASIC; // The first target used in nextPhase() will be TVA_PHASE_ATTACK
}
ampRamp->reset();//currentAmp = 0;
// "Go downward as quickly as possible".
// Since the current value is 0, the LA32Ramp will notice that we're already at or below the target and trying to go downward,
// and therefore jump to the target immediately and raise an interrupt.
startRamp(Bit8u(newTarget), 0x80 | 127, newPhase);
}
void TVA::startAbort() {
startRamp(64, 0x80 | 127, TVA_PHASE_RELEASE);
}
void TVA::startDecay() {
if (phase >= TVA_PHASE_RELEASE) {
return;
}
Bit8u newIncrement;
if (partialParam->tva.envTime[4] == 0) {
newIncrement = 1;
} else {
newIncrement = -partialParam->tva.envTime[4];
}
// The next time nextPhase() is called, it will think TVA_PHASE_RELEASE has finished and the partial will be aborted
startRamp(0, newIncrement, TVA_PHASE_RELEASE);
}
void TVA::handleInterrupt() {
nextPhase();
}
void TVA::recalcSustain() {
// We get pinged periodically by the pitch code to recalculate our values when in sustain.
// This is done so that the TVA will respond to things like MIDI expression and volume changes while it's sustaining, which it otherwise wouldn't do.
// The check for envLevel[3] == 0 strikes me as slightly dumb. FIXME: Explain why
if (phase != TVA_PHASE_SUSTAIN || partialParam->tva.envLevel[3] == 0) {
return;
}
// We're sustaining. Recalculate all the values
const Tables *tables = &Tables::getInstance();
int newTarget = calcBasicAmp(tables, partial, system, partialParam, part->getVolume(), rhythmTemp, biasAmpSubtraction, veloAmpSubtraction, part->getExpression(), partial->getSynth()->controlROMFeatures->quirkRingModulationNoMix);
newTarget += partialParam->tva.envLevel[3];
// Although we're in TVA_PHASE_SUSTAIN at this point, we cannot be sure that there is no active ramp at the moment.
// In case the channel volume or the expression changes frequently, the previously started ramp may still be in progress.
// Real hardware units ignore this possibility and rely on the assumption that the target is the current amp.
// This is OK in most situations but when the ramp that is currently in progress needs to change direction
// due to a volume/expression update, this leads to a jump in the amp that is audible as an unpleasant click.
// To avoid that, we compare the newTarget with the the actual current ramp value and correct the direction if necessary.
int targetDelta = newTarget - target;
// Calculate an increment to get to the new amp value in a short, more or less consistent amount of time
Bit8u newIncrement;
bool descending = targetDelta < 0;
if (!descending) {
newIncrement = tables->envLogarithmicTime[Bit8u(targetDelta)] - 2;
} else {
newIncrement = (tables->envLogarithmicTime[Bit8u(-targetDelta)] - 2) | 0x80;
}
if (part->getSynth()->isNiceAmpRampEnabled() && (descending != ampRamp->isBelowCurrent(newTarget))) {
newIncrement ^= 0x80;
}
// Configure so that once the transition's complete and nextPhase() is called, we'll just re-enter sustain phase (or decay phase, depending on parameters at the time).
startRamp(newTarget, newIncrement, TVA_PHASE_SUSTAIN - 1);
}
bool TVA::isPlaying() const {
return playing;
}
int TVA::getPhase() const {
return phase;
}
void TVA::nextPhase() {
const Tables *tables = &Tables::getInstance();
if (phase >= TVA_PHASE_DEAD || !playing) {
partial->getSynth()->printDebug("TVA::nextPhase(): Shouldn't have got here with phase %d, playing=%s", phase, playing ? "true" : "false");
return;
}
int newPhase = phase + 1;
if (newPhase == TVA_PHASE_DEAD) {
end(newPhase);
return;
}
bool allLevelsZeroFromNowOn = false;
if (partialParam->tva.envLevel[3] == 0) {
if (newPhase == TVA_PHASE_4) {
allLevelsZeroFromNowOn = true;
} else if (!partial->getSynth()->controlROMFeatures->quirkTVAZeroEnvLevels && partialParam->tva.envLevel[2] == 0) {
if (newPhase == TVA_PHASE_3) {
allLevelsZeroFromNowOn = true;
} else if (partialParam->tva.envLevel[1] == 0) {
if (newPhase == TVA_PHASE_2) {
allLevelsZeroFromNowOn = true;
} else if (partialParam->tva.envLevel[0] == 0) {
if (newPhase == TVA_PHASE_ATTACK) { // this line added, missing in ROM - FIXME: Add description of repercussions
allLevelsZeroFromNowOn = true;
}
}
}
}
}
int newTarget;
int newIncrement = 0; // Initialised to please compilers
int envPointIndex = phase;
if (!allLevelsZeroFromNowOn) {
newTarget = calcBasicAmp(tables, partial, system, partialParam, part->getVolume(), rhythmTemp, biasAmpSubtraction, veloAmpSubtraction, part->getExpression(), partial->getSynth()->controlROMFeatures->quirkRingModulationNoMix);
if (newPhase == TVA_PHASE_SUSTAIN || newPhase == TVA_PHASE_RELEASE) {
if (partialParam->tva.envLevel[3] == 0) {
end(newPhase);
return;
}
if (!partial->getPoly()->canSustain()) {
newPhase = TVA_PHASE_RELEASE;
newTarget = 0;
newIncrement = -partialParam->tva.envTime[4];
if (newIncrement == 0) {
// We can't let the increment be 0, or there would be no emulated interrupt.
// So we do an "upward" increment, which should set the amp to 0 extremely quickly
// and cause an "interrupt" to bring us back to nextPhase().
newIncrement = 1;
}
} else {
newTarget += partialParam->tva.envLevel[3];
newIncrement = 0;
}
} else {
newTarget += partialParam->tva.envLevel[envPointIndex];
}
} else {
newTarget = 0;
}
if ((newPhase != TVA_PHASE_SUSTAIN && newPhase != TVA_PHASE_RELEASE) || allLevelsZeroFromNowOn) {
int envTimeSetting = partialParam->tva.envTime[envPointIndex];
if (newPhase == TVA_PHASE_ATTACK) {
envTimeSetting -= (signed(partial->getPoly()->getVelocity()) - 64) >> (6 - partialParam->tva.envTimeVeloSensitivity); // PORTABILITY NOTE: Assumes arithmetic shift
if (envTimeSetting <= 0 && partialParam->tva.envTime[envPointIndex] != 0) {
envTimeSetting = 1;
}
} else {
envTimeSetting -= keyTimeSubtraction;
}
if (envTimeSetting > 0) {
int targetDelta = newTarget - target;
if (targetDelta <= 0) {
if (targetDelta == 0) {
// target and newTarget are the same.
// We can't have an increment of 0 or we wouldn't get an emulated interrupt.
// So instead make the target one less than it really should be and set targetDelta accordingly.
targetDelta = -1;
newTarget--;
if (newTarget < 0) {
// Oops, newTarget is less than zero now, so let's do it the other way:
// Make newTarget one more than it really should've been and set targetDelta accordingly.
// FIXME (apparent bug in real firmware):
// This means targetDelta will be positive just below here where it's inverted, and we'll end up using envLogarithmicTime[-1], and we'll be setting newIncrement to be descending later on, etc..
targetDelta = 1;
newTarget = -newTarget;
}
}
targetDelta = -targetDelta;
newIncrement = tables->envLogarithmicTime[Bit8u(targetDelta)] - envTimeSetting;
if (newIncrement <= 0) {
newIncrement = 1;
}
newIncrement = newIncrement | 0x80;
} else {
// FIXME: The last 22 or so entries in this table are 128 - surely that fucks things up, since that ends up being -128 signed?
newIncrement = tables->envLogarithmicTime[Bit8u(targetDelta)] - envTimeSetting;
if (newIncrement <= 0) {
newIncrement = 1;
}
}
} else {
newIncrement = newTarget >= target ? (0x80 | 127) : 127;
}
// FIXME: What's the point of this? It's checked or set to non-zero everywhere above
if (newIncrement == 0) {
newIncrement = 1;
}
}
startRamp(Bit8u(newTarget), Bit8u(newIncrement), newPhase);
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/TVA.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 4,041 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_LA32_WAVE_GENERATOR_H
#define MT32EMU_LA32_WAVE_GENERATOR_H
#include "globals.h"
#include "internals.h"
#include "Types.h"
namespace MT32Emu {
/**
* LA32 performs wave generation in the log-space that allows replacing multiplications by cheap additions
* It's assumed that only low-bit multiplications occur in a few places which are unavoidable like these:
* - interpolation of exponent table (obvious, a delta value has 4 bits)
* - computation of resonance amp decay envelope (the table contains values with 1-2 "1" bits except the very first value 31 but this case can be found using inversion)
* - interpolation of PCM samples (obvious, the wave position counter is in the linear space, there is no log() table in the chip)
* and it seems to be implemented in the same way as in the Boss chip, i.e. right shifted additions which involved noticeable precision loss
* Subtraction is supposed to be replaced by simple inversion
* As the logarithmic sine is always negative, all the logarithmic values are treated as decrements
*/
struct LogSample {
// 16-bit fixed point value, includes 12-bit fractional part
// 4-bit integer part allows to present any 16-bit sample in the log-space
// Obviously, the log value doesn't contain the sign of the resulting sample
Bit16u logValue;
enum {
POSITIVE,
NEGATIVE
} sign;
};
class LA32Utilites {
public:
static Bit16u interpolateExp(const Bit16u fract);
static Bit16s unlog(const LogSample &logSample);
static void addLogSamples(LogSample &logSample1, const LogSample &logSample2);
};
/**
* LA32WaveGenerator is aimed to represent the exact model of LA32 wave generator.
* The output square wave is created by adding high / low linear segments in-between
* the rising and falling cosine segments. Basically, it's very similar to the phase distortion synthesis.
* Behaviour of a true resonance filter is emulated by adding decaying sine wave.
* The beginning and the ending of the resonant sine is multiplied by a cosine window.
* To synthesise sawtooth waves, the resulting square wave is multiplied by synchronous cosine wave.
*/
class LA32WaveGenerator {
//***************************************************************************
// The local copy of partial parameters below
//***************************************************************************
bool active;
// True means the resulting square wave is to be multiplied by the synchronous cosine
bool sawtoothWaveform;
// Logarithmic amp of the wave generator
Bit32u amp;
// Logarithmic frequency of the resulting wave
Bit16u pitch;
// Values in range [1..31]
// Value 1 correspong to the minimum resonance
Bit8u resonance;
// Processed value in range [0..255]
// Values in range [0..128] have no effect and the resulting wave remains symmetrical
// Value 255 corresponds to the maximum possible asymmetric of the resulting wave
Bit8u pulseWidth;
// Composed of the base cutoff in range [78..178] left-shifted by 18 bits and the TVF modifier
Bit32u cutoffVal;
// Logarithmic PCM sample start address
const Bit16s *pcmWaveAddress;
// Logarithmic PCM sample length
Bit32u pcmWaveLength;
// true for looped logarithmic PCM samples
bool pcmWaveLooped;
// false for slave PCM partials in the structures with the ring modulation
bool pcmWaveInterpolated;
//***************************************************************************
// Internal variables below
//***************************************************************************
// Relative position within either the synth wave or the PCM sampled wave
// 0 - start of the positive rising sine segment of the square wave or start of the PCM sample
// 1048576 (2^20) - end of the negative rising sine segment of the square wave
// For PCM waves, the address of the currently playing sample equals (wavePosition / 256)
Bit32u wavePosition;
// Relative position within a square wave phase:
// 0 - start of the phase
// 262144 (2^18) - end of a sine phase in the square wave
Bit32u squareWavePosition;
// Relative position within the positive or negative wave segment:
// 0 - start of the corresponding positive or negative segment of the square wave
// 262144 (2^18) - corresponds to end of the first sine phase in the square wave
// The same increment sampleStep is used to indicate the current position
// since the length of the resonance wave is always equal to four square wave sine segments.
Bit32u resonanceSinePosition;
// The amp of the resonance sine wave grows with the resonance value
// As the resonance value cannot change while the partial is active, it is initialised once
Bit32u resonanceAmpSubtraction;
// The decay speed of resonance sine wave, depends on the resonance value
Bit32u resAmpDecayFactor;
// Fractional part of the pcmPosition
Bit32u pcmInterpolationFactor;
// Current phase of the square wave
enum {
POSITIVE_RISING_SINE_SEGMENT,
POSITIVE_LINEAR_SEGMENT,
POSITIVE_FALLING_SINE_SEGMENT,
NEGATIVE_FALLING_SINE_SEGMENT,
NEGATIVE_LINEAR_SEGMENT,
NEGATIVE_RISING_SINE_SEGMENT
} phase;
// Current phase of the resonance wave
enum ResonancePhase {
POSITIVE_RISING_RESONANCE_SINE_SEGMENT,
POSITIVE_FALLING_RESONANCE_SINE_SEGMENT,
NEGATIVE_FALLING_RESONANCE_SINE_SEGMENT,
NEGATIVE_RISING_RESONANCE_SINE_SEGMENT
} resonancePhase;
// Resulting log-space samples of the square and resonance waves
LogSample squareLogSample;
LogSample resonanceLogSample;
// Processed neighbour log-space samples of the PCM wave
LogSample firstPCMLogSample;
LogSample secondPCMLogSample;
//***************************************************************************
// Internal methods below
//***************************************************************************
Bit32u getSampleStep();
Bit32u getResonanceWaveLengthFactor(Bit32u effectiveCutoffValue);
Bit32u getHighLinearLength(Bit32u effectiveCutoffValue);
void computePositions(Bit32u highLinearLength, Bit32u lowLinearLength, Bit32u resonanceWaveLengthFactor);
void advancePosition();
void generateNextSquareWaveLogSample();
void generateNextResonanceWaveLogSample();
void generateNextSawtoothCosineLogSample(LogSample &logSample) const;
void pcmSampleToLogSample(LogSample &logSample, const Bit16s pcmSample) const;
void generateNextPCMWaveLogSamples();
public:
// Initialise the WG engine for generation of synth partial samples and set up the invariant parameters
void initSynth(const bool sawtoothWaveform, const Bit8u pulseWidth, const Bit8u resonance);
// Initialise the WG engine for generation of PCM partial samples and set up the invariant parameters
void initPCM(const Bit16s * const pcmWaveAddress, const Bit32u pcmWaveLength, const bool pcmWaveLooped, const bool pcmWaveInterpolated);
// Update parameters with respect to TVP, TVA and TVF, and generate next sample
void generateNextSample(const Bit32u amp, const Bit16u pitch, const Bit32u cutoff);
// WG output in the log-space consists of two components which are to be added (or ring modulated) in the linear-space afterwards
LogSample getOutputLogSample(const bool first) const;
// Deactivate the WG engine
void deactivate();
// Return active state of the WG engine
bool isActive() const;
// Return true if the WG engine generates PCM wave samples
bool isPCMWave() const;
// Return current PCM interpolation factor
Bit32u getPCMInterpolationFactor() const;
}; // class LA32WaveGenerator
// LA32PartialPair contains a structure of two partials being mixed / ring modulated
class LA32PartialPair {
public:
enum PairType {
MASTER,
SLAVE
};
virtual ~LA32PartialPair() {}
// ringModulated should be set to false for the structures with mixing or stereo output
// ringModulated should be set to true for the structures with ring modulation
// mixed is used for the structures with ring modulation and indicates whether the master partial output is mixed to the ring modulator output
virtual void init(const bool ringModulated, const bool mixed) = 0;
// Initialise the WG engine for generation of synth partial samples and set up the invariant parameters
virtual void initSynth(const PairType master, const bool sawtoothWaveform, const Bit8u pulseWidth, const Bit8u resonance) = 0;
// Initialise the WG engine for generation of PCM partial samples and set up the invariant parameters
virtual void initPCM(const PairType master, const Bit16s * const pcmWaveAddress, const Bit32u pcmWaveLength, const bool pcmWaveLooped) = 0;
// Deactivate the WG engine
virtual void deactivate(const PairType master) = 0;
}; // class LA32PartialPair
class LA32IntPartialPair : public LA32PartialPair {
LA32WaveGenerator master;
LA32WaveGenerator slave;
bool ringModulated;
bool mixed;
static Bit16s unlogAndMixWGOutput(const LA32WaveGenerator &wg);
public:
// ringModulated should be set to false for the structures with mixing or stereo output
// ringModulated should be set to true for the structures with ring modulation
// mixed is used for the structures with ring modulation and indicates whether the master partial output is mixed to the ring modulator output
void init(const bool ringModulated, const bool mixed);
// Initialise the WG engine for generation of synth partial samples and set up the invariant parameters
void initSynth(const PairType master, const bool sawtoothWaveform, const Bit8u pulseWidth, const Bit8u resonance);
// Initialise the WG engine for generation of PCM partial samples and set up the invariant parameters
void initPCM(const PairType master, const Bit16s * const pcmWaveAddress, const Bit32u pcmWaveLength, const bool pcmWaveLooped);
// Update parameters with respect to TVP, TVA and TVF, and generate next sample
void generateNextSample(const PairType master, const Bit32u amp, const Bit16u pitch, const Bit32u cutoff);
// Perform mixing / ring modulation of WG output and return the result
// Although, LA32 applies panning itself, we assume it is applied in the mixer, not within a pair
Bit16s nextOutSample();
// Deactivate the WG engine
void deactivate(const PairType master);
// Return active state of the WG engine
bool isActive(const PairType master) const;
}; // class LA32IntPartialPair
} // namespace MT32Emu
#endif // #ifndef MT32EMU_LA32_WAVE_GENERATOR_H
``` | /content/code_sandbox/src/sound/munt/LA32WaveGenerator.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,458 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_TVA_H
#define MT32EMU_TVA_H
#include "globals.h"
#include "Types.h"
#include "Structures.h"
namespace MT32Emu {
class LA32Ramp;
class Part;
class Partial;
// Note that when entering nextPhase(), newPhase is set to phase + 1, and the descriptions/names below refer to
// newPhase's value.
enum {
// In this phase, the base amp (as calculated in calcBasicAmp()) is targeted with an instant time.
// This phase is entered by reset() only if time[0] != 0.
TVA_PHASE_BASIC = 0,
// In this phase, level[0] is targeted within time[0], and velocity potentially affects time
TVA_PHASE_ATTACK = 1,
// In this phase, level[1] is targeted within time[1]
TVA_PHASE_2 = 2,
// In this phase, level[2] is targeted within time[2]
TVA_PHASE_3 = 3,
// In this phase, level[3] is targeted within time[3]
TVA_PHASE_4 = 4,
// In this phase, immediately goes to PHASE_RELEASE unless the poly is set to sustain.
// Aborts the partial if level[3] is 0.
// Otherwise level[3] is continued, no phase change will occur until some external influence (like pedal release)
TVA_PHASE_SUSTAIN = 5,
// In this phase, 0 is targeted within time[4] (the time calculation is quite different from the other phases)
TVA_PHASE_RELEASE = 6,
// It's PHASE_DEAD, Jim.
TVA_PHASE_DEAD = 7
};
class TVA {
private:
const Partial * const partial;
LA32Ramp *ampRamp;
const MemParams::System * const system;
const Part *part;
const TimbreParam::PartialParam *partialParam;
const MemParams::RhythmTemp *rhythmTemp;
bool playing;
int biasAmpSubtraction;
int veloAmpSubtraction;
int keyTimeSubtraction;
Bit8u target;
int phase;
void startRamp(Bit8u newTarget, Bit8u newIncrement, int newPhase);
void end(int newPhase);
void nextPhase();
public:
TVA(const Partial *partial, LA32Ramp *ampRamp);
void reset(const Part *part, const TimbreParam::PartialParam *partialParam, const MemParams::RhythmTemp *rhythmTemp);
void handleInterrupt();
void recalcSustain();
void startDecay();
void startAbort();
bool isPlaying() const;
int getPhase() const;
}; // class TVA
} // namespace MT32Emu
#endif // #ifndef MT32EMU_TVA_H
``` | /content/code_sandbox/src/sound/munt/TVA.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 687 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_FILE_H
#define MT32EMU_FILE_H
#include <cstddef>
#include "globals.h"
#include "Types.h"
namespace MT32Emu {
class MT32EMU_EXPORT File {
public:
// Includes terminator char.
typedef char SHA1Digest[41];
virtual ~File() {}
virtual size_t getSize() = 0;
virtual const Bit8u *getData() = 0;
virtual const SHA1Digest &getSHA1() = 0;
virtual void close() = 0;
};
class MT32EMU_EXPORT AbstractFile : public File {
public:
const SHA1Digest &getSHA1();
protected:
AbstractFile();
AbstractFile(const SHA1Digest &sha1Digest);
private:
bool sha1DigestCalculated;
SHA1Digest sha1Digest;
// Binary compatibility helper.
void *reserved;
};
class MT32EMU_EXPORT ArrayFile : public AbstractFile {
public:
ArrayFile(const Bit8u *data, size_t size);
ArrayFile(const Bit8u *data, size_t size, const SHA1Digest &sha1Digest);
size_t getSize();
const Bit8u *getData();
void close() {}
private:
const Bit8u *data;
size_t size;
};
} // namespace MT32Emu
#endif // #ifndef MT32EMU_FILE_H
``` | /content/code_sandbox/src/sound/munt/File.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 363 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_DISPLAY_H
#define MT32EMU_DISPLAY_H
#include "globals.h"
#include "Types.h"
namespace MT32Emu {
class Synth;
/** Facilitates emulation of internal state of the MIDI MESSAGE LED and the MT-32 LCD. */
class Display {
public:
static const unsigned int LCD_TEXT_SIZE = 20;
enum Mode {
Mode_MAIN, // a.k.a. Master Volume
Mode_STARTUP_MESSAGE,
Mode_PROGRAM_CHANGE,
Mode_CUSTOM_MESSAGE,
Mode_ERROR_MESSAGE
};
Display(Synth &synth);
void checkDisplayStateUpdated(bool &midiMessageLEDState, bool &midiMessageLEDUpdated, bool &lcdUpdated);
/** Returns whether the MIDI MESSAGE LED is ON and fills the targetBuffer parameter. */
bool getDisplayState(char *targetBuffer, bool narrowLCD);
void setMainDisplayMode();
void midiMessagePlayed();
void rhythmNotePlayed();
void voicePartStateChanged(Bit8u partIndex, bool activated);
void masterVolumeChanged();
void programChanged(Bit8u partIndex);
void checksumErrorOccurred();
bool customDisplayMessageReceived(const Bit8u *message, Bit32u startIndex, Bit32u length);
void displayControlMessageReceived(const Bit8u *messageBytes, Bit32u length);
private:
typedef Bit8u DisplayBuffer[LCD_TEXT_SIZE];
static const unsigned int TIMBRE_NAME_SIZE = 10;
Synth &synth;
bool lastLEDState;
bool lcdDirty;
bool lcdUpdateSignalled;
bool lastRhythmPartState;
bool voicePartStates[8];
Bit8u lastProgramChangePartIndex;
const char *lastProgramChangeSoundGroupName;
Bit8u lastProgramChangeTimbreName[TIMBRE_NAME_SIZE];
Mode mode;
Bit32u displayResetTimestamp;
bool displayResetScheduled;
Bit32u midiMessageLEDResetTimestamp;
bool midiMessagePlayedSinceLastReset;
Bit32u rhythmStateResetTimestamp;
bool rhythmNotePlayedSinceLastReset;
DisplayBuffer displayBuffer;
DisplayBuffer customMessageBuffer;
void scheduleDisplayReset();
bool shouldResetTimer(Bit32u scheduledResetTimestamp);
void maybeResetTimer(bool &timerState, Bit32u scheduledResetTimestamp);
};
} // namespace MT32Emu
#endif // #ifndef MT32EMU_DISPLAY_H
``` | /content/code_sandbox/src/sound/munt/Display.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 570 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_INTERNALS_H
#define MT32EMU_INTERNALS_H
#include "Types.h"
// Debugging
// 0: Standard debug output is not stamped with the rendered sample count
// 1: Standard debug output is stamped with the rendered sample count
// NOTE: The "samplestamp" corresponds to the end of the last completed rendering run.
// This is important to bear in mind for debug output that occurs during a run.
#ifndef MT32EMU_DEBUG_SAMPLESTAMPS
#define MT32EMU_DEBUG_SAMPLESTAMPS 0
#endif
// 0: No debug output for initialisation progress
// 1: Debug output for initialisation progress
#ifndef MT32EMU_MONITOR_INIT
#define MT32EMU_MONITOR_INIT 0
#endif
// 0: No debug output for MIDI events
// 1: Debug output for weird MIDI events
#ifndef MT32EMU_MONITOR_MIDI
#define MT32EMU_MONITOR_MIDI 0
#endif
// 0: No debug output for note on/off
// 1: Basic debug output for note on/off
// 2: Comprehensive debug output for note on/off
#ifndef MT32EMU_MONITOR_INSTRUMENTS
#define MT32EMU_MONITOR_INSTRUMENTS 0
#endif
// 0: No debug output for partial allocations
// 1: Show partial stats when an allocation fails
// 2: Show partial stats with every new poly
// 3: Show individual partial allocations/deactivations
#ifndef MT32EMU_MONITOR_PARTIALS
#define MT32EMU_MONITOR_PARTIALS 0
#endif
// 0: No debug output for sysex
// 1: Basic debug output for sysex
#ifndef MT32EMU_MONITOR_SYSEX
#define MT32EMU_MONITOR_SYSEX 0
#endif
// 0: No debug output for sysex writes to the timbre areas
// 1: Debug output with the name and location of newly-written timbres
// 2: Complete dump of timbre parameters for newly-written timbres
#ifndef MT32EMU_MONITOR_TIMBRES
#define MT32EMU_MONITOR_TIMBRES 0
#endif
// 0: No TVA/TVF-related debug output.
// 1: Shows changes to TVA/TVF target, increment and phase.
#ifndef MT32EMU_MONITOR_TVA
#define MT32EMU_MONITOR_TVA 0
#endif
#ifndef MT32EMU_MONITOR_TVF
#define MT32EMU_MONITOR_TVF 0
#endif
// Configuration
// 0: Maximum speed at the cost of a bit lower emulation accuracy.
// 1: Maximum achievable emulation accuracy.
#ifndef MT32EMU_BOSS_REVERB_PRECISE_MODE
#define MT32EMU_BOSS_REVERB_PRECISE_MODE 0
#endif
namespace MT32Emu {
typedef Bit16s IntSample;
typedef Bit32s IntSampleEx;
typedef float FloatSample;
enum PolyState {
POLY_Playing,
POLY_Held, // This marks keys that have been released on the keyboard, but are being held by the pedal
POLY_Releasing,
POLY_Inactive
};
enum ReverbMode {
REVERB_MODE_ROOM,
REVERB_MODE_HALL,
REVERB_MODE_PLATE,
REVERB_MODE_TAP_DELAY
};
} // namespace MT32Emu
#endif // #ifndef MT32EMU_INTERNALS_H
``` | /content/code_sandbox/src/sound/munt/internals.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 797 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstddef>
#include "internals.h"
#include "BReverbModel.h"
#include "Synth.h"
// Analysing of state of reverb RAM address lines gives exact sizes of the buffers of filters used. This also indicates that
// the reverb model implemented in the real devices consists of three series allpass filters preceded by a non-feedback comb (or a delay with a LPF)
// and followed by three parallel comb filters
namespace MT32Emu {
// Because LA-32 chip makes it's output available to process by the Boss chip with a significant delay,
// the Boss chip puts to the buffer the LA32 dry output when it is ready and performs processing of the _previously_ latched data.
// Of course, the right way would be to use a dedicated variable for this, but our reverb model is way higher level,
// so we can simply increase the input buffer size.
static const Bit32u PROCESS_DELAY = 1;
static const Bit32u MODE_3_ADDITIONAL_DELAY = 1;
static const Bit32u MODE_3_FEEDBACK_DELAY = 1;
// Avoid denormals degrading performance, using biased input
static const FloatSample BIAS = 1e-20f;
struct BReverbSettings {
const Bit32u numberOfAllpasses;
const Bit32u * const allpassSizes;
const Bit32u numberOfCombs;
const Bit32u * const combSizes;
const Bit32u * const outLPositions;
const Bit32u * const outRPositions;
const Bit8u * const filterFactors;
const Bit8u * const feedbackFactors;
const Bit8u * const dryAmps;
const Bit8u * const wetLevels;
const Bit8u lpfAmp;
};
// Default reverb settings for "new" reverb model implemented in CM-32L / LAPC-I.
// Found by tracing reverb RAM data lines (thanks go to Lord_Nightmare & balrog).
static const BReverbSettings &getCM32L_LAPCSettings(const ReverbMode mode) {
static const Bit32u MODE_0_NUMBER_OF_ALLPASSES = 3;
static const Bit32u MODE_0_ALLPASSES[] = {994, 729, 78};
static const Bit32u MODE_0_NUMBER_OF_COMBS = 4; // Well, actually there are 3 comb filters, but the entrance LPF + delay can be processed via a hacked comb.
static const Bit32u MODE_0_COMBS[] = {705 + PROCESS_DELAY, 2349, 2839, 3632};
static const Bit32u MODE_0_OUTL[] = {2349, 141, 1960};
static const Bit32u MODE_0_OUTR[] = {1174, 1570, 145};
static const Bit8u MODE_0_COMB_FACTOR[] = {0xA0, 0x60, 0x60, 0x60};
static const Bit8u MODE_0_COMB_FEEDBACK[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x28, 0x48, 0x60, 0x78, 0x80, 0x88, 0x90, 0x98,
0x28, 0x48, 0x60, 0x78, 0x80, 0x88, 0x90, 0x98,
0x28, 0x48, 0x60, 0x78, 0x80, 0x88, 0x90, 0x98};
static const Bit8u MODE_0_DRY_AMP[] = {0xA0, 0xA0, 0xA0, 0xA0, 0xB0, 0xB0, 0xB0, 0xD0};
static const Bit8u MODE_0_WET_AMP[] = {0x10, 0x30, 0x50, 0x70, 0x90, 0xC0, 0xF0, 0xF0};
static const Bit8u MODE_0_LPF_AMP = 0x60;
static const Bit32u MODE_1_NUMBER_OF_ALLPASSES = 3;
static const Bit32u MODE_1_ALLPASSES[] = {1324, 809, 176};
static const Bit32u MODE_1_NUMBER_OF_COMBS = 4; // Same as for mode 0 above
static const Bit32u MODE_1_COMBS[] = {961 + PROCESS_DELAY, 2619, 3545, 4519};
static const Bit32u MODE_1_OUTL[] = {2618, 1760, 4518};
static const Bit32u MODE_1_OUTR[] = {1300, 3532, 2274};
static const Bit8u MODE_1_COMB_FACTOR[] = {0x80, 0x60, 0x60, 0x60};
static const Bit8u MODE_1_COMB_FEEDBACK[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x28, 0x48, 0x60, 0x70, 0x78, 0x80, 0x90, 0x98,
0x28, 0x48, 0x60, 0x78, 0x80, 0x88, 0x90, 0x98,
0x28, 0x48, 0x60, 0x78, 0x80, 0x88, 0x90, 0x98};
static const Bit8u MODE_1_DRY_AMP[] = {0xA0, 0xA0, 0xB0, 0xB0, 0xB0, 0xB0, 0xB0, 0xE0};
static const Bit8u MODE_1_WET_AMP[] = {0x10, 0x30, 0x50, 0x70, 0x90, 0xC0, 0xF0, 0xF0};
static const Bit8u MODE_1_LPF_AMP = 0x60;
static const Bit32u MODE_2_NUMBER_OF_ALLPASSES = 3;
static const Bit32u MODE_2_ALLPASSES[] = {969, 644, 157};
static const Bit32u MODE_2_NUMBER_OF_COMBS = 4; // Same as for mode 0 above
static const Bit32u MODE_2_COMBS[] = {116 + PROCESS_DELAY, 2259, 2839, 3539};
static const Bit32u MODE_2_OUTL[] = {2259, 718, 1769};
static const Bit32u MODE_2_OUTR[] = {1136, 2128, 1};
static const Bit8u MODE_2_COMB_FACTOR[] = {0, 0x20, 0x20, 0x20};
static const Bit8u MODE_2_COMB_FEEDBACK[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x30, 0x58, 0x78, 0x88, 0xA0, 0xB8, 0xC0, 0xD0,
0x30, 0x58, 0x78, 0x88, 0xA0, 0xB8, 0xC0, 0xD0,
0x30, 0x58, 0x78, 0x88, 0xA0, 0xB8, 0xC0, 0xD0};
static const Bit8u MODE_2_DRY_AMP[] = {0xA0, 0xA0, 0xB0, 0xB0, 0xB0, 0xB0, 0xC0, 0xE0};
static const Bit8u MODE_2_WET_AMP[] = {0x10, 0x30, 0x50, 0x70, 0x90, 0xC0, 0xF0, 0xF0};
static const Bit8u MODE_2_LPF_AMP = 0x80;
static const Bit32u MODE_3_NUMBER_OF_ALLPASSES = 0;
static const Bit32u MODE_3_NUMBER_OF_COMBS = 1;
static const Bit32u MODE_3_DELAY[] = {16000 + MODE_3_FEEDBACK_DELAY + PROCESS_DELAY + MODE_3_ADDITIONAL_DELAY};
static const Bit32u MODE_3_OUTL[] = {400, 624, 960, 1488, 2256, 3472, 5280, 8000};
static const Bit32u MODE_3_OUTR[] = {800, 1248, 1920, 2976, 4512, 6944, 10560, 16000};
static const Bit8u MODE_3_COMB_FACTOR[] = {0x68};
static const Bit8u MODE_3_COMB_FEEDBACK[] = {0x68, 0x60};
static const Bit8u MODE_3_DRY_AMP[] = {0x20, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50,
0x20, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50};
static const Bit8u MODE_3_WET_AMP[] = {0x18, 0x18, 0x28, 0x40, 0x60, 0x80, 0xA8, 0xF8};
static const BReverbSettings REVERB_MODE_0_SETTINGS = {MODE_0_NUMBER_OF_ALLPASSES, MODE_0_ALLPASSES, MODE_0_NUMBER_OF_COMBS, MODE_0_COMBS, MODE_0_OUTL, MODE_0_OUTR, MODE_0_COMB_FACTOR, MODE_0_COMB_FEEDBACK, MODE_0_DRY_AMP, MODE_0_WET_AMP, MODE_0_LPF_AMP};
static const BReverbSettings REVERB_MODE_1_SETTINGS = {MODE_1_NUMBER_OF_ALLPASSES, MODE_1_ALLPASSES, MODE_1_NUMBER_OF_COMBS, MODE_1_COMBS, MODE_1_OUTL, MODE_1_OUTR, MODE_1_COMB_FACTOR, MODE_1_COMB_FEEDBACK, MODE_1_DRY_AMP, MODE_1_WET_AMP, MODE_1_LPF_AMP};
static const BReverbSettings REVERB_MODE_2_SETTINGS = {MODE_2_NUMBER_OF_ALLPASSES, MODE_2_ALLPASSES, MODE_2_NUMBER_OF_COMBS, MODE_2_COMBS, MODE_2_OUTL, MODE_2_OUTR, MODE_2_COMB_FACTOR, MODE_2_COMB_FEEDBACK, MODE_2_DRY_AMP, MODE_2_WET_AMP, MODE_2_LPF_AMP};
static const BReverbSettings REVERB_MODE_3_SETTINGS = {MODE_3_NUMBER_OF_ALLPASSES, NULL, MODE_3_NUMBER_OF_COMBS, MODE_3_DELAY, MODE_3_OUTL, MODE_3_OUTR, MODE_3_COMB_FACTOR, MODE_3_COMB_FEEDBACK, MODE_3_DRY_AMP, MODE_3_WET_AMP, 0};
static const BReverbSettings * const REVERB_SETTINGS[] = {&REVERB_MODE_0_SETTINGS, &REVERB_MODE_1_SETTINGS, &REVERB_MODE_2_SETTINGS, &REVERB_MODE_3_SETTINGS};
return *REVERB_SETTINGS[mode];
}
// Default reverb settings for "old" reverb model implemented in MT-32.
// Found by tracing reverb RAM data lines (thanks go to Lord_Nightmare & balrog).
static const BReverbSettings &getMT32Settings(const ReverbMode mode) {
static const Bit32u MODE_0_NUMBER_OF_ALLPASSES = 3;
static const Bit32u MODE_0_ALLPASSES[] = {994, 729, 78};
static const Bit32u MODE_0_NUMBER_OF_COMBS = 4; // Same as above in the new model implementation
static const Bit32u MODE_0_COMBS[] = {575 + PROCESS_DELAY, 2040, 2752, 3629};
static const Bit32u MODE_0_OUTL[] = {2040, 687, 1814};
static const Bit32u MODE_0_OUTR[] = {1019, 2072, 1};
static const Bit8u MODE_0_COMB_FACTOR[] = {0xB0, 0x60, 0x60, 0x60};
static const Bit8u MODE_0_COMB_FEEDBACK[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x28, 0x48, 0x60, 0x70, 0x78, 0x80, 0x90, 0x98,
0x28, 0x48, 0x60, 0x78, 0x80, 0x88, 0x90, 0x98,
0x28, 0x48, 0x60, 0x78, 0x80, 0x88, 0x90, 0x98};
static const Bit8u MODE_0_DRY_AMP[] = {0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80};
static const Bit8u MODE_0_WET_AMP[] = {0x10, 0x20, 0x30, 0x40, 0x50, 0x70, 0xA0, 0xE0};
static const Bit8u MODE_0_LPF_AMP = 0x80;
static const Bit32u MODE_1_NUMBER_OF_ALLPASSES = 3;
static const Bit32u MODE_1_ALLPASSES[] = {1324, 809, 176};
static const Bit32u MODE_1_NUMBER_OF_COMBS = 4; // Same as above in the new model implementation
static const Bit32u MODE_1_COMBS[] = {961 + PROCESS_DELAY, 2619, 3545, 4519};
static const Bit32u MODE_1_OUTL[] = {2618, 1760, 4518};
static const Bit32u MODE_1_OUTR[] = {1300, 3532, 2274};
static const Bit8u MODE_1_COMB_FACTOR[] = {0x90, 0x60, 0x60, 0x60};
static const Bit8u MODE_1_COMB_FEEDBACK[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x28, 0x48, 0x60, 0x70, 0x78, 0x80, 0x90, 0x98,
0x28, 0x48, 0x60, 0x78, 0x80, 0x88, 0x90, 0x98,
0x28, 0x48, 0x60, 0x78, 0x80, 0x88, 0x90, 0x98};
static const Bit8u MODE_1_DRY_AMP[] = {0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80};
static const Bit8u MODE_1_WET_AMP[] = {0x10, 0x20, 0x30, 0x40, 0x50, 0x70, 0xA0, 0xE0};
static const Bit8u MODE_1_LPF_AMP = 0x80;
static const Bit32u MODE_2_NUMBER_OF_ALLPASSES = 3;
static const Bit32u MODE_2_ALLPASSES[] = {969, 644, 157};
static const Bit32u MODE_2_NUMBER_OF_COMBS = 4; // Same as above in the new model implementation
static const Bit32u MODE_2_COMBS[] = {116 + PROCESS_DELAY, 2259, 2839, 3539};
static const Bit32u MODE_2_OUTL[] = {2259, 718, 1769};
static const Bit32u MODE_2_OUTR[] = {1136, 2128, 1};
static const Bit8u MODE_2_COMB_FACTOR[] = {0, 0x60, 0x60, 0x60};
static const Bit8u MODE_2_COMB_FEEDBACK[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x28, 0x48, 0x60, 0x70, 0x78, 0x80, 0x90, 0x98,
0x28, 0x48, 0x60, 0x78, 0x80, 0x88, 0x90, 0x98,
0x28, 0x48, 0x60, 0x78, 0x80, 0x88, 0x90, 0x98};
static const Bit8u MODE_2_DRY_AMP[] = {0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80};
static const Bit8u MODE_2_WET_AMP[] = {0x10, 0x20, 0x30, 0x40, 0x50, 0x70, 0xA0, 0xE0};
static const Bit8u MODE_2_LPF_AMP = 0x80;
static const Bit32u MODE_3_NUMBER_OF_ALLPASSES = 0;
static const Bit32u MODE_3_NUMBER_OF_COMBS = 1;
static const Bit32u MODE_3_DELAY[] = {16000 + MODE_3_FEEDBACK_DELAY + PROCESS_DELAY + MODE_3_ADDITIONAL_DELAY};
static const Bit32u MODE_3_OUTL[] = {400, 624, 960, 1488, 2256, 3472, 5280, 8000};
static const Bit32u MODE_3_OUTR[] = {800, 1248, 1920, 2976, 4512, 6944, 10560, 16000};
static const Bit8u MODE_3_COMB_FACTOR[] = {0x68};
static const Bit8u MODE_3_COMB_FEEDBACK[] = {0x68, 0x60};
static const Bit8u MODE_3_DRY_AMP[] = {0x10, 0x10, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x10, 0x20, 0x20, 0x10, 0x20, 0x10, 0x20, 0x10};
static const Bit8u MODE_3_WET_AMP[] = {0x08, 0x18, 0x28, 0x40, 0x60, 0x80, 0xA8, 0xF8};
static const BReverbSettings REVERB_MODE_0_SETTINGS = {MODE_0_NUMBER_OF_ALLPASSES, MODE_0_ALLPASSES, MODE_0_NUMBER_OF_COMBS, MODE_0_COMBS, MODE_0_OUTL, MODE_0_OUTR, MODE_0_COMB_FACTOR, MODE_0_COMB_FEEDBACK, MODE_0_DRY_AMP, MODE_0_WET_AMP, MODE_0_LPF_AMP};
static const BReverbSettings REVERB_MODE_1_SETTINGS = {MODE_1_NUMBER_OF_ALLPASSES, MODE_1_ALLPASSES, MODE_1_NUMBER_OF_COMBS, MODE_1_COMBS, MODE_1_OUTL, MODE_1_OUTR, MODE_1_COMB_FACTOR, MODE_1_COMB_FEEDBACK, MODE_1_DRY_AMP, MODE_1_WET_AMP, MODE_1_LPF_AMP};
static const BReverbSettings REVERB_MODE_2_SETTINGS = {MODE_2_NUMBER_OF_ALLPASSES, MODE_2_ALLPASSES, MODE_2_NUMBER_OF_COMBS, MODE_2_COMBS, MODE_2_OUTL, MODE_2_OUTR, MODE_2_COMB_FACTOR, MODE_2_COMB_FEEDBACK, MODE_2_DRY_AMP, MODE_2_WET_AMP, MODE_2_LPF_AMP};
static const BReverbSettings REVERB_MODE_3_SETTINGS = {MODE_3_NUMBER_OF_ALLPASSES, NULL, MODE_3_NUMBER_OF_COMBS, MODE_3_DELAY, MODE_3_OUTL, MODE_3_OUTR, MODE_3_COMB_FACTOR, MODE_3_COMB_FEEDBACK, MODE_3_DRY_AMP, MODE_3_WET_AMP, 0};
static const BReverbSettings * const REVERB_SETTINGS[] = {&REVERB_MODE_0_SETTINGS, &REVERB_MODE_1_SETTINGS, &REVERB_MODE_2_SETTINGS, &REVERB_MODE_3_SETTINGS};
return *REVERB_SETTINGS[mode];
}
static inline IntSample weirdMul(IntSample sample, Bit8u addMask, Bit8u carryMask) {
#if MT32EMU_BOSS_REVERB_PRECISE_MODE
// This algorithm tries to emulate exactly Boss multiplication operation (at least this is what we see on reverb RAM data lines).
Bit8u mask = 0x80;
IntSampleEx res = 0;
for (int i = 0; i < 8; i++) {
IntSampleEx carry = (sample < 0) && (mask & carryMask) > 0 ? sample & 1 : 0;
sample >>= 1;
res += (mask & addMask) > 0 ? sample + carry : 0;
mask >>= 1;
}
return IntSample(res);
#else
(void)carryMask;
return IntSample((IntSampleEx(sample) * addMask) >> 8);
#endif
}
static inline FloatSample weirdMul(FloatSample sample, Bit8u addMask, Bit8u carryMask) {
(void)carryMask;
return sample * addMask / 256.0f;
}
static inline IntSample halveSample(IntSample sample) {
return sample >> 1;
}
static inline FloatSample halveSample(FloatSample sample) {
return 0.5f * sample;
}
static inline IntSample quarterSample(IntSample sample) {
#if MT32EMU_BOSS_REVERB_PRECISE_MODE
return (sample >> 1) / 2;
#else
return sample >> 2;
#endif
}
static inline FloatSample quarterSample(FloatSample sample) {
return 0.25f * sample;
}
static inline IntSample addDCBias(IntSample sample) {
return sample;
}
static inline FloatSample addDCBias(FloatSample sample) {
return sample + BIAS;
}
static inline IntSample addAllpassNoise(IntSample sample) {
#if MT32EMU_BOSS_REVERB_PRECISE_MODE
// This introduces reverb noise which actually makes output from the real Boss chip nondeterministic
return sample - 1;
#else
return sample;
#endif
}
static inline FloatSample addAllpassNoise(FloatSample sample) {
return sample;
}
/* NOTE:
* Thanks to Mok for discovering, the adder in BOSS reverb chip is found to perform addition with saturation to avoid integer overflow.
* Analysing of the algorithm suggests that the overflow is most probable when the combs output is added below.
* So, despite this isn't actually accurate, we only add the check here for performance reasons.
*/
static inline IntSample mixCombs(IntSample out1, IntSample out2, IntSample out3) {
#if MT32EMU_BOSS_REVERB_PRECISE_MODE
return Synth::clipSampleEx(Synth::clipSampleEx(Synth::clipSampleEx(Synth::clipSampleEx(IntSampleEx(out1) + (IntSampleEx(out1) >> 1)) + IntSampleEx(out2)) + (IntSampleEx(out2) >> 1)) + IntSampleEx(out3));
#else
return Synth::clipSampleEx(IntSampleEx(out1) + (IntSampleEx(out1) >> 1) + IntSampleEx(out2) + (IntSampleEx(out2) >> 1) + IntSampleEx(out3));
#endif
}
static inline FloatSample mixCombs(FloatSample out1, FloatSample out2, FloatSample out3) {
return 1.5f * (out1 + out2) + out3;
}
template <class Sample>
class RingBuffer {
static inline Sample sampleValueThreshold();
protected:
Sample *buffer;
const Bit32u size;
Bit32u index;
public:
RingBuffer(const Bit32u newsize) : size(newsize), index(0) {
buffer = new Sample[size];
}
virtual ~RingBuffer() {
delete[] buffer;
buffer = NULL;
}
Sample next() {
if (++index >= size) {
index = 0;
}
return buffer[index];
}
bool isEmpty() const {
if (buffer == NULL) return true;
Sample *buf = buffer;
for (Bit32u i = 0; i < size; i++) {
if (*buf < -sampleValueThreshold() || *buf > sampleValueThreshold()) return false;
buf++;
}
return true;
}
void mute() {
Synth::muteSampleBuffer(buffer, size);
}
};
template<>
IntSample RingBuffer<IntSample>::sampleValueThreshold() {
return 8;
}
template<>
FloatSample RingBuffer<FloatSample>::sampleValueThreshold() {
return 0.001f;
}
template <class Sample>
class AllpassFilter : public RingBuffer<Sample> {
public:
AllpassFilter(const Bit32u useSize) : RingBuffer<Sample>(useSize) {}
// This model corresponds to the allpass filter implementation of the real CM-32L device
// found from sample analysis
Sample process(const Sample in) {
const Sample bufferOut = this->next();
// store input - feedback / 2
this->buffer[this->index] = in - halveSample(bufferOut);
// return buffer output + feedforward / 2
return bufferOut + halveSample(this->buffer[this->index]);
}
};
template <class Sample>
class CombFilter : public RingBuffer<Sample> {
protected:
const Bit8u filterFactor;
Bit8u feedbackFactor;
public:
CombFilter(const Bit32u useSize, const Bit8u useFilterFactor) : RingBuffer<Sample>(useSize), filterFactor(useFilterFactor) {}
// This model corresponds to the comb filter implementation of the real CM-32L device
void process(const Sample in) {
// the previously stored value
const Sample last = this->buffer[this->index];
// prepare input + feedback
const Sample filterIn = in + weirdMul(this->next(), feedbackFactor, 0xF0);
// store input + feedback processed by a low-pass filter
this->buffer[this->index] = weirdMul(last, filterFactor, 0xC0) - filterIn;
}
Sample getOutputAt(const Bit32u outIndex) const {
return this->buffer[(this->size + this->index - outIndex) % this->size];
}
void setFeedbackFactor(const Bit8u useFeedbackFactor) {
feedbackFactor = useFeedbackFactor;
}
};
template <class Sample>
class DelayWithLowPassFilter : public CombFilter<Sample> {
Bit8u amp;
public:
DelayWithLowPassFilter(const Bit32u useSize, const Bit8u useFilterFactor, const Bit8u useAmp)
: CombFilter<Sample>(useSize, useFilterFactor), amp(useAmp) {}
void process(const Sample in) {
// the previously stored value
const Sample last = this->buffer[this->index];
// move to the next index
this->next();
// low-pass filter process
Sample lpfOut = weirdMul(last, this->filterFactor, 0xFF) + in;
// store lpfOut multiplied by LPF amp factor
this->buffer[this->index] = weirdMul(lpfOut, amp, 0xFF);
}
};
template <class Sample>
class TapDelayCombFilter : public CombFilter<Sample> {
Bit32u outL;
Bit32u outR;
public:
TapDelayCombFilter(const Bit32u useSize, const Bit8u useFilterFactor) : CombFilter<Sample>(useSize, useFilterFactor) {}
void process(const Sample in) {
// the previously stored value
const Sample last = this->buffer[this->index];
// move to the next index
this->next();
// prepare input + feedback
// Actually, the size of the filter varies with the TIME parameter, the feedback sample is taken from the position just below the right output
const Sample filterIn = in + weirdMul(this->getOutputAt(outR + MODE_3_FEEDBACK_DELAY), this->feedbackFactor, 0xF0);
// store input + feedback processed by a low-pass filter
this->buffer[this->index] = weirdMul(last, this->filterFactor, 0xF0) - filterIn;
}
Sample getLeftOutput() const {
return this->getOutputAt(outL + PROCESS_DELAY + MODE_3_ADDITIONAL_DELAY);
}
Sample getRightOutput() const {
return this->getOutputAt(outR + PROCESS_DELAY + MODE_3_ADDITIONAL_DELAY);
}
void setOutputPositions(const Bit32u useOutL, const Bit32u useOutR) {
outL = useOutL;
outR = useOutR;
}
};
template <class Sample>
class BReverbModelImpl : public BReverbModel {
public:
AllpassFilter<Sample> **allpasses;
CombFilter<Sample> **combs;
const BReverbSettings ¤tSettings;
const bool tapDelayMode;
Bit8u dryAmp;
Bit8u wetLevel;
BReverbModelImpl(const ReverbMode mode, const bool mt32CompatibleModel) :
allpasses(NULL), combs(NULL),
currentSettings(mt32CompatibleModel ? getMT32Settings(mode) : getCM32L_LAPCSettings(mode)),
tapDelayMode(mode == REVERB_MODE_TAP_DELAY)
{}
~BReverbModelImpl() {
close();
}
bool isOpen() const {
return combs != NULL;
}
void open() {
if (isOpen()) return;
if (currentSettings.numberOfAllpasses > 0) {
allpasses = new AllpassFilter<Sample>*[currentSettings.numberOfAllpasses];
for (Bit32u i = 0; i < currentSettings.numberOfAllpasses; i++) {
allpasses[i] = new AllpassFilter<Sample>(currentSettings.allpassSizes[i]);
}
}
combs = new CombFilter<Sample>*[currentSettings.numberOfCombs];
if (tapDelayMode) {
*combs = new TapDelayCombFilter<Sample>(*currentSettings.combSizes, *currentSettings.filterFactors);
} else {
combs[0] = new DelayWithLowPassFilter<Sample>(currentSettings.combSizes[0], currentSettings.filterFactors[0], currentSettings.lpfAmp);
for (Bit32u i = 1; i < currentSettings.numberOfCombs; i++) {
combs[i] = new CombFilter<Sample>(currentSettings.combSizes[i], currentSettings.filterFactors[i]);
}
}
mute();
}
void close() {
if (allpasses != NULL) {
for (Bit32u i = 0; i < currentSettings.numberOfAllpasses; i++) {
if (allpasses[i] != NULL) {
delete allpasses[i];
allpasses[i] = NULL;
}
}
delete[] allpasses;
allpasses = NULL;
}
if (combs != NULL) {
for (Bit32u i = 0; i < currentSettings.numberOfCombs; i++) {
if (combs[i] != NULL) {
delete combs[i];
combs[i] = NULL;
}
}
delete[] combs;
combs = NULL;
}
}
void mute() {
if (allpasses != NULL) {
for (Bit32u i = 0; i < currentSettings.numberOfAllpasses; i++) {
allpasses[i]->mute();
}
}
if (combs != NULL) {
for (Bit32u i = 0; i < currentSettings.numberOfCombs; i++) {
combs[i]->mute();
}
}
}
void setParameters(Bit8u time, Bit8u level) {
if (!isOpen()) return;
level &= 7;
time &= 7;
if (tapDelayMode) {
TapDelayCombFilter<Sample> *comb = static_cast<TapDelayCombFilter<Sample> *> (*combs);
comb->setOutputPositions(currentSettings.outLPositions[time], currentSettings.outRPositions[time & 7]);
comb->setFeedbackFactor(currentSettings.feedbackFactors[((level < 3) || (time < 6)) ? 0 : 1]);
} else {
for (Bit32u i = 1; i < currentSettings.numberOfCombs; i++) {
combs[i]->setFeedbackFactor(currentSettings.feedbackFactors[(i << 3) + time]);
}
}
if (time == 0 && level == 0) {
dryAmp = wetLevel = 0;
} else {
if (tapDelayMode && ((time == 0) || (time == 1 && level == 1))) {
// Looks like MT-32 implementation has some minor quirks in this mode:
// for odd level values, the output level changes sometimes depending on the time value which doesn't seem right.
dryAmp = currentSettings.dryAmps[level + 8];
} else {
dryAmp = currentSettings.dryAmps[level];
}
wetLevel = currentSettings.wetLevels[level];
}
}
bool isActive() const {
if (!isOpen()) return false;
for (Bit32u i = 0; i < currentSettings.numberOfAllpasses; i++) {
if (!allpasses[i]->isEmpty()) return true;
}
for (Bit32u i = 0; i < currentSettings.numberOfCombs; i++) {
if (!combs[i]->isEmpty()) return true;
}
return false;
}
bool isMT32Compatible(const ReverbMode mode) const {
return ¤tSettings == &getMT32Settings(mode);
}
template <class SampleEx>
void produceOutput(const Sample *inLeft, const Sample *inRight, Sample *outLeft, Sample *outRight, Bit32u numSamples) {
if (!isOpen()) {
Synth::muteSampleBuffer(outLeft, numSamples);
Synth::muteSampleBuffer(outRight, numSamples);
return;
}
while ((numSamples--) > 0) {
Sample dry;
if (tapDelayMode) {
dry = halveSample(*(inLeft++)) + halveSample(*(inRight++));
} else {
dry = quarterSample(*(inLeft++)) + quarterSample(*(inRight++));
}
// Looks like dryAmp doesn't change in MT-32 but it does in CM-32L / LAPC-I
dry = weirdMul(addDCBias(dry), dryAmp, 0xFF);
if (tapDelayMode) {
TapDelayCombFilter<Sample> *comb = static_cast<TapDelayCombFilter<Sample> *>(*combs);
comb->process(dry);
if (outLeft != NULL) {
*(outLeft++) = weirdMul(comb->getLeftOutput(), wetLevel, 0xFF);
}
if (outRight != NULL) {
*(outRight++) = weirdMul(comb->getRightOutput(), wetLevel, 0xFF);
}
} else {
DelayWithLowPassFilter<Sample> * const entranceDelay = static_cast<DelayWithLowPassFilter<Sample> *>(combs[0]);
// If the output position is equal to the comb size, get it now in order not to loose it
Sample link = entranceDelay->getOutputAt(currentSettings.combSizes[0] - 1);
// Entrance LPF. Note, comb.process() differs a bit here.
entranceDelay->process(dry);
link = allpasses[0]->process(addAllpassNoise(link));
link = allpasses[1]->process(link);
link = allpasses[2]->process(link);
// If the output position is equal to the comb size, get it now in order not to loose it
Sample outL1 = combs[1]->getOutputAt(currentSettings.outLPositions[0] - 1);
combs[1]->process(link);
combs[2]->process(link);
combs[3]->process(link);
if (outLeft != NULL) {
Sample outL2 = combs[2]->getOutputAt(currentSettings.outLPositions[1]);
Sample outL3 = combs[3]->getOutputAt(currentSettings.outLPositions[2]);
Sample outSample = mixCombs(outL1, outL2, outL3);
*(outLeft++) = weirdMul(outSample, wetLevel, 0xFF);
}
if (outRight != NULL) {
Sample outR1 = combs[1]->getOutputAt(currentSettings.outRPositions[0]);
Sample outR2 = combs[2]->getOutputAt(currentSettings.outRPositions[1]);
Sample outR3 = combs[3]->getOutputAt(currentSettings.outRPositions[2]);
Sample outSample = mixCombs(outR1, outR2, outR3);
*(outRight++) = weirdMul(outSample, wetLevel, 0xFF);
}
} // if (tapDelayMode)
} // while ((numSamples--) > 0)
} // produceOutput
bool process(const IntSample *inLeft, const IntSample *inRight, IntSample *outLeft, IntSample *outRight, Bit32u numSamples);
bool process(const FloatSample *inLeft, const FloatSample *inRight, FloatSample *outLeft, FloatSample *outRight, Bit32u numSamples);
};
BReverbModel *BReverbModel::createBReverbModel(const ReverbMode mode, const bool mt32CompatibleModel, const RendererType rendererType) {
switch (rendererType)
{
case RendererType_BIT16S:
return new BReverbModelImpl<IntSample>(mode, mt32CompatibleModel);
case RendererType_FLOAT:
return new BReverbModelImpl<FloatSample>(mode, mt32CompatibleModel);
default:
break;
}
return NULL;
}
template <>
bool BReverbModelImpl<IntSample>::process(const IntSample *inLeft, const IntSample *inRight, IntSample *outLeft, IntSample *outRight, Bit32u numSamples) {
produceOutput<IntSampleEx>(inLeft, inRight, outLeft, outRight, numSamples);
return true;
}
template <>
bool BReverbModelImpl<IntSample>::process(const FloatSample *, const FloatSample *, FloatSample *, FloatSample *, Bit32u) {
return false;
}
template <>
bool BReverbModelImpl<FloatSample>::process(const IntSample *, const IntSample *, IntSample *, IntSample *, Bit32u) {
return false;
}
template <>
bool BReverbModelImpl<FloatSample>::process(const FloatSample *inLeft, const FloatSample *inRight, FloatSample *outLeft, FloatSample *outRight, Bit32u numSamples) {
produceOutput<FloatSample>(inLeft, inRight, outLeft, outRight, numSamples);
return true;
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/BReverbModel.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 9,250 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#if defined MT32EMU_SHARED && defined MT32EMU_INSTALL_DEFAULT_LOCALE
#include <clocale>
#endif
#include "internals.h"
#include "FileStream.h"
namespace MT32Emu {
// This initialises C locale with the user-preferred system locale once facilitating access
// to ROM files with localised pathnames. This is only necessary in rare cases e.g. when building
// shared library statically linked with C runtime with old MS VC versions, so that the C locale
// set by the client application does not have effect, and thus such ROM files cannot be opened.
static inline void configureSystemLocale() {
#if defined MT32EMU_SHARED && defined MT32EMU_INSTALL_DEFAULT_LOCALE
static bool configured = false;
if (configured) return;
configured = true;
setlocale(LC_ALL, "");
#endif
}
using std::ios_base;
FileStream::FileStream() : ifsp(*new std::ifstream), data(NULL), size(0)
{}
FileStream::~FileStream() {
// destructor closes ifsp
delete &ifsp;
delete[] data;
}
size_t FileStream::getSize() {
if (size != 0) {
return size;
}
if (!ifsp.is_open()) {
return 0;
}
ifsp.seekg(0, ios_base::end);
size = size_t(ifsp.tellg());
return size;
}
const Bit8u *FileStream::getData() {
if (data != NULL) {
return data;
}
if (!ifsp.is_open()) {
return NULL;
}
if (getSize() == 0) {
return NULL;
}
Bit8u *fileData = new Bit8u[size];
if (fileData == NULL) {
return NULL;
}
ifsp.seekg(0);
ifsp.read(reinterpret_cast<char *>(fileData), std::streamsize(size));
if (size_t(ifsp.tellg()) != size) {
delete[] fileData;
return NULL;
}
data = fileData;
close();
return data;
}
bool FileStream::open(const char *filename) {
configureSystemLocale();
ifsp.clear();
ifsp.open(filename, ios_base::in | ios_base::binary);
return !ifsp.fail();
}
void FileStream::close() {
ifsp.close();
ifsp.clear();
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/FileStream.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 576 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_POLY_H
#define MT32EMU_POLY_H
#include "globals.h"
#include "internals.h"
namespace MT32Emu {
class Part;
class Partial;
struct PatchCache;
class Poly {
private:
Part *part;
unsigned int key;
unsigned int velocity;
unsigned int activePartialCount;
bool sustain;
PolyState state;
Partial *partials[4];
Poly *next;
void setState(PolyState state);
public:
Poly();
void setPart(Part *usePart);
void reset(unsigned int key, unsigned int velocity, bool sustain, Partial **partials);
bool noteOff(bool pedalHeld);
bool stopPedalHold();
bool startDecay();
bool startAbort();
void backupCacheToPartials(PatchCache cache[4]);
unsigned int getKey() const;
unsigned int getVelocity() const;
bool canSustain() const;
PolyState getState() const;
unsigned int getActivePartialCount() const;
bool isActive() const;
void partialDeactivated(Partial *partial);
Poly *getNext() const;
void setNext(Poly *poly);
}; // class Poly
} // namespace MT32Emu
#endif // #ifndef MT32EMU_POLY_H
``` | /content/code_sandbox/src/sound/munt/Poly.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 342 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstdio>
#include <cstring>
#include "internals.h"
#include "MidiStreamParser.h"
#include "Synth.h"
using namespace MT32Emu;
DefaultMidiStreamParser::DefaultMidiStreamParser(Synth &useSynth, Bit32u initialStreamBufferCapacity) :
MidiStreamParser(initialStreamBufferCapacity), synth(useSynth), timestampSet(false) {}
void DefaultMidiStreamParser::setTimestamp(const Bit32u useTimestamp) {
timestampSet = true;
timestamp = useTimestamp;
}
void DefaultMidiStreamParser::resetTimestamp() {
timestampSet = false;
}
void DefaultMidiStreamParser::handleShortMessage(const Bit32u message) {
do {
if (timestampSet) {
if (synth.playMsg(message, timestamp)) return;
}
else {
if (synth.playMsg(message)) return;
}
} while (synth.reportHandler->onMIDIQueueOverflow());
}
void DefaultMidiStreamParser::handleSysex(const Bit8u *stream, const Bit32u length) {
do {
if (timestampSet) {
if (synth.playSysex(stream, length, timestamp)) return;
}
else {
if (synth.playSysex(stream, length)) return;
}
} while (synth.reportHandler->onMIDIQueueOverflow());
}
void DefaultMidiStreamParser::handleSystemRealtimeMessage(const Bit8u realtime) {
synth.reportHandler->onMIDISystemRealtime(realtime);
}
void DefaultMidiStreamParser::printDebug(const char *debugMessage) {
synth.printDebug("%s", debugMessage);
}
MidiStreamParser::MidiStreamParser(Bit32u initialStreamBufferCapacity) :
MidiStreamParserImpl(*this, *this, initialStreamBufferCapacity) {}
MidiStreamParserImpl::MidiStreamParserImpl(MidiReceiver &useReceiver, MidiReporter &useReporter, Bit32u initialStreamBufferCapacity) :
midiReceiver(useReceiver), midiReporter(useReporter)
{
if (initialStreamBufferCapacity < SYSEX_BUFFER_SIZE) initialStreamBufferCapacity = SYSEX_BUFFER_SIZE;
if (MAX_STREAM_BUFFER_SIZE < initialStreamBufferCapacity) initialStreamBufferCapacity = MAX_STREAM_BUFFER_SIZE;
streamBufferCapacity = initialStreamBufferCapacity;
streamBuffer = new Bit8u[streamBufferCapacity];
streamBufferSize = 0;
runningStatus = 0;
reserved = NULL;
}
MidiStreamParserImpl::~MidiStreamParserImpl() {
delete[] streamBuffer;
}
void MidiStreamParserImpl::parseStream(const Bit8u *stream, Bit32u length) {
while (length > 0) {
Bit32u parsedMessageLength = 0;
if (0xF8 <= *stream) {
// Process System Realtime immediately and go on
midiReceiver.handleSystemRealtimeMessage(*stream);
parsedMessageLength = 1;
// No effect on the running status
} else if (streamBufferSize > 0) {
// Check if there is something in streamBuffer waiting for being processed
if (*streamBuffer == 0xF0) {
parsedMessageLength = parseSysexFragment(stream, length);
} else {
parsedMessageLength = parseShortMessageDataBytes(stream, length);
}
} else {
if (*stream == 0xF0) {
runningStatus = 0; // SysEx clears the running status
parsedMessageLength = parseSysex(stream, length);
} else {
parsedMessageLength = parseShortMessageStatus(stream);
}
}
// Parsed successfully
stream += parsedMessageLength;
length -= parsedMessageLength;
}
}
void MidiStreamParserImpl::processShortMessage(const Bit32u message) {
// Adds running status to the MIDI message if it doesn't contain one
Bit8u status = Bit8u(message & 0xFF);
if (0xF8 <= status) {
midiReceiver.handleSystemRealtimeMessage(status);
} else if (processStatusByte(status)) {
midiReceiver.handleShortMessage((message << 8) | status);
} else if (0x80 <= status) { // If no running status available yet, skip this message
midiReceiver.handleShortMessage(message);
}
}
// We deal with SysEx messages below 512 bytes long in most cases. Nevertheless, it seems reasonable to support a possibility
// to load bulk dumps using a single message. However, this is known to fail with a real device due to limited input buffer size.
bool MidiStreamParserImpl::checkStreamBufferCapacity(const bool preserveContent) {
if (streamBufferSize < streamBufferCapacity) return true;
if (streamBufferCapacity < MAX_STREAM_BUFFER_SIZE) {
Bit8u *oldStreamBuffer = streamBuffer;
streamBufferCapacity = MAX_STREAM_BUFFER_SIZE;
streamBuffer = new Bit8u[streamBufferCapacity];
if (preserveContent) memcpy(streamBuffer, oldStreamBuffer, streamBufferSize);
delete[] oldStreamBuffer;
return true;
}
return false;
}
// Checks input byte whether it is a status byte. If not, replaces it with running status when available.
// Returns true if the input byte was changed to running status.
bool MidiStreamParserImpl::processStatusByte(Bit8u &status) {
if (status < 0x80) {
// First byte isn't status, try running status
if (runningStatus < 0x80) {
// No running status available yet
midiReporter.printDebug("processStatusByte: No valid running status yet, MIDI message ignored");
return false;
}
status = runningStatus;
return true;
} else if (status < 0xF0) {
// Store current status as running for a Voice message
runningStatus = status;
} else if (status < 0xF8) {
// System Common clears running status
runningStatus = 0;
} // System Realtime doesn't affect running status
return false;
}
// Returns # of bytes parsed
Bit32u MidiStreamParserImpl::parseShortMessageStatus(const Bit8u stream[]) {
Bit8u status = *stream;
Bit32u parsedLength = processStatusByte(status) ? 0 : 1;
if (0x80 <= status) { // If no running status available yet, skip one byte
*streamBuffer = status;
++streamBufferSize;
}
return parsedLength;
}
// Returns # of bytes parsed
Bit32u MidiStreamParserImpl::parseShortMessageDataBytes(const Bit8u stream[], Bit32u length) {
const Bit32u shortMessageLength = Synth::getShortMessageLength(*streamBuffer);
Bit32u parsedLength = 0;
// Append incoming bytes to streamBuffer
while ((streamBufferSize < shortMessageLength) && (length-- > 0)) {
Bit8u dataByte = *(stream++);
if (dataByte < 0x80) {
// Add data byte to streamBuffer
streamBuffer[streamBufferSize++] = dataByte;
} else if (dataByte < 0xF8) {
// Discard invalid bytes and start over
char s[128];
snprintf(s, sizeof(s), "parseShortMessageDataBytes: Invalid short message: status %02x, expected length %i, actual %i -> ignored", *streamBuffer, shortMessageLength, streamBufferSize);
midiReporter.printDebug(s);
streamBufferSize = 0; // Clear streamBuffer
return parsedLength;
} else {
// Bypass System Realtime message
midiReceiver.handleSystemRealtimeMessage(dataByte);
}
++parsedLength;
}
if (streamBufferSize < shortMessageLength) return parsedLength; // Still lacks data bytes
// Assemble short message
Bit32u shortMessage = streamBuffer[0];
for (Bit32u i = 1; i < shortMessageLength; ++i) {
shortMessage |= streamBuffer[i] << (i << 3);
}
midiReceiver.handleShortMessage(shortMessage);
streamBufferSize = 0; // Clear streamBuffer
return parsedLength;
}
// Returns # of bytes parsed
Bit32u MidiStreamParserImpl::parseSysex(const Bit8u stream[], const Bit32u length) {
// Find SysEx length
Bit32u sysexLength = 1;
while (sysexLength < length) {
Bit8u nextByte = stream[sysexLength++];
if (0x80 <= nextByte) {
if (nextByte == 0xF7) {
// End of SysEx
midiReceiver.handleSysex(stream, sysexLength);
return sysexLength;
}
if (0xF8 <= nextByte) {
// The System Realtime message must be processed right after return
// but the SysEx is actually fragmented and to be reconstructed in streamBuffer
--sysexLength;
break;
}
// Illegal status byte in SysEx message, aborting
midiReporter.printDebug("parseSysex: SysEx message lacks end-of-sysex (0xf7), ignored");
// Continue parsing from that point
return sysexLength - 1;
}
}
// Store incomplete SysEx message for further processing
streamBufferSize = sysexLength;
if (checkStreamBufferCapacity(false)) {
memcpy(streamBuffer, stream, sysexLength);
} else {
// Not enough buffer capacity, don't care about the real buffer content, just mark the first byte
*streamBuffer = *stream;
streamBufferSize = streamBufferCapacity;
}
return sysexLength;
}
// Returns # of bytes parsed
Bit32u MidiStreamParserImpl::parseSysexFragment(const Bit8u stream[], const Bit32u length) {
Bit32u parsedLength = 0;
while (parsedLength < length) {
Bit8u nextByte = stream[parsedLength++];
if (nextByte < 0x80) {
// Add SysEx data byte to streamBuffer
if (checkStreamBufferCapacity(true)) streamBuffer[streamBufferSize++] = nextByte;
continue;
}
if (0xF8 <= nextByte) {
// Bypass System Realtime message
midiReceiver.handleSystemRealtimeMessage(nextByte);
continue;
}
if (nextByte != 0xF7) {
// Illegal status byte in SysEx message, aborting
midiReporter.printDebug("parseSysexFragment: SysEx message lacks end-of-sysex (0xf7), ignored");
// Clear streamBuffer and continue parsing from that point
streamBufferSize = 0;
--parsedLength;
break;
}
// End of SysEx
if (checkStreamBufferCapacity(true)) {
streamBuffer[streamBufferSize++] = nextByte;
midiReceiver.handleSysex(streamBuffer, streamBufferSize);
streamBufferSize = 0; // Clear streamBuffer
break;
}
// Encountered streamBuffer overrun
midiReporter.printDebug("parseSysexFragment: streamBuffer overrun while receiving SysEx message, ignored. Max allowed size of fragmented SysEx is 32768 bytes.");
streamBufferSize = 0; // Clear streamBuffer
break;
}
return parsedLength;
}
``` | /content/code_sandbox/src/sound/munt/MidiStreamParser.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,569 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstddef>
#include "internals.h"
#include "LA32WaveGenerator.h"
#include "Tables.h"
namespace MT32Emu {
static const Bit32u SINE_SEGMENT_RELATIVE_LENGTH = 1 << 18;
static const Bit32u MIDDLE_CUTOFF_VALUE = 128 << 18;
static const Bit32u RESONANCE_DECAY_THRESHOLD_CUTOFF_VALUE = 144 << 18;
static const Bit32u MAX_CUTOFF_VALUE = 240 << 18;
static const LogSample SILENCE = {65535, LogSample::POSITIVE};
Bit16u LA32Utilites::interpolateExp(const Bit16u fract) {
Bit16u expTabIndex = fract >> 3;
Bit16u extraBits = ~fract & 7;
Bit16u expTabEntry2 = 8191 - Tables::getInstance().exp9[expTabIndex];
Bit16u expTabEntry1 = expTabIndex == 0 ? 8191 : (8191 - Tables::getInstance().exp9[expTabIndex - 1]);
return expTabEntry2 + (((expTabEntry1 - expTabEntry2) * extraBits) >> 3);
}
Bit16s LA32Utilites::unlog(const LogSample &logSample) {
//Bit16s sample = (Bit16s)EXP2F(13.0f - logSample.logValue / 1024.0f);
Bit32u intLogValue = logSample.logValue >> 12;
Bit16u fracLogValue = logSample.logValue & 4095;
Bit16s sample = interpolateExp(fracLogValue) >> intLogValue;
return logSample.sign == LogSample::POSITIVE ? sample : -sample;
}
void LA32Utilites::addLogSamples(LogSample &logSample1, const LogSample &logSample2) {
Bit32u logSampleValue = logSample1.logValue + logSample2.logValue;
logSample1.logValue = logSampleValue < 65536 ? Bit16u(logSampleValue) : 65535;
logSample1.sign = logSample1.sign == logSample2.sign ? LogSample::POSITIVE : LogSample::NEGATIVE;
}
Bit32u LA32WaveGenerator::getSampleStep() {
// sampleStep = EXP2F(pitch / 4096.0f + 4.0f)
Bit32u sampleStep = LA32Utilites::interpolateExp(~pitch & 4095);
sampleStep <<= pitch >> 12;
sampleStep >>= 8;
sampleStep &= ~1;
return sampleStep;
}
Bit32u LA32WaveGenerator::getResonanceWaveLengthFactor(Bit32u effectiveCutoffValue) {
// resonanceWaveLengthFactor = (Bit32u)EXP2F(12.0f + effectiveCutoffValue / 4096.0f);
Bit32u resonanceWaveLengthFactor = LA32Utilites::interpolateExp(~effectiveCutoffValue & 4095);
resonanceWaveLengthFactor <<= effectiveCutoffValue >> 12;
return resonanceWaveLengthFactor;
}
Bit32u LA32WaveGenerator::getHighLinearLength(Bit32u effectiveCutoffValue) {
// Ratio of positive segment to wave length
Bit32u effectivePulseWidthValue = 0;
if (pulseWidth > 128) {
effectivePulseWidthValue = (pulseWidth - 128) << 6;
}
Bit32u highLinearLength = 0;
// highLinearLength = EXP2F(19.0f - effectivePulseWidthValue / 4096.0f + effectiveCutoffValue / 4096.0f) - 2 * SINE_SEGMENT_RELATIVE_LENGTH;
if (effectivePulseWidthValue < effectiveCutoffValue) {
Bit32u expArg = effectiveCutoffValue - effectivePulseWidthValue;
highLinearLength = LA32Utilites::interpolateExp(~expArg & 4095);
highLinearLength <<= 7 + (expArg >> 12);
highLinearLength -= 2 * SINE_SEGMENT_RELATIVE_LENGTH;
}
return highLinearLength;
}
void LA32WaveGenerator::computePositions(Bit32u highLinearLength, Bit32u lowLinearLength, Bit32u resonanceWaveLengthFactor) {
// Assuming 12-bit multiplication used here
squareWavePosition = resonanceSinePosition = (wavePosition >> 8) * (resonanceWaveLengthFactor >> 4);
if (squareWavePosition < SINE_SEGMENT_RELATIVE_LENGTH) {
phase = POSITIVE_RISING_SINE_SEGMENT;
return;
}
squareWavePosition -= SINE_SEGMENT_RELATIVE_LENGTH;
if (squareWavePosition < highLinearLength) {
phase = POSITIVE_LINEAR_SEGMENT;
return;
}
squareWavePosition -= highLinearLength;
if (squareWavePosition < SINE_SEGMENT_RELATIVE_LENGTH) {
phase = POSITIVE_FALLING_SINE_SEGMENT;
return;
}
squareWavePosition -= SINE_SEGMENT_RELATIVE_LENGTH;
resonanceSinePosition = squareWavePosition;
if (squareWavePosition < SINE_SEGMENT_RELATIVE_LENGTH) {
phase = NEGATIVE_FALLING_SINE_SEGMENT;
return;
}
squareWavePosition -= SINE_SEGMENT_RELATIVE_LENGTH;
if (squareWavePosition < lowLinearLength) {
phase = NEGATIVE_LINEAR_SEGMENT;
return;
}
squareWavePosition -= lowLinearLength;
phase = NEGATIVE_RISING_SINE_SEGMENT;
}
void LA32WaveGenerator::advancePosition() {
wavePosition += getSampleStep();
wavePosition %= 4 * SINE_SEGMENT_RELATIVE_LENGTH;
Bit32u effectiveCutoffValue = (cutoffVal > MIDDLE_CUTOFF_VALUE) ? (cutoffVal - MIDDLE_CUTOFF_VALUE) >> 10 : 0;
Bit32u resonanceWaveLengthFactor = getResonanceWaveLengthFactor(effectiveCutoffValue);
Bit32u highLinearLength = getHighLinearLength(effectiveCutoffValue);
Bit32u lowLinearLength = (resonanceWaveLengthFactor << 8) - 4 * SINE_SEGMENT_RELATIVE_LENGTH - highLinearLength;
computePositions(highLinearLength, lowLinearLength, resonanceWaveLengthFactor);
resonancePhase = ResonancePhase(((resonanceSinePosition >> 18) + (phase > POSITIVE_FALLING_SINE_SEGMENT ? 2 : 0)) & 3);
}
void LA32WaveGenerator::generateNextSquareWaveLogSample() {
Bit32u logSampleValue;
switch (phase) {
case POSITIVE_RISING_SINE_SEGMENT:
case NEGATIVE_FALLING_SINE_SEGMENT:
logSampleValue = Tables::getInstance().logsin9[(squareWavePosition >> 9) & 511];
break;
case POSITIVE_FALLING_SINE_SEGMENT:
case NEGATIVE_RISING_SINE_SEGMENT:
logSampleValue = Tables::getInstance().logsin9[~(squareWavePosition >> 9) & 511];
break;
case POSITIVE_LINEAR_SEGMENT:
case NEGATIVE_LINEAR_SEGMENT:
default:
logSampleValue = 0;
break;
}
logSampleValue <<= 2;
logSampleValue += amp >> 10;
if (cutoffVal < MIDDLE_CUTOFF_VALUE) {
logSampleValue += (MIDDLE_CUTOFF_VALUE - cutoffVal) >> 9;
}
squareLogSample.logValue = logSampleValue < 65536 ? Bit16u(logSampleValue) : 65535;
squareLogSample.sign = phase < NEGATIVE_FALLING_SINE_SEGMENT ? LogSample::POSITIVE : LogSample::NEGATIVE;
}
void LA32WaveGenerator::generateNextResonanceWaveLogSample() {
Bit32u logSampleValue;
if (resonancePhase == POSITIVE_FALLING_RESONANCE_SINE_SEGMENT || resonancePhase == NEGATIVE_RISING_RESONANCE_SINE_SEGMENT) {
logSampleValue = Tables::getInstance().logsin9[~(resonanceSinePosition >> 9) & 511];
} else {
logSampleValue = Tables::getInstance().logsin9[(resonanceSinePosition >> 9) & 511];
}
logSampleValue <<= 2;
logSampleValue += amp >> 10;
// From the digital captures, the decaying speed of the resonance sine is found a bit different for the positive and the negative segments
Bit32u decayFactor = phase < NEGATIVE_FALLING_SINE_SEGMENT ? resAmpDecayFactor : resAmpDecayFactor + 1;
// Unsure about resonanceSinePosition here. It's possible that dedicated counter & decrement are used. Although, cutoff is finely ramped, so maybe not.
logSampleValue += resonanceAmpSubtraction + (((resonanceSinePosition >> 4) * decayFactor) >> 8);
// To ensure the output wave has no breaks, two different windows are applied to the beginning and the ending of the resonance sine segment
if (phase == POSITIVE_RISING_SINE_SEGMENT || phase == NEGATIVE_FALLING_SINE_SEGMENT) {
// The window is synchronous sine here
logSampleValue += Tables::getInstance().logsin9[(squareWavePosition >> 9) & 511] << 2;
} else if (phase == POSITIVE_FALLING_SINE_SEGMENT || phase == NEGATIVE_RISING_SINE_SEGMENT) {
// The window is synchronous square sine here
logSampleValue += Tables::getInstance().logsin9[~(squareWavePosition >> 9) & 511] << 3;
}
if (cutoffVal < MIDDLE_CUTOFF_VALUE) {
// For the cutoff values below the cutoff middle point, it seems the amp of the resonance wave is exponentially decayed
logSampleValue += 31743 + ((MIDDLE_CUTOFF_VALUE - cutoffVal) >> 9);
} else if (cutoffVal < RESONANCE_DECAY_THRESHOLD_CUTOFF_VALUE) {
// For the cutoff values below this point, the amp of the resonance wave is sinusoidally decayed
Bit32u sineIx = (cutoffVal - MIDDLE_CUTOFF_VALUE) >> 13;
logSampleValue += Tables::getInstance().logsin9[sineIx] << 2;
}
// After all the amp decrements are added, it should be safe now to adjust the amp of the resonance wave to what we see on captures
logSampleValue -= 1 << 12;
resonanceLogSample.logValue = logSampleValue < 65536 ? Bit16u(logSampleValue) : 65535;
resonanceLogSample.sign = resonancePhase < NEGATIVE_FALLING_RESONANCE_SINE_SEGMENT ? LogSample::POSITIVE : LogSample::NEGATIVE;
}
void LA32WaveGenerator::generateNextSawtoothCosineLogSample(LogSample &logSample) const {
Bit32u sawtoothCosinePosition = wavePosition + (1 << 18);
if ((sawtoothCosinePosition & (1 << 18)) > 0) {
logSample.logValue = Tables::getInstance().logsin9[~(sawtoothCosinePosition >> 9) & 511];
} else {
logSample.logValue = Tables::getInstance().logsin9[(sawtoothCosinePosition >> 9) & 511];
}
logSample.logValue <<= 2;
logSample.sign = ((sawtoothCosinePosition & (1 << 19)) == 0) ? LogSample::POSITIVE : LogSample::NEGATIVE;
}
void LA32WaveGenerator::pcmSampleToLogSample(LogSample &logSample, const Bit16s pcmSample) const {
Bit32u logSampleValue = (32787 - (pcmSample & 32767)) << 1;
logSampleValue += amp >> 10;
logSample.logValue = logSampleValue < 65536 ? Bit16u(logSampleValue) : 65535;
logSample.sign = pcmSample < 0 ? LogSample::NEGATIVE : LogSample::POSITIVE;
}
void LA32WaveGenerator::generateNextPCMWaveLogSamples() {
// This should emulate the ladder we see in the PCM captures for pitches 01, 02, 07, etc.
// The most probable cause is the factor in the interpolation formula is one bit less
// accurate than the sample position counter
pcmInterpolationFactor = (wavePosition & 255) >> 1;
Bit32u pcmWaveTableIx = wavePosition >> 8;
pcmSampleToLogSample(firstPCMLogSample, pcmWaveAddress[pcmWaveTableIx]);
if (pcmWaveInterpolated) {
pcmWaveTableIx++;
if (pcmWaveTableIx < pcmWaveLength) {
pcmSampleToLogSample(secondPCMLogSample, pcmWaveAddress[pcmWaveTableIx]);
} else {
if (pcmWaveLooped) {
pcmWaveTableIx -= pcmWaveLength;
pcmSampleToLogSample(secondPCMLogSample, pcmWaveAddress[pcmWaveTableIx]);
} else {
secondPCMLogSample = SILENCE;
}
}
} else {
secondPCMLogSample = SILENCE;
}
// pcmSampleStep = (Bit32u)EXP2F(pitch / 4096.0f + 3.0f);
Bit32u pcmSampleStep = LA32Utilites::interpolateExp(~pitch & 4095);
pcmSampleStep <<= pitch >> 12;
// Seeing the actual lengths of the PCM wave for pitches 00..12,
// the pcmPosition counter can be assumed to have 8-bit fractions
pcmSampleStep >>= 9;
wavePosition += pcmSampleStep;
if (wavePosition >= (pcmWaveLength << 8)) {
if (pcmWaveLooped) {
wavePosition -= pcmWaveLength << 8;
} else {
deactivate();
}
}
}
void LA32WaveGenerator::initSynth(const bool useSawtoothWaveform, const Bit8u usePulseWidth, const Bit8u useResonance) {
sawtoothWaveform = useSawtoothWaveform;
pulseWidth = usePulseWidth;
resonance = useResonance;
wavePosition = 0;
squareWavePosition = 0;
phase = POSITIVE_RISING_SINE_SEGMENT;
resonanceSinePosition = 0;
resonancePhase = POSITIVE_RISING_RESONANCE_SINE_SEGMENT;
resonanceAmpSubtraction = (32 - resonance) << 10;
resAmpDecayFactor = Tables::getInstance().resAmpDecayFactor[resonance >> 2] << 2;
pcmWaveAddress = NULL;
active = true;
}
void LA32WaveGenerator::initPCM(const Bit16s * const usePCMWaveAddress, const Bit32u usePCMWaveLength, const bool usePCMWaveLooped, const bool usePCMWaveInterpolated) {
pcmWaveAddress = usePCMWaveAddress;
pcmWaveLength = usePCMWaveLength;
pcmWaveLooped = usePCMWaveLooped;
pcmWaveInterpolated = usePCMWaveInterpolated;
wavePosition = 0;
active = true;
}
void LA32WaveGenerator::generateNextSample(const Bit32u useAmp, const Bit16u usePitch, const Bit32u useCutoffVal) {
if (!active) {
return;
}
amp = useAmp;
pitch = usePitch;
if (isPCMWave()) {
generateNextPCMWaveLogSamples();
return;
}
// The 240 cutoffVal limit was determined via sample analysis (internal Munt capture IDs: glop3, glop4).
// More research is needed to be sure that this is correct, however.
cutoffVal = (useCutoffVal > MAX_CUTOFF_VALUE) ? MAX_CUTOFF_VALUE : useCutoffVal;
generateNextSquareWaveLogSample();
generateNextResonanceWaveLogSample();
if (sawtoothWaveform) {
LogSample cosineLogSample;
generateNextSawtoothCosineLogSample(cosineLogSample);
LA32Utilites::addLogSamples(squareLogSample, cosineLogSample);
LA32Utilites::addLogSamples(resonanceLogSample, cosineLogSample);
}
advancePosition();
}
LogSample LA32WaveGenerator::getOutputLogSample(const bool first) const {
if (!isActive()) {
return SILENCE;
}
if (isPCMWave()) {
return first ? firstPCMLogSample : secondPCMLogSample;
}
return first ? squareLogSample : resonanceLogSample;
}
void LA32WaveGenerator::deactivate() {
active = false;
}
bool LA32WaveGenerator::isActive() const {
return active;
}
bool LA32WaveGenerator::isPCMWave() const {
return pcmWaveAddress != NULL;
}
Bit32u LA32WaveGenerator::getPCMInterpolationFactor() const {
return pcmInterpolationFactor;
}
void LA32IntPartialPair::init(const bool useRingModulated, const bool useMixed) {
ringModulated = useRingModulated;
mixed = useMixed;
}
void LA32IntPartialPair::initSynth(const PairType useMaster, const bool sawtoothWaveform, const Bit8u pulseWidth, const Bit8u resonance) {
if (useMaster == MASTER) {
master.initSynth(sawtoothWaveform, pulseWidth, resonance);
} else {
slave.initSynth(sawtoothWaveform, pulseWidth, resonance);
}
}
void LA32IntPartialPair::initPCM(const PairType useMaster, const Bit16s *pcmWaveAddress, const Bit32u pcmWaveLength, const bool pcmWaveLooped) {
if (useMaster == MASTER) {
master.initPCM(pcmWaveAddress, pcmWaveLength, pcmWaveLooped, true);
} else {
slave.initPCM(pcmWaveAddress, pcmWaveLength, pcmWaveLooped, !ringModulated);
}
}
void LA32IntPartialPair::generateNextSample(const PairType useMaster, const Bit32u amp, const Bit16u pitch, const Bit32u cutoff) {
if (useMaster == MASTER) {
master.generateNextSample(amp, pitch, cutoff);
} else {
slave.generateNextSample(amp, pitch, cutoff);
}
}
Bit16s LA32IntPartialPair::unlogAndMixWGOutput(const LA32WaveGenerator &wg) {
if (!wg.isActive()) {
return 0;
}
Bit16s firstSample = LA32Utilites::unlog(wg.getOutputLogSample(true));
Bit16s secondSample = LA32Utilites::unlog(wg.getOutputLogSample(false));
if (wg.isPCMWave()) {
return Bit16s(firstSample + (((Bit32s(secondSample) - Bit32s(firstSample)) * wg.getPCMInterpolationFactor()) >> 7));
}
return firstSample + secondSample;
}
static inline Bit16s produceDistortedSample(Bit16s sample) {
return ((sample & 0x2000) == 0) ? Bit16s(sample & 0x1fff) : Bit16s(sample | ~0x1fff);
}
Bit16s LA32IntPartialPair::nextOutSample() {
if (!ringModulated) {
return unlogAndMixWGOutput(master) + unlogAndMixWGOutput(slave);
}
Bit16s masterSample = unlogAndMixWGOutput(master); // Store master partial sample for further mixing
/* SEMI-CONFIRMED from sample analysis:
* We observe that for partial structures with ring modulation the interpolation is not applied to the slave PCM partial.
* It's assumed that the multiplication circuitry intended to perform the interpolation on the slave PCM partial
* is borrowed by the ring modulation circuit (or the LA32 chip has a similar lack of resources assigned to each partial pair).
*/
Bit16s slaveSample = slave.isPCMWave() ? LA32Utilites::unlog(slave.getOutputLogSample(true)) : unlogAndMixWGOutput(slave);
/* SEMI-CONFIRMED: Ring modulation model derived from sample analysis of specially constructed patches which exploit distortion.
* LA32 ring modulator found to produce distorted output in case if the absolute value of maximal amplitude of one of the input partials exceeds 8191.
* This is easy to reproduce using synth partials with resonance values close to the maximum. It looks like an integer overflow happens in this case.
* As the distortion is strictly bound to the amplitude of the complete mixed square + resonance wave in the linear space,
* it is reasonable to assume the ring modulation is performed also in the linear space by sample multiplication.
* Most probably the overflow is caused by limited precision of the multiplication circuit as the very similar distortion occurs with panning.
*/
Bit16s ringModulatedSample = Bit16s((Bit32s(produceDistortedSample(masterSample)) * Bit32s(produceDistortedSample(slaveSample))) >> 13);
return mixed ? masterSample + ringModulatedSample : ringModulatedSample;
}
void LA32IntPartialPair::deactivate(const PairType useMaster) {
if (useMaster == MASTER) {
master.deactivate();
} else {
slave.deactivate();
}
}
bool LA32IntPartialPair::isActive(const PairType useMaster) const {
return useMaster == MASTER ? master.isActive() : slave.isActive();
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/LA32WaveGenerator.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 4,766 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstddef>
#include "SampleRateConverter.h"
#if MT32EMU_WITH_LIBSOXR_RESAMPLER
#include "srchelper/SoxrAdapter.h"
#elif MT32EMU_WITH_LIBSAMPLERATE_RESAMPLER
#include "srchelper/SamplerateAdapter.h"
#elif MT32EMU_WITH_INTERNAL_RESAMPLER
#include "srchelper/InternalResampler.h"
#endif
#include "Synth.h"
using namespace MT32Emu;
static inline void *createDelegate(Synth &synth, double targetSampleRate, SamplerateConversionQuality quality) {
#if MT32EMU_WITH_LIBSOXR_RESAMPLER
return new SoxrAdapter(synth, targetSampleRate, quality);
#elif MT32EMU_WITH_LIBSAMPLERATE_RESAMPLER
return new SamplerateAdapter(synth, targetSampleRate, quality);
#elif MT32EMU_WITH_INTERNAL_RESAMPLER
return new InternalResampler(synth, targetSampleRate, quality);
#else
(void)synth, (void)targetSampleRate, (void)quality;
return NULL;
#endif
}
AnalogOutputMode SampleRateConverter::getBestAnalogOutputMode(double targetSampleRate) {
if (Synth::getStereoOutputSampleRate(AnalogOutputMode_ACCURATE) < targetSampleRate) {
return AnalogOutputMode_OVERSAMPLED;
} else if (Synth::getStereoOutputSampleRate(AnalogOutputMode_COARSE) < targetSampleRate) {
return AnalogOutputMode_ACCURATE;
}
return AnalogOutputMode_COARSE;
}
double SampleRateConverter::getSupportedOutputSampleRate(double desiredSampleRate) {
#if MT32EMU_WITH_LIBSOXR_RESAMPLER || MT32EMU_WITH_LIBSAMPLERATE_RESAMPLER || MT32EMU_WITH_INTERNAL_RESAMPLER
return desiredSampleRate > 0 ? desiredSampleRate : 0;
#else
(void)desiredSampleRate;
return 0;
#endif
}
SampleRateConverter::SampleRateConverter(Synth &useSynth, double targetSampleRate, SamplerateConversionQuality useQuality) :
synthInternalToTargetSampleRateRatio(SAMPLE_RATE / targetSampleRate),
useSynthDelegate(useSynth.getStereoOutputSampleRate() == targetSampleRate),
srcDelegate(useSynthDelegate ? &useSynth : createDelegate(useSynth, targetSampleRate, useQuality))
{}
SampleRateConverter::~SampleRateConverter() {
if (!useSynthDelegate) {
#if MT32EMU_WITH_LIBSOXR_RESAMPLER
delete static_cast<SoxrAdapter *>(srcDelegate);
#elif MT32EMU_WITH_LIBSAMPLERATE_RESAMPLER
delete static_cast<SamplerateAdapter *>(srcDelegate);
#elif MT32EMU_WITH_INTERNAL_RESAMPLER
delete static_cast<InternalResampler *>(srcDelegate);
#endif
}
}
void SampleRateConverter::getOutputSamples(float *buffer, unsigned int length) {
if (useSynthDelegate) {
static_cast<Synth *>(srcDelegate)->render(buffer, length);
return;
}
#if MT32EMU_WITH_LIBSOXR_RESAMPLER
static_cast<SoxrAdapter *>(srcDelegate)->getOutputSamples(buffer, length);
#elif MT32EMU_WITH_LIBSAMPLERATE_RESAMPLER
static_cast<SamplerateAdapter *>(srcDelegate)->getOutputSamples(buffer, length);
#elif MT32EMU_WITH_INTERNAL_RESAMPLER
static_cast<InternalResampler *>(srcDelegate)->getOutputSamples(buffer, length);
#else
Synth::muteSampleBuffer(buffer, length);
#endif
}
void SampleRateConverter::getOutputSamples(Bit16s *outBuffer, unsigned int length) {
static const unsigned int CHANNEL_COUNT = 2;
if (useSynthDelegate) {
static_cast<Synth *>(srcDelegate)->render(outBuffer, length);
return;
}
float floatBuffer[CHANNEL_COUNT * MAX_SAMPLES_PER_RUN];
while (length > 0) {
const unsigned int size = MAX_SAMPLES_PER_RUN < length ? MAX_SAMPLES_PER_RUN : length;
getOutputSamples(floatBuffer, size);
float *outs = floatBuffer;
float *ends = floatBuffer + CHANNEL_COUNT * size;
while (outs < ends) {
*(outBuffer++) = Synth::convertSample(*(outs++));
}
length -= size;
}
}
double SampleRateConverter::convertOutputToSynthTimestamp(double outputTimestamp) const {
return outputTimestamp * synthInternalToTargetSampleRateRatio;
}
double SampleRateConverter::convertSynthToOutputTimestamp(double synthTimestamp) const {
return synthTimestamp / synthInternalToTargetSampleRateRatio;
}
``` | /content/code_sandbox/src/sound/munt/SampleRateConverter.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,048 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstddef>
#include "internals.h"
#include "LA32FloatWaveGenerator.h"
#include "mmath.h"
#include "Tables.h"
namespace MT32Emu {
static const float MIDDLE_CUTOFF_VALUE = 128.0f;
static const float RESONANCE_DECAY_THRESHOLD_CUTOFF_VALUE = 144.0f;
static const float MAX_CUTOFF_VALUE = 240.0f;
float LA32FloatWaveGenerator::getPCMSample(unsigned int position) {
if (position >= pcmWaveLength) {
if (!pcmWaveLooped) {
return 0;
}
position = position % pcmWaveLength;
}
Bit16s pcmSample = pcmWaveAddress[position];
float sampleValue = EXP2F(((pcmSample & 32767) - 32787.0f) / 2048.0f);
return ((pcmSample & 32768) == 0) ? sampleValue : -sampleValue;
}
void LA32FloatWaveGenerator::initSynth(const bool useSawtoothWaveform, const Bit8u usePulseWidth, const Bit8u useResonance) {
sawtoothWaveform = useSawtoothWaveform;
pulseWidth = usePulseWidth;
resonance = useResonance;
wavePos = 0.0f;
lastFreq = 0.0f;
pcmWaveAddress = NULL;
active = true;
}
void LA32FloatWaveGenerator::initPCM(const Bit16s * const usePCMWaveAddress, const Bit32u usePCMWaveLength, const bool usePCMWaveLooped, const bool usePCMWaveInterpolated) {
pcmWaveAddress = usePCMWaveAddress;
pcmWaveLength = usePCMWaveLength;
pcmWaveLooped = usePCMWaveLooped;
pcmWaveInterpolated = usePCMWaveInterpolated;
pcmPosition = 0.0f;
active = true;
}
// ampVal - Logarithmic amp of the wave generator
// pitch - Logarithmic frequency of the resulting wave
// cutoffRampVal - Composed of the base cutoff in range [78..178] left-shifted by 18 bits and the TVF modifier
float LA32FloatWaveGenerator::generateNextSample(const Bit32u ampVal, const Bit16u pitch, const Bit32u cutoffRampVal) {
if (!active) {
return 0.0f;
}
float sample = 0.0f;
// SEMI-CONFIRMED: From sample analysis:
// (1) Tested with a single partial playing PCM wave 77 with pitchCoarse 36 and no keyfollow, velocity follow, etc.
// This gives results within +/- 2 at the output (before any DAC bitshifting)
// when sustaining at levels 156 - 255 with no modifiers.
// (2) Tested with a special square wave partial (internal capture ID tva5) at TVA envelope levels 155-255.
// This gives deltas between -1 and 0 compared to the real output. Note that this special partial only produces
// positive amps, so negative still needs to be explored, as well as lower levels.
//
// Also still partially unconfirmed is the behaviour when ramping between levels, as well as the timing.
float amp = EXP2F(ampVal / -1024.0f / 4096.0f);
float freq = EXP2F(pitch / 4096.0f - 16.0f) * SAMPLE_RATE;
if (isPCMWave()) {
// Render PCM waveform
int len = pcmWaveLength;
int intPCMPosition = int(pcmPosition);
if (intPCMPosition >= len && !pcmWaveLooped) {
// We're now past the end of a non-looping PCM waveform so it's time to die.
deactivate();
return 0.0f;
}
float positionDelta = freq * 2048.0f / SAMPLE_RATE;
// Linear interpolation
float firstSample = getPCMSample(intPCMPosition);
// We observe that for partial structures with ring modulation the interpolation is not applied to the slave PCM partial.
// It's assumed that the multiplication circuitry intended to perform the interpolation on the slave PCM partial
// is borrowed by the ring modulation circuit (or the LA32 chip has a similar lack of resources assigned to each partial pair).
if (pcmWaveInterpolated) {
sample = firstSample + (getPCMSample(intPCMPosition + 1) - firstSample) * (pcmPosition - intPCMPosition);
} else {
sample = firstSample;
}
float newPCMPosition = pcmPosition + positionDelta;
if (pcmWaveLooped) {
newPCMPosition = fmod(newPCMPosition, float(pcmWaveLength));
}
pcmPosition = newPCMPosition;
} else {
// Render synthesised waveform
wavePos *= lastFreq / freq;
lastFreq = freq;
float resAmp = EXP2F(1.0f - (32 - resonance) / 4.0f);
{
//static const float resAmpFactor = EXP2F(-7);
//resAmp = EXP2I(resonance << 10) * resAmpFactor;
}
// The cutoffModifier may not be supposed to be directly added to the cutoff -
// it may for example need to be multiplied in some way.
// The 240 cutoffVal limit was determined via sample analysis (internal Munt capture IDs: glop3, glop4).
// More research is needed to be sure that this is correct, however.
float cutoffVal = cutoffRampVal / 262144.0f;
if (cutoffVal > MAX_CUTOFF_VALUE) {
cutoffVal = MAX_CUTOFF_VALUE;
}
// Wave length in samples
float waveLen = SAMPLE_RATE / freq;
// Init cosineLen
float cosineLen = 0.5f * waveLen;
if (cutoffVal > MIDDLE_CUTOFF_VALUE) {
cosineLen *= EXP2F((cutoffVal - MIDDLE_CUTOFF_VALUE) / -16.0f); // found from sample analysis
}
// Start playing in center of first cosine segment
// relWavePos is shifted by a half of cosineLen
float relWavePos = wavePos + 0.5f * cosineLen;
if (relWavePos > waveLen) {
relWavePos -= waveLen;
}
// Ratio of positive segment to wave length
float pulseLen = 0.5f;
if (pulseWidth > 128) {
pulseLen = EXP2F((64 - pulseWidth) / 64.0f);
//static const float pulseLenFactor = EXP2F(-192 / 64);
//pulseLen = EXP2I((256 - pulseWidthVal) << 6) * pulseLenFactor;
}
pulseLen *= waveLen;
float hLen = pulseLen - cosineLen;
// Ignore pulsewidths too high for given freq
if (hLen < 0.0f) {
hLen = 0.0f;
}
// Correct resAmp for cutoff in range 50..66
if ((cutoffVal >= MIDDLE_CUTOFF_VALUE) && (cutoffVal < RESONANCE_DECAY_THRESHOLD_CUTOFF_VALUE)) {
resAmp *= sin(FLOAT_PI * (cutoffVal - MIDDLE_CUTOFF_VALUE) / 32.0f);
}
// Produce filtered square wave with 2 cosine waves on slopes
// 1st cosine segment
if (relWavePos < cosineLen) {
sample = -cos(FLOAT_PI * relWavePos / cosineLen);
} else
// high linear segment
if (relWavePos < (cosineLen + hLen)) {
sample = 1.f;
} else
// 2nd cosine segment
if (relWavePos < (2 * cosineLen + hLen)) {
sample = cos(FLOAT_PI * (relWavePos - (cosineLen + hLen)) / cosineLen);
} else {
// low linear segment
sample = -1.f;
}
if (cutoffVal < MIDDLE_CUTOFF_VALUE) {
// Attenuate samples below cutoff 50
// Found by sample analysis
sample *= EXP2F(-0.125f * (MIDDLE_CUTOFF_VALUE - cutoffVal));
} else {
// Add resonance sine. Effective for cutoff > 50 only
float resSample = 1.0f;
// Resonance decay speed factor
float resAmpDecayFactor = Tables::getInstance().resAmpDecayFactor[resonance >> 2];
// Now relWavePos counts from the middle of first cosine
relWavePos = wavePos;
// negative segments
if (!(relWavePos < (cosineLen + hLen))) {
resSample = -resSample;
relWavePos -= cosineLen + hLen;
// From the digital captures, the decaying speed of the resonance sine is found a bit different for the positive and the negative segments
resAmpDecayFactor += 0.25f;
}
// Resonance sine WG
resSample *= sin(FLOAT_PI * relWavePos / cosineLen);
// Resonance sine amp
float resAmpFadeLog2 = -0.125f * resAmpDecayFactor * (relWavePos / cosineLen); // seems to be exact
float resAmpFade = EXP2F(resAmpFadeLog2);
// Now relWavePos set negative to the left from center of any cosine
relWavePos = wavePos;
// negative segment
if (!(wavePos < (waveLen - 0.5f * cosineLen))) {
relWavePos -= waveLen;
} else
// positive segment
if (!(wavePos < (hLen + 0.5f * cosineLen))) {
relWavePos -= cosineLen + hLen;
}
// To ensure the output wave has no breaks, two different windows are applied to the beginning and the ending of the resonance sine segment
if (relWavePos < 0.5f * cosineLen) {
float syncSine = sin(FLOAT_PI * relWavePos / cosineLen);
if (relWavePos < 0.0f) {
// The window is synchronous square sine here
resAmpFade *= syncSine * syncSine;
} else {
// The window is synchronous sine here
resAmpFade *= syncSine;
}
}
sample += resSample * resAmp * resAmpFade;
}
// sawtooth waves
if (sawtoothWaveform) {
sample *= cos(FLOAT_2PI * wavePos / waveLen);
}
wavePos++;
// wavePos isn't supposed to be > waveLen
if (wavePos > waveLen) {
wavePos -= waveLen;
}
}
// Multiply sample with current TVA value
sample *= amp;
return sample;
}
void LA32FloatWaveGenerator::deactivate() {
active = false;
}
bool LA32FloatWaveGenerator::isActive() const {
return active;
}
bool LA32FloatWaveGenerator::isPCMWave() const {
return pcmWaveAddress != NULL;
}
void LA32FloatPartialPair::init(const bool useRingModulated, const bool useMixed) {
ringModulated = useRingModulated;
mixed = useMixed;
masterOutputSample = 0.0f;
slaveOutputSample = 0.0f;
}
void LA32FloatPartialPair::initSynth(const PairType useMaster, const bool sawtoothWaveform, const Bit8u pulseWidth, const Bit8u resonance) {
if (useMaster == MASTER) {
master.initSynth(sawtoothWaveform, pulseWidth, resonance);
} else {
slave.initSynth(sawtoothWaveform, pulseWidth, resonance);
}
}
void LA32FloatPartialPair::initPCM(const PairType useMaster, const Bit16s *pcmWaveAddress, const Bit32u pcmWaveLength, const bool pcmWaveLooped) {
if (useMaster == MASTER) {
master.initPCM(pcmWaveAddress, pcmWaveLength, pcmWaveLooped, true);
} else {
slave.initPCM(pcmWaveAddress, pcmWaveLength, pcmWaveLooped, !ringModulated);
}
}
void LA32FloatPartialPair::generateNextSample(const PairType useMaster, const Bit32u amp, const Bit16u pitch, const Bit32u cutoff) {
if (useMaster == MASTER) {
masterOutputSample = master.generateNextSample(amp, pitch, cutoff);
} else {
slaveOutputSample = slave.generateNextSample(amp, pitch, cutoff);
}
}
static inline float produceDistortedSample(float sample) {
if (sample < -1.0f) {
return sample + 2.0f;
} else if (1.0f < sample) {
return sample - 2.0f;
}
return sample;
}
float LA32FloatPartialPair::nextOutSample() {
// Note, LA32FloatWaveGenerator produces each sample normalised in terms of a single playing partial,
// so the unity sample corresponds to the internal LA32 logarithmic fixed-point unity sample.
// However, each logarithmic sample is then unlogged to a 14-bit signed integer value, i.e. the max absolute value is 8192.
// Thus, considering that samples are further mapped to a 16-bit signed integer,
// we apply a conversion factor 0.25 to produce properly normalised float samples.
if (!ringModulated) {
return 0.25f * (masterOutputSample + slaveOutputSample);
}
/*
* SEMI-CONFIRMED: Ring modulation model derived from sample analysis of specially constructed patches which exploit distortion.
* LA32 ring modulator found to produce distorted output in case if the absolute value of maximal amplitude of one of the input partials exceeds 8191.
* This is easy to reproduce using synth partials with resonance values close to the maximum. It looks like an integer overflow happens in this case.
* As the distortion is strictly bound to the amplitude of the complete mixed square + resonance wave in the linear space,
* it is reasonable to assume the ring modulation is performed also in the linear space by sample multiplication.
* Most probably the overflow is caused by limited precision of the multiplication circuit as the very similar distortion occurs with panning.
*/
float ringModulatedSample = produceDistortedSample(masterOutputSample) * produceDistortedSample(slaveOutputSample);
return 0.25f * (mixed ? masterOutputSample + ringModulatedSample : ringModulatedSample);
}
void LA32FloatPartialPair::deactivate(const PairType useMaster) {
if (useMaster == MASTER) {
master.deactivate();
masterOutputSample = 0.0f;
} else {
slave.deactivate();
slaveOutputSample = 0.0f;
}
}
bool LA32FloatPartialPair::isActive(const PairType useMaster) const {
return useMaster == MASTER ? master.isActive() : slave.isActive();
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/LA32FloatWaveGenerator.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,539 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_ANALOG_H
#define MT32EMU_ANALOG_H
#include "globals.h"
#include "internals.h"
#include "Enumerations.h"
#include "Types.h"
namespace MT32Emu {
/* Analog class is dedicated to perform fair emulation of analogue circuitry of hardware units that is responsible
* for processing output signal after the DAC. It appears that the analogue circuit labeled "LPF" on the schematic
* also applies audible changes to the signal spectra. There is a significant boost of higher frequencies observed
* aside from quite poor attenuation of the mirror spectra above 16 kHz which is due to a relatively low filter order.
*
* As the final mixing of multiplexed output signal is performed after the DAC, this function is migrated here from Synth.
* Saying precisely, mixing is performed within the LPF as the entrance resistors are actually components of a LPF
* designed using the multiple feedback topology. Nevertheless, the schematic separates them.
*/
class Analog {
public:
static Analog *createAnalog(const AnalogOutputMode mode, const bool oldMT32AnalogLPF, const RendererType rendererType);
virtual ~Analog() {}
virtual unsigned int getOutputSampleRate() const = 0;
virtual Bit32u getDACStreamsLength(const Bit32u outputLength) const = 0;
virtual void setSynthOutputGain(const float synthGain) = 0;
virtual void setReverbOutputGain(const float reverbGain, const bool mt32ReverbCompatibilityMode) = 0;
virtual bool process(IntSample *outStream, const IntSample *nonReverbLeft, const IntSample *nonReverbRight, const IntSample *reverbDryLeft, const IntSample *reverbDryRight, const IntSample *reverbWetLeft, const IntSample *reverbWetRight, Bit32u outLength) = 0;
virtual bool process(FloatSample *outStream, const FloatSample *nonReverbLeft, const FloatSample *nonReverbRight, const FloatSample *reverbDryLeft, const FloatSample *reverbDryRight, const FloatSample *reverbWetLeft, const FloatSample *reverbWetRight, Bit32u outLength) = 0;
};
} // namespace MT32Emu
#endif // #ifndef MT32EMU_ANALOG_H
``` | /content/code_sandbox/src/sound/munt/Analog.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 575 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include "internals.h"
#include "Tables.h"
#include "mmath.h"
namespace MT32Emu {
// UNUSED: const int MIDDLEC = 60;
const Tables &Tables::getInstance() {
static const Tables instance;
return instance;
}
Tables::Tables() {
for (int lf = 0; lf <= 100; lf++) {
// CONFIRMED:KG: This matches a ROM table found by Mok
float fVal = (2.0f - LOG10F(float(lf) + 1.0f)) * 128.0f;
int val = int(fVal + 1.0);
if (val > 255) {
val = 255;
}
levelToAmpSubtraction[lf] = Bit8u(val);
}
envLogarithmicTime[0] = 64;
for (int lf = 1; lf <= 255; lf++) {
// CONFIRMED:KG: This matches a ROM table found by Mok
envLogarithmicTime[lf] = Bit8u(ceil(64.0f + LOG2F(float(lf)) * 8.0f));
}
#if 0
// The table below is to be used in conjunction with emulation of VCA of newer generation units which is currently missing.
// These relatively small values are rather intended to fine-tune the overall amplification of the VCA.
// CONFIRMED: Based on a table found by Mok in the LAPC-I control ROM
// Note that this matches the MT-32 table, but with the values clamped to a maximum of 8.
memset(masterVolToAmpSubtraction, 8, 71);
memset(masterVolToAmpSubtraction + 71, 7, 3);
memset(masterVolToAmpSubtraction + 74, 6, 4);
memset(masterVolToAmpSubtraction + 78, 5, 3);
memset(masterVolToAmpSubtraction + 81, 4, 4);
memset(masterVolToAmpSubtraction + 85, 3, 3);
memset(masterVolToAmpSubtraction + 88, 2, 4);
memset(masterVolToAmpSubtraction + 92, 1, 4);
memset(masterVolToAmpSubtraction + 96, 0, 5);
#else
// CONFIRMED: Based on a table found by Mok in the MT-32 control ROM
masterVolToAmpSubtraction[0] = 255;
for (int masterVol = 1; masterVol <= 100; masterVol++) {
masterVolToAmpSubtraction[masterVol] = Bit8u(106.31 - 16.0f * LOG2F(float(masterVol)));
}
#endif
for (int i = 0; i <= 100; i++) {
pulseWidth100To255[i] = Bit8u(i * 255 / 100.0f + 0.5f);
//synth->printDebug("%d: %d", i, pulseWidth100To255[i]);
}
// The LA32 chip contains an exponent table inside. The table contains 12-bit integer values.
// The actual table size is 512 rows. The 9 higher bits of the fractional part of the argument are used as a lookup address.
// To improve the precision of computations, the lower bits are supposed to be used for interpolation as the LA32 chip also
// contains another 512-row table with inverted differences between the main table values.
for (int i = 0; i < 512; i++) {
exp9[i] = Bit16u(8191.5f - EXP2F(13.0f + ~i / 512.0f));
}
// There is a logarithmic sine table inside the LA32 chip. The table contains 13-bit integer values.
for (int i = 1; i < 512; i++) {
logsin9[i] = Bit16u(0.5f - LOG2F(sin((i + 0.5f) / 1024.0f * FLOAT_PI)) * 1024.0f);
}
// The very first value is clamped to the maximum possible 13-bit integer
logsin9[0] = 8191;
// found from sample analysis
static const Bit8u resAmpDecayFactorTable[] = {31, 16, 12, 8, 5, 3, 2, 1};
resAmpDecayFactor = resAmpDecayFactorTable;
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/Tables.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,108 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_VERSION_TAG_H
#define MT32EMU_VERSION_TAG_H
#include "globals.h"
/* This is intended to implement a simple check of a shared library version in runtime. Sadly, per-symbol versioning
* is unavailable on many platforms, and even where it is, it's still not too easy to maintain for a C++ library.
* Therefore, the goal here is just to ensure that the client application quickly bails out when attempted to run
* with an older version of shared library, as well as to produce a more readable error message indicating a version mismatch
* rather than a report about some missing symbols with unreadable mangled names.
* This is an optional feature, since it adds some minor burden to both the library and client applications code,
* albeit it is ought to work on platforms that do not implement symbol versioning.
*/
#define MT32EMU_REALLY_BUILD_VERSION_TAG(major, minor) mt32emu_ ## major ## _ ## minor
/* This macro expansion step permits resolution the actual version numbers. */
#define MT32EMU_BUILD_VERSION_TAG(major, minor) MT32EMU_REALLY_BUILD_VERSION_TAG(major, minor)
#define MT32EMU_VERSION_TAG MT32EMU_BUILD_VERSION_TAG(MT32EMU_VERSION_MAJOR, MT32EMU_VERSION_MINOR)
#if defined(__cplusplus)
extern "C" {
MT32EMU_EXPORT extern const volatile char MT32EMU_VERSION_TAG;
}
// This pulls the external reference in yet prevents it from being optimised out.
static const volatile char mt32emu_version_tag = MT32EMU_VERSION_TAG;
#else
static void mt32emu_refer_version_tag(void) {
MT32EMU_EXPORT extern const volatile char MT32EMU_VERSION_TAG;
(void)MT32EMU_VERSION_TAG;
}
static void (*const volatile mt32emu_refer_version_tag_ref)(void) = mt32emu_refer_version_tag;
#endif
#undef MT32EMU_REALLY_BUILD_VERSION_TAG
#undef MT32EMU_BUILD_VERSION_TAG
#undef MT32EMU_VERSION_TAG
#endif
``` | /content/code_sandbox/src/sound/munt/VersionTagging.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 502 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_B_REVERB_MODEL_H
#define MT32EMU_B_REVERB_MODEL_H
#include "globals.h"
#include "internals.h"
#include "Enumerations.h"
#include "Types.h"
namespace MT32Emu {
class BReverbModel {
public:
static BReverbModel *createBReverbModel(const ReverbMode mode, const bool mt32CompatibleModel, const RendererType rendererType);
virtual ~BReverbModel() {}
virtual bool isOpen() const = 0;
// After construction or a close(), open() must be called at least once before any other call (with the exception of close()).
virtual void open() = 0;
// May be called multiple times without an open() in between.
virtual void close() = 0;
virtual void mute() = 0;
virtual void setParameters(Bit8u time, Bit8u level) = 0;
virtual bool isActive() const = 0;
virtual bool isMT32Compatible(const ReverbMode mode) const = 0;
virtual bool process(const IntSample *inLeft, const IntSample *inRight, IntSample *outLeft, IntSample *outRight, Bit32u numSamples) = 0;
virtual bool process(const FloatSample *inLeft, const FloatSample *inRight, FloatSample *outLeft, FloatSample *outRight, Bit32u numSamples) = 0;
};
} // namespace MT32Emu
#endif // #ifndef MT32EMU_B_REVERB_MODEL_H
``` | /content/code_sandbox/src/sound/munt/BReverbModel.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 408 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_ROMINFO_H
#define MT32EMU_ROMINFO_H
#include <cstddef>
#include "globals.h"
#include "File.h"
namespace MT32Emu {
// Defines vital info about ROM file to be used by synth and applications
struct ROMInfo {
public:
size_t fileSize;
const File::SHA1Digest &sha1Digest;
enum Type {PCM, Control, Reverb} type;
const char *shortName;
const char *description;
enum PairType {
// Complete ROM image ready to use with Synth.
Full,
// ROM image contains data that occupies lower addresses. Needs pairing before use.
FirstHalf,
// ROM image contains data that occupies higher addresses. Needs pairing before use.
SecondHalf,
// ROM image contains data that occupies even addresses. Needs pairing before use.
Mux0,
// ROM image contains data that occupies odd addresses. Needs pairing before use.
Mux1
} pairType;
// NULL for Full images or a pointer to the corresponding other image for pairing.
const ROMInfo *pairROMInfo;
// Returns a ROMInfo struct by inspecting the size and the SHA1 hash of the file
// among all the known ROMInfos.
MT32EMU_EXPORT static const ROMInfo *getROMInfo(File *file);
// Returns a ROMInfo struct by inspecting the size and the SHA1 hash of the file
// among the ROMInfos listed in the NULL-terminated list romInfos.
MT32EMU_EXPORT_V(2.5) static const ROMInfo *getROMInfo(File *file, const ROMInfo * const *romInfos);
// Currently no-op
MT32EMU_EXPORT static void freeROMInfo(const ROMInfo *romInfo);
// Allows retrieving a NULL-terminated list of ROMInfos for a range of types and pairTypes
// (specified by bitmasks)
// Useful for GUI/console app to output information on what ROMs it supports
// The caller must free the returned list with freeROMInfoList when finished.
MT32EMU_EXPORT static const ROMInfo **getROMInfoList(Bit32u types, Bit32u pairTypes);
// Frees the list of ROMInfos given that has been created by getROMInfoList.
MT32EMU_EXPORT static void freeROMInfoList(const ROMInfo **romInfos);
// Returns an immutable NULL-terminated list of all (full and partial) supported ROMInfos.
// For convenience, this method also can fill the number of non-NULL items present in the list
// if a non-NULL value is provided in optional argument itemCount.
MT32EMU_EXPORT_V(2.5) static const ROMInfo * const *getAllROMInfos(Bit32u *itemCount = NULL);
// Returns an immutable NULL-terminated list of all supported full ROMInfos.
// For convenience, this method also can fill the number of non-NULL items present in the list
// if a non-NULL value is provided in optional argument itemCount.
MT32EMU_EXPORT_V(2.5) static const ROMInfo * const *getFullROMInfos(Bit32u *itemCount = NULL);
// Returns an immutable NULL-terminated list of all supported partial ROMInfos.
// For convenience, this method also can fill the number of non-NULL items present in the list
// if a non-NULL value is provided in optional argument itemCount.
MT32EMU_EXPORT_V(2.5) static const ROMInfo * const *getPartialROMInfos(Bit32u *itemCount = NULL);
};
// Synth::open() requires a full control ROMImage and a compatible full PCM ROMImage to work
class ROMImage {
public:
// Creates a ROMImage object given a ROMInfo and a File. Keeps a reference
// to the File and ROMInfo given, which must be freed separately by the user
// after the ROMImage is freed.
// CAVEAT: This method always prefers full ROM images over partial ones.
// Because the lower half of CM-32L/CM-64/LAPC-I PCM ROM is essentially the full
// MT-32 PCM ROM, it is therefore aliased. In this case a partial image can only be
// created by the overridden method makeROMImage(File *, const ROMInfo * const *).
MT32EMU_EXPORT static const ROMImage *makeROMImage(File *file);
// Same as the method above but only permits creation of a ROMImage if the file content
// matches one of the ROMs described in a NULL-terminated list romInfos. This list can be
// created using e.g. method ROMInfo::getROMInfoList.
MT32EMU_EXPORT_V(2.5) static const ROMImage *makeROMImage(File *file, const ROMInfo * const *romInfos);
// Creates a ROMImage object given a couple of files that contain compatible partial ROM images.
// The files aren't referenced by the resulting ROMImage and may be freed anytime afterwards.
// The file in the resulting image will be automatically freed along with the ROMImage.
// If the given files contain incompatible partial images, NULL is returned.
MT32EMU_EXPORT_V(2.5) static const ROMImage *makeROMImage(File *file1, File *file2);
// Must only be done after all Synths using the ROMImage are deleted
MT32EMU_EXPORT static void freeROMImage(const ROMImage *romImage);
// Checks whether the given ROMImages are pairable and merges them into a full image, if possible.
// If the check fails, NULL is returned.
MT32EMU_EXPORT_V(2.5) static const ROMImage *mergeROMImages(const ROMImage *romImage1, const ROMImage *romImage2);
MT32EMU_EXPORT File *getFile() const;
// Returns true in case this ROMImage is built with a user provided File that has to be deallocated separately.
// For a ROMImage created via merging two partial ROMImages, this method returns false.
MT32EMU_EXPORT_V(2.5) bool isFileUserProvided() const;
MT32EMU_EXPORT const ROMInfo *getROMInfo() const;
private:
static const ROMImage *makeFullROMImage(Bit8u *data, size_t dataSize);
static const ROMImage *appendImages(const ROMImage *romImageLow, const ROMImage *romImageHigh);
static const ROMImage *interleaveImages(const ROMImage *romImageEven, const ROMImage *romImageOdd);
File * const file;
const bool ownFile;
const ROMInfo * const romInfo;
ROMImage(File *file, bool ownFile, const ROMInfo * const *romInfos);
~ROMImage();
// Make ROMIMage an identity class.
ROMImage(const ROMImage &);
ROMImage &operator=(const ROMImage &);
};
class MachineConfiguration {
public:
// Returns an immutable NULL-terminated list of all supported machine configurations.
// For convenience, this method also can fill the number of non-NULL items present in the list
// if a non-NULL value is provided in optional argument itemCount.
MT32EMU_EXPORT_V(2.5) static const MachineConfiguration * const *getAllMachineConfigurations(Bit32u *itemCount = NULL);
// Returns a string identifier of this MachineConfiguration.
MT32EMU_EXPORT_V(2.5) const char *getMachineID() const;
// Returns an immutable NULL-terminated list of ROMInfos that are compatible with this
// MachineConfiguration. That means the respective ROMImages can be successfully used together
// by the emulation engine. Calling ROMInfo::getROMInfo or ROMImage::makeROMImage with this list
// supplied enables identification of all files containing desired ROM images while filtering out
// any incompatible ones.
// For convenience, this method also can fill the number of non-NULL items present in the list
// if a non-NULL value is provided in optional argument itemCount.
MT32EMU_EXPORT_V(2.5) const ROMInfo * const *getCompatibleROMInfos(Bit32u *itemCount = NULL) const;
private:
const char * const machineID;
const ROMInfo * const * const romInfos;
const Bit32u romInfosCount;
MachineConfiguration(const char *machineID, const ROMInfo * const *romInfos, Bit32u romInfosCount);
// Make MachineConfiguration an identity class.
MachineConfiguration(const MachineConfiguration &);
~MachineConfiguration() {}
MachineConfiguration &operator=(const MachineConfiguration &);
};
} // namespace MT32Emu
#endif // #ifndef MT32EMU_ROMINFO_H
``` | /content/code_sandbox/src/sound/munt/ROMInfo.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,920 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstring>
#include "internals.h"
#include "File.h"
#include "sha1/sha1.h"
namespace MT32Emu {
AbstractFile::AbstractFile() : sha1DigestCalculated(false) {
sha1Digest[0] = 0;
reserved = NULL;
}
AbstractFile::AbstractFile(const SHA1Digest &useSHA1Digest) : sha1DigestCalculated(true) {
memcpy(sha1Digest, useSHA1Digest, sizeof(SHA1Digest) - 1);
sha1Digest[sizeof(SHA1Digest) - 1] = 0; // Ensure terminator char.
reserved = NULL;
}
const File::SHA1Digest &AbstractFile::getSHA1() {
if (sha1DigestCalculated) {
return sha1Digest;
}
sha1DigestCalculated = true;
size_t size = getSize();
if (size == 0) {
return sha1Digest;
}
const Bit8u *data = getData();
if (data == NULL) {
return sha1Digest;
}
unsigned char fileDigest[20];
sha1::calc(data, int(size), fileDigest);
sha1::toHexString(fileDigest, sha1Digest);
return sha1Digest;
}
ArrayFile::ArrayFile(const Bit8u *useData, size_t useSize) : data(useData), size(useSize)
{}
ArrayFile::ArrayFile(const Bit8u *useData, size_t useSize, const SHA1Digest &useSHA1Digest) : AbstractFile(useSHA1Digest), data(useData), size(useSize)
{}
size_t ArrayFile::getSize() {
return size;
}
const Bit8u *ArrayFile::getData() {
return data;
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/File.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 462 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstdio>
#include "internals.h"
#include "Synth.h"
#include "Analog.h"
#include "BReverbModel.h"
#include "Display.h"
#include "File.h"
#include "MemoryRegion.h"
#include "MidiEventQueue.h"
#include "Part.h"
#include "Partial.h"
#include "PartialManager.h"
#include "Poly.h"
#include "ROMInfo.h"
#include "TVA.h"
#if MT32EMU_MONITOR_SYSEX > 0
#include "mmath.h"
#endif
namespace MT32Emu {
// MIDI interface data transfer rate in samples. Used to simulate the transfer delay.
static const double MIDI_DATA_TRANSFER_RATE = double(SAMPLE_RATE) / 31250.0 * 8.0;
static const ControlROMFeatureSet OLD_MT32_ELDER = {
true, // quirkBasePitchOverflow
true, // quirkPitchEnvelopeOverflow
true, // quirkRingModulationNoMix
true, // quirkTVAZeroEnvLevels
true, // quirkPanMult
true, // quirkKeyShift
true, // quirkTVFBaseCutoffLimit
false, // quirkFastPitchChanges
true, // quirkDisplayCustomMessagePriority
true, // oldMT32DisplayFeatures
true, // defaultReverbMT32Compatible
true // oldMT32AnalogLPF
};
static const ControlROMFeatureSet OLD_MT32_LATER = {
true, // quirkBasePitchOverflow
true, // quirkPitchEnvelopeOverflow
true, // quirkRingModulationNoMix
true, // quirkTVAZeroEnvLevels
true, // quirkPanMult
true, // quirkKeyShift
true, // quirkTVFBaseCutoffLimit
false, // quirkFastPitchChanges
false, // quirkDisplayCustomMessagePriority
true, // oldMT32DisplayFeatures
true, // defaultReverbMT32Compatible
true // oldMT32AnalogLPF
};
static const ControlROMFeatureSet NEW_MT32_COMPATIBLE = {
false, // quirkBasePitchOverflow
false, // quirkPitchEnvelopeOverflow
false, // quirkRingModulationNoMix
false, // quirkTVAZeroEnvLevels
false, // quirkPanMult
false, // quirkKeyShift
false, // quirkTVFBaseCutoffLimit
false, // quirkFastPitchChanges
false, // quirkDisplayCustomMessagePriority
false, // oldMT32DisplayFeatures
false, // defaultReverbMT32Compatible
false // oldMT32AnalogLPF
};
static const ControlROMFeatureSet CM32LN_COMPATIBLE = {
false, // quirkBasePitchOverflow
false, // quirkPitchEnvelopeOverflow
false, // quirkRingModulationNoMix
false, // quirkTVAZeroEnvLevels
false, // quirkPanMult
false, // quirkKeyShift
false, // quirkTVFBaseCutoffLimit
true, // quirkFastPitchChanges
false, // quirkDisplayCustomMessagePriority
false, // oldMT32DisplayFeatures
false, // defaultReverbMT32Compatible
false // oldMT32AnalogLPF
};
static const ControlROMMap ControlROMMaps[] = {
// ID Features PCMmap PCMc tmbrA tmbrAO, tmbrAC tmbrB tmbrBO tmbrBC tmbrR trC rhythm rhyC rsrv panpot prog rhyMax patMax sysMax timMax sndGrp sGC stMsg sErMsg
{"ctrl_mt32_1_04", OLD_MT32_ELDER, 0x3000, 128, 0x8000, 0x0000, false, 0xC000, 0x4000, false, 0x3200, 30, 0x73A6, 85, 0x57C7, 0x57E2, 0x57D0, 0x5252, 0x525E, 0x526E, 0x520A, 0x7064, 19, 0x217A, 0x4BB6},
{"ctrl_mt32_1_05", OLD_MT32_ELDER, 0x3000, 128, 0x8000, 0x0000, false, 0xC000, 0x4000, false, 0x3200, 30, 0x7414, 85, 0x57C7, 0x57E2, 0x57D0, 0x5252, 0x525E, 0x526E, 0x520A, 0x70CA, 19, 0x217A, 0x4BB6},
{"ctrl_mt32_1_06", OLD_MT32_LATER, 0x3000, 128, 0x8000, 0x0000, false, 0xC000, 0x4000, false, 0x3200, 30, 0x7414, 85, 0x57D9, 0x57F4, 0x57E2, 0x5264, 0x5270, 0x5280, 0x521C, 0x70CA, 19, 0x217A, 0x4BBA},
{"ctrl_mt32_1_07", OLD_MT32_LATER, 0x3000, 128, 0x8000, 0x0000, false, 0xC000, 0x4000, false, 0x3200, 30, 0x73fe, 85, 0x57B1, 0x57CC, 0x57BA, 0x523C, 0x5248, 0x5258, 0x51F4, 0x70B0, 19, 0x217A, 0x4B92},
{"ctrl_mt32_bluer", OLD_MT32_LATER, 0x3000, 128, 0x8000, 0x0000, false, 0xC000, 0x4000, false, 0x3200, 30, 0x741C, 85, 0x57E5, 0x5800, 0x57EE, 0x5270, 0x527C, 0x528C, 0x5228, 0x70CE, 19, 0x217A, 0x4BC6},
{"ctrl_mt32_2_03", NEW_MT32_COMPATIBLE, 0x8100, 128, 0x8000, 0x8000, true, 0x8080, 0x8000, true, 0x8500, 64, 0x8580, 85, 0x4F49, 0x4F64, 0x4F52, 0x4885, 0x4889, 0x48A2, 0x48B9, 0x5A44, 19, 0x1EF0, 0x4066},
{"ctrl_mt32_2_04", NEW_MT32_COMPATIBLE, 0x8100, 128, 0x8000, 0x8000, true, 0x8080, 0x8000, true, 0x8500, 64, 0x8580, 85, 0x4F5D, 0x4F78, 0x4F66, 0x4899, 0x489D, 0x48B6, 0x48CD, 0x5A58, 19, 0x1EF0, 0x406D},
{"ctrl_mt32_2_06", NEW_MT32_COMPATIBLE, 0x8100, 128, 0x8000, 0x8000, true, 0x8080, 0x8000, true, 0x8500, 64, 0x8580, 85, 0x4F69, 0x4F84, 0x4F72, 0x48A5, 0x48A9, 0x48C2, 0x48D9, 0x5A64, 19, 0x1EF0, 0x4021},
{"ctrl_mt32_2_07", NEW_MT32_COMPATIBLE, 0x8100, 128, 0x8000, 0x8000, true, 0x8080, 0x8000, true, 0x8500, 64, 0x8580, 85, 0x4F81, 0x4F9C, 0x4F8A, 0x48B9, 0x48BD, 0x48D6, 0x48ED, 0x5A78, 19, 0x1EE7, 0x4035},
{"ctrl_cm32l_1_00", NEW_MT32_COMPATIBLE, 0x8100, 256, 0x8000, 0x8000, true, 0x8080, 0x8000, true, 0x8500, 64, 0x8580, 85, 0x4F65, 0x4F80, 0x4F6E, 0x48A1, 0x48A5, 0x48BE, 0x48D5, 0x5A6C, 19, 0x1EF0, 0x401D},
{"ctrl_cm32l_1_02", NEW_MT32_COMPATIBLE, 0x8100, 256, 0x8000, 0x8000, true, 0x8080, 0x8000, true, 0x8500, 64, 0x8580, 85, 0x4F93, 0x4FAE, 0x4F9C, 0x48CB, 0x48CF, 0x48E8, 0x48FF, 0x5A96, 19, 0x1EE7, 0x4047},
{"ctrl_cm32ln_1_00", CM32LN_COMPATIBLE, 0x8100, 256, 0x8000, 0x8000, true, 0x8080, 0x8000, true, 0x8500, 64, 0x8580, 85, 0x4EC7, 0x4EE2, 0x4ED0, 0x47FF, 0x4803, 0x481C, 0x4833, 0x55A2, 19, 0x1F59, 0x3F7C}
// (Note that old MT-32 ROMs actually have 86 entries for rhythmTemp)
};
static const PartialState PARTIAL_PHASE_TO_STATE[8] = {
PartialState_ATTACK, PartialState_ATTACK, PartialState_ATTACK, PartialState_ATTACK,
PartialState_SUSTAIN, PartialState_SUSTAIN, PartialState_RELEASE, PartialState_INACTIVE
};
static inline PartialState getPartialState(PartialManager *partialManager, unsigned int partialNum) {
const Partial *partial = partialManager->getPartial(partialNum);
return partial->isActive() ? PARTIAL_PHASE_TO_STATE[partial->getTVA()->getPhase()] : PartialState_INACTIVE;
}
template <class I, class O>
static inline void convertSampleFormat(const I *inBuffer, O *outBuffer, const Bit32u len) {
if (inBuffer == NULL || outBuffer == NULL) return;
const I *inBufferEnd = inBuffer + len;
while (inBuffer < inBufferEnd) {
*(outBuffer++) = Synth::convertSample(*(inBuffer++));
}
}
class Renderer {
protected:
Synth &synth;
void printDebug(const char *msg) const {
synth.printDebug("%s", msg);
}
bool isActivated() const {
return synth.activated;
}
bool isAbortingPoly() const {
return synth.isAbortingPoly();
}
Analog &getAnalog() const {
return *synth.analog;
}
MidiEventQueue &getMidiQueue() {
return *synth.midiQueue;
}
PartialManager &getPartialManager() {
return *synth.partialManager;
}
BReverbModel &getReverbModel() {
return *synth.reverbModel;
}
Bit32u getRenderedSampleCount() {
return synth.renderedSampleCount;
}
void incRenderedSampleCount(const Bit32u count) {
synth.renderedSampleCount += count;
}
void updateDisplayState();
public:
Renderer(Synth &useSynth) : synth(useSynth) {}
virtual ~Renderer() {}
virtual void render(IntSample *stereoStream, Bit32u len) = 0;
virtual void render(FloatSample *stereoStream, Bit32u len) = 0;
virtual void renderStreams(const DACOutputStreams<IntSample> &streams, Bit32u len) = 0;
virtual void renderStreams(const DACOutputStreams<FloatSample> &streams, Bit32u len) = 0;
};
template <class Sample>
class RendererImpl : public Renderer {
// These buffers are used for building the output streams as they are found at the DAC entrance.
// The output is mixed down to stereo interleaved further in the analog circuitry emulation.
Sample tmpNonReverbLeft[MAX_SAMPLES_PER_RUN], tmpNonReverbRight[MAX_SAMPLES_PER_RUN];
Sample tmpReverbDryLeft[MAX_SAMPLES_PER_RUN], tmpReverbDryRight[MAX_SAMPLES_PER_RUN];
Sample tmpReverbWetLeft[MAX_SAMPLES_PER_RUN], tmpReverbWetRight[MAX_SAMPLES_PER_RUN];
const DACOutputStreams<Sample> tmpBuffers;
DACOutputStreams<Sample> createTmpBuffers() {
DACOutputStreams<Sample> buffers = {
tmpNonReverbLeft, tmpNonReverbRight,
tmpReverbDryLeft, tmpReverbDryRight,
tmpReverbWetLeft, tmpReverbWetRight
};
return buffers;
}
public:
RendererImpl(Synth &useSynth) :
Renderer(useSynth),
tmpBuffers(createTmpBuffers())
{}
void render(IntSample *stereoStream, Bit32u len);
void render(FloatSample *stereoStream, Bit32u len);
void renderStreams(const DACOutputStreams<IntSample> &streams, Bit32u len);
void renderStreams(const DACOutputStreams<FloatSample> &streams, Bit32u len);
template <class O>
void doRenderAndConvert(O *stereoStream, Bit32u len);
void doRender(Sample *stereoStream, Bit32u len);
template <class O>
void doRenderAndConvertStreams(const DACOutputStreams<O> &streams, Bit32u len);
void doRenderStreams(const DACOutputStreams<Sample> &streams, Bit32u len);
void produceLA32Output(Sample *buffer, Bit32u len);
void convertSamplesToOutput(Sample *buffer, Bit32u len);
void produceStreams(const DACOutputStreams<Sample> &streams, Bit32u len);
};
class Extensions {
public:
RendererType selectedRendererType;
Bit32s masterTunePitchDelta;
bool niceAmpRamp;
bool nicePanning;
bool nicePartialMixing;
// Here we keep the reverse mapping of assigned parts per MIDI channel.
// NOTE: value above 8 means that the channel is not assigned
Bit8u chantable[16][9];
// This stores the index of Part in chantable that failed to play and required partial abortion.
Bit32u abortingPartIx;
bool preallocatedReverbMemory;
Bit32u midiEventQueueSize;
Bit32u midiEventQueueSysexStorageBufferSize;
Display *display;
bool oldMT32DisplayFeatures;
ReportHandler2 defaultReportHandler;
ReportHandler2 *reportHandler2;
};
Bit32u Synth::getLibraryVersionInt() {
return MT32EMU_CURRENT_VERSION_INT;
}
const char *Synth::getLibraryVersionString() {
return MT32EMU_VERSION;
}
Bit8u Synth::calcSysexChecksum(const Bit8u *data, const Bit32u len, const Bit8u initChecksum) {
unsigned int checksum = -initChecksum;
for (unsigned int i = 0; i < len; i++) {
checksum -= data[i];
}
return Bit8u(checksum & 0x7f);
}
Bit32u Synth::getStereoOutputSampleRate(AnalogOutputMode analogOutputMode) {
static const unsigned int SAMPLE_RATES[] = {SAMPLE_RATE, SAMPLE_RATE, SAMPLE_RATE * 3 / 2, SAMPLE_RATE * 3};
return SAMPLE_RATES[analogOutputMode];
}
Synth::Synth(ReportHandler *useReportHandler) :
mt32ram(*new MemParams),
mt32default(*new MemParams),
extensions(*new Extensions)
{
opened = false;
reverbOverridden = false;
partialCount = DEFAULT_MAX_PARTIALS;
controlROMMap = NULL;
controlROMFeatures = NULL;
reportHandler = useReportHandler != NULL ? useReportHandler : &extensions.defaultReportHandler;
extensions.reportHandler2 = &extensions.defaultReportHandler;
extensions.preallocatedReverbMemory = false;
for (int i = REVERB_MODE_ROOM; i <= REVERB_MODE_TAP_DELAY; i++) {
reverbModels[i] = NULL;
}
reverbModel = NULL;
analog = NULL;
renderer = NULL;
setDACInputMode(DACInputMode_NICE);
setMIDIDelayMode(MIDIDelayMode_DELAY_SHORT_MESSAGES_ONLY);
setOutputGain(1.0f);
setReverbOutputGain(1.0f);
setReversedStereoEnabled(false);
setNiceAmpRampEnabled(true);
setNicePanningEnabled(false);
setNicePartialMixingEnabled(false);
selectRendererType(RendererType_BIT16S);
patchTempMemoryRegion = NULL;
rhythmTempMemoryRegion = NULL;
timbreTempMemoryRegion = NULL;
patchesMemoryRegion = NULL;
timbresMemoryRegion = NULL;
systemMemoryRegion = NULL;
displayMemoryRegion = NULL;
resetMemoryRegion = NULL;
paddedTimbreMaxTable = NULL;
partialManager = NULL;
pcmWaves = NULL;
pcmROMData = NULL;
soundGroupNames = NULL;
midiQueue = NULL;
extensions.midiEventQueueSize = DEFAULT_MIDI_EVENT_QUEUE_SIZE;
extensions.midiEventQueueSysexStorageBufferSize = 0;
lastReceivedMIDIEventTimestamp = 0;
memset(parts, 0, sizeof(parts));
renderedSampleCount = 0;
extensions.display = NULL;
extensions.oldMT32DisplayFeatures = false;
}
Synth::~Synth() {
close(); // Make sure we're closed and everything is freed
delete &mt32ram;
delete &mt32default;
delete &extensions;
}
void Synth::setReportHandler2(ReportHandler2 *reportHandler2) {
if (reportHandler2 != NULL) {
reportHandler = reportHandler2;
extensions.reportHandler2 = reportHandler2;
} else {
reportHandler = &extensions.defaultReportHandler;
extensions.reportHandler2 = &extensions.defaultReportHandler;
}
}
void ReportHandler::showLCDMessage(const char *data) {
printf("WRITE-LCD: %s\n", data);
}
void ReportHandler::printDebug(const char *fmt, va_list list) {
vprintf(fmt, list);
printf("\n");
}
void Synth::rhythmNotePlayed() const {
extensions.display->rhythmNotePlayed();
}
void Synth::voicePartStateChanged(Bit8u partNum, bool partActivated) const {
extensions.display->voicePartStateChanged(partNum, partActivated);
}
void Synth::newTimbreSet(Bit8u partNum) const {
const Part *part = getPart(partNum);
reportHandler->onProgramChanged(partNum, getSoundGroupName(part), part->getCurrentInstr());
}
const char *Synth::getSoundGroupName(const Part *part) const {
const PatchParam &patch = part->getPatchTemp()->patch;
return getSoundGroupName(patch.timbreGroup, patch.timbreNum);
}
const char *Synth::getSoundGroupName(Bit8u timbreGroup, Bit8u timbreNumber) const {
switch (timbreGroup) {
case 1:
timbreNumber += 64;
// Fall-through
case 0:
return soundGroupNames[soundGroupIx[timbreNumber]];
case 2:
return soundGroupNames[controlROMMap->soundGroupsCount - 2];
case 3:
return soundGroupNames[controlROMMap->soundGroupsCount - 1];
default:
return NULL;
}
}
#define MT32EMU_PRINT_DEBUG \
va_list ap; \
va_start(ap, fmt); \
reportHandler->printDebug(fmt, ap); \
va_end(ap);
#if MT32EMU_DEBUG_SAMPLESTAMPS > 0
static inline void printSamplestamp(ReportHandler *reportHandler, const char *fmt, ...) {
MT32EMU_PRINT_DEBUG
}
#endif
void Synth::printDebug(const char *fmt, ...) {
#if MT32EMU_DEBUG_SAMPLESTAMPS > 0
printSamplestamp(reportHandler, "[%u]", renderedSampleCount);
#endif
MT32EMU_PRINT_DEBUG
}
#undef MT32EMU_PRINT_DEBUG
void Synth::setReverbEnabled(bool newReverbEnabled) {
if (!opened) return;
if (isReverbEnabled() == newReverbEnabled) return;
if (newReverbEnabled) {
bool oldReverbOverridden = reverbOverridden;
reverbOverridden = false;
refreshSystemReverbParameters();
reverbOverridden = oldReverbOverridden;
} else {
if (!extensions.preallocatedReverbMemory) {
reverbModel->close();
}
reverbModel = NULL;
}
}
bool Synth::isReverbEnabled() const {
return reverbModel != NULL;
}
void Synth::setReverbOverridden(bool newReverbOverridden) {
reverbOverridden = newReverbOverridden;
}
bool Synth::isReverbOverridden() const {
return reverbOverridden;
}
void Synth::setReverbCompatibilityMode(bool mt32CompatibleMode) {
if (!opened || (isMT32ReverbCompatibilityMode() == mt32CompatibleMode)) return;
bool oldReverbEnabled = isReverbEnabled();
setReverbEnabled(false);
for (int i = REVERB_MODE_ROOM; i <= REVERB_MODE_TAP_DELAY; i++) {
delete reverbModels[i];
}
initReverbModels(mt32CompatibleMode);
setReverbEnabled(oldReverbEnabled);
setReverbOutputGain(reverbOutputGain);
}
bool Synth::isMT32ReverbCompatibilityMode() const {
return opened && (reverbModels[REVERB_MODE_ROOM]->isMT32Compatible(REVERB_MODE_ROOM));
}
bool Synth::isDefaultReverbMT32Compatible() const {
return opened && controlROMFeatures->defaultReverbMT32Compatible;
}
void Synth::preallocateReverbMemory(bool enabled) {
if (extensions.preallocatedReverbMemory == enabled) return;
extensions.preallocatedReverbMemory = enabled;
if (!opened) return;
for (int i = REVERB_MODE_ROOM; i <= REVERB_MODE_TAP_DELAY; i++) {
if (enabled) {
reverbModels[i]->open();
} else if (reverbModel != reverbModels[i]) {
reverbModels[i]->close();
}
}
}
void Synth::setDACInputMode(DACInputMode mode) {
dacInputMode = mode;
}
DACInputMode Synth::getDACInputMode() const {
return dacInputMode;
}
void Synth::setMIDIDelayMode(MIDIDelayMode mode) {
midiDelayMode = mode;
}
MIDIDelayMode Synth::getMIDIDelayMode() const {
return midiDelayMode;
}
void Synth::setOutputGain(float newOutputGain) {
if (newOutputGain < 0.0f) newOutputGain = -newOutputGain;
outputGain = newOutputGain;
if (analog != NULL) analog->setSynthOutputGain(newOutputGain);
}
float Synth::getOutputGain() const {
return outputGain;
}
void Synth::setReverbOutputGain(float newReverbOutputGain) {
if (newReverbOutputGain < 0.0f) newReverbOutputGain = -newReverbOutputGain;
reverbOutputGain = newReverbOutputGain;
if (analog != NULL) analog->setReverbOutputGain(newReverbOutputGain, isMT32ReverbCompatibilityMode());
}
float Synth::getReverbOutputGain() const {
return reverbOutputGain;
}
void Synth::setPartVolumeOverride(Bit8u partNumber, Bit8u volumeOverride) {
if (opened && partNumber < 9) {
parts[partNumber]->setVolumeOverride(volumeOverride);
}
}
Bit8u Synth::getPartVolumeOverride(Bit8u partNumber) const {
return (!opened || partNumber > 8) ? 255 : parts[partNumber]->getVolumeOverride();
}
void Synth::setReversedStereoEnabled(bool enabled) {
reversedStereoEnabled = enabled;
}
bool Synth::isReversedStereoEnabled() const {
return reversedStereoEnabled;
}
void Synth::setNiceAmpRampEnabled(bool enabled) {
extensions.niceAmpRamp = enabled;
}
bool Synth::isNiceAmpRampEnabled() const {
return extensions.niceAmpRamp;
}
void Synth::setNicePanningEnabled(bool enabled) {
extensions.nicePanning = enabled;
}
bool Synth::isNicePanningEnabled() const {
return extensions.nicePanning;
}
void Synth::setNicePartialMixingEnabled(bool enabled) {
extensions.nicePartialMixing = enabled;
}
bool Synth::isNicePartialMixingEnabled() const {
return extensions.nicePartialMixing;
}
bool Synth::loadControlROM(const ROMImage &controlROMImage) {
File *file = controlROMImage.getFile();
const ROMInfo *controlROMInfo = controlROMImage.getROMInfo();
if ((controlROMInfo == NULL)
|| (controlROMInfo->type != ROMInfo::Control)
|| (controlROMInfo->pairType != ROMInfo::Full)) {
#if MT32EMU_MONITOR_INIT
printDebug("Invalid Control ROM Info provided");
#endif
return false;
}
#if MT32EMU_MONITOR_INIT
printDebug("Found Control ROM: %s, %s", controlROMInfo->shortName, controlROMInfo->description);
#endif
const Bit8u *fileData = file->getData();
memcpy(controlROMData, fileData, CONTROL_ROM_SIZE);
// Control ROM successfully loaded, now check whether it's a known type
controlROMMap = NULL;
controlROMFeatures = NULL;
for (unsigned int i = 0; i < sizeof(ControlROMMaps) / sizeof(ControlROMMaps[0]); i++) {
if (strcmp(controlROMInfo->shortName, ControlROMMaps[i].shortName) == 0) {
controlROMMap = &ControlROMMaps[i];
controlROMFeatures = &controlROMMap->featureSet;
return true;
}
}
#if MT32EMU_MONITOR_INIT
printDebug("Control ROM failed to load");
#endif
return false;
}
bool Synth::loadPCMROM(const ROMImage &pcmROMImage) {
File *file = pcmROMImage.getFile();
const ROMInfo *pcmROMInfo = pcmROMImage.getROMInfo();
if ((pcmROMInfo == NULL)
|| (pcmROMInfo->type != ROMInfo::PCM)
|| (pcmROMInfo->pairType != ROMInfo::Full)) {
return false;
}
#if MT32EMU_MONITOR_INIT
printDebug("Found PCM ROM: %s, %s", pcmROMInfo->shortName, pcmROMInfo->description);
#endif
size_t fileSize = file->getSize();
if (fileSize != (2 * pcmROMSize)) {
#if MT32EMU_MONITOR_INIT
printDebug("PCM ROM file has wrong size (expected %d, got %d)", 2 * pcmROMSize, fileSize);
#endif
return false;
}
const Bit8u *fileData = file->getData();
for (size_t i = 0; i < pcmROMSize; i++) {
Bit8u s = *(fileData++);
Bit8u c = *(fileData++);
int order[16] = {0, 9, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 8};
Bit16s log = 0;
for (int u = 0; u < 16; u++) {
int bit;
if (order[u] < 8) {
bit = (s >> (7 - order[u])) & 0x1;
} else {
bit = (c >> (7 - (order[u] - 8))) & 0x1;
}
log = log | Bit16s(bit << (15 - u));
}
pcmROMData[i] = log;
}
return true;
}
bool Synth::initPCMList(Bit16u mapAddress, Bit16u count) {
ControlROMPCMStruct *tps = reinterpret_cast<ControlROMPCMStruct *>(&controlROMData[mapAddress]);
for (int i = 0; i < count; i++) {
Bit32u rAddr = tps[i].pos * 0x800;
Bit32u rLenExp = (tps[i].len & 0x70) >> 4;
Bit32u rLen = 0x800 << rLenExp;
if (rAddr + rLen > pcmROMSize) {
printDebug("Control ROM error: Wave map entry %d points to invalid PCM address 0x%04X, length 0x%04X", i, rAddr, rLen);
return false;
}
pcmWaves[i].addr = rAddr;
pcmWaves[i].len = rLen;
pcmWaves[i].loop = (tps[i].len & 0x80) != 0;
pcmWaves[i].controlROMPCMStruct = &tps[i];
//int pitch = (tps[i].pitchMSB << 8) | tps[i].pitchLSB;
//bool unaffectedByMasterTune = (tps[i].len & 0x01) == 0;
//printDebug("PCM %d: pos=%d, len=%d, pitch=%d, loop=%s, unaffectedByMasterTune=%s", i, rAddr, rLen, pitch, pcmWaves[i].loop ? "YES" : "NO", unaffectedByMasterTune ? "YES" : "NO");
}
return false;
}
bool Synth::initCompressedTimbre(Bit16u timbreNum, const Bit8u *src, Bit32u srcLen) {
// "Compressed" here means that muted partials aren't present in ROM (except in the case of partial 0 being muted).
// Instead the data from the previous unmuted partial is used.
if (srcLen < sizeof(TimbreParam::CommonParam)) {
return false;
}
TimbreParam *timbre = &mt32ram.timbres[timbreNum].timbre;
timbresMemoryRegion->write(timbreNum, 0, src, sizeof(TimbreParam::CommonParam), true);
unsigned int srcPos = sizeof(TimbreParam::CommonParam);
unsigned int memPos = sizeof(TimbreParam::CommonParam);
for (int t = 0; t < 4; t++) {
if (t != 0 && ((timbre->common.partialMute >> t) & 0x1) == 0x00) {
// This partial is muted - we'll copy the previously copied partial, then
srcPos -= sizeof(TimbreParam::PartialParam);
} else if (srcPos + sizeof(TimbreParam::PartialParam) >= srcLen) {
return false;
}
timbresMemoryRegion->write(timbreNum, memPos, src + srcPos, sizeof(TimbreParam::PartialParam));
srcPos += sizeof(TimbreParam::PartialParam);
memPos += sizeof(TimbreParam::PartialParam);
}
return true;
}
bool Synth::initTimbres(Bit16u mapAddress, Bit16u offset, Bit16u count, Bit16u startTimbre, bool compressed) {
const Bit8u *timbreMap = &controlROMData[mapAddress];
for (Bit16u i = 0; i < count * 2; i += 2) {
Bit16u address = (timbreMap[i + 1] << 8) | timbreMap[i];
if (!compressed && (address + offset + sizeof(TimbreParam) > CONTROL_ROM_SIZE)) {
printDebug("Control ROM error: Timbre map entry 0x%04x for timbre %d points to invalid timbre address 0x%04x", i, startTimbre, address);
return false;
}
address += offset;
if (compressed) {
if (!initCompressedTimbre(startTimbre, &controlROMData[address], CONTROL_ROM_SIZE - address)) {
printDebug("Control ROM error: Timbre map entry 0x%04x for timbre %d points to invalid timbre at 0x%04x", i, startTimbre, address);
return false;
}
} else {
timbresMemoryRegion->write(startTimbre, 0, &controlROMData[address], sizeof(TimbreParam), true);
}
startTimbre++;
}
return true;
}
void Synth::initReverbModels(bool mt32CompatibleMode) {
for (int mode = REVERB_MODE_ROOM; mode <= REVERB_MODE_TAP_DELAY; mode++) {
reverbModels[mode] = BReverbModel::createBReverbModel(ReverbMode(mode), mt32CompatibleMode, getSelectedRendererType());
if (extensions.preallocatedReverbMemory) {
reverbModels[mode]->open();
}
}
}
void Synth::initSoundGroups(char newSoundGroupNames[][9]) {
memcpy(soundGroupIx, &controlROMData[controlROMMap->soundGroupsTable - sizeof(soundGroupIx)], sizeof(soundGroupIx));
const SoundGroup *table = reinterpret_cast<SoundGroup *>(&controlROMData[controlROMMap->soundGroupsTable]);
for (unsigned int i = 0; i < controlROMMap->soundGroupsCount; i++) {
memcpy(&newSoundGroupNames[i][0], table[i].name, sizeof(table[i].name));
}
}
bool Synth::open(const ROMImage &controlROMImage, const ROMImage &pcmROMImage, AnalogOutputMode analogOutputMode) {
return open(controlROMImage, pcmROMImage, DEFAULT_MAX_PARTIALS, analogOutputMode);
}
bool Synth::open(const ROMImage &controlROMImage, const ROMImage &pcmROMImage, Bit32u usePartialCount, AnalogOutputMode analogOutputMode) {
if (opened) {
return false;
}
partialCount = usePartialCount;
abortingPoly = NULL;
extensions.abortingPartIx = 0;
// This is to help detect bugs
memset(&mt32ram, '?', sizeof(mt32ram));
#if MT32EMU_MONITOR_INIT
printDebug("Loading Control ROM");
#endif
if (!loadControlROM(controlROMImage)) {
printDebug("Init Error - Missing or invalid Control ROM image");
reportHandler->onErrorControlROM();
dispose();
return false;
}
initMemoryRegions();
// 512KB PCM ROM for MT-32, etc.
// 1MB PCM ROM for CM-32L, LAPC-I, CM-64, CM-500
// Note that the size below is given in samples (16-bit), not bytes
pcmROMSize = controlROMMap->pcmCount == 256 ? 512 * 1024 : 256 * 1024;
pcmROMData = new Bit16s[pcmROMSize];
#if MT32EMU_MONITOR_INIT
printDebug("Loading PCM ROM");
#endif
if (!loadPCMROM(pcmROMImage)) {
printDebug("Init Error - Missing PCM ROM image");
reportHandler->onErrorPCMROM();
dispose();
return false;
}
#if MT32EMU_MONITOR_INIT
printDebug("Initialising Reverb Models");
#endif
bool mt32CompatibleReverb = controlROMFeatures->defaultReverbMT32Compatible;
#if MT32EMU_MONITOR_INIT
printDebug("Using %s Compatible Reverb Models", mt32CompatibleReverb ? "MT-32" : "CM-32L");
#endif
initReverbModels(mt32CompatibleReverb);
#if MT32EMU_MONITOR_INIT
printDebug("Initialising Timbre Bank A");
#endif
if (!initTimbres(controlROMMap->timbreAMap, controlROMMap->timbreAOffset, 0x40, 0, controlROMMap->timbreACompressed)) {
dispose();
return false;
}
#if MT32EMU_MONITOR_INIT
printDebug("Initialising Timbre Bank B");
#endif
if (!initTimbres(controlROMMap->timbreBMap, controlROMMap->timbreBOffset, 0x40, 64, controlROMMap->timbreBCompressed)) {
dispose();
return false;
}
#if MT32EMU_MONITOR_INIT
printDebug("Initialising Timbre Bank R");
#endif
if (!initTimbres(controlROMMap->timbreRMap, 0, controlROMMap->timbreRCount, 192, true)) {
dispose();
return false;
}
if (controlROMMap->timbreRCount == 30) {
// We must initialise all 64 rhythm timbres to avoid undefined behaviour.
// SEMI-CONFIRMED: Old-gen MT-32 units likely map timbres 30..59 to 0..29.
// Attempts to play rhythm timbres 60..63 exhibit undefined behaviour.
// We want to emulate the wrap around, so merely copy the entire set of standard
// timbres once more. The last 4 dangerous timbres are zeroed out.
memcpy(&mt32ram.timbres[222], &mt32ram.timbres[192], sizeof(*mt32ram.timbres) * 30);
memset(&mt32ram.timbres[252], 0, sizeof(*mt32ram.timbres) * 4);
}
#if MT32EMU_MONITOR_INIT
printDebug("Initialising Timbre Bank M");
#endif
// CM-64 seems to initialise all bytes in this bank to 0.
memset(&mt32ram.timbres[128], 0, sizeof(mt32ram.timbres[128]) * 64);
partialManager = new PartialManager(this, parts);
pcmWaves = new PCMWaveEntry[controlROMMap->pcmCount];
#if MT32EMU_MONITOR_INIT
printDebug("Initialising PCM List");
#endif
initPCMList(controlROMMap->pcmTable, controlROMMap->pcmCount);
#if MT32EMU_MONITOR_INIT
printDebug("Initialising Rhythm Temp");
#endif
memcpy(mt32ram.rhythmTemp, &controlROMData[controlROMMap->rhythmSettings], controlROMMap->rhythmSettingsCount * 4);
#if MT32EMU_MONITOR_INIT
printDebug("Initialising Patches");
#endif
for (Bit8u i = 0; i < 128; i++) {
PatchParam *patch = &mt32ram.patches[i];
patch->timbreGroup = i / 64;
patch->timbreNum = i % 64;
patch->keyShift = 24;
patch->fineTune = 50;
patch->benderRange = 12;
patch->assignMode = 0;
patch->reverbSwitch = 1;
patch->dummy = 0;
}
#if MT32EMU_MONITOR_INIT
printDebug("Initialising System");
#endif
// The MT-32 manual claims that "Standard pitch" is 442Hz.
mt32ram.system.masterTune = 0x4A; // Confirmed on CM-64
mt32ram.system.reverbMode = 0; // Confirmed
mt32ram.system.reverbTime = 5; // Confirmed
mt32ram.system.reverbLevel = 3; // Confirmed
memcpy(mt32ram.system.reserveSettings, &controlROMData[controlROMMap->reserveSettings], 9); // Confirmed
for (Bit8u i = 0; i < 9; i++) {
// This is the default: {1, 2, 3, 4, 5, 6, 7, 8, 9}
// An alternative configuration can be selected by holding "Master Volume"
// and pressing "PART button 1" on the real MT-32's frontpanel.
// The channel assignment is then {0, 1, 2, 3, 4, 5, 6, 7, 9}
mt32ram.system.chanAssign[i] = i + 1;
}
mt32ram.system.masterVol = 100; // Confirmed
bool oldReverbOverridden = reverbOverridden;
reverbOverridden = false;
refreshSystem();
resetMasterTunePitchDelta();
reverbOverridden = oldReverbOverridden;
char(*writableSoundGroupNames)[9] = new char[controlROMMap->soundGroupsCount][9];
soundGroupNames = writableSoundGroupNames;
initSoundGroups(writableSoundGroupNames);
for (int i = 0; i < 9; i++) {
MemParams::PatchTemp *patchTemp = &mt32ram.patchTemp[i];
// Note that except for the rhythm part, these patch fields will be set in setProgram() below anyway.
patchTemp->patch.timbreGroup = 0;
patchTemp->patch.timbreNum = 0;
patchTemp->patch.keyShift = 24;
patchTemp->patch.fineTune = 50;
patchTemp->patch.benderRange = 12;
patchTemp->patch.assignMode = 0;
patchTemp->patch.reverbSwitch = 1;
patchTemp->patch.dummy = 0;
patchTemp->outputLevel = 80;
patchTemp->panpot = controlROMData[controlROMMap->panSettings + i];
memset(patchTemp->dummyv, 0, sizeof(patchTemp->dummyv));
patchTemp->dummyv[1] = 127;
if (i < 8) {
parts[i] = new Part(this, i);
parts[i]->setProgram(controlROMData[controlROMMap->programSettings + i]);
} else {
parts[i] = new RhythmPart(this, i);
}
}
// For resetting mt32 mid-execution
mt32default = mt32ram;
midiQueue = new MidiEventQueue(extensions.midiEventQueueSize, extensions.midiEventQueueSysexStorageBufferSize);
analog = Analog::createAnalog(analogOutputMode, controlROMFeatures->oldMT32AnalogLPF, getSelectedRendererType());
#if MT32EMU_MONITOR_INIT
static const char *ANALOG_OUTPUT_MODES[] = { "Digital only", "Coarse", "Accurate", "Oversampled2x" };
printDebug("Using Analog output mode %s", ANALOG_OUTPUT_MODES[analogOutputMode]);
#endif
setOutputGain(outputGain);
setReverbOutputGain(reverbOutputGain);
switch (getSelectedRendererType()) {
case RendererType_BIT16S:
renderer = new RendererImpl<IntSample>(*this);
#if MT32EMU_MONITOR_INIT
printDebug("Using integer 16-bit samples in renderer and wave generator");
#endif
break;
case RendererType_FLOAT:
renderer = new RendererImpl<FloatSample>(*this);
#if MT32EMU_MONITOR_INIT
printDebug("Using float 32-bit samples in renderer and wave generator");
#endif
break;
default:
printDebug("Synth: Unknown renderer type %i\n", getSelectedRendererType());
dispose();
return false;
}
extensions.display = new Display(*this);
extensions.oldMT32DisplayFeatures = controlROMFeatures->oldMT32DisplayFeatures;
opened = true;
activated = false;
#if MT32EMU_MONITOR_INIT
printDebug("*** Initialisation complete ***");
#endif
return true;
}
void Synth::dispose() {
opened = false;
delete extensions.display;
extensions.display = NULL;
delete midiQueue;
midiQueue = NULL;
delete renderer;
renderer = NULL;
delete analog;
analog = NULL;
delete partialManager;
partialManager = NULL;
for (int i = 0; i < 9; i++) {
delete parts[i];
parts[i] = NULL;
}
delete[] soundGroupNames;
soundGroupNames = NULL;
delete[] pcmWaves;
pcmWaves = NULL;
delete[] pcmROMData;
pcmROMData = NULL;
deleteMemoryRegions();
for (int i = REVERB_MODE_ROOM; i <= REVERB_MODE_TAP_DELAY; i++) {
delete reverbModels[i];
reverbModels[i] = NULL;
}
reverbModel = NULL;
controlROMFeatures = NULL;
controlROMMap = NULL;
}
void Synth::close() {
if (opened) {
dispose();
}
}
bool Synth::isOpen() const {
return opened;
}
void Synth::flushMIDIQueue() {
if (midiQueue == NULL) return;
for (;;) {
const volatile MidiEventQueue::MidiEvent *midiEvent = midiQueue->peekMidiEvent();
if (midiEvent == NULL) break;
if (midiEvent->sysexData == NULL) {
playMsgNow(midiEvent->shortMessageData);
} else {
playSysexNow(midiEvent->sysexData, midiEvent->sysexLength);
}
midiQueue->dropMidiEvent();
}
lastReceivedMIDIEventTimestamp = renderedSampleCount;
}
Bit32u Synth::setMIDIEventQueueSize(Bit32u useSize) {
static const Bit32u MAX_QUEUE_SIZE = (1 << 24); // This results in about 256 Mb - much greater than any reasonable value
if (extensions.midiEventQueueSize == useSize) return useSize;
// Find a power of 2 that is >= useSize
Bit32u binarySize = 1;
if (useSize < MAX_QUEUE_SIZE) {
// Using simple linear search as this isn't time critical
while (binarySize < useSize) binarySize <<= 1;
} else {
binarySize = MAX_QUEUE_SIZE;
}
extensions.midiEventQueueSize = binarySize;
if (midiQueue != NULL) {
flushMIDIQueue();
delete midiQueue;
midiQueue = new MidiEventQueue(binarySize, extensions.midiEventQueueSysexStorageBufferSize);
}
return binarySize;
}
void Synth::configureMIDIEventQueueSysexStorage(Bit32u storageBufferSize) {
if (extensions.midiEventQueueSysexStorageBufferSize == storageBufferSize) return;
extensions.midiEventQueueSysexStorageBufferSize = storageBufferSize;
if (midiQueue != NULL) {
flushMIDIQueue();
delete midiQueue;
midiQueue = new MidiEventQueue(extensions.midiEventQueueSize, storageBufferSize);
}
}
Bit32u Synth::getShortMessageLength(Bit32u msg) {
if ((msg & 0xF0) == 0xF0) {
switch (msg & 0xFF) {
case 0xF1:
case 0xF3:
return 2;
case 0xF2:
return 3;
default:
return 1;
}
}
// NOTE: This calculation isn't quite correct
// as it doesn't consider the running status byte
return ((msg & 0xE0) == 0xC0) ? 2 : 3;
}
Bit32u Synth::addMIDIInterfaceDelay(Bit32u len, Bit32u timestamp) {
Bit32u transferTime = Bit32u(double(len) * MIDI_DATA_TRANSFER_RATE);
// Dealing with wrapping
if (Bit32s(timestamp - lastReceivedMIDIEventTimestamp) < 0) {
timestamp = lastReceivedMIDIEventTimestamp;
}
timestamp += transferTime;
lastReceivedMIDIEventTimestamp = timestamp;
return timestamp;
}
Bit32u Synth::getInternalRenderedSampleCount() const {
return renderedSampleCount;
}
bool Synth::playMsg(Bit32u msg) {
return playMsg(msg, renderedSampleCount);
}
bool Synth::playMsg(Bit32u msg, Bit32u timestamp) {
if ((msg & 0xF8) == 0xF8) {
reportHandler->onMIDISystemRealtime(Bit8u(msg & 0xFF));
return true;
}
if (midiQueue == NULL) return false;
if (midiDelayMode != MIDIDelayMode_IMMEDIATE) {
timestamp = addMIDIInterfaceDelay(getShortMessageLength(msg), timestamp);
}
if (!activated) activated = true;
do {
if (midiQueue->pushShortMessage(msg, timestamp)) return true;
} while (reportHandler->onMIDIQueueOverflow());
return false;
}
bool Synth::playSysex(const Bit8u *sysex, Bit32u len) {
return playSysex(sysex, len, renderedSampleCount);
}
bool Synth::playSysex(const Bit8u *sysex, Bit32u len, Bit32u timestamp) {
if (midiQueue == NULL) return false;
if (midiDelayMode == MIDIDelayMode_DELAY_ALL) {
timestamp = addMIDIInterfaceDelay(len, timestamp);
}
if (!activated) activated = true;
do {
if (midiQueue->pushSysex(sysex, len, timestamp)) return true;
} while (reportHandler->onMIDIQueueOverflow());
return false;
}
void Synth::playMsgNow(Bit32u msg) {
if (!opened) return;
// NOTE: Active sense IS implemented in real hardware. However, realtime processing is clearly out of the library scope.
// It is assumed that realtime consumers of the library respond to these MIDI events as appropriate.
Bit8u code = Bit8u((msg & 0x0000F0) >> 4);
Bit8u chan = Bit8u(msg & 0x00000F);
Bit8u note = Bit8u((msg & 0x007F00) >> 8);
Bit8u velocity = Bit8u((msg & 0x7F0000) >> 16);
//printDebug("Playing chan %d, code 0x%01x note: 0x%02x", chan, code, note);
Bit8u *chanParts = extensions.chantable[chan];
if (*chanParts > 8) {
#if MT32EMU_MONITOR_MIDI > 0
printDebug("Play msg on unreg chan %d (%d): code=0x%01x, vel=%d", chan, *chanParts, code, velocity);
#endif
return;
}
for (Bit32u i = extensions.abortingPartIx; i <= 8; i++) {
const Bit32u partNum = chanParts[i];
if (partNum > 8) break;
playMsgOnPart(partNum, code, note, velocity);
if (isAbortingPoly()) {
extensions.abortingPartIx = i;
break;
} else if (extensions.abortingPartIx) {
extensions.abortingPartIx = 0;
}
}
}
void Synth::playMsgOnPart(Bit8u part, Bit8u code, Bit8u note, Bit8u velocity) {
if (!opened) return;
Bit32u bend;
if (!activated) activated = true;
//printDebug("Synth::playMsgOnPart(%02x, %02x, %02x, %02x)", part, code, note, velocity);
switch (code) {
case 0x8:
//printDebug("Note OFF - Part %d", part);
// The MT-32 ignores velocity for note off
parts[part]->noteOff(note);
break;
case 0x9:
//printDebug("Note ON - Part %d, Note %d Vel %d", part, note, velocity);
if (velocity == 0) {
// MIDI defines note-on with velocity 0 as being the same as note-off with velocity 40
parts[part]->noteOff(note);
} else if (parts[part]->getVolumeOverride() > 0) {
parts[part]->noteOn(note, velocity);
}
break;
case 0xB: // Control change
switch (note) {
case 0x01: // Modulation
//printDebug("Modulation: %d", velocity);
parts[part]->setModulation(velocity);
break;
case 0x06:
parts[part]->setDataEntryMSB(velocity);
break;
case 0x07: // Set volume
//printDebug("Volume set: %d", velocity);
parts[part]->setVolume(velocity);
break;
case 0x0A: // Pan
//printDebug("Pan set: %d", velocity);
parts[part]->setPan(velocity);
break;
case 0x0B:
//printDebug("Expression set: %d", velocity);
parts[part]->setExpression(velocity);
break;
case 0x40: // Hold (sustain) pedal
//printDebug("Hold pedal set: %d", velocity);
parts[part]->setHoldPedal(velocity >= 64);
break;
case 0x62:
case 0x63:
parts[part]->setNRPN();
break;
case 0x64:
parts[part]->setRPNLSB(velocity);
break;
case 0x65:
parts[part]->setRPNMSB(velocity);
break;
case 0x79: // Reset all controllers
//printDebug("Reset all controllers");
parts[part]->resetAllControllers();
break;
case 0x7B: // All notes off
//printDebug("All notes off");
parts[part]->allNotesOff();
break;
case 0x7C:
case 0x7D:
case 0x7E:
case 0x7F:
// CONFIRMED:Mok: A real LAPC-I responds to these controllers as follows:
parts[part]->setHoldPedal(false);
parts[part]->allNotesOff();
break;
default:
#if MT32EMU_MONITOR_MIDI > 0
printDebug("Unknown MIDI Control code: 0x%02x - vel 0x%02x", note, velocity);
#endif
return;
}
extensions.display->midiMessagePlayed();
break;
case 0xC: // Program change
//printDebug("Program change %01x", note);
parts[part]->setProgram(note);
if (part < 8) {
extensions.display->midiMessagePlayed();
extensions.display->programChanged(part);
}
break;
case 0xE: // Pitch bender
bend = (velocity << 7) | (note);
//printDebug("Pitch bender %02x", bend);
parts[part]->setBend(bend);
extensions.display->midiMessagePlayed();
break;
default:
#if MT32EMU_MONITOR_MIDI > 0
printDebug("Unknown Midi code: 0x%01x - %02x - %02x", code, note, velocity);
#endif
return;
}
reportHandler->onMIDIMessagePlayed();
}
void Synth::playSysexNow(const Bit8u *sysex, Bit32u len) {
if (len < 2) {
printDebug("playSysex: Message is too short for sysex (%d bytes)", len);
}
if (sysex[0] != 0xF0) {
printDebug("playSysex: Message lacks start-of-sysex (0xF0)");
return;
}
// Due to some programs (e.g. Java) sending buffers with junk at the end, we have to go through and find the end marker rather than relying on len.
Bit32u endPos;
for (endPos = 1; endPos < len; endPos++) {
if (sysex[endPos] == 0xF7) {
break;
}
}
if (endPos == len) {
printDebug("playSysex: Message lacks end-of-sysex (0xf7)");
return;
}
playSysexWithoutFraming(sysex + 1, endPos - 1);
}
void Synth::playSysexWithoutFraming(const Bit8u *sysex, Bit32u len) {
if (len < 4) {
printDebug("playSysexWithoutFraming: Message is too short (%d bytes)!", len);
return;
}
if (sysex[0] != SYSEX_MANUFACTURER_ROLAND) {
printDebug("playSysexWithoutFraming: Header not intended for this device manufacturer: %02x %02x %02x %02x", int(sysex[0]), int(sysex[1]), int(sysex[2]), int(sysex[3]));
return;
}
if (sysex[2] == SYSEX_MDL_D50) {
printDebug("playSysexWithoutFraming: Header is intended for model D-50 (not yet supported): %02x %02x %02x %02x", int(sysex[0]), int(sysex[1]), int(sysex[2]), int(sysex[3]));
return;
} else if (sysex[2] != SYSEX_MDL_MT32) {
printDebug("playSysexWithoutFraming: Header not intended for model MT-32: %02x %02x %02x %02x", int(sysex[0]), int(sysex[1]), int(sysex[2]), int(sysex[3]));
return;
}
playSysexWithoutHeader(sysex[1], sysex[3], sysex + 4, len - 4);
}
void Synth::playSysexWithoutHeader(Bit8u device, Bit8u command, const Bit8u *sysex, Bit32u len) {
if (device > 0x10) {
// We have device ID 0x10 (default, but changeable, on real MT-32), < 0x10 is for channels
printDebug("playSysexWithoutHeader: Message is not intended for this device ID (provided: %02x, expected: 0x10 or channel)", int(device));
return;
}
// All models process the checksum before anything else and ignore messages lacking the checksum, or containing the checksum only.
if (len < 2) {
printDebug("playSysexWithoutHeader: Message is too short (%d bytes)!", len);
return;
}
Bit8u checksum = calcSysexChecksum(sysex, len - 1);
if (checksum != sysex[len - 1]) {
printDebug("playSysexWithoutHeader: Message checksum is incorrect (provided: %02x, expected: %02x)!", sysex[len - 1], checksum);
if (opened) extensions.display->checksumErrorOccurred();
return;
}
len -= 1; // Exclude checksum
if (command == SYSEX_CMD_EOD) {
#if MT32EMU_MONITOR_SYSEX > 0
printDebug("playSysexWithoutHeader: Ignored unsupported command %02x", command);
#endif
return;
}
switch (command) {
case SYSEX_CMD_WSD:
#if MT32EMU_MONITOR_SYSEX > 0
printDebug("playSysexWithoutHeader: Ignored unsupported command %02x", command);
#endif
break;
case SYSEX_CMD_DAT:
/* Outcommented until we (ever) actually implement handshake communication
if (hasActivePartials()) {
printDebug("playSysexWithoutHeader: Got SYSEX_CMD_DAT but partials are active - ignoring");
// FIXME: We should send SYSEX_CMD_RJC in this case
break;
}
*/
// Fall-through
case SYSEX_CMD_DT1:
writeSysex(device, sysex, len);
break;
case SYSEX_CMD_RQD:
if (hasActivePartials()) {
printDebug("playSysexWithoutHeader: Got SYSEX_CMD_RQD but partials are active - ignoring");
// FIXME: We should send SYSEX_CMD_RJC in this case
break;
}
// Fall-through
case SYSEX_CMD_RQ1:
readSysex(device, sysex, len);
break;
default:
printDebug("playSysexWithoutHeader: Unsupported command %02x", command);
return;
}
}
void Synth::readSysex(Bit8u /*device*/, const Bit8u * /*sysex*/, Bit32u /*len*/) const {
// NYI
}
void Synth::writeSysex(Bit8u device, const Bit8u *sysex, Bit32u len) {
if (!opened || len < 1) return;
// This is checked early in the real devices (before any sysex length checks or further processing)
if (sysex[0] == 0x7F) {
if (!isDisplayOldMT32Compatible()) extensions.display->midiMessagePlayed();
reset();
return;
}
extensions.display->midiMessagePlayed();
reportHandler->onMIDIMessagePlayed();
if (len < 3) {
// A short message of just 1 or 2 bytes may be written to the display area yet it may cause a user-visible effect,
// similarly to the reset area.
if (sysex[0] == 0x20) {
extensions.display->displayControlMessageReceived(sysex, len);
return;
}
printDebug("writeSysex: Message is too short (%d bytes)!", len);
return;
}
Bit32u addr = (sysex[0] << 16) | (sysex[1] << 8) | (sysex[2]);
addr = MT32EMU_MEMADDR(addr);
sysex += 3;
len -= 3;
//printDebug("Sysex addr: 0x%06x", MT32EMU_SYSEXMEMADDR(addr));
// NOTE: Please keep both lower and upper bounds in each check, for ease of reading
// Process channel-specific sysex by converting it to device-global
if (device < 0x10) {
#if MT32EMU_MONITOR_SYSEX > 0
printDebug("WRITE-CHANNEL: Channel %d temp area 0x%06x", device, MT32EMU_SYSEXMEMADDR(addr));
#endif
if (/*addr >= MT32EMU_MEMADDR(0x000000) && */addr < MT32EMU_MEMADDR(0x010000)) {
addr += MT32EMU_MEMADDR(0x030000);
Bit8u *chanParts = extensions.chantable[device];
if (*chanParts > 8) {
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" (Channel not mapped to a part... 0 offset)");
#endif
} else {
for (Bit32u partIx = 0; partIx <= 8; partIx++) {
if (chanParts[partIx] > 8) break;
int offset;
if (chanParts[partIx] == 8) {
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" (Channel mapped to rhythm... 0 offset)");
#endif
offset = 0;
} else {
offset = chanParts[partIx] * sizeof(MemParams::PatchTemp);
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" (Setting extra offset to %d)", offset);
#endif
}
writeSysexGlobal(addr + offset, sysex, len);
}
return;
}
} else if (/*addr >= MT32EMU_MEMADDR(0x010000) && */ addr < MT32EMU_MEMADDR(0x020000)) {
addr += MT32EMU_MEMADDR(0x030110) - MT32EMU_MEMADDR(0x010000);
} else if (/*addr >= MT32EMU_MEMADDR(0x020000) && */ addr < MT32EMU_MEMADDR(0x030000)) {
addr += MT32EMU_MEMADDR(0x040000) - MT32EMU_MEMADDR(0x020000);
Bit8u *chanParts = extensions.chantable[device];
if (*chanParts > 8) {
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" (Channel not mapped to a part... 0 offset)");
#endif
} else {
for (Bit32u partIx = 0; partIx <= 8; partIx++) {
if (chanParts[partIx] > 8) break;
int offset;
if (chanParts[partIx] == 8) {
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" (Channel mapped to rhythm... 0 offset)");
#endif
offset = 0;
} else {
offset = chanParts[partIx] * sizeof(TimbreParam);
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" (Setting extra offset to %d)", offset);
#endif
}
writeSysexGlobal(addr + offset, sysex, len);
}
return;
}
} else {
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" Invalid channel");
#endif
return;
}
}
writeSysexGlobal(addr, sysex, len);
}
// Process device-global sysex (possibly converted from channel-specific sysex above)
void Synth::writeSysexGlobal(Bit32u addr, const Bit8u *sysex, Bit32u len) {
for (;;) {
// Find the appropriate memory region
const MemoryRegion *region = findMemoryRegion(addr);
if (region == NULL) {
printDebug("Sysex write to unrecognised address %06x, len %d", MT32EMU_SYSEXMEMADDR(addr), len);
// FIXME: Real devices may respond differently to a long SysEx that covers adjacent regions.
break;
}
writeMemoryRegion(region, addr, region->getClampedLen(addr, len), sysex);
Bit32u next = region->next(addr, len);
if (next == 0) {
break;
}
addr += next;
sysex += next;
len -= next;
}
}
void Synth::readMemory(Bit32u addr, Bit32u len, Bit8u *data) {
if (!opened) return;
const MemoryRegion *region = findMemoryRegion(addr);
if (region != NULL) {
readMemoryRegion(region, addr, len, data);
}
}
void Synth::initMemoryRegions() {
// Timbre max tables are slightly more complicated than the others, which are used directly from the ROM.
// The ROM (sensibly) just has maximums for TimbreParam.commonParam followed by just one TimbreParam.partialParam,
// so we produce a table with all partialParams filled out, as well as padding for PaddedTimbre, for quick lookup.
paddedTimbreMaxTable = new Bit8u[sizeof(MemParams::PaddedTimbre)];
memcpy(&paddedTimbreMaxTable[0], &controlROMData[controlROMMap->timbreMaxTable], sizeof(TimbreParam::CommonParam) + sizeof(TimbreParam::PartialParam)); // commonParam and one partialParam
int pos = sizeof(TimbreParam::CommonParam) + sizeof(TimbreParam::PartialParam);
for (int i = 0; i < 3; i++) {
memcpy(&paddedTimbreMaxTable[pos], &controlROMData[controlROMMap->timbreMaxTable + sizeof(TimbreParam::CommonParam)], sizeof(TimbreParam::PartialParam));
pos += sizeof(TimbreParam::PartialParam);
}
memset(&paddedTimbreMaxTable[pos], 0, 10); // Padding
patchTempMemoryRegion = new PatchTempMemoryRegion(this, reinterpret_cast<Bit8u *>(&mt32ram.patchTemp[0]), &controlROMData[controlROMMap->patchMaxTable]);
rhythmTempMemoryRegion = new RhythmTempMemoryRegion(this, reinterpret_cast<Bit8u *>(&mt32ram.rhythmTemp[0]), &controlROMData[controlROMMap->rhythmMaxTable]);
timbreTempMemoryRegion = new TimbreTempMemoryRegion(this, reinterpret_cast<Bit8u *>(&mt32ram.timbreTemp[0]), paddedTimbreMaxTable);
patchesMemoryRegion = new PatchesMemoryRegion(this, reinterpret_cast<Bit8u *>(&mt32ram.patches[0]), &controlROMData[controlROMMap->patchMaxTable]);
timbresMemoryRegion = new TimbresMemoryRegion(this, reinterpret_cast<Bit8u *>(&mt32ram.timbres[0]), paddedTimbreMaxTable);
systemMemoryRegion = new SystemMemoryRegion(this, reinterpret_cast<Bit8u *>(&mt32ram.system), &controlROMData[controlROMMap->systemMaxTable]);
displayMemoryRegion = new DisplayMemoryRegion(this);
resetMemoryRegion = new ResetMemoryRegion(this);
}
void Synth::deleteMemoryRegions() {
delete patchTempMemoryRegion;
patchTempMemoryRegion = NULL;
delete rhythmTempMemoryRegion;
rhythmTempMemoryRegion = NULL;
delete timbreTempMemoryRegion;
timbreTempMemoryRegion = NULL;
delete patchesMemoryRegion;
patchesMemoryRegion = NULL;
delete timbresMemoryRegion;
timbresMemoryRegion = NULL;
delete systemMemoryRegion;
systemMemoryRegion = NULL;
delete displayMemoryRegion;
displayMemoryRegion = NULL;
delete resetMemoryRegion;
resetMemoryRegion = NULL;
delete[] paddedTimbreMaxTable;
paddedTimbreMaxTable = NULL;
}
MemoryRegion *Synth::findMemoryRegion(Bit32u addr) {
MemoryRegion *regions[] = {
patchTempMemoryRegion,
rhythmTempMemoryRegion,
timbreTempMemoryRegion,
patchesMemoryRegion,
timbresMemoryRegion,
systemMemoryRegion,
displayMemoryRegion,
resetMemoryRegion,
NULL
};
for (int pos = 0; regions[pos] != NULL; pos++) {
if (regions[pos]->contains(addr)) {
return regions[pos];
}
}
return NULL;
}
void Synth::readMemoryRegion(const MemoryRegion *region, Bit32u addr, Bit32u len, Bit8u *data) {
unsigned int first = region->firstTouched(addr);
//unsigned int last = region->lastTouched(addr, len);
unsigned int off = region->firstTouchedOffset(addr);
len = region->getClampedLen(addr, len);
unsigned int m;
if (region->isReadable()) {
region->read(first, off, data, len);
} else {
// FIXME: We might want to do these properly in future
for (m = 0; m < len; m += 2) {
data[m] = 0xff;
if (m + 1 < len) {
data[m+1] = Bit8u(region->type);
}
}
}
}
void Synth::writeMemoryRegion(const MemoryRegion *region, Bit32u addr, Bit32u len, const Bit8u *data) {
unsigned int first = region->firstTouched(addr);
unsigned int last = region->lastTouched(addr, len);
unsigned int off = region->firstTouchedOffset(addr);
switch (region->type) {
case MR_PatchTemp:
region->write(first, off, data, len);
//printDebug("Patch temp: Patch %d, offset %x, len %d", off/16, off % 16, len);
for (unsigned int i = first; i <= last; i++) {
int absTimbreNum = mt32ram.patchTemp[i].patch.timbreGroup * 64 + mt32ram.patchTemp[i].patch.timbreNum;
char timbreName[11];
memcpy(timbreName, mt32ram.timbres[absTimbreNum].timbre.common.name, 10);
timbreName[10] = 0;
#if MT32EMU_MONITOR_SYSEX > 0
printDebug("WRITE-PARTPATCH (%d-%d@%d..%d): %d; timbre=%d (%s), outlevel=%d", first, last, off, off + len, i, absTimbreNum, timbreName, mt32ram.patchTemp[i].outputLevel);
#endif
if (parts[i] != NULL) {
if (i != 8) {
// Note: Confirmed on CM-64 that we definitely *should* update the timbre here,
// but only in the case that the sysex actually writes to those values
if (i == first && off > 2) {
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" (Not updating timbre, since those values weren't touched)");
#endif
} else {
parts[i]->setTimbre(&mt32ram.timbres[parts[i]->getAbsTimbreNum()].timbre);
}
}
parts[i]->refresh();
}
}
break;
case MR_RhythmTemp:
region->write(first, off, data, len);
for (unsigned int i = first; i <= last; i++) {
int timbreNum = mt32ram.rhythmTemp[i].timbre;
char timbreName[11];
if (timbreNum < 94) {
memcpy(timbreName, mt32ram.timbres[128 + timbreNum].timbre.common.name, 10);
timbreName[10] = 0;
} else {
strcpy(timbreName, "[None]");
}
#if MT32EMU_MONITOR_SYSEX > 0
printDebug("WRITE-RHYTHM (%d-%d@%d..%d): %d; level=%02x, panpot=%02x, reverb=%02x, timbre=%d (%s)", first, last, off, off + len, i, mt32ram.rhythmTemp[i].outputLevel, mt32ram.rhythmTemp[i].panpot, mt32ram.rhythmTemp[i].reverbSwitch, mt32ram.rhythmTemp[i].timbre, timbreName);
#endif
}
if (parts[8] != NULL) {
parts[8]->refresh();
}
break;
case MR_TimbreTemp:
region->write(first, off, data, len);
for (unsigned int i = first; i <= last; i++) {
char instrumentName[11];
memcpy(instrumentName, mt32ram.timbreTemp[i].common.name, 10);
instrumentName[10] = 0;
#if MT32EMU_MONITOR_SYSEX > 0
printDebug("WRITE-PARTTIMBRE (%d-%d@%d..%d): timbre=%d (%s)", first, last, off, off + len, i, instrumentName);
#endif
if (parts[i] != NULL) {
parts[i]->refresh();
}
}
break;
case MR_Patches:
region->write(first, off, data, len);
#if MT32EMU_MONITOR_SYSEX > 0
for (unsigned int i = first; i <= last; i++) {
PatchParam *patch = &mt32ram.patches[i];
int patchAbsTimbreNum = patch->timbreGroup * 64 + patch->timbreNum;
char instrumentName[11];
memcpy(instrumentName, mt32ram.timbres[patchAbsTimbreNum].timbre.common.name, 10);
instrumentName[10] = 0;
Bit8u *n = reinterpret_cast<Bit8u *>(patch);
printDebug("WRITE-PATCH (%d-%d@%d..%d): %d; timbre=%d (%s) %02X%02X%02X%02X%02X%02X%02X%02X", first, last, off, off + len, i, patchAbsTimbreNum, instrumentName, n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7]);
}
#endif
break;
case MR_Timbres:
// Timbres
first += 128;
last += 128;
region->write(first, off, data, len);
for (unsigned int i = first; i <= last; i++) {
#if MT32EMU_MONITOR_TIMBRES >= 1
TimbreParam *timbre = &mt32ram.timbres[i].timbre;
char instrumentName[11];
memcpy(instrumentName, timbre->common.name, 10);
instrumentName[10] = 0;
printDebug("WRITE-TIMBRE (%d-%d@%d..%d): %d; name=\"%s\"", first, last, off, off + len, i, instrumentName);
#if MT32EMU_MONITOR_TIMBRES >= 2
#define DT(x) printDebug(" " #x ": %d", timbre->x)
DT(common.partialStructure12);
DT(common.partialStructure34);
DT(common.partialMute);
DT(common.noSustain);
#define DTP(x) \
DT(partial[x].wg.pitchCoarse); \
DT(partial[x].wg.pitchFine); \
DT(partial[x].wg.pitchKeyfollow); \
DT(partial[x].wg.pitchBenderEnabled); \
DT(partial[x].wg.waveform); \
DT(partial[x].wg.pcmWave); \
DT(partial[x].wg.pulseWidth); \
DT(partial[x].wg.pulseWidthVeloSensitivity); \
DT(partial[x].pitchEnv.depth); \
DT(partial[x].pitchEnv.veloSensitivity); \
DT(partial[x].pitchEnv.timeKeyfollow); \
DT(partial[x].pitchEnv.time[0]); \
DT(partial[x].pitchEnv.time[1]); \
DT(partial[x].pitchEnv.time[2]); \
DT(partial[x].pitchEnv.time[3]); \
DT(partial[x].pitchEnv.level[0]); \
DT(partial[x].pitchEnv.level[1]); \
DT(partial[x].pitchEnv.level[2]); \
DT(partial[x].pitchEnv.level[3]); \
DT(partial[x].pitchEnv.level[4]); \
DT(partial[x].pitchLFO.rate); \
DT(partial[x].pitchLFO.depth); \
DT(partial[x].pitchLFO.modSensitivity); \
DT(partial[x].tvf.cutoff); \
DT(partial[x].tvf.resonance); \
DT(partial[x].tvf.keyfollow); \
DT(partial[x].tvf.biasPoint); \
DT(partial[x].tvf.biasLevel); \
DT(partial[x].tvf.envDepth); \
DT(partial[x].tvf.envVeloSensitivity); \
DT(partial[x].tvf.envDepthKeyfollow); \
DT(partial[x].tvf.envTimeKeyfollow); \
DT(partial[x].tvf.envTime[0]); \
DT(partial[x].tvf.envTime[1]); \
DT(partial[x].tvf.envTime[2]); \
DT(partial[x].tvf.envTime[3]); \
DT(partial[x].tvf.envTime[4]); \
DT(partial[x].tvf.envLevel[0]); \
DT(partial[x].tvf.envLevel[1]); \
DT(partial[x].tvf.envLevel[2]); \
DT(partial[x].tvf.envLevel[3]); \
DT(partial[x].tva.level); \
DT(partial[x].tva.veloSensitivity); \
DT(partial[x].tva.biasPoint1); \
DT(partial[x].tva.biasLevel1); \
DT(partial[x].tva.biasPoint2); \
DT(partial[x].tva.biasLevel2); \
DT(partial[x].tva.envTimeKeyfollow); \
DT(partial[x].tva.envTimeVeloSensitivity); \
DT(partial[x].tva.envTime[0]); \
DT(partial[x].tva.envTime[1]); \
DT(partial[x].tva.envTime[2]); \
DT(partial[x].tva.envTime[3]); \
DT(partial[x].tva.envTime[4]); \
DT(partial[x].tva.envLevel[0]); \
DT(partial[x].tva.envLevel[1]); \
DT(partial[x].tva.envLevel[2]); \
DT(partial[x].tva.envLevel[3]);
DTP(0);
DTP(1);
DTP(2);
DTP(3);
#undef DTP
#undef DT
#endif
#endif
// FIXME:KG: Not sure if the stuff below should be done (for rhythm and/or parts)...
// Does the real MT-32 automatically do this?
for (unsigned int part = 0; part < 9; part++) {
if (parts[part] != NULL) {
parts[part]->refreshTimbre(i);
}
}
}
break;
case MR_System:
region->write(0, off, data, len);
reportHandler->onDeviceReconfig();
// FIXME: We haven't properly confirmed any of this behaviour
// In particular, we tend to reset things such as reverb even if the write contained
// the same parameters as were already set, which may be wrong.
// On the other hand, the real thing could be resetting things even when they aren't touched
// by the write at all.
#if MT32EMU_MONITOR_SYSEX > 0
printDebug("WRITE-SYSTEM:");
#endif
if (off <= SYSTEM_MASTER_TUNE_OFF && off + len > SYSTEM_MASTER_TUNE_OFF) {
refreshSystemMasterTune();
}
if (off <= SYSTEM_REVERB_LEVEL_OFF && off + len > SYSTEM_REVERB_MODE_OFF) {
refreshSystemReverbParameters();
}
if (off <= SYSTEM_RESERVE_SETTINGS_END_OFF && off + len > SYSTEM_RESERVE_SETTINGS_START_OFF) {
refreshSystemReserveSettings();
}
if (off <= SYSTEM_CHAN_ASSIGN_END_OFF && off + len > SYSTEM_CHAN_ASSIGN_START_OFF) {
int firstPart = off - SYSTEM_CHAN_ASSIGN_START_OFF;
if(firstPart < 0)
firstPart = 0;
int lastPart = off + len - SYSTEM_CHAN_ASSIGN_START_OFF;
if(lastPart > 8)
lastPart = 8;
refreshSystemChanAssign(Bit8u(firstPart), Bit8u(lastPart));
}
if (off <= SYSTEM_MASTER_VOL_OFF && off + len > SYSTEM_MASTER_VOL_OFF) {
refreshSystemMasterVol();
}
break;
case MR_Display:
if (len > Display::LCD_TEXT_SIZE) len = Display::LCD_TEXT_SIZE;
if (!extensions.display->customDisplayMessageReceived(data, off, len)) break;
// Holds zero-terminated string of the maximum length.
char buf[Display::LCD_TEXT_SIZE + 1];
memcpy(&buf, &data[0], len);
buf[len] = 0;
#if MT32EMU_MONITOR_SYSEX > 0
printDebug("WRITE-LCD: %s", buf);
#endif
reportHandler->showLCDMessage(buf);
break;
case MR_Reset:
reset();
break;
default:
break;
}
}
void Synth::refreshSystemMasterTune() {
// 171 is ~half a semitone.
extensions.masterTunePitchDelta = ((mt32ram.system.masterTune - 64) * 171) >> 6; // PORTABILITY NOTE: Assumes arithmetic shift.
#if MT32EMU_MONITOR_SYSEX > 0
//FIXME:KG: This is just an educated guess.
// The LAPC-I documentation claims a range of 427.5Hz-452.6Hz (similar to what we have here)
// The MT-32 documentation claims a range of 432.1Hz-457.6Hz
float masterTune = 440.0f * EXP2F((mt32ram.system.masterTune - 64.0f) / (128.0f * 12.0f));
printDebug(" Master Tune: %f", masterTune);
#endif
}
void Synth::refreshSystemReverbParameters() {
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" Reverb: mode=%d, time=%d, level=%d", mt32ram.system.reverbMode, mt32ram.system.reverbTime, mt32ram.system.reverbLevel);
#endif
if (reverbOverridden) {
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" (Reverb overridden - ignoring)");
#endif
return;
}
reportHandler->onNewReverbMode(mt32ram.system.reverbMode);
reportHandler->onNewReverbTime(mt32ram.system.reverbTime);
reportHandler->onNewReverbLevel(mt32ram.system.reverbLevel);
BReverbModel *oldReverbModel = reverbModel;
if (mt32ram.system.reverbTime == 0 && mt32ram.system.reverbLevel == 0) {
// Setting both time and level to 0 effectively disables wet reverb output on real devices.
// Take a shortcut in this case to reduce CPU load.
reverbModel = NULL;
} else {
reverbModel = reverbModels[mt32ram.system.reverbMode];
}
if (reverbModel != oldReverbModel) {
if (extensions.preallocatedReverbMemory) {
if (isReverbEnabled()) {
reverbModel->mute();
}
} else {
if (oldReverbModel != NULL) {
oldReverbModel->close();
}
if (isReverbEnabled()) {
reverbModel->open();
}
}
}
if (isReverbEnabled()) {
reverbModel->setParameters(mt32ram.system.reverbTime, mt32ram.system.reverbLevel);
}
}
void Synth::refreshSystemReserveSettings() {
Bit8u *rset = mt32ram.system.reserveSettings;
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" Partial reserve: 1=%02d 2=%02d 3=%02d 4=%02d 5=%02d 6=%02d 7=%02d 8=%02d Rhythm=%02d", rset[0], rset[1], rset[2], rset[3], rset[4], rset[5], rset[6], rset[7], rset[8]);
#endif
partialManager->setReserve(rset);
}
void Synth::refreshSystemChanAssign(Bit8u firstPart, Bit8u lastPart) {
memset(extensions.chantable, 0xFF, sizeof(extensions.chantable));
// CONFIRMED: In the case of assigning a MIDI channel to multiple parts,
// the messages received on that MIDI channel are handled by all the parts.
for (Bit32u i = 0; i <= 8; i++) {
if (parts[i] != NULL && i >= firstPart && i <= lastPart) {
// CONFIRMED: Decay is started for all polys, and all controllers are reset, for every part whose assignment was touched by the sysex write.
parts[i]->allSoundOff();
parts[i]->resetAllControllers();
}
Bit8u chan = mt32ram.system.chanAssign[i];
if (chan > 15) continue;
Bit8u *chanParts = extensions.chantable[chan];
for (Bit32u j = 0; j <= 8; j++) {
if (chanParts[j] > 8) {
chanParts[j] = Bit8u(i);
break;
}
}
}
#if MT32EMU_MONITOR_SYSEX > 0
Bit8u *rset = mt32ram.system.chanAssign;
printDebug(" Part assign: 1=%02d 2=%02d 3=%02d 4=%02d 5=%02d 6=%02d 7=%02d 8=%02d Rhythm=%02d", rset[0], rset[1], rset[2], rset[3], rset[4], rset[5], rset[6], rset[7], rset[8]);
#endif
}
void Synth::refreshSystemMasterVol() {
// Note, this should only occur when the user turns the volume knob. When the master volume is set via a SysEx, display
// doesn't actually update on all real devices. However, we anyway update the display, as we don't foresee a dedicated
// API for setting the master volume yet it's rather dubious that one really needs this quirk to be fairly emulated.
if (opened) extensions.display->masterVolumeChanged();
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" Master volume: %d", mt32ram.system.masterVol);
#endif
}
void Synth::refreshSystem() {
refreshSystemMasterTune();
refreshSystemReverbParameters();
refreshSystemReserveSettings();
refreshSystemChanAssign(0, 8);
refreshSystemMasterVol();
}
void Synth::reset() {
if (!opened) return;
#if MT32EMU_MONITOR_SYSEX > 0
printDebug("RESET");
#endif
reportHandler->onDeviceReset();
partialManager->deactivateAll();
mt32ram = mt32default;
for (int i = 0; i < 9; i++) {
parts[i]->reset();
if (i != 8) {
parts[i]->setProgram(controlROMData[controlROMMap->programSettings + i]);
} else {
parts[8]->refresh();
}
}
refreshSystem();
resetMasterTunePitchDelta();
isActive();
}
void Synth::resetMasterTunePitchDelta() {
// This effectively resets master tune to 440.0Hz.
// Despite that the manual claims 442.0Hz is the default setting for master tune,
// it doesn't actually take effect upon a reset due to a bug in the reset routine.
// CONFIRMED: This bug is present in all supported Control ROMs.
extensions.masterTunePitchDelta = 0;
#if MT32EMU_MONITOR_SYSEX > 0
printDebug(" Actual Master Tune reset to 440.0");
#endif
}
Bit32s Synth::getMasterTunePitchDelta() const {
return extensions.masterTunePitchDelta;
}
bool Synth::getDisplayState(char *targetBuffer, bool narrowLCD) const {
if (!opened) {
memset(targetBuffer, ' ', Display::LCD_TEXT_SIZE);
targetBuffer[Display::LCD_TEXT_SIZE] = 0;
return false;
}
return extensions.display->getDisplayState(targetBuffer, narrowLCD);
}
void Synth::setMainDisplayMode() {
if (opened) extensions.display->setMainDisplayMode();
}
void Synth::setDisplayCompatibility(bool oldMT32CompatibilityEnabled) {
extensions.oldMT32DisplayFeatures = oldMT32CompatibilityEnabled;
}
bool Synth::isDisplayOldMT32Compatible() const {
return extensions.oldMT32DisplayFeatures;
}
bool Synth::isDefaultDisplayOldMT32Compatible() const {
return opened && controlROMFeatures->oldMT32DisplayFeatures;
}
/** Defines an interface of a class that maintains storage of variable-sized data of SysEx messages. */
class MidiEventQueue::SysexDataStorage {
public:
static MidiEventQueue::SysexDataStorage *create(Bit32u storageBufferSize);
virtual ~SysexDataStorage() {}
virtual Bit8u *allocate(Bit32u sysexLength) = 0;
virtual void reclaimUnused(const Bit8u *sysexData, Bit32u sysexLength) = 0;
virtual void dispose(const Bit8u *sysexData, Bit32u sysexLength) = 0;
};
/** Storage space for SysEx data is allocated dynamically on demand and is disposed lazily. */
class DynamicSysexDataStorage : public MidiEventQueue::SysexDataStorage {
public:
Bit8u *allocate(Bit32u sysexLength) {
return new Bit8u[sysexLength];
}
void reclaimUnused(const Bit8u *, Bit32u) {}
void dispose(const Bit8u *sysexData, Bit32u) {
delete[] sysexData;
}
};
/**
* SysEx data is stored in a preallocated buffer, that makes this kind of storage safe
* for use in a realtime thread. Additionally, the space retained by a SysEx event,
* that has been processed and thus is no longer necessary, is disposed instantly.
*/
class BufferedSysexDataStorage : public MidiEventQueue::SysexDataStorage {
public:
explicit BufferedSysexDataStorage(Bit32u useStorageBufferSize) :
storageBuffer(new Bit8u[useStorageBufferSize]),
storageBufferSize(useStorageBufferSize),
startPosition(),
endPosition()
{}
~BufferedSysexDataStorage() {
delete[] storageBuffer;
}
Bit8u *allocate(Bit32u sysexLength) {
Bit32u myStartPosition = startPosition;
Bit32u myEndPosition = endPosition;
// When the free space isn't contiguous, the data is allocated either right after the end position
// or at the buffer beginning, wherever it fits.
if (myStartPosition > myEndPosition) {
if (myStartPosition - myEndPosition <= sysexLength) return NULL;
} else if (storageBufferSize - myEndPosition < sysexLength) {
// There's not enough free space at the end to place the data block.
if (myStartPosition == myEndPosition) {
// The buffer is empty -> reset positions to the buffer beginning.
if (storageBufferSize <= sysexLength) return NULL;
if (myStartPosition != 0) {
myStartPosition = 0;
// It's OK to write startPosition here non-atomically. We don't expect any
// concurrent reads, as there must be no SysEx messages in the queue.
startPosition = myStartPosition;
}
} else if (myStartPosition <= sysexLength) return NULL;
myEndPosition = 0;
}
endPosition = myEndPosition + sysexLength;
return storageBuffer + myEndPosition;
}
void reclaimUnused(const Bit8u *sysexData, Bit32u sysexLength) {
if (sysexData == NULL) return;
Bit32u allocatedPosition = startPosition;
if (storageBuffer + allocatedPosition == sysexData) {
startPosition = allocatedPosition + sysexLength;
} else if (storageBuffer == sysexData) {
// Buffer wrapped around.
startPosition = sysexLength;
}
}
void dispose(const Bit8u *, Bit32u) {}
private:
Bit8u * const storageBuffer;
const Bit32u storageBufferSize;
volatile Bit32u startPosition;
volatile Bit32u endPosition;
};
MidiEventQueue::SysexDataStorage *MidiEventQueue::SysexDataStorage::create(Bit32u storageBufferSize) {
if (storageBufferSize > 0) {
return new BufferedSysexDataStorage(storageBufferSize);
} else {
return new DynamicSysexDataStorage;
}
}
MidiEventQueue::MidiEventQueue(Bit32u useRingBufferSize, Bit32u storageBufferSize) :
sysexDataStorage(*SysexDataStorage::create(storageBufferSize)),
ringBuffer(new MidiEvent[useRingBufferSize]), ringBufferMask(useRingBufferSize - 1)
{
for (Bit32u i = 0; i <= ringBufferMask; i++) {
ringBuffer[i].sysexData = NULL;
}
reset();
}
MidiEventQueue::~MidiEventQueue() {
for (Bit32u i = 0; i <= ringBufferMask; i++) {
volatile MidiEvent ¤tEvent = ringBuffer[i];
sysexDataStorage.dispose(currentEvent.sysexData, currentEvent.sysexLength);
}
delete &sysexDataStorage;
delete[] ringBuffer;
}
void MidiEventQueue::reset() {
startPosition = 0;
endPosition = 0;
}
bool MidiEventQueue::pushShortMessage(Bit32u shortMessageData, Bit32u timestamp) {
Bit32u newEndPosition = (endPosition + 1) & ringBufferMask;
// If ring buffer is full, bail out.
if (startPosition == newEndPosition) return false;
volatile MidiEvent &newEvent = ringBuffer[endPosition];
sysexDataStorage.dispose(newEvent.sysexData, newEvent.sysexLength);
newEvent.sysexData = NULL;
newEvent.shortMessageData = shortMessageData;
newEvent.timestamp = timestamp;
endPosition = newEndPosition;
return true;
}
bool MidiEventQueue::pushSysex(const Bit8u *sysexData, Bit32u sysexLength, Bit32u timestamp) {
Bit32u newEndPosition = (endPosition + 1) & ringBufferMask;
// If ring buffer is full, bail out.
if (startPosition == newEndPosition) return false;
volatile MidiEvent &newEvent = ringBuffer[endPosition];
sysexDataStorage.dispose(newEvent.sysexData, newEvent.sysexLength);
Bit8u *dstSysexData = sysexDataStorage.allocate(sysexLength);
if (dstSysexData == NULL) return false;
memcpy(dstSysexData, sysexData, sysexLength);
newEvent.sysexData = dstSysexData;
newEvent.sysexLength = sysexLength;
newEvent.timestamp = timestamp;
endPosition = newEndPosition;
return true;
}
const volatile MidiEventQueue::MidiEvent *MidiEventQueue::peekMidiEvent() {
return isEmpty() ? NULL : &ringBuffer[startPosition];
}
void MidiEventQueue::dropMidiEvent() {
if (isEmpty()) return;
volatile MidiEvent &unusedEvent = ringBuffer[startPosition];
sysexDataStorage.reclaimUnused(unusedEvent.sysexData, unusedEvent.sysexLength);
startPosition = (startPosition + 1) & ringBufferMask;
}
bool MidiEventQueue::isEmpty() const {
return startPosition == endPosition;
}
void Synth::selectRendererType(RendererType newRendererType) {
extensions.selectedRendererType = newRendererType;
}
RendererType Synth::getSelectedRendererType() const {
return extensions.selectedRendererType;
}
Bit32u Synth::getStereoOutputSampleRate() const {
return (analog == NULL) ? SAMPLE_RATE : analog->getOutputSampleRate();
}
void Renderer::updateDisplayState() {
bool midiMessageLEDState;
bool midiMessageLEDStateUpdated;
bool lcdUpdated;
synth.extensions.display->checkDisplayStateUpdated(midiMessageLEDState, midiMessageLEDStateUpdated, lcdUpdated);
if (midiMessageLEDStateUpdated) synth.extensions.reportHandler2->onMidiMessageLEDStateUpdated(midiMessageLEDState);
if (lcdUpdated) synth.extensions.reportHandler2->onLCDStateUpdated();
}
template <class Sample>
void RendererImpl<Sample>::doRender(Sample *stereoStream, Bit32u len) {
if (!isActivated()) {
incRenderedSampleCount(getAnalog().getDACStreamsLength(len));
if (!getAnalog().process(NULL, NULL, NULL, NULL, NULL, NULL, stereoStream, len)) {
printDebug("RendererImpl: Invalid call to Analog::process()!\n");
}
Synth::muteSampleBuffer(stereoStream, len << 1);
updateDisplayState();
return;
}
while (len > 0) {
// As in AnalogOutputMode_ACCURATE mode output is upsampled, MAX_SAMPLES_PER_RUN is more than enough for the temp buffers.
Bit32u thisPassLen = len > MAX_SAMPLES_PER_RUN ? MAX_SAMPLES_PER_RUN : len;
doRenderStreams(tmpBuffers, getAnalog().getDACStreamsLength(thisPassLen));
if (!getAnalog().process(stereoStream, tmpNonReverbLeft, tmpNonReverbRight, tmpReverbDryLeft, tmpReverbDryRight, tmpReverbWetLeft, tmpReverbWetRight, thisPassLen)) {
printDebug("RendererImpl: Invalid call to Analog::process()!\n");
Synth::muteSampleBuffer(stereoStream, len << 1);
return;
}
stereoStream += thisPassLen << 1;
len -= thisPassLen;
}
}
template <class Sample>
template <class O>
void RendererImpl<Sample>::doRenderAndConvert(O *stereoStream, Bit32u len) {
Sample renderingBuffer[MAX_SAMPLES_PER_RUN << 1];
while (len > 0) {
Bit32u thisPassLen = len > MAX_SAMPLES_PER_RUN ? MAX_SAMPLES_PER_RUN : len;
doRender(renderingBuffer, thisPassLen);
convertSampleFormat(renderingBuffer, stereoStream, thisPassLen << 1);
stereoStream += thisPassLen << 1;
len -= thisPassLen;
}
}
template<>
void RendererImpl<IntSample>::render(IntSample *stereoStream, Bit32u len) {
doRender(stereoStream, len);
}
template<>
void RendererImpl<IntSample>::render(FloatSample *stereoStream, Bit32u len) {
doRenderAndConvert(stereoStream, len);
}
template<>
void RendererImpl<FloatSample>::render(IntSample *stereoStream, Bit32u len) {
doRenderAndConvert(stereoStream, len);
}
template<>
void RendererImpl<FloatSample>::render(FloatSample *stereoStream, Bit32u len) {
doRender(stereoStream, len);
}
template <class S>
static inline void renderStereo(bool opened, Renderer *renderer, S *stream, Bit32u len) {
if (opened) {
renderer->render(stream, len);
} else {
Synth::muteSampleBuffer(stream, len << 1);
}
}
void Synth::render(Bit16s *stream, Bit32u len) {
renderStereo(opened, renderer, stream, len);
}
void Synth::render(float *stream, Bit32u len) {
renderStereo(opened, renderer, stream, len);
}
template <class Sample>
static inline void advanceStream(Sample *&stream, Bit32u len) {
if (stream != NULL) {
stream += len;
}
}
template <class Sample>
static inline void advanceStreams(DACOutputStreams<Sample> &streams, Bit32u len) {
advanceStream(streams.nonReverbLeft, len);
advanceStream(streams.nonReverbRight, len);
advanceStream(streams.reverbDryLeft, len);
advanceStream(streams.reverbDryRight, len);
advanceStream(streams.reverbWetLeft, len);
advanceStream(streams.reverbWetRight, len);
}
template <class Sample>
static inline void muteStreams(const DACOutputStreams<Sample> &streams, Bit32u len) {
Synth::muteSampleBuffer(streams.nonReverbLeft, len);
Synth::muteSampleBuffer(streams.nonReverbRight, len);
Synth::muteSampleBuffer(streams.reverbDryLeft, len);
Synth::muteSampleBuffer(streams.reverbDryRight, len);
Synth::muteSampleBuffer(streams.reverbWetLeft, len);
Synth::muteSampleBuffer(streams.reverbWetRight, len);
}
template <class I, class O>
static inline void convertStreamsFormat(const DACOutputStreams<I> &inStreams, const DACOutputStreams<O> &outStreams, Bit32u len) {
convertSampleFormat(inStreams.nonReverbLeft, outStreams.nonReverbLeft, len);
convertSampleFormat(inStreams.nonReverbRight, outStreams.nonReverbRight, len);
convertSampleFormat(inStreams.reverbDryLeft, outStreams.reverbDryLeft, len);
convertSampleFormat(inStreams.reverbDryRight, outStreams.reverbDryRight, len);
convertSampleFormat(inStreams.reverbWetLeft, outStreams.reverbWetLeft, len);
convertSampleFormat(inStreams.reverbWetRight, outStreams.reverbWetRight, len);
}
template <class Sample>
void RendererImpl<Sample>::doRenderStreams(const DACOutputStreams<Sample> &streams, Bit32u len)
{
DACOutputStreams<Sample> tmpStreams = streams;
while (len > 0) {
// We need to ensure zero-duration notes will play so add minimum 1-sample delay.
Bit32u thisLen = 1;
if (!isAbortingPoly()) {
const volatile MidiEventQueue::MidiEvent *nextEvent = getMidiQueue().peekMidiEvent();
Bit32s samplesToNextEvent = (nextEvent != NULL) ? Bit32s(nextEvent->timestamp - getRenderedSampleCount()) : MAX_SAMPLES_PER_RUN;
if (samplesToNextEvent > 0) {
thisLen = len > MAX_SAMPLES_PER_RUN ? MAX_SAMPLES_PER_RUN : len;
if (thisLen > Bit32u(samplesToNextEvent)) {
thisLen = samplesToNextEvent;
}
} else {
if (nextEvent->sysexData == NULL) {
synth.playMsgNow(nextEvent->shortMessageData);
// If a poly is aborting we don't drop the event from the queue.
// Instead, we'll return to it again when the abortion is done.
if (!isAbortingPoly()) {
getMidiQueue().dropMidiEvent();
}
} else {
synth.playSysexNow(nextEvent->sysexData, nextEvent->sysexLength);
getMidiQueue().dropMidiEvent();
}
}
}
produceStreams(tmpStreams, thisLen);
advanceStreams(tmpStreams, thisLen);
len -= thisLen;
}
}
template <class Sample>
template <class O>
void RendererImpl<Sample>::doRenderAndConvertStreams(const DACOutputStreams<O> &streams, Bit32u len) {
Sample cnvNonReverbLeft[MAX_SAMPLES_PER_RUN], cnvNonReverbRight[MAX_SAMPLES_PER_RUN];
Sample cnvReverbDryLeft[MAX_SAMPLES_PER_RUN], cnvReverbDryRight[MAX_SAMPLES_PER_RUN];
Sample cnvReverbWetLeft[MAX_SAMPLES_PER_RUN], cnvReverbWetRight[MAX_SAMPLES_PER_RUN];
const DACOutputStreams<Sample> cnvStreams = {
cnvNonReverbLeft, cnvNonReverbRight,
cnvReverbDryLeft, cnvReverbDryRight,
cnvReverbWetLeft, cnvReverbWetRight
};
DACOutputStreams<O> tmpStreams = streams;
while (len > 0) {
Bit32u thisPassLen = len > MAX_SAMPLES_PER_RUN ? MAX_SAMPLES_PER_RUN : len;
doRenderStreams(cnvStreams, thisPassLen);
convertStreamsFormat(cnvStreams, tmpStreams, thisPassLen);
advanceStreams(tmpStreams, thisPassLen);
len -= thisPassLen;
}
}
template<>
void RendererImpl<IntSample>::renderStreams(const DACOutputStreams<IntSample> &streams, Bit32u len) {
doRenderStreams(streams, len);
}
template<>
void RendererImpl<IntSample>::renderStreams(const DACOutputStreams<FloatSample> &streams, Bit32u len) {
doRenderAndConvertStreams(streams, len);
}
template<>
void RendererImpl<FloatSample>::renderStreams(const DACOutputStreams<IntSample> &streams, Bit32u len) {
doRenderAndConvertStreams(streams, len);
}
template<>
void RendererImpl<FloatSample>::renderStreams(const DACOutputStreams<FloatSample> &streams, Bit32u len) {
doRenderStreams(streams, len);
}
template <class S>
static inline void renderStreams(bool opened, Renderer *renderer, const DACOutputStreams<S> &streams, Bit32u len) {
if (opened) {
renderer->renderStreams(streams, len);
} else {
muteStreams(streams, len);
}
}
void Synth::renderStreams(const DACOutputStreams<Bit16s> &streams, Bit32u len) {
MT32Emu::renderStreams(opened, renderer, streams, len);
}
void Synth::renderStreams(const DACOutputStreams<float> &streams, Bit32u len) {
MT32Emu::renderStreams(opened, renderer, streams, len);
}
void Synth::renderStreams(
Bit16s *nonReverbLeft, Bit16s *nonReverbRight,
Bit16s *reverbDryLeft, Bit16s *reverbDryRight,
Bit16s *reverbWetLeft, Bit16s *reverbWetRight,
Bit32u len)
{
DACOutputStreams<IntSample> streams = {
nonReverbLeft, nonReverbRight,
reverbDryLeft, reverbDryRight,
reverbWetLeft, reverbWetRight
};
renderStreams(streams, len);
}
void Synth::renderStreams(
float *nonReverbLeft, float *nonReverbRight,
float *reverbDryLeft, float *reverbDryRight,
float *reverbWetLeft, float *reverbWetRight,
Bit32u len)
{
DACOutputStreams<FloatSample> streams = {
nonReverbLeft, nonReverbRight,
reverbDryLeft, reverbDryRight,
reverbWetLeft, reverbWetRight
};
renderStreams(streams, len);
}
// In GENERATION2 units, the output from LA32 goes to the Boss chip already bit-shifted.
// In NICE mode, it's also better to increase volume before the reverb processing to preserve accuracy.
template <>
void RendererImpl<IntSample>::produceLA32Output(IntSample *buffer, Bit32u len) {
switch (synth.getDACInputMode()) {
case DACInputMode_GENERATION2:
while (len--) {
*buffer = (*buffer & 0x8000) | ((*buffer << 1) & 0x7FFE) | ((*buffer >> 14) & 0x0001);
++buffer;
}
break;
case DACInputMode_NICE:
while (len--) {
*buffer = Synth::clipSampleEx(IntSampleEx(*buffer) << 1);
++buffer;
}
break;
default:
break;
}
}
template <>
void RendererImpl<IntSample>::convertSamplesToOutput(IntSample *buffer, Bit32u len) {
if (synth.getDACInputMode() == DACInputMode_GENERATION1) {
while (len--) {
*buffer = IntSample((*buffer & 0x8000) | ((*buffer << 1) & 0x7FFE));
++buffer;
}
}
}
static inline float produceDistortedSample(float sample) {
// Here we roughly simulate the distortion caused by the DAC bit shift.
if (sample < -1.0f) {
return sample + 2.0f;
} else if (1.0f < sample) {
return sample - 2.0f;
}
return sample;
}
template <>
void RendererImpl<FloatSample>::produceLA32Output(FloatSample *buffer, Bit32u len) {
switch (synth.getDACInputMode()) {
case DACInputMode_NICE:
// Note, we do not do any clamping for floats here to avoid introducing distortions.
// This means that the output signal may actually overshoot the unity when the volume is set too high.
// We leave it up to the consumer whether the output is to be clamped or properly normalised further on.
while (len--) {
*buffer *= 2.0f;
buffer++;
}
break;
case DACInputMode_GENERATION2:
while (len--) {
*buffer = produceDistortedSample(2.0f * *buffer);
buffer++;
}
break;
default:
break;
}
}
template <>
void RendererImpl<FloatSample>::convertSamplesToOutput(FloatSample *buffer, Bit32u len) {
if (synth.getDACInputMode() == DACInputMode_GENERATION1) {
while (len--) {
*buffer = produceDistortedSample(2.0f * *buffer);
buffer++;
}
}
}
template <class Sample>
void RendererImpl<Sample>::produceStreams(const DACOutputStreams<Sample> &streams, Bit32u len) {
if (isActivated()) {
// Even if LA32 output isn't desired, we proceed anyway with temp buffers
Sample *nonReverbLeft = streams.nonReverbLeft == NULL ? tmpNonReverbLeft : streams.nonReverbLeft;
Sample *nonReverbRight = streams.nonReverbRight == NULL ? tmpNonReverbRight : streams.nonReverbRight;
Sample *reverbDryLeft = streams.reverbDryLeft == NULL ? tmpReverbDryLeft : streams.reverbDryLeft;
Sample *reverbDryRight = streams.reverbDryRight == NULL ? tmpReverbDryRight : streams.reverbDryRight;
Synth::muteSampleBuffer(nonReverbLeft, len);
Synth::muteSampleBuffer(nonReverbRight, len);
Synth::muteSampleBuffer(reverbDryLeft, len);
Synth::muteSampleBuffer(reverbDryRight, len);
for (unsigned int i = 0; i < synth.getPartialCount(); i++) {
if (getPartialManager().shouldReverb(i)) {
getPartialManager().produceOutput(i, reverbDryLeft, reverbDryRight, len);
} else {
getPartialManager().produceOutput(i, nonReverbLeft, nonReverbRight, len);
}
}
produceLA32Output(reverbDryLeft, len);
produceLA32Output(reverbDryRight, len);
if (synth.isReverbEnabled()) {
if (!getReverbModel().process(reverbDryLeft, reverbDryRight, streams.reverbWetLeft, streams.reverbWetRight, len)) {
printDebug("RendererImpl: Invalid call to BReverbModel::process()!\n");
}
if (streams.reverbWetLeft != NULL) convertSamplesToOutput(streams.reverbWetLeft, len);
if (streams.reverbWetRight != NULL) convertSamplesToOutput(streams.reverbWetRight, len);
} else {
Synth::muteSampleBuffer(streams.reverbWetLeft, len);
Synth::muteSampleBuffer(streams.reverbWetRight, len);
}
// Don't bother with conversion if the output is going to be unused
if (streams.nonReverbLeft != NULL) {
produceLA32Output(nonReverbLeft, len);
convertSamplesToOutput(nonReverbLeft, len);
}
if (streams.nonReverbRight != NULL) {
produceLA32Output(nonReverbRight, len);
convertSamplesToOutput(nonReverbRight, len);
}
if (streams.reverbDryLeft != NULL) convertSamplesToOutput(reverbDryLeft, len);
if (streams.reverbDryRight != NULL) convertSamplesToOutput(reverbDryRight, len);
} else {
muteStreams(streams, len);
}
getPartialManager().clearAlreadyOutputed();
incRenderedSampleCount(len);
updateDisplayState();
}
void Synth::printPartialUsage(Bit32u sampleOffset) {
unsigned int partialUsage[9];
partialManager->getPerPartPartialUsage(partialUsage);
if (sampleOffset > 0) {
printDebug("[+%u] Partial Usage: 1:%02d 2:%02d 3:%02d 4:%02d 5:%02d 6:%02d 7:%02d 8:%02d R: %02d TOTAL: %02d", sampleOffset, partialUsage[0], partialUsage[1], partialUsage[2], partialUsage[3], partialUsage[4], partialUsage[5], partialUsage[6], partialUsage[7], partialUsage[8], getPartialCount() - partialManager->getFreePartialCount());
} else {
printDebug("Partial Usage: 1:%02d 2:%02d 3:%02d 4:%02d 5:%02d 6:%02d 7:%02d 8:%02d R: %02d TOTAL: %02d", partialUsage[0], partialUsage[1], partialUsage[2], partialUsage[3], partialUsage[4], partialUsage[5], partialUsage[6], partialUsage[7], partialUsage[8], getPartialCount() - partialManager->getFreePartialCount());
}
}
bool Synth::hasActivePartials() const {
if (!opened) {
return false;
}
for (unsigned int partialNum = 0; partialNum < getPartialCount(); partialNum++) {
if (partialManager->getPartial(partialNum)->isActive()) {
return true;
}
}
return false;
}
bool Synth::isActive() {
if (!opened) {
return false;
}
if (!midiQueue->isEmpty() || hasActivePartials()) {
return true;
}
if (isReverbEnabled() && reverbModel->isActive()) {
return true;
}
activated = false;
return false;
}
Bit32u Synth::getPartialCount() const {
return partialCount;
}
void Synth::getPartStates(bool *partStates) const {
if (!opened) {
memset(partStates, 0, 9 * sizeof(bool));
return;
}
for (int partNumber = 0; partNumber < 9; partNumber++) {
const Part *part = parts[partNumber];
partStates[partNumber] = part->getActiveNonReleasingPartialCount() > 0;
}
}
Bit32u Synth::getPartStates() const {
if (!opened) return 0;
bool partStates[9];
getPartStates(partStates);
Bit32u bitSet = 0;
for (int partNumber = 8; partNumber >= 0; partNumber--) {
bitSet = (bitSet << 1) | (partStates[partNumber] ? 1 : 0);
}
return bitSet;
}
void Synth::getPartialStates(PartialState *partialStates) const {
if (!opened) {
memset(partialStates, 0, partialCount * sizeof(PartialState));
return;
}
for (unsigned int partialNum = 0; partialNum < partialCount; partialNum++) {
partialStates[partialNum] = getPartialState(partialManager, partialNum);
}
}
void Synth::getPartialStates(Bit8u *partialStates) const {
if (!opened) {
memset(partialStates, 0, ((partialCount + 3) >> 2));
return;
}
for (unsigned int quartNum = 0; (4 * quartNum) < partialCount; quartNum++) {
Bit8u packedStates = 0;
for (unsigned int i = 0; i < 4; i++) {
unsigned int partialNum = (4 * quartNum) + i;
if (partialCount <= partialNum) break;
PartialState partialState = getPartialState(partialManager, partialNum);
packedStates |= (partialState & 3) << (2 * i);
}
partialStates[quartNum] = packedStates;
}
}
Bit32u Synth::getPlayingNotes(Bit8u partNumber, Bit8u *keys, Bit8u *velocities) const {
Bit32u playingNotes = 0;
if (opened && (partNumber < 9)) {
const Part *part = parts[partNumber];
const Poly *poly = part->getFirstActivePoly();
while (poly != NULL) {
keys[playingNotes] = Bit8u(poly->getKey());
velocities[playingNotes] = Bit8u(poly->getVelocity());
playingNotes++;
poly = poly->getNext();
}
}
return playingNotes;
}
const char *Synth::getPatchName(Bit8u partNumber) const {
return (!opened || partNumber > 8) ? NULL : parts[partNumber]->getCurrentInstr();
}
bool Synth::getSoundGroupName(char *soundGroupName, Bit8u timbreGroup, Bit8u timbreNumber) const {
if (!opened || 63 < timbreNumber) return false;
const char *foundGroupName = getSoundGroupName(timbreGroup, timbreNumber);
if (foundGroupName == NULL) return false;
memcpy(soundGroupName, foundGroupName, 7);
soundGroupName[7] = 0;
return true;
}
bool Synth::getSoundName(char *soundName, Bit8u timbreGroup, Bit8u timbreNumber) const {
if (!opened || 3 < timbreGroup) return false;
Bit8u timbresInGroup = 3 == timbreGroup ? controlROMMap->timbreRCount : 64;
if (timbresInGroup <= timbreNumber) return false;
TimbreParam::CommonParam &timbreCommon = mt32ram.timbres[timbreGroup * 64 + timbreNumber].timbre.common;
if (timbreCommon.partialMute == 0) return false;
memcpy(soundName, timbreCommon.name, sizeof timbreCommon.name);
soundName[sizeof timbreCommon.name] = 0;
return true;
}
const Part *Synth::getPart(Bit8u partNum) const {
if (partNum > 8) {
return NULL;
}
return parts[partNum];
}
void MemoryRegion::read(unsigned int entry, unsigned int off, Bit8u *dst, unsigned int len) const {
off += entry * entrySize;
// This method should never be called with out-of-bounds parameters,
// or on an unsupported region - seeing any of this debug output indicates a bug in the emulator
if (off > entrySize * entries - 1) {
#if MT32EMU_MONITOR_SYSEX > 0
synth->printDebug("read[%d]: parameters start out of bounds: entry=%d, off=%d, len=%d", type, entry, off, len);
#endif
return;
}
if (off + len > entrySize * entries) {
#if MT32EMU_MONITOR_SYSEX > 0
synth->printDebug("read[%d]: parameters end out of bounds: entry=%d, off=%d, len=%d", type, entry, off, len);
#endif
len = entrySize * entries - off;
}
Bit8u *src = getRealMemory();
if (src == NULL) {
#if MT32EMU_MONITOR_SYSEX > 0
synth->printDebug("read[%d]: unreadable region: entry=%d, off=%d, len=%d", type, entry, off, len);
#endif
return;
}
memcpy(dst, src + off, len);
}
void MemoryRegion::write(unsigned int entry, unsigned int off, const Bit8u *src, unsigned int len, bool init) const {
unsigned int memOff = entry * entrySize + off;
// This method should never be called with out-of-bounds parameters,
// or on an unsupported region - seeing any of this debug output indicates a bug in the emulator
if (off > entrySize * entries - 1) {
#if MT32EMU_MONITOR_SYSEX > 0
synth->printDebug("write[%d]: parameters start out of bounds: entry=%d, off=%d, len=%d", type, entry, off, len);
#endif
return;
}
if (off + len > entrySize * entries) {
#if MT32EMU_MONITOR_SYSEX > 0
synth->printDebug("write[%d]: parameters end out of bounds: entry=%d, off=%d, len=%d", type, entry, off, len);
#endif
len = entrySize * entries - off;
}
Bit8u *dest = getRealMemory();
if (dest == NULL) {
#if MT32EMU_MONITOR_SYSEX > 0
synth->printDebug("write[%d]: unwritable region: entry=%d, off=%d, len=%d", type, entry, off, len);
#endif
return;
}
for (unsigned int i = 0; i < len; i++) {
Bit8u desiredValue = src[i];
Bit8u maxValue = getMaxValue(memOff);
// maxValue == 0 means write-protected unless called from initialisation code, in which case it really means the maximum value is 0.
if (maxValue != 0 || init) {
if (desiredValue > maxValue) {
#if MT32EMU_MONITOR_SYSEX > 0
synth->printDebug("write[%d]: Wanted 0x%02x at %d, but max 0x%02x", type, desiredValue, memOff, maxValue);
#endif
desiredValue = maxValue;
}
dest[memOff] = desiredValue;
} else if (desiredValue != 0) {
#if MT32EMU_MONITOR_SYSEX > 0
// Only output debug info if they wanted to write non-zero, since a lot of things cause this to spit out a lot of debug info otherwise.
synth->printDebug("write[%d]: Wanted 0x%02x at %d, but write-protected", type, desiredValue, memOff);
#endif
}
memOff++;
}
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/Synth.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 28,137 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
/* Using two guards since this file may be included twice with different MT32EMU_C_ENUMERATIONS define. */
#if (!defined MT32EMU_CPP_ENUMERATIONS_H && !defined MT32EMU_C_ENUMERATIONS) || (!defined MT32EMU_C_ENUMERATIONS_H && defined MT32EMU_C_ENUMERATIONS)
#ifdef MT32EMU_C_ENUMERATIONS
#define MT32EMU_C_ENUMERATIONS_H
#define MT32EMU_DAC_INPUT_MODE_NAME mt32emu_dac_input_mode
#define MT32EMU_DAC_INPUT_MODE(ident) MT32EMU_DAC_##ident
#define MT32EMU_MIDI_DELAY_MODE_NAME mt32emu_midi_delay_mode
#define MT32EMU_MIDI_DELAY_MODE(ident) MT32EMU_MDM_##ident
#define MT32EMU_ANALOG_OUTPUT_MODE_NAME mt32emu_analog_output_mode
#define MT32EMU_ANALOG_OUTPUT_MODE(ident) MT32EMU_AOM_##ident
#define MT32EMU_PARTIAL_STATE_NAME mt32emu_partial_state
#define MT32EMU_PARTIAL_STATE(ident) MT32EMU_PS_##ident
#define MT32EMU_SAMPLERATE_CONVERSION_QUALITY_NAME mt32emu_samplerate_conversion_quality
#define MT32EMU_SAMPLERATE_CONVERSION_QUALITY(ident) MT32EMU_SRCQ_##ident
#define MT32EMU_RENDERER_TYPE_NAME mt32emu_renderer_type
#define MT32EMU_RENDERER_TYPE(ident) MT32EMU_RT_##ident
#else /* #ifdef MT32EMU_C_ENUMERATIONS */
#define MT32EMU_CPP_ENUMERATIONS_H
#define MT32EMU_DAC_INPUT_MODE_NAME DACInputMode
#define MT32EMU_DAC_INPUT_MODE(ident) DACInputMode_##ident
#define MT32EMU_MIDI_DELAY_MODE_NAME MIDIDelayMode
#define MT32EMU_MIDI_DELAY_MODE(ident) MIDIDelayMode_##ident
#define MT32EMU_ANALOG_OUTPUT_MODE_NAME AnalogOutputMode
#define MT32EMU_ANALOG_OUTPUT_MODE(ident) AnalogOutputMode_##ident
#define MT32EMU_PARTIAL_STATE_NAME PartialState
#define MT32EMU_PARTIAL_STATE(ident) PartialState_##ident
#define MT32EMU_SAMPLERATE_CONVERSION_QUALITY_NAME SamplerateConversionQuality
#define MT32EMU_SAMPLERATE_CONVERSION_QUALITY(ident) SamplerateConversionQuality_##ident
#define MT32EMU_RENDERER_TYPE_NAME RendererType
#define MT32EMU_RENDERER_TYPE(ident) RendererType_##ident
namespace MT32Emu {
#endif /* #ifdef MT32EMU_C_ENUMERATIONS */
/**
* Methods for emulating the connection between the LA32 and the DAC, which involves
* some hacks in the real devices for doubling the volume.
* See also path_to_url#Digital_overflow
*/
enum MT32EMU_DAC_INPUT_MODE_NAME {
/**
* Produces samples at double the volume, without tricks.
* Nicer overdrive characteristics than the DAC hacks (it simply clips samples within range)
* Higher quality than the real devices
*/
MT32EMU_DAC_INPUT_MODE(NICE),
/**
* Produces samples that exactly match the bits output from the emulated LA32.
* Nicer overdrive characteristics than the DAC hacks (it simply clips samples within range)
* Much less likely to overdrive than any other mode.
* Half the volume of any of the other modes.
* Perfect for developers while debugging :)
*/
MT32EMU_DAC_INPUT_MODE(PURE),
/**
* Re-orders the LA32 output bits as in early generation MT-32s (according to Wikipedia).
* Bit order at DAC (where each number represents the original LA32 output bit number, and XX means the bit is always low):
* 15 13 12 11 10 09 08 07 06 05 04 03 02 01 00 XX
*/
MT32EMU_DAC_INPUT_MODE(GENERATION1),
/**
* Re-orders the LA32 output bits as in later generations (personally confirmed on my CM-32L - KG).
* Bit order at DAC (where each number represents the original LA32 output bit number):
* 15 13 12 11 10 09 08 07 06 05 04 03 02 01 00 14
*/
MT32EMU_DAC_INPUT_MODE(GENERATION2)
};
/** Methods for emulating the effective delay of incoming MIDI messages introduced by a MIDI interface. */
enum MT32EMU_MIDI_DELAY_MODE_NAME {
/** Process incoming MIDI events immediately. */
MT32EMU_MIDI_DELAY_MODE(IMMEDIATE),
/**
* Delay incoming short MIDI messages as if they where transferred via a MIDI cable to a real hardware unit and immediate sysex processing.
* This ensures more accurate timing of simultaneous NoteOn messages.
*/
MT32EMU_MIDI_DELAY_MODE(DELAY_SHORT_MESSAGES_ONLY),
/** Delay all incoming MIDI events as if they where transferred via a MIDI cable to a real hardware unit.*/
MT32EMU_MIDI_DELAY_MODE(DELAY_ALL)
};
/** Methods for emulating the effects of analogue circuits of real hardware units on the output signal. */
enum MT32EMU_ANALOG_OUTPUT_MODE_NAME {
/** Only digital path is emulated. The output samples correspond to the digital signal at the DAC entrance. */
MT32EMU_ANALOG_OUTPUT_MODE(DIGITAL_ONLY),
/** Coarse emulation of LPF circuit. High frequencies are boosted, sample rate remains unchanged. */
MT32EMU_ANALOG_OUTPUT_MODE(COARSE),
/**
* Finer emulation of LPF circuit. Output signal is upsampled to 48 kHz to allow emulation of audible mirror spectra above 16 kHz,
* which is passed through the LPF circuit without significant attenuation.
*/
MT32EMU_ANALOG_OUTPUT_MODE(ACCURATE),
/**
* Same as AnalogOutputMode_ACCURATE mode but the output signal is 2x oversampled, i.e. the output sample rate is 96 kHz.
* This makes subsequent resampling easier. Besides, due to nonlinear passband of the LPF emulated, it takes fewer number of MACs
* compared to a regular LPF FIR implementations.
*/
MT32EMU_ANALOG_OUTPUT_MODE(OVERSAMPLED)
};
enum MT32EMU_PARTIAL_STATE_NAME {
MT32EMU_PARTIAL_STATE(INACTIVE),
MT32EMU_PARTIAL_STATE(ATTACK),
MT32EMU_PARTIAL_STATE(SUSTAIN),
MT32EMU_PARTIAL_STATE(RELEASE)
};
enum MT32EMU_SAMPLERATE_CONVERSION_QUALITY_NAME {
/** Use this only when the speed is more important than the audio quality. */
MT32EMU_SAMPLERATE_CONVERSION_QUALITY(FASTEST),
MT32EMU_SAMPLERATE_CONVERSION_QUALITY(FAST),
MT32EMU_SAMPLERATE_CONVERSION_QUALITY(GOOD),
MT32EMU_SAMPLERATE_CONVERSION_QUALITY(BEST)
};
enum MT32EMU_RENDERER_TYPE_NAME {
/** Use 16-bit signed samples in the renderer and the accurate wave generator model based on logarithmic fixed-point computations and LUTs. Maximum emulation accuracy and speed. */
MT32EMU_RENDERER_TYPE(BIT16S),
/** Use float samples in the renderer and simplified wave generator model. Maximum output quality and minimum noise. */
MT32EMU_RENDERER_TYPE(FLOAT)
};
#ifndef MT32EMU_C_ENUMERATIONS
} // namespace MT32Emu
#endif
#undef MT32EMU_DAC_INPUT_MODE_NAME
#undef MT32EMU_DAC_INPUT_MODE
#undef MT32EMU_MIDI_DELAY_MODE_NAME
#undef MT32EMU_MIDI_DELAY_MODE
#undef MT32EMU_ANALOG_OUTPUT_MODE_NAME
#undef MT32EMU_ANALOG_OUTPUT_MODE
#undef MT32EMU_PARTIAL_STATE_NAME
#undef MT32EMU_PARTIAL_STATE
#undef MT32EMU_SAMPLERATE_CONVERSION_QUALITY_NAME
#undef MT32EMU_SAMPLERATE_CONVERSION_QUALITY
#undef MT32EMU_RENDERER_TYPE_NAME
#undef MT32EMU_RENDERER_TYPE
#endif /* #if (!defined MT32EMU_CPP_ENUMERATIONS_H && !defined MT32EMU_C_ENUMERATIONS) || (!defined MT32EMU_C_ENUMERATIONS_H && defined MT32EMU_C_ENUMERATIONS) */
``` | /content/code_sandbox/src/sound/munt/Enumerations.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,781 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_MIDI_EVENT_QUEUE_H
#define MT32EMU_MIDI_EVENT_QUEUE_H
#include "globals.h"
#include "Types.h"
namespace MT32Emu {
/**
* Simple queue implementation using a ring buffer to store incoming MIDI event before the synth actually processes it.
* It is intended to:
* - get rid of prerenderer while retaining graceful partial abortion
* - add fair emulation of the MIDI interface delays
* - extend the synth interface with the default implementation of a typical rendering loop.
* THREAD SAFETY:
* It is safe to use either in a single thread environment or when there are only two threads - one performs only reading
* and one performs only writing. More complicated usage requires external synchronisation.
*/
class MidiEventQueue {
public:
class SysexDataStorage;
struct MidiEvent {
const Bit8u *sysexData;
union {
Bit32u sysexLength;
Bit32u shortMessageData;
};
Bit32u timestamp;
};
explicit MidiEventQueue(
// Must be a power of 2
Bit32u ringBufferSize,
Bit32u storageBufferSize
);
~MidiEventQueue();
void reset();
bool pushShortMessage(Bit32u shortMessageData, Bit32u timestamp);
bool pushSysex(const Bit8u *sysexData, Bit32u sysexLength, Bit32u timestamp);
const volatile MidiEvent *peekMidiEvent();
void dropMidiEvent();
inline bool isEmpty() const;
private:
SysexDataStorage &sysexDataStorage;
MidiEvent * const ringBuffer;
const Bit32u ringBufferMask;
volatile Bit32u startPosition;
volatile Bit32u endPosition;
};
} // namespace MT32Emu
#endif // #ifndef MT32EMU_MIDI_EVENT_QUEUE_H
``` | /content/code_sandbox/src/sound/munt/MidiEventQueue.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 473 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstring>
#include "internals.h"
#include "File.h"
#include "ROMInfo.h"
namespace MT32Emu {
namespace {
struct ROMInfoList {
const ROMInfo * const *romInfos;
const Bit32u itemCount;
};
struct ROMInfoLists {
ROMInfoList mt32_1_04;
ROMInfoList mt32_1_05;
ROMInfoList mt32_1_06;
ROMInfoList mt32_1_07;
ROMInfoList mt32_bluer;
ROMInfoList mt32_2_03;
ROMInfoList mt32_2_04;
ROMInfoList mt32_2_06;
ROMInfoList mt32_2_07;
ROMInfoList cm32l_1_00;
ROMInfoList cm32l_1_02;
ROMInfoList cm32ln_1_00;
ROMInfoList fullROMInfos;
ROMInfoList partialROMInfos;
ROMInfoList allROMInfos;
};
}
#define _CALC_ARRAY_LENGTH(x) Bit32u(sizeof (x) / sizeof *(x) - 1)
static const ROMInfoLists &getROMInfoLists() {
static ROMInfo CTRL_MT32_V1_04_A = {32768, "9cd4858014c4e8a9dff96053f784bfaac1092a2e", ROMInfo::Control, "ctrl_mt32_1_04_a", "MT-32 Control v1.04", ROMInfo::Mux0, NULL};
static ROMInfo CTRL_MT32_V1_04_B = {32768, "fe8db469b5bfeb37edb269fd47e3ce6d91014652", ROMInfo::Control, "ctrl_mt32_1_04_b", "MT-32 Control v1.04", ROMInfo::Mux1, &CTRL_MT32_V1_04_A};
static ROMInfo CTRL_MT32_V1_04 = {65536, "5a5cb5a77d7d55ee69657c2f870416daed52dea7", ROMInfo::Control, "ctrl_mt32_1_04", "MT-32 Control v1.04", ROMInfo::Full, NULL};
static ROMInfo CTRL_MT32_V1_05_A = {32768, "57a09d80d2f7ca5b9734edbe9645e6e700f83701", ROMInfo::Control, "ctrl_mt32_1_05_a", "MT-32 Control v1.05", ROMInfo::Mux0, NULL};
static ROMInfo CTRL_MT32_V1_05_B = {32768, "52e3c6666db9ef962591a8ee99be0cde17f3a6b6", ROMInfo::Control, "ctrl_mt32_1_05_b", "MT-32 Control v1.05", ROMInfo::Mux1, &CTRL_MT32_V1_05_A};
static ROMInfo CTRL_MT32_V1_05 = {65536, "e17a3a6d265bf1fa150312061134293d2b58288c", ROMInfo::Control, "ctrl_mt32_1_05", "MT-32 Control v1.05", ROMInfo::Full, NULL};
static ROMInfo CTRL_MT32_V1_06_A = {32768, "cc83bf23cee533097fb4c7e2c116e43b50ebacc8", ROMInfo::Control, "ctrl_mt32_1_06_a", "MT-32 Control v1.06", ROMInfo::Mux0, NULL};
static ROMInfo CTRL_MT32_V1_06_B = {32768, "bf4f15666bc46679579498386704893b630c1171", ROMInfo::Control, "ctrl_mt32_1_06_b", "MT-32 Control v1.06", ROMInfo::Mux1, &CTRL_MT32_V1_06_A};
static ROMInfo CTRL_MT32_V1_06 = {65536, "a553481f4e2794c10cfe597fef154eef0d8257de", ROMInfo::Control, "ctrl_mt32_1_06", "MT-32 Control v1.06", ROMInfo::Full, NULL};
static ROMInfo CTRL_MT32_V1_07_A = {32768, "13f06b38f0d9e0fc050b6503ab777bb938603260", ROMInfo::Control, "ctrl_mt32_1_07_a", "MT-32 Control v1.07", ROMInfo::Mux0, NULL};
static ROMInfo CTRL_MT32_V1_07_B = {32768, "c55e165487d71fa88bd8c5e9c083bc456c1a89aa", ROMInfo::Control, "ctrl_mt32_1_07_b", "MT-32 Control v1.07", ROMInfo::Mux1, &CTRL_MT32_V1_07_A};
static ROMInfo CTRL_MT32_V1_07 = {65536, "b083518fffb7f66b03c23b7eb4f868e62dc5a987", ROMInfo::Control, "ctrl_mt32_1_07", "MT-32 Control v1.07", ROMInfo::Full, NULL};
static ROMInfo CTRL_MT32_BLUER_A = {32768, "11a6ae5d8b6ee328b371af7f1e40b82125aa6b4d", ROMInfo::Control, "ctrl_mt32_bluer_a", "MT-32 Control BlueRidge", ROMInfo::Mux0, NULL};
static ROMInfo CTRL_MT32_BLUER_B = {32768, "e0934320d7cbb5edfaa29e0d01ae835ef620085b", ROMInfo::Control, "ctrl_mt32_bluer_b", "MT-32 Control BlueRidge", ROMInfo::Mux1, &CTRL_MT32_BLUER_A};
static ROMInfo CTRL_MT32_BLUER = {65536, "7b8c2a5ddb42fd0732e2f22b3340dcf5360edf92", ROMInfo::Control, "ctrl_mt32_bluer", "MT-32 Control BlueRidge", ROMInfo::Full, NULL};
static const ROMInfo CTRL_MT32_V2_03 = {131072, "5837064c9df4741a55f7c4d8787ac158dff2d3ce", ROMInfo::Control, "ctrl_mt32_2_03", "MT-32 Control v2.03", ROMInfo::Full, NULL};
static const ROMInfo CTRL_MT32_V2_04 = {131072, "2c16432b6c73dd2a3947cba950a0f4c19d6180eb", ROMInfo::Control, "ctrl_mt32_2_04", "MT-32 Control v2.04", ROMInfo::Full, NULL};
static const ROMInfo CTRL_MT32_V2_06 = {131072, "2869cf4c235d671668cfcb62415e2ce8323ad4ed", ROMInfo::Control, "ctrl_mt32_2_06", "MT-32 Control v2.06", ROMInfo::Full, NULL};
static const ROMInfo CTRL_MT32_V2_07 = {131072, "47b52adefedaec475c925e54340e37673c11707c", ROMInfo::Control, "ctrl_mt32_2_07", "MT-32 Control v2.07", ROMInfo::Full, NULL};
static const ROMInfo CTRL_CM32L_V1_00 = {65536, "73683d585cd6948cc19547942ca0e14a0319456d", ROMInfo::Control, "ctrl_cm32l_1_00", "CM-32L/LAPC-I Control v1.00", ROMInfo::Full, NULL};
static const ROMInfo CTRL_CM32L_V1_02 = {65536, "a439fbb390da38cada95a7cbb1d6ca199cd66ef8", ROMInfo::Control, "ctrl_cm32l_1_02", "CM-32L/LAPC-I Control v1.02", ROMInfo::Full, NULL};
static const ROMInfo CTRL_CM32LN_V1_00 = {65536, "dc1c5b1b90a4646d00f7daf3679733c7badc7077", ROMInfo::Control, "ctrl_cm32ln_1_00", "CM-32LN/CM-500/LAPC-N Control v1.00", ROMInfo::Full, NULL};
static ROMInfo PCM_MT32_L = {262144, "3a1e19b0cd4036623fd1d1d11f5f25995585962b", ROMInfo::PCM, "pcm_mt32_l", "MT-32 PCM ROM", ROMInfo::FirstHalf, NULL};
static ROMInfo PCM_MT32_H = {262144, "2cadb99d21a6a4a6f5b61b6218d16e9b43f61d01", ROMInfo::PCM, "pcm_mt32_h", "MT-32 PCM ROM", ROMInfo::SecondHalf, &PCM_MT32_L};
static ROMInfo PCM_MT32 = {524288, "f6b1eebc4b2d200ec6d3d21d51325d5b48c60252", ROMInfo::PCM, "pcm_mt32", "MT-32 PCM ROM", ROMInfo::Full, NULL};
// Alias of PCM_MT32 ROM, only useful for pairing with PCM_CM32L_H.
static ROMInfo PCM_CM32L_L = {524288, "f6b1eebc4b2d200ec6d3d21d51325d5b48c60252", ROMInfo::PCM, "pcm_cm32l_l", "CM-32L/CM-64/LAPC-I PCM ROM", ROMInfo::FirstHalf, NULL};
static ROMInfo PCM_CM32L_H = {524288, "3ad889fde5db5b6437cbc2eb6e305312fec3df93", ROMInfo::PCM, "pcm_cm32l_h", "CM-32L/CM-64/LAPC-I PCM ROM", ROMInfo::SecondHalf, &PCM_CM32L_L};
static ROMInfo PCM_CM32L = {1048576, "289cc298ad532b702461bfc738009d9ebe8025ea", ROMInfo::PCM, "pcm_cm32l", "CM-32L/CM-64/LAPC-I PCM ROM", ROMInfo::Full, NULL};
static const ROMInfo * const FULL_ROM_INFOS[] = {
&CTRL_MT32_V1_04,
&CTRL_MT32_V1_05,
&CTRL_MT32_V1_06,
&CTRL_MT32_V1_07,
&CTRL_MT32_BLUER,
&CTRL_MT32_V2_03,
&CTRL_MT32_V2_04,
&CTRL_MT32_V2_06,
&CTRL_MT32_V2_07,
&CTRL_CM32L_V1_00,
&CTRL_CM32L_V1_02,
&CTRL_CM32LN_V1_00,
&PCM_MT32,
&PCM_CM32L,
NULL
};
static const ROMInfo * const PARTIAL_ROM_INFOS[] = {
&CTRL_MT32_V1_04_A, &CTRL_MT32_V1_04_B,
&CTRL_MT32_V1_05_A, &CTRL_MT32_V1_05_B,
&CTRL_MT32_V1_06_A, &CTRL_MT32_V1_06_B,
&CTRL_MT32_V1_07_A, &CTRL_MT32_V1_07_B,
&CTRL_MT32_BLUER_A, &CTRL_MT32_BLUER_B,
&PCM_MT32_L, &PCM_MT32_H,
&PCM_CM32L_L, &PCM_CM32L_H,
NULL
};
static const ROMInfo *ALL_ROM_INFOS[_CALC_ARRAY_LENGTH(FULL_ROM_INFOS) + _CALC_ARRAY_LENGTH(PARTIAL_ROM_INFOS) + 1];
if (CTRL_MT32_V1_04_A.pairROMInfo == NULL) {
CTRL_MT32_V1_04_A.pairROMInfo = &CTRL_MT32_V1_04_B;
CTRL_MT32_V1_05_A.pairROMInfo = &CTRL_MT32_V1_05_B;
CTRL_MT32_V1_06_A.pairROMInfo = &CTRL_MT32_V1_06_B;
CTRL_MT32_V1_07_A.pairROMInfo = &CTRL_MT32_V1_07_B;
CTRL_MT32_BLUER_A.pairROMInfo = &CTRL_MT32_BLUER_B;
PCM_MT32_L.pairROMInfo = &PCM_MT32_H;
PCM_CM32L_L.pairROMInfo = &PCM_CM32L_H;
memcpy(&ALL_ROM_INFOS[0], FULL_ROM_INFOS, sizeof FULL_ROM_INFOS);
memcpy(&ALL_ROM_INFOS[_CALC_ARRAY_LENGTH(FULL_ROM_INFOS)], PARTIAL_ROM_INFOS, sizeof PARTIAL_ROM_INFOS); // Includes NULL terminator.
}
static const ROMInfo * const MT32_V1_04_ROMS[] = {&CTRL_MT32_V1_04, &PCM_MT32, &CTRL_MT32_V1_04_A, &CTRL_MT32_V1_04_B, &PCM_MT32_L, &PCM_MT32_H, NULL};
static const ROMInfo * const MT32_V1_05_ROMS[] = {&CTRL_MT32_V1_05, &PCM_MT32, &CTRL_MT32_V1_05_A, &CTRL_MT32_V1_05_B, &PCM_MT32_L, &PCM_MT32_H, NULL};
static const ROMInfo * const MT32_V1_06_ROMS[] = {&CTRL_MT32_V1_06, &PCM_MT32, &CTRL_MT32_V1_06_A, &CTRL_MT32_V1_06_B, &PCM_MT32_L, &PCM_MT32_H, NULL};
static const ROMInfo * const MT32_V1_07_ROMS[] = {&CTRL_MT32_V1_07, &PCM_MT32, &CTRL_MT32_V1_07_A, &CTRL_MT32_V1_07_B, &PCM_MT32_L, &PCM_MT32_H, NULL};
static const ROMInfo * const MT32_BLUER_ROMS[] = {&CTRL_MT32_BLUER, &PCM_MT32, &CTRL_MT32_BLUER_A, &CTRL_MT32_BLUER_B, &PCM_MT32_L, &PCM_MT32_H, NULL};
static const ROMInfo * const MT32_V2_03_ROMS[] = {&CTRL_MT32_V2_03, &PCM_MT32, &PCM_MT32_L, &PCM_MT32_H, NULL};
static const ROMInfo * const MT32_V2_04_ROMS[] = {&CTRL_MT32_V2_04, &PCM_MT32, &PCM_MT32_L, &PCM_MT32_H, NULL};
static const ROMInfo * const MT32_V2_06_ROMS[] = {&CTRL_MT32_V2_06, &PCM_MT32, &PCM_MT32_L, &PCM_MT32_H, NULL};
static const ROMInfo * const MT32_V2_07_ROMS[] = {&CTRL_MT32_V2_07, &PCM_MT32, &PCM_MT32_L, &PCM_MT32_H, NULL};
static const ROMInfo * const CM32L_V1_00_ROMS[] = {&CTRL_CM32L_V1_00, &PCM_CM32L, &PCM_CM32L_L, &PCM_CM32L_H, NULL};
static const ROMInfo * const CM32L_V1_02_ROMS[] = {&CTRL_CM32L_V1_02, &PCM_CM32L, &PCM_CM32L_L, &PCM_CM32L_H, NULL};
static const ROMInfo * const CM32LN_V1_00_ROMS[] = {&CTRL_CM32LN_V1_00, &PCM_CM32L, NULL};
static const ROMInfoLists romInfoLists = {
{MT32_V1_04_ROMS, _CALC_ARRAY_LENGTH(MT32_V1_04_ROMS)},
{MT32_V1_05_ROMS, _CALC_ARRAY_LENGTH(MT32_V1_05_ROMS)},
{MT32_V1_06_ROMS, _CALC_ARRAY_LENGTH(MT32_V1_06_ROMS)},
{MT32_V1_07_ROMS, _CALC_ARRAY_LENGTH(MT32_V1_07_ROMS)},
{MT32_BLUER_ROMS, _CALC_ARRAY_LENGTH(MT32_BLUER_ROMS)},
{MT32_V2_03_ROMS, _CALC_ARRAY_LENGTH(MT32_V2_03_ROMS)},
{MT32_V2_04_ROMS, _CALC_ARRAY_LENGTH(MT32_V2_04_ROMS)},
{MT32_V2_06_ROMS, _CALC_ARRAY_LENGTH(MT32_V2_06_ROMS)},
{MT32_V2_07_ROMS, _CALC_ARRAY_LENGTH(MT32_V2_07_ROMS)},
{CM32L_V1_00_ROMS, _CALC_ARRAY_LENGTH(CM32L_V1_00_ROMS)},
{CM32L_V1_02_ROMS, _CALC_ARRAY_LENGTH(CM32L_V1_02_ROMS)},
{CM32LN_V1_00_ROMS, _CALC_ARRAY_LENGTH(CM32LN_V1_00_ROMS)},
{FULL_ROM_INFOS, _CALC_ARRAY_LENGTH(FULL_ROM_INFOS)},
{PARTIAL_ROM_INFOS, _CALC_ARRAY_LENGTH(PARTIAL_ROM_INFOS)},
{ALL_ROM_INFOS, _CALC_ARRAY_LENGTH(ALL_ROM_INFOS)}
};
return romInfoLists;
}
static const ROMInfo * const *getKnownROMInfoList() {
return getROMInfoLists().allROMInfos.romInfos;
}
static const ROMInfo *getKnownROMInfoFromList(Bit32u index) {
return getKnownROMInfoList()[index];
}
const ROMInfo *ROMInfo::getROMInfo(File *file) {
return getROMInfo(file, getKnownROMInfoList());
}
const ROMInfo *ROMInfo::getROMInfo(File *file, const ROMInfo * const *romInfos) {
size_t fileSize = file->getSize();
for (Bit32u i = 0; romInfos[i] != NULL; i++) {
const ROMInfo *romInfo = romInfos[i];
if (fileSize == romInfo->fileSize && !strcmp(file->getSHA1(), romInfo->sha1Digest)) {
return romInfo;
}
}
return NULL;
}
void ROMInfo::freeROMInfo(const ROMInfo *romInfo) {
(void) romInfo;
}
const ROMInfo **ROMInfo::getROMInfoList(Bit32u types, Bit32u pairTypes) {
Bit32u romCount = getROMInfoLists().allROMInfos.itemCount; // Excludes the NULL terminator.
const ROMInfo **romInfoList = new const ROMInfo*[romCount + 1];
const ROMInfo **currentROMInList = romInfoList;
for (Bit32u i = 0; i < romCount; i++) {
const ROMInfo *romInfo = getKnownROMInfoFromList(i);
if ((types & (1 << romInfo->type)) && (pairTypes & (1 << romInfo->pairType))) {
*currentROMInList++ = romInfo;
}
}
*currentROMInList = NULL;
return romInfoList;
}
void ROMInfo::freeROMInfoList(const ROMInfo **romInfoList) {
delete[] romInfoList;
}
const ROMInfo * const *ROMInfo::getAllROMInfos(Bit32u *itemCount) {
if (itemCount != NULL) *itemCount = getROMInfoLists().allROMInfos.itemCount;
return getROMInfoLists().allROMInfos.romInfos;
}
const ROMInfo * const *ROMInfo::getFullROMInfos(Bit32u *itemCount) {
if (itemCount != NULL) *itemCount = getROMInfoLists().fullROMInfos.itemCount;
return getROMInfoLists().fullROMInfos.romInfos;
}
const ROMInfo * const *ROMInfo::getPartialROMInfos(Bit32u *itemCount) {
if (itemCount != NULL) *itemCount = getROMInfoLists().partialROMInfos.itemCount;
return getROMInfoLists().partialROMInfos.romInfos;
}
const ROMImage *ROMImage::makeFullROMImage(Bit8u *data, size_t dataSize) {
return new ROMImage(new ArrayFile(data, dataSize), true, getKnownROMInfoList());
}
const ROMImage *ROMImage::appendImages(const ROMImage *romImageLow, const ROMImage *romImageHigh) {
const Bit8u *romDataLow = romImageLow->getFile()->getData();
const Bit8u *romDataHigh = romImageHigh->getFile()->getData();
size_t partSize = romImageLow->getFile()->getSize();
Bit8u *data = new Bit8u[2 * partSize];
memcpy(data, romDataLow, partSize);
memcpy(data + partSize, romDataHigh, partSize);
const ROMImage *romImageFull = makeFullROMImage(data, 2 * partSize);
if (romImageFull->getROMInfo() == NULL) {
freeROMImage(romImageFull);
return NULL;
}
return romImageFull;
}
const ROMImage *ROMImage::interleaveImages(const ROMImage *romImageEven, const ROMImage *romImageOdd) {
const Bit8u *romDataEven = romImageEven->getFile()->getData();
const Bit8u *romDataOdd = romImageOdd->getFile()->getData();
size_t partSize = romImageEven->getFile()->getSize();
Bit8u *data = new Bit8u[2 * partSize];
Bit8u *writePtr = data;
for (size_t romDataIx = 0; romDataIx < partSize; romDataIx++) {
*(writePtr++) = romDataEven[romDataIx];
*(writePtr++) = romDataOdd[romDataIx];
}
const ROMImage *romImageFull = makeFullROMImage(data, 2 * partSize);
if (romImageFull->getROMInfo() == NULL) {
freeROMImage(romImageFull);
return NULL;
}
return romImageFull;
}
ROMImage::ROMImage(File *useFile, bool useOwnFile, const ROMInfo * const *romInfos) :
file(useFile), ownFile(useOwnFile), romInfo(ROMInfo::getROMInfo(file, romInfos))
{}
ROMImage::~ROMImage() {
ROMInfo::freeROMInfo(romInfo);
if (ownFile) {
const Bit8u *data = file->getData();
delete file;
delete[] data;
}
}
const ROMImage *ROMImage::makeROMImage(File *file) {
return new ROMImage(file, false, getKnownROMInfoList());
}
const ROMImage *ROMImage::makeROMImage(File *file, const ROMInfo * const *romInfos) {
return new ROMImage(file, false, romInfos);
}
const ROMImage *ROMImage::makeROMImage(File *file1, File *file2) {
const ROMInfo * const *partialROMInfos = getROMInfoLists().partialROMInfos.romInfos;
const ROMImage *image1 = makeROMImage(file1, partialROMInfos);
const ROMImage *image2 = makeROMImage(file2, partialROMInfos);
const ROMImage *fullImage = image1->getROMInfo() == NULL || image2->getROMInfo() == NULL ? NULL : mergeROMImages(image1, image2);
freeROMImage(image1);
freeROMImage(image2);
return fullImage;
}
void ROMImage::freeROMImage(const ROMImage *romImage) {
delete romImage;
}
const ROMImage *ROMImage::mergeROMImages(const ROMImage *romImage1, const ROMImage *romImage2) {
if (romImage1->romInfo->pairROMInfo != romImage2->romInfo) {
return NULL;
}
switch (romImage1->romInfo->pairType) {
case ROMInfo::FirstHalf:
return appendImages(romImage1, romImage2);
case ROMInfo::SecondHalf:
return appendImages(romImage2, romImage1);
case ROMInfo::Mux0:
return interleaveImages(romImage1, romImage2);
case ROMInfo::Mux1:
return interleaveImages(romImage2, romImage1);
default:
break;
}
return NULL;
}
File *ROMImage::getFile() const {
return file;
}
bool ROMImage::isFileUserProvided() const {
return !ownFile;
}
const ROMInfo *ROMImage::getROMInfo() const {
return romInfo;
}
const MachineConfiguration * const *MachineConfiguration::getAllMachineConfigurations(Bit32u *itemCount) {
static const ROMInfoLists &romInfoLists = getROMInfoLists();
static const MachineConfiguration MT32_1_04 = MachineConfiguration("mt32_1_04", romInfoLists.mt32_1_04.romInfos, romInfoLists.mt32_1_04.itemCount);
static const MachineConfiguration MT32_1_05 = MachineConfiguration("mt32_1_05", romInfoLists.mt32_1_05.romInfos, romInfoLists.mt32_1_05.itemCount);
static const MachineConfiguration MT32_1_06 = MachineConfiguration("mt32_1_06", romInfoLists.mt32_1_06.romInfos, romInfoLists.mt32_1_06.itemCount);
static const MachineConfiguration MT32_1_07 = MachineConfiguration("mt32_1_07", romInfoLists.mt32_1_07.romInfos, romInfoLists.mt32_1_07.itemCount);
static const MachineConfiguration MT32_BLUER = MachineConfiguration("mt32_bluer", romInfoLists.mt32_bluer.romInfos, romInfoLists.mt32_bluer.itemCount);
static const MachineConfiguration MT32_2_03 = MachineConfiguration("mt32_2_03", romInfoLists.mt32_2_03.romInfos, romInfoLists.mt32_2_03.itemCount);
static const MachineConfiguration MT32_2_04 = MachineConfiguration("mt32_2_04", romInfoLists.mt32_2_04.romInfos, romInfoLists.mt32_2_04.itemCount);
static const MachineConfiguration MT32_2_06 = MachineConfiguration("mt32_2_06", romInfoLists.mt32_2_06.romInfos, romInfoLists.mt32_2_06.itemCount);
static const MachineConfiguration MT32_2_07 = MachineConfiguration("mt32_2_07", romInfoLists.mt32_2_07.romInfos, romInfoLists.mt32_2_07.itemCount);
static const MachineConfiguration CM32L_1_00 = MachineConfiguration("cm32l_1_00", romInfoLists.cm32l_1_00.romInfos, romInfoLists.cm32l_1_00.itemCount);
static const MachineConfiguration CM32L_1_02 = MachineConfiguration("cm32l_1_02", romInfoLists.cm32l_1_02.romInfos, romInfoLists.cm32l_1_02.itemCount);
static const MachineConfiguration CM32LN_1_00 = MachineConfiguration("cm32ln_1_00", romInfoLists.cm32ln_1_00.romInfos, romInfoLists.cm32ln_1_00.itemCount);
static const MachineConfiguration * const MACHINE_CONFIGURATIONS[] = {
&MT32_1_04, &MT32_1_05, &MT32_1_06, &MT32_1_07, &MT32_BLUER, &MT32_2_03, &MT32_2_04, &MT32_2_06, &MT32_2_07, &CM32L_1_00, &CM32L_1_02, &CM32LN_1_00, NULL
};
if (itemCount != NULL) *itemCount = _CALC_ARRAY_LENGTH(MACHINE_CONFIGURATIONS);
return MACHINE_CONFIGURATIONS;
}
MachineConfiguration::MachineConfiguration(const char *useMachineID, const ROMInfo * const *useROMInfos, Bit32u useROMInfosCount) :
machineID(useMachineID), romInfos(useROMInfos), romInfosCount(useROMInfosCount)
{}
const char *MachineConfiguration::getMachineID() const {
return machineID;
}
const ROMInfo * const *MachineConfiguration::getCompatibleROMInfos(Bit32u *itemCount) const {
if (itemCount != NULL) *itemCount = romInfosCount;
return romInfos;
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/ROMInfo.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 6,469 |
```objective-c
/*
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Micael Hildenborg nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Micael Hildenborg ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Micael Hildenborg BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SHA1_DEFINED
#define SHA1_DEFINED
namespace sha1
{
/**
@param src points to any kind of data to be hashed.
@param bytelength the number of bytes to hash from the src pointer.
@param hash should point to a buffer of at least 20 bytes of size for storing the sha1 result in.
*/
void calc(const void* src, const int bytelength, unsigned char* hash);
/**
@param hash is 20 bytes of sha1 hash. This is the same data that is the result from the calc function.
@param hexstring should point to a buffer of at least 41 bytes of size for storing the hexadecimal representation of the hash. A zero will be written at position 40, so the buffer will be a valid zero ended string.
*/
void toHexString(const unsigned char* hash, char* hexstring);
} // namespace sha1
#endif // SHA1_DEFINED
``` | /content/code_sandbox/src/sound/munt/sha1/sha1.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 485 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstddef>
#include "internals.h"
#include "Poly.h"
#include "Part.h"
#include "Partial.h"
#include "Synth.h"
namespace MT32Emu {
Poly::Poly() {
part = NULL;
key = 255;
velocity = 255;
sustain = false;
activePartialCount = 0;
for (int i = 0; i < 4; i++) {
partials[i] = NULL;
}
state = POLY_Inactive;
next = NULL;
}
void Poly::setPart(Part *usePart) {
part = usePart;
}
void Poly::reset(unsigned int newKey, unsigned int newVelocity, bool newSustain, Partial **newPartials) {
if (isActive()) {
// This should never happen
part->getSynth()->printDebug("Resetting active poly. Active partial count: %i\n", activePartialCount);
for (int i = 0; i < 4; i++) {
if (partials[i] != NULL && partials[i]->isActive()) {
partials[i]->deactivate();
activePartialCount--;
}
}
setState(POLY_Inactive);
}
key = newKey;
velocity = newVelocity;
sustain = newSustain;
activePartialCount = 0;
for (int i = 0; i < 4; i++) {
partials[i] = newPartials[i];
if (newPartials[i] != NULL) {
activePartialCount++;
setState(POLY_Playing);
}
}
}
bool Poly::noteOff(bool pedalHeld) {
// Generally, non-sustaining instruments ignore note off. They die away eventually anyway.
// Key 0 (only used by special cases on rhythm part) reacts to note off even if non-sustaining or pedal held.
if (state == POLY_Inactive || state == POLY_Releasing) {
return false;
}
if (pedalHeld) {
if (state == POLY_Held) {
return false;
}
setState(POLY_Held);
} else {
startDecay();
}
return true;
}
bool Poly::stopPedalHold() {
if (state != POLY_Held) {
return false;
}
return startDecay();
}
bool Poly::startDecay() {
if (state == POLY_Inactive || state == POLY_Releasing) {
return false;
}
setState(POLY_Releasing);
for (int t = 0; t < 4; t++) {
Partial *partial = partials[t];
if (partial != NULL) {
partial->startDecayAll();
}
}
return true;
}
bool Poly::startAbort() {
if (state == POLY_Inactive || part->getSynth()->isAbortingPoly()) {
return false;
}
for (int t = 0; t < 4; t++) {
Partial *partial = partials[t];
if (partial != NULL) {
partial->startAbort();
part->getSynth()->abortingPoly = this;
}
}
return true;
}
void Poly::setState(PolyState newState) {
if (state == newState) return;
PolyState oldState = state;
state = newState;
part->polyStateChanged(oldState, newState);
}
void Poly::backupCacheToPartials(PatchCache cache[4]) {
for (int partialNum = 0; partialNum < 4; partialNum++) {
Partial *partial = partials[partialNum];
if (partial != NULL) {
partial->backupCache(cache[partialNum]);
}
}
}
/**
* Returns the internal key identifier.
* For non-rhythm, this is within the range 12 to 108.
* For rhythm on MT-32, this is 0 or 1 (special cases) or within the range 24 to 87.
* For rhythm on devices with extended PCM sounds (e.g. CM-32L), this is 0, 1 or 24 to 108
*/
unsigned int Poly::getKey() const {
return key;
}
unsigned int Poly::getVelocity() const {
return velocity;
}
bool Poly::canSustain() const {
return sustain;
}
PolyState Poly::getState() const {
return state;
}
unsigned int Poly::getActivePartialCount() const {
return activePartialCount;
}
bool Poly::isActive() const {
return state != POLY_Inactive;
}
// This is called by Partial to inform the poly that the Partial has deactivated
void Poly::partialDeactivated(Partial *partial) {
for (int i = 0; i < 4; i++) {
if (partials[i] == partial) {
partials[i] = NULL;
activePartialCount--;
}
}
if (activePartialCount == 0) {
setState(POLY_Inactive);
if (part->getSynth()->abortingPoly == this) {
part->getSynth()->abortingPoly = NULL;
}
}
part->partialDeactivated(this);
}
Poly *Poly::getNext() const {
return next;
}
void Poly::setNext(Poly *poly) {
next = poly;
}
} // namespace MT32Emu
``` | /content/code_sandbox/src/sound/munt/Poly.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,228 |
```c++
/*
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Micael Hildenborg nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Micael Hildenborg ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Micael Hildenborg BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Contributors:
Gustav
Several members in the gamedev.se forum.
Gregory Petrosyan
*/
#include "sha1.h"
namespace sha1
{
namespace // local
{
// Rotate an integer value to left.
inline unsigned int rol(const unsigned int value,
const unsigned int steps)
{
return ((value << steps) | (value >> (32 - steps)));
}
// Sets the first 16 integers in the buffert to zero.
// Used for clearing the W buffert.
inline void clearWBuffert(unsigned int* buffert)
{
for (int pos = 16; --pos >= 0;)
{
buffert[pos] = 0;
}
}
void innerHash(unsigned int* result, unsigned int* w)
{
unsigned int a = result[0];
unsigned int b = result[1];
unsigned int c = result[2];
unsigned int d = result[3];
unsigned int e = result[4];
int round = 0;
#define sha1macro(func,val) \
{ \
const unsigned int t = rol(a, 5) + (func) + e + val + w[round]; \
e = d; \
d = c; \
c = rol(b, 30); \
b = a; \
a = t; \
}
while (round < 16)
{
sha1macro((b & c) | (~b & d), 0x5a827999)
++round;
}
while (round < 20)
{
w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
sha1macro((b & c) | (~b & d), 0x5a827999)
++round;
}
while (round < 40)
{
w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
sha1macro(b ^ c ^ d, 0x6ed9eba1)
++round;
}
while (round < 60)
{
w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
sha1macro((b & c) | (b & d) | (c & d), 0x8f1bbcdc)
++round;
}
while (round < 80)
{
w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
sha1macro(b ^ c ^ d, 0xca62c1d6)
++round;
}
#undef sha1macro
result[0] += a;
result[1] += b;
result[2] += c;
result[3] += d;
result[4] += e;
}
} // namespace
void calc(const void* src, const int bytelength, unsigned char* hash)
{
// Init the result array.
unsigned int result[5] = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 };
// Cast the void src pointer to be the byte array we can work with.
const unsigned char* sarray = static_cast<const unsigned char*>(src);
// The reusable round buffer
unsigned int w[80];
// Loop through all complete 64byte blocks.
const int endOfFullBlocks = bytelength - 64;
int endCurrentBlock;
int currentBlock = 0;
while (currentBlock <= endOfFullBlocks)
{
endCurrentBlock = currentBlock + 64;
// Init the round buffer with the 64 byte block data.
for (int roundPos = 0; currentBlock < endCurrentBlock; currentBlock += 4)
{
// This line will swap endian on big endian and keep endian on little endian.
w[roundPos++] = static_cast<unsigned int>(sarray[currentBlock + 3])
| (static_cast<unsigned int>(sarray[currentBlock + 2]) << 8)
| (static_cast<unsigned int>(sarray[currentBlock + 1]) << 16)
| (static_cast<unsigned int>(sarray[currentBlock]) << 24);
}
innerHash(result, w);
}
// Handle the last and not full 64 byte block if existing.
endCurrentBlock = bytelength - currentBlock;
clearWBuffert(w);
int lastBlockBytes = 0;
for (;lastBlockBytes < endCurrentBlock; ++lastBlockBytes)
{
w[lastBlockBytes >> 2] |= static_cast<unsigned int>(sarray[lastBlockBytes + currentBlock]) << ((3 - (lastBlockBytes & 3)) << 3);
}
w[lastBlockBytes >> 2] |= 0x80 << ((3 - (lastBlockBytes & 3)) << 3);
if (endCurrentBlock >= 56)
{
innerHash(result, w);
clearWBuffert(w);
}
w[15] = bytelength << 3;
innerHash(result, w);
// Store hash in result pointer, and make sure we get in in the correct order on both endian models.
for (int hashByte = 20; --hashByte >= 0;)
{
hash[hashByte] = (result[hashByte >> 2] >> (((3 - hashByte) & 0x3) << 3)) & 0xff;
}
}
void toHexString(const unsigned char* hash, char* hexstring)
{
const char hexDigits[] = { "0123456789abcdef" };
for (int hashByte = 20; --hashByte >= 0;)
{
hexstring[hashByte << 1] = hexDigits[(hash[hashByte] >> 4) & 0xf];
hexstring[(hashByte << 1) + 1] = hexDigits[hash[hashByte] & 0xf];
}
hexstring[40] = 0;
}
} // namespace sha1
``` | /content/code_sandbox/src/sound/munt/sha1/sha1.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,723 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_C_TYPES_H
#define MT32EMU_C_TYPES_H
#include <stdarg.h>
#include <stddef.h>
#include "../globals.h"
#define MT32EMU_C_ENUMERATIONS
#include "../Enumerations.h"
#undef MT32EMU_C_ENUMERATIONS
#ifdef _WIN32
# define MT32EMU_C_CALL __cdecl
#else
# define MT32EMU_C_CALL
#endif
typedef unsigned int mt32emu_bit32u;
typedef signed int mt32emu_bit32s;
typedef unsigned short int mt32emu_bit16u;
typedef signed short int mt32emu_bit16s;
typedef unsigned char mt32emu_bit8u;
typedef signed char mt32emu_bit8s;
typedef char mt32emu_sha1_digest[41];
typedef enum {
MT32EMU_BOOL_FALSE, MT32EMU_BOOL_TRUE
} mt32emu_boolean;
typedef enum {
/* Operation completed normally. */
MT32EMU_RC_OK = 0,
MT32EMU_RC_ADDED_CONTROL_ROM = 1,
MT32EMU_RC_ADDED_PCM_ROM = 2,
MT32EMU_RC_ADDED_PARTIAL_CONTROL_ROM = 3,
MT32EMU_RC_ADDED_PARTIAL_PCM_ROM = 4,
/* Definite error occurred. */
MT32EMU_RC_ROM_NOT_IDENTIFIED = -1,
MT32EMU_RC_FILE_NOT_FOUND = -2,
MT32EMU_RC_FILE_NOT_LOADED = -3,
MT32EMU_RC_MISSING_ROMS = -4,
MT32EMU_RC_NOT_OPENED = -5,
MT32EMU_RC_QUEUE_FULL = -6,
MT32EMU_RC_ROMS_NOT_PAIRABLE = -7,
MT32EMU_RC_MACHINE_NOT_IDENTIFIED = -8,
/* Undefined error occurred. */
MT32EMU_RC_FAILED = -100
} mt32emu_return_code;
/** Emulation context */
typedef struct mt32emu_data *mt32emu_context;
typedef const struct mt32emu_data *mt32emu_const_context;
/* Convenience aliases */
#ifndef __cplusplus
typedef enum mt32emu_analog_output_mode mt32emu_analog_output_mode;
typedef enum mt32emu_dac_input_mode mt32emu_dac_input_mode;
typedef enum mt32emu_midi_delay_mode mt32emu_midi_delay_mode;
typedef enum mt32emu_partial_state mt32emu_partial_state;
typedef enum mt32emu_samplerate_conversion_quality mt32emu_samplerate_conversion_quality;
typedef enum mt32emu_renderer_type mt32emu_renderer_type;
#endif
/** Contains identifiers and descriptions of ROM files being used. */
typedef struct {
const char *control_rom_id;
const char *control_rom_description;
const char *control_rom_sha1_digest;
const char *pcm_rom_id;
const char *pcm_rom_description;
const char *pcm_rom_sha1_digest;
} mt32emu_rom_info;
/** Set of multiplexed output bit16s streams appeared at the DAC entrance. */
typedef struct {
mt32emu_bit16s *nonReverbLeft;
mt32emu_bit16s *nonReverbRight;
mt32emu_bit16s *reverbDryLeft;
mt32emu_bit16s *reverbDryRight;
mt32emu_bit16s *reverbWetLeft;
mt32emu_bit16s *reverbWetRight;
} mt32emu_dac_output_bit16s_streams;
/** Set of multiplexed output float streams appeared at the DAC entrance. */
typedef struct {
float *nonReverbLeft;
float *nonReverbRight;
float *reverbDryLeft;
float *reverbDryRight;
float *reverbWetLeft;
float *reverbWetRight;
} mt32emu_dac_output_float_streams;
/* === Interface handling === */
/** Report handler interface versions */
typedef enum {
MT32EMU_REPORT_HANDLER_VERSION_0 = 0,
MT32EMU_REPORT_HANDLER_VERSION_1 = 1,
MT32EMU_REPORT_HANDLER_VERSION_CURRENT = MT32EMU_REPORT_HANDLER_VERSION_1
} mt32emu_report_handler_version;
/** MIDI receiver interface versions */
typedef enum {
MT32EMU_MIDI_RECEIVER_VERSION_0 = 0,
MT32EMU_MIDI_RECEIVER_VERSION_CURRENT = MT32EMU_MIDI_RECEIVER_VERSION_0
} mt32emu_midi_receiver_version;
/** Synth interface versions */
typedef enum {
MT32EMU_SERVICE_VERSION_0 = 0,
MT32EMU_SERVICE_VERSION_1 = 1,
MT32EMU_SERVICE_VERSION_2 = 2,
MT32EMU_SERVICE_VERSION_3 = 3,
MT32EMU_SERVICE_VERSION_4 = 4,
MT32EMU_SERVICE_VERSION_5 = 5,
MT32EMU_SERVICE_VERSION_6 = 6,
MT32EMU_SERVICE_VERSION_CURRENT = MT32EMU_SERVICE_VERSION_6
} mt32emu_service_version;
/* === Report Handler Interface === */
typedef union mt32emu_report_handler_i mt32emu_report_handler_i;
/** Interface for handling reported events (initial version) */
#define MT32EMU_REPORT_HANDLER_I_V0 \
/** Returns the actual interface version ID */ \
mt32emu_report_handler_version (MT32EMU_C_CALL *getVersionID)(mt32emu_report_handler_i i); \
\
/** Callback for debug messages, in vprintf() format */ \
void (MT32EMU_C_CALL *printDebug)(void *instance_data, const char *fmt, va_list list); \
/** Callbacks for reporting errors */ \
void (MT32EMU_C_CALL *onErrorControlROM)(void *instance_data); \
void (MT32EMU_C_CALL *onErrorPCMROM)(void *instance_data); \
/** Callback for reporting about displaying a new custom message on LCD */ \
void (MT32EMU_C_CALL *showLCDMessage)(void *instance_data, const char *message); \
/** Callback for reporting actual processing of a MIDI message */ \
void (MT32EMU_C_CALL *onMIDIMessagePlayed)(void *instance_data); \
/**
* Callback for reporting an overflow of the input MIDI queue.
* Returns MT32EMU_BOOL_TRUE if a recovery action was taken
* and yet another attempt to enqueue the MIDI event is desired.
*/ \
mt32emu_boolean (MT32EMU_C_CALL *onMIDIQueueOverflow)(void *instance_data); \
/**
* Callback invoked when a System Realtime MIDI message is detected in functions
* mt32emu_parse_stream and mt32emu_play_short_message and the likes.
*/ \
void (MT32EMU_C_CALL *onMIDISystemRealtime)(void *instance_data, mt32emu_bit8u system_realtime); \
/** Callbacks for reporting system events */ \
void (MT32EMU_C_CALL *onDeviceReset)(void *instance_data); \
void (MT32EMU_C_CALL *onDeviceReconfig)(void *instance_data); \
/** Callbacks for reporting changes of reverb settings */ \
void (MT32EMU_C_CALL *onNewReverbMode)(void *instance_data, mt32emu_bit8u mode); \
void (MT32EMU_C_CALL *onNewReverbTime)(void *instance_data, mt32emu_bit8u time); \
void (MT32EMU_C_CALL *onNewReverbLevel)(void *instance_data, mt32emu_bit8u level); \
/** Callbacks for reporting various information */ \
void (MT32EMU_C_CALL *onPolyStateChanged)(void *instance_data, mt32emu_bit8u part_num); \
void (MT32EMU_C_CALL *onProgramChanged)(void *instance_data, mt32emu_bit8u part_num, const char *sound_group_name, const char *patch_name);
#define MT32EMU_REPORT_HANDLER_I_V1 \
/**
* Invoked to signal about a change of the emulated LCD state. Use mt32emu_get_display_state to retrieve the actual data.
* This callback will not be invoked on further changes, until the client retrieves the LCD state.
*/ \
void (MT32EMU_C_CALL *onLCDStateUpdated)(void *instance_data); \
/** Invoked when the emulated MIDI MESSAGE LED changes state. The led_state parameter represents whether the LED is ON. */ \
void (MT32EMU_C_CALL *onMidiMessageLEDStateUpdated)(void *instance_data, mt32emu_boolean led_state);
typedef struct {
MT32EMU_REPORT_HANDLER_I_V0
} mt32emu_report_handler_i_v0;
typedef struct {
MT32EMU_REPORT_HANDLER_I_V0
MT32EMU_REPORT_HANDLER_I_V1
} mt32emu_report_handler_i_v1;
/**
* Extensible interface for handling reported events.
* Union intended to view an interface of any subsequent version as any parent interface not requiring a cast.
* It is caller's responsibility to check the actual interface version in runtime using the getVersionID() method.
*/
union mt32emu_report_handler_i {
const mt32emu_report_handler_i_v0 *v0;
const mt32emu_report_handler_i_v1 *v1;
};
#undef MT32EMU_REPORT_HANDLER_I_V0
#undef MT32EMU_REPORT_HANDLER_I_V1
/* === MIDI Receiver Interface === */
typedef union mt32emu_midi_receiver_i mt32emu_midi_receiver_i;
/** Interface for receiving MIDI messages generated by MIDI stream parser (initial version) */
typedef struct {
/** Returns the actual interface version ID */
mt32emu_midi_receiver_version (MT32EMU_C_CALL *getVersionID)(mt32emu_midi_receiver_i i);
/** Invoked when a complete short MIDI message is parsed in the input MIDI stream. */
void (MT32EMU_C_CALL *handleShortMessage)(void *instance_data, const mt32emu_bit32u message);
/** Invoked when a complete well-formed System Exclusive MIDI message is parsed in the input MIDI stream. */
void (MT32EMU_C_CALL *handleSysex)(void *instance_data, const mt32emu_bit8u stream[], const mt32emu_bit32u length);
/** Invoked when a System Realtime MIDI message is parsed in the input MIDI stream. */
void (MT32EMU_C_CALL *handleSystemRealtimeMessage)(void *instance_data, const mt32emu_bit8u realtime);
} mt32emu_midi_receiver_i_v0;
/**
* Extensible interface for receiving MIDI messages.
* Union intended to view an interface of any subsequent version as any parent interface not requiring a cast.
* It is caller's responsibility to check the actual interface version in runtime using the getVersionID() method.
*/
union mt32emu_midi_receiver_i {
const mt32emu_midi_receiver_i_v0 *v0;
};
/* === Service Interface === */
typedef union mt32emu_service_i mt32emu_service_i;
/**
* Basic interface that defines all the library services (initial version).
* The members closely resemble C functions declared in c_interface.h, and the intention is to provide for easier
* access when the library is dynamically loaded in run-time, e.g. as a plugin. This way the client only needs
* to bind to mt32emu_get_service_i() function instead of binding to each function it needs to use.
* See c_interface.h for parameter description.
*/
#define MT32EMU_SERVICE_I_V0 \
/** Returns the actual interface version ID */ \
mt32emu_service_version (MT32EMU_C_CALL *getVersionID)(mt32emu_service_i i); \
mt32emu_report_handler_version (MT32EMU_C_CALL *getSupportedReportHandlerVersionID)(void); \
mt32emu_midi_receiver_version (MT32EMU_C_CALL *getSupportedMIDIReceiverVersionID)(void); \
\
mt32emu_bit32u (MT32EMU_C_CALL *getLibraryVersionInt)(void); \
const char *(MT32EMU_C_CALL *getLibraryVersionString)(void); \
\
mt32emu_bit32u (MT32EMU_C_CALL *getStereoOutputSamplerate)(const mt32emu_analog_output_mode analog_output_mode); \
\
mt32emu_context (MT32EMU_C_CALL *createContext)(mt32emu_report_handler_i report_handler, void *instance_data); \
void (MT32EMU_C_CALL *freeContext)(mt32emu_context context); \
mt32emu_return_code (MT32EMU_C_CALL *addROMData)(mt32emu_context context, const mt32emu_bit8u *data, size_t data_size, const mt32emu_sha1_digest *sha1_digest); \
mt32emu_return_code (MT32EMU_C_CALL *addROMFile)(mt32emu_context context, const char *filename); \
void (MT32EMU_C_CALL *getROMInfo)(mt32emu_const_context context, mt32emu_rom_info *rom_info); \
void (MT32EMU_C_CALL *setPartialCount)(mt32emu_context context, const mt32emu_bit32u partial_count); \
void (MT32EMU_C_CALL *setAnalogOutputMode)(mt32emu_context context, const mt32emu_analog_output_mode analog_output_mode); \
mt32emu_return_code (MT32EMU_C_CALL *openSynth)(mt32emu_const_context context); \
void (MT32EMU_C_CALL *closeSynth)(mt32emu_const_context context); \
mt32emu_boolean (MT32EMU_C_CALL *isOpen)(mt32emu_const_context context); \
mt32emu_bit32u (MT32EMU_C_CALL *getActualStereoOutputSamplerate)(mt32emu_const_context context); \
void (MT32EMU_C_CALL *flushMIDIQueue)(mt32emu_const_context context); \
mt32emu_bit32u (MT32EMU_C_CALL *setMIDIEventQueueSize)(mt32emu_const_context context, const mt32emu_bit32u queue_size); \
void (MT32EMU_C_CALL *setMIDIReceiver)(mt32emu_context context, mt32emu_midi_receiver_i midi_receiver, void *instance_data); \
\
void (MT32EMU_C_CALL *parseStream)(mt32emu_const_context context, const mt32emu_bit8u *stream, mt32emu_bit32u length); \
void (MT32EMU_C_CALL *parseStream_At)(mt32emu_const_context context, const mt32emu_bit8u *stream, mt32emu_bit32u length, mt32emu_bit32u timestamp); \
void (MT32EMU_C_CALL *playShortMessage)(mt32emu_const_context context, mt32emu_bit32u message); \
void (MT32EMU_C_CALL *playShortMessageAt)(mt32emu_const_context context, mt32emu_bit32u message, mt32emu_bit32u timestamp); \
mt32emu_return_code (MT32EMU_C_CALL *playMsg)(mt32emu_const_context context, mt32emu_bit32u msg); \
mt32emu_return_code (MT32EMU_C_CALL *playSysex)(mt32emu_const_context context, const mt32emu_bit8u *sysex, mt32emu_bit32u len); \
mt32emu_return_code (MT32EMU_C_CALL *playMsgAt)(mt32emu_const_context context, mt32emu_bit32u msg, mt32emu_bit32u timestamp); \
mt32emu_return_code (MT32EMU_C_CALL *playSysexAt)(mt32emu_const_context context, const mt32emu_bit8u *sysex, mt32emu_bit32u len, mt32emu_bit32u timestamp); \
\
void (MT32EMU_C_CALL *playMsgNow)(mt32emu_const_context context, mt32emu_bit32u msg); \
void (MT32EMU_C_CALL *playMsgOnPart)(mt32emu_const_context context, mt32emu_bit8u part, mt32emu_bit8u code, mt32emu_bit8u note, mt32emu_bit8u velocity); \
void (MT32EMU_C_CALL *playSysexNow)(mt32emu_const_context context, const mt32emu_bit8u *sysex, mt32emu_bit32u len); \
void (MT32EMU_C_CALL *writeSysex)(mt32emu_const_context context, mt32emu_bit8u channel, const mt32emu_bit8u *sysex, mt32emu_bit32u len); \
\
void (MT32EMU_C_CALL *setReverbEnabled)(mt32emu_const_context context, const mt32emu_boolean reverb_enabled); \
mt32emu_boolean (MT32EMU_C_CALL *isReverbEnabled)(mt32emu_const_context context); \
void (MT32EMU_C_CALL *setReverbOverridden)(mt32emu_const_context context, const mt32emu_boolean reverb_overridden); \
mt32emu_boolean (MT32EMU_C_CALL *isReverbOverridden)(mt32emu_const_context context); \
void (MT32EMU_C_CALL *setReverbCompatibilityMode)(mt32emu_const_context context, const mt32emu_boolean mt32_compatible_mode); \
mt32emu_boolean (MT32EMU_C_CALL *isMT32ReverbCompatibilityMode)(mt32emu_const_context context); \
mt32emu_boolean (MT32EMU_C_CALL *isDefaultReverbMT32Compatible)(mt32emu_const_context context); \
\
void (MT32EMU_C_CALL *setDACInputMode)(mt32emu_const_context context, const mt32emu_dac_input_mode mode); \
mt32emu_dac_input_mode (MT32EMU_C_CALL *getDACInputMode)(mt32emu_const_context context); \
\
void (MT32EMU_C_CALL *setMIDIDelayMode)(mt32emu_const_context context, const mt32emu_midi_delay_mode mode); \
mt32emu_midi_delay_mode (MT32EMU_C_CALL *getMIDIDelayMode)(mt32emu_const_context context); \
\
void (MT32EMU_C_CALL *setOutputGain)(mt32emu_const_context context, float gain); \
float (MT32EMU_C_CALL *getOutputGain)(mt32emu_const_context context); \
void (MT32EMU_C_CALL *setReverbOutputGain)(mt32emu_const_context context, float gain); \
float (MT32EMU_C_CALL *getReverbOutputGain)(mt32emu_const_context context); \
\
void (MT32EMU_C_CALL *setReversedStereoEnabled)(mt32emu_const_context context, const mt32emu_boolean enabled); \
mt32emu_boolean (MT32EMU_C_CALL *isReversedStereoEnabled)(mt32emu_const_context context); \
\
void (MT32EMU_C_CALL *renderBit16s)(mt32emu_const_context context, mt32emu_bit16s *stream, mt32emu_bit32u len); \
void (MT32EMU_C_CALL *renderFloat)(mt32emu_const_context context, float *stream, mt32emu_bit32u len); \
void (MT32EMU_C_CALL *renderBit16sStreams)(mt32emu_const_context context, const mt32emu_dac_output_bit16s_streams *streams, mt32emu_bit32u len); \
void (MT32EMU_C_CALL *renderFloatStreams)(mt32emu_const_context context, const mt32emu_dac_output_float_streams *streams, mt32emu_bit32u len); \
\
mt32emu_boolean (MT32EMU_C_CALL *hasActivePartials)(mt32emu_const_context context); \
mt32emu_boolean (MT32EMU_C_CALL *isActive)(mt32emu_const_context context); \
mt32emu_bit32u (MT32EMU_C_CALL *getPartialCount)(mt32emu_const_context context); \
mt32emu_bit32u (MT32EMU_C_CALL *getPartStates)(mt32emu_const_context context); \
void (MT32EMU_C_CALL *getPartialStates)(mt32emu_const_context context, mt32emu_bit8u *partial_states); \
mt32emu_bit32u (MT32EMU_C_CALL *getPlayingNotes)(mt32emu_const_context context, mt32emu_bit8u part_number, mt32emu_bit8u *keys, mt32emu_bit8u *velocities); \
const char *(MT32EMU_C_CALL *getPatchName)(mt32emu_const_context context, mt32emu_bit8u part_number); \
void (MT32EMU_C_CALL *readMemory)(mt32emu_const_context context, mt32emu_bit32u addr, mt32emu_bit32u len, mt32emu_bit8u *data);
#define MT32EMU_SERVICE_I_V1 \
mt32emu_analog_output_mode (MT32EMU_C_CALL *getBestAnalogOutputMode)(const double target_samplerate); \
void (MT32EMU_C_CALL *setStereoOutputSampleRate)(mt32emu_context context, const double samplerate); \
void (MT32EMU_C_CALL *setSamplerateConversionQuality)(mt32emu_context context, const mt32emu_samplerate_conversion_quality quality); \
void (MT32EMU_C_CALL *selectRendererType)(mt32emu_context context, mt32emu_renderer_type renderer_type); \
mt32emu_renderer_type (MT32EMU_C_CALL *getSelectedRendererType)(mt32emu_context context); \
mt32emu_bit32u (MT32EMU_C_CALL *convertOutputToSynthTimestamp)(mt32emu_const_context context, mt32emu_bit32u output_timestamp); \
mt32emu_bit32u (MT32EMU_C_CALL *convertSynthToOutputTimestamp)(mt32emu_const_context context, mt32emu_bit32u synth_timestamp);
#define MT32EMU_SERVICE_I_V2 \
mt32emu_bit32u (MT32EMU_C_CALL *getInternalRenderedSampleCount)(mt32emu_const_context context); \
void (MT32EMU_C_CALL *setNiceAmpRampEnabled)(mt32emu_const_context context, const mt32emu_boolean enabled); \
mt32emu_boolean (MT32EMU_C_CALL *isNiceAmpRampEnabled)(mt32emu_const_context context);
#define MT32EMU_SERVICE_I_V3 \
void (MT32EMU_C_CALL *setNicePanningEnabled)(mt32emu_const_context context, const mt32emu_boolean enabled); \
mt32emu_boolean (MT32EMU_C_CALL *isNicePanningEnabled)(mt32emu_const_context context); \
void (MT32EMU_C_CALL *setNicePartialMixingEnabled)(mt32emu_const_context context, const mt32emu_boolean enabled); \
mt32emu_boolean (MT32EMU_C_CALL *isNicePartialMixingEnabled)(mt32emu_const_context context); \
void (MT32EMU_C_CALL *preallocateReverbMemory)(mt32emu_const_context context, const mt32emu_boolean enabled); \
void (MT32EMU_C_CALL *configureMIDIEventQueueSysexStorage)(mt32emu_const_context context, const mt32emu_bit32u storage_buffer_size);
#define MT32EMU_SERVICE_I_V4 \
size_t (MT32EMU_C_CALL *getMachineIDs)(const char **machine_ids, size_t machine_ids_size); \
size_t (MT32EMU_C_CALL *getROMIDs)(const char **rom_ids, size_t rom_ids_size, const char *machine_id); \
mt32emu_return_code (MT32EMU_C_CALL *identifyROMData)(mt32emu_rom_info *rom_info, const mt32emu_bit8u *data, size_t data_size, const char *machine_id); \
mt32emu_return_code (MT32EMU_C_CALL *identifyROMFile)(mt32emu_rom_info *rom_info, const char *filename, const char *machine_id); \
\
mt32emu_return_code (MT32EMU_C_CALL *mergeAndAddROMData)(mt32emu_context context, const mt32emu_bit8u *part1_data, size_t part1_data_size, const mt32emu_sha1_digest *part1_sha1_digest, const mt32emu_bit8u *part2_data, size_t part2_data_size, const mt32emu_sha1_digest *part2_sha1_digest); \
mt32emu_return_code (MT32EMU_C_CALL *mergeAndAddROMFiles)(mt32emu_context context, const char *part1_filename, const char *part2_filename); \
mt32emu_return_code (MT32EMU_C_CALL *addMachineROMFile)(mt32emu_context context, const char *machine_id, const char *filename);
#define MT32EMU_SERVICE_I_V5 \
mt32emu_boolean (MT32EMU_C_CALL *getDisplayState)(mt32emu_const_context context, char *target_buffer, const mt32emu_boolean narrow_lcd); \
void (MT32EMU_C_CALL *setMainDisplayMode)(mt32emu_const_context context); \
void (MT32EMU_C_CALL *setDisplayCompatibility)(mt32emu_const_context context, mt32emu_boolean old_mt32_compatibility_enabled); \
mt32emu_boolean (MT32EMU_C_CALL *isDisplayOldMT32Compatible)(mt32emu_const_context context); \
mt32emu_boolean (MT32EMU_C_CALL *isDefaultDisplayOldMT32Compatible)(mt32emu_const_context context); \
void (MT32EMU_C_CALL *setPartVolumeOverride)(mt32emu_const_context context, mt32emu_bit8u part_number, mt32emu_bit8u volume_override); \
mt32emu_bit8u (MT32EMU_C_CALL *getPartVolumeOverride)(mt32emu_const_context context, mt32emu_bit8u part_number);
#define MT32EMU_SERVICE_I_V6 \
mt32emu_boolean (MT32EMU_C_CALL *getSoundGroupName)(mt32emu_const_context context, char *sound_group_name, mt32emu_bit8u timbre_group, mt32emu_bit8u timbre_number); \
mt32emu_boolean (MT32EMU_C_CALL *getSoundName)(mt32emu_const_context context, char *sound_name, mt32emu_bit8u timbre_group, mt32emu_bit8u timbre_number);
typedef struct {
MT32EMU_SERVICE_I_V0
} mt32emu_service_i_v0;
typedef struct {
MT32EMU_SERVICE_I_V0
MT32EMU_SERVICE_I_V1
} mt32emu_service_i_v1;
typedef struct {
MT32EMU_SERVICE_I_V0
MT32EMU_SERVICE_I_V1
MT32EMU_SERVICE_I_V2
} mt32emu_service_i_v2;
typedef struct {
MT32EMU_SERVICE_I_V0
MT32EMU_SERVICE_I_V1
MT32EMU_SERVICE_I_V2
MT32EMU_SERVICE_I_V3
} mt32emu_service_i_v3;
typedef struct {
MT32EMU_SERVICE_I_V0
MT32EMU_SERVICE_I_V1
MT32EMU_SERVICE_I_V2
MT32EMU_SERVICE_I_V3
MT32EMU_SERVICE_I_V4
} mt32emu_service_i_v4;
typedef struct {
MT32EMU_SERVICE_I_V0
MT32EMU_SERVICE_I_V1
MT32EMU_SERVICE_I_V2
MT32EMU_SERVICE_I_V3
MT32EMU_SERVICE_I_V4
MT32EMU_SERVICE_I_V5
} mt32emu_service_i_v5;
typedef struct {
MT32EMU_SERVICE_I_V0
MT32EMU_SERVICE_I_V1
MT32EMU_SERVICE_I_V2
MT32EMU_SERVICE_I_V3
MT32EMU_SERVICE_I_V4
MT32EMU_SERVICE_I_V5
MT32EMU_SERVICE_I_V6
} mt32emu_service_i_v6;
/**
* Extensible interface for all the library services.
* Union intended to view an interface of any subsequent version as any parent interface not requiring a cast.
* It is caller's responsibility to check the actual interface version in runtime using the getVersionID() method.
*/
union mt32emu_service_i {
const mt32emu_service_i_v0 *v0;
const mt32emu_service_i_v1 *v1;
const mt32emu_service_i_v2 *v2;
const mt32emu_service_i_v3 *v3;
const mt32emu_service_i_v4 *v4;
const mt32emu_service_i_v5 *v5;
const mt32emu_service_i_v6 *v6;
};
#undef MT32EMU_SERVICE_I_V0
#undef MT32EMU_SERVICE_I_V1
#undef MT32EMU_SERVICE_I_V2
#undef MT32EMU_SERVICE_I_V3
#undef MT32EMU_SERVICE_I_V4
#undef MT32EMU_SERVICE_I_V5
#undef MT32EMU_SERVICE_I_V6
#endif /* #ifndef MT32EMU_C_TYPES_H */
``` | /content/code_sandbox/src/sound/munt/c_interface/c_types.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 6,114 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_C_INTERFACE_H
#define MT32EMU_C_INTERFACE_H
#include <stddef.h>
#include "../globals.h"
#include "c_types.h"
#undef MT32EMU_EXPORT
#undef MT32EMU_EXPORT_V
#define MT32EMU_EXPORT MT32EMU_EXPORT_ATTRIBUTE
#define MT32EMU_EXPORT_V(symbol_version_tag) MT32EMU_EXPORT
#ifdef __cplusplus
extern "C" {
#endif
/* == Context-independent functions == */
/* === Interface handling === */
/** Returns mt32emu_service_i interface. */
MT32EMU_EXPORT mt32emu_service_i MT32EMU_C_CALL mt32emu_get_service_i(void);
#if MT32EMU_EXPORTS_TYPE == 2
#undef MT32EMU_EXPORT
#undef MT32EMU_EXPORT_V
#define MT32EMU_EXPORT
#define MT32EMU_EXPORT_V(symbol_version_tag) MT32EMU_EXPORT
#endif
/**
* Returns the version ID of mt32emu_report_handler_i interface the library has been compiled with.
* This allows a client to fall-back gracefully instead of silently not receiving expected event reports.
*/
MT32EMU_EXPORT mt32emu_report_handler_version MT32EMU_C_CALL mt32emu_get_supported_report_handler_version(void);
/**
* Returns the version ID of mt32emu_midi_receiver_version_i interface the library has been compiled with.
* This allows a client to fall-back gracefully instead of silently not receiving expected MIDI messages.
*/
MT32EMU_EXPORT mt32emu_midi_receiver_version MT32EMU_C_CALL mt32emu_get_supported_midi_receiver_version(void);
/* === Utility === */
/**
* Returns library version as an integer in format: 0x00MMmmpp, where:
* MM - major version number
* mm - minor version number
* pp - patch number
*/
MT32EMU_EXPORT mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_library_version_int(void);
/**
* Returns library version as a C-string in format: "MAJOR.MINOR.PATCH".
*/
MT32EMU_EXPORT const char * MT32EMU_C_CALL mt32emu_get_library_version_string(void);
/**
* Returns output sample rate used in emulation of stereo analog circuitry of hardware units for particular analog_output_mode.
* See comment for mt32emu_analog_output_mode.
*/
MT32EMU_EXPORT mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_stereo_output_samplerate(const mt32emu_analog_output_mode analog_output_mode);
/**
* Returns the value of analog_output_mode for which the output signal may retain its full frequency spectrum
* at the sample rate specified by the target_samplerate argument.
* See comment for mt32emu_analog_output_mode.
*/
MT32EMU_EXPORT mt32emu_analog_output_mode MT32EMU_C_CALL mt32emu_get_best_analog_output_mode(const double target_samplerate);
/* === ROM handling === */
/**
* Retrieves a list of identifiers (as C-strings) of supported machines. Argument machine_ids points to the array of size
* machine_ids_size to be filled.
* Returns the number of identifiers available for retrieval. The size of the target array to be allocated can be found
* by passing NULL in argument machine_ids; argument machine_ids_size is ignored in this case.
*/
MT32EMU_EXPORT_V(2.5) size_t MT32EMU_C_CALL mt32emu_get_machine_ids(const char **machine_ids, size_t machine_ids_size);
/**
* Retrieves a list of identifiers (as C-strings) of supported ROM images. Argument rom_ids points to the array of size
* rom_ids_size to be filled. Optional argument machine_id can be used to indicate a specific machine to retrieve ROM identifiers
* for; if NULL, identifiers of all the ROM images supported by the emulation engine are retrieved.
* Returns the number of ROM identifiers available for retrieval. The size of the target array to be allocated can be found
* by passing NULL in argument rom_ids; argument rom_ids_size is ignored in this case. If argument machine_id contains
* an unrecognised value, 0 is returned.
*/
MT32EMU_EXPORT_V(2.5) size_t MT32EMU_C_CALL mt32emu_get_rom_ids(const char **rom_ids, size_t rom_ids_size, const char *machine_id);
/**
* Identifies a ROM image the provided data array contains by its SHA1 digest. Optional argument machine_id can be used to indicate
* a specific machine to identify the ROM image for; if NULL, the ROM image is identified for any supported machine.
* A mt32emu_rom_info structure supplied in argument rom_info is filled in accordance with the provided ROM image; unused fields
* are filled with NULLs. If the content of the ROM image is not identified successfully (e.g. when the ROM image is incompatible
* with the specified machine), all fields of rom_info are filled with NULLs.
* Returns MT32EMU_RC_OK upon success or a negative error code otherwise.
*/
MT32EMU_EXPORT_V(2.5) mt32emu_return_code MT32EMU_C_CALL mt32emu_identify_rom_data(mt32emu_rom_info *rom_info, const mt32emu_bit8u *data, size_t data_size, const char *machine_id);
/**
* Loads the content of the file specified by argument filename and identifies a ROM image the file contains by its SHA1 digest.
* Optional argument machine_id can be used to indicate a specific machine to identify the ROM image for; if NULL, the ROM image
* is identified for any supported machine.
* A mt32emu_rom_info structure supplied in argument rom_info is filled in accordance with the provided ROM image; unused fields
* are filled with NULLs. If the content of the file is not identified successfully (e.g. when the ROM image is incompatible
* with the specified machine), all fields of rom_info are filled with NULLs.
* Returns MT32EMU_RC_OK upon success or a negative error code otherwise.
*/
MT32EMU_EXPORT_V(2.5) mt32emu_return_code MT32EMU_C_CALL mt32emu_identify_rom_file(mt32emu_rom_info *rom_info, const char *filename, const char *machine_id);
/* == Context-dependent functions == */
/** Initialises a new emulation context and installs custom report handler if non-NULL. */
MT32EMU_EXPORT mt32emu_context MT32EMU_C_CALL mt32emu_create_context(mt32emu_report_handler_i report_handler, void *instance_data);
/** Closes and destroys emulation context. */
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_free_context(mt32emu_context context);
/**
* Adds a new full ROM data image identified by its SHA1 digest to the emulation context replacing previously added ROM of the same
* type if any. Argument sha1_digest can be NULL, in this case the digest will be computed using the actual ROM data.
* If sha1_digest is set to non-NULL, it is assumed being correct and will not be recomputed.
* The provided data array is NOT copied and used directly for efficiency. The caller should not deallocate it while the emulation
* context is referring to the ROM data.
* This function doesn't immediately change the state of already opened synth. Newly added ROM will take effect upon next call of
* mt32emu_open_synth().
* Returns positive value upon success.
*/
MT32EMU_EXPORT mt32emu_return_code MT32EMU_C_CALL mt32emu_add_rom_data(mt32emu_context context, const mt32emu_bit8u *data, size_t data_size, const mt32emu_sha1_digest *sha1_digest);
/**
* Loads a ROM file that contains a full ROM data image, identifies it by the SHA1 digest, and adds it to the emulation context
* replacing previously added ROM of the same type if any.
* This function doesn't immediately change the state of already opened synth. Newly added ROM will take effect upon next call of
* mt32emu_open_synth().
* Returns positive value upon success.
*/
MT32EMU_EXPORT mt32emu_return_code MT32EMU_C_CALL mt32emu_add_rom_file(mt32emu_context context, const char *filename);
/**
* Merges a pair of compatible ROM data image parts into a full image and adds it to the emulation context replacing previously
* added ROM of the same type if any. Each partial image is identified by its SHA1 digest. Arguments partN_sha1_digest can be NULL,
* in this case the digest will be computed using the actual ROM data. If a non-NULL SHA1 value is provided, it is assumed being
* correct and will not be recomputed. The provided data arrays may be deallocated as soon as the function completes.
* This function doesn't immediately change the state of already opened synth. Newly added ROM will take effect upon next call of
* mt32emu_open_synth().
* Returns positive value upon success.
*/
MT32EMU_EXPORT_V(2.5) mt32emu_return_code MT32EMU_C_CALL mt32emu_merge_and_add_rom_data(mt32emu_context context, const mt32emu_bit8u *part1_data, size_t part1_data_size, const mt32emu_sha1_digest *part1_sha1_digest, const mt32emu_bit8u *part2_data, size_t part2_data_size, const mt32emu_sha1_digest *part2_sha1_digest);
/**
* Loads a pair of files that contains compatible parts of a full ROM image, identifies them by the SHA1 digest, merges these
* parts into a full ROM image and adds it to the emulation context replacing previously added ROM of the same type if any.
* This function doesn't immediately change the state of already opened synth. Newly added ROM will take effect upon next call of
* mt32emu_open_synth().
* Returns positive value upon success.
*/
MT32EMU_EXPORT_V(2.5) mt32emu_return_code MT32EMU_C_CALL mt32emu_merge_and_add_rom_files(mt32emu_context context, const char *part1_filename, const char *part2_filename);
/**
* Loads a file that contains a ROM image of a specific machine, identifies it by the SHA1 digest, and adds it to the emulation
* context. The ROM image can only be identified successfully if it is compatible with the specified machine.
* Full and partial ROM images are supported and handled according to the following rules:
* - a file with any compatible ROM image is added if none (of the same type) exists in the emulation context;
* - a file with any compatible ROM image replaces any image of the same type that is incompatible with the specified machine;
* - a file with a full ROM image replaces the previously added partial ROM of the same type;
* - a file with a partial ROM image is merged with the previously added ROM image if pairable;
* - otherwise, the file is ignored.
* The described behaviour allows the caller application to traverse a directory with ROM files attempting to add each one in turn.
* As soon as both the full control and the full PCM ROM images are added and / or merged, the iteration can be stopped.
* This function doesn't immediately change the state of already opened synth. Newly added ROMs will take effect upon next call of
* mt32emu_open_synth().
* Returns a positive value in case changes have been made, MT32EMU_RC_OK if the file has been ignored or a negative error code
* upon failure.
*/
MT32EMU_EXPORT_V(2.5) mt32emu_return_code MT32EMU_C_CALL mt32emu_add_machine_rom_file(mt32emu_context context, const char *machine_id, const char *filename);
/**
* Fills in mt32emu_rom_info structure with identifiers and descriptions of control and PCM ROM files identified and added to the synth context.
* If one of the ROM files is not loaded and identified yet, NULL is returned in the corresponding fields of the mt32emu_rom_info structure.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_get_rom_info(mt32emu_const_context context, mt32emu_rom_info *rom_info);
/**
* Allows to override the default maximum number of partials playing simultaneously within the emulation session.
* This function doesn't immediately change the state of already opened synth. Newly set value will take effect upon next call of mt32emu_open_synth().
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_partial_count(mt32emu_context context, const mt32emu_bit32u partial_count);
/**
* Allows to override the default mode for emulation of analogue circuitry of the hardware units within the emulation session.
* This function doesn't immediately change the state of already opened synth. Newly set value will take effect upon next call of mt32emu_open_synth().
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_analog_output_mode(mt32emu_context context, const mt32emu_analog_output_mode analog_output_mode);
/**
* Allows to convert the synthesiser output to any desired sample rate. The samplerate conversion
* processes the completely mixed stereo output signal as it passes the analogue circuit emulation,
* so emulating the synthesiser output signal passing further through an ADC. When the samplerate
* argument is set to 0, the default output sample rate is used which depends on the current
* mode of analog circuitry emulation. See mt32emu_analog_output_mode.
* This function doesn't immediately change the state of already opened synth.
* Newly set value will take effect upon next call of mt32emu_open_synth().
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_stereo_output_samplerate(mt32emu_context context, const double samplerate);
/**
* Several samplerate conversion quality options are provided which allow to trade-off the conversion speed vs.
* the retained passband width. All the options except FASTEST guarantee full suppression of the aliasing noise
* in terms of the 16-bit integer samples.
* This function doesn't immediately change the state of already opened synth.
* Newly set value will take effect upon next call of mt32emu_open_synth().
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_samplerate_conversion_quality(mt32emu_context context, const mt32emu_samplerate_conversion_quality quality);
/**
* Selects new type of the wave generator and renderer to be used during subsequent calls to mt32emu_open_synth().
* By default, MT32EMU_RT_BIT16S is selected.
* See mt32emu_renderer_type for details.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_select_renderer_type(mt32emu_context context, const mt32emu_renderer_type renderer_type);
/**
* Returns previously selected type of the wave generator and renderer.
* See mt32emu_renderer_type for details.
*/
MT32EMU_EXPORT mt32emu_renderer_type MT32EMU_C_CALL mt32emu_get_selected_renderer_type(mt32emu_context context);
/**
* Prepares the emulation context to receive MIDI messages and produce output audio data using aforehand added set of ROMs,
* and optionally set the maximum partial count and the analog output mode.
* Returns MT32EMU_RC_OK upon success.
*/
MT32EMU_EXPORT mt32emu_return_code MT32EMU_C_CALL mt32emu_open_synth(mt32emu_const_context context);
/** Closes the emulation context freeing allocated resources. Added ROMs remain unaffected and ready for reuse. */
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_close_synth(mt32emu_const_context context);
/** Returns true if the synth is in completely initialized state, otherwise returns false. */
MT32EMU_EXPORT mt32emu_boolean MT32EMU_C_CALL mt32emu_is_open(mt32emu_const_context context);
/**
* Returns actual sample rate of the fully processed output stereo signal.
* If samplerate conversion is used (i.e. when mt32emu_set_stereo_output_samplerate() has been invoked with a non-zero value),
* the returned value is the desired output samplerate rounded down to the closest integer.
* Otherwise, the output samplerate is chosen depending on the emulation mode of stereo analog circuitry of hardware units.
* See comment for mt32emu_analog_output_mode for more info.
*/
MT32EMU_EXPORT mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_actual_stereo_output_samplerate(mt32emu_const_context context);
/**
* Returns the number of samples produced at the internal synth sample rate (32000 Hz)
* that correspond to the given number of samples at the output sample rate.
* Intended to facilitate audio time synchronisation.
*/
MT32EMU_EXPORT mt32emu_bit32u MT32EMU_C_CALL mt32emu_convert_output_to_synth_timestamp(mt32emu_const_context context, mt32emu_bit32u output_timestamp);
/**
* Returns the number of samples produced at the output sample rate
* that correspond to the given number of samples at the internal synth sample rate (32000 Hz).
* Intended to facilitate audio time synchronisation.
*/
MT32EMU_EXPORT mt32emu_bit32u MT32EMU_C_CALL mt32emu_convert_synth_to_output_timestamp(mt32emu_const_context context, mt32emu_bit32u synth_timestamp);
/** All the enqueued events are processed by the synth immediately. */
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_flush_midi_queue(mt32emu_const_context context);
/**
* Sets size of the internal MIDI event queue. The queue size is set to the minimum power of 2 that is greater or equal to the size specified.
* The queue is flushed before reallocation.
* Returns the actual queue size being used.
*/
MT32EMU_EXPORT mt32emu_bit32u MT32EMU_C_CALL mt32emu_set_midi_event_queue_size(mt32emu_const_context context, const mt32emu_bit32u queue_size);
/**
* Configures the SysEx storage of the internal MIDI event queue.
* Supplying 0 in the storage_buffer_size argument makes the SysEx data stored
* in multiple dynamically allocated buffers per MIDI event. These buffers are only disposed
* when a new MIDI event replaces the SysEx event in the queue, thus never on the rendering thread.
* This is the default behaviour.
* In contrast, when a positive value is specified, SysEx data will be stored in a single preallocated buffer,
* which makes this kind of storage safe for use in a realtime thread. Additionally, the space retained
* by a SysEx event, that has been processed and thus is no longer necessary, is disposed instantly.
* Note, the queue is flushed and recreated in the process so that its size remains intact.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_configure_midi_event_queue_sysex_storage(mt32emu_const_context context, const mt32emu_bit32u storage_buffer_size);
/**
* Installs custom MIDI receiver object intended for receiving MIDI messages generated by MIDI stream parser.
* MIDI stream parser is involved when functions mt32emu_parse_stream() and mt32emu_play_short_message() or the likes are called.
* By default, parsed short MIDI messages and System Exclusive messages are sent to the synth input MIDI queue.
* This function allows to override default behaviour. If midi_receiver argument is set to NULL, the default behaviour is restored.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_midi_receiver(mt32emu_context context, mt32emu_midi_receiver_i midi_receiver, void *instance_data);
/**
* Returns current value of the global counter of samples rendered since the synth was created (at the native sample rate 32000 Hz).
* This method helps to compute accurate timestamp of a MIDI message to use with the methods below.
*/
MT32EMU_EXPORT mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_internal_rendered_sample_count(mt32emu_const_context context);
/* Enqueues a MIDI event for subsequent playback.
* The MIDI event will be processed not before the specified timestamp.
* The timestamp is measured as the global rendered sample count since the synth was created (at the native sample rate 32000 Hz).
* The minimum delay involves emulation of the delay introduced while the event is transferred via MIDI interface
* and emulation of the MCU busy-loop while it frees partials for use by a new Poly.
* Calls from multiple threads must be synchronised, although, no synchronisation is required with the rendering thread.
* onMIDIQueueOverflow callback is invoked when the MIDI event queue is full and the message cannot be enqueued.
*/
/**
* Parses a block of raw MIDI bytes and enqueues parsed MIDI messages for further processing ASAP.
* SysEx messages are allowed to be fragmented across several calls to this method. Running status is also handled for short messages.
* When a System Realtime MIDI message is parsed, onMIDISystemRealtime callback is invoked.
* NOTE: the total length of a SysEx message being fragmented shall not exceed MT32EMU_MAX_STREAM_BUFFER_SIZE (32768 bytes).
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_parse_stream(mt32emu_const_context context, const mt32emu_bit8u *stream, mt32emu_bit32u length);
/**
* Parses a block of raw MIDI bytes and enqueues parsed MIDI messages to play at specified time.
* SysEx messages are allowed to be fragmented across several calls to this method. Running status is also handled for short messages.
* When a System Realtime MIDI message is parsed, onMIDISystemRealtime callback is invoked.
* NOTE: the total length of a SysEx message being fragmented shall not exceed MT32EMU_MAX_STREAM_BUFFER_SIZE (32768 bytes).
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_parse_stream_at(mt32emu_const_context context, const mt32emu_bit8u *stream, mt32emu_bit32u length, mt32emu_bit32u timestamp);
/**
* Enqueues a single mt32emu_bit32u-encoded short MIDI message with full processing ASAP.
* The short MIDI message may contain no status byte, the running status is used in this case.
* When the argument is a System Realtime MIDI message, onMIDISystemRealtime callback is invoked.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_play_short_message(mt32emu_const_context context, mt32emu_bit32u message);
/**
* Enqueues a single mt32emu_bit32u-encoded short MIDI message to play at specified time with full processing.
* The short MIDI message may contain no status byte, the running status is used in this case.
* When the argument is a System Realtime MIDI message, onMIDISystemRealtime callback is invoked.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_play_short_message_at(mt32emu_const_context context, mt32emu_bit32u message, mt32emu_bit32u timestamp);
/** Enqueues a single short MIDI message to be processed ASAP. The message must contain a status byte. */
MT32EMU_EXPORT mt32emu_return_code MT32EMU_C_CALL mt32emu_play_msg(mt32emu_const_context context, mt32emu_bit32u msg);
/** Enqueues a single well formed System Exclusive MIDI message to be processed ASAP. */
MT32EMU_EXPORT mt32emu_return_code MT32EMU_C_CALL mt32emu_play_sysex(mt32emu_const_context context, const mt32emu_bit8u *sysex, mt32emu_bit32u len);
/** Enqueues a single short MIDI message to play at specified time. The message must contain a status byte. */
MT32EMU_EXPORT mt32emu_return_code MT32EMU_C_CALL mt32emu_play_msg_at(mt32emu_const_context context, mt32emu_bit32u msg, mt32emu_bit32u timestamp);
/** Enqueues a single well formed System Exclusive MIDI message to play at specified time. */
MT32EMU_EXPORT mt32emu_return_code MT32EMU_C_CALL mt32emu_play_sysex_at(mt32emu_const_context context, const mt32emu_bit8u *sysex, mt32emu_bit32u len, mt32emu_bit32u timestamp);
/* WARNING:
* The methods below don't ensure minimum 1-sample delay between sequential MIDI events,
* and a sequence of NoteOn and immediately succeeding NoteOff messages is always silent.
* A thread that invokes these methods must be explicitly synchronised with the thread performing sample rendering.
*/
/**
* Sends a short MIDI message to the synth for immediate playback. The message must contain a status byte.
* See the WARNING above.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_play_msg_now(mt32emu_const_context context, mt32emu_bit32u msg);
/**
* Sends unpacked short MIDI message to the synth for immediate playback. The message must contain a status byte.
* See the WARNING above.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_play_msg_on_part(mt32emu_const_context context, mt32emu_bit8u part, mt32emu_bit8u code, mt32emu_bit8u note, mt32emu_bit8u velocity);
/**
* Sends a single well formed System Exclusive MIDI message for immediate processing. The length is in bytes.
* See the WARNING above.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_play_sysex_now(mt32emu_const_context context, const mt32emu_bit8u *sysex, mt32emu_bit32u len);
/**
* Sends inner body of a System Exclusive MIDI message for direct processing. The length is in bytes.
* See the WARNING above.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_write_sysex(mt32emu_const_context context, mt32emu_bit8u channel, const mt32emu_bit8u *sysex, mt32emu_bit32u len);
/** Allows to disable wet reverb output altogether. */
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_reverb_enabled(mt32emu_const_context context, const mt32emu_boolean reverb_enabled);
/** Returns whether wet reverb output is enabled. */
MT32EMU_EXPORT mt32emu_boolean MT32EMU_C_CALL mt32emu_is_reverb_enabled(mt32emu_const_context context);
/**
* Sets override reverb mode. In this mode, emulation ignores sysexes (or the related part of them) which control the reverb parameters.
* This mode is in effect until it is turned off. When the synth is re-opened, the override mode is unchanged but the state
* of the reverb model is reset to default.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_reverb_overridden(mt32emu_const_context context, const mt32emu_boolean reverb_overridden);
/** Returns whether reverb settings are overridden. */
MT32EMU_EXPORT mt32emu_boolean MT32EMU_C_CALL mt32emu_is_reverb_overridden(mt32emu_const_context context);
/**
* Forces reverb model compatibility mode. By default, the compatibility mode corresponds to the used control ROM version.
* Invoking this method with the argument set to true forces emulation of old MT-32 reverb circuit.
* When the argument is false, emulation of the reverb circuit used in new generation of MT-32 compatible modules is enforced
* (these include CM-32L and LAPC-I).
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_reverb_compatibility_mode(mt32emu_const_context context, const mt32emu_boolean mt32_compatible_mode);
/** Returns whether reverb is in old MT-32 compatibility mode. */
MT32EMU_EXPORT mt32emu_boolean MT32EMU_C_CALL mt32emu_is_mt32_reverb_compatibility_mode(mt32emu_const_context context);
/** Returns whether default reverb compatibility mode is the old MT-32 compatibility mode. */
MT32EMU_EXPORT mt32emu_boolean MT32EMU_C_CALL mt32emu_is_default_reverb_mt32_compatible(mt32emu_const_context context);
/**
* If enabled, reverb buffers for all modes are kept around allocated all the time to avoid memory
* allocating/freeing in the rendering thread, which may be required for realtime operation.
* Otherwise, reverb buffers that are not in use are deleted to save memory (the default behaviour).
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_preallocate_reverb_memory(mt32emu_const_context context, const mt32emu_boolean enabled);
/** Sets new DAC input mode. See mt32emu_dac_input_mode for details. */
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_dac_input_mode(mt32emu_const_context context, const mt32emu_dac_input_mode mode);
/** Returns current DAC input mode. See mt32emu_dac_input_mode for details. */
MT32EMU_EXPORT mt32emu_dac_input_mode MT32EMU_C_CALL mt32emu_get_dac_input_mode(mt32emu_const_context context);
/** Sets new MIDI delay mode. See mt32emu_midi_delay_mode for details. */
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_midi_delay_mode(mt32emu_const_context context, const mt32emu_midi_delay_mode mode);
/** Returns current MIDI delay mode. See mt32emu_midi_delay_mode for details. */
MT32EMU_EXPORT mt32emu_midi_delay_mode MT32EMU_C_CALL mt32emu_get_midi_delay_mode(mt32emu_const_context context);
/**
* Sets output gain factor for synth output channels. Applied to all output samples and unrelated with the synth's Master volume,
* it rather corresponds to the gain of the output analog circuitry of the hardware units. However, together with mt32emu_set_reverb_output_gain()
* it offers to the user a capability to control the gain of reverb and non-reverb output channels independently.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_output_gain(mt32emu_const_context context, float gain);
/** Returns current output gain factor for synth output channels. */
MT32EMU_EXPORT float MT32EMU_C_CALL mt32emu_get_output_gain(mt32emu_const_context context);
/**
* Sets output gain factor for the reverb wet output channels. It rather corresponds to the gain of the output
* analog circuitry of the hardware units. However, together with mt32emu_set_output_gain() it offers to the user a capability
* to control the gain of reverb and non-reverb output channels independently.
*
* Note: We're currently emulate CM-32L/CM-64 reverb quite accurately and the reverb output level closely
* corresponds to the level of digital capture. Although, according to the CM-64 PCB schematic,
* there is a difference in the reverb analogue circuit, and the resulting output gain is 0.68
* of that for LA32 analogue output. This factor is applied to the reverb output gain.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_reverb_output_gain(mt32emu_const_context context, float gain);
/** Returns current output gain factor for reverb wet output channels. */
MT32EMU_EXPORT float MT32EMU_C_CALL mt32emu_get_reverb_output_gain(mt32emu_const_context context);
/**
* Sets (or removes) an override for the current volume (output level) on a specific part.
* When the part volume is overridden, the MIDI controller Volume (7) on the MIDI channel this part is assigned to
* has no effect on the output level of this part. Similarly, the output level value set on this part via a SysEx that
* modifies the Patch temp structure is disregarded.
* To enable the override mode, argument volumeOverride should be in range 0..100, setting a value outside this range
* disables the previously set override, if any.
* Note: Setting volumeOverride to 0 mutes the part completely, meaning no sound is generated at all.
* This is unlike the behaviour of real devices - setting 0 volume on a part may leave it still producing
* sound at a very low level.
* Argument partNumber should be 0..7 for Part 1..8, or 8 for Rhythm.
*/
MT32EMU_EXPORT_V(2.6) void MT32EMU_C_CALL mt32emu_set_part_volume_override(mt32emu_const_context context, mt32emu_bit8u part_number, mt32emu_bit8u volume_override);
/**
* Returns the overridden volume previously set on a specific part; a value outside the range 0..100 means no override
* is currently in effect.
* Argument partNumber should be 0..7 for Part 1..8, or 8 for Rhythm.
*/
MT32EMU_EXPORT_V(2.6) mt32emu_bit8u MT32EMU_C_CALL mt32emu_get_part_volume_override(mt32emu_const_context context, mt32emu_bit8u part_number);
/** Swaps left and right output channels. */
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_reversed_stereo_enabled(mt32emu_const_context context, const mt32emu_boolean enabled);
/** Returns whether left and right output channels are swapped. */
MT32EMU_EXPORT mt32emu_boolean MT32EMU_C_CALL mt32emu_is_reversed_stereo_enabled(mt32emu_const_context context);
/**
* Allows to toggle the NiceAmpRamp mode.
* In this mode, we want to ensure that amp ramp never jumps to the target
* value and always gradually increases or decreases. It seems that real units
* do not bother to always check if a newly started ramp leads to a jump.
* We also prefer the quality improvement over the emulation accuracy,
* so this mode is enabled by default.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_nice_amp_ramp_enabled(mt32emu_const_context context, const mt32emu_boolean enabled);
/** Returns whether NiceAmpRamp mode is enabled. */
MT32EMU_EXPORT mt32emu_boolean MT32EMU_C_CALL mt32emu_is_nice_amp_ramp_enabled(mt32emu_const_context context);
/**
* Allows to toggle the NicePanning mode.
* Despite the Roland's manual specifies allowed panpot values in range 0-14,
* the LA-32 only receives 3-bit pan setting in fact. In particular, this
* makes it impossible to set the "middle" panning for a single partial.
* In the NicePanning mode, we enlarge the pan setting accuracy to 4 bits
* making it smoother thus sacrificing the emulation accuracy.
* This mode is disabled by default.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_nice_panning_enabled(mt32emu_const_context context, const mt32emu_boolean enabled);
/** Returns whether NicePanning mode is enabled. */
MT32EMU_EXPORT mt32emu_boolean MT32EMU_C_CALL mt32emu_is_nice_panning_enabled(mt32emu_const_context context);
/**
* Allows to toggle the NicePartialMixing mode.
* LA-32 is known to mix partials either in-phase (so that they are added)
* or in counter-phase (so that they are subtracted instead).
* In some cases, this quirk isn't highly desired because a pair of closely
* sounding partials may occasionally cancel out.
* In the NicePartialMixing mode, the mixing is always performed in-phase,
* thus making the behaviour more predictable.
* This mode is disabled by default.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_set_nice_partial_mixing_enabled(mt32emu_const_context context, const mt32emu_boolean enabled);
/** Returns whether NicePartialMixing mode is enabled. */
MT32EMU_EXPORT mt32emu_boolean MT32EMU_C_CALL mt32emu_is_nice_partial_mixing_enabled(mt32emu_const_context context);
/**
* Renders samples to the specified output stream as if they were sampled at the analog stereo output at the desired sample rate.
* If the output sample rate is not specified explicitly, the default output sample rate is used which depends on the current
* mode of analog circuitry emulation. See mt32emu_analog_output_mode.
* The length is in frames, not bytes (in 16-bit stereo, one frame is 4 bytes). Uses NATIVE byte ordering.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_render_bit16s(mt32emu_const_context context, mt32emu_bit16s *stream, mt32emu_bit32u len);
/** Same as above but outputs to a float stereo stream. */
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_render_float(mt32emu_const_context context, float *stream, mt32emu_bit32u len);
/**
* Renders samples to the specified output streams as if they appeared at the DAC entrance.
* No further processing performed in analog circuitry emulation is applied to the signal.
* NULL may be specified in place of any or all of the stream buffers to skip it.
* The length is in samples, not bytes. Uses NATIVE byte ordering.
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_render_bit16s_streams(mt32emu_const_context context, const mt32emu_dac_output_bit16s_streams *streams, mt32emu_bit32u len);
/** Same as above but outputs to float streams. */
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_render_float_streams(mt32emu_const_context context, const mt32emu_dac_output_float_streams *streams, mt32emu_bit32u len);
/** Returns true when there is at least one active partial, otherwise false. */
MT32EMU_EXPORT mt32emu_boolean MT32EMU_C_CALL mt32emu_has_active_partials(mt32emu_const_context context);
/** Returns true if mt32emu_has_active_partials() returns true, or reverb is (somewhat unreliably) detected as being active. */
MT32EMU_EXPORT mt32emu_boolean MT32EMU_C_CALL mt32emu_is_active(mt32emu_const_context context);
/** Returns the maximum number of partials playing simultaneously. */
MT32EMU_EXPORT mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_partial_count(mt32emu_const_context context);
/**
* Returns current states of all the parts as a bit set. The least significant bit corresponds to the state of part 1,
* total of 9 bits hold the states of all the parts. If the returned bit for a part is set, there is at least one active
* non-releasing partial playing on this part. This info is useful in emulating behaviour of LCD display of the hardware units.
*/
MT32EMU_EXPORT mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_part_states(mt32emu_const_context context);
/**
* Fills in current states of all the partials into the array provided. Each byte in the array holds states of 4 partials
* starting from the least significant bits. The state of each partial is packed in a pair of bits.
* The array must be large enough to accommodate states of all the partials.
* @see getPartialCount()
*/
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_get_partial_states(mt32emu_const_context context, mt32emu_bit8u *partial_states);
/**
* Fills in information about currently playing notes on the specified part into the arrays provided. The arrays must be large enough
* to accommodate data for all the playing notes. The maximum number of simultaneously playing notes cannot exceed the number of partials.
* Argument partNumber should be 0..7 for Part 1..8, or 8 for Rhythm.
* Returns the number of currently playing notes on the specified part.
*/
MT32EMU_EXPORT mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_playing_notes(mt32emu_const_context context, mt32emu_bit8u part_number, mt32emu_bit8u *keys, mt32emu_bit8u *velocities);
/**
* Returns name of the patch set on the specified part.
* Argument partNumber should be 0..7 for Part 1..8, or 8 for Rhythm.
* The returned value is a null-terminated string which is guaranteed to remain valid until the next call to one of functions
* that perform sample rendering or immediate SysEx processing (e.g. mt32emu_play_sysex_now).
*/
MT32EMU_EXPORT const char * MT32EMU_C_CALL mt32emu_get_patch_name(mt32emu_const_context context, mt32emu_bit8u part_number);
/**
* Retrieves the name of the sound group the timbre identified by arguments timbre_group and timbre_number is associated with.
* Values 0-3 of timbre_group correspond to the timbre banks GROUP A, GROUP B, MEMORY and RHYTHM.
* For all but the RHYTHM timbre bank, allowed values of timbre_number are in range 0-63. The number of timbres
* contained in the RHYTHM bank depends on the used control ROM version.
* The argument sound_group_name must point to an array of at least 8 characters. The result is a null-terminated string.
* Returns whether the specified timbre has been found and the result written in sound_group_name.
*/
MT32EMU_EXPORT_V(2.7) mt32emu_boolean MT32EMU_C_CALL mt32emu_get_sound_group_name(mt32emu_const_context context, char *sound_group_name, mt32emu_bit8u timbre_group, mt32emu_bit8u timbre_number);
/**
* Retrieves the name of the timbre identified by arguments timbre_group and timbre_number.
* Values 0-3 of timbre_group correspond to the timbre banks GROUP A, GROUP B, MEMORY and RHYTHM.
* For all but the RHYTHM timbre bank, allowed values of timbre_number are in range 0-63. The number of timbres
* contained in the RHYTHM bank depends on the used control ROM version.
* The argument sound_name must point to an array of at least 11 characters. The result is a null-terminated string.
* Returns whether the specified timbre has been found and the result written in sound_name.
*/
MT32EMU_EXPORT_V(2.7) mt32emu_boolean MT32EMU_C_CALL mt32emu_get_sound_name(mt32emu_const_context context, char *sound_name, mt32emu_bit8u timbreGroup, mt32emu_bit8u timbreNumber);
/** Stores internal state of emulated synth into an array provided (as it would be acquired from hardware). */
MT32EMU_EXPORT void MT32EMU_C_CALL mt32emu_read_memory(mt32emu_const_context context, mt32emu_bit32u addr, mt32emu_bit32u len, mt32emu_bit8u *data);
/**
* Retrieves the current state of the emulated MT-32 display facilities.
* Typically, the state is updated during the rendering. When that happens, a related callback from mt32emu_report_handler_i_v1
* is invoked. However, there might be no need to invoke this method after each update, e.g. when the render buffer is just
* a few milliseconds long.
* The argument target_buffer must point to an array of at least 21 characters. The result is a null-terminated string.
* The argument narrow_lcd enables a condensed representation of the displayed information in some cases. This is mainly intended
* to route the result to a hardware LCD that is only 16 characters wide. Automatic scrolling of longer strings is not supported.
* Returns whether the MIDI MESSAGE LED is ON and fills the target_buffer parameter.
*/
MT32EMU_EXPORT_V(2.6) mt32emu_boolean MT32EMU_C_CALL mt32emu_get_display_state(mt32emu_const_context context, char *target_buffer, const mt32emu_boolean narrow_lcd);
/**
* Resets the emulated LCD to the main mode (Master Volume). This has the same effect as pressing the Master Volume button
* while the display shows some other message. Useful for the new-gen devices as those require a special Display Reset SysEx
* to return to the main mode e.g. from showing a custom display message or a checksum error.
*/
MT32EMU_EXPORT_V(2.6) void MT32EMU_C_CALL mt32emu_set_main_display_mode(mt32emu_const_context context);
/**
* Permits to select an arbitrary display emulation model that does not necessarily match the actual behaviour implemented
* in the control ROM version being used.
* Invoking this method with the argument set to true forces emulation of the old-gen MT-32 display features.
* Otherwise, emulation of the new-gen devices is enforced (these include CM-32L and LAPC-I as if these were connected to an LCD).
*/
MT32EMU_EXPORT_V(2.6) void MT32EMU_C_CALL mt32emu_set_display_compatibility(mt32emu_const_context context, mt32emu_boolean old_mt32_compatibility_enabled);
/** Returns whether the currently configured features of the emulated display are compatible with the old-gen MT-32 devices. */
MT32EMU_EXPORT_V(2.6) mt32emu_boolean MT32EMU_C_CALL mt32emu_is_display_old_mt32_compatible(mt32emu_const_context context);
/**
* Returns whether the emulated display features configured by default depending on the actual control ROM version
* are compatible with the old-gen MT-32 devices.
*/
MT32EMU_EXPORT_V(2.6) mt32emu_boolean MT32EMU_C_CALL mt32emu_is_default_display_old_mt32_compatible(mt32emu_const_context context);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* #ifndef MT32EMU_C_INTERFACE_H */
``` | /content/code_sandbox/src/sound/munt/c_interface/c_interface.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 9,532 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstring>
#include "../globals.h"
#include "../Types.h"
#include "../File.h"
#include "../FileStream.h"
#include "../ROMInfo.h"
#include "../Synth.h"
#include "../MidiStreamParser.h"
#include "../SampleRateConverter.h"
#include "c_types.h"
#include "c_interface.h"
using namespace MT32Emu;
namespace MT32Emu {
struct SamplerateConversionState {
double outputSampleRate;
SamplerateConversionQuality srcQuality;
SampleRateConverter *src;
};
static mt32emu_service_version MT32EMU_C_CALL getSynthVersionID(mt32emu_service_i) {
return MT32EMU_SERVICE_VERSION_CURRENT;
}
static const mt32emu_service_i_v6 SERVICE_VTABLE = {
getSynthVersionID,
mt32emu_get_supported_report_handler_version,
mt32emu_get_supported_midi_receiver_version,
mt32emu_get_library_version_int,
mt32emu_get_library_version_string,
mt32emu_get_stereo_output_samplerate,
mt32emu_create_context,
mt32emu_free_context,
mt32emu_add_rom_data,
mt32emu_add_rom_file,
mt32emu_get_rom_info,
mt32emu_set_partial_count,
mt32emu_set_analog_output_mode,
mt32emu_open_synth,
mt32emu_close_synth,
mt32emu_is_open,
mt32emu_get_actual_stereo_output_samplerate,
mt32emu_flush_midi_queue,
mt32emu_set_midi_event_queue_size,
mt32emu_set_midi_receiver,
mt32emu_parse_stream,
mt32emu_parse_stream_at,
mt32emu_play_short_message,
mt32emu_play_short_message_at,
mt32emu_play_msg,
mt32emu_play_sysex,
mt32emu_play_msg_at,
mt32emu_play_sysex_at,
mt32emu_play_msg_now,
mt32emu_play_msg_on_part,
mt32emu_play_sysex_now,
mt32emu_write_sysex,
mt32emu_set_reverb_enabled,
mt32emu_is_reverb_enabled,
mt32emu_set_reverb_overridden,
mt32emu_is_reverb_overridden,
mt32emu_set_reverb_compatibility_mode,
mt32emu_is_mt32_reverb_compatibility_mode,
mt32emu_is_default_reverb_mt32_compatible,
mt32emu_set_dac_input_mode,
mt32emu_get_dac_input_mode,
mt32emu_set_midi_delay_mode,
mt32emu_get_midi_delay_mode,
mt32emu_set_output_gain,
mt32emu_get_output_gain,
mt32emu_set_reverb_output_gain,
mt32emu_get_reverb_output_gain,
mt32emu_set_reversed_stereo_enabled,
mt32emu_is_reversed_stereo_enabled,
mt32emu_render_bit16s,
mt32emu_render_float,
mt32emu_render_bit16s_streams,
mt32emu_render_float_streams,
mt32emu_has_active_partials,
mt32emu_is_active,
mt32emu_get_partial_count,
mt32emu_get_part_states,
mt32emu_get_partial_states,
mt32emu_get_playing_notes,
mt32emu_get_patch_name,
mt32emu_read_memory,
mt32emu_get_best_analog_output_mode,
mt32emu_set_stereo_output_samplerate,
mt32emu_set_samplerate_conversion_quality,
mt32emu_select_renderer_type,
mt32emu_get_selected_renderer_type,
mt32emu_convert_output_to_synth_timestamp,
mt32emu_convert_synth_to_output_timestamp,
mt32emu_get_internal_rendered_sample_count,
mt32emu_set_nice_amp_ramp_enabled,
mt32emu_is_nice_amp_ramp_enabled,
mt32emu_set_nice_panning_enabled,
mt32emu_is_nice_panning_enabled,
mt32emu_set_nice_partial_mixing_enabled,
mt32emu_is_nice_partial_mixing_enabled,
mt32emu_preallocate_reverb_memory,
mt32emu_configure_midi_event_queue_sysex_storage,
mt32emu_get_machine_ids,
mt32emu_get_rom_ids,
mt32emu_identify_rom_data,
mt32emu_identify_rom_file,
mt32emu_merge_and_add_rom_data,
mt32emu_merge_and_add_rom_files,
mt32emu_add_machine_rom_file,
mt32emu_get_display_state,
mt32emu_set_main_display_mode,
mt32emu_set_display_compatibility,
mt32emu_is_display_old_mt32_compatible,
mt32emu_is_default_display_old_mt32_compatible,
mt32emu_set_part_volume_override,
mt32emu_get_part_volume_override,
mt32emu_get_sound_group_name,
mt32emu_get_sound_name
};
} // namespace MT32Emu
struct mt32emu_data {
ReportHandler2 *reportHandler;
Synth *synth;
const ROMImage *controlROMImage;
const ROMImage *pcmROMImage;
DefaultMidiStreamParser *midiParser;
Bit32u partialCount;
AnalogOutputMode analogOutputMode;
SamplerateConversionState *srcState;
};
// Internal C++ utility stuff
namespace MT32Emu {
class DelegatingReportHandlerAdapter : public ReportHandler2 {
public:
DelegatingReportHandlerAdapter(mt32emu_report_handler_i useReportHandler, void *useInstanceData) :
delegate(useReportHandler), instanceData(useInstanceData) {}
private:
const mt32emu_report_handler_i delegate;
void * const instanceData;
bool isVersionLess(mt32emu_report_handler_version versionID) {
return delegate.v0->getVersionID(delegate) < versionID;
}
void printDebug(const char *fmt, va_list list) {
if (delegate.v0->printDebug == NULL) {
ReportHandler::printDebug(fmt, list);
} else {
delegate.v0->printDebug(instanceData, fmt, list);
}
}
void onErrorControlROM() {
if (delegate.v0->onErrorControlROM == NULL) {
ReportHandler::onErrorControlROM();
} else {
delegate.v0->onErrorControlROM(instanceData);
}
}
void onErrorPCMROM() {
if (delegate.v0->onErrorPCMROM == NULL) {
ReportHandler::onErrorPCMROM();
} else {
delegate.v0->onErrorPCMROM(instanceData);
}
}
void showLCDMessage(const char *message) {
if (delegate.v0->showLCDMessage == NULL) {
ReportHandler::showLCDMessage(message);
} else {
delegate.v0->showLCDMessage(instanceData, message);
}
}
void onMIDIMessagePlayed() {
if (delegate.v0->onMIDIMessagePlayed == NULL) {
ReportHandler::onMIDIMessagePlayed();
} else {
delegate.v0->onMIDIMessagePlayed(instanceData);
}
}
bool onMIDIQueueOverflow() {
if (delegate.v0->onMIDIQueueOverflow == NULL) {
return ReportHandler::onMIDIQueueOverflow();
}
return delegate.v0->onMIDIQueueOverflow(instanceData) != MT32EMU_BOOL_FALSE;
}
void onMIDISystemRealtime(Bit8u systemRealtime) {
if (delegate.v0->onMIDISystemRealtime == NULL) {
ReportHandler::onMIDISystemRealtime(systemRealtime);
} else {
delegate.v0->onMIDISystemRealtime(instanceData, systemRealtime);
}
}
void onDeviceReset() {
if (delegate.v0->onDeviceReset == NULL) {
ReportHandler::onDeviceReset();
} else {
delegate.v0->onDeviceReset(instanceData);
}
}
void onDeviceReconfig() {
if (delegate.v0->onDeviceReconfig == NULL) {
ReportHandler::onDeviceReconfig();
} else {
delegate.v0->onDeviceReconfig(instanceData);
}
}
void onNewReverbMode(Bit8u mode) {
if (delegate.v0->onNewReverbMode == NULL) {
ReportHandler::onNewReverbMode(mode);
} else {
delegate.v0->onNewReverbMode(instanceData, mode);
}
}
void onNewReverbTime(Bit8u time) {
if (delegate.v0->onNewReverbTime == NULL) {
ReportHandler::onNewReverbTime(time);
} else {
delegate.v0->onNewReverbTime(instanceData, time);
}
}
void onNewReverbLevel(Bit8u level) {
if (delegate.v0->onNewReverbLevel == NULL) {
ReportHandler::onNewReverbLevel(level);
} else {
delegate.v0->onNewReverbLevel(instanceData, level);
}
}
void onPolyStateChanged(Bit8u partNum) {
if (delegate.v0->onPolyStateChanged == NULL) {
ReportHandler::onPolyStateChanged(partNum);
} else {
delegate.v0->onPolyStateChanged(instanceData, partNum);
}
}
void onProgramChanged(Bit8u partNum, const char *soundGroupName, const char *patchName) {
if (delegate.v0->onProgramChanged == NULL) {
ReportHandler::onProgramChanged(partNum, soundGroupName, patchName);
} else {
delegate.v0->onProgramChanged(instanceData, partNum, soundGroupName, patchName);
}
}
void onLCDStateUpdated() {
if (isVersionLess(MT32EMU_REPORT_HANDLER_VERSION_1) || delegate.v1->onLCDStateUpdated == NULL) {
ReportHandler2::onLCDStateUpdated();
} else {
delegate.v1->onLCDStateUpdated(instanceData);
}
}
void onMidiMessageLEDStateUpdated(bool ledState) {
if (isVersionLess(MT32EMU_REPORT_HANDLER_VERSION_1) || delegate.v1->onMidiMessageLEDStateUpdated == NULL) {
ReportHandler2::onMidiMessageLEDStateUpdated(ledState);
} else {
delegate.v1->onMidiMessageLEDStateUpdated(instanceData, ledState ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE);
}
}
};
class DelegatingMidiStreamParser : public DefaultMidiStreamParser {
public:
DelegatingMidiStreamParser(const mt32emu_data *useData, mt32emu_midi_receiver_i useMIDIReceiver, void *useInstanceData) :
DefaultMidiStreamParser(*useData->synth), delegate(useMIDIReceiver), instanceData(useInstanceData) {}
protected:
mt32emu_midi_receiver_i delegate;
void *instanceData;
private:
void handleShortMessage(const Bit32u message) {
if (delegate.v0->handleShortMessage == NULL) {
DefaultMidiStreamParser::handleShortMessage(message);
} else {
delegate.v0->handleShortMessage(instanceData, message);
}
}
void handleSysex(const Bit8u *stream, const Bit32u length) {
if (delegate.v0->handleSysex == NULL) {
DefaultMidiStreamParser::handleSysex(stream, length);
} else {
delegate.v0->handleSysex(instanceData, stream, length);
}
}
void handleSystemRealtimeMessage(const Bit8u realtime) {
if (delegate.v0->handleSystemRealtimeMessage == NULL) {
DefaultMidiStreamParser::handleSystemRealtimeMessage(realtime);
} else {
delegate.v0->handleSystemRealtimeMessage(instanceData, realtime);
}
}
};
static void fillROMInfo(mt32emu_rom_info *rom_info, const ROMInfo *controlROMInfo, const ROMInfo *pcmROMInfo) {
if (controlROMInfo != NULL) {
rom_info->control_rom_id = controlROMInfo->shortName;
rom_info->control_rom_description = controlROMInfo->description;
rom_info->control_rom_sha1_digest = controlROMInfo->sha1Digest;
} else {
rom_info->control_rom_id = NULL;
rom_info->control_rom_description = NULL;
rom_info->control_rom_sha1_digest = NULL;
}
if (pcmROMInfo != NULL) {
rom_info->pcm_rom_id = pcmROMInfo->shortName;
rom_info->pcm_rom_description = pcmROMInfo->description;
rom_info->pcm_rom_sha1_digest = pcmROMInfo->sha1Digest;
} else {
rom_info->pcm_rom_id = NULL;
rom_info->pcm_rom_description = NULL;
rom_info->pcm_rom_sha1_digest = NULL;
}
}
static const MachineConfiguration *findMachineConfiguration(const char *machine_id) {
Bit32u configurationCount;
const MachineConfiguration * const *configurations = MachineConfiguration::getAllMachineConfigurations(&configurationCount);
for (Bit32u i = 0; i < configurationCount; i++) {
if (!strcmp(configurations[i]->getMachineID(), machine_id)) return configurations[i];
}
return NULL;
}
static mt32emu_return_code identifyROM(mt32emu_rom_info *rom_info, File *romFile, const char *machineID) {
const ROMInfo *romInfo;
if (machineID == NULL) {
romInfo = ROMInfo::getROMInfo(romFile);
} else {
const MachineConfiguration *configuration = findMachineConfiguration(machineID);
if (configuration == NULL) {
fillROMInfo(rom_info, NULL, NULL);
return MT32EMU_RC_MACHINE_NOT_IDENTIFIED;
}
romInfo = ROMInfo::getROMInfo(romFile, configuration->getCompatibleROMInfos());
}
if (romInfo == NULL) {
fillROMInfo(rom_info, NULL, NULL);
return MT32EMU_RC_ROM_NOT_IDENTIFIED;
}
if (romInfo->type == ROMInfo::Control) fillROMInfo(rom_info, romInfo, NULL);
else if (romInfo->type == ROMInfo::PCM) fillROMInfo(rom_info, NULL, romInfo);
else fillROMInfo(rom_info, NULL, NULL);
return MT32EMU_RC_OK;
}
static bool isROMInfoCompatible(const MachineConfiguration *machineConfiguration, const ROMInfo *romInfo) {
Bit32u romCount;
const ROMInfo * const *compatibleROMInfos = machineConfiguration->getCompatibleROMInfos(&romCount);
for (Bit32u i = 0; i < romCount; i++) {
if (romInfo == compatibleROMInfos[i]) return true;
}
return false;
}
static mt32emu_return_code replaceOrMergeROMImage(const ROMImage *&contextROMImage, const ROMImage *newROMImage, const MachineConfiguration *machineConfiguration, mt32emu_return_code addedFullROM, mt32emu_return_code addedPartialROM) {
if (contextROMImage != NULL) {
if (machineConfiguration != NULL) {
const ROMImage *mergedROMImage = ROMImage::mergeROMImages(contextROMImage, newROMImage);
if (mergedROMImage != NULL) {
if (newROMImage->isFileUserProvided()) delete newROMImage->getFile();
ROMImage::freeROMImage(newROMImage);
if (contextROMImage->isFileUserProvided()) delete contextROMImage->getFile();
ROMImage::freeROMImage(contextROMImage);
contextROMImage = mergedROMImage;
return addedFullROM;
}
if (newROMImage->getROMInfo() == contextROMImage->getROMInfo()
|| (newROMImage->getROMInfo()->pairType != ROMInfo::Full
&& isROMInfoCompatible(machineConfiguration, contextROMImage->getROMInfo()))) {
ROMImage::freeROMImage(newROMImage);
return MT32EMU_RC_OK;
}
}
if (contextROMImage->isFileUserProvided()) delete contextROMImage->getFile();
ROMImage::freeROMImage(contextROMImage);
}
contextROMImage = newROMImage;
return newROMImage->getROMInfo()->pairType == ROMInfo::Full ? addedFullROM: addedPartialROM;
}
static mt32emu_return_code addROMFiles(mt32emu_data *data, File *file1, File *file2 = NULL, const MachineConfiguration *machineConfiguration = NULL) {
const ROMImage *romImage;
if (machineConfiguration != NULL) {
romImage = ROMImage::makeROMImage(file1, machineConfiguration->getCompatibleROMInfos());
} else {
romImage = file2 == NULL ? ROMImage::makeROMImage(file1, ROMInfo::getFullROMInfos()) : ROMImage::makeROMImage(file1, file2);
}
if (romImage == NULL) return MT32EMU_RC_ROMS_NOT_PAIRABLE;
const ROMInfo *info = romImage->getROMInfo();
if (info == NULL) {
ROMImage::freeROMImage(romImage);
return MT32EMU_RC_ROM_NOT_IDENTIFIED;
}
switch (info->type) {
case ROMInfo::Control:
return replaceOrMergeROMImage(data->controlROMImage, romImage, machineConfiguration, MT32EMU_RC_ADDED_CONTROL_ROM, MT32EMU_RC_ADDED_PARTIAL_CONTROL_ROM);
case ROMInfo::PCM:
return replaceOrMergeROMImage(data->pcmROMImage, romImage, machineConfiguration, MT32EMU_RC_ADDED_PCM_ROM, MT32EMU_RC_ADDED_PARTIAL_PCM_ROM);
default:
ROMImage::freeROMImage(romImage);
return MT32EMU_RC_OK; // No support for reverb ROM yet.
}
}
static mt32emu_return_code createFileStream(const char *filename, FileStream *&fileStream) {
mt32emu_return_code rc;
fileStream = new FileStream;
if (!fileStream->open(filename)) {
rc = MT32EMU_RC_FILE_NOT_FOUND;
} else if (fileStream->getSize() == 0) {
rc = MT32EMU_RC_FILE_NOT_LOADED;
} else {
return MT32EMU_RC_OK;
}
delete fileStream;
fileStream = NULL;
return rc;
}
} // namespace MT32Emu
// C-visible implementation
extern "C" {
mt32emu_service_i MT32EMU_C_CALL mt32emu_get_service_i() {
mt32emu_service_i i;
i.v6 = &SERVICE_VTABLE;
return i;
}
mt32emu_report_handler_version MT32EMU_C_CALL mt32emu_get_supported_report_handler_version() {
return MT32EMU_REPORT_HANDLER_VERSION_CURRENT;
}
mt32emu_midi_receiver_version MT32EMU_C_CALL mt32emu_get_supported_midi_receiver_version() {
return MT32EMU_MIDI_RECEIVER_VERSION_CURRENT;
}
mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_library_version_int() {
return Synth::getLibraryVersionInt();
}
const char * MT32EMU_C_CALL mt32emu_get_library_version_string() {
return Synth::getLibraryVersionString();
}
mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_stereo_output_samplerate(const mt32emu_analog_output_mode analog_output_mode) {
return Synth::getStereoOutputSampleRate(static_cast<AnalogOutputMode>(analog_output_mode));
}
mt32emu_analog_output_mode MT32EMU_C_CALL mt32emu_get_best_analog_output_mode(const double target_samplerate) {
return mt32emu_analog_output_mode(SampleRateConverter::getBestAnalogOutputMode(target_samplerate));
}
size_t MT32EMU_C_CALL mt32emu_get_machine_ids(const char **machine_ids, size_t machine_ids_size) {
Bit32u configurationCount;
const MachineConfiguration * const *configurations = MachineConfiguration::getAllMachineConfigurations(&configurationCount);
if (machine_ids != NULL) {
for (Bit32u i = 0; i < machine_ids_size; i++) {
machine_ids[i] = i < configurationCount ? configurations[i]->getMachineID() : NULL;
}
}
return configurationCount;
}
size_t MT32EMU_C_CALL mt32emu_get_rom_ids(const char **rom_ids, size_t rom_ids_size, const char *machine_id) {
const ROMInfo * const *romInfos;
Bit32u romCount;
if (machine_id != NULL) {
const MachineConfiguration *configuration = findMachineConfiguration(machine_id);
if (configuration != NULL) {
romInfos = configuration->getCompatibleROMInfos(&romCount);
} else {
romInfos = NULL;
romCount = 0U;
}
} else {
romInfos = ROMInfo::getAllROMInfos(&romCount);
}
if (rom_ids != NULL) {
for (size_t i = 0; i < rom_ids_size; i++) {
rom_ids[i] = i < romCount ? romInfos[i]->shortName : NULL;
}
}
return romCount;
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_identify_rom_data(mt32emu_rom_info *rom_info, const mt32emu_bit8u *data, size_t data_size, const char *machine_id) {
ArrayFile romFile = ArrayFile(data, data_size);
return identifyROM(rom_info, &romFile, machine_id);
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_identify_rom_file(mt32emu_rom_info *rom_info, const char *filename, const char *machine_id) {
FileStream *fs;
mt32emu_return_code rc = createFileStream(filename, fs);
if (fs == NULL) return rc;
rc = identifyROM(rom_info, fs, machine_id);
delete fs;
return rc;
}
mt32emu_context MT32EMU_C_CALL mt32emu_create_context(mt32emu_report_handler_i report_handler, void *instance_data) {
mt32emu_data *data = new mt32emu_data;
data->synth = new Synth;
if (report_handler.v0 != NULL) {
data->reportHandler = new DelegatingReportHandlerAdapter(report_handler, instance_data);
data->synth->setReportHandler2(data->reportHandler);
} else {
data->reportHandler = NULL;
}
data->midiParser = new DefaultMidiStreamParser(*data->synth);
data->controlROMImage = NULL;
data->pcmROMImage = NULL;
data->partialCount = DEFAULT_MAX_PARTIALS;
data->analogOutputMode = AnalogOutputMode_COARSE;
data->srcState = new SamplerateConversionState;
data->srcState->outputSampleRate = 0.0;
data->srcState->srcQuality = SamplerateConversionQuality_GOOD;
data->srcState->src = NULL;
return data;
}
void MT32EMU_C_CALL mt32emu_free_context(mt32emu_context data) {
if (data == NULL) return;
delete data->srcState->src;
data->srcState->src = NULL;
delete data->srcState;
data->srcState = NULL;
if (data->controlROMImage != NULL) {
if (data->controlROMImage->isFileUserProvided()) delete data->controlROMImage->getFile();
ROMImage::freeROMImage(data->controlROMImage);
data->controlROMImage = NULL;
}
if (data->pcmROMImage != NULL) {
if (data->pcmROMImage->isFileUserProvided()) delete data->pcmROMImage->getFile();
ROMImage::freeROMImage(data->pcmROMImage);
data->pcmROMImage = NULL;
}
delete data->midiParser;
data->midiParser = NULL;
delete data->synth;
data->synth = NULL;
delete data->reportHandler;
data->reportHandler = NULL;
delete data;
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_add_rom_data(mt32emu_context context, const mt32emu_bit8u *data, size_t data_size, const mt32emu_sha1_digest *sha1_digest) {
if (sha1_digest == NULL) return addROMFiles(context, new ArrayFile(data, data_size));
return addROMFiles(context, new ArrayFile(data, data_size, *sha1_digest));
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_add_rom_file(mt32emu_context context, const char *filename) {
FileStream *fs;
mt32emu_return_code rc = createFileStream(filename, fs);
if (fs != NULL) rc = addROMFiles(context, fs);
if (rc <= MT32EMU_RC_OK) delete fs;
return rc;
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_merge_and_add_rom_data(mt32emu_context context, const mt32emu_bit8u *part1_data, size_t part1_data_size, const mt32emu_sha1_digest *part1_sha1_digest, const mt32emu_bit8u *part2_data, size_t part2_data_size, const mt32emu_sha1_digest *part2_sha1_digest) {
ArrayFile *file1 = part1_sha1_digest == NULL ? new ArrayFile(part1_data, part1_data_size) : new ArrayFile(part1_data, part1_data_size, *part1_sha1_digest);
ArrayFile *file2 = part2_sha1_digest == NULL ? new ArrayFile(part2_data, part2_data_size) : new ArrayFile(part2_data, part2_data_size, *part2_sha1_digest);
mt32emu_return_code rc = addROMFiles(context, file1, file2);
delete file1;
delete file2;
return rc;
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_merge_and_add_rom_files(mt32emu_context context, const char *part1_filename, const char *part2_filename) {
FileStream *fs1;
mt32emu_return_code rc = createFileStream(part1_filename, fs1);
if (fs1 != NULL) {
FileStream *fs2;
rc = createFileStream(part2_filename, fs2);
if (fs2 != NULL) {
rc = addROMFiles(context, fs1, fs2);
delete fs2;
}
delete fs1;
}
return rc;
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_add_machine_rom_file(mt32emu_context context, const char *machine_id, const char *filename) {
const MachineConfiguration *machineConfiguration = findMachineConfiguration(machine_id);
if (machineConfiguration == NULL) return MT32EMU_RC_MACHINE_NOT_IDENTIFIED;
FileStream *fs;
mt32emu_return_code rc = createFileStream(filename, fs);
if (fs == NULL) return rc;
rc = addROMFiles(context, fs, NULL, machineConfiguration);
if (rc <= MT32EMU_RC_OK) delete fs;
return rc;
}
void MT32EMU_C_CALL mt32emu_get_rom_info(mt32emu_const_context context, mt32emu_rom_info *rom_info) {
const ROMInfo *controlROMInfo = context->controlROMImage == NULL ? NULL : context->controlROMImage->getROMInfo();
const ROMInfo *pcmROMInfo = context->pcmROMImage == NULL ? NULL : context->pcmROMImage->getROMInfo();
fillROMInfo(rom_info, controlROMInfo, pcmROMInfo);
}
void MT32EMU_C_CALL mt32emu_set_partial_count(mt32emu_context context, const mt32emu_bit32u partial_count) {
context->partialCount = partial_count;
}
void MT32EMU_C_CALL mt32emu_set_analog_output_mode(mt32emu_context context, const mt32emu_analog_output_mode analog_output_mode) {
context->analogOutputMode = static_cast<AnalogOutputMode>(analog_output_mode);
}
void MT32EMU_C_CALL mt32emu_set_stereo_output_samplerate(mt32emu_context context, const double samplerate) {
context->srcState->outputSampleRate = SampleRateConverter::getSupportedOutputSampleRate(samplerate);
}
void MT32EMU_C_CALL mt32emu_set_samplerate_conversion_quality(mt32emu_context context, const mt32emu_samplerate_conversion_quality quality) {
context->srcState->srcQuality = SamplerateConversionQuality(quality);
}
void MT32EMU_C_CALL mt32emu_select_renderer_type(mt32emu_context context, const mt32emu_renderer_type renderer_type) {
context->synth->selectRendererType(static_cast<RendererType>(renderer_type));
}
mt32emu_renderer_type MT32EMU_C_CALL mt32emu_get_selected_renderer_type(mt32emu_context context) {
return static_cast<mt32emu_renderer_type>(context->synth->getSelectedRendererType());
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_open_synth(mt32emu_const_context context) {
if ((context->controlROMImage == NULL) || (context->pcmROMImage == NULL)) {
return MT32EMU_RC_MISSING_ROMS;
}
if (!context->synth->open(*context->controlROMImage, *context->pcmROMImage, context->partialCount, context->analogOutputMode)) {
return MT32EMU_RC_FAILED;
}
SamplerateConversionState &srcState = *context->srcState;
const double outputSampleRate = (0.0 < srcState.outputSampleRate) ? srcState.outputSampleRate : context->synth->getStereoOutputSampleRate();
srcState.src = new SampleRateConverter(*context->synth, outputSampleRate, srcState.srcQuality);
return MT32EMU_RC_OK;
}
void MT32EMU_C_CALL mt32emu_close_synth(mt32emu_const_context context) {
context->synth->close();
delete context->srcState->src;
context->srcState->src = NULL;
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_open(mt32emu_const_context context) {
return context->synth->isOpen() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_actual_stereo_output_samplerate(mt32emu_const_context context) {
if (context->srcState->src == NULL) {
return context->synth->getStereoOutputSampleRate();
}
return mt32emu_bit32u(0.5 + context->srcState->src->convertSynthToOutputTimestamp(SAMPLE_RATE));
}
mt32emu_bit32u MT32EMU_C_CALL mt32emu_convert_output_to_synth_timestamp(mt32emu_const_context context, mt32emu_bit32u output_timestamp) {
if (context->srcState->src == NULL) {
return output_timestamp;
}
return mt32emu_bit32u(0.5 + context->srcState->src->convertOutputToSynthTimestamp(output_timestamp));
}
mt32emu_bit32u MT32EMU_C_CALL mt32emu_convert_synth_to_output_timestamp(mt32emu_const_context context, mt32emu_bit32u synth_timestamp) {
if (context->srcState->src == NULL) {
return synth_timestamp;
}
return mt32emu_bit32u(0.5 + context->srcState->src->convertSynthToOutputTimestamp(synth_timestamp));
}
void MT32EMU_C_CALL mt32emu_flush_midi_queue(mt32emu_const_context context) {
context->synth->flushMIDIQueue();
}
mt32emu_bit32u MT32EMU_C_CALL mt32emu_set_midi_event_queue_size(mt32emu_const_context context, const mt32emu_bit32u queue_size) {
return context->synth->setMIDIEventQueueSize(queue_size);
}
void MT32EMU_C_CALL mt32emu_configure_midi_event_queue_sysex_storage(mt32emu_const_context context, const mt32emu_bit32u storage_buffer_size) {
context->synth->configureMIDIEventQueueSysexStorage(storage_buffer_size);
}
void MT32EMU_C_CALL mt32emu_set_midi_receiver(mt32emu_context context, mt32emu_midi_receiver_i midi_receiver, void *instance_data) {
delete context->midiParser;
context->midiParser = (midi_receiver.v0 != NULL) ? new DelegatingMidiStreamParser(context, midi_receiver, instance_data) : new DefaultMidiStreamParser(*context->synth);
}
mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_internal_rendered_sample_count(mt32emu_const_context context) {
return context->synth->getInternalRenderedSampleCount();
}
void MT32EMU_C_CALL mt32emu_parse_stream(mt32emu_const_context context, const mt32emu_bit8u *stream, mt32emu_bit32u length) {
context->midiParser->resetTimestamp();
context->midiParser->parseStream(stream, length);
}
void MT32EMU_C_CALL mt32emu_parse_stream_at(mt32emu_const_context context, const mt32emu_bit8u *stream, mt32emu_bit32u length, mt32emu_bit32u timestamp) {
context->midiParser->setTimestamp(timestamp);
context->midiParser->parseStream(stream, length);
}
void MT32EMU_C_CALL mt32emu_play_short_message(mt32emu_const_context context, mt32emu_bit32u message) {
context->midiParser->resetTimestamp();
context->midiParser->processShortMessage(message);
}
void MT32EMU_C_CALL mt32emu_play_short_message_at(mt32emu_const_context context, mt32emu_bit32u message, mt32emu_bit32u timestamp) {
context->midiParser->setTimestamp(timestamp);
context->midiParser->processShortMessage(message);
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_play_msg(mt32emu_const_context context, mt32emu_bit32u msg) {
if (!context->synth->isOpen()) return MT32EMU_RC_NOT_OPENED;
return (context->synth->playMsg(msg)) ? MT32EMU_RC_OK : MT32EMU_RC_QUEUE_FULL;
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_play_sysex(mt32emu_const_context context, const mt32emu_bit8u *sysex, mt32emu_bit32u len) {
if (!context->synth->isOpen()) return MT32EMU_RC_NOT_OPENED;
return (context->synth->playSysex(sysex, len)) ? MT32EMU_RC_OK : MT32EMU_RC_QUEUE_FULL;
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_play_msg_at(mt32emu_const_context context, mt32emu_bit32u msg, mt32emu_bit32u timestamp) {
if (!context->synth->isOpen()) return MT32EMU_RC_NOT_OPENED;
return (context->synth->playMsg(msg, timestamp)) ? MT32EMU_RC_OK : MT32EMU_RC_QUEUE_FULL;
}
mt32emu_return_code MT32EMU_C_CALL mt32emu_play_sysex_at(mt32emu_const_context context, const mt32emu_bit8u *sysex, mt32emu_bit32u len, mt32emu_bit32u timestamp) {
if (!context->synth->isOpen()) return MT32EMU_RC_NOT_OPENED;
return (context->synth->playSysex(sysex, len, timestamp)) ? MT32EMU_RC_OK : MT32EMU_RC_QUEUE_FULL;
}
void MT32EMU_C_CALL mt32emu_play_msg_now(mt32emu_const_context context, mt32emu_bit32u msg) {
context->synth->playMsgNow(msg);
}
void MT32EMU_C_CALL mt32emu_play_msg_on_part(mt32emu_const_context context, mt32emu_bit8u part, mt32emu_bit8u code, mt32emu_bit8u note, mt32emu_bit8u velocity) {
context->synth->playMsgOnPart(part, code, note, velocity);
}
void MT32EMU_C_CALL mt32emu_play_sysex_now(mt32emu_const_context context, const mt32emu_bit8u *sysex, mt32emu_bit32u len) {
context->synth->playSysexNow(sysex, len);
}
void MT32EMU_C_CALL mt32emu_write_sysex(mt32emu_const_context context, mt32emu_bit8u channel, const mt32emu_bit8u *sysex, mt32emu_bit32u len) {
context->synth->writeSysex(channel, sysex, len);
}
void MT32EMU_C_CALL mt32emu_set_reverb_enabled(mt32emu_const_context context, const mt32emu_boolean reverb_enabled) {
context->synth->setReverbEnabled(reverb_enabled != MT32EMU_BOOL_FALSE);
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_reverb_enabled(mt32emu_const_context context) {
return context->synth->isReverbEnabled() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
void MT32EMU_C_CALL mt32emu_set_reverb_overridden(mt32emu_const_context context, const mt32emu_boolean reverb_overridden) {
context->synth->setReverbOverridden(reverb_overridden != MT32EMU_BOOL_FALSE);
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_reverb_overridden(mt32emu_const_context context) {
return context->synth->isReverbOverridden() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
void MT32EMU_C_CALL mt32emu_set_reverb_compatibility_mode(mt32emu_const_context context, const mt32emu_boolean mt32_compatible_mode) {
context->synth->setReverbCompatibilityMode(mt32_compatible_mode != MT32EMU_BOOL_FALSE);
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_mt32_reverb_compatibility_mode(mt32emu_const_context context) {
return context->synth->isMT32ReverbCompatibilityMode() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_default_reverb_mt32_compatible(mt32emu_const_context context) {
return context->synth->isDefaultReverbMT32Compatible() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
void MT32EMU_C_CALL mt32emu_preallocate_reverb_memory(mt32emu_const_context context, const mt32emu_boolean enabled) {
context->synth->preallocateReverbMemory(enabled != MT32EMU_BOOL_FALSE);
}
void MT32EMU_C_CALL mt32emu_set_dac_input_mode(mt32emu_const_context context, const mt32emu_dac_input_mode mode) {
context->synth->setDACInputMode(static_cast<DACInputMode>(mode));
}
mt32emu_dac_input_mode MT32EMU_C_CALL mt32emu_get_dac_input_mode(mt32emu_const_context context) {
return static_cast<mt32emu_dac_input_mode>(context->synth->getDACInputMode());
}
void MT32EMU_C_CALL mt32emu_set_midi_delay_mode(mt32emu_const_context context, const mt32emu_midi_delay_mode mode) {
context->synth->setMIDIDelayMode(static_cast<MIDIDelayMode>(mode));
}
mt32emu_midi_delay_mode MT32EMU_C_CALL mt32emu_get_midi_delay_mode(mt32emu_const_context context) {
return static_cast<mt32emu_midi_delay_mode>(context->synth->getMIDIDelayMode());
}
void MT32EMU_C_CALL mt32emu_set_output_gain(mt32emu_const_context context, float gain) {
context->synth->setOutputGain(gain);
}
float MT32EMU_C_CALL mt32emu_get_output_gain(mt32emu_const_context context) {
return context->synth->getOutputGain();
}
void MT32EMU_C_CALL mt32emu_set_reverb_output_gain(mt32emu_const_context context, float gain) {
context->synth->setReverbOutputGain(gain);
}
float MT32EMU_C_CALL mt32emu_get_reverb_output_gain(mt32emu_const_context context) {
return context->synth->getReverbOutputGain();
}
void MT32EMU_C_CALL mt32emu_set_part_volume_override(mt32emu_const_context context, mt32emu_bit8u part_number, mt32emu_bit8u volume_override) {
context->synth->setPartVolumeOverride(part_number, volume_override);
}
mt32emu_bit8u MT32EMU_C_CALL mt32emu_get_part_volume_override(mt32emu_const_context context, mt32emu_bit8u part_number) {
return context->synth->getPartVolumeOverride(part_number);
}
void MT32EMU_C_CALL mt32emu_set_reversed_stereo_enabled(mt32emu_const_context context, const mt32emu_boolean enabled) {
context->synth->setReversedStereoEnabled(enabled != MT32EMU_BOOL_FALSE);
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_reversed_stereo_enabled(mt32emu_const_context context) {
return context->synth->isReversedStereoEnabled() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
void MT32EMU_C_CALL mt32emu_set_nice_amp_ramp_enabled(mt32emu_const_context context, const mt32emu_boolean enabled) {
context->synth->setNiceAmpRampEnabled(enabled != MT32EMU_BOOL_FALSE);
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_nice_amp_ramp_enabled(mt32emu_const_context context) {
return context->synth->isNiceAmpRampEnabled() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
void MT32EMU_C_CALL mt32emu_set_nice_panning_enabled(mt32emu_const_context context, const mt32emu_boolean enabled) {
context->synth->setNicePanningEnabled(enabled != MT32EMU_BOOL_FALSE);
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_nice_panning_enabled(mt32emu_const_context context) {
return context->synth->isNicePanningEnabled() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
void MT32EMU_C_CALL mt32emu_set_nice_partial_mixing_enabled(mt32emu_const_context context, const mt32emu_boolean enabled) {
context->synth->setNicePartialMixingEnabled(enabled != MT32EMU_BOOL_FALSE);
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_nice_partial_mixing_enabled(mt32emu_const_context context) {
return context->synth->isNicePartialMixingEnabled() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
void MT32EMU_C_CALL mt32emu_render_bit16s(mt32emu_const_context context, mt32emu_bit16s *stream, mt32emu_bit32u len) {
if (context->srcState->src != NULL) {
context->srcState->src->getOutputSamples(stream, len);
} else {
context->synth->render(stream, len);
}
}
void MT32EMU_C_CALL mt32emu_render_float(mt32emu_const_context context, float *stream, mt32emu_bit32u len) {
if (context->srcState->src != NULL) {
context->srcState->src->getOutputSamples(stream, len);
} else {
context->synth->render(stream, len);
}
}
void MT32EMU_C_CALL mt32emu_render_bit16s_streams(mt32emu_const_context context, const mt32emu_dac_output_bit16s_streams *streams, mt32emu_bit32u len) {
context->synth->renderStreams(*reinterpret_cast<const DACOutputStreams<Bit16s> *>(streams), len);
}
void MT32EMU_C_CALL mt32emu_render_float_streams(mt32emu_const_context context, const mt32emu_dac_output_float_streams *streams, mt32emu_bit32u len) {
context->synth->renderStreams(*reinterpret_cast<const DACOutputStreams<float> *>(streams), len);
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_has_active_partials(mt32emu_const_context context) {
return context->synth->hasActivePartials() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_active(mt32emu_const_context context) {
return context->synth->isActive() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_partial_count(mt32emu_const_context context) {
return context->synth->getPartialCount();
}
mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_part_states(mt32emu_const_context context) {
return context->synth->getPartStates();
}
void MT32EMU_C_CALL mt32emu_get_partial_states(mt32emu_const_context context, mt32emu_bit8u *partial_states) {
context->synth->getPartialStates(partial_states);
}
mt32emu_bit32u MT32EMU_C_CALL mt32emu_get_playing_notes(mt32emu_const_context context, mt32emu_bit8u part_number, mt32emu_bit8u *keys, mt32emu_bit8u *velocities) {
return context->synth->getPlayingNotes(part_number, keys, velocities);
}
const char * MT32EMU_C_CALL mt32emu_get_patch_name(mt32emu_const_context context, mt32emu_bit8u part_number) {
return context->synth->getPatchName(part_number);
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_get_sound_group_name(mt32emu_const_context context, char *sound_group_name, mt32emu_bit8u timbre_group, mt32emu_bit8u timbre_number) {
return context->synth->getSoundGroupName(sound_group_name, timbre_group, timbre_number) ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_get_sound_name(mt32emu_const_context context, char *sound_name, mt32emu_bit8u timbre_group, mt32emu_bit8u timbre_number) {
return context->synth->getSoundName(sound_name, timbre_group, timbre_number) ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
void MT32EMU_C_CALL mt32emu_read_memory(mt32emu_const_context context, mt32emu_bit32u addr, mt32emu_bit32u len, mt32emu_bit8u *data) {
context->synth->readMemory(addr, len, data);
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_get_display_state(mt32emu_const_context context, char *target_buffer, const mt32emu_boolean narrow_lcd) {
return context->synth->getDisplayState(target_buffer, narrow_lcd != MT32EMU_BOOL_FALSE) ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
void MT32EMU_C_CALL mt32emu_set_main_display_mode(mt32emu_const_context context) {
context->synth->setMainDisplayMode();
}
void MT32EMU_C_CALL mt32emu_set_display_compatibility(mt32emu_const_context context, mt32emu_boolean old_mt32_compatibility_enabled) {
context->synth->setDisplayCompatibility(old_mt32_compatibility_enabled != MT32EMU_BOOL_FALSE);
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_display_old_mt32_compatible(mt32emu_const_context context) {
return context->synth->isDisplayOldMT32Compatible() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
mt32emu_boolean MT32EMU_C_CALL mt32emu_is_default_display_old_mt32_compatible(mt32emu_const_context context) {
return context->synth->isDefaultDisplayOldMT32Compatible() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
} // extern "C"
``` | /content/code_sandbox/src/sound/munt/c_interface/c_interface.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 10,279 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include "SoxrAdapter.h"
#include "../Synth.h"
using namespace MT32Emu;
static const unsigned int CHANNEL_COUNT = 2;
size_t SoxrAdapter::getInputSamples(void *input_fn_state, soxr_in_t *data, size_t requested_len) {
unsigned int length = requested_len < 1 ? 1 : (MAX_SAMPLES_PER_RUN < requested_len ? MAX_SAMPLES_PER_RUN : static_cast<unsigned int>(requested_len));
SoxrAdapter *instance = static_cast<SoxrAdapter *>(input_fn_state);
instance->synth.render(instance->inBuffer, length);
*data = instance->inBuffer;
return length;
}
SoxrAdapter::SoxrAdapter(Synth &useSynth, double targetSampleRate, SamplerateConversionQuality quality) :
synth(useSynth),
inBuffer(new float[CHANNEL_COUNT * MAX_SAMPLES_PER_RUN])
{
soxr_io_spec_t ioSpec = soxr_io_spec(SOXR_FLOAT32_I, SOXR_FLOAT32_I);
unsigned long qualityRecipe;
switch (quality) {
case SamplerateConversionQuality_FASTEST:
qualityRecipe = SOXR_QQ;
break;
case SamplerateConversionQuality_FAST:
qualityRecipe = SOXR_LQ;
break;
case SamplerateConversionQuality_GOOD:
qualityRecipe = SOXR_MQ;
break;
case SamplerateConversionQuality_BEST:
default:
qualityRecipe = SOXR_16_BITQ;
break;
};
soxr_quality_spec_t qSpec = soxr_quality_spec(qualityRecipe, 0);
soxr_runtime_spec_t rtSpec = soxr_runtime_spec(1);
soxr_error_t error;
resampler = soxr_create(synth.getStereoOutputSampleRate(), targetSampleRate, CHANNEL_COUNT, &error, &ioSpec, &qSpec, &rtSpec);
if (error != NULL) {
synth.printDebug("SoxrAdapter: Creation of SOXR instance failed: %s\n", soxr_strerror(error));
soxr_delete(resampler);
resampler = NULL;
return;
}
error = soxr_set_input_fn(resampler, getInputSamples, this, MAX_SAMPLES_PER_RUN);
if (error != NULL) {
synth.printDebug("SoxrAdapter: Installing sample feed for SOXR failed: %s\n", soxr_strerror(error));
soxr_delete(resampler);
resampler = NULL;
}
}
SoxrAdapter::~SoxrAdapter() {
delete[] inBuffer;
if (resampler != NULL) {
soxr_delete(resampler);
}
}
void SoxrAdapter::getOutputSamples(float *buffer, unsigned int length) {
if (resampler == NULL) {
Synth::muteSampleBuffer(buffer, CHANNEL_COUNT * length);
return;
}
while (length > 0) {
size_t gotFrames = soxr_output(resampler, buffer, size_t(length));
soxr_error_t error = soxr_error(resampler);
if (error != NULL) {
synth.printDebug("SoxrAdapter: SOXR error during processing: %s > resetting\n", soxr_strerror(error));
error = soxr_clear(resampler);
if (error != NULL) {
synth.printDebug("SoxrAdapter: SOXR failed to reset: %s\n", soxr_strerror(error));
soxr_delete(resampler);
resampler = NULL;
Synth::muteSampleBuffer(buffer, CHANNEL_COUNT * length);
synth.printDebug("SoxrAdapter: SOXR disabled\n");
return;
}
continue;
}
if (gotFrames == 0) {
synth.printDebug("SoxrAdapter: got 0 frames from SOXR, weird\n");
}
buffer += CHANNEL_COUNT * gotFrames;
length -= static_cast<unsigned int>(gotFrames);
}
}
``` | /content/code_sandbox/src/sound/munt/srchelper/SoxrAdapter.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 906 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_SOXR_ADAPTER_H
#define MT32EMU_SOXR_ADAPTER_H
#include <soxr.h>
#include "../Enumerations.h"
namespace MT32Emu {
class Synth;
class SoxrAdapter {
public:
SoxrAdapter(Synth &synth, double targetSampleRate, SamplerateConversionQuality quality);
~SoxrAdapter();
void getOutputSamples(float *buffer, unsigned int length);
private:
Synth &synth;
float * const inBuffer;
soxr_t resampler;
static size_t getInputSamples(void *input_fn_state, soxr_in_t *data, size_t requested_len);
};
} // namespace MT32Emu
#endif // MT32EMU_SOXR_ADAPTER_H
``` | /content/code_sandbox/src/sound/munt/srchelper/SoxrAdapter.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 240 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_INTERNAL_RESAMPLER_H
#define MT32EMU_INTERNAL_RESAMPLER_H
#include "../Enumerations.h"
#include "srctools/include/FloatSampleProvider.h"
namespace MT32Emu {
class Synth;
class InternalResampler {
public:
InternalResampler(Synth &synth, double targetSampleRate, SamplerateConversionQuality quality);
~InternalResampler();
void getOutputSamples(float *buffer, unsigned int length);
private:
SRCTools::FloatSampleProvider &synthSource;
SRCTools::FloatSampleProvider &model;
};
} // namespace MT32Emu
#endif // MT32EMU_INTERNAL_RESAMPLER_H
``` | /content/code_sandbox/src/sound/munt/srchelper/InternalResampler.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 230 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_CPP_INTERFACE_H
#define MT32EMU_CPP_INTERFACE_H
#include <cstdarg>
#include "../globals.h"
#include "c_types.h"
#include "../Types.h"
#include "../Enumerations.h"
#if MT32EMU_API_TYPE == 2
extern "C" {
/** Returns mt32emu_service_i interface. */
mt32emu_service_i mt32emu_get_service_i();
}
#define mt32emu_get_supported_report_handler_version i.v0->getSupportedReportHandlerVersionID
#define mt32emu_get_supported_midi_receiver_version i.v0->getSupportedMIDIReceiverVersionID
#define mt32emu_get_library_version_int i.v0->getLibraryVersionInt
#define mt32emu_get_library_version_string i.v0->getLibraryVersionString
#define mt32emu_get_stereo_output_samplerate i.v0->getStereoOutputSamplerate
#define mt32emu_get_best_analog_output_mode iV1()->getBestAnalogOutputMode
#define mt32emu_get_machine_ids iV4()->getMachineIDs
#define mt32emu_get_rom_ids iV4()->getROMIDs
#define mt32emu_identify_rom_data iV4()->identifyROMData
#define mt32emu_identify_rom_file iV4()->identifyROMFile
#define mt32emu_create_context i.v0->createContext
#define mt32emu_free_context i.v0->freeContext
#define mt32emu_add_rom_data i.v0->addROMData
#define mt32emu_add_rom_file i.v0->addROMFile
#define mt32emu_merge_and_add_rom_data iV4()->mergeAndAddROMData
#define mt32emu_merge_and_add_rom_files iV4()->mergeAndAddROMFiles
#define mt32emu_add_machine_rom_file iV4()->addMachineROMFile
#define mt32emu_get_rom_info i.v0->getROMInfo
#define mt32emu_set_partial_count i.v0->setPartialCount
#define mt32emu_set_analog_output_mode i.v0->setAnalogOutputMode
#define mt32emu_set_stereo_output_samplerate iV1()->setStereoOutputSampleRate
#define mt32emu_set_samplerate_conversion_quality iV1()->setSamplerateConversionQuality
#define mt32emu_select_renderer_type iV1()->selectRendererType
#define mt32emu_get_selected_renderer_type iV1()->getSelectedRendererType
#define mt32emu_open_synth i.v0->openSynth
#define mt32emu_close_synth i.v0->closeSynth
#define mt32emu_is_open i.v0->isOpen
#define mt32emu_get_actual_stereo_output_samplerate i.v0->getActualStereoOutputSamplerate
#define mt32emu_convert_output_to_synth_timestamp iV1()->convertOutputToSynthTimestamp
#define mt32emu_convert_synth_to_output_timestamp iV1()->convertSynthToOutputTimestamp
#define mt32emu_flush_midi_queue i.v0->flushMIDIQueue
#define mt32emu_set_midi_event_queue_size i.v0->setMIDIEventQueueSize
#define mt32emu_configure_midi_event_queue_sysex_storage iV3()->configureMIDIEventQueueSysexStorage
#define mt32emu_set_midi_receiver i.v0->setMIDIReceiver
#define mt32emu_get_internal_rendered_sample_count iV2()->getInternalRenderedSampleCount
#define mt32emu_parse_stream i.v0->parseStream
#define mt32emu_parse_stream_at i.v0->parseStream_At
#define mt32emu_play_short_message i.v0->playShortMessage
#define mt32emu_play_short_message_at i.v0->playShortMessageAt
#define mt32emu_play_msg i.v0->playMsg
#define mt32emu_play_sysex i.v0->playSysex
#define mt32emu_play_msg_at i.v0->playMsgAt
#define mt32emu_play_sysex_at i.v0->playSysexAt
#define mt32emu_play_msg_now i.v0->playMsgNow
#define mt32emu_play_msg_on_part i.v0->playMsgOnPart
#define mt32emu_play_sysex_now i.v0->playSysexNow
#define mt32emu_write_sysex i.v0->writeSysex
#define mt32emu_set_reverb_enabled i.v0->setReverbEnabled
#define mt32emu_is_reverb_enabled i.v0->isReverbEnabled
#define mt32emu_set_reverb_overridden i.v0->setReverbOverridden
#define mt32emu_is_reverb_overridden i.v0->isReverbOverridden
#define mt32emu_set_reverb_compatibility_mode i.v0->setReverbCompatibilityMode
#define mt32emu_is_mt32_reverb_compatibility_mode i.v0->isMT32ReverbCompatibilityMode
#define mt32emu_is_default_reverb_mt32_compatible i.v0->isDefaultReverbMT32Compatible
#define mt32emu_preallocate_reverb_memory iV3()->preallocateReverbMemory
#define mt32emu_set_dac_input_mode i.v0->setDACInputMode
#define mt32emu_get_dac_input_mode i.v0->getDACInputMode
#define mt32emu_set_midi_delay_mode i.v0->setMIDIDelayMode
#define mt32emu_get_midi_delay_mode i.v0->getMIDIDelayMode
#define mt32emu_set_output_gain i.v0->setOutputGain
#define mt32emu_get_output_gain i.v0->getOutputGain
#define mt32emu_set_reverb_output_gain i.v0->setReverbOutputGain
#define mt32emu_get_reverb_output_gain i.v0->getReverbOutputGain
#define mt32emu_set_part_volume_override iV5()->setPartVolumeOverride
#define mt32emu_get_part_volume_override iV5()->getPartVolumeOverride
#define mt32emu_set_reversed_stereo_enabled i.v0->setReversedStereoEnabled
#define mt32emu_is_reversed_stereo_enabled i.v0->isReversedStereoEnabled
#define mt32emu_set_nice_amp_ramp_enabled iV2()->setNiceAmpRampEnabled
#define mt32emu_is_nice_amp_ramp_enabled iV2()->isNiceAmpRampEnabled
#define mt32emu_set_nice_panning_enabled iV3()->setNicePanningEnabled
#define mt32emu_is_nice_panning_enabled iV3()->isNicePanningEnabled
#define mt32emu_set_nice_partial_mixing_enabled iV3()->setNicePartialMixingEnabled
#define mt32emu_is_nice_partial_mixing_enabled iV3()->isNicePartialMixingEnabled
#define mt32emu_render_bit16s i.v0->renderBit16s
#define mt32emu_render_float i.v0->renderFloat
#define mt32emu_render_bit16s_streams i.v0->renderBit16sStreams
#define mt32emu_render_float_streams i.v0->renderFloatStreams
#define mt32emu_has_active_partials i.v0->hasActivePartials
#define mt32emu_is_active i.v0->isActive
#define mt32emu_get_partial_count i.v0->getPartialCount
#define mt32emu_get_part_states i.v0->getPartStates
#define mt32emu_get_partial_states i.v0->getPartialStates
#define mt32emu_get_playing_notes i.v0->getPlayingNotes
#define mt32emu_get_patch_name i.v0->getPatchName
#define mt32emu_get_sound_group_name iV6()->getSoundGroupName
#define mt32emu_get_sound_name iV6()->getSoundName
#define mt32emu_read_memory i.v0->readMemory
#define mt32emu_get_display_state iV5()->getDisplayState
#define mt32emu_set_main_display_mode iV5()->setMainDisplayMode
#define mt32emu_set_display_compatibility iV5()->setDisplayCompatibility
#define mt32emu_is_display_old_mt32_compatible iV5()->isDisplayOldMT32Compatible
#define mt32emu_is_default_display_old_mt32_compatible iV5()->isDefaultDisplayOldMT32Compatible
#else // #if MT32EMU_API_TYPE == 2
#include "c_interface.h"
#endif // #if MT32EMU_API_TYPE == 2
namespace MT32Emu {
namespace CppInterfaceImpl {
static const mt32emu_report_handler_i NULL_REPORT_HANDLER = { NULL };
static mt32emu_report_handler_i getReportHandlerThunk(mt32emu_report_handler_version);
static mt32emu_midi_receiver_i getMidiReceiverThunk();
}
/*
* The classes below correspond to the interfaces defined in c_types.h and provided for convenience when using C++.
* The approach used makes no assumption of any internal class data memory layout, since the C++ standard does not
* provide any detail in this area and leaves it up to the implementation. Therefore, this way portability is guaranteed,
* despite the implementation may be a little inefficient.
* See c_types.h and c_interface.h for description of the corresponding interface methods.
*/
// Defines the interface for handling reported events (initial version).
// Corresponds to the mt32emu_report_handler_i_v0 interface.
class IReportHandler {
public:
virtual void printDebug(const char *fmt, va_list list) = 0;
virtual void onErrorControlROM() = 0;
virtual void onErrorPCMROM() = 0;
virtual void showLCDMessage(const char *message) = 0;
virtual void onMIDIMessagePlayed() = 0;
virtual bool onMIDIQueueOverflow() = 0;
virtual void onMIDISystemRealtime(Bit8u system_realtime) = 0;
virtual void onDeviceReset() = 0;
virtual void onDeviceReconfig() = 0;
virtual void onNewReverbMode(Bit8u mode) = 0;
virtual void onNewReverbTime(Bit8u time) = 0;
virtual void onNewReverbLevel(Bit8u level) = 0;
virtual void onPolyStateChanged(Bit8u part_num) = 0;
virtual void onProgramChanged(Bit8u part_num, const char *sound_group_name, const char *patch_name) = 0;
protected:
~IReportHandler() {}
};
// Extends IReportHandler, so that the client may supply callbacks for reporting signals about updated display state.
// Corresponds to the mt32emu_report_handler_i_v1 interface.
class IReportHandlerV1 : public IReportHandler {
public:
virtual void onLCDStateUpdated() = 0;
virtual void onMidiMessageLEDStateUpdated(bool ledState) = 0;
protected:
~IReportHandlerV1() {}
};
// Defines the interface for receiving MIDI messages generated by MIDI stream parser.
// Corresponds to the current version of mt32emu_midi_receiver_i interface.
class IMidiReceiver {
public:
virtual void handleShortMessage(const Bit32u message) = 0;
virtual void handleSysex(const Bit8u stream[], const Bit32u length) = 0;
virtual void handleSystemRealtimeMessage(const Bit8u realtime) = 0;
protected:
~IMidiReceiver() {}
};
// Defines all the library services.
// Corresponds to the current version of mt32emu_service_i interface.
class Service {
public:
#if MT32EMU_API_TYPE == 2
explicit Service(mt32emu_service_i interface, mt32emu_context context = NULL) : i(interface), c(context) {}
#else
explicit Service(mt32emu_context context = NULL) : c(context) {}
#endif
~Service() { if (c != NULL) mt32emu_free_context(c); }
// Context-independent methods
#if MT32EMU_API_TYPE == 2
mt32emu_service_version getVersionID() { return i.v0->getVersionID(i); }
#endif
mt32emu_report_handler_version getSupportedReportHandlerVersionID() { return mt32emu_get_supported_report_handler_version(); }
mt32emu_midi_receiver_version getSupportedMIDIReceiverVersionID() { return mt32emu_get_supported_midi_receiver_version(); }
Bit32u getLibraryVersionInt() { return mt32emu_get_library_version_int(); }
const char *getLibraryVersionString() { return mt32emu_get_library_version_string(); }
Bit32u getStereoOutputSamplerate(const AnalogOutputMode analog_output_mode) { return mt32emu_get_stereo_output_samplerate(static_cast<mt32emu_analog_output_mode>(analog_output_mode)); }
AnalogOutputMode getBestAnalogOutputMode(const double target_samplerate) { return static_cast<AnalogOutputMode>(mt32emu_get_best_analog_output_mode(target_samplerate)); }
size_t getMachineIDs(const char **machine_ids, size_t machine_ids_size) { return mt32emu_get_machine_ids(machine_ids, machine_ids_size); }
size_t getROMIDs(const char **rom_ids, size_t rom_ids_size, const char *machine_id) { return mt32emu_get_rom_ids(rom_ids, rom_ids_size, machine_id); }
mt32emu_return_code identifyROMData(mt32emu_rom_info *rom_info, const Bit8u *data, size_t data_size, const char *machine_id) { return mt32emu_identify_rom_data(rom_info, data, data_size, machine_id); }
mt32emu_return_code identifyROMFile(mt32emu_rom_info *rom_info, const char *filename, const char *machine_id) { return mt32emu_identify_rom_file(rom_info, filename, machine_id); }
// Context-dependent methods
mt32emu_context getContext() { return c; }
void createContext(mt32emu_report_handler_i report_handler = CppInterfaceImpl::NULL_REPORT_HANDLER, void *instance_data = NULL) { freeContext(); c = mt32emu_create_context(report_handler, instance_data); }
void createContext(IReportHandler &report_handler) { createContext(CppInterfaceImpl::getReportHandlerThunk(MT32EMU_REPORT_HANDLER_VERSION_0), &report_handler); }
void createContext(IReportHandlerV1 &report_handler) { createContext(CppInterfaceImpl::getReportHandlerThunk(MT32EMU_REPORT_HANDLER_VERSION_1), &report_handler); }
void freeContext() { if (c != NULL) { mt32emu_free_context(c); c = NULL; } }
mt32emu_return_code addROMData(const Bit8u *data, size_t data_size, const mt32emu_sha1_digest *sha1_digest = NULL) { return mt32emu_add_rom_data(c, data, data_size, sha1_digest); }
mt32emu_return_code addROMFile(const char *filename) { return mt32emu_add_rom_file(c, filename); }
mt32emu_return_code mergeAndAddROMData(const Bit8u *part1_data, size_t part1_data_size, const Bit8u *part2_data, size_t part2_data_size) { return mt32emu_merge_and_add_rom_data(c, part1_data, part1_data_size, NULL, part2_data, part2_data_size, NULL); }
mt32emu_return_code mergeAndAddROMData(const Bit8u *part1_data, size_t part1_data_size, const mt32emu_sha1_digest *part1_sha1_digest, const Bit8u *part2_data, size_t part2_data_size, const mt32emu_sha1_digest *part2_sha1_digest) { return mt32emu_merge_and_add_rom_data(c, part1_data, part1_data_size, part1_sha1_digest, part2_data, part2_data_size, part2_sha1_digest); }
mt32emu_return_code mergeAndAddROMFiles(const char *part1_filename, const char *part2_filename) { return mt32emu_merge_and_add_rom_files(c, part1_filename, part2_filename); }
mt32emu_return_code addMachineROMFile(const char *machine_id, const char *filename) { return mt32emu_add_machine_rom_file(c, machine_id, filename); }
void getROMInfo(mt32emu_rom_info *rom_info) { mt32emu_get_rom_info(c, rom_info); }
void setPartialCount(const Bit32u partial_count) { mt32emu_set_partial_count(c, partial_count); }
void setAnalogOutputMode(const AnalogOutputMode analog_output_mode) { mt32emu_set_analog_output_mode(c, static_cast<mt32emu_analog_output_mode>(analog_output_mode)); }
void setStereoOutputSampleRate(const double samplerate) { mt32emu_set_stereo_output_samplerate(c, samplerate); }
void setSamplerateConversionQuality(const SamplerateConversionQuality quality) { mt32emu_set_samplerate_conversion_quality(c, static_cast<mt32emu_samplerate_conversion_quality>(quality)); }
void selectRendererType(const RendererType newRendererType) { mt32emu_select_renderer_type(c, static_cast<mt32emu_renderer_type>(newRendererType)); }
RendererType getSelectedRendererType() { return static_cast<RendererType>(mt32emu_get_selected_renderer_type(c)); }
mt32emu_return_code openSynth() { return mt32emu_open_synth(c); }
void closeSynth() { mt32emu_close_synth(c); }
bool isOpen() { return mt32emu_is_open(c) != MT32EMU_BOOL_FALSE; }
Bit32u getActualStereoOutputSamplerate() { return mt32emu_get_actual_stereo_output_samplerate(c); }
Bit32u convertOutputToSynthTimestamp(Bit32u output_timestamp) { return mt32emu_convert_output_to_synth_timestamp(c, output_timestamp); }
Bit32u convertSynthToOutputTimestamp(Bit32u synth_timestamp) { return mt32emu_convert_synth_to_output_timestamp(c, synth_timestamp); }
void flushMIDIQueue() { mt32emu_flush_midi_queue(c); }
Bit32u setMIDIEventQueueSize(const Bit32u queue_size) { return mt32emu_set_midi_event_queue_size(c, queue_size); }
void configureMIDIEventQueueSysexStorage(const Bit32u storage_buffer_size) { mt32emu_configure_midi_event_queue_sysex_storage(c, storage_buffer_size); }
void setMIDIReceiver(mt32emu_midi_receiver_i midi_receiver, void *instance_data) { mt32emu_set_midi_receiver(c, midi_receiver, instance_data); }
void setMIDIReceiver(IMidiReceiver &midi_receiver) { setMIDIReceiver(CppInterfaceImpl::getMidiReceiverThunk(), &midi_receiver); }
Bit32u getInternalRenderedSampleCount() { return mt32emu_get_internal_rendered_sample_count(c); }
void parseStream(const Bit8u *stream, Bit32u length) { mt32emu_parse_stream(c, stream, length); }
void parseStream_At(const Bit8u *stream, Bit32u length, Bit32u timestamp) { mt32emu_parse_stream_at(c, stream, length, timestamp); }
void playShortMessage(Bit32u message) { mt32emu_play_short_message(c, message); }
void playShortMessageAt(Bit32u message, Bit32u timestamp) { mt32emu_play_short_message_at(c, message, timestamp); }
mt32emu_return_code playMsg(Bit32u msg) { return mt32emu_play_msg(c, msg); }
mt32emu_return_code playSysex(const Bit8u *sysex, Bit32u len) { return mt32emu_play_sysex(c, sysex, len); }
mt32emu_return_code playMsgAt(Bit32u msg, Bit32u timestamp) { return mt32emu_play_msg_at(c, msg, timestamp); }
mt32emu_return_code playSysexAt(const Bit8u *sysex, Bit32u len, Bit32u timestamp) { return mt32emu_play_sysex_at(c, sysex, len, timestamp); }
void playMsgNow(Bit32u msg) { mt32emu_play_msg_now(c, msg); }
void playMsgOnPart(Bit8u part, Bit8u code, Bit8u note, Bit8u velocity) { mt32emu_play_msg_on_part(c, part, code, note, velocity); }
void playSysexNow(const Bit8u *sysex, Bit32u len) { mt32emu_play_sysex_now(c, sysex, len); }
void writeSysex(Bit8u channel, const Bit8u *sysex, Bit32u len) { mt32emu_write_sysex(c, channel, sysex, len); }
void setReverbEnabled(const bool reverb_enabled) { mt32emu_set_reverb_enabled(c, reverb_enabled ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE); }
bool isReverbEnabled() { return mt32emu_is_reverb_enabled(c) != MT32EMU_BOOL_FALSE; }
void setReverbOverridden(const bool reverb_overridden) { mt32emu_set_reverb_overridden(c, reverb_overridden ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE); }
bool isReverbOverridden() { return mt32emu_is_reverb_overridden(c) != MT32EMU_BOOL_FALSE; }
void setReverbCompatibilityMode(const bool mt32_compatible_mode) { mt32emu_set_reverb_compatibility_mode(c, mt32_compatible_mode ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE); }
bool isMT32ReverbCompatibilityMode() { return mt32emu_is_mt32_reverb_compatibility_mode(c) != MT32EMU_BOOL_FALSE; }
bool isDefaultReverbMT32Compatible() { return mt32emu_is_default_reverb_mt32_compatible(c) != MT32EMU_BOOL_FALSE; }
void preallocateReverbMemory(const bool enabled) { mt32emu_preallocate_reverb_memory(c, enabled ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE); }
void setDACInputMode(const DACInputMode mode) { mt32emu_set_dac_input_mode(c, static_cast<mt32emu_dac_input_mode>(mode)); }
DACInputMode getDACInputMode() { return static_cast<DACInputMode>(mt32emu_get_dac_input_mode(c)); }
void setMIDIDelayMode(const MIDIDelayMode mode) { mt32emu_set_midi_delay_mode(c, static_cast<mt32emu_midi_delay_mode>(mode)); }
MIDIDelayMode getMIDIDelayMode() { return static_cast<MIDIDelayMode>(mt32emu_get_midi_delay_mode(c)); }
void setOutputGain(float gain) { mt32emu_set_output_gain(c, gain); }
float getOutputGain() { return mt32emu_get_output_gain(c); }
void setReverbOutputGain(float gain) { mt32emu_set_reverb_output_gain(c, gain); }
float getReverbOutputGain() { return mt32emu_get_reverb_output_gain(c); }
void setPartVolumeOverride(Bit8u part_number, Bit8u volume_override) { mt32emu_set_part_volume_override(c, part_number, volume_override); }
Bit8u getPartVolumeOverride(Bit8u part_number) { return mt32emu_get_part_volume_override(c, part_number); }
void setReversedStereoEnabled(const bool enabled) { mt32emu_set_reversed_stereo_enabled(c, enabled ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE); }
bool isReversedStereoEnabled() { return mt32emu_is_reversed_stereo_enabled(c) != MT32EMU_BOOL_FALSE; }
void setNiceAmpRampEnabled(const bool enabled) { mt32emu_set_nice_amp_ramp_enabled(c, enabled ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE); }
bool isNiceAmpRampEnabled() { return mt32emu_is_nice_amp_ramp_enabled(c) != MT32EMU_BOOL_FALSE; }
void setNicePanningEnabled(const bool enabled) { mt32emu_set_nice_panning_enabled(c, enabled ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE); }
bool isNicePanningEnabled() { return mt32emu_is_nice_panning_enabled(c) != MT32EMU_BOOL_FALSE; }
void setNicePartialMixingEnabled(const bool enabled) { mt32emu_set_nice_partial_mixing_enabled(c, enabled ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE); }
bool isNicePartialMixingEnabled() { return mt32emu_is_nice_partial_mixing_enabled(c) != MT32EMU_BOOL_FALSE; }
void renderBit16s(Bit16s *stream, Bit32u len) { mt32emu_render_bit16s(c, stream, len); }
void renderFloat(float *stream, Bit32u len) { mt32emu_render_float(c, stream, len); }
void renderBit16sStreams(const mt32emu_dac_output_bit16s_streams *streams, Bit32u len) { mt32emu_render_bit16s_streams(c, streams, len); }
void renderFloatStreams(const mt32emu_dac_output_float_streams *streams, Bit32u len) { mt32emu_render_float_streams(c, streams, len); }
bool hasActivePartials() { return mt32emu_has_active_partials(c) != MT32EMU_BOOL_FALSE; }
bool isActive() { return mt32emu_is_active(c) != MT32EMU_BOOL_FALSE; }
Bit32u getPartialCount() { return mt32emu_get_partial_count(c); }
Bit32u getPartStates() { return mt32emu_get_part_states(c); }
void getPartialStates(Bit8u *partial_states) { mt32emu_get_partial_states(c, partial_states); }
Bit32u getPlayingNotes(Bit8u part_number, Bit8u *keys, Bit8u *velocities) { return mt32emu_get_playing_notes(c, part_number, keys, velocities); }
const char *getPatchName(Bit8u part_number) { return mt32emu_get_patch_name(c, part_number); }
bool getSoundGroupName(char *soundGroupName, Bit8u timbreGroup, Bit8u timbreNumber) { return mt32emu_get_sound_group_name(c, soundGroupName, timbreGroup, timbreNumber) != MT32EMU_BOOL_FALSE; }
bool getSoundName(char *soundName, Bit8u timbreGroup, Bit8u timbreNumber) { return mt32emu_get_sound_name(c, soundName, timbreGroup, timbreNumber) != MT32EMU_BOOL_FALSE; }
void readMemory(Bit32u addr, Bit32u len, Bit8u *data) { mt32emu_read_memory(c, addr, len, data); }
bool getDisplayState(char *target_buffer, const bool narrow_lcd) { return mt32emu_get_display_state(c, target_buffer, narrow_lcd ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE) != MT32EMU_BOOL_FALSE; }
void setMainDisplayMode() { mt32emu_set_main_display_mode(c); }
void setDisplayCompatibility(const bool oldMT32CompatibilityEnabled) { mt32emu_set_display_compatibility(c, oldMT32CompatibilityEnabled ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE); }
bool isDisplayOldMT32Compatible() { return mt32emu_is_display_old_mt32_compatible(c) != MT32EMU_BOOL_FALSE; }
bool isDefaultDisplayOldMT32Compatible() { return mt32emu_is_default_display_old_mt32_compatible(c) != MT32EMU_BOOL_FALSE; }
private:
#if MT32EMU_API_TYPE == 2
const mt32emu_service_i i;
#endif
mt32emu_context c;
#if MT32EMU_API_TYPE == 2
const mt32emu_service_i_v1 *iV1() { return (getVersionID() < MT32EMU_SERVICE_VERSION_1) ? NULL : i.v1; }
const mt32emu_service_i_v2 *iV2() { return (getVersionID() < MT32EMU_SERVICE_VERSION_2) ? NULL : i.v2; }
const mt32emu_service_i_v3 *iV3() { return (getVersionID() < MT32EMU_SERVICE_VERSION_3) ? NULL : i.v3; }
const mt32emu_service_i_v4 *iV4() { return (getVersionID() < MT32EMU_SERVICE_VERSION_4) ? NULL : i.v4; }
const mt32emu_service_i_v5 *iV5() { return (getVersionID() < MT32EMU_SERVICE_VERSION_5) ? NULL : i.v5; }
const mt32emu_service_i_v6 *iV6() { return (getVersionID() < MT32EMU_SERVICE_VERSION_6) ? NULL : i.v6; }
#endif
Service(const Service &); // prevent copy-construction
Service& operator=(const Service &); // prevent assignment
};
namespace CppInterfaceImpl {
static mt32emu_report_handler_version MT32EMU_C_CALL getReportHandlerVersionID(mt32emu_report_handler_i);
static void MT32EMU_C_CALL printDebug(void *instance_data, const char *fmt, va_list list) {
static_cast<IReportHandler *>(instance_data)->printDebug(fmt, list);
}
static void MT32EMU_C_CALL onErrorControlROM(void *instance_data) {
static_cast<IReportHandler *>(instance_data)->onErrorControlROM();
}
static void MT32EMU_C_CALL onErrorPCMROM(void *instance_data) {
static_cast<IReportHandler *>(instance_data)->onErrorPCMROM();
}
static void MT32EMU_C_CALL showLCDMessage(void *instance_data, const char *message) {
static_cast<IReportHandler *>(instance_data)->showLCDMessage(message);
}
static void MT32EMU_C_CALL onMIDIMessagePlayed(void *instance_data) {
static_cast<IReportHandler *>(instance_data)->onMIDIMessagePlayed();
}
static mt32emu_boolean MT32EMU_C_CALL onMIDIQueueOverflow(void *instance_data) {
return static_cast<IReportHandler *>(instance_data)->onMIDIQueueOverflow() ? MT32EMU_BOOL_TRUE : MT32EMU_BOOL_FALSE;
}
static void MT32EMU_C_CALL onMIDISystemRealtime(void *instance_data, mt32emu_bit8u system_realtime) {
static_cast<IReportHandler *>(instance_data)->onMIDISystemRealtime(system_realtime);
}
static void MT32EMU_C_CALL onDeviceReset(void *instance_data) {
static_cast<IReportHandler *>(instance_data)->onDeviceReset();
}
static void MT32EMU_C_CALL onDeviceReconfig(void *instance_data) {
static_cast<IReportHandler *>(instance_data)->onDeviceReconfig();
}
static void MT32EMU_C_CALL onNewReverbMode(void *instance_data, mt32emu_bit8u mode) {
static_cast<IReportHandler *>(instance_data)->onNewReverbMode(mode);
}
static void MT32EMU_C_CALL onNewReverbTime(void *instance_data, mt32emu_bit8u time) {
static_cast<IReportHandler *>(instance_data)->onNewReverbTime(time);
}
static void MT32EMU_C_CALL onNewReverbLevel(void *instance_data, mt32emu_bit8u level) {
static_cast<IReportHandler *>(instance_data)->onNewReverbLevel(level);
}
static void MT32EMU_C_CALL onPolyStateChanged(void *instance_data, mt32emu_bit8u part_num) {
static_cast<IReportHandler *>(instance_data)->onPolyStateChanged(part_num);
}
static void MT32EMU_C_CALL onProgramChanged(void *instance_data, mt32emu_bit8u part_num, const char *sound_group_name, const char *patch_name) {
static_cast<IReportHandler *>(instance_data)->onProgramChanged(part_num, sound_group_name, patch_name);
}
static void MT32EMU_C_CALL onLCDStateUpdated(void *instance_data) {
static_cast<IReportHandlerV1 *>(instance_data)->onLCDStateUpdated();
}
static void MT32EMU_C_CALL onMidiMessageLEDStateUpdated(void *instance_data, mt32emu_boolean led_state) {
static_cast<IReportHandlerV1 *>(instance_data)->onMidiMessageLEDStateUpdated(led_state != MT32EMU_BOOL_FALSE);
}
#define MT32EMU_REPORT_HANDLER_V0_THUNK \
getReportHandlerVersionID, \
printDebug, \
onErrorControlROM, \
onErrorPCMROM, \
showLCDMessage, \
onMIDIMessagePlayed, \
onMIDIQueueOverflow, \
onMIDISystemRealtime, \
onDeviceReset, \
onDeviceReconfig, \
onNewReverbMode, \
onNewReverbTime, \
onNewReverbLevel, \
onPolyStateChanged, \
onProgramChanged
static const mt32emu_report_handler_i_v0 REPORT_HANDLER_V0_THUNK = {
MT32EMU_REPORT_HANDLER_V0_THUNK
};
static const mt32emu_report_handler_i_v1 REPORT_HANDLER_V1_THUNK = {
MT32EMU_REPORT_HANDLER_V0_THUNK,
onLCDStateUpdated,
onMidiMessageLEDStateUpdated
};
#undef MT32EMU_REPORT_HANDLER_THUNK_V0
static mt32emu_report_handler_version MT32EMU_C_CALL getReportHandlerVersionID(mt32emu_report_handler_i thunk) {
if (thunk.v0 == &REPORT_HANDLER_V0_THUNK) return MT32EMU_REPORT_HANDLER_VERSION_0;
return MT32EMU_REPORT_HANDLER_VERSION_CURRENT;
}
static mt32emu_report_handler_i getReportHandlerThunk(mt32emu_report_handler_version versionID) {
mt32emu_report_handler_i thunk;
if (versionID == MT32EMU_REPORT_HANDLER_VERSION_0) thunk.v0 = &REPORT_HANDLER_V0_THUNK;
else thunk.v1 = &REPORT_HANDLER_V1_THUNK;
return thunk;
}
static mt32emu_midi_receiver_version MT32EMU_C_CALL getMidiReceiverVersionID(mt32emu_midi_receiver_i) {
return MT32EMU_MIDI_RECEIVER_VERSION_CURRENT;
}
static void MT32EMU_C_CALL handleShortMessage(void *instance_data, const mt32emu_bit32u message) {
static_cast<IMidiReceiver *>(instance_data)->handleShortMessage(message);
}
static void MT32EMU_C_CALL handleSysex(void *instance_data, const mt32emu_bit8u stream[], const mt32emu_bit32u length) {
static_cast<IMidiReceiver *>(instance_data)->handleSysex(stream, length);
}
static void MT32EMU_C_CALL handleSystemRealtimeMessage(void *instance_data, const mt32emu_bit8u realtime) {
static_cast<IMidiReceiver *>(instance_data)->handleSystemRealtimeMessage(realtime);
}
static mt32emu_midi_receiver_i getMidiReceiverThunk() {
static const mt32emu_midi_receiver_i_v0 MIDI_RECEIVER_V0_THUNK = {
getMidiReceiverVersionID,
handleShortMessage,
handleSysex,
handleSystemRealtimeMessage
};
static const mt32emu_midi_receiver_i MIDI_RECEIVER_THUNK = { &MIDI_RECEIVER_V0_THUNK };
return MIDI_RECEIVER_THUNK;
}
} // namespace CppInterfaceImpl
} // namespace MT32Emu
#if MT32EMU_API_TYPE == 2
#undef mt32emu_get_supported_report_handler_version
#undef mt32emu_get_supported_midi_receiver_version
#undef mt32emu_get_library_version_int
#undef mt32emu_get_library_version_string
#undef mt32emu_get_stereo_output_samplerate
#undef mt32emu_get_best_analog_output_mode
#undef mt32emu_get_machine_ids
#undef mt32emu_get_rom_ids
#undef mt32emu_identify_rom_data
#undef mt32emu_identify_rom_file
#undef mt32emu_create_context
#undef mt32emu_free_context
#undef mt32emu_add_rom_data
#undef mt32emu_add_rom_file
#undef mt32emu_merge_and_add_rom_data
#undef mt32emu_merge_and_add_rom_files
#undef mt32emu_add_machine_rom_file
#undef mt32emu_get_rom_info
#undef mt32emu_set_partial_count
#undef mt32emu_set_analog_output_mode
#undef mt32emu_set_stereo_output_samplerate
#undef mt32emu_set_samplerate_conversion_quality
#undef mt32emu_select_renderer_type
#undef mt32emu_get_selected_renderer_type
#undef mt32emu_open_synth
#undef mt32emu_close_synth
#undef mt32emu_is_open
#undef mt32emu_get_actual_stereo_output_samplerate
#undef mt32emu_convert_output_to_synth_timestamp
#undef mt32emu_convert_synth_to_output_timestamp
#undef mt32emu_flush_midi_queue
#undef mt32emu_set_midi_event_queue_size
#undef mt32emu_configure_midi_event_queue_sysex_storage
#undef mt32emu_set_midi_receiver
#undef mt32emu_get_internal_rendered_sample_count
#undef mt32emu_parse_stream
#undef mt32emu_parse_stream_at
#undef mt32emu_play_short_message
#undef mt32emu_play_short_message_at
#undef mt32emu_play_msg
#undef mt32emu_play_sysex
#undef mt32emu_play_msg_at
#undef mt32emu_play_sysex_at
#undef mt32emu_play_msg_now
#undef mt32emu_play_msg_on_part
#undef mt32emu_play_sysex_now
#undef mt32emu_write_sysex
#undef mt32emu_set_reverb_enabled
#undef mt32emu_is_reverb_enabled
#undef mt32emu_set_reverb_overridden
#undef mt32emu_is_reverb_overridden
#undef mt32emu_set_reverb_compatibility_mode
#undef mt32emu_is_mt32_reverb_compatibility_mode
#undef mt32emu_is_default_reverb_mt32_compatible
#undef mt32emu_preallocate_reverb_memory
#undef mt32emu_set_dac_input_mode
#undef mt32emu_get_dac_input_mode
#undef mt32emu_set_midi_delay_mode
#undef mt32emu_get_midi_delay_mode
#undef mt32emu_set_output_gain
#undef mt32emu_get_output_gain
#undef mt32emu_set_reverb_output_gain
#undef mt32emu_get_reverb_output_gain
#undef mt32emu_set_reversed_stereo_enabled
#undef mt32emu_is_reversed_stereo_enabled
#undef mt32emu_set_nice_amp_ramp_enabled
#undef mt32emu_is_nice_amp_ramp_enabled
#undef mt32emu_set_nice_panning_enabled
#undef mt32emu_is_nice_panning_enabled
#undef mt32emu_set_nice_partial_mixing_enabled
#undef mt32emu_is_nice_partial_mixing_enabled
#undef mt32emu_render_bit16s
#undef mt32emu_render_float
#undef mt32emu_render_bit16s_streams
#undef mt32emu_render_float_streams
#undef mt32emu_has_active_partials
#undef mt32emu_is_active
#undef mt32emu_get_partial_count
#undef mt32emu_get_part_states
#undef mt32emu_get_partial_states
#undef mt32emu_get_playing_notes
#undef mt32emu_get_patch_name
#undef mt32emu_get_sound_group_name
#undef mt32emu_get_sound_name
#undef mt32emu_read_memory
#undef mt32emu_get_display_state
#undef mt32emu_set_main_display_mode
#undef mt32emu_set_display_compatibility
#undef mt32emu_is_display_old_mt32_compatible
#undef mt32emu_is_default_display_old_mt32_compatible
#endif // #if MT32EMU_API_TYPE == 2
#endif /* #ifndef MT32EMU_CPP_INTERFACE_H */
``` | /content/code_sandbox/src/sound/munt/c_interface/cpp_interface.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 8,300 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include "InternalResampler.h"
#include "srctools/include/SincResampler.h"
#include "srctools/include/ResamplerModel.h"
#include "../Synth.h"
using namespace SRCTools;
namespace MT32Emu {
class SynthWrapper : public FloatSampleProvider {
Synth &synth;
public:
SynthWrapper(Synth &useSynth) : synth(useSynth)
{}
void getOutputSamples(FloatSample *outBuffer, unsigned int size) {
synth.render(outBuffer, size);
}
};
static FloatSampleProvider &createModel(Synth &synth, SRCTools::FloatSampleProvider &synthSource, double targetSampleRate, SamplerateConversionQuality quality) {
static const double MAX_AUDIBLE_FREQUENCY = 20000.0;
const double sourceSampleRate = synth.getStereoOutputSampleRate();
if (quality != SamplerateConversionQuality_FASTEST) {
const bool oversampledMode = synth.getStereoOutputSampleRate() == Synth::getStereoOutputSampleRate(AnalogOutputMode_OVERSAMPLED);
// Oversampled input allows to bypass IIR interpolation stage and, in some cases, IIR decimation stage
if (oversampledMode && (0.5 * sourceSampleRate) <= targetSampleRate) {
// NOTE: In the oversampled mode, the transition band starts at 20kHz and ends at 28kHz
double passband = MAX_AUDIBLE_FREQUENCY;
double stopband = 0.5 * sourceSampleRate + MAX_AUDIBLE_FREQUENCY;
ResamplerStage &resamplerStage = *SincResampler::createSincResampler(sourceSampleRate, targetSampleRate, passband, stopband, ResamplerModel::DEFAULT_DB_SNR, ResamplerModel::DEFAULT_WINDOWED_SINC_MAX_UPSAMPLE_FACTOR);
return ResamplerModel::createResamplerModel(synthSource, resamplerStage);
}
}
return ResamplerModel::createResamplerModel(synthSource, sourceSampleRate, targetSampleRate, static_cast<ResamplerModel::Quality>(quality));
}
} // namespace MT32Emu
using namespace MT32Emu;
InternalResampler::InternalResampler(Synth &synth, double targetSampleRate, SamplerateConversionQuality quality) :
synthSource(*new SynthWrapper(synth)),
model(createModel(synth, synthSource, targetSampleRate, quality))
{}
InternalResampler::~InternalResampler() {
ResamplerModel::freeResamplerModel(model, synthSource);
delete &synthSource;
}
void InternalResampler::getOutputSamples(float *buffer, unsigned int length) {
model.getOutputSamples(buffer, length);
}
``` | /content/code_sandbox/src/sound/munt/srchelper/InternalResampler.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 654 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include "SamplerateAdapter.h"
#include "../Synth.h"
using namespace MT32Emu;
static const unsigned int CHANNEL_COUNT = 2;
long SamplerateAdapter::getInputSamples(void *cb_data, float **data) {
SamplerateAdapter *instance = static_cast<SamplerateAdapter *>(cb_data);
unsigned int length = instance->inBufferSize < 1 ? 1 : (MAX_SAMPLES_PER_RUN < instance->inBufferSize ? MAX_SAMPLES_PER_RUN : instance->inBufferSize);
instance->synth.render(instance->inBuffer, length);
*data = instance->inBuffer;
instance->inBufferSize -= length;
return length;
}
SamplerateAdapter::SamplerateAdapter(Synth &useSynth, double targetSampleRate, SamplerateConversionQuality quality) :
synth(useSynth),
inBuffer(new float[CHANNEL_COUNT * MAX_SAMPLES_PER_RUN]),
inBufferSize(MAX_SAMPLES_PER_RUN),
inputToOutputRatio(useSynth.getStereoOutputSampleRate() / targetSampleRate),
outputToInputRatio(targetSampleRate / useSynth.getStereoOutputSampleRate())
{
int error;
int conversionType;
switch (quality) {
case SamplerateConversionQuality_FASTEST:
conversionType = SRC_LINEAR;
break;
case SamplerateConversionQuality_FAST:
conversionType = SRC_SINC_FASTEST;
break;
case SamplerateConversionQuality_BEST:
conversionType = SRC_SINC_BEST_QUALITY;
break;
case SamplerateConversionQuality_GOOD:
default:
conversionType = SRC_SINC_MEDIUM_QUALITY;
break;
};
resampler = src_callback_new(getInputSamples, conversionType, CHANNEL_COUNT, &error, this);
if (error != 0) {
synth.printDebug("SamplerateAdapter: Creation of Samplerate instance failed: %s\n", src_strerror(error));
src_delete(resampler);
resampler = NULL;
}
}
SamplerateAdapter::~SamplerateAdapter() {
delete[] inBuffer;
src_delete(resampler);
}
void SamplerateAdapter::getOutputSamples(float *buffer, unsigned int length) {
if (resampler == NULL) {
Synth::muteSampleBuffer(buffer, CHANNEL_COUNT * length);
return;
}
while (length > 0) {
inBufferSize = static_cast<unsigned int>(length * inputToOutputRatio + 0.5);
long gotFrames = src_callback_read(resampler, outputToInputRatio, long(length), buffer);
int error = src_error(resampler);
if (error != 0) {
synth.printDebug("SamplerateAdapter: Samplerate error during processing: %s > resetting\n", src_strerror(error));
error = src_reset(resampler);
if (error != 0) {
synth.printDebug("SamplerateAdapter: Samplerate failed to reset: %s\n", src_strerror(error));
src_delete(resampler);
resampler = NULL;
Synth::muteSampleBuffer(buffer, CHANNEL_COUNT * length);
synth.printDebug("SamplerateAdapter: Samplerate disabled\n");
return;
}
continue;
}
if (gotFrames <= 0) {
synth.printDebug("SamplerateAdapter: got %li frames from Samplerate, weird\n", gotFrames);
}
buffer += CHANNEL_COUNT * gotFrames;
length -= gotFrames;
}
}
``` | /content/code_sandbox/src/sound/munt/srchelper/SamplerateAdapter.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 793 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef MT32EMU_SAMPLERATE_ADAPTER_H
#define MT32EMU_SAMPLERATE_ADAPTER_H
#include <samplerate.h>
#include "../Enumerations.h"
namespace MT32Emu {
class Synth;
class SamplerateAdapter {
public:
SamplerateAdapter(Synth &synth, double targetSampleRate, SamplerateConversionQuality quality);
~SamplerateAdapter();
void getOutputSamples(float *outBuffer, unsigned int length);
private:
Synth &synth;
float * const inBuffer;
unsigned int inBufferSize;
const double inputToOutputRatio;
const double outputToInputRatio;
SRC_STATE *resampler;
static long getInputSamples(void *cb_data, float **data);
};
} // namespace MT32Emu
#endif // MT32EMU_SAMPLERATE_ADAPTER_H
``` | /content/code_sandbox/src/sound/munt/srchelper/SamplerateAdapter.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 255 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include "../include/LinearResampler.h"
using namespace SRCTools;
LinearResampler::LinearResampler(double sourceSampleRate, double targetSampleRate) :
inputToOutputRatio(sourceSampleRate / targetSampleRate),
position(1.0) // Preload delay line which effectively makes resampler zero phase
{}
void LinearResampler::process(const FloatSample *&inSamples, unsigned int &inLength, FloatSample *&outSamples, unsigned int &outLength) {
if (inLength == 0) return;
while (outLength > 0) {
while (1.0 <= position) {
position--;
inLength--;
for (unsigned int chIx = 0; chIx < LINEAR_RESAMPER_CHANNEL_COUNT; ++chIx) {
lastInputSamples[chIx] = *(inSamples++);
}
if (inLength == 0) return;
}
for (unsigned int chIx = 0; chIx < LINEAR_RESAMPER_CHANNEL_COUNT; chIx++) {
*(outSamples++) = FloatSample(lastInputSamples[chIx] + position * (inSamples[chIx] - lastInputSamples[chIx]));
}
outLength--;
position += inputToOutputRatio;
}
}
unsigned int LinearResampler::estimateInLength(const unsigned int outLength) const {
return static_cast<unsigned int>(outLength * inputToOutputRatio);
}
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/src/LinearResampler.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 386 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cmath>
#include <cstring>
#include "../include/FIRResampler.h"
using namespace SRCTools;
FIRResampler::Constants::Constants(const unsigned int upsampleFactor, const double downsampleFactor, const FIRCoefficient kernel[], const unsigned int kernelLength) {
usePhaseInterpolation = downsampleFactor != floor(downsampleFactor);
FIRCoefficient *kernelCopy = new FIRCoefficient[kernelLength];
memcpy(kernelCopy, kernel, kernelLength * sizeof(FIRCoefficient));
taps = kernelCopy;
numberOfTaps = kernelLength;
numberOfPhases = upsampleFactor;
phaseIncrement = downsampleFactor;
unsigned int minDelayLineLength = static_cast<unsigned int>(ceil(double(kernelLength) / upsampleFactor));
unsigned int delayLineLength = 2;
while (delayLineLength < minDelayLineLength) delayLineLength <<= 1;
delayLineMask = delayLineLength - 1;
ringBuffer = new FloatSample[delayLineLength][FIR_INTERPOLATOR_CHANNEL_COUNT];
FloatSample *s = *ringBuffer;
FloatSample *e = ringBuffer[delayLineLength];
while (s < e) *(s++) = 0;
}
FIRResampler::FIRResampler(const unsigned int upsampleFactor, const double downsampleFactor, const FIRCoefficient kernel[], const unsigned int kernelLength) :
constants(upsampleFactor, downsampleFactor, kernel, kernelLength),
ringBufferPosition(0),
phase(constants.numberOfPhases)
{}
FIRResampler::~FIRResampler() {
delete[] constants.ringBuffer;
delete[] constants.taps;
}
void FIRResampler::process(const FloatSample *&inSamples, unsigned int &inLength, FloatSample *&outSamples, unsigned int &outLength) {
while (outLength > 0) {
while (needNextInSample()) {
if (inLength == 0) return;
addInSamples(inSamples);
--inLength;
}
getOutSamplesStereo(outSamples);
--outLength;
}
}
unsigned int FIRResampler::estimateInLength(const unsigned int outLength) const {
return static_cast<unsigned int>((outLength * constants.phaseIncrement + phase) / constants.numberOfPhases);
}
bool FIRResampler::needNextInSample() const {
return constants.numberOfPhases <= phase;
}
void FIRResampler::addInSamples(const FloatSample *&inSamples) {
ringBufferPosition = (ringBufferPosition - 1) & constants.delayLineMask;
for (unsigned int i = 0; i < FIR_INTERPOLATOR_CHANNEL_COUNT; i++) {
constants.ringBuffer[ringBufferPosition][i] = *(inSamples++);
}
phase -= constants.numberOfPhases;
}
// Optimised for processing stereo interleaved streams
void FIRResampler::getOutSamplesStereo(FloatSample *&outSamples) {
FloatSample leftSample = 0.0;
FloatSample rightSample = 0.0;
unsigned int delaySampleIx = ringBufferPosition;
if (constants.usePhaseInterpolation) {
double phaseFraction = phase - floor(phase);
unsigned int maxTapIx = phaseFraction == 0 ? constants.numberOfTaps : constants.numberOfTaps - 1;
for (unsigned int tapIx = static_cast<unsigned int>(phase); tapIx < maxTapIx; tapIx += constants.numberOfPhases) {
FIRCoefficient tap = FIRCoefficient(constants.taps[tapIx] + (constants.taps[tapIx + 1] - constants.taps[tapIx]) * phaseFraction);
leftSample += tap * constants.ringBuffer[delaySampleIx][0];
rightSample += tap * constants.ringBuffer[delaySampleIx][1];
delaySampleIx = (delaySampleIx + 1) & constants.delayLineMask;
}
} else {
// Optimised for rational resampling ratios when phase is always integer
for (unsigned int tapIx = static_cast<unsigned int>(phase); tapIx < constants.numberOfTaps; tapIx += constants.numberOfPhases) {
FIRCoefficient tap = constants.taps[tapIx];
leftSample += tap * constants.ringBuffer[delaySampleIx][0];
rightSample += tap * constants.ringBuffer[delaySampleIx][1];
delaySampleIx = (delaySampleIx + 1) & constants.delayLineMask;
}
}
*(outSamples++) = leftSample;
*(outSamples++) = rightSample;
phase += constants.phaseIncrement;
}
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/src/FIRResampler.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,047 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cmath>
#include <cstddef>
#include "../include/ResamplerModel.h"
#include "../include/ResamplerStage.h"
#include "../include/SincResampler.h"
#include "../include/IIR2xResampler.h"
#include "../include/LinearResampler.h"
namespace SRCTools {
namespace ResamplerModel {
static const unsigned int CHANNEL_COUNT = 2;
static const unsigned int MAX_SAMPLES_PER_RUN = 4096;
class CascadeStage : public FloatSampleProvider {
friend void freeResamplerModel(FloatSampleProvider &model, FloatSampleProvider &source);
public:
CascadeStage(FloatSampleProvider &source, ResamplerStage &resamplerStage);
void getOutputSamples(FloatSample *outBuffer, unsigned int size);
protected:
ResamplerStage &resamplerStage;
private:
FloatSampleProvider &source;
FloatSample buffer[CHANNEL_COUNT * MAX_SAMPLES_PER_RUN];
const FloatSample *bufferPtr;
unsigned int size;
};
class InternalResamplerCascadeStage : public CascadeStage {
public:
InternalResamplerCascadeStage(FloatSampleProvider &useSource, ResamplerStage &useResamplerStage) :
CascadeStage(useSource, useResamplerStage)
{}
~InternalResamplerCascadeStage() {
delete &resamplerStage;
}
};
} // namespace ResamplerModel
} // namespace SRCTools
using namespace SRCTools;
FloatSampleProvider &ResamplerModel::createResamplerModel(FloatSampleProvider &source, double sourceSampleRate, double targetSampleRate, Quality quality) {
if (sourceSampleRate == targetSampleRate) {
return source;
}
if (quality == FASTEST) {
return *new InternalResamplerCascadeStage(source, *new LinearResampler(sourceSampleRate, targetSampleRate));
}
const IIRResampler::Quality iirQuality = static_cast<IIRResampler::Quality>(quality);
const double iirPassbandFraction = IIRResampler::getPassbandFractionForQuality(iirQuality);
if (sourceSampleRate < targetSampleRate) {
ResamplerStage *iir2xInterpolator = new IIR2xInterpolator(iirQuality);
FloatSampleProvider &iir2xInterpolatorStage = *new InternalResamplerCascadeStage(source, *iir2xInterpolator);
if (2.0 * sourceSampleRate == targetSampleRate) {
return iir2xInterpolatorStage;
}
double passband = 0.5 * sourceSampleRate * iirPassbandFraction;
double stopband = 1.5 * sourceSampleRate;
ResamplerStage *sincResampler = SincResampler::createSincResampler(2.0 * sourceSampleRate, targetSampleRate, passband, stopband, DEFAULT_DB_SNR, DEFAULT_WINDOWED_SINC_MAX_UPSAMPLE_FACTOR);
return *new InternalResamplerCascadeStage(iir2xInterpolatorStage, *sincResampler);
}
if (sourceSampleRate == 2.0 * targetSampleRate) {
ResamplerStage *iir2xDecimator = new IIR2xDecimator(iirQuality);
return *new InternalResamplerCascadeStage(source, *iir2xDecimator);
}
double passband = 0.5 * targetSampleRate * iirPassbandFraction;
double stopband = 1.5 * targetSampleRate;
double sincOutSampleRate = 2.0 * targetSampleRate;
const unsigned int maxUpsampleFactor = static_cast<unsigned int>(ceil(DEFAULT_WINDOWED_SINC_MAX_DOWNSAMPLE_FACTOR * sincOutSampleRate / sourceSampleRate));
ResamplerStage *sincResampler = SincResampler::createSincResampler(sourceSampleRate, sincOutSampleRate, passband, stopband, DEFAULT_DB_SNR, maxUpsampleFactor);
FloatSampleProvider &sincResamplerStage = *new InternalResamplerCascadeStage(source, *sincResampler);
ResamplerStage *iir2xDecimator = new IIR2xDecimator(iirQuality);
return *new InternalResamplerCascadeStage(sincResamplerStage, *iir2xDecimator);
}
FloatSampleProvider &ResamplerModel::createResamplerModel(FloatSampleProvider &source, ResamplerStage **resamplerStages, unsigned int stageCount) {
FloatSampleProvider *prevStage = &source;
for (unsigned int i = 0; i < stageCount; i++) {
prevStage = new CascadeStage(*prevStage, *(resamplerStages[i]));
}
return *prevStage;
}
FloatSampleProvider &ResamplerModel::createResamplerModel(FloatSampleProvider &source, ResamplerStage &stage) {
return *new CascadeStage(source, stage);
}
void ResamplerModel::freeResamplerModel(FloatSampleProvider &model, FloatSampleProvider &source) {
FloatSampleProvider *currentStage = &model;
while (currentStage != &source) {
CascadeStage *cascadeStage = dynamic_cast<CascadeStage *>(currentStage);
if (cascadeStage == NULL) return;
FloatSampleProvider &prevStage = cascadeStage->source;
delete currentStage;
currentStage = &prevStage;
}
}
using namespace ResamplerModel;
CascadeStage::CascadeStage(FloatSampleProvider &useSource, ResamplerStage &useResamplerStage) :
resamplerStage(useResamplerStage),
source(useSource),
bufferPtr(buffer),
size()
{}
void CascadeStage::getOutputSamples(FloatSample *outBuffer, unsigned int length) {
while (length > 0) {
if (size == 0) {
size = resamplerStage.estimateInLength(length);
if (size < 1) {
size = 1;
} else if (MAX_SAMPLES_PER_RUN < size) {
size = MAX_SAMPLES_PER_RUN;
}
source.getOutputSamples(buffer, size);
bufferPtr = buffer;
}
resamplerStage.process(bufferPtr, size, outBuffer, length);
}
}
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/src/ResamplerModel.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,357 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cmath>
#ifdef SRCTOOLS_SINC_RESAMPLER_DEBUG_LOG
#include <iostream>
#endif
#include "../include/SincResampler.h"
#ifndef M_PI
static const double M_PI = 3.1415926535897932;
#endif
using namespace SRCTools;
using namespace SincResampler;
using namespace Utils;
void Utils::computeResampleFactors(unsigned int &upsampleFactor, double &downsampleFactor, const double inputFrequency, const double outputFrequency, const unsigned int maxUpsampleFactor) {
static const double RATIONAL_RATIO_ACCURACY_FACTOR = 1E15;
upsampleFactor = static_cast<unsigned int>(outputFrequency);
unsigned int downsampleFactorInt = static_cast<unsigned int>(inputFrequency);
if ((upsampleFactor == outputFrequency) && (downsampleFactorInt == inputFrequency)) {
// Input and output frequencies are integers, try to reduce them
const unsigned int gcd = greatestCommonDivisor(upsampleFactor, downsampleFactorInt);
if (gcd > 1) {
upsampleFactor /= gcd;
downsampleFactor = downsampleFactorInt / gcd;
} else {
downsampleFactor = downsampleFactorInt;
}
if (upsampleFactor <= maxUpsampleFactor) return;
} else {
// Try to recover rational resample ratio by brute force
double inputToOutputRatio = inputFrequency / outputFrequency;
for (unsigned int i = 1; i <= maxUpsampleFactor; ++i) {
double testFactor = inputToOutputRatio * i;
if (floor(RATIONAL_RATIO_ACCURACY_FACTOR * testFactor + 0.5) == RATIONAL_RATIO_ACCURACY_FACTOR * floor(testFactor + 0.5)) {
// inputToOutputRatio found to be rational within the accuracy
upsampleFactor = i;
downsampleFactor = floor(testFactor + 0.5);
return;
}
}
}
// Use interpolation of FIR taps as the last resort
upsampleFactor = maxUpsampleFactor;
downsampleFactor = maxUpsampleFactor * inputFrequency / outputFrequency;
}
unsigned int Utils::greatestCommonDivisor(unsigned int a, unsigned int b) {
while (0 < b) {
unsigned int r = a % b;
a = b;
b = r;
}
return a;
}
double KaizerWindow::estimateBeta(double dbRipple) {
return 0.1102 * (dbRipple - 8.7);
}
unsigned int KaizerWindow::estimateOrder(double dbRipple, double fp, double fs) {
const double transBW = (fs - fp);
return static_cast<unsigned int>(ceil((dbRipple - 8) / (2.285 * 2 * M_PI * transBW)));
}
double KaizerWindow::bessel(const double x) {
static const double EPS = 1.11E-16;
double sum = 0.0;
double f = 1.0;
for (unsigned int i = 1;; ++i) {
f *= (0.5 * x / i);
double f2 = f * f;
if (f2 <= sum * EPS) break;
sum += f2;
}
return 1.0 + sum;
}
void KaizerWindow::windowedSinc(FIRCoefficient kernel[], const unsigned int order, const double fc, const double beta, const double amp) {
const double fc_pi = M_PI * fc;
const double recipOrder = 1.0 / order;
const double mult = 2.0 * fc * amp / bessel(beta);
for (int i = order, j = 0; 0 <= i; i -= 2, ++j) {
double xw = i * recipOrder;
double win = bessel(beta * sqrt(fabs(1.0 - xw * xw)));
double xs = i * fc_pi;
double sinc = (i == 0) ? 1.0 : sin(xs) / xs;
FIRCoefficient imp = FIRCoefficient(mult * sinc * win);
kernel[j] = imp;
kernel[order - j] = imp;
}
}
ResamplerStage *SincResampler::createSincResampler(const double inputFrequency, const double outputFrequency, const double passbandFrequency, const double stopbandFrequency, const double dbSNR, const unsigned int maxUpsampleFactor) {
unsigned int upsampleFactor;
double downsampleFactor;
computeResampleFactors(upsampleFactor, downsampleFactor, inputFrequency, outputFrequency, maxUpsampleFactor);
double baseSamplePeriod = 1.0 / (inputFrequency * upsampleFactor);
double fp = passbandFrequency * baseSamplePeriod;
double fs = stopbandFrequency * baseSamplePeriod;
double fc = 0.5 * (fp + fs);
double beta = KaizerWindow::estimateBeta(dbSNR);
unsigned int order = KaizerWindow::estimateOrder(dbSNR, fp, fs);
const unsigned int kernelLength = order + 1;
#ifdef SRCTOOLS_SINC_RESAMPLER_DEBUG_LOG
std::clog << "FIR: " << upsampleFactor << "/" << downsampleFactor << ", N=" << kernelLength << ", NPh=" << kernelLength / double(upsampleFactor) << ", C=" << 0.5 / fc << ", fp=" << fp << ", fs=" << fs << ", M=" << maxUpsampleFactor << std::endl;
#endif
FIRCoefficient *windowedSincKernel = new FIRCoefficient[kernelLength];
KaizerWindow::windowedSinc(windowedSincKernel, order, fc, beta, upsampleFactor);
ResamplerStage *windowedSincStage = new FIRResampler(upsampleFactor, downsampleFactor, windowedSincKernel, kernelLength);
delete[] windowedSincKernel;
return windowedSincStage;
}
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/src/SincResampler.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,364 |
```c++
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#include <cstddef>
#include "../include/IIR2xResampler.h"
namespace SRCTools {
// Avoid denormals degrading performance, using biased input
static const BufferedSample BIAS = 1e-20f;
// Sharp elliptic filter with symmetric ripple: N=18, Ap=As=-106 dB, fp=0.238, fs = 0.25 (in terms of sample rate)
static const IIRCoefficient FIR_BEST = 0.0014313792470984f;
static const IIRSection SECTIONS_BEST[] = {
{ 2.85800356692148000f,-0.2607342682253230f,-0.602478421807085f, 0.109823442522145f },
{ -4.39519408383016000f, 1.4651975326003500f,-0.533817668127954f, 0.226045921792036f },
{ 0.86638550740991800f,-2.1053851417898500f,-0.429134968401065f, 0.403512574222174f },
{ 1.67161485530774000f, 0.7963595880494520f,-0.324989203363446f, 0.580756666711889f },
{ -1.19962759276471000f, 0.5873595178851540f,-0.241486447489019f, 0.724264899930934f },
{ 0.01631779946479250f,-0.6282334739461620f,-0.182766025706656f, 0.827774001858882f },
{ 0.28404415859352400f, 0.1038619997715160f,-0.145276649558926f, 0.898510501923554f },
{ -0.08105788424234910f, 0.0781551578108934f,-0.123965846623366f, 0.947105257601873f },
{ -0.00872608905948005f,-0.0222098231712466f,-0.115056854360748f, 0.983542001125711f }
};
// Average elliptic filter with symmetric ripple: N=12, Ap=As=-106 dB, fp=0.193, fs = 0.25 (in terms of sample rate)
static const IIRCoefficient FIR_GOOD = 0.000891054570268146f;
static const IIRSection SECTIONS_GOOD[] = {
{ 2.2650157226725700f,-0.4034180565140230f,-0.750061486095301f, 0.157801404511953f },
{ -3.2788261989161700f, 1.3952152147542600f,-0.705854270206788f, 0.265564985645774f },
{ 0.4397975114813240f,-1.3957634748753100f,-0.639718853965265f, 0.435324134360315f },
{ 0.9827040216680520f, 0.1837182774040940f,-0.578569965618418f, 0.615205557837542f },
{ -0.3759752818621670f, 0.3266073609399490f,-0.540913588637109f, 0.778264420176574f },
{ -0.0253548089519618f,-0.0925779221603846f,-0.537704370375240f, 0.925800083252964f }
};
// Fast elliptic filter with symmetric ripple: N=8, Ap=As=-99 dB, fp=0.125, fs = 0.25 (in terms of sample rate)
static const IIRCoefficient FIR_FAST = 0.000882837778745889f;
static const IIRSection SECTIONS_FAST[] = {
{ 1.215377077431620f,-0.35864455030878000f,-0.972220718789242f, 0.252934735930620f },
{ -1.525654419254140f, 0.86784918631245500f,-0.977713689358124f, 0.376580616703668f },
{ 0.136094441564220f,-0.50414116798010400f,-1.007004471865290f, 0.584048854845331f },
{ 0.180604082285806f,-0.00467624342403851f,-1.093486919012100f, 0.844904524843996f }
};
static inline BufferedSample calcNumerator(const IIRSection §ion, const BufferedSample buffer1, const BufferedSample buffer2) {
return section.num1 * buffer1 + section.num2 * buffer2;
}
static inline BufferedSample calcDenominator(const IIRSection §ion, const BufferedSample input, const BufferedSample buffer1, const BufferedSample buffer2) {
return input - section.den1 * buffer1 - section.den2 * buffer2;
}
} // namespace SRCTools
using namespace SRCTools;
double IIRResampler::getPassbandFractionForQuality(Quality quality) {
switch (quality) {
case FAST:
return 0.5;
case GOOD:
return 0.7708;
case BEST:
return 0.9524;
default:
return 0;
}
}
IIRResampler::Constants::Constants(const unsigned int useSectionsCount, const IIRCoefficient useFIR, const IIRSection useSections[], const Quality quality) {
if (quality == CUSTOM) {
sectionsCount = useSectionsCount;
fir = useFIR;
sections = useSections;
} else {
unsigned int sectionsSize;
switch (quality) {
case FAST:
fir = FIR_FAST;
sections = SECTIONS_FAST;
sectionsSize = sizeof(SECTIONS_FAST);
break;
case GOOD:
fir = FIR_GOOD;
sections = SECTIONS_GOOD;
sectionsSize = sizeof(SECTIONS_GOOD);
break;
case BEST:
fir = FIR_BEST;
sections = SECTIONS_BEST;
sectionsSize = sizeof(SECTIONS_BEST);
break;
default:
sectionsSize = 0;
break;
}
sectionsCount = (sectionsSize / sizeof(IIRSection));
}
const unsigned int delayLineSize = IIR_RESAMPER_CHANNEL_COUNT * sectionsCount;
buffer = new SectionBuffer[delayLineSize];
BufferedSample *s = buffer[0];
BufferedSample *e = buffer[delayLineSize];
while (s < e) *(s++) = 0;
}
IIRResampler::IIRResampler(const Quality quality) :
constants(0, 0.0f, NULL, quality)
{}
IIRResampler::IIRResampler(const unsigned int useSectionsCount, const IIRCoefficient useFIR, const IIRSection useSections[]) :
constants(useSectionsCount, useFIR, useSections, IIRResampler::CUSTOM)
{}
IIRResampler::~IIRResampler() {
delete[] constants.buffer;
}
IIR2xInterpolator::IIR2xInterpolator(const Quality quality) :
IIRResampler(quality),
phase(1)
{
for (unsigned int chIx = 0; chIx < IIR_RESAMPER_CHANNEL_COUNT; ++chIx) {
lastInputSamples[chIx] = 0;
}
}
IIR2xInterpolator::IIR2xInterpolator(const unsigned int useSectionsCount, const IIRCoefficient useFIR, const IIRSection useSections[]) :
IIRResampler(useSectionsCount, useFIR, useSections),
phase(1)
{
for (unsigned int chIx = 0; chIx < IIR_RESAMPER_CHANNEL_COUNT; ++chIx) {
lastInputSamples[chIx] = 0;
}
}
void IIR2xInterpolator::process(const FloatSample *&inSamples, unsigned int &inLength, FloatSample *&outSamples, unsigned int &outLength) {
static const IIRCoefficient INTERPOLATOR_AMP = 2.0;
while (outLength > 0 && inLength > 0) {
SectionBuffer *bufferp = constants.buffer;
for (unsigned int chIx = 0; chIx < IIR_RESAMPER_CHANNEL_COUNT; ++chIx) {
const FloatSample lastInputSample = lastInputSamples[chIx];
const FloatSample inSample = inSamples[chIx];
BufferedSample tmpOut = phase == 0 ? 0 : inSample * constants.fir;
for (unsigned int i = 0; i < constants.sectionsCount; ++i) {
const IIRSection §ion = constants.sections[i];
SectionBuffer &buffer = *bufferp;
// For 2x interpolation, calculation of the numerator reduces to a single multiplication depending on the phase.
if (phase == 0) {
const BufferedSample numOutSample = section.num1 * lastInputSample;
const BufferedSample denOutSample = calcDenominator(section, BIAS + numOutSample, buffer[0], buffer[1]);
buffer[1] = denOutSample;
tmpOut += denOutSample;
} else {
const BufferedSample numOutSample = section.num2 * lastInputSample;
const BufferedSample denOutSample = calcDenominator(section, BIAS + numOutSample, buffer[1], buffer[0]);
buffer[0] = denOutSample;
tmpOut += denOutSample;
}
bufferp++;
}
*(outSamples++) = FloatSample(INTERPOLATOR_AMP * tmpOut);
if (phase > 0) {
lastInputSamples[chIx] = inSample;
}
}
outLength--;
if (phase > 0) {
inSamples += IIR_RESAMPER_CHANNEL_COUNT;
inLength--;
phase = 0;
} else {
phase = 1;
}
}
}
unsigned int IIR2xInterpolator::estimateInLength(const unsigned int outLength) const {
return outLength >> 1;
}
IIR2xDecimator::IIR2xDecimator(const Quality quality) :
IIRResampler(quality)
{}
IIR2xDecimator::IIR2xDecimator(const unsigned int useSectionsCount, const IIRCoefficient useFIR, const IIRSection useSections[]) :
IIRResampler(useSectionsCount, useFIR, useSections)
{}
void IIR2xDecimator::process(const FloatSample *&inSamples, unsigned int &inLength, FloatSample *&outSamples, unsigned int &outLength) {
while (outLength > 0 && inLength > 1) {
SectionBuffer *bufferp = constants.buffer;
for (unsigned int chIx = 0; chIx < IIR_RESAMPER_CHANNEL_COUNT; ++chIx) {
BufferedSample tmpOut = inSamples[chIx] * constants.fir;
for (unsigned int i = 0; i < constants.sectionsCount; ++i) {
const IIRSection §ion = constants.sections[i];
SectionBuffer &buffer = *bufferp;
// For 2x decimation, calculation of the numerator is not performed for odd output samples which are to be omitted.
tmpOut += calcNumerator(section, buffer[0], buffer[1]);
buffer[1] = calcDenominator(section, BIAS + inSamples[chIx], buffer[0], buffer[1]);
buffer[0] = calcDenominator(section, BIAS + inSamples[chIx + IIR_RESAMPER_CHANNEL_COUNT], buffer[1], buffer[0]);
bufferp++;
}
*(outSamples++) = FloatSample(tmpOut);
}
outLength--;
inLength -= 2;
inSamples += 2 * IIR_RESAMPER_CHANNEL_COUNT;
}
}
unsigned int IIR2xDecimator::estimateInLength(const unsigned int outLength) const {
return outLength << 1;
}
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/src/IIR2xResampler.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,799 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef SRCTOOLS_FIR_RESAMPLER_H
#define SRCTOOLS_FIR_RESAMPLER_H
#include "ResamplerStage.h"
namespace SRCTools {
typedef FloatSample FIRCoefficient;
static const unsigned int FIR_INTERPOLATOR_CHANNEL_COUNT = 2;
class FIRResampler : public ResamplerStage {
public:
FIRResampler(const unsigned int upsampleFactor, const double downsampleFactor, const FIRCoefficient kernel[], const unsigned int kernelLength);
~FIRResampler();
void process(const FloatSample *&inSamples, unsigned int &inLength, FloatSample *&outSamples, unsigned int &outLength);
unsigned int estimateInLength(const unsigned int outLength) const;
private:
const struct Constants {
// Filter coefficients
const FIRCoefficient *taps;
// Indicates whether to interpolate filter taps
bool usePhaseInterpolation;
// Size of array of filter coefficients
unsigned int numberOfTaps;
// Upsampling factor
unsigned int numberOfPhases;
// Downsampling factor
double phaseIncrement;
// Index of last delay line element, generally greater than numberOfTaps to form a proper binary mask
unsigned int delayLineMask;
// Delay line
FloatSample(*ringBuffer)[FIR_INTERPOLATOR_CHANNEL_COUNT];
Constants(const unsigned int upsampleFactor, const double downsampleFactor, const FIRCoefficient kernel[], const unsigned int kernelLength);
} constants;
// Index of current sample in delay line
unsigned int ringBufferPosition;
// Current phase
double phase;
bool needNextInSample() const;
void addInSamples(const FloatSample *&inSamples);
void getOutSamplesStereo(FloatSample *&outSamples);
}; // class FIRResampler
} // namespace SRCTools
#endif // SRCTOOLS_FIR_RESAMPLER_H
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/include/FIRResampler.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 480 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef SRCTOOLS_RESAMPLER_MODEL_H
#define SRCTOOLS_RESAMPLER_MODEL_H
#include "FloatSampleProvider.h"
namespace SRCTools {
class ResamplerStage;
/** Model consists of one or more ResampleStage instances connected in a cascade. */
namespace ResamplerModel {
// Seems to be a good choice for 16-bit integer samples.
static const double DEFAULT_DB_SNR = 106;
// When using linear interpolation, oversampling factor necessary to achieve the DEFAULT_DB_SNR is about 256.
// This figure is the upper estimation, and it can be found by analysing the frequency response of the linear interpolator.
// When less SNR is desired, this value should also decrease in accordance.
static const unsigned int DEFAULT_WINDOWED_SINC_MAX_DOWNSAMPLE_FACTOR = 256;
// In the default resampler model, the input to the windowed sinc filter is always at least 2x oversampled during upsampling,
// so oversampling factor of 128 should be sufficient to achieve the DEFAULT_DB_SNR with linear interpolation.
static const unsigned int DEFAULT_WINDOWED_SINC_MAX_UPSAMPLE_FACTOR = DEFAULT_WINDOWED_SINC_MAX_DOWNSAMPLE_FACTOR / 2;
enum Quality {
// Use when the speed is more important than the audio quality.
FASTEST,
// Use FAST quality setting of the IIR stage (50% of passband retained).
FAST,
// Use GOOD quality setting of the IIR stage (77% of passband retained).
GOOD,
// Use BEST quality setting of the IIR stage (95% of passband retained).
BEST
};
FloatSampleProvider &createResamplerModel(FloatSampleProvider &source, double sourceSampleRate, double targetSampleRate, Quality quality);
FloatSampleProvider &createResamplerModel(FloatSampleProvider &source, ResamplerStage **stages, unsigned int stageCount);
FloatSampleProvider &createResamplerModel(FloatSampleProvider &source, ResamplerStage &stage);
void freeResamplerModel(FloatSampleProvider &model, FloatSampleProvider &source);
} // namespace ResamplerModel
} // namespace SRCTools
#endif // SRCTOOLS_RESAMPLER_MODEL_H
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/include/ResamplerModel.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 544 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef SRCTOOLS_SINC_RESAMPLER_H
#define SRCTOOLS_SINC_RESAMPLER_H
#include "FIRResampler.h"
namespace SRCTools {
class ResamplerStage;
namespace SincResampler {
ResamplerStage *createSincResampler(const double inputFrequency, const double outputFrequency, const double passbandFrequency, const double stopbandFrequency, const double dbSNR, const unsigned int maxUpsampleFactor);
namespace Utils {
void computeResampleFactors(unsigned int &upsampleFactor, double &downsampleFactor, const double inputFrequency, const double outputFrequency, const unsigned int maxUpsampleFactor);
unsigned int greatestCommonDivisor(unsigned int a, unsigned int b);
}
namespace KaizerWindow {
double estimateBeta(double dbRipple);
unsigned int estimateOrder(double dbRipple, double fp, double fs);
double bessel(const double x);
void windowedSinc(FIRCoefficient kernel[], const unsigned int order, const double fc, const double beta, const double amp);
}
} // namespace SincResampler
} // namespace SRCTools
#endif // SRCTOOLS_SINC_RESAMPLER_H
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/include/SincResampler.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 339 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef SRCTOOLS_IIR_2X_RESAMPLER_H
#define SRCTOOLS_IIR_2X_RESAMPLER_H
#include "ResamplerStage.h"
namespace SRCTools {
static const unsigned int IIR_RESAMPER_CHANNEL_COUNT = 2;
static const unsigned int IIR_SECTION_ORDER = 2;
typedef FloatSample IIRCoefficient;
typedef FloatSample BufferedSample;
typedef BufferedSample SectionBuffer[IIR_SECTION_ORDER];
// Non-trivial coefficients of a 2nd-order section of a parallel bank
// (zero-order numerator coefficient is always zero, zero-order denominator coefficient is always unity)
struct IIRSection {
IIRCoefficient num1;
IIRCoefficient num2;
IIRCoefficient den1;
IIRCoefficient den2;
};
class IIRResampler : public ResamplerStage {
public:
enum Quality {
// Used when providing custom IIR filter coefficients.
CUSTOM,
// Use fast elliptic filter with symmetric ripple: N=8, Ap=As=-99 dB, fp=0.125, fs = 0.25 (in terms of sample rate)
FAST,
// Use average elliptic filter with symmetric ripple: N=12, Ap=As=-106 dB, fp=0.193, fs = 0.25 (in terms of sample rate)
GOOD,
// Use sharp elliptic filter with symmetric ripple: N=18, Ap=As=-106 dB, fp=0.238, fs = 0.25 (in terms of sample rate)
BEST
};
// Returns the retained fraction of the passband for the given standard quality value
static double getPassbandFractionForQuality(Quality quality);
protected:
explicit IIRResampler(const Quality quality);
explicit IIRResampler(const unsigned int useSectionsCount, const IIRCoefficient useFIR, const IIRSection useSections[]);
~IIRResampler();
const struct Constants {
// Coefficient of the 0-order FIR part
IIRCoefficient fir;
// 2nd-order sections that comprise a parallel bank
const IIRSection *sections;
// Number of 2nd-order sections
unsigned int sectionsCount;
// Delay line per channel per section
SectionBuffer *buffer;
Constants(const unsigned int useSectionsCount, const IIRCoefficient useFIR, const IIRSection useSections[], const Quality quality);
} constants;
}; // class IIRResampler
class IIR2xInterpolator : public IIRResampler {
public:
explicit IIR2xInterpolator(const Quality quality);
explicit IIR2xInterpolator(const unsigned int useSectionsCount, const IIRCoefficient useFIR, const IIRSection useSections[]);
void process(const FloatSample *&inSamples, unsigned int &inLength, FloatSample *&outSamples, unsigned int &outLength);
unsigned int estimateInLength(const unsigned int outLength) const;
private:
FloatSample lastInputSamples[IIR_RESAMPER_CHANNEL_COUNT];
unsigned int phase;
};
class IIR2xDecimator : public IIRResampler {
public:
explicit IIR2xDecimator(const Quality quality);
explicit IIR2xDecimator(const unsigned int useSectionsCount, const IIRCoefficient useFIR, const IIRSection useSections[]);
void process(const FloatSample *&inSamples, unsigned int &inLength, FloatSample *&outSamples, unsigned int &outLength);
unsigned int estimateInLength(const unsigned int outLength) const;
};
} // namespace SRCTools
#endif // SRCTOOLS_IIR_2X_RESAMPLER_H
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/include/IIR2xResampler.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 851 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef SRCTOOLS_FLOAT_SAMPLE_PROVIDER_H
#define SRCTOOLS_FLOAT_SAMPLE_PROVIDER_H
namespace SRCTools {
typedef float FloatSample;
/** Interface defines an abstract source of samples. It can either define a single channel stream or a stream with interleaved channels. */
class FloatSampleProvider {
public:
virtual ~FloatSampleProvider() {}
virtual void getOutputSamples(FloatSample *outBuffer, unsigned int size) = 0;
};
} // namespace SRCTools
#endif // SRCTOOLS_FLOAT_SAMPLE_PROVIDER_H
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/include/FloatSampleProvider.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 200 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef SRCTOOLS_RESAMPLER_STAGE_H
#define SRCTOOLS_RESAMPLER_STAGE_H
#include "FloatSampleProvider.h"
namespace SRCTools {
/** Interface defines an abstract source of samples. It can either define a single channel stream or a stream with interleaved channels. */
class ResamplerStage {
public:
virtual ~ResamplerStage() {}
/** Returns a lower estimation of required number of input samples to produce the specified number of output samples. */
virtual unsigned int estimateInLength(const unsigned int outLength) const = 0;
/** Generates output samples. The arguments are adjusted in accordance with the number of samples processed. */
virtual void process(const FloatSample *&inSamples, unsigned int &inLength, FloatSample *&outSamples, unsigned int &outLength) = 0;
};
} // namespace SRCTools
#endif // SRCTOOLS_RESAMPLER_STAGE_H
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/include/ResamplerStage.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 277 |
```objective-c
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
#ifndef SRCTOOLS_LINEAR_RESAMPLER_H
#define SRCTOOLS_LINEAR_RESAMPLER_H
#include "ResamplerStage.h"
namespace SRCTools {
static const unsigned int LINEAR_RESAMPER_CHANNEL_COUNT = 2;
class LinearResampler : public ResamplerStage {
public:
LinearResampler(double sourceSampleRate, double targetSampleRate);
~LinearResampler() {}
unsigned int estimateInLength(const unsigned int outLength) const;
void process(const FloatSample *&inSamples, unsigned int &inLength, FloatSample *&outSamples, unsigned int &outLength);
private:
const double inputToOutputRatio;
double position;
FloatSample lastInputSamples[LINEAR_RESAMPER_CHANNEL_COUNT];
};
} // namespace SRCTools
#endif // SRCTOOLS_LINEAR_RESAMPLER_H
``` | /content/code_sandbox/src/sound/munt/srchelper/srctools/include/LinearResampler.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 260 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_MISC_H
#define YMFM_MISC_H
#pragma once
#include "ymfm.h"
#include "ymfm_adpcm.h"
#include "ymfm_ssg.h"
namespace ymfm
{
//*********************************************************
// SSG IMPLEMENTATION CLASSES
//*********************************************************
// ======================> ym2149
// ym2149 is just an SSG with no FM part, but we expose FM-like parts so that it
// integrates smoothly with everything else; they just don't do anything
class ym2149
{
public:
static constexpr uint32_t OUTPUTS = ssg_engine::OUTPUTS;
static constexpr uint32_t SSG_OUTPUTS = ssg_engine::OUTPUTS;
using output_data = ymfm_output<OUTPUTS>;
// constructor
ym2149(ymfm_interface &intf);
// configuration
void ssg_override(ssg_override &intf) { m_ssg.override(intf); }
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return input_clock / ssg_engine::CLOCK_DIVIDER / 8; }
// read access
uint8_t read_data();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal state
uint8_t m_address; // address register
ssg_engine m_ssg; // SSG engine
};
}
#endif // YMFM_MISC_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm_misc.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 682 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_SSG_H
#define YMFM_SSG_H
#pragma once
#include "ymfm.h"
namespace ymfm
{
//*********************************************************
// OVERRIDE INTERFACE
//*********************************************************
// ======================> ssg_override
// this class describes a simple interface to allow the internal SSG to be
// overridden with another implementation
class ssg_override
{
public:
virtual ~ssg_override() = default;
// reset our status
virtual void ssg_reset() = 0;
// read/write to the SSG registers
virtual uint8_t ssg_read(uint32_t regnum) = 0;
virtual void ssg_write(uint32_t regnum, uint8_t data) = 0;
// notification when the prescale has changed
virtual void ssg_prescale_changed() = 0;
};
//*********************************************************
// REGISTER CLASS
//*********************************************************
// ======================> ssg_registers
//
// SSG register map:
//
// System-wide registers:
// 06 ---xxxxx Noise period
// 07 x------- I/O B in(0) or out(1)
// -x------ I/O A in(0) or out(1)
// --x----- Noise enable(0) or disable(1) for channel C
// ---x---- Noise enable(0) or disable(1) for channel B
// ----x--- Noise enable(0) or disable(1) for channel A
// -----x-- Tone enable(0) or disable(1) for channel C
// ------x- Tone enable(0) or disable(1) for channel B
// -------x Tone enable(0) or disable(1) for channel A
// 0B xxxxxxxx Envelope period fine
// 0C xxxxxxxx Envelope period coarse
// 0D ----x--- Envelope shape: continue
// -----x-- Envelope shape: attack/decay
// ------x- Envelope shape: alternate
// -------x Envelope shape: hold
// 0E xxxxxxxx 8-bit parallel I/O port A
// 0F xxxxxxxx 8-bit parallel I/O port B
//
// Per-channel registers:
// 00,02,04 xxxxxxxx Tone period (fine) for channel A,B,C
// 01,03,05 ----xxxx Tone period (coarse) for channel A,B,C
// 08,09,0A ---x---- Mode: fixed(0) or variable(1) for channel A,B,C
// ----xxxx Amplitude for channel A,B,C
//
class ssg_registers
{
public:
// constants
static constexpr uint32_t OUTPUTS = 3;
static constexpr uint32_t CHANNELS = 3;
static constexpr uint32_t REGISTERS = 0x10;
static constexpr uint32_t ALL_CHANNELS = (1 << CHANNELS) - 1;
// constructor
ssg_registers() { }
// reset to initial state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// direct read/write access
uint8_t read(uint32_t index) { return m_regdata[index]; }
void write(uint32_t index, uint8_t data) { m_regdata[index] = data; }
// system-wide registers
uint32_t noise_period() const { return bitfield(m_regdata[0x06], 0, 5); }
uint32_t io_b_out() const { return bitfield(m_regdata[0x07], 7); }
uint32_t io_a_out() const { return bitfield(m_regdata[0x07], 6); }
uint32_t envelope_period() const { return m_regdata[0x0b] | (m_regdata[0x0c] << 8); }
uint32_t envelope_continue() const { return bitfield(m_regdata[0x0d], 3); }
uint32_t envelope_attack() const { return bitfield(m_regdata[0x0d], 2); }
uint32_t envelope_alternate() const { return bitfield(m_regdata[0x0d], 1); }
uint32_t envelope_hold() const { return bitfield(m_regdata[0x0d], 0); }
uint32_t io_a_data() const { return m_regdata[0x0e]; }
uint32_t io_b_data() const { return m_regdata[0x0f]; }
// per-channel registers
uint32_t ch_noise_enable_n(uint32_t choffs) const { return bitfield(m_regdata[0x07], 3 + choffs); }
uint32_t ch_tone_enable_n(uint32_t choffs) const { return bitfield(m_regdata[0x07], 0 + choffs); }
uint32_t ch_tone_period(uint32_t choffs) const { return m_regdata[0x00 + 2 * choffs] | (bitfield(m_regdata[0x01 + 2 * choffs], 0, 4) << 8); }
uint32_t ch_envelope_enable(uint32_t choffs) const { return bitfield(m_regdata[0x08 + choffs], 4); }
uint32_t ch_amplitude(uint32_t choffs) const { return bitfield(m_regdata[0x08 + choffs], 0, 4); }
private:
// internal state
uint8_t m_regdata[REGISTERS]; // register data
};
// ======================> ssg_engine
class ssg_engine
{
public:
static constexpr int OUTPUTS = ssg_registers::OUTPUTS;
static constexpr int CHANNELS = ssg_registers::CHANNELS;
static constexpr int CLOCK_DIVIDER = 8;
using output_data = ymfm_output<OUTPUTS>;
// constructor
ssg_engine(ymfm_interface &intf);
// configure an override
void override(ssg_override &override) { m_override = &override; }
// reset our status
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// master clocking function
void clock();
// compute sum of channel outputs
void output(output_data &output);
// read/write to the SSG registers
uint8_t read(uint32_t regnum);
void write(uint32_t regnum, uint8_t data);
// return a reference to our interface
ymfm_interface &intf() { return m_intf; }
// return a reference to our registers
ssg_registers ®s() { return m_regs; }
// true if we are overridden
bool overridden() const { return (m_override != nullptr); }
// indicate the prescale has changed
void prescale_changed() { if (m_override != nullptr) m_override->ssg_prescale_changed(); }
private:
// internal state
ymfm_interface &m_intf; // reference to the interface
uint32_t m_tone_count[3]; // current tone counter
uint32_t m_tone_state[3]; // current tone state
uint32_t m_envelope_count; // envelope counter
uint32_t m_envelope_state; // envelope state
uint32_t m_noise_count; // current noise counter
uint32_t m_noise_state; // current noise state
ssg_registers m_regs; // registers
ssg_override *m_override; // override interface
};
}
#endif // YMFM_SSG_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm_ssg.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,930 |
```c++
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ymfm_misc.h"
namespace ymfm
{
//*********************************************************
// YM2149
//*********************************************************
//-------------------------------------------------
// ym2149 - constructor
//-------------------------------------------------
ym2149::ym2149(ymfm_interface &intf) :
m_address(0),
m_ssg(intf)
{
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ym2149::reset()
{
// reset the engines
m_ssg.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ym2149::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
m_ssg.save_restore(state);
}
//-------------------------------------------------
// read_data - read the data register
//-------------------------------------------------
uint8_t ym2149::read_data()
{
return m_ssg.read(m_address & 0x0f);
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ym2149::read(uint32_t offset)
{
uint8_t result = 0xff;
switch (offset & 3) // BC2,BC1
{
case 0: // inactive
break;
case 1: // address
break;
case 2: // inactive
break;
case 3: // read
result = read_data();
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ym2149::write_address(uint8_t data)
{
// just set the address
m_address = data;
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym2149::write_data(uint8_t data)
{
m_ssg.write(m_address & 0x0f, data);
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym2149::write(uint32_t offset, uint8_t data)
{
switch (offset & 3) // BC2,BC1
{
case 0: // address
write_address(data);
break;
case 1: // inactive
break;
case 2: // write
write_data(data);
break;
case 3: // address
write_address(data);
break;
}
}
//-------------------------------------------------
// generate - generate samples of SSG sound
//-------------------------------------------------
void ym2149::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the SSG
m_ssg.clock();
// YM2149 keeps the three SSG outputs independent
m_ssg.output(*output);
}
}
}
``` | /content/code_sandbox/src/sound/ymfm/ymfm_misc.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 912 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_PCM_H
#define YMFM_PCM_H
#pragma once
#include "ymfm.h"
namespace ymfm
{
/*
Note to self: Sega "Multi-PCM" is almost identical to this
28 channels
Writes:
00 = data reg, causes write
01 = target slot = data - (data / 8)
02 = address (clamped to 7)
Slot data (registers with ADSR/KSR seem to be inaccessible):
0: xxxx---- panpot
1: xxxxxxxx wavetable low
2: xxxxxx-- pitch low
-------x wavetable high
3: xxxx---- octave
----xxxx pitch hi
4: x------- key on
5: xxxxxxx- total level
-------x level direct (0=interpolate)
6: --xxx--- LFO frequency
-----xxx PM sensitivity
7: -----xxx AM sensitivity
Sample data:
+00: start hi
+01: start mid
+02: start low
+03: loop hi
+04: loop low
+05: -end hi
+06: -end low
+07: vibrato (reg 6)
+08: attack/decay
+09: sustain level/rate
+0A: ksr/release
+0B: LFO amplitude (reg 7)
*/
//*********************************************************
// INTERFACE CLASSES
//*********************************************************
class pcm_engine;
// ======================> pcm_cache
// this class holds data that is computed once at the start of clocking
// and remains static during subsequent sound generation
struct pcm_cache
{
uint32_t step; // sample position step, as a .16 value
uint32_t total_level; // target total level, as a .10 value
uint32_t pan_left; // left panning attenuation
uint32_t pan_right; // right panning attenuation
uint32_t eg_sustain; // sustain level, shifted up to envelope values
uint8_t eg_rate[EG_STATES]; // envelope rate, including KSR
uint8_t lfo_step; // stepping value for LFO
uint8_t am_depth; // scale value for AM LFO
uint8_t pm_depth; // scale value for PM LFO
};
// ======================> pcm_registers
//
// PCM register map:
//
// System-wide registers:
// 00-01 xxxxxxxx LSI Test
// 02 -------x Memory access mode (0=sound gen, 1=read/write)
// ------x- Memory type (0=ROM, 1=ROM+SRAM)
// ---xxx-- Wave table header
// xxx----- Device ID (=1 for YMF278B)
// 03 --xxxxxx Memory address high
// 04 xxxxxxxx Memory address mid
// 05 xxxxxxxx Memory address low
// 06 xxxxxxxx Memory data
// F8 --xxx--- Mix control (FM_R)
// -----xxx Mix control (FM_L)
// F9 --xxx--- Mix control (PCM_R)
// -----xxx Mix control (PCM_L)
//
// Channel-specific registers:
// 08-1F xxxxxxxx Wave table number low
// 20-37 -------x Wave table number high
// xxxxxxx- F-number low
// 38-4F -----xxx F-number high
// ----x--- Pseudo-reverb
// xxxx---- Octave
// 50-67 xxxxxxx- Total level
// -------x Level direct
// 68-7F x------- Key on
// -x------ Damp
// --x----- LFO reset
// ---x---- Output channel
// ----xxxx Panpot
// 80-97 --xxx--- LFO speed
// -----xxx Vibrato
// 98-AF xxxx---- Attack rate
// ----xxxx Decay rate
// B0-C7 xxxx---- Sustain level
// ----xxxx Sustain rate
// C8-DF xxxx---- Rate correction
// ----xxxx Release rate
// E0-F7 -----xxx AM depth
class pcm_registers
{
public:
// constants
static constexpr uint32_t OUTPUTS = 4;
static constexpr uint32_t CHANNELS = 24;
static constexpr uint32_t REGISTERS = 0x100;
static constexpr uint32_t ALL_CHANNELS = (1 << CHANNELS) - 1;
// constructor
pcm_registers() { }
// save/restore
void save_restore(ymfm_saved_state &state);
// reset to initial state
void reset();
// update cache information
void cache_channel_data(uint32_t choffs, pcm_cache &cache);
// direct read/write access
uint8_t read(uint32_t index ) { return m_regdata[index]; }
void write(uint32_t index, uint8_t data) { m_regdata[index] = data; }
// system-wide registers
uint32_t memory_access_mode() const { return bitfield(m_regdata[0x02], 0); }
uint32_t memory_type() const { return bitfield(m_regdata[0x02], 1); }
uint32_t wave_table_header() const { return bitfield(m_regdata[0x02], 2, 3); }
uint32_t device_id() const { return bitfield(m_regdata[0x02], 5, 3); }
uint32_t memory_address() const { return (bitfield(m_regdata[0x03], 0, 6) << 16) | (m_regdata[0x04] << 8) | m_regdata[0x05]; }
uint32_t memory_data() const { return m_regdata[0x06]; }
uint32_t mix_fm_r() const { return bitfield(m_regdata[0xf8], 3, 3); }
uint32_t mix_fm_l() const { return bitfield(m_regdata[0xf8], 0, 3); }
uint32_t mix_pcm_r() const { return bitfield(m_regdata[0xf9], 3, 3); }
uint32_t mix_pcm_l() const { return bitfield(m_regdata[0xf9], 0, 3); }
// per-channel registers
uint32_t ch_wave_table_num(uint32_t choffs) const { return m_regdata[choffs + 0x08] | (bitfield(m_regdata[choffs + 0x20], 0) << 8); }
uint32_t ch_fnumber(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x20], 1, 7) | (bitfield(m_regdata[choffs + 0x38], 0, 3) << 7); }
uint32_t ch_pseudo_reverb(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x38], 3); }
uint32_t ch_octave(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x38], 4, 4); }
uint32_t ch_total_level(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x50], 1, 7); }
uint32_t ch_level_direct(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x50], 0); }
uint32_t ch_keyon(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x68], 7); }
uint32_t ch_damp(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x68], 6); }
uint32_t ch_lfo_reset(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x68], 5); }
uint32_t ch_output_channel(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x68], 4); }
uint32_t ch_panpot(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x68], 0, 4); }
uint32_t ch_lfo_speed(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x80], 3, 3); }
uint32_t ch_vibrato(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x80], 0, 3); }
uint32_t ch_attack_rate(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x98], 4, 4); }
uint32_t ch_decay_rate(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x98], 0, 4); }
uint32_t ch_sustain_level(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0xb0], 4, 4); }
uint32_t ch_sustain_rate(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0xb0], 0, 4); }
uint32_t ch_rate_correction(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0xc8], 4, 4); }
uint32_t ch_release_rate(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0xc8], 0, 4); }
uint32_t ch_am_depth(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0xe0], 0, 3); }
// return the memory address and increment it
uint32_t memory_address_autoinc()
{
uint32_t result = memory_address();
uint32_t newval = result + 1;
m_regdata[0x05] = newval >> 0;
m_regdata[0x04] = newval >> 8;
m_regdata[0x03] = (newval >> 16) & 0x3f;
return result;
}
private:
// internal helpers
uint32_t effective_rate(uint32_t raw, uint32_t correction);
// internal state
uint8_t m_regdata[REGISTERS]; // register data
};
// ======================> pcm_channel
class pcm_channel
{
static constexpr uint8_t KEY_ON = 0x01;
static constexpr uint8_t KEY_PENDING_ON = 0x02;
static constexpr uint8_t KEY_PENDING = 0x04;
// "quiet" value, used to optimize when we can skip doing working
static constexpr uint32_t EG_QUIET = 0x200;
public:
using output_data = ymfm_output<pcm_registers::OUTPUTS>;
// constructor
pcm_channel(pcm_engine &owner, uint32_t choffs);
// save/restore
void save_restore(ymfm_saved_state &state);
// reset the channel state
void reset();
// return the channel offset
uint32_t choffs() const { return m_choffs; }
// prepare prior to clocking
bool prepare();
// master clocking function
void clock(uint32_t env_counter);
// return the computed output value, with panning applied
void output(output_data &output) const;
// signal key on/off
void keyonoff(bool on);
// load a new wavetable entry
void load_wavetable();
private:
// internal helpers
void start_attack();
void start_release();
void clock_envelope(uint32_t env_counter);
int16_t fetch_sample() const;
uint8_t read_pcm(uint32_t address) const;
// internal state
uint32_t const m_choffs; // channel offset
uint32_t m_baseaddr; // base address
uint32_t m_endpos; // ending position
uint32_t m_looppos; // loop position
uint32_t m_curpos; // current position
uint32_t m_nextpos; // next position
uint32_t m_lfo_counter; // LFO counter
envelope_state m_eg_state; // envelope state
uint16_t m_env_attenuation; // computed envelope attenuation
uint32_t m_total_level; // total level with as 7.10 for interp
uint8_t m_format; // sample format
uint8_t m_key_state; // current key state
pcm_cache m_cache; // cached data
pcm_registers &m_regs; // reference to registers
pcm_engine &m_owner; // reference to our owner
};
// ======================> pcm_engine
class pcm_engine
{
public:
static constexpr int OUTPUTS = pcm_registers::OUTPUTS;
static constexpr int CHANNELS = pcm_registers::CHANNELS;
static constexpr uint32_t ALL_CHANNELS = pcm_registers::ALL_CHANNELS;
using output_data = pcm_channel::output_data;
// constructor
pcm_engine(ymfm_interface &intf);
// reset our status
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// master clocking function
void clock(uint32_t chanmask);
// compute sum of channel outputs
void output(output_data &output, uint32_t chanmask);
// read from the PCM registers
uint8_t read(uint32_t regnum);
// write to the PCM registers
void write(uint32_t regnum, uint8_t data);
// return a reference to our interface
ymfm_interface &intf() { return m_intf; }
// return a reference to our registers
pcm_registers ®s() { return m_regs; }
private:
// internal state
ymfm_interface &m_intf; // reference to the interface
uint32_t m_env_counter; // envelope counter
uint32_t m_modified_channels; // bitmask of modified channels
uint32_t m_active_channels; // bitmask of active channels
uint32_t m_prepare_count; // counter to do periodic prepare sweeps
std::unique_ptr<pcm_channel> m_channel[CHANNELS]; // array of channels
pcm_registers m_regs; // registers
};
}
#endif // YMFM_PCM_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm_pcm.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,434 |
```c++
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ymfm_adpcm.h"
namespace ymfm
{
//*********************************************************
// ADPCM "A" REGISTERS
//*********************************************************
//-------------------------------------------------
// reset - reset the register state
//-------------------------------------------------
void adpcm_a_registers::reset()
{
std::fill_n(&m_regdata[0], REGISTERS, 0);
// initialize the pans to on by default, and max instrument volume;
// some neogeo homebrews (for example ffeast) rely on this
m_regdata[0x08] = m_regdata[0x09] = m_regdata[0x0a] =
m_regdata[0x0b] = m_regdata[0x0c] = m_regdata[0x0d] = 0xdf;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void adpcm_a_registers::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_regdata);
}
//*********************************************************
// ADPCM "A" CHANNEL
//*********************************************************
//-------------------------------------------------
// adpcm_a_channel - constructor
//-------------------------------------------------
adpcm_a_channel::adpcm_a_channel(adpcm_a_engine &owner, uint32_t choffs, uint32_t addrshift) :
m_choffs(choffs),
m_address_shift(addrshift),
m_playing(0),
m_curnibble(0),
m_curbyte(0),
m_curaddress(0),
m_accumulator(0),
m_step_index(0),
m_regs(owner.regs()),
m_owner(owner)
{
}
//-------------------------------------------------
// reset - reset the channel state
//-------------------------------------------------
void adpcm_a_channel::reset()
{
m_playing = 0;
m_curnibble = 0;
m_curbyte = 0;
m_curaddress = 0;
m_accumulator = 0;
m_step_index = 0;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void adpcm_a_channel::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_playing);
state.save_restore(m_curnibble);
state.save_restore(m_curbyte);
state.save_restore(m_curaddress);
state.save_restore(m_accumulator);
state.save_restore(m_step_index);
}
//-------------------------------------------------
// keyonoff - signal key on/off
//-------------------------------------------------
void adpcm_a_channel::keyonoff(bool on)
{
// QUESTION: repeated key ons restart the sample?
m_playing = on;
if (m_playing)
{
m_curaddress = m_regs.ch_start(m_choffs) << m_address_shift;
m_curnibble = 0;
m_curbyte = 0;
m_accumulator = 0;
m_step_index = 0;
// don't log masked channels
if (((debug::GLOBAL_ADPCM_A_CHANNEL_MASK >> m_choffs) & 1) != 0)
debug::log_keyon("KeyOn ADPCM-A%d: pan=%d%d start=%04X end=%04X level=%02X\n",
m_choffs,
m_regs.ch_pan_left(m_choffs),
m_regs.ch_pan_right(m_choffs),
m_regs.ch_start(m_choffs),
m_regs.ch_end(m_choffs),
m_regs.ch_instrument_level(m_choffs));
}
}
//-------------------------------------------------
// clock - master clocking function
//-------------------------------------------------
bool adpcm_a_channel::clock()
{
// if not playing, just output 0
if (m_playing == 0)
{
m_accumulator = 0;
return false;
}
// if we're about to read nibble 0, fetch the data
uint8_t data;
if (m_curnibble == 0)
{
// stop when we hit the end address; apparently only low 20 bits are used for
// comparison on the YM2610: this affects sample playback in some games, for
// example twinspri character select screen music will skip some samples if
// this is not correct
//
// note also: end address is inclusive, so wait until we are about to fetch
// the sample just after the end before stopping; this is needed for nitd's
// jump sound, for example
uint32_t end = (m_regs.ch_end(m_choffs) + 1) << m_address_shift;
if (((m_curaddress ^ end) & 0xfffff) == 0)
{
m_playing = m_accumulator = 0;
return true;
}
m_curbyte = m_owner.intf().ymfm_external_read(ACCESS_ADPCM_A, m_curaddress++);
data = m_curbyte >> 4;
m_curnibble = 1;
}
// otherwise just extract from the previosuly-fetched byte
else
{
data = m_curbyte & 0xf;
m_curnibble = 0;
}
// compute the ADPCM delta
static uint16_t const s_steps[49] =
{
16, 17, 19, 21, 23, 25, 28,
31, 34, 37, 41, 45, 50, 55,
60, 66, 73, 80, 88, 97, 107,
118, 130, 143, 157, 173, 190, 209,
230, 253, 279, 307, 337, 371, 408,
449, 494, 544, 598, 658, 724, 796,
876, 963, 1060, 1166, 1282, 1411, 1552
};
int32_t delta = (2 * bitfield(data, 0, 3) + 1) * s_steps[m_step_index] / 8;
if (bitfield(data, 3))
delta = -delta;
// the 12-bit accumulator wraps on the ym2610 and ym2608 (like the msm5205)
m_accumulator = (m_accumulator + delta) & 0xfff;
// adjust ADPCM step
static int8_t const s_step_inc[8] = { -1, -1, -1, -1, 2, 5, 7, 9 };
m_step_index = clamp(m_step_index + s_step_inc[bitfield(data, 0, 3)], 0, 48);
return false;
}
//-------------------------------------------------
// output - return the computed output value, with
// panning applied
//-------------------------------------------------
template<int NumOutputs>
void adpcm_a_channel::output(ymfm_output<NumOutputs> &output) const
{
// volume combines instrument and total levels
int vol = (m_regs.ch_instrument_level(m_choffs) ^ 0x1f) + (m_regs.total_level() ^ 0x3f);
// if combined is maximum, don't add to outputs
if (vol >= 63)
return;
// convert into a shift and a multiplier
// QUESTION: verify this from other sources
int8_t mul = 15 - (vol & 7);
uint8_t shift = 4 + 1 + (vol >> 3);
// m_accumulator is a 12-bit value; shift up to sign-extend;
// the downshift is incorporated into 'shift'
int16_t value = ((int16_t(m_accumulator << 4) * mul) >> shift) & ~3;
// apply to left/right as appropriate
if (NumOutputs == 1 || m_regs.ch_pan_left(m_choffs))
output.data[0] += value;
if (NumOutputs > 1 && m_regs.ch_pan_right(m_choffs))
output.data[1] += value;
}
//*********************************************************
// ADPCM "A" ENGINE
//*********************************************************
//-------------------------------------------------
// adpcm_a_engine - constructor
//-------------------------------------------------
adpcm_a_engine::adpcm_a_engine(ymfm_interface &intf, uint32_t addrshift) :
m_intf(intf)
{
// create the channels
for (int chnum = 0; chnum < CHANNELS; chnum++)
m_channel[chnum] = std::make_unique<adpcm_a_channel>(*this, chnum, addrshift);
}
//-------------------------------------------------
// reset - reset the engine state
//-------------------------------------------------
void adpcm_a_engine::reset()
{
// reset register state
m_regs.reset();
// reset each channel
for (auto &chan : m_channel)
chan->reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void adpcm_a_engine::save_restore(ymfm_saved_state &state)
{
// save register state
m_regs.save_restore(state);
// save channel state
for (int chnum = 0; chnum < CHANNELS; chnum++)
m_channel[chnum]->save_restore(state);
}
//-------------------------------------------------
// clock - master clocking function
//-------------------------------------------------
uint32_t adpcm_a_engine::clock(uint32_t chanmask)
{
// clock each channel, setting a bit in result if it finished
uint32_t result = 0;
for (int chnum = 0; chnum < CHANNELS; chnum++)
if (bitfield(chanmask, chnum))
if (m_channel[chnum]->clock())
result |= 1 << chnum;
// return the bitmask of completed samples
return result;
}
//-------------------------------------------------
// update - master update function
//-------------------------------------------------
template<int NumOutputs>
void adpcm_a_engine::output(ymfm_output<NumOutputs> &output, uint32_t chanmask)
{
// mask out some channels for debug purposes
chanmask &= debug::GLOBAL_ADPCM_A_CHANNEL_MASK;
// compute the output of each channel
for (int chnum = 0; chnum < CHANNELS; chnum++)
if (bitfield(chanmask, chnum))
m_channel[chnum]->output(output);
}
template void adpcm_a_engine::output<1>(ymfm_output<1> &output, uint32_t chanmask);
template void adpcm_a_engine::output<2>(ymfm_output<2> &output, uint32_t chanmask);
//-------------------------------------------------
// write - handle writes to the ADPCM-A registers
//-------------------------------------------------
void adpcm_a_engine::write(uint32_t regnum, uint8_t data)
{
// store the raw value to the register array;
// most writes are passive, consumed only when needed
m_regs.write(regnum, data);
// actively handle writes to the control register
if (regnum == 0x00)
for (int chnum = 0; chnum < CHANNELS; chnum++)
if (bitfield(data, chnum))
m_channel[chnum]->keyonoff(bitfield(~data, 7));
}
//*********************************************************
// ADPCM "B" REGISTERS
//*********************************************************
//-------------------------------------------------
// reset - reset the register state
//-------------------------------------------------
void adpcm_b_registers::reset()
{
std::fill_n(&m_regdata[0], REGISTERS, 0);
// default limit to wide open
m_regdata[0x0c] = m_regdata[0x0d] = 0xff;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void adpcm_b_registers::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_regdata);
}
//*********************************************************
// ADPCM "B" CHANNEL
//*********************************************************
//-------------------------------------------------
// adpcm_b_channel - constructor
//-------------------------------------------------
adpcm_b_channel::adpcm_b_channel(adpcm_b_engine &owner, uint32_t addrshift) :
m_address_shift(addrshift),
m_status(STATUS_BRDY),
m_curnibble(0),
m_curbyte(0),
m_dummy_read(0),
m_position(0),
m_curaddress(0),
m_accumulator(0),
m_prev_accum(0),
m_adpcm_step(STEP_MIN),
m_regs(owner.regs()),
m_owner(owner)
{
}
//-------------------------------------------------
// reset - reset the channel state
//-------------------------------------------------
void adpcm_b_channel::reset()
{
m_status = STATUS_BRDY;
m_curnibble = 0;
m_curbyte = 0;
m_dummy_read = 0;
m_position = 0;
m_curaddress = 0;
m_accumulator = 0;
m_prev_accum = 0;
m_adpcm_step = STEP_MIN;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void adpcm_b_channel::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_status);
state.save_restore(m_curnibble);
state.save_restore(m_curbyte);
state.save_restore(m_dummy_read);
state.save_restore(m_position);
state.save_restore(m_curaddress);
state.save_restore(m_accumulator);
state.save_restore(m_prev_accum);
state.save_restore(m_adpcm_step);
}
//-------------------------------------------------
// clock - master clocking function
//-------------------------------------------------
void adpcm_b_channel::clock()
{
// only process if active and not recording (which we don't support)
if (!m_regs.execute() || m_regs.record() || (m_status & STATUS_PLAYING) == 0)
{
m_status &= ~STATUS_PLAYING;
return;
}
// otherwise, advance the step
uint32_t position = m_position + m_regs.delta_n();
m_position = uint16_t(position);
if (position < 0x10000)
return;
// if we're about to process nibble 0, fetch sample
if (m_curnibble == 0)
{
// playing from RAM/ROM
if (m_regs.external())
m_curbyte = m_owner.intf().ymfm_external_read(ACCESS_ADPCM_B, m_curaddress);
}
// extract the nibble from our current byte
uint8_t data = uint8_t(m_curbyte << (4 * m_curnibble)) >> 4;
m_curnibble ^= 1;
// we just processed the last nibble
if (m_curnibble == 0)
{
// if playing from RAM/ROM, check the end/limit address or advance
if (m_regs.external())
{
// handle the sample end, either repeating or stopping
if (at_end())
{
// if repeating, go back to the start
if (m_regs.repeat())
load_start();
// otherwise, done; set the EOS bit
else
{
m_accumulator = 0;
m_prev_accum = 0;
m_status = (m_status & ~STATUS_PLAYING) | STATUS_EOS;
debug::log_keyon("%s\n", "ADPCM EOS");
return;
}
}
// wrap at the limit address
else if (at_limit())
m_curaddress = 0;
// otherwise, advance the current address
else
{
m_curaddress++;
m_curaddress &= 0xffffff;
}
}
// if CPU-driven, copy the next byte and request more
else
{
m_curbyte = m_regs.cpudata();
m_status |= STATUS_BRDY;
}
}
// remember previous value for interpolation
m_prev_accum = m_accumulator;
// forecast to next forecast: 1/8, 3/8, 5/8, 7/8, 9/8, 11/8, 13/8, 15/8
int32_t delta = (2 * bitfield(data, 0, 3) + 1) * m_adpcm_step / 8;
if (bitfield(data, 3))
delta = -delta;
// add and clamp to 16 bits
m_accumulator = clamp(m_accumulator + delta, -32768, 32767);
// scale the ADPCM step: 0.9, 0.9, 0.9, 0.9, 1.2, 1.6, 2.0, 2.4
static uint8_t const s_step_scale[8] = { 57, 57, 57, 57, 77, 102, 128, 153 };
m_adpcm_step = clamp((m_adpcm_step * s_step_scale[bitfield(data, 0, 3)]) / 64, STEP_MIN, STEP_MAX);
}
//-------------------------------------------------
// output - return the computed output value, with
// panning applied
//-------------------------------------------------
template<int NumOutputs>
void adpcm_b_channel::output(ymfm_output<NumOutputs> &output, uint32_t rshift) const
{
// mask out some channels for debug purposes
if ((debug::GLOBAL_ADPCM_B_CHANNEL_MASK & 1) == 0)
return;
// do a linear interpolation between samples
int32_t result = (m_prev_accum * int32_t((m_position ^ 0xffff) + 1) + m_accumulator * int32_t(m_position)) >> 16;
// apply volume (level) in a linear fashion and reduce
result = (result * int32_t(m_regs.level())) >> (8 + rshift);
// apply to left/right
if (NumOutputs == 1 || m_regs.pan_left())
output.data[0] += result;
if (NumOutputs > 1 && m_regs.pan_right())
output.data[1] += result;
}
//-------------------------------------------------
// read - handle special register reads
//-------------------------------------------------
uint8_t adpcm_b_channel::read(uint32_t regnum)
{
uint8_t result = 0;
// register 8 reads over the bus under some conditions
if (regnum == 0x08 && !m_regs.execute() && !m_regs.record() && m_regs.external())
{
// two dummy reads are consumed first
if (m_dummy_read != 0)
{
load_start();
m_dummy_read--;
}
// read the data
else
{
// read from outside of the chip
result = m_owner.intf().ymfm_external_read(ACCESS_ADPCM_B, m_curaddress++);
// did we hit the end? if so, signal EOS
if (at_end())
{
m_status = STATUS_EOS | STATUS_BRDY;
debug::log_keyon("%s\n", "ADPCM EOS");
}
else
{
// signal ready
m_status = STATUS_BRDY;
}
// wrap at the limit address
if (at_limit())
m_curaddress = 0;
}
}
return result;
}
//-------------------------------------------------
// write - handle special register writes
//-------------------------------------------------
void adpcm_b_channel::write(uint32_t regnum, uint8_t value)
{
// register 0 can do a reset; also use writes here to reset the
// dummy read counter
if (regnum == 0x00)
{
if (m_regs.execute())
{
load_start();
// don't log masked channels
if ((debug::GLOBAL_ADPCM_B_CHANNEL_MASK & 1) != 0)
debug::log_keyon("KeyOn ADPCM-B: rep=%d spk=%d pan=%d%d dac=%d 8b=%d rom=%d ext=%d rec=%d start=%04X end=%04X pre=%04X dn=%04X lvl=%02X lim=%04X\n",
m_regs.repeat(),
m_regs.speaker(),
m_regs.pan_left(),
m_regs.pan_right(),
m_regs.dac_enable(),
m_regs.dram_8bit(),
m_regs.rom_ram(),
m_regs.external(),
m_regs.record(),
m_regs.start(),
m_regs.end(),
m_regs.prescale(),
m_regs.delta_n(),
m_regs.level(),
m_regs.limit());
}
else
m_status &= ~STATUS_EOS;
if (m_regs.resetflag())
reset();
if (m_regs.external())
m_dummy_read = 2;
}
// register 8 writes over the bus under some conditions
else if (regnum == 0x08)
{
// if writing from the CPU during execute, clear the ready flag
if (m_regs.execute() && !m_regs.record() && !m_regs.external())
m_status &= ~STATUS_BRDY;
// if writing during "record", pass through as data
else if (!m_regs.execute() && m_regs.record() && m_regs.external())
{
// clear out dummy reads and set start address
if (m_dummy_read != 0)
{
load_start();
m_dummy_read = 0;
}
// did we hit the end? if so, signal EOS
if (at_end())
{
debug::log_keyon("%s\n", "ADPCM EOS");
m_status = STATUS_EOS | STATUS_BRDY;
}
// otherwise, write the data and signal ready
else
{
m_owner.intf().ymfm_external_write(ACCESS_ADPCM_B, m_curaddress++, value);
m_status = STATUS_BRDY;
}
}
}
}
//-------------------------------------------------
// address_shift - compute the current address
// shift amount based on register settings
//-------------------------------------------------
uint32_t adpcm_b_channel::address_shift() const
{
// if a constant address shift, just provide that
if (m_address_shift != 0)
return m_address_shift;
// if ROM or 8-bit DRAM, shift is 5 bits
if (m_regs.rom_ram())
return 5;
if (m_regs.dram_8bit())
return 5;
// otherwise, shift is 2 bits
return 2;
}
//-------------------------------------------------
// load_start - load the start address and
// initialize the state
//-------------------------------------------------
void adpcm_b_channel::load_start()
{
m_status = (m_status & ~STATUS_EOS) | STATUS_PLAYING;
m_curaddress = m_regs.external() ? (m_regs.start() << address_shift()) : 0;
m_curnibble = 0;
m_curbyte = 0;
m_position = 0;
m_accumulator = 0;
m_prev_accum = 0;
m_adpcm_step = STEP_MIN;
}
//*********************************************************
// ADPCM "B" ENGINE
//*********************************************************
//-------------------------------------------------
// adpcm_b_engine - constructor
//-------------------------------------------------
adpcm_b_engine::adpcm_b_engine(ymfm_interface &intf, uint32_t addrshift) :
m_intf(intf)
{
// create the channel (only one supported for now, but leaving possibilities open)
m_channel = std::make_unique<adpcm_b_channel>(*this, addrshift);
}
//-------------------------------------------------
// reset - reset the engine state
//-------------------------------------------------
void adpcm_b_engine::reset()
{
// reset registers
m_regs.reset();
// reset each channel
m_channel->reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void adpcm_b_engine::save_restore(ymfm_saved_state &state)
{
// save our state
m_regs.save_restore(state);
// save channel state
m_channel->save_restore(state);
}
//-------------------------------------------------
// clock - master clocking function
//-------------------------------------------------
void adpcm_b_engine::clock()
{
// clock each channel, setting a bit in result if it finished
m_channel->clock();
}
//-------------------------------------------------
// output - master output function
//-------------------------------------------------
template<int NumOutputs>
void adpcm_b_engine::output(ymfm_output<NumOutputs> &output, uint32_t rshift)
{
// compute the output of each channel
m_channel->output(output, rshift);
}
template void adpcm_b_engine::output<1>(ymfm_output<1> &output, uint32_t rshift);
template void adpcm_b_engine::output<2>(ymfm_output<2> &output, uint32_t rshift);
//-------------------------------------------------
// write - handle writes to the ADPCM-B registers
//-------------------------------------------------
void adpcm_b_engine::write(uint32_t regnum, uint8_t data)
{
// store the raw value to the register array;
// most writes are passive, consumed only when needed
m_regs.write(regnum, data);
// let the channel handle any special writes
m_channel->write(regnum, data);
}
}
``` | /content/code_sandbox/src/sound/ymfm/ymfm_adpcm.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 5,632 |
```c++
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ymfm_opq.h"
#include "ymfm_fm.ipp"
#define TEMPORARY_DEBUG_PRINTS (0)
//
// OPQ (aka YM3806/YM3533)
//
// This chip is not officially documented as far as I know. What I have
// comes from Jari Kangas' work on reverse engineering the PSR70:
//
// path_to_url
//
// OPQ appears be bsaically a mixture of OPM and OPN.
//
namespace ymfm
{
//*********************************************************
// OPQ SPECIFICS
//*********************************************************
//-------------------------------------------------
// opq_registers - constructor
//-------------------------------------------------
opq_registers::opq_registers() :
m_lfo_counter(0),
m_lfo_am(0)
{
// create the waveforms
for (uint32_t index = 0; index < WAVEFORM_LENGTH; index++)
m_waveform[0][index] = abs_sin_attenuation(index) | (bitfield(index, 9) << 15);
uint16_t zeroval = m_waveform[0][0];
for (uint32_t index = 0; index < WAVEFORM_LENGTH; index++)
m_waveform[1][index] = bitfield(index, 9) ? zeroval : m_waveform[0][index];
}
//-------------------------------------------------
// reset - reset to initial state
//-------------------------------------------------
void opq_registers::reset()
{
std::fill_n(&m_regdata[0], REGISTERS, 0);
// enable output on both channels by default
m_regdata[0x10] = m_regdata[0x11] = m_regdata[0x12] = m_regdata[0x13] = 0xc0;
m_regdata[0x14] = m_regdata[0x15] = m_regdata[0x16] = m_regdata[0x17] = 0xc0;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void opq_registers::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_lfo_counter);
state.save_restore(m_lfo_am);
state.save_restore(m_regdata);
}
//-------------------------------------------------
// operator_map - return an array of operator
// indices for each channel; for OPM this is fixed
//-------------------------------------------------
void opq_registers::operator_map(operator_mapping &dest) const
{
// seems like the operators are not swizzled like they are on OPM/OPN?
static const operator_mapping s_fixed_map =
{ {
operator_list( 0, 8, 16, 24 ), // Channel 0 operators
operator_list( 1, 9, 17, 25 ), // Channel 1 operators
operator_list( 2, 10, 18, 26 ), // Channel 2 operators
operator_list( 3, 11, 19, 27 ), // Channel 3 operators
operator_list( 4, 12, 20, 28 ), // Channel 4 operators
operator_list( 5, 13, 21, 29 ), // Channel 5 operators
operator_list( 6, 14, 22, 30 ), // Channel 6 operators
operator_list( 7, 15, 23, 31 ), // Channel 7 operators
} };
dest = s_fixed_map;
}
//-------------------------------------------------
// write - handle writes to the register array
//-------------------------------------------------
bool opq_registers::write(uint16_t index, uint8_t data, uint32_t &channel, uint32_t &opmask)
{
assert(index < REGISTERS);
// detune/multiple share a register based on the MSB of what is written
// remap the multiple values to 100-11F
if ((index & 0xe0) == 0x40 && bitfield(data, 7) != 0)
index += 0xc0;
m_regdata[index] = data;
// handle writes to the key on index
if (index == 0x05)
{
channel = bitfield(data, 0, 3);
opmask = bitfield(data, 3, 4);
return true;
}
return false;
}
//-------------------------------------------------
// clock_noise_and_lfo - clock the noise and LFO,
// handling clock division, depth, and waveform
// computations
//-------------------------------------------------
int32_t opq_registers::clock_noise_and_lfo()
{
// OPQ LFO is not well-understood, but the enable and rate values
// look a lot like OPN, so we'll crib from there as a starting point
// if LFO not enabled (not present on OPN), quick exit with 0s
if (!lfo_enable())
{
m_lfo_counter = 0;
m_lfo_am = 0;
return 0;
}
// this table is based on converting the frequencies in the applications
// manual to clock dividers, based on the assumption of a 7-bit LFO value
static uint8_t const lfo_max_count[8] = { 109, 78, 72, 68, 63, 45, 9, 6 };
uint32_t subcount = uint8_t(m_lfo_counter++);
// when we cross the divider count, add enough to zero it and cause an
// increment at bit 8; the 7-bit value lives from bits 8-14
if (subcount >= lfo_max_count[lfo_rate()])
m_lfo_counter += 0x101 - subcount;
// AM value is 7 bits, staring at bit 8; grab the low 6 directly
m_lfo_am = bitfield(m_lfo_counter, 8, 6);
// first half of the AM period (bit 6 == 0) is inverted
if (bitfield(m_lfo_counter, 8+6) == 0)
m_lfo_am ^= 0x3f;
// PM value is 5 bits, starting at bit 10; grab the low 3 directly
int32_t pm = bitfield(m_lfo_counter, 10, 3);
// PM is reflected based on bit 3
if (bitfield(m_lfo_counter, 10+3))
pm ^= 7;
// PM is negated based on bit 4
return bitfield(m_lfo_counter, 10+4) ? -pm : pm;
}
//-------------------------------------------------
// lfo_am_offset - return the AM offset from LFO
// for the given channel
//-------------------------------------------------
uint32_t opq_registers::lfo_am_offset(uint32_t choffs) const
{
// OPM maps AM quite differently from OPN
// shift value for AM sensitivity is [*, 0, 1, 2],
// mapping to values of [0, 23.9, 47.8, and 95.6dB]
uint32_t am_sensitivity = ch_lfo_am_sens(choffs);
if (am_sensitivity == 0)
return 0;
// QUESTION: see OPN note below for the dB range mapping; it applies
// here as well
// raw LFO AM value on OPM is 0-FF, which is already a factor of 2
// larger than the OPN below, putting our staring point at 2x theirs;
// this works out since our minimum is 2x their maximum
return m_lfo_am << (am_sensitivity - 1);
}
//-------------------------------------------------
// cache_operator_data - fill the operator cache
// with prefetched data
//-------------------------------------------------
void opq_registers::cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache)
{
// set up the easy stuff
cache.waveform = &m_waveform[op_waveform(opoffs)][0];
// get frequency from the appropriate registers
uint32_t block_freq = cache.block_freq = (opoffs & 8) ? ch_block_freq_24(choffs) : ch_block_freq_13(choffs);
// compute the keycode: block_freq is:
//
// BBBFFFFFFFFFFFF
// ^^^^???
//
// keycode is not understood, so just guessing it is like OPN:
// the 5-bit keycode uses the top 4 bits plus a magic formula
// for the final bit
uint32_t keycode = bitfield(block_freq, 11, 4) << 1;
// lowest bit is determined by a mix of next lower FNUM bits
// according to this equation from the YM2608 manual:
//
// (F11 & (F10 | F9 | F8)) | (!F11 & F10 & F9 & F8)
//
// for speed, we just look it up in a 16-bit constant
keycode |= bitfield(0xfe80, bitfield(block_freq, 8, 4));
// detune adjustment: the detune values supported by the OPQ are
// a much larger range (6 bits vs 3 bits) compared to any other
// known FM chip; based on experiments, it seems that the extra
// bits provide a bigger detune range rather than finer control,
// so until we get true measurements just assemble a net detune
// value by summing smaller detunes
int32_t detune = int32_t(op_detune(opoffs)) - 0x20;
int32_t abs_detune = std::abs(detune);
int32_t adjust = (abs_detune / 3) * detune_adjustment(3, keycode) + detune_adjustment(abs_detune % 3, keycode);
cache.detune = (detune >= 0) ? adjust : -adjust;
// multiple value, as an x.1 value (0 means 0.5)
static const uint8_t s_multiple_map[16] = { 1,2,4,6,8,10,12,14,16,18,20,24,30,32,34,36 };
cache.multiple = s_multiple_map[op_multiple(opoffs)];
// phase step, or PHASE_STEP_DYNAMIC if PM is active; this depends on
// block_freq, detune, and multiple, so compute it after we've done those
if (lfo_enable() == 0 || ch_lfo_pm_sens(choffs) == 0)
cache.phase_step = compute_phase_step(choffs, opoffs, cache, 0);
else
cache.phase_step = opdata_cache::PHASE_STEP_DYNAMIC;
// total level, scaled by 8
cache.total_level = op_total_level(opoffs) << 3;
// 4-bit sustain level, but 15 means 31 so effectively 5 bits
cache.eg_sustain = op_sustain_level(opoffs);
cache.eg_sustain |= (cache.eg_sustain + 1) & 0x10;
cache.eg_sustain <<= 5;
// determine KSR adjustment for enevlope rates
uint32_t ksrval = keycode >> (op_ksr(opoffs) ^ 3);
cache.eg_rate[EG_ATTACK] = effective_rate(op_attack_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_DECAY] = effective_rate(op_decay_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_SUSTAIN] = effective_rate(op_sustain_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_RELEASE] = effective_rate(op_release_rate(opoffs) * 4 + 2, ksrval);
cache.eg_rate[EG_REVERB] = (ch_reverb(choffs) != 0) ? 5*4 : cache.eg_rate[EG_RELEASE];
cache.eg_shift = 0;
}
//-------------------------------------------------
// compute_phase_step - compute the phase step
//-------------------------------------------------
uint32_t opq_registers::compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm)
{
// OPN phase calculation has only a single detune parameter
// and uses FNUMs instead of keycodes
// extract frequency number (low 12 bits of block_freq)
uint32_t fnum = bitfield(cache.block_freq, 0, 12);
// if there's a non-zero PM sensitivity, compute the adjustment
uint32_t pm_sensitivity = ch_lfo_pm_sens(choffs);
if (pm_sensitivity != 0)
{
// apply the phase adjustment based on the upper 7 bits
// of FNUM and the PM depth parameters
fnum += opn_lfo_pm_phase_adjustment(bitfield(cache.block_freq, 5, 7), pm_sensitivity, lfo_raw_pm);
// keep fnum to 12 bits
fnum &= 0xfff;
}
// apply block shift to compute phase step
uint32_t block = bitfield(cache.block_freq, 12, 3);
uint32_t phase_step = (fnum << block) >> 2;
// apply detune based on the keycode
phase_step += cache.detune;
// clamp to 17 bits in case detune overflows
// QUESTION: is this specific to the YM2612/3438?
phase_step &= 0x1ffff;
// apply frequency multiplier (which is cached as an x.1 value)
return (phase_step * cache.multiple) >> 1;
}
//-------------------------------------------------
// log_keyon - log a key-on event
//-------------------------------------------------
std::string opq_registers::log_keyon(uint32_t choffs, uint32_t opoffs)
{
uint32_t chnum = choffs;
uint32_t opnum = opoffs;
char buffer[256];
char *end = &buffer[0];
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, "%u.%02u freq=%04X dt=%+2d fb=%u alg=%X mul=%X tl=%02X ksr=%u adsr=%02X/%02X/%02X/%X sl=%X out=%c%c",
chnum, opnum,
(opoffs & 1) ? ch_block_freq_24(choffs) : ch_block_freq_13(choffs),
int32_t(op_detune(opoffs)) - 0x20,
ch_feedback(choffs),
ch_algorithm(choffs),
op_multiple(opoffs),
op_total_level(opoffs),
op_ksr(opoffs),
op_attack_rate(opoffs),
op_decay_rate(opoffs),
op_sustain_rate(opoffs),
op_release_rate(opoffs),
op_sustain_level(opoffs),
ch_output_0(choffs) ? 'L' : '-',
ch_output_1(choffs) ? 'R' : '-');
bool am = (lfo_enable() && op_lfo_am_enable(opoffs) && ch_lfo_am_sens(choffs) != 0);
if (am)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " am=%u", ch_lfo_am_sens(choffs));
bool pm = (lfo_enable() && ch_lfo_pm_sens(choffs) != 0);
if (pm)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " pm=%u", ch_lfo_pm_sens(choffs));
if (am || pm)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " lfo=%02X", lfo_rate());
if (ch_reverb(choffs))
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " reverb");
return buffer;
}
//*********************************************************
// YM3806
//*********************************************************
//-------------------------------------------------
// ym3806 - constructor
//-------------------------------------------------
ym3806::ym3806(ymfm_interface &intf) :
m_fm(intf)
{
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ym3806::reset()
{
// reset the engines
m_fm.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ym3806::save_restore(ymfm_saved_state &state)
{
m_fm.save_restore(state);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ym3806::read_status()
{
uint8_t result = m_fm.status();
if (m_fm.intf().ymfm_is_busy())
result |= fm_engine::STATUS_BUSY;
return result;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ym3806::read(uint32_t offset)
{
uint8_t result = 0xff;
switch (offset)
{
case 0: // status port
result = read_status();
break;
default: // unknown
debug::log_unexpected_read_write("Unexpected read from YM3806 offset %02X\n", offset);
break;
}
if (TEMPORARY_DEBUG_PRINTS && offset != 0) printf("Read %02X = %02X\n", offset, result);
return result;
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym3806::write(uint32_t offset, uint8_t data)
{
if (TEMPORARY_DEBUG_PRINTS && (offset != 3 || data != 0x71)) printf("Write %02X = %02X\n", offset, data);
// write the FM register
m_fm.write(offset, data);
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void ym3806::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// update the FM content; YM3806 is full 14-bit with no intermediate clipping
m_fm.output(output->clear(), 0, 32767, fm_engine::ALL_CHANNELS);
// YM3608 appears to go through a YM3012 DAC, which means we want to apply
// the FP truncation logic to the outputs
output->roundtrip_fp();
}
}
}
``` | /content/code_sandbox/src/sound/ymfm/ymfm_opq.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 4,302 |
```c++
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ymfm_ssg.h"
namespace ymfm
{
//*********************************************************
// SSG REGISTERS
//*********************************************************
//-------------------------------------------------
// reset - reset the register state
//-------------------------------------------------
void ssg_registers::reset()
{
std::fill_n(&m_regdata[0], REGISTERS, 0);
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ssg_registers::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_regdata);
}
//*********************************************************
// SSG ENGINE
//*********************************************************
//-------------------------------------------------
// ssg_engine - constructor
//-------------------------------------------------
ssg_engine::ssg_engine(ymfm_interface &intf) :
m_intf(intf),
m_tone_count{ 0,0,0 },
m_tone_state{ 0,0,0 },
m_envelope_count(0),
m_envelope_state(0),
m_noise_count(0),
m_noise_state(1),
m_override(nullptr)
{
}
//-------------------------------------------------
// reset - reset the engine state
//-------------------------------------------------
void ssg_engine::reset()
{
// defer to the override if present
if (m_override != nullptr)
return m_override->ssg_reset();
// reset register state
m_regs.reset();
// reset engine state
for (int chan = 0; chan < 3; chan++)
{
m_tone_count[chan] = 0;
m_tone_state[chan] = 0;
}
m_envelope_count = 0;
m_envelope_state = 0;
m_noise_count = 0;
m_noise_state = 1;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ssg_engine::save_restore(ymfm_saved_state &state)
{
// save register state
m_regs.save_restore(state);
// save engine state
state.save_restore(m_tone_count);
state.save_restore(m_tone_state);
state.save_restore(m_envelope_count);
state.save_restore(m_envelope_state);
state.save_restore(m_noise_count);
state.save_restore(m_noise_state);
}
//-------------------------------------------------
// clock - master clocking function
//-------------------------------------------------
void ssg_engine::clock()
{
// clock tones; tone period units are clock/16 but since we run at clock/8
// that works out for us to toggle the state (50% duty cycle) at twice the
// programmed period
for (int chan = 0; chan < 3; chan++)
{
m_tone_count[chan]++;
if (m_tone_count[chan] >= m_regs.ch_tone_period(chan))
{
m_tone_state[chan] ^= 1;
m_tone_count[chan] = 0;
}
}
// clock noise; noise period units are clock/16 but since we run at clock/8,
// our counter needs a right shift prior to compare; note that a period of 0
// should produce an indentical result to a period of 1, so add a special
// check against that case
m_noise_count++;
if ((m_noise_count >> 1) >= m_regs.noise_period() && m_noise_count != 1)
{
m_noise_state ^= (bitfield(m_noise_state, 0) ^ bitfield(m_noise_state, 3)) << 17;
m_noise_state >>= 1;
m_noise_count = 0;
}
// clock envelope; envelope period units are clock/8 (manual says clock/256
// but that's for all 32 steps)
m_envelope_count++;
if (m_envelope_count >= m_regs.envelope_period())
{
m_envelope_state++;
m_envelope_count = 0;
}
}
//-------------------------------------------------
// output - output the current state
//-------------------------------------------------
void ssg_engine::output(output_data &output)
{
// volume to amplitude table, taken from MAME's implementation but biased
// so that 0 == 0
static int16_t const s_amplitudes[32] =
{
0, 32, 78, 141, 178, 222, 262, 306,
369, 441, 509, 585, 701, 836, 965, 1112,
1334, 1595, 1853, 2146, 2576, 3081, 3576, 4135,
5000, 6006, 7023, 8155, 9963,11976,14132,16382
};
// compute the envelope volume
uint32_t envelope_volume;
if ((m_regs.envelope_hold() | (m_regs.envelope_continue() ^ 1)) && m_envelope_state >= 32)
{
m_envelope_state = 32;
envelope_volume = ((m_regs.envelope_attack() ^ m_regs.envelope_alternate()) & m_regs.envelope_continue()) ? 31 : 0;
}
else
{
uint32_t attack = m_regs.envelope_attack();
if (m_regs.envelope_alternate())
attack ^= bitfield(m_envelope_state, 5);
envelope_volume = (m_envelope_state & 31) ^ (attack ? 0 : 31);
}
// iterate over channels
for (int chan = 0; chan < 3; chan++)
{
// noise depends on the noise state, which is the LSB of m_noise_state
uint32_t noise_on = m_regs.ch_noise_enable_n(chan) | m_noise_state;
// tone depends on the current tone state
uint32_t tone_on = m_regs.ch_tone_enable_n(chan) | m_tone_state[chan];
// if neither tone nor noise enabled, return 0
uint32_t volume;
if ((noise_on & tone_on) == 0)
volume = 0;
// if the envelope is enabled, use its amplitude
else if (m_regs.ch_envelope_enable(chan))
volume = envelope_volume;
// otherwise, scale the tone amplitude up to match envelope values
// according to the datasheet, amplitude 15 maps to envelope 31
else
{
volume = m_regs.ch_amplitude(chan) * 2;
if (volume != 0)
volume |= 1;
}
// convert to amplitude
output.data[chan] = s_amplitudes[volume];
}
}
//-------------------------------------------------
// read - handle reads from the SSG registers
//-------------------------------------------------
uint8_t ssg_engine::read(uint32_t regnum)
{
// defer to the override if present
if (m_override != nullptr)
return m_override->ssg_read(regnum);
// read from the I/O ports call the handlers if they are configured for input
if (regnum == 0x0e && !m_regs.io_a_out())
return m_intf.ymfm_external_read(ACCESS_IO, 0);
else if (regnum == 0x0f && !m_regs.io_b_out())
return m_intf.ymfm_external_read(ACCESS_IO, 1);
// otherwise just return the register value
return m_regs.read(regnum);
}
//-------------------------------------------------
// write - handle writes to the SSG registers
//-------------------------------------------------
void ssg_engine::write(uint32_t regnum, uint8_t data)
{
// defer to the override if present
if (m_override != nullptr)
return m_override->ssg_write(regnum, data);
// store the raw value to the register array;
// most writes are passive, consumed only when needed
m_regs.write(regnum, data);
// writes to the envelope shape register reset the state
if (regnum == 0x0d)
m_envelope_state = 0;
// writes to the I/O ports call the handlers if they are configured for output
else if (regnum == 0x0e && m_regs.io_a_out())
m_intf.ymfm_external_write(ACCESS_IO, 0, data);
else if (regnum == 0x0f && m_regs.io_b_out())
m_intf.ymfm_external_write(ACCESS_IO, 1, data);
}
}
``` | /content/code_sandbox/src/sound/ymfm/ymfm_ssg.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,088 |
```c++
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace ymfm
{
//*********************************************************
// GLOBAL TABLE LOOKUPS
//*********************************************************
//-------------------------------------------------
// abs_sin_attenuation - given a sin (phase) input
// where the range 0-2*PI is mapped onto 10 bits,
// return the absolute value of sin(input),
// logarithmically-adjusted and treated as an
// attenuation value, in 4.8 fixed point format
//-------------------------------------------------
inline uint32_t abs_sin_attenuation(uint32_t input)
{
// the values here are stored as 4.8 logarithmic values for 1/4 phase
// this matches the internal format of the OPN chip, extracted from the die
static uint16_t const s_sin_table[256] =
{
0x859,0x6c3,0x607,0x58b,0x52e,0x4e4,0x4a6,0x471,0x443,0x41a,0x3f5,0x3d3,0x3b5,0x398,0x37e,0x365,
0x34e,0x339,0x324,0x311,0x2ff,0x2ed,0x2dc,0x2cd,0x2bd,0x2af,0x2a0,0x293,0x286,0x279,0x26d,0x261,
0x256,0x24b,0x240,0x236,0x22c,0x222,0x218,0x20f,0x206,0x1fd,0x1f5,0x1ec,0x1e4,0x1dc,0x1d4,0x1cd,
0x1c5,0x1be,0x1b7,0x1b0,0x1a9,0x1a2,0x19b,0x195,0x18f,0x188,0x182,0x17c,0x177,0x171,0x16b,0x166,
0x160,0x15b,0x155,0x150,0x14b,0x146,0x141,0x13c,0x137,0x133,0x12e,0x129,0x125,0x121,0x11c,0x118,
0x114,0x10f,0x10b,0x107,0x103,0x0ff,0x0fb,0x0f8,0x0f4,0x0f0,0x0ec,0x0e9,0x0e5,0x0e2,0x0de,0x0db,
0x0d7,0x0d4,0x0d1,0x0cd,0x0ca,0x0c7,0x0c4,0x0c1,0x0be,0x0bb,0x0b8,0x0b5,0x0b2,0x0af,0x0ac,0x0a9,
0x0a7,0x0a4,0x0a1,0x09f,0x09c,0x099,0x097,0x094,0x092,0x08f,0x08d,0x08a,0x088,0x086,0x083,0x081,
0x07f,0x07d,0x07a,0x078,0x076,0x074,0x072,0x070,0x06e,0x06c,0x06a,0x068,0x066,0x064,0x062,0x060,
0x05e,0x05c,0x05b,0x059,0x057,0x055,0x053,0x052,0x050,0x04e,0x04d,0x04b,0x04a,0x048,0x046,0x045,
0x043,0x042,0x040,0x03f,0x03e,0x03c,0x03b,0x039,0x038,0x037,0x035,0x034,0x033,0x031,0x030,0x02f,
0x02e,0x02d,0x02b,0x02a,0x029,0x028,0x027,0x026,0x025,0x024,0x023,0x022,0x021,0x020,0x01f,0x01e,
0x01d,0x01c,0x01b,0x01a,0x019,0x018,0x017,0x017,0x016,0x015,0x014,0x014,0x013,0x012,0x011,0x011,
0x010,0x00f,0x00f,0x00e,0x00d,0x00d,0x00c,0x00c,0x00b,0x00a,0x00a,0x009,0x009,0x008,0x008,0x007,
0x007,0x007,0x006,0x006,0x005,0x005,0x005,0x004,0x004,0x004,0x003,0x003,0x003,0x002,0x002,0x002,
0x002,0x001,0x001,0x001,0x001,0x001,0x001,0x001,0x000,0x000,0x000,0x000,0x000,0x000,0x000,0x000
};
// if the top bit is set, we're in the second half of the curve
// which is a mirror image, so invert the index
if (bitfield(input, 8))
input = ~input;
// return the value from the table
return s_sin_table[input & 0xff];
}
//-------------------------------------------------
// attenuation_to_volume - given a 5.8 fixed point
// logarithmic attenuation value, return a 13-bit
// linear volume
//-------------------------------------------------
inline uint32_t attenuation_to_volume(uint32_t input)
{
// the values here are 10-bit mantissas with an implied leading bit
// this matches the internal format of the OPN chip, extracted from the die
// as a nod to performance, the implicit 0x400 bit is pre-incorporated, and
// the values are left-shifted by 2 so that a simple right shift is all that
// is needed; also the order is reversed to save a NOT on the input
#define X(a) (((a) | 0x400) << 2)
static uint16_t const s_power_table[256] =
{
X(0x3fa),X(0x3f5),X(0x3ef),X(0x3ea),X(0x3e4),X(0x3df),X(0x3da),X(0x3d4),
X(0x3cf),X(0x3c9),X(0x3c4),X(0x3bf),X(0x3b9),X(0x3b4),X(0x3ae),X(0x3a9),
X(0x3a4),X(0x39f),X(0x399),X(0x394),X(0x38f),X(0x38a),X(0x384),X(0x37f),
X(0x37a),X(0x375),X(0x370),X(0x36a),X(0x365),X(0x360),X(0x35b),X(0x356),
X(0x351),X(0x34c),X(0x347),X(0x342),X(0x33d),X(0x338),X(0x333),X(0x32e),
X(0x329),X(0x324),X(0x31f),X(0x31a),X(0x315),X(0x310),X(0x30b),X(0x306),
X(0x302),X(0x2fd),X(0x2f8),X(0x2f3),X(0x2ee),X(0x2e9),X(0x2e5),X(0x2e0),
X(0x2db),X(0x2d6),X(0x2d2),X(0x2cd),X(0x2c8),X(0x2c4),X(0x2bf),X(0x2ba),
X(0x2b5),X(0x2b1),X(0x2ac),X(0x2a8),X(0x2a3),X(0x29e),X(0x29a),X(0x295),
X(0x291),X(0x28c),X(0x288),X(0x283),X(0x27f),X(0x27a),X(0x276),X(0x271),
X(0x26d),X(0x268),X(0x264),X(0x25f),X(0x25b),X(0x257),X(0x252),X(0x24e),
X(0x249),X(0x245),X(0x241),X(0x23c),X(0x238),X(0x234),X(0x230),X(0x22b),
X(0x227),X(0x223),X(0x21e),X(0x21a),X(0x216),X(0x212),X(0x20e),X(0x209),
X(0x205),X(0x201),X(0x1fd),X(0x1f9),X(0x1f5),X(0x1f0),X(0x1ec),X(0x1e8),
X(0x1e4),X(0x1e0),X(0x1dc),X(0x1d8),X(0x1d4),X(0x1d0),X(0x1cc),X(0x1c8),
X(0x1c4),X(0x1c0),X(0x1bc),X(0x1b8),X(0x1b4),X(0x1b0),X(0x1ac),X(0x1a8),
X(0x1a4),X(0x1a0),X(0x19c),X(0x199),X(0x195),X(0x191),X(0x18d),X(0x189),
X(0x185),X(0x181),X(0x17e),X(0x17a),X(0x176),X(0x172),X(0x16f),X(0x16b),
X(0x167),X(0x163),X(0x160),X(0x15c),X(0x158),X(0x154),X(0x151),X(0x14d),
X(0x149),X(0x146),X(0x142),X(0x13e),X(0x13b),X(0x137),X(0x134),X(0x130),
X(0x12c),X(0x129),X(0x125),X(0x122),X(0x11e),X(0x11b),X(0x117),X(0x114),
X(0x110),X(0x10c),X(0x109),X(0x106),X(0x102),X(0x0ff),X(0x0fb),X(0x0f8),
X(0x0f4),X(0x0f1),X(0x0ed),X(0x0ea),X(0x0e7),X(0x0e3),X(0x0e0),X(0x0dc),
X(0x0d9),X(0x0d6),X(0x0d2),X(0x0cf),X(0x0cc),X(0x0c8),X(0x0c5),X(0x0c2),
X(0x0be),X(0x0bb),X(0x0b8),X(0x0b5),X(0x0b1),X(0x0ae),X(0x0ab),X(0x0a8),
X(0x0a4),X(0x0a1),X(0x09e),X(0x09b),X(0x098),X(0x094),X(0x091),X(0x08e),
X(0x08b),X(0x088),X(0x085),X(0x082),X(0x07e),X(0x07b),X(0x078),X(0x075),
X(0x072),X(0x06f),X(0x06c),X(0x069),X(0x066),X(0x063),X(0x060),X(0x05d),
X(0x05a),X(0x057),X(0x054),X(0x051),X(0x04e),X(0x04b),X(0x048),X(0x045),
X(0x042),X(0x03f),X(0x03c),X(0x039),X(0x036),X(0x033),X(0x030),X(0x02d),
X(0x02a),X(0x028),X(0x025),X(0x022),X(0x01f),X(0x01c),X(0x019),X(0x016),
X(0x014),X(0x011),X(0x00e),X(0x00b),X(0x008),X(0x006),X(0x003),X(0x000)
};
#undef X
// look up the fractional part, then shift by the whole
return s_power_table[input & 0xff] >> (input >> 8);
}
//-------------------------------------------------
// attenuation_increment - given a 6-bit ADSR
// rate value and a 3-bit stepping index,
// return a 4-bit increment to the attenutaion
// for this step (or for the attack case, the
// fractional scale factor to decrease by)
//-------------------------------------------------
inline uint32_t attenuation_increment(uint32_t rate, uint32_t index)
{
static uint32_t const s_increment_table[64] =
{
0x00000000, 0x00000000, 0x10101010, 0x10101010, // 0-3 (0x00-0x03)
0x10101010, 0x10101010, 0x11101110, 0x11101110, // 4-7 (0x04-0x07)
0x10101010, 0x10111010, 0x11101110, 0x11111110, // 8-11 (0x08-0x0B)
0x10101010, 0x10111010, 0x11101110, 0x11111110, // 12-15 (0x0C-0x0F)
0x10101010, 0x10111010, 0x11101110, 0x11111110, // 16-19 (0x10-0x13)
0x10101010, 0x10111010, 0x11101110, 0x11111110, // 20-23 (0x14-0x17)
0x10101010, 0x10111010, 0x11101110, 0x11111110, // 24-27 (0x18-0x1B)
0x10101010, 0x10111010, 0x11101110, 0x11111110, // 28-31 (0x1C-0x1F)
0x10101010, 0x10111010, 0x11101110, 0x11111110, // 32-35 (0x20-0x23)
0x10101010, 0x10111010, 0x11101110, 0x11111110, // 36-39 (0x24-0x27)
0x10101010, 0x10111010, 0x11101110, 0x11111110, // 40-43 (0x28-0x2B)
0x10101010, 0x10111010, 0x11101110, 0x11111110, // 44-47 (0x2C-0x2F)
0x11111111, 0x21112111, 0x21212121, 0x22212221, // 48-51 (0x30-0x33)
0x22222222, 0x42224222, 0x42424242, 0x44424442, // 52-55 (0x34-0x37)
0x44444444, 0x84448444, 0x84848484, 0x88848884, // 56-59 (0x38-0x3B)
0x88888888, 0x88888888, 0x88888888, 0x88888888 // 60-63 (0x3C-0x3F)
};
return bitfield(s_increment_table[rate], 4*index, 4);
}
//-------------------------------------------------
// detune_adjustment - given a 5-bit key code
// value and a 3-bit detune parameter, return a
// 6-bit signed phase displacement; this table
// has been verified against Nuked's equations,
// but the equations are rather complicated, so
// we'll keep the simplicity of the table
//-------------------------------------------------
inline int32_t detune_adjustment(uint32_t detune, uint32_t keycode)
{
static uint8_t const s_detune_adjustment[32][4] =
{
{ 0, 0, 1, 2 }, { 0, 0, 1, 2 }, { 0, 0, 1, 2 }, { 0, 0, 1, 2 },
{ 0, 1, 2, 2 }, { 0, 1, 2, 3 }, { 0, 1, 2, 3 }, { 0, 1, 2, 3 },
{ 0, 1, 2, 4 }, { 0, 1, 3, 4 }, { 0, 1, 3, 4 }, { 0, 1, 3, 5 },
{ 0, 2, 4, 5 }, { 0, 2, 4, 6 }, { 0, 2, 4, 6 }, { 0, 2, 5, 7 },
{ 0, 2, 5, 8 }, { 0, 3, 6, 8 }, { 0, 3, 6, 9 }, { 0, 3, 7, 10 },
{ 0, 4, 8, 11 }, { 0, 4, 8, 12 }, { 0, 4, 9, 13 }, { 0, 5, 10, 14 },
{ 0, 5, 11, 16 }, { 0, 6, 12, 17 }, { 0, 6, 13, 19 }, { 0, 7, 14, 20 },
{ 0, 8, 16, 22 }, { 0, 8, 16, 22 }, { 0, 8, 16, 22 }, { 0, 8, 16, 22 }
};
int32_t result = s_detune_adjustment[keycode][detune & 3];
return bitfield(detune, 2) ? -result : result;
}
//-------------------------------------------------
// opm_key_code_to_phase_step - converts an
// OPM concatenated block (3 bits), keycode
// (4 bits) and key fraction (6 bits) to a 0.10
// phase step, after applying the given delta;
// this applies to OPM and OPZ, so it lives here
// in a central location
//-------------------------------------------------
inline uint32_t opm_key_code_to_phase_step(uint32_t block_freq, int32_t delta)
{
// The phase step is essentially the fnum in OPN-speak. To compute this table,
// we used the standard formula for computing the frequency of a note, and
// then converted that frequency to fnum using the formula documented in the
// YM2608 manual.
//
// However, the YM2608 manual describes everything in terms of a nominal 8MHz
// clock, which produces an FM clock of:
//
// 8000000 / 24(operators) / 6(prescale) = 55555Hz FM clock
//
// Whereas the descriptions for the YM2151 use a nominal 3.579545MHz clock:
//
// 3579545 / 32(operators) / 2(prescale) = 55930Hz FM clock
//
// To correct for this, the YM2608 formula was adjusted to use a clock of
// 8053920Hz, giving this equation for the fnum:
//
// fnum = (double(144) * freq * (1 << 20)) / double(8053920) / 4;
//
// Unfortunately, the computed table differs in a few spots from the data
// verified from an actual chip. The table below comes from David Viens'
// analysis, used with his permission.
static const uint32_t s_phase_step[12*64] =
{
41568,41600,41632,41664,41696,41728,41760,41792,41856,41888,41920,41952,42016,42048,42080,42112,
42176,42208,42240,42272,42304,42336,42368,42400,42464,42496,42528,42560,42624,42656,42688,42720,
42784,42816,42848,42880,42912,42944,42976,43008,43072,43104,43136,43168,43232,43264,43296,43328,
43392,43424,43456,43488,43552,43584,43616,43648,43712,43744,43776,43808,43872,43904,43936,43968,
44032,44064,44096,44128,44192,44224,44256,44288,44352,44384,44416,44448,44512,44544,44576,44608,
44672,44704,44736,44768,44832,44864,44896,44928,44992,45024,45056,45088,45152,45184,45216,45248,
45312,45344,45376,45408,45472,45504,45536,45568,45632,45664,45728,45760,45792,45824,45888,45920,
45984,46016,46048,46080,46144,46176,46208,46240,46304,46336,46368,46400,46464,46496,46528,46560,
46656,46688,46720,46752,46816,46848,46880,46912,46976,47008,47072,47104,47136,47168,47232,47264,
47328,47360,47392,47424,47488,47520,47552,47584,47648,47680,47744,47776,47808,47840,47904,47936,
48032,48064,48096,48128,48192,48224,48288,48320,48384,48416,48448,48480,48544,48576,48640,48672,
48736,48768,48800,48832,48896,48928,48992,49024,49088,49120,49152,49184,49248,49280,49344,49376,
49440,49472,49504,49536,49600,49632,49696,49728,49792,49824,49856,49888,49952,49984,50048,50080,
50144,50176,50208,50240,50304,50336,50400,50432,50496,50528,50560,50592,50656,50688,50752,50784,
50880,50912,50944,50976,51040,51072,51136,51168,51232,51264,51328,51360,51424,51456,51488,51520,
51616,51648,51680,51712,51776,51808,51872,51904,51968,52000,52064,52096,52160,52192,52224,52256,
52384,52416,52448,52480,52544,52576,52640,52672,52736,52768,52832,52864,52928,52960,52992,53024,
53120,53152,53216,53248,53312,53344,53408,53440,53504,53536,53600,53632,53696,53728,53792,53824,
53920,53952,54016,54048,54112,54144,54208,54240,54304,54336,54400,54432,54496,54528,54592,54624,
54688,54720,54784,54816,54880,54912,54976,55008,55072,55104,55168,55200,55264,55296,55360,55392,
55488,55520,55584,55616,55680,55712,55776,55808,55872,55936,55968,56032,56064,56128,56160,56224,
56288,56320,56384,56416,56480,56512,56576,56608,56672,56736,56768,56832,56864,56928,56960,57024,
57120,57152,57216,57248,57312,57376,57408,57472,57536,57568,57632,57664,57728,57792,57824,57888,
57952,57984,58048,58080,58144,58208,58240,58304,58368,58400,58464,58496,58560,58624,58656,58720,
58784,58816,58880,58912,58976,59040,59072,59136,59200,59232,59296,59328,59392,59456,59488,59552,
59648,59680,59744,59776,59840,59904,59936,60000,60064,60128,60160,60224,60288,60320,60384,60416,
60512,60544,60608,60640,60704,60768,60800,60864,60928,60992,61024,61088,61152,61184,61248,61280,
61376,61408,61472,61536,61600,61632,61696,61760,61824,61856,61920,61984,62048,62080,62144,62208,
62272,62304,62368,62432,62496,62528,62592,62656,62720,62752,62816,62880,62944,62976,63040,63104,
63200,63232,63296,63360,63424,63456,63520,63584,63648,63680,63744,63808,63872,63904,63968,64032,
64096,64128,64192,64256,64320,64352,64416,64480,64544,64608,64672,64704,64768,64832,64896,64928,
65024,65056,65120,65184,65248,65312,65376,65408,65504,65536,65600,65664,65728,65792,65856,65888,
65984,66016,66080,66144,66208,66272,66336,66368,66464,66496,66560,66624,66688,66752,66816,66848,
66944,66976,67040,67104,67168,67232,67296,67328,67424,67456,67520,67584,67648,67712,67776,67808,
67904,67936,68000,68064,68128,68192,68256,68288,68384,68448,68512,68544,68640,68672,68736,68800,
68896,68928,68992,69056,69120,69184,69248,69280,69376,69440,69504,69536,69632,69664,69728,69792,
69920,69952,70016,70080,70144,70208,70272,70304,70400,70464,70528,70560,70656,70688,70752,70816,
70912,70976,71040,71104,71136,71232,71264,71360,71424,71488,71552,71616,71648,71744,71776,71872,
71968,72032,72096,72160,72192,72288,72320,72416,72480,72544,72608,72672,72704,72800,72832,72928,
72992,73056,73120,73184,73216,73312,73344,73440,73504,73568,73632,73696,73728,73824,73856,73952,
74080,74144,74208,74272,74304,74400,74432,74528,74592,74656,74720,74784,74816,74912,74944,75040,
75136,75200,75264,75328,75360,75456,75488,75584,75648,75712,75776,75840,75872,75968,76000,76096,
76224,76288,76352,76416,76448,76544,76576,76672,76736,76800,76864,76928,77024,77120,77152,77248,
77344,77408,77472,77536,77568,77664,77696,77792,77856,77920,77984,78048,78144,78240,78272,78368,
78464,78528,78592,78656,78688,78784,78816,78912,78976,79040,79104,79168,79264,79360,79392,79488,
79616,79680,79744,79808,79840,79936,79968,80064,80128,80192,80256,80320,80416,80512,80544,80640,
80768,80832,80896,80960,80992,81088,81120,81216,81280,81344,81408,81472,81568,81664,81696,81792,
81952,82016,82080,82144,82176,82272,82304,82400,82464,82528,82592,82656,82752,82848,82880,82976
};
// extract the block (octave) first
uint32_t block = bitfield(block_freq, 10, 3);
// the keycode (bits 6-9) is "gappy", mapping 12 values over 16 in each
// octave; to correct for this, we multiply the 4-bit value by 3/4 (or
// rather subtract 1/4); note that a (invalid) value of 15 will bleed into
// the next octave -- this is confirmed
uint32_t adjusted_code = bitfield(block_freq, 6, 4) - bitfield(block_freq, 8, 2);
// now re-insert the 6-bit fraction
int32_t eff_freq = (adjusted_code << 6) | bitfield(block_freq, 0, 6);
// now that the gaps are removed, add the delta
eff_freq += delta;
// handle over/underflow by adjusting the block:
if (uint32_t(eff_freq) >= 768)
{
// minimum delta is -512 (PM), so we can only underflow by 1 octave
if (eff_freq < 0)
{
eff_freq += 768;
if (block-- == 0)
return s_phase_step[0] >> 7;
}
// maximum delta is +512+608 (PM+detune), so we can overflow by up to 2 octaves
else
{
eff_freq -= 768;
if (eff_freq >= 768)
block++, eff_freq -= 768;
if (block++ >= 7)
return s_phase_step[767];
}
}
// look up the phase shift for the key code, then shift by octave
return s_phase_step[eff_freq] >> (block ^ 7);
}
//-------------------------------------------------
// opn_lfo_pm_phase_adjustment - given the 7 most
// significant frequency number bits, plus a 3-bit
// PM depth value and a signed 5-bit raw PM value,
// return a signed PM adjustment to the frequency;
// algorithm written to match Nuked behavior
//-------------------------------------------------
inline int32_t opn_lfo_pm_phase_adjustment(uint32_t fnum_bits, uint32_t pm_sensitivity, int32_t lfo_raw_pm)
{
// this table encodes 2 shift values to apply to the top 7 bits
// of fnum; it is effectively a cheap multiply by a constant
// value containing 0-2 bits
static uint8_t const s_lfo_pm_shifts[8][8] =
{
{ 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77 },
{ 0x77, 0x77, 0x77, 0x77, 0x72, 0x72, 0x72, 0x72 },
{ 0x77, 0x77, 0x77, 0x72, 0x72, 0x72, 0x17, 0x17 },
{ 0x77, 0x77, 0x72, 0x72, 0x17, 0x17, 0x12, 0x12 },
{ 0x77, 0x77, 0x72, 0x17, 0x17, 0x17, 0x12, 0x07 },
{ 0x77, 0x77, 0x17, 0x12, 0x07, 0x07, 0x02, 0x01 },
{ 0x77, 0x77, 0x17, 0x12, 0x07, 0x07, 0x02, 0x01 },
{ 0x77, 0x77, 0x17, 0x12, 0x07, 0x07, 0x02, 0x01 }
};
// look up the relevant shifts
int32_t abs_pm = (lfo_raw_pm < 0) ? -lfo_raw_pm : lfo_raw_pm;
uint32_t const shifts = s_lfo_pm_shifts[pm_sensitivity][bitfield(abs_pm, 0, 3)];
// compute the adjustment
int32_t adjust = (fnum_bits >> bitfield(shifts, 0, 4)) + (fnum_bits >> bitfield(shifts, 4, 4));
if (pm_sensitivity > 5)
adjust <<= pm_sensitivity - 5;
adjust >>= 2;
// every 16 cycles it inverts sign
return (lfo_raw_pm < 0) ? -adjust : adjust;
}
//*********************************************************
// FM OPERATOR
//*********************************************************
//-------------------------------------------------
// fm_operator - constructor
//-------------------------------------------------
template<class RegisterType>
fm_operator<RegisterType>::fm_operator(fm_engine_base<RegisterType> &owner, uint32_t opoffs) :
m_choffs(0),
m_opoffs(opoffs),
m_phase(0),
m_env_attenuation(0x3ff),
m_env_state(EG_RELEASE),
m_ssg_inverted(false),
m_key_state(0),
m_keyon_live(0),
m_regs(owner.regs()),
m_owner(owner)
{
}
//-------------------------------------------------
// reset - reset the channel state
//-------------------------------------------------
template<class RegisterType>
void fm_operator<RegisterType>::reset()
{
// reset our data
m_phase = 0;
m_env_attenuation = 0x3ff;
m_env_state = EG_RELEASE;
m_ssg_inverted = 0;
m_key_state = 0;
m_keyon_live = 0;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
template<class RegisterType>
void fm_operator<RegisterType>::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_phase);
state.save_restore(m_env_attenuation);
state.save_restore(m_env_state);
state.save_restore(m_ssg_inverted);
state.save_restore(m_key_state);
state.save_restore(m_keyon_live);
}
//-------------------------------------------------
// prepare - prepare for clocking
//-------------------------------------------------
template<class RegisterType>
bool fm_operator<RegisterType>::prepare()
{
// cache the data
m_regs.cache_operator_data(m_choffs, m_opoffs, m_cache);
// clock the key state
clock_keystate(uint32_t(m_keyon_live != 0));
m_keyon_live &= ~(1 << KEYON_CSM);
// we're active until we're quiet after the release
return (m_env_state != (RegisterType::EG_HAS_REVERB ? EG_REVERB : EG_RELEASE) || m_env_attenuation < EG_QUIET);
}
//-------------------------------------------------
// clock - master clocking function
//-------------------------------------------------
template<class RegisterType>
void fm_operator<RegisterType>::clock(uint32_t env_counter, int32_t lfo_raw_pm)
{
// clock the SSG-EG state (OPN/OPNA)
if (m_regs.op_ssg_eg_enable(m_opoffs))
clock_ssg_eg_state();
else
m_ssg_inverted = false;
// clock the envelope if on an envelope cycle; env_counter is a x.2 value
if (bitfield(env_counter, 0, 2) == 0)
clock_envelope(env_counter >> 2);
// clock the phase
clock_phase(lfo_raw_pm);
}
//-------------------------------------------------
// compute_volume - compute the 14-bit signed
// volume of this operator, given a phase
// modulation and an AM LFO offset
//-------------------------------------------------
template<class RegisterType>
int32_t fm_operator<RegisterType>::compute_volume(uint32_t phase, uint32_t am_offset) const
{
// the low 10 bits of phase represents a full 2*PI period over
// the full sin wave
// early out if the envelope is effectively off
if (m_env_attenuation > EG_QUIET)
return 0;
// get the absolute value of the sin, as attenuation, as a 4.8 fixed point value
uint32_t sin_attenuation = m_cache.waveform[phase & (RegisterType::WAVEFORM_LENGTH - 1)];
// get the attenuation from the evelope generator as a 4.6 value, shifted up to 4.8
uint32_t env_attenuation = envelope_attenuation(am_offset) << 2;
// combine into a 5.8 value, then convert from attenuation to 13-bit linear volume
int32_t result = attenuation_to_volume((sin_attenuation & 0x7fff) + env_attenuation);
// negate if in the negative part of the sin wave (sign bit gives 14 bits)
return bitfield(sin_attenuation, 15) ? -result : result;
}
//-------------------------------------------------
// compute_noise_volume - compute the 14-bit
// signed noise volume of this operator, given a
// noise input value and an AM offset
//-------------------------------------------------
template<class RegisterType>
int32_t fm_operator<RegisterType>::compute_noise_volume(uint32_t am_offset) const
{
// application manual says the logarithmic transform is not applied here, so we
// just use the raw envelope attenuation, inverted (since 0 attenuation should be
// maximum), and shift it up from a 10-bit value to an 11-bit value
int32_t result = (envelope_attenuation(am_offset) ^ 0x3ff) << 1;
// QUESTION: is AM applied still?
// negate based on the noise state
return bitfield(m_regs.noise_state(), 0) ? -result : result;
}
//-------------------------------------------------
// keyonoff - signal a key on/off event
//-------------------------------------------------
template<class RegisterType>
void fm_operator<RegisterType>::keyonoff(uint32_t on, keyon_type type)
{
m_keyon_live = (m_keyon_live & ~(1 << int(type))) | (bitfield(on, 0) << int(type));
}
//-------------------------------------------------
// start_attack - start the attack phase; called
// when a keyon happens or when an SSG-EG cycle
// is complete and restarts
//-------------------------------------------------
template<class RegisterType>
void fm_operator<RegisterType>::start_attack(bool is_restart)
{
// don't change anything if already in attack state
if (m_env_state == EG_ATTACK)
return;
m_env_state = EG_ATTACK;
// generally not inverted at start, except if SSG-EG is enabled and
// one of the inverted modes is specified; leave this alone on a
// restart, as it is managed by the clock_ssg_eg_state() code
if (RegisterType::EG_HAS_SSG && !is_restart)
m_ssg_inverted = m_regs.op_ssg_eg_enable(m_opoffs) & bitfield(m_regs.op_ssg_eg_mode(m_opoffs), 2);
// reset the phase when we start an attack due to a key on
// (but not when due to an SSG-EG restart except in certain cases
// managed directly by the SSG-EG code)
if (!is_restart)
m_phase = 0;
// if the attack rate >= 62 then immediately go to max attenuation
if (m_cache.eg_rate[EG_ATTACK] >= 62)
m_env_attenuation = 0;
}
//-------------------------------------------------
// start_release - start the release phase;
// called when a keyoff happens
//-------------------------------------------------
template<class RegisterType>
void fm_operator<RegisterType>::start_release()
{
// don't change anything if already in release state
if (m_env_state >= EG_RELEASE)
return;
m_env_state = EG_RELEASE;
// if attenuation if inverted due to SSG-EG, snap the inverted attenuation
// as the starting point
if (RegisterType::EG_HAS_SSG && m_ssg_inverted)
{
m_env_attenuation = (0x200 - m_env_attenuation) & 0x3ff;
m_ssg_inverted = false;
}
}
//-------------------------------------------------
// clock_keystate - clock the keystate to match
// the incoming keystate
//-------------------------------------------------
template<class RegisterType>
void fm_operator<RegisterType>::clock_keystate(uint32_t keystate)
{
assert(keystate == 0 || keystate == 1);
// has the key changed?
if ((keystate ^ m_key_state) != 0)
{
m_key_state = keystate;
// if the key has turned on, start the attack
if (keystate != 0)
{
// OPLL has a DP ("depress"?) state to bring the volume
// down before starting the attack
if (RegisterType::EG_HAS_DEPRESS && m_env_attenuation < 0x200)
m_env_state = EG_DEPRESS;
else
start_attack();
}
// otherwise, start the release
else
start_release();
}
}
//-------------------------------------------------
// clock_ssg_eg_state - clock the SSG-EG state;
// should only be called if SSG-EG is enabled
//-------------------------------------------------
template<class RegisterType>
void fm_operator<RegisterType>::clock_ssg_eg_state()
{
// work only happens once the attenuation crosses above 0x200
if (!bitfield(m_env_attenuation, 9))
return;
// 8 SSG-EG modes:
// 000: repeat normally
// 001: run once, hold low
// 010: repeat, alternating between inverted/non-inverted
// 011: run once, hold high
// 100: inverted repeat normally
// 101: inverted run once, hold low
// 110: inverted repeat, alternating between inverted/non-inverted
// 111: inverted run once, hold high
uint32_t mode = m_regs.op_ssg_eg_mode(m_opoffs);
// hold modes (1/3/5/7)
if (bitfield(mode, 0))
{
// set the inverted flag to the end state (0 for modes 1/7, 1 for modes 3/5)
m_ssg_inverted = bitfield(mode, 2) ^ bitfield(mode, 1);
// if holding, force the attenuation to the expected value once we're
// past the attack phase
if (m_env_state != EG_ATTACK)
m_env_attenuation = m_ssg_inverted ? 0x200 : 0x3ff;
}
// continuous modes (0/2/4/6)
else
{
// toggle invert in alternating mode (even in attack state)
m_ssg_inverted ^= bitfield(mode, 1);
// restart attack if in decay/sustain states
if (m_env_state == EG_DECAY || m_env_state == EG_SUSTAIN)
start_attack(true);
// phase is reset to 0 in modes 0/4
if (bitfield(mode, 1) == 0)
m_phase = 0;
}
// in all modes, once we hit release state, attenuation is forced to maximum
if (m_env_state == EG_RELEASE)
m_env_attenuation = 0x3ff;
}
//-------------------------------------------------
// clock_envelope - clock the envelope state
// according to the given count
//-------------------------------------------------
template<class RegisterType>
void fm_operator<RegisterType>::clock_envelope(uint32_t env_counter)
{
// handle attack->decay transitions
if (m_env_state == EG_ATTACK && m_env_attenuation == 0)
m_env_state = EG_DECAY;
// handle decay->sustain transitions; it is important to do this immediately
// after the attack->decay transition above in the event that the sustain level
// is set to 0 (in which case we will skip right to sustain without doing any
// decay); as an example where this can be heard, check the cymbals sound
// in channel 0 of shinobi's test mode sound #5
if (m_env_state == EG_DECAY && m_env_attenuation >= m_cache.eg_sustain)
m_env_state = EG_SUSTAIN;
// fetch the appropriate 6-bit rate value from the cache
uint32_t rate = m_cache.eg_rate[m_env_state];
// compute the rate shift value; this is the shift needed to
// apply to the env_counter such that it becomes a 5.11 fixed
// point number
uint32_t rate_shift = rate >> 2;
env_counter <<= rate_shift;
// see if the fractional part is 0; if not, it's not time to clock
if (bitfield(env_counter, 0, 11) != 0)
return;
// determine the increment based on the non-fractional part of env_counter
uint32_t relevant_bits = bitfield(env_counter, (rate_shift <= 11) ? 11 : rate_shift, 3);
uint32_t increment = attenuation_increment(rate, relevant_bits);
// attack is the only one that increases
if (m_env_state == EG_ATTACK)
{
// glitch means that attack rates of 62/63 don't increment if
// changed after the initial key on (where they are handled
// specially); nukeykt confirms this happens on OPM, OPN, OPL/OPLL
// at least so assuming it is true for everyone
if (rate < 62)
m_env_attenuation += (~m_env_attenuation * increment) >> 4;
}
// all other cases are similar
else
{
// non-SSG-EG cases just apply the increment
if (!m_regs.op_ssg_eg_enable(m_opoffs))
m_env_attenuation += increment;
// SSG-EG only applies if less than mid-point, and then at 4x
else if (m_env_attenuation < 0x200)
m_env_attenuation += 4 * increment;
// clamp the final attenuation
if (m_env_attenuation >= 0x400)
m_env_attenuation = 0x3ff;
// transition from depress to attack
if (RegisterType::EG_HAS_DEPRESS && m_env_state == EG_DEPRESS && m_env_attenuation >= 0x200)
start_attack();
// transition from release to reverb, should switch at -18dB
if (RegisterType::EG_HAS_REVERB && m_env_state == EG_RELEASE && m_env_attenuation >= 0xc0)
m_env_state = EG_REVERB;
}
}
//-------------------------------------------------
// clock_phase - clock the 10.10 phase value; the
// OPN version of the logic has been verified
// against the Nuked phase generator
//-------------------------------------------------
template<class RegisterType>
void fm_operator<RegisterType>::clock_phase(int32_t lfo_raw_pm)
{
// read from the cache, or recalculate if PM active
uint32_t phase_step = m_cache.phase_step;
if (phase_step == opdata_cache::PHASE_STEP_DYNAMIC)
phase_step = m_regs.compute_phase_step(m_choffs, m_opoffs, m_cache, lfo_raw_pm);
// finally apply the step to the current phase value
m_phase += phase_step;
}
//-------------------------------------------------
// envelope_attenuation - return the effective
// attenuation of the envelope
//-------------------------------------------------
template<class RegisterType>
uint32_t fm_operator<RegisterType>::envelope_attenuation(uint32_t am_offset) const
{
uint32_t result = m_env_attenuation >> m_cache.eg_shift;
// invert if necessary due to SSG-EG
if (RegisterType::EG_HAS_SSG && m_ssg_inverted)
result = (0x200 - result) & 0x3ff;
// add in LFO AM modulation
if (m_regs.op_lfo_am_enable(m_opoffs))
result += am_offset;
// add in total level and KSL from the cache
result += m_cache.total_level;
// clamp to max, apply shift, and return
return std::min<uint32_t>(result, 0x3ff);
}
//*********************************************************
// FM CHANNEL
//*********************************************************
//-------------------------------------------------
// fm_channel - constructor
//-------------------------------------------------
template<class RegisterType>
fm_channel<RegisterType>::fm_channel(fm_engine_base<RegisterType> &owner, uint32_t choffs) :
m_choffs(choffs),
m_feedback{ 0, 0 },
m_feedback_in(0),
m_op{ nullptr, nullptr, nullptr, nullptr },
m_regs(owner.regs()),
m_owner(owner)
{
}
//-------------------------------------------------
// reset - reset the channel state
//-------------------------------------------------
template<class RegisterType>
void fm_channel<RegisterType>::reset()
{
// reset our data
m_feedback[0] = m_feedback[1] = 0;
m_feedback_in = 0;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
template<class RegisterType>
void fm_channel<RegisterType>::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_feedback[0]);
state.save_restore(m_feedback[1]);
state.save_restore(m_feedback_in);
}
//-------------------------------------------------
// keyonoff - signal key on/off to our operators
//-------------------------------------------------
template<class RegisterType>
void fm_channel<RegisterType>::keyonoff(uint32_t states, keyon_type type, uint32_t chnum)
{
for (uint32_t opnum = 0; opnum < array_size(m_op); opnum++)
if (m_op[opnum] != nullptr)
m_op[opnum]->keyonoff(bitfield(states, opnum), type);
if (debug::LOG_KEYON_EVENTS && ((debug::GLOBAL_FM_CHANNEL_MASK >> chnum) & 1) != 0)
for (uint32_t opnum = 0; opnum < array_size(m_op); opnum++)
if (m_op[opnum] != nullptr)
debug::log_keyon("%c%s\n", bitfield(states, opnum) ? '+' : '-', m_regs.log_keyon(m_choffs, m_op[opnum]->opoffs()).c_str());
}
//-------------------------------------------------
// prepare - prepare for clocking
//-------------------------------------------------
template<class RegisterType>
bool fm_channel<RegisterType>::prepare()
{
uint32_t active_mask = 0;
// prepare all operators and determine if they are active
for (uint32_t opnum = 0; opnum < array_size(m_op); opnum++)
if (m_op[opnum] != nullptr)
if (m_op[opnum]->prepare())
active_mask |= 1 << opnum;
return (active_mask != 0);
}
//-------------------------------------------------
// clock - master clock of all operators
//-------------------------------------------------
template<class RegisterType>
void fm_channel<RegisterType>::clock(uint32_t env_counter, int32_t lfo_raw_pm)
{
// clock the feedback through
m_feedback[0] = m_feedback[1];
m_feedback[1] = m_feedback_in;
for (uint32_t opnum = 0; opnum < array_size(m_op); opnum++)
if (m_op[opnum] != nullptr)
m_op[opnum]->clock(env_counter, lfo_raw_pm);
/*
useful temporary code for envelope debugging
if (m_choffs == 0x101)
{
for (uint32_t opnum = 0; opnum < array_size(m_op); opnum++)
{
auto &op = *m_op[((opnum & 1) << 1) | ((opnum >> 1) & 1)];
printf(" %c%03X%c%c ",
"PADSRV"[op.debug_eg_state()],
op.debug_eg_attenuation(),
op.debug_ssg_inverted() ? '-' : '+',
m_regs.op_ssg_eg_enable(op.opoffs()) ? '0' + m_regs.op_ssg_eg_mode(op.opoffs()) : ' ');
}
printf(" -- ");
}
*/
}
//-------------------------------------------------
// output_2op - combine 4 operators according to
// the specified algorithm, returning a sum
// according to the rshift and clipmax parameters,
// which vary between different implementations
//-------------------------------------------------
template<class RegisterType>
void fm_channel<RegisterType>::output_2op(output_data &output, uint32_t rshift, int32_t clipmax) const
{
// The first 2 operators should be populated
assert(m_op[0] != nullptr);
assert(m_op[1] != nullptr);
// AM amount is the same across all operators; compute it once
uint32_t am_offset = m_regs.lfo_am_offset(m_choffs);
// operator 1 has optional self-feedback
int32_t opmod = 0;
uint32_t feedback = m_regs.ch_feedback(m_choffs);
if (feedback != 0)
opmod = (m_feedback[0] + m_feedback[1]) >> (10 - feedback);
// compute the 14-bit volume/value of operator 1 and update the feedback
int32_t op1value = m_feedback_in = m_op[0]->compute_volume(m_op[0]->phase() + opmod, am_offset);
// now that the feedback has been computed, skip the rest if all volumes
// are clear; no need to do all this work for nothing
if (m_regs.ch_output_any(m_choffs) == 0)
return;
// Algorithms for two-operator case:
// 0: O1 -> O2 -> out
// 1: (O1 + O2) -> out
int32_t result;
if (bitfield(m_regs.ch_algorithm(m_choffs), 0) == 0)
{
// some OPL chips use the previous sample for modulation instead of
// the current sample
opmod = (RegisterType::MODULATOR_DELAY ? m_feedback[1] : op1value) >> 1;
result = m_op[1]->compute_volume(m_op[1]->phase() + opmod, am_offset) >> rshift;
}
else
{
result = (RegisterType::MODULATOR_DELAY ? m_feedback[1] : op1value) >> rshift;
result += m_op[1]->compute_volume(m_op[1]->phase(), am_offset) >> rshift;
int32_t clipmin = -clipmax - 1;
result = clamp(result, clipmin, clipmax);
}
// add to the output
add_to_output(m_choffs, output, result);
}
//-------------------------------------------------
// output_4op - combine 4 operators according to
// the specified algorithm, returning a sum
// according to the rshift and clipmax parameters,
// which vary between different implementations
//-------------------------------------------------
template<class RegisterType>
void fm_channel<RegisterType>::output_4op(output_data &output, uint32_t rshift, int32_t clipmax) const
{
// all 4 operators should be populated
assert(m_op[0] != nullptr);
assert(m_op[1] != nullptr);
assert(m_op[2] != nullptr);
assert(m_op[3] != nullptr);
// AM amount is the same across all operators; compute it once
uint32_t am_offset = m_regs.lfo_am_offset(m_choffs);
// operator 1 has optional self-feedback
int32_t opmod = 0;
uint32_t feedback = m_regs.ch_feedback(m_choffs);
if (feedback != 0)
opmod = (m_feedback[0] + m_feedback[1]) >> (10 - feedback);
// compute the 14-bit volume/value of operator 1 and update the feedback
int32_t op1value = m_feedback_in = m_op[0]->compute_volume(m_op[0]->phase() + opmod, am_offset);
// now that the feedback has been computed, skip the rest if all volumes
// are clear; no need to do all this work for nothing
if (m_regs.ch_output_any(m_choffs) == 0)
return;
// OPM/OPN offer 8 different connection algorithms for 4 operators,
// and OPL3 offers 4 more, which we designate here as 8-11.
//
// The operators are computed in order, with the inputs pulled from
// an array of values (opout) that is populated as we go:
// 0 = 0
// 1 = O1
// 2 = O2
// 3 = O3
// 4 = (O4)
// 5 = O1+O2
// 6 = O1+O3
// 7 = O2+O3
//
// The s_algorithm_ops table describes the inputs and outputs of each
// algorithm as follows:
//
// ---------x use opout[x] as operator 2 input
// ------xxx- use opout[x] as operator 3 input
// ---xxx---- use opout[x] as operator 4 input
// --x------- include opout[1] in final sum
// -x-------- include opout[2] in final sum
// x--------- include opout[3] in final sum
#define ALGORITHM(op2in, op3in, op4in, op1out, op2out, op3out) \
((op2in) | ((op3in) << 1) | ((op4in) << 4) | ((op1out) << 7) | ((op2out) << 8) | ((op3out) << 9))
static uint16_t const s_algorithm_ops[8+4] =
{
ALGORITHM(1,2,3, 0,0,0), // 0: O1 -> O2 -> O3 -> O4 -> out (O4)
ALGORITHM(0,5,3, 0,0,0), // 1: (O1 + O2) -> O3 -> O4 -> out (O4)
ALGORITHM(0,2,6, 0,0,0), // 2: (O1 + (O2 -> O3)) -> O4 -> out (O4)
ALGORITHM(1,0,7, 0,0,0), // 3: ((O1 -> O2) + O3) -> O4 -> out (O4)
ALGORITHM(1,0,3, 0,1,0), // 4: ((O1 -> O2) + (O3 -> O4)) -> out (O2+O4)
ALGORITHM(1,1,1, 0,1,1), // 5: ((O1 -> O2) + (O1 -> O3) + (O1 -> O4)) -> out (O2+O3+O4)
ALGORITHM(1,0,0, 0,1,1), // 6: ((O1 -> O2) + O3 + O4) -> out (O2+O3+O4)
ALGORITHM(0,0,0, 1,1,1), // 7: (O1 + O2 + O3 + O4) -> out (O1+O2+O3+O4)
ALGORITHM(1,2,3, 0,0,0), // 8: O1 -> O2 -> O3 -> O4 -> out (O4) [same as 0]
ALGORITHM(0,2,3, 1,0,0), // 9: (O1 + (O2 -> O3 -> O4)) -> out (O1+O4) [unique]
ALGORITHM(1,0,3, 0,1,0), // 10: ((O1 -> O2) + (O3 -> O4)) -> out (O2+O4) [same as 4]
ALGORITHM(0,2,0, 1,0,1) // 11: (O1 + (O2 -> O3) + O4) -> out (O1+O3+O4) [unique]
};
uint32_t algorithm_ops = s_algorithm_ops[m_regs.ch_algorithm(m_choffs)];
// populate the opout table
int16_t opout[8];
opout[0] = 0;
opout[1] = op1value;
// compute the 14-bit volume/value of operator 2
opmod = opout[bitfield(algorithm_ops, 0, 1)] >> 1;
opout[2] = m_op[1]->compute_volume(m_op[1]->phase() + opmod, am_offset);
opout[5] = opout[1] + opout[2];
// compute the 14-bit volume/value of operator 3
opmod = opout[bitfield(algorithm_ops, 1, 3)] >> 1;
opout[3] = m_op[2]->compute_volume(m_op[2]->phase() + opmod, am_offset);
opout[6] = opout[1] + opout[3];
opout[7] = opout[2] + opout[3];
// compute the 14-bit volume/value of operator 4; this could be a noise
// value on the OPM; all algorithms consume OP4 output at a minimum
int32_t result;
if (m_regs.noise_enable() && m_choffs == 7)
result = m_op[3]->compute_noise_volume(am_offset);
else
{
opmod = opout[bitfield(algorithm_ops, 4, 3)] >> 1;
result = m_op[3]->compute_volume(m_op[3]->phase() + opmod, am_offset);
}
result >>= rshift;
// optionally add OP1, OP2, OP3
int32_t clipmin = -clipmax - 1;
if (bitfield(algorithm_ops, 7) != 0)
result = clamp(result + (opout[1] >> rshift), clipmin, clipmax);
if (bitfield(algorithm_ops, 8) != 0)
result = clamp(result + (opout[2] >> rshift), clipmin, clipmax);
if (bitfield(algorithm_ops, 9) != 0)
result = clamp(result + (opout[3] >> rshift), clipmin, clipmax);
// add to the output
add_to_output(m_choffs, output, result);
}
//-------------------------------------------------
// output_rhythm_ch6 - special case output
// computation for OPL channel 6 in rhythm mode,
// which outputs a Bass Drum instrument
//-------------------------------------------------
template<class RegisterType>
void fm_channel<RegisterType>::output_rhythm_ch6(output_data &output, uint32_t rshift, int32_t clipmax) const
{
// AM amount is the same across all operators; compute it once
uint32_t am_offset = m_regs.lfo_am_offset(m_choffs);
// Bass Drum: this uses operators 12 and 15 (i.e., channel 6)
// in an almost-normal way, except that if the algorithm is 1,
// the first operator is ignored instead of added in
// operator 1 has optional self-feedback
int32_t opmod = 0;
uint32_t feedback = m_regs.ch_feedback(m_choffs);
if (feedback != 0)
opmod = (m_feedback[0] + m_feedback[1]) >> (10 - feedback);
// compute the 14-bit volume/value of operator 1 and update the feedback
int32_t opout1 = m_feedback_in = m_op[0]->compute_volume(m_op[0]->phase() + opmod, am_offset);
// compute the 14-bit volume/value of operator 2, which is the result
opmod = bitfield(m_regs.ch_algorithm(m_choffs), 0) ? 0 : (opout1 >> 1);
int32_t result = m_op[1]->compute_volume(m_op[1]->phase() + opmod, am_offset) >> rshift;
// add to the output
add_to_output(m_choffs, output, result * 2);
}
//-------------------------------------------------
// output_rhythm_ch7 - special case output
// computation for OPL channel 7 in rhythm mode,
// which outputs High Hat and Snare Drum
// instruments
//-------------------------------------------------
template<class RegisterType>
void fm_channel<RegisterType>::output_rhythm_ch7(uint32_t phase_select, output_data &output, uint32_t rshift, int32_t clipmax) const
{
// AM amount is the same across all operators; compute it once
uint32_t am_offset = m_regs.lfo_am_offset(m_choffs);
uint32_t noise_state = bitfield(m_regs.noise_state(), 0);
// High Hat: this uses the envelope from operator 13 (channel 7),
// and a combination of noise and the operator 13/17 phase select
// to compute the phase
uint32_t phase = (phase_select << 9) | (0xd0 >> (2 * (noise_state ^ phase_select)));
int32_t result = m_op[0]->compute_volume(phase, am_offset) >> rshift;
// Snare Drum: this uses the envelope from operator 16 (channel 7),
// and a combination of noise and operator 13 phase to pick a phase
uint32_t op13phase = m_op[0]->phase();
phase = (0x100 << bitfield(op13phase, 8)) ^ (noise_state << 8);
result += m_op[1]->compute_volume(phase, am_offset) >> rshift;
result = clamp(result, -clipmax - 1, clipmax);
// add to the output
add_to_output(m_choffs, output, result * 2);
}
//-------------------------------------------------
// output_rhythm_ch8 - special case output
// computation for OPL channel 8 in rhythm mode,
// which outputs Tom Tom and Top Cymbal instruments
//-------------------------------------------------
template<class RegisterType>
void fm_channel<RegisterType>::output_rhythm_ch8(uint32_t phase_select, output_data &output, uint32_t rshift, int32_t clipmax) const
{
// AM amount is the same across all operators; compute it once
uint32_t am_offset = m_regs.lfo_am_offset(m_choffs);
// Tom Tom: this is just a single operator processed normally
int32_t result = m_op[0]->compute_volume(m_op[0]->phase(), am_offset) >> rshift;
// Top Cymbal: this uses the envelope from operator 17 (channel 8),
// and the operator 13/17 phase select to compute the phase
uint32_t phase = 0x100 | (phase_select << 9);
result += m_op[1]->compute_volume(phase, am_offset) >> rshift;
result = clamp(result, -clipmax - 1, clipmax);
// add to the output
add_to_output(m_choffs, output, result * 2);
}
//*********************************************************
// FM ENGINE BASE
//*********************************************************
//-------------------------------------------------
// fm_engine_base - constructor
//-------------------------------------------------
template<class RegisterType>
fm_engine_base<RegisterType>::fm_engine_base(ymfm_interface &intf) :
m_intf(intf),
m_env_counter(0),
m_status(0),
m_clock_prescale(RegisterType::DEFAULT_PRESCALE),
m_irq_mask(STATUS_TIMERA | STATUS_TIMERB),
m_irq_state(0),
m_timer_running{0,0},
m_total_clocks(0),
m_active_channels(ALL_CHANNELS),
m_modified_channels(ALL_CHANNELS),
m_prepare_count(0)
{
// inform the interface of their engine
m_intf.m_engine = this;
// create the channels
for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
m_channel[chnum] = std::make_unique<fm_channel<RegisterType>>(*this, RegisterType::channel_offset(chnum));
// create the operators
for (uint32_t opnum = 0; opnum < OPERATORS; opnum++)
m_operator[opnum] = std::make_unique<fm_operator<RegisterType>>(*this, RegisterType::operator_offset(opnum));
#if (YMFM_DEBUG_LOG_WAVFILES)
for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
m_wavfile[chnum].set_index(chnum);
#endif
// do the initial operator assignment
assign_operators();
}
//-------------------------------------------------
// reset - reset the overall state
//-------------------------------------------------
template<class RegisterType>
void fm_engine_base<RegisterType>::reset()
{
// reset all status bits
set_reset_status(0, 0xff);
// register type-specific initialization
m_regs.reset();
// explicitly write to the mode register since it has side-effects
// QUESTION: old cores initialize this to 0x30 -- who is right?
write(RegisterType::REG_MODE, 0);
// reset the channels
for (auto &chan : m_channel)
chan->reset();
// reset the operators
for (auto &op : m_operator)
op->reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
template<class RegisterType>
void fm_engine_base<RegisterType>::save_restore(ymfm_saved_state &state)
{
// save our data
state.save_restore(m_env_counter);
state.save_restore(m_status);
state.save_restore(m_clock_prescale);
state.save_restore(m_irq_mask);
state.save_restore(m_irq_state);
state.save_restore(m_timer_running[0]);
state.save_restore(m_timer_running[1]);
state.save_restore(m_total_clocks);
// save the register/family data
m_regs.save_restore(state);
// save channel data
for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
m_channel[chnum]->save_restore(state);
// save operator data
for (uint32_t opnum = 0; opnum < OPERATORS; opnum++)
m_operator[opnum]->save_restore(state);
// invalidate any caches
invalidate_caches();
}
//-------------------------------------------------
// clock - iterate over all channels, clocking
// them forward one step
//-------------------------------------------------
template<class RegisterType>
uint32_t fm_engine_base<RegisterType>::clock(uint32_t chanmask)
{
// update the clock counter
m_total_clocks++;
// if something was modified, prepare
// also prepare every 4k samples to catch ending notes
if (m_modified_channels != 0 || m_prepare_count++ >= 4096)
{
// reassign operators to channels if dynamic
if (RegisterType::DYNAMIC_OPS)
assign_operators();
// call each channel to prepare
m_active_channels = 0;
for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
if (bitfield(chanmask, chnum))
if (m_channel[chnum]->prepare())
m_active_channels |= 1 << chnum;
// reset the modified channels and prepare count
m_modified_channels = m_prepare_count = 0;
}
// if the envelope clock divider is 1, just increment by 4;
// otherwise, increment by 1 and manually wrap when we reach the divide count
if (RegisterType::EG_CLOCK_DIVIDER == 1)
m_env_counter += 4;
else if (bitfield(++m_env_counter, 0, 2) == RegisterType::EG_CLOCK_DIVIDER)
m_env_counter += 4 - RegisterType::EG_CLOCK_DIVIDER;
// clock the noise generator
int32_t lfo_raw_pm = m_regs.clock_noise_and_lfo();
// now update the state of all the channels and operators
for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
if (bitfield(chanmask, chnum))
m_channel[chnum]->clock(m_env_counter, lfo_raw_pm);
// return the envelope counter as it is used to clock ADPCM-A
return m_env_counter;
}
//-------------------------------------------------
// output - compute a sum over the relevant
// channels
//-------------------------------------------------
template<class RegisterType>
void fm_engine_base<RegisterType>::output(output_data &output, uint32_t rshift, int32_t clipmax, uint32_t chanmask) const
{
// mask out some channels for debug purposes
chanmask &= debug::GLOBAL_FM_CHANNEL_MASK;
// mask out inactive channels
if (!YMFM_DEBUG_LOG_WAVFILES)
chanmask &= m_active_channels;
// handle the rhythm case, where some of the operators are dedicated
// to percussion (this is an OPL-specific feature)
if (m_regs.rhythm_enable())
{
// we don't support the OPM noise channel here; ensure it is off
assert(m_regs.noise_enable() == 0);
// precompute the operator 13+17 phase selection value
uint32_t op13phase = m_operator[13]->phase();
uint32_t op17phase = m_operator[17]->phase();
uint32_t phase_select = (bitfield(op13phase, 2) ^ bitfield(op13phase, 7)) | bitfield(op13phase, 3) | (bitfield(op17phase, 5) ^ bitfield(op17phase, 3));
// sum over all the desired channels
for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
if (bitfield(chanmask, chnum))
{
#if (YMFM_DEBUG_LOG_WAVFILES)
auto reference = output;
#endif
if (chnum == 6)
m_channel[chnum]->output_rhythm_ch6(output, rshift, clipmax);
else if (chnum == 7)
m_channel[chnum]->output_rhythm_ch7(phase_select, output, rshift, clipmax);
else if (chnum == 8)
m_channel[chnum]->output_rhythm_ch8(phase_select, output, rshift, clipmax);
else if (m_channel[chnum]->is4op())
m_channel[chnum]->output_4op(output, rshift, clipmax);
else
m_channel[chnum]->output_2op(output, rshift, clipmax);
#if (YMFM_DEBUG_LOG_WAVFILES)
m_wavfile[chnum].add(output, reference);
#endif
}
}
else
{
// sum over all the desired channels
for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
if (bitfield(chanmask, chnum))
{
#if (YMFM_DEBUG_LOG_WAVFILES)
auto reference = output;
#endif
if (m_channel[chnum]->is4op())
m_channel[chnum]->output_4op(output, rshift, clipmax);
else
m_channel[chnum]->output_2op(output, rshift, clipmax);
#if (YMFM_DEBUG_LOG_WAVFILES)
m_wavfile[chnum].add(output, reference);
#endif
}
}
}
//-------------------------------------------------
// write - handle writes to the OPN registers
//-------------------------------------------------
template<class RegisterType>
void fm_engine_base<RegisterType>::write(uint16_t regnum, uint8_t data)
{
debug::log_fm_write("%03X = %02X\n", regnum, data);
// special case: writes to the mode register can impact IRQs;
// schedule these writes to ensure ordering with timers
if (regnum == RegisterType::REG_MODE)
{
m_intf.ymfm_sync_mode_write(data);
return;
}
// for now just mark all channels as modified
m_modified_channels = ALL_CHANNELS;
// most writes are passive, consumed only when needed
uint32_t keyon_channel;
uint32_t keyon_opmask;
if (m_regs.write(regnum, data, keyon_channel, keyon_opmask))
{
// handle writes to the keyon register(s)
if (keyon_channel < CHANNELS)
{
// normal channel on/off
m_channel[keyon_channel]->keyonoff(keyon_opmask, KEYON_NORMAL, keyon_channel);
}
else if (CHANNELS >= 9 && keyon_channel == RegisterType::RHYTHM_CHANNEL)
{
// special case for the OPL rhythm channels
m_channel[6]->keyonoff(bitfield(keyon_opmask, 4) ? 3 : 0, KEYON_RHYTHM, 6);
m_channel[7]->keyonoff(bitfield(keyon_opmask, 0) | (bitfield(keyon_opmask, 3) << 1), KEYON_RHYTHM, 7);
m_channel[8]->keyonoff(bitfield(keyon_opmask, 2) | (bitfield(keyon_opmask, 1) << 1), KEYON_RHYTHM, 8);
}
}
}
//-------------------------------------------------
// status - return the current state of the
// status flags
//-------------------------------------------------
template<class RegisterType>
uint8_t fm_engine_base<RegisterType>::status() const
{
return m_status & ~STATUS_BUSY & ~m_regs.status_mask();
}
//-------------------------------------------------
// assign_operators - get the current mapping of
// operators to channels and assign them all
//-------------------------------------------------
template<class RegisterType>
void fm_engine_base<RegisterType>::assign_operators()
{
typename RegisterType::operator_mapping map;
m_regs.operator_map(map);
for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
for (uint32_t index = 0; index < 4; index++)
{
uint32_t opnum = bitfield(map.chan[chnum], 8 * index, 8);
m_channel[chnum]->assign(index, (opnum == 0xff) ? nullptr : m_operator[opnum].get());
}
}
//-------------------------------------------------
// update_timer - update the state of the given
// timer
//-------------------------------------------------
template<class RegisterType>
void fm_engine_base<RegisterType>::update_timer(uint32_t tnum, uint32_t enable, int32_t delta_clocks)
{
uint32_t subtract = !!(tnum >> 15);
tnum &= 0x7fff;
// if the timer is live, but not currently enabled, set the timer
if (enable && !m_timer_running[tnum])
{
// period comes from the registers, and is different for each
uint32_t period = (tnum == 0) ? (1024 - subtract - m_regs.timer_a_value()) : 16 * (256 - subtract - m_regs.timer_b_value());
// caller can also specify a delta to account for other effects
period += delta_clocks;
// reset it
m_intf.ymfm_set_timer(tnum, period * OPERATORS * m_clock_prescale);
m_timer_running[tnum] = 1;
}
// if the timer is not live, ensure it is not enabled
else if (!enable)
{
m_intf.ymfm_set_timer(tnum, -1);
m_timer_running[tnum] = 0;
}
}
//-------------------------------------------------
// engine_timer_expired - timer has expired - signal
// status and possibly IRQs
//-------------------------------------------------
template<class RegisterType>
void fm_engine_base<RegisterType>::engine_timer_expired(uint32_t tnum)
{
// update status
if (tnum == 0 && m_regs.enable_timer_a())
set_reset_status(STATUS_TIMERA, 0);
else if (tnum == 1 && m_regs.enable_timer_b())
set_reset_status(STATUS_TIMERB, 0);
// if timer A fired in CSM mode, trigger CSM on all relevant channels
if (tnum == 0 && m_regs.csm())
for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
if (bitfield(RegisterType::CSM_TRIGGER_MASK, chnum))
{
m_channel[chnum]->keyonoff(0xf, KEYON_CSM, chnum);
m_modified_channels |= 1 << chnum;
}
// Make sure the array does not go out of bounds to keep gcc happy
if ((tnum < 2) || (sizeof(m_timer_running) > (2 * sizeof(uint8_t)))) {
// reset
m_timer_running[tnum] = false;
}
update_timer(tnum, 1, 0);
}
//-------------------------------------------------
// check_interrupts - check the interrupt sources
// for interrupts
//-------------------------------------------------
template<class RegisterType>
void fm_engine_base<RegisterType>::engine_check_interrupts()
{
// update the state
uint8_t old_state = m_irq_state;
m_irq_state = ((m_status & m_irq_mask & ~m_regs.status_mask()) != 0);
// set the IRQ status bit
if (m_irq_state)
m_status |= STATUS_IRQ;
else
m_status &= ~STATUS_IRQ;
// if changed, signal the new state
if (old_state != m_irq_state)
m_intf.ymfm_update_irq(m_irq_state ? true : false);
}
//-------------------------------------------------
// engine_mode_write - handle a mode register write
// via timer callback
//-------------------------------------------------
template<class RegisterType>
void fm_engine_base<RegisterType>::engine_mode_write(uint8_t data)
{
// mark all channels as modified
m_modified_channels = ALL_CHANNELS;
// actually write the mode register now
uint32_t dummy1, dummy2;
m_regs.write(RegisterType::REG_MODE, data, dummy1, dummy2);
// reset IRQ status -- when written, all other bits are ignored
// QUESTION: should this maybe just reset the IRQ bit and not all the bits?
// That is, check_interrupts would only set, this would only clear?
if (m_regs.irq_reset())
set_reset_status(0, 0x78);
else
{
// reset timer status
uint8_t reset_mask = 0;
if (m_regs.reset_timer_b())
reset_mask |= RegisterType::STATUS_TIMERB;
if (m_regs.reset_timer_a())
reset_mask |= RegisterType::STATUS_TIMERA;
set_reset_status(0, reset_mask);
// load timers; note that timer B gets a small negative adjustment because
// the *16 multiplier is free-running, so the first tick of the clock
// is a bit shorter
// OPL3 begins counting immediately instead of after the first period is over.
// We use bit 15 of the timer number on those chips to inform that this was a
// control register write, and to therefore, subtract 1 counting cycle.
update_timer(1 | m_intf.get_special_flags(), m_regs.load_timer_b(), -(m_total_clocks & 15));
update_timer(0 | m_intf.get_special_flags(), m_regs.load_timer_a(), 0);
}
}
}
``` | /content/code_sandbox/src/sound/ymfm/ymfm_fm.ipp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 20,209 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_OPQ_H
#define YMFM_OPQ_H
#pragma once
#include "ymfm.h"
#include "ymfm_fm.h"
namespace ymfm
{
//*********************************************************
// REGISTER CLASSES
//*********************************************************
// ======================> opq_registers
//
// OPQ register map:
//
// System-wide registers:
// 03 xxxxxxxx Timer control (unknown; 0x71 causes interrupts at ~10ms)
// 04 ----x--- LFO disable
// -----xxx LFO frequency (0=~4Hz, 6=~10Hz, 7=~47Hz)
// 05 -x------ Key on/off operator 4
// --x----- Key on/off operator 3
// ---x---- Key on/off operator 2
// ----x--- Key on/off operator 1
// -----xxx Channel select
//
// Per-channel registers (channel in address bits 0-2)
// 10-17 x------- Pan right
// -x------ Pan left
// --xxx--- Feedback level for operator 1 (0-7)
// -----xxx Operator connection algorithm (0-7)
// 18-1F x------- Reverb
// -xxx---- PM sensitivity
// ------xx AM shift
// 20-27 -xxx---- Block (0-7), Operator 2 & 4
// ----xxxx Frequency number upper 4 bits, Operator 2 & 4
// 28-2F -xxx---- Block (0-7), Operator 1 & 3
// ----xxxx Frequency number upper 4 bits, Operator 1 & 3
// 30-37 xxxxxxxx Frequency number lower 8 bits, Operator 2 & 4
// 38-3F xxxxxxxx Frequency number lower 8 bits, Operator 1 & 3
//
// Per-operator registers (channel in address bits 0-2, operator in bits 3-4)
// 40-5F 0-xxxxxx Detune value (0-63)
// 1---xxxx Multiple value (0-15)
// 60-7F -xxxxxxx Total level (0-127)
// 80-9F xx------ Key scale rate (0-3)
// ---xxxxx Attack rate (0-31)
// A0-BF x------- LFO AM enable, retrigger disable
// x------ Waveform select
// ---xxxxx Decay rate (0-31)
// C0-DF ---xxxxx Sustain rate (0-31)
// E0-FF xxxx---- Sustain level (0-15)
// ----xxxx Release rate (0-15)
//
// Diffs from OPM:
// - 2 frequencies/channel
// - retrigger disable
// - 2 waveforms
// - uses FNUM
// - reverb behavior
// - larger detune range
//
// Questions:
// - timer information is pretty light
// - how does echo work?
// -
class opq_registers : public fm_registers_base
{
public:
// constants
static constexpr uint32_t OUTPUTS = 2;
static constexpr uint32_t CHANNELS = 8;
static constexpr uint32_t ALL_CHANNELS = (1 << CHANNELS) - 1;
static constexpr uint32_t OPERATORS = CHANNELS * 4;
static constexpr uint32_t WAVEFORMS = 2;
static constexpr uint32_t REGISTERS = 0x120;
static constexpr uint32_t REG_MODE = 0x03;
static constexpr uint32_t DEFAULT_PRESCALE = 2;
static constexpr uint32_t EG_CLOCK_DIVIDER = 3;
static constexpr bool EG_HAS_REVERB = true;
static constexpr bool MODULATOR_DELAY = false;
static constexpr uint32_t CSM_TRIGGER_MASK = ALL_CHANNELS;
static constexpr uint8_t STATUS_TIMERA = 0;
static constexpr uint8_t STATUS_TIMERB = 0x04;
static constexpr uint8_t STATUS_BUSY = 0x80;
static constexpr uint8_t STATUS_IRQ = 0;
// constructor
opq_registers();
// reset to initial state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// map channel number to register offset
static constexpr uint32_t channel_offset(uint32_t chnum)
{
assert(chnum < CHANNELS);
return chnum;
}
// map operator number to register offset
static constexpr uint32_t operator_offset(uint32_t opnum)
{
assert(opnum < OPERATORS);
return opnum;
}
// return an array of operator indices for each channel
struct operator_mapping { uint32_t chan[CHANNELS]; };
void operator_map(operator_mapping &dest) const;
// handle writes to the register array
bool write(uint16_t index, uint8_t data, uint32_t &chan, uint32_t &opmask);
// clock the noise and LFO, if present, returning LFO PM value
int32_t clock_noise_and_lfo();
// reset the LFO
void reset_lfo() { m_lfo_counter = 0; }
// return the AM offset from LFO for the given channel
uint32_t lfo_am_offset(uint32_t choffs) const;
// return the current noise state, gated by the noise clock
uint32_t noise_state() const { return 0; }
// caching helpers
void cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache);
// compute the phase step, given a PM value
uint32_t compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm);
// log a key-on event
std::string log_keyon(uint32_t choffs, uint32_t opoffs);
// system-wide registers
uint32_t timer_a_value() const { return 0; }
uint32_t timer_b_value() const { return byte(0x03, 2, 6) | 0xc0; } // ???
uint32_t csm() const { return 0; }
uint32_t reset_timer_b() const { return byte(0x03, 0, 1); } // ???
uint32_t reset_timer_a() const { return 0; }
uint32_t enable_timer_b() const { return byte(0x03, 0, 1); } // ???
uint32_t enable_timer_a() const { return 0; }
uint32_t load_timer_b() const { return byte(0x03, 0, 1); } // ???
uint32_t load_timer_a() const { return 0; }
uint32_t lfo_enable() const { return byte(0x04, 3, 1) ^ 1; }
uint32_t lfo_rate() const { return byte(0x04, 0, 3); }
// per-channel registers
uint32_t ch_output_any(uint32_t choffs) const { return byte(0x10, 6, 2, choffs); }
uint32_t ch_output_0(uint32_t choffs) const { return byte(0x10, 6, 1, choffs); }
uint32_t ch_output_1(uint32_t choffs) const { return byte(0x10, 7, 1, choffs); }
uint32_t ch_output_2(uint32_t choffs) const { return 0; }
uint32_t ch_output_3(uint32_t choffs) const { return 0; }
uint32_t ch_feedback(uint32_t choffs) const { return byte(0x10, 3, 3, choffs); }
uint32_t ch_algorithm(uint32_t choffs) const { return byte(0x10, 0, 3, choffs); }
uint32_t ch_reverb(uint32_t choffs) const { return byte(0x18, 7, 1, choffs); }
uint32_t ch_lfo_pm_sens(uint32_t choffs) const { return byte(0x18, 4, 3, choffs); }
uint32_t ch_lfo_am_sens(uint32_t choffs) const { return byte(0x18, 0, 2, choffs); }
uint32_t ch_block_freq_24(uint32_t choffs) const { return word(0x20, 0, 7, 0x30, 0, 8, choffs); }
uint32_t ch_block_freq_13(uint32_t choffs) const { return word(0x28, 0, 7, 0x38, 0, 8, choffs); }
// per-operator registers
uint32_t op_detune(uint32_t opoffs) const { return byte(0x40, 0, 6, opoffs); }
uint32_t op_multiple(uint32_t opoffs) const { return byte(0x100, 0, 4, opoffs); }
uint32_t op_total_level(uint32_t opoffs) const { return byte(0x60, 0, 7, opoffs); }
uint32_t op_ksr(uint32_t opoffs) const { return byte(0x80, 6, 2, opoffs); }
uint32_t op_attack_rate(uint32_t opoffs) const { return byte(0x80, 0, 5, opoffs); }
uint32_t op_lfo_am_enable(uint32_t opoffs) const { return byte(0xa0, 7, 1, opoffs); }
uint32_t op_waveform(uint32_t opoffs) const { return byte(0xa0, 6, 1, opoffs); }
uint32_t op_decay_rate(uint32_t opoffs) const { return byte(0xa0, 0, 5, opoffs); }
uint32_t op_sustain_rate(uint32_t opoffs) const { return byte(0xc0, 0, 5, opoffs); }
uint32_t op_sustain_level(uint32_t opoffs) const { return byte(0xe0, 4, 4, opoffs); }
uint32_t op_release_rate(uint32_t opoffs) const { return byte(0xe0, 0, 4, opoffs); }
protected:
// return a bitfield extracted from a byte
uint32_t byte(uint32_t offset, uint32_t start, uint32_t count, uint32_t extra_offset = 0) const
{
return bitfield(m_regdata[offset + extra_offset], start, count);
}
// return a bitfield extracted from a pair of bytes, MSBs listed first
uint32_t word(uint32_t offset1, uint32_t start1, uint32_t count1, uint32_t offset2, uint32_t start2, uint32_t count2, uint32_t extra_offset = 0) const
{
return (byte(offset1, start1, count1, extra_offset) << count2) | byte(offset2, start2, count2, extra_offset);
}
// internal state
uint32_t m_lfo_counter; // LFO counter
uint8_t m_lfo_am; // current LFO AM value
uint8_t m_regdata[REGISTERS]; // register data
uint16_t m_waveform[WAVEFORMS][WAVEFORM_LENGTH]; // waveforms
};
//*********************************************************
// IMPLEMENTATION CLASSES
//*********************************************************
// ======================> ym3806
class ym3806
{
public:
using fm_engine = fm_engine_base<opq_registers>;
static constexpr uint32_t OUTPUTS = fm_engine::OUTPUTS;
using output_data = fm_engine::output_data;
// constructor
ym3806(ymfm_interface &intf);
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return m_fm.sample_rate(input_clock); }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data) { /* not supported; only direct writes */ }
void write_data(uint8_t data) { /* not supported; only direct writes */ }
void write(uint32_t offset, uint8_t data);
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal state
fm_engine m_fm; // core FM engine
};
// ======================> ym3533
class ym3533 : public ym3806
{
public:
// constructor
ym3533(ymfm_interface &intf) :
ym3806(intf) { }
};
}
#endif // YMFM_OPQ_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm_opq.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,148 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_OPN_H
#define YMFM_OPN_H
#pragma once
#include "ymfm.h"
#include "ymfm_adpcm.h"
#include "ymfm_fm.h"
#include "ymfm_ssg.h"
namespace ymfm
{
//*********************************************************
// REGISTER CLASSES
//*********************************************************
// ======================> opn_registers_base
//
// OPN register map:
//
// System-wide registers:
// 21 xxxxxxxx Test register
// 22 ----x--- LFO enable [OPNA+ only]
// -----xxx LFO rate [OPNA+ only]
// 24 xxxxxxxx Timer A value (upper 8 bits)
// 25 ------xx Timer A value (lower 2 bits)
// 26 xxxxxxxx Timer B value
// 27 xx------ CSM/Multi-frequency mode for channel #2
// --x----- Reset timer B
// ---x---- Reset timer A
// ----x--- Enable timer B
// -----x-- Enable timer A
// ------x- Load timer B
// -------x Load timer A
// 28 x------- Key on/off operator 4
// -x------ Key on/off operator 3
// --x----- Key on/off operator 2
// ---x---- Key on/off operator 1
// ------xx Channel select
//
// Per-channel registers (channel in address bits 0-1)
// Note that all these apply to address+100 as well on OPNA+
// A0-A3 xxxxxxxx Frequency number lower 8 bits
// A4-A7 --xxx--- Block (0-7)
// -----xxx Frequency number upper 3 bits
// B0-B3 --xxx--- Feedback level for operator 1 (0-7)
// -----xxx Operator connection algorithm (0-7)
// B4-B7 x------- Pan left [OPNA]
// -x------ Pan right [OPNA]
// --xx---- LFO AM shift (0-3) [OPNA+ only]
// -----xxx LFO PM depth (0-7) [OPNA+ only]
//
// Per-operator registers (channel in address bits 0-1, operator in bits 2-3)
// Note that all these apply to address+100 as well on OPNA+
// 30-3F -xxx---- Detune value (0-7)
// ----xxxx Multiple value (0-15)
// 40-4F -xxxxxxx Total level (0-127)
// 50-5F xx------ Key scale rate (0-3)
// ---xxxxx Attack rate (0-31)
// 60-6F x------- LFO AM enable [OPNA]
// ---xxxxx Decay rate (0-31)
// 70-7F ---xxxxx Sustain rate (0-31)
// 80-8F xxxx---- Sustain level (0-15)
// ----xxxx Release rate (0-15)
// 90-9F ----x--- SSG-EG enable
// -----xxx SSG-EG envelope (0-7)
//
// Special multi-frequency registers (channel implicitly #2; operator in address bits 0-1)
// A8-AB xxxxxxxx Frequency number lower 8 bits
// AC-AF --xxx--- Block (0-7)
// -----xxx Frequency number upper 3 bits
//
// Internal (fake) registers:
// B8-BB --xxxxxx Latched frequency number upper bits (from A4-A7)
// BC-BF --xxxxxx Latched frequency number upper bits (from AC-AF)
//
template<bool IsOpnA>
class opn_registers_base : public fm_registers_base
{
public:
// constants
static constexpr uint32_t OUTPUTS = IsOpnA ? 2 : 1;
static constexpr uint32_t CHANNELS = IsOpnA ? 6 : 3;
static constexpr uint32_t ALL_CHANNELS = (1 << CHANNELS) - 1;
static constexpr uint32_t OPERATORS = CHANNELS * 4;
static constexpr uint32_t WAVEFORMS = 1;
static constexpr uint32_t REGISTERS = IsOpnA ? 0x200 : 0x100;
static constexpr uint32_t REG_MODE = 0x27;
static constexpr uint32_t DEFAULT_PRESCALE = 6;
static constexpr uint32_t EG_CLOCK_DIVIDER = 3;
static constexpr bool EG_HAS_SSG = true;
static constexpr bool MODULATOR_DELAY = false;
static constexpr uint32_t CSM_TRIGGER_MASK = 1 << 2;
static constexpr uint8_t STATUS_TIMERA = 0x01;
static constexpr uint8_t STATUS_TIMERB = 0x02;
static constexpr uint8_t STATUS_BUSY = 0x80;
static constexpr uint8_t STATUS_IRQ = 0;
// constructor
opn_registers_base();
// reset to initial state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// map channel number to register offset
static constexpr uint32_t channel_offset(uint32_t chnum)
{
assert(chnum < CHANNELS);
if (!IsOpnA)
return chnum;
else
return (chnum % 3) + 0x100 * (chnum / 3);
}
// map operator number to register offset
static constexpr uint32_t operator_offset(uint32_t opnum)
{
assert(opnum < OPERATORS);
if (!IsOpnA)
return opnum + opnum / 3;
else
return (opnum % 12) + ((opnum % 12) / 3) + 0x100 * (opnum / 12);
}
// return an array of operator indices for each channel
struct operator_mapping { uint32_t chan[CHANNELS]; };
void operator_map(operator_mapping &dest) const;
// read a register value
uint8_t read(uint16_t index) const { return m_regdata[index]; }
// handle writes to the register array
bool write(uint16_t index, uint8_t data, uint32_t &chan, uint32_t &opmask);
// clock the noise and LFO, if present, returning LFO PM value
int32_t clock_noise_and_lfo();
// reset the LFO
void reset_lfo() { m_lfo_counter = 0; }
// return the AM offset from LFO for the given channel
uint32_t lfo_am_offset(uint32_t choffs) const;
// return LFO/noise states
uint32_t noise_state() const { return 0; }
// caching helpers
void cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache);
// compute the phase step, given a PM value
uint32_t compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm);
// log a key-on event
std::string log_keyon(uint32_t choffs, uint32_t opoffs);
// system-wide registers
uint32_t test() const { return byte(0x21, 0, 8); }
uint32_t lfo_enable() const { return IsOpnA ? byte(0x22, 3, 1) : 0; }
uint32_t lfo_rate() const { return IsOpnA ? byte(0x22, 0, 3) : 0; }
uint32_t timer_a_value() const { return word(0x24, 0, 8, 0x25, 0, 2); }
uint32_t timer_b_value() const { return byte(0x26, 0, 8); }
uint32_t csm() const { return (byte(0x27, 6, 2) == 2); }
uint32_t multi_freq() const { return (byte(0x27, 6, 2) != 0); }
uint32_t reset_timer_b() const { return byte(0x27, 5, 1); }
uint32_t reset_timer_a() const { return byte(0x27, 4, 1); }
uint32_t enable_timer_b() const { return byte(0x27, 3, 1); }
uint32_t enable_timer_a() const { return byte(0x27, 2, 1); }
uint32_t load_timer_b() const { return byte(0x27, 1, 1); }
uint32_t load_timer_a() const { return byte(0x27, 0, 1); }
uint32_t multi_block_freq(uint32_t num) const { return word(0xac, 0, 6, 0xa8, 0, 8, num); }
// per-channel registers
uint32_t ch_block_freq(uint32_t choffs) const { return word(0xa4, 0, 6, 0xa0, 0, 8, choffs); }
uint32_t ch_feedback(uint32_t choffs) const { return byte(0xb0, 3, 3, choffs); }
uint32_t ch_algorithm(uint32_t choffs) const { return byte(0xb0, 0, 3, choffs); }
uint32_t ch_output_any(uint32_t choffs) const { return IsOpnA ? byte(0xb4, 6, 2, choffs) : 1; }
uint32_t ch_output_0(uint32_t choffs) const { return IsOpnA ? byte(0xb4, 7, 1, choffs) : 1; }
uint32_t ch_output_1(uint32_t choffs) const { return IsOpnA ? byte(0xb4, 6, 1, choffs) : 0; }
uint32_t ch_output_2(uint32_t choffs) const { return 0; }
uint32_t ch_output_3(uint32_t choffs) const { return 0; }
uint32_t ch_lfo_am_sens(uint32_t choffs) const { return IsOpnA ? byte(0xb4, 4, 2, choffs) : 0; }
uint32_t ch_lfo_pm_sens(uint32_t choffs) const { return IsOpnA ? byte(0xb4, 0, 3, choffs) : 0; }
// per-operator registers
uint32_t op_detune(uint32_t opoffs) const { return byte(0x30, 4, 3, opoffs); }
uint32_t op_multiple(uint32_t opoffs) const { return byte(0x30, 0, 4, opoffs); }
uint32_t op_total_level(uint32_t opoffs) const { return byte(0x40, 0, 7, opoffs); }
uint32_t op_ksr(uint32_t opoffs) const { return byte(0x50, 6, 2, opoffs); }
uint32_t op_attack_rate(uint32_t opoffs) const { return byte(0x50, 0, 5, opoffs); }
uint32_t op_decay_rate(uint32_t opoffs) const { return byte(0x60, 0, 5, opoffs); }
uint32_t op_lfo_am_enable(uint32_t opoffs) const { return IsOpnA ? byte(0x60, 7, 1, opoffs) : 0; }
uint32_t op_sustain_rate(uint32_t opoffs) const { return byte(0x70, 0, 5, opoffs); }
uint32_t op_sustain_level(uint32_t opoffs) const { return byte(0x80, 4, 4, opoffs); }
uint32_t op_release_rate(uint32_t opoffs) const { return byte(0x80, 0, 4, opoffs); }
uint32_t op_ssg_eg_enable(uint32_t opoffs) const { return byte(0x90, 3, 1, opoffs); }
uint32_t op_ssg_eg_mode(uint32_t opoffs) const { return byte(0x90, 0, 3, opoffs); }
protected:
// return a bitfield extracted from a byte
uint32_t byte(uint32_t offset, uint32_t start, uint32_t count, uint32_t extra_offset = 0) const
{
return bitfield(m_regdata[offset + extra_offset], start, count);
}
// return a bitfield extracted from a pair of bytes, MSBs listed first
uint32_t word(uint32_t offset1, uint32_t start1, uint32_t count1, uint32_t offset2, uint32_t start2, uint32_t count2, uint32_t extra_offset = 0) const
{
return (byte(offset1, start1, count1, extra_offset) << count2) | byte(offset2, start2, count2, extra_offset);
}
// internal state
uint32_t m_lfo_counter; // LFO counter
uint8_t m_lfo_am; // current LFO AM value
uint8_t m_regdata[REGISTERS]; // register data
uint16_t m_waveform[WAVEFORMS][WAVEFORM_LENGTH]; // waveforms
};
using opn_registers = opn_registers_base<false>;
using opna_registers = opn_registers_base<true>;
//*********************************************************
// OPN IMPLEMENTATION CLASSES
//*********************************************************
// A note about prescaling and sample rates.
//
// YM2203, YM2608, and YM2610 contain an onboard SSG (basically, a YM2149).
// In order to properly generate sound at fully fidelity, the output sample
// rate of the YM2149 must be input_clock / 8. This is much higher than the
// FM needs, but in the interest of keeping things simple, the OPN generate
// functions will output at the higher rate and just replicate the last FM
// sample as many times as needed.
//
// To make things even more complicated, the YM2203 and YM2608 allow for
// software-controlled prescaling, which affects the FM and SSG clocks in
// different ways. There are three settings: divide by 6/4 (FM/SSG); divide
// by 3/2; and divide by 2/1.
//
// Thus, the minimum output sample rate needed by each part of the chip
// varies with the prescale as follows:
//
// ---- YM2203 ----- ---- YM2608 ----- ---- YM2610 -----
// Prescale FM rate SSG rate FM rate SSG rate FM rate SSG rate
// 6 /72 /16 /144 /32 /144 /32
// 3 /36 /8 /72 /16
// 2 /24 /4 /48 /8
//
// If we standardized on the fastest SSG rate, we'd end up with the following
// (ratios are output_samples:source_samples):
//
// ---- YM2203 ----- ---- YM2608 ----- ---- YM2610 -----
// rate = clock/4 rate = clock/8 rate = clock/16
// Prescale FM rate SSG rate FM rate SSG rate FM rate SSG rate
// 6 18:1 4:1 18:1 4:1 9:1 2:1
// 3 9:1 2:1 9:1 2:1
// 2 6:1 1:1 6:1 1:1
//
// However, that's a pretty big performance hit for minimal gain. Going to
// the other extreme, we could standardize on the fastest FM rate, but then
// at least one prescale case (3) requires the FM to be smeared across two
// output samples:
//
// ---- YM2203 ----- ---- YM2608 ----- ---- YM2610 -----
// rate = clock/24 rate = clock/48 rate = clock/144
// Prescale FM rate SSG rate FM rate SSG rate FM rate SSG rate
// 6 3:1 2:3 3:1 2:3 1:1 2:9
// 3 1.5:1 1:3 1.5:1 1:3
// 2 1:1 1:6 1:1 1:6
//
// Stepping back one factor of 2 addresses that issue:
//
// ---- YM2203 ----- ---- YM2608 ----- ---- YM2610 -----
// rate = clock/12 rate = clock/24 rate = clock/144
// Prescale FM rate SSG rate FM rate SSG rate FM rate SSG rate
// 6 6:1 4:3 6:1 4:3 1:1 2:9
// 3 3:1 2:3 3:1 2:3
// 2 2:1 1:3 2:1 1:3
//
// This gives us three levels of output fidelity:
// OPN_FIDELITY_MAX -- highest sample rate, using fastest SSG rate
// OPN_FIDELITY_MIN -- lowest sample rate, using fastest FM rate
// OPN_FIDELITY_MED -- medium sample rate such that FM is never smeared
//
// At the maximum clocks for YM2203/YM2608 (4Mhz/8MHz), these rates will
// end up as:
// OPN_FIDELITY_MAX = 1000kHz
// OPN_FIDELITY_MIN = 166kHz
// OPN_FIEDLITY_MED = 333kHz
// ======================> opn_fidelity
enum opn_fidelity : uint8_t
{
OPN_FIDELITY_MAX,
OPN_FIDELITY_MIN,
OPN_FIDELITY_MED,
OPN_FIDELITY_DEFAULT = OPN_FIDELITY_MAX
};
// ======================> ssg_resampler
template<typename OutputType, int FirstOutput, bool MixTo1>
class ssg_resampler
{
private:
// helper to add the last computed value to the sums, applying the given scale
void add_last(int32_t &sum0, int32_t &sum1, int32_t &sum2, int32_t scale = 1);
// helper to clock a new value and then add it to the sums, applying the given scale
void clock_and_add(int32_t &sum0, int32_t &sum1, int32_t &sum2, int32_t scale = 1);
// helper to write the sums to the appropriate outputs, applying the given
// divisor to the final result
void write_to_output(OutputType *output, int32_t sum0, int32_t sum1, int32_t sum2, int32_t divisor = 1);
public:
// constructor
ssg_resampler(ssg_engine &ssg);
// save/restore
void save_restore(ymfm_saved_state &state);
// get the current sample index
uint32_t sampindex() const { return m_sampindex; }
// configure the ratio
void configure(uint8_t outsamples, uint8_t srcsamples);
// resample
void resample(OutputType *output, uint32_t numsamples)
{
(this->*m_resampler)(output, numsamples);
}
private:
// resample SSG output to the target at a rate of 1 SSG sample
// to every n output samples
template<int Multiplier>
void resample_n_1(OutputType *output, uint32_t numsamples);
// resample SSG output to the target at a rate of n SSG samples
// to every 1 output sample
template<int Divisor>
void resample_1_n(OutputType *output, uint32_t numsamples);
// resample SSG output to the target at a rate of 9 SSG samples
// to every 2 output samples
void resample_2_9(OutputType *output, uint32_t numsamples);
// resample SSG output to the target at a rate of 3 SSG samples
// to every 1 output sample
void resample_1_3(OutputType *output, uint32_t numsamples);
// resample SSG output to the target at a rate of 3 SSG samples
// to every 2 output samples
void resample_2_3(OutputType *output, uint32_t numsamples);
// resample SSG output to the target at a rate of 3 SSG samples
// to every 4 output samples
void resample_4_3(OutputType *output, uint32_t numsamples);
// no-op resampler
void resample_nop(OutputType *output, uint32_t numsamples);
// define a pointer type
using resample_func = void (ssg_resampler::*)(OutputType *output, uint32_t numsamples);
// internal state
ssg_engine &m_ssg;
uint32_t m_sampindex;
resample_func m_resampler;
ssg_engine::output_data m_last;
};
// ======================> ym2203
class ym2203
{
public:
using fm_engine = fm_engine_base<opn_registers>;
static constexpr uint32_t FM_OUTPUTS = fm_engine::OUTPUTS;
static constexpr uint32_t SSG_OUTPUTS = ssg_engine::OUTPUTS;
static constexpr uint32_t OUTPUTS = FM_OUTPUTS + SSG_OUTPUTS;
using output_data = ymfm_output<OUTPUTS>;
// constructor
ym2203(ymfm_interface &intf);
// configuration
void ssg_override(ssg_override &intf) { m_ssg.override(intf); }
void set_fidelity(opn_fidelity fidelity) { m_fidelity = fidelity; update_prescale(m_fm.clock_prescale()); }
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const
{
switch (m_fidelity)
{
case OPN_FIDELITY_MIN: return input_clock / 24;
case OPN_FIDELITY_MED: return input_clock / 12;
default:
case OPN_FIDELITY_MAX: return input_clock / 4;
}
}
uint32_t ssg_effective_clock(uint32_t input_clock) const { uint32_t scale = m_fm.clock_prescale() * 2 / 3; return input_clock * 2 / scale; }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read_data();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal helpers
void update_prescale(uint8_t prescale);
void clock_fm();
// internal state
opn_fidelity m_fidelity; // configured fidelity
uint8_t m_address; // address register
uint8_t m_fm_samples_per_output; // how many samples to repeat
fm_engine::output_data m_last_fm; // last FM output
fm_engine m_fm; // core FM engine
ssg_engine m_ssg; // SSG engine
ssg_resampler<output_data, 1, false> m_ssg_resampler; // SSG resampler helper
};
//*********************************************************
// OPNA IMPLEMENTATION CLASSES
//*********************************************************
// ======================> ym2608
class ym2608
{
static constexpr uint8_t STATUS_ADPCM_B_EOS = 0x04;
static constexpr uint8_t STATUS_ADPCM_B_BRDY = 0x08;
static constexpr uint8_t STATUS_ADPCM_B_ZERO = 0x10;
static constexpr uint8_t STATUS_ADPCM_B_PLAYING = 0x20;
public:
using fm_engine = fm_engine_base<opna_registers>;
static constexpr uint32_t FM_OUTPUTS = fm_engine::OUTPUTS;
static constexpr uint32_t SSG_OUTPUTS = 1;
static constexpr uint32_t OUTPUTS = FM_OUTPUTS + SSG_OUTPUTS;
using output_data = ymfm_output<OUTPUTS>;
// constructor
ym2608(ymfm_interface &intf);
// configuration
void ssg_override(ssg_override &intf) { m_ssg.override(intf); }
void set_fidelity(opn_fidelity fidelity) { m_fidelity = fidelity; update_prescale(m_fm.clock_prescale()); }
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const
{
switch (m_fidelity)
{
case OPN_FIDELITY_MIN: return input_clock / 48;
case OPN_FIDELITY_MED: return input_clock / 24;
default:
case OPN_FIDELITY_MAX: return input_clock / 8;
}
}
uint32_t ssg_effective_clock(uint32_t input_clock) const { uint32_t scale = m_fm.clock_prescale() * 2 / 3; return input_clock / scale; }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read_data();
uint8_t read_status_hi();
uint8_t read_data_hi();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write_address_hi(uint8_t data);
void write_data_hi(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal helpers
void update_prescale(uint8_t prescale);
void clock_fm_and_adpcm();
// internal state
opn_fidelity m_fidelity; // configured fidelity
uint16_t m_address; // address register
uint8_t m_fm_samples_per_output; // how many samples to repeat
uint8_t m_irq_enable; // IRQ enable register
uint8_t m_flag_control; // flag control register
fm_engine::output_data m_last_fm; // last FM output
fm_engine m_fm; // core FM engine
ssg_engine m_ssg; // SSG engine
ssg_resampler<output_data, 2, true> m_ssg_resampler; // SSG resampler helper
adpcm_a_engine m_adpcm_a; // ADPCM-A engine
adpcm_b_engine m_adpcm_b; // ADPCM-B engine
};
// ======================> ymf288
class ymf288
{
public:
using fm_engine = fm_engine_base<opna_registers>;
static constexpr uint32_t FM_OUTPUTS = fm_engine::OUTPUTS;
static constexpr uint32_t SSG_OUTPUTS = 1;
static constexpr uint32_t OUTPUTS = FM_OUTPUTS + SSG_OUTPUTS;
using output_data = ymfm_output<OUTPUTS>;
// constructor
ymf288(ymfm_interface &intf);
// configuration
void ssg_override(ssg_override &intf) { m_ssg.override(intf); }
void set_fidelity(opn_fidelity fidelity) { m_fidelity = fidelity; update_prescale(); }
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const
{
switch (m_fidelity)
{
case OPN_FIDELITY_MIN: return input_clock / 144;
case OPN_FIDELITY_MED: return input_clock / 144;
default:
case OPN_FIDELITY_MAX: return input_clock / 16;
}
}
uint32_t ssg_effective_clock(uint32_t input_clock) const { return input_clock / 4; }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read_data();
uint8_t read_status_hi();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write_address_hi(uint8_t data);
void write_data_hi(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal helpers
bool ymf288_mode() { return ((m_fm.regs().read(0x20) & 0x02) != 0); }
void update_prescale();
void clock_fm_and_adpcm();
// internal state
opn_fidelity m_fidelity; // configured fidelity
uint16_t m_address; // address register
uint8_t m_fm_samples_per_output; // how many samples to repeat
uint8_t m_irq_enable; // IRQ enable register
uint8_t m_flag_control; // flag control register
fm_engine::output_data m_last_fm; // last FM output
fm_engine m_fm; // core FM engine
ssg_engine m_ssg; // SSG engine
ssg_resampler<output_data, 2, true> m_ssg_resampler; // SSG resampler helper
adpcm_a_engine m_adpcm_a; // ADPCM-A engine
};
// ======================> ym2610/ym2610b
class ym2610
{
static constexpr uint8_t EOS_FLAGS_MASK = 0xbf;
public:
using fm_engine = fm_engine_base<opna_registers>;
static constexpr uint32_t FM_OUTPUTS = fm_engine::OUTPUTS;
static constexpr uint32_t SSG_OUTPUTS = 1;
static constexpr uint32_t OUTPUTS = FM_OUTPUTS + SSG_OUTPUTS;
using output_data = ymfm_output<OUTPUTS>;
// constructor
ym2610(ymfm_interface &intf, uint8_t channel_mask = 0x36);
// configuration
void ssg_override(ssg_override &intf) { m_ssg.override(intf); }
void set_fidelity(opn_fidelity fidelity) { m_fidelity = fidelity; update_prescale(); }
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const
{
switch (m_fidelity)
{
case OPN_FIDELITY_MIN: return input_clock / 144;
case OPN_FIDELITY_MED: return input_clock / 144;
default:
case OPN_FIDELITY_MAX: return input_clock / 16;
}
}
uint32_t ssg_effective_clock(uint32_t input_clock) const { return input_clock / 4; }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read_data();
uint8_t read_status_hi();
uint8_t read_data_hi();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write_address_hi(uint8_t data);
void write_data_hi(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal helpers
void update_prescale();
void clock_fm_and_adpcm();
// internal state
opn_fidelity m_fidelity; // configured fidelity
uint16_t m_address; // address register
uint8_t const m_fm_mask; // FM channel mask
uint8_t m_fm_samples_per_output; // how many samples to repeat
uint8_t m_eos_status; // end-of-sample signals
uint8_t m_flag_mask; // flag mask control
fm_engine::output_data m_last_fm; // last FM output
fm_engine m_fm; // core FM engine
ssg_engine m_ssg; // core FM engine
ssg_resampler<output_data, 2, true> m_ssg_resampler; // SSG resampler helper
adpcm_a_engine m_adpcm_a; // ADPCM-A engine
adpcm_b_engine m_adpcm_b; // ADPCM-B engine
};
class ym2610b : public ym2610
{
public:
// constructor
ym2610b(ymfm_interface &intf) : ym2610(intf, 0x3f) { }
};
// ======================> ym2612
class ym2612
{
public:
using fm_engine = fm_engine_base<opna_registers>;
static constexpr uint32_t OUTPUTS = fm_engine::OUTPUTS;
using output_data = fm_engine::output_data;
// constructor
ym2612(ymfm_interface &intf);
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return m_fm.sample_rate(input_clock); }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write_address_hi(uint8_t data);
void write_data_hi(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// simulate the DAC discontinuity
constexpr int32_t dac_discontinuity(int32_t value) const { return (value < 0) ? (value - 3) : (value + 4); }
// internal state
uint16_t m_address; // address register
uint16_t m_dac_data; // 9-bit DAC data
uint8_t m_dac_enable; // DAC enabled?
fm_engine m_fm; // core FM engine
};
// ======================> ym3438
class ym3438 : public ym2612
{
public:
ym3438(ymfm_interface &intf) : ym2612(intf) { }
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples = 1);
};
// ======================> ymf276
class ymf276 : public ym2612
{
public:
ymf276(ymfm_interface &intf) : ym2612(intf) { }
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples);
};
}
#endif // YMFM_OPN_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm_opn.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 8,136 |
```c++
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ymfm_opl.h"
#include "ymfm_fm.ipp"
namespace ymfm
{
//-------------------------------------------------
// opl_key_scale_atten - converts an
// OPL concatenated block (3 bits) and fnum
// (10 bits) into an attenuation offset; values
// here are for 6dB/octave, in 0.75dB units
// (matching total level LSB)
//-------------------------------------------------
inline uint32_t opl_key_scale_atten(uint32_t block, uint32_t fnum_4msb)
{
// this table uses the top 4 bits of FNUM and are the maximal values
// (for when block == 7). Values for other blocks can be computed by
// subtracting 8 for each block below 7.
static uint8_t const fnum_to_atten[16] = { 0,24,32,37,40,43,45,47,48,50,51,52,53,54,55,56 };
int32_t result = fnum_to_atten[fnum_4msb] - 8 * (block ^ 7);
return std::max<int32_t>(0, result);
}
//*********************************************************
// OPL REGISTERS
//*********************************************************
//-------------------------------------------------
// opl_registers_base - constructor
//-------------------------------------------------
template<int Revision>
opl_registers_base<Revision>::opl_registers_base() :
m_lfo_am_counter(0),
m_lfo_pm_counter(0),
m_noise_lfsr(1),
m_lfo_am(0)
{
// create these pointers to appease overzealous compilers checking array
// bounds in unreachable code (looking at you, clang)
uint16_t *wf0 = &m_waveform[0][0];
uint16_t *wf1 = &m_waveform[1 % WAVEFORMS][0];
uint16_t *wf2 = &m_waveform[2 % WAVEFORMS][0];
uint16_t *wf3 = &m_waveform[3 % WAVEFORMS][0];
uint16_t *wf4 = &m_waveform[4 % WAVEFORMS][0];
uint16_t *wf5 = &m_waveform[5 % WAVEFORMS][0];
uint16_t *wf6 = &m_waveform[6 % WAVEFORMS][0];
uint16_t *wf7 = &m_waveform[7 % WAVEFORMS][0];
// create the waveforms
for (uint32_t index = 0; index < WAVEFORM_LENGTH; index++)
wf0[index] = abs_sin_attenuation(index) | (bitfield(index, 9) << 15);
if (WAVEFORMS >= 4)
{
uint16_t zeroval = wf0[0];
for (uint32_t index = 0; index < WAVEFORM_LENGTH; index++)
{
wf1[index] = bitfield(index, 9) ? zeroval : wf0[index];
wf2[index] = wf0[index] & 0x7fff;
wf3[index] = bitfield(index, 8) ? zeroval : (wf0[index] & 0x7fff);
if (WAVEFORMS >= 8)
{
wf4[index] = bitfield(index, 9) ? zeroval : wf0[index * 2];
wf5[index] = bitfield(index, 9) ? zeroval : wf0[(index * 2) & 0x1ff];
wf6[index] = bitfield(index, 9) << 15;
wf7[index] = (bitfield(index, 9) ? (index ^ 0x13ff) : index) << 3;
}
}
}
// OPL3/OPL4 have dynamic operators, so initialize the fourop_enable value here
// since operator_map() is called right away, prior to reset()
if (Revision > 2)
m_regdata[0x104 % REGISTERS] = 0;
}
//-------------------------------------------------
// reset - reset to initial state
//-------------------------------------------------
template<int Revision>
void opl_registers_base<Revision>::reset()
{
std::fill_n(&m_regdata[0], REGISTERS, 0);
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
template<int Revision>
void opl_registers_base<Revision>::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_lfo_am_counter);
state.save_restore(m_lfo_pm_counter);
state.save_restore(m_lfo_am);
state.save_restore(m_noise_lfsr);
state.save_restore(m_regdata);
}
//-------------------------------------------------
// operator_map - return an array of operator
// indices for each channel; for OPL this is fixed
//-------------------------------------------------
template<int Revision>
void opl_registers_base<Revision>::operator_map(operator_mapping &dest) const
{
if (Revision <= 2)
{
// OPL/OPL2 has a fixed map, all 2 operators
static const operator_mapping s_fixed_map =
{ {
operator_list( 0, 3 ), // Channel 0 operators
operator_list( 1, 4 ), // Channel 1 operators
operator_list( 2, 5 ), // Channel 2 operators
operator_list( 6, 9 ), // Channel 3 operators
operator_list( 7, 10 ), // Channel 4 operators
operator_list( 8, 11 ), // Channel 5 operators
operator_list( 12, 15 ), // Channel 6 operators
operator_list( 13, 16 ), // Channel 7 operators
operator_list( 14, 17 ), // Channel 8 operators
} };
dest = s_fixed_map;
}
else
{
// OPL3/OPL4 can be configured for 2 or 4 operators
uint32_t fourop = fourop_enable();
dest.chan[ 0] = bitfield(fourop, 0) ? operator_list( 0, 3, 6, 9 ) : operator_list( 0, 3 );
dest.chan[ 1] = bitfield(fourop, 1) ? operator_list( 1, 4, 7, 10 ) : operator_list( 1, 4 );
dest.chan[ 2] = bitfield(fourop, 2) ? operator_list( 2, 5, 8, 11 ) : operator_list( 2, 5 );
dest.chan[ 3] = bitfield(fourop, 0) ? operator_list() : operator_list( 6, 9 );
dest.chan[ 4] = bitfield(fourop, 1) ? operator_list() : operator_list( 7, 10 );
dest.chan[ 5] = bitfield(fourop, 2) ? operator_list() : operator_list( 8, 11 );
dest.chan[ 6] = operator_list( 12, 15 );
dest.chan[ 7] = operator_list( 13, 16 );
dest.chan[ 8] = operator_list( 14, 17 );
dest.chan[ 9] = bitfield(fourop, 3) ? operator_list( 18, 21, 24, 27 ) : operator_list( 18, 21 );
dest.chan[10] = bitfield(fourop, 4) ? operator_list( 19, 22, 25, 28 ) : operator_list( 19, 22 );
dest.chan[11] = bitfield(fourop, 5) ? operator_list( 20, 23, 26, 29 ) : operator_list( 20, 23 );
dest.chan[12] = bitfield(fourop, 3) ? operator_list() : operator_list( 24, 27 );
dest.chan[13] = bitfield(fourop, 4) ? operator_list() : operator_list( 25, 28 );
dest.chan[14] = bitfield(fourop, 5) ? operator_list() : operator_list( 26, 29 );
dest.chan[15] = operator_list( 30, 33 );
dest.chan[16] = operator_list( 31, 34 );
dest.chan[17] = operator_list( 32, 35 );
}
}
//-------------------------------------------------
// write - handle writes to the register array
//-------------------------------------------------
template<int Revision>
bool opl_registers_base<Revision>::write(uint16_t index, uint8_t data, uint32_t &channel, uint32_t &opmask)
{
assert(index < REGISTERS);
// writes to the mode register with high bit set ignore the low bits
if (index == REG_MODE && bitfield(data, 7) != 0)
m_regdata[index] |= 0x80;
else
m_regdata[index] = data;
// handle writes to the rhythm keyons
if (index == 0xbd)
{
channel = RHYTHM_CHANNEL;
opmask = bitfield(data, 5) ? bitfield(data, 0, 5) : 0;
return true;
}
// handle writes to the channel keyons
if ((index & 0xf0) == 0xb0)
{
channel = index & 0x0f;
if (channel < 9)
{
if (IsOpl3Plus)
channel += 9 * bitfield(index, 8);
opmask = bitfield(data, 5) ? 15 : 0;
return true;
}
}
return false;
}
//-------------------------------------------------
// clock_noise_and_lfo - clock the noise and LFO,
// handling clock division, depth, and waveform
// computations
//-------------------------------------------------
static int32_t opl_clock_noise_and_lfo(uint32_t &noise_lfsr, uint16_t &lfo_am_counter, uint16_t &lfo_pm_counter, uint8_t &lfo_am, uint32_t am_depth, uint32_t pm_depth)
{
// OPL has a 23-bit noise generator for the rhythm section, running at
// a constant rate, used only for percussion input
noise_lfsr <<= 1;
noise_lfsr |= bitfield(noise_lfsr, 23) ^ bitfield(noise_lfsr, 9) ^ bitfield(noise_lfsr, 8) ^ bitfield(noise_lfsr, 1);
// OPL has two fixed-frequency LFOs, one for AM, one for PM
// the AM LFO has 210*64 steps; at a nominal 50kHz output,
// this equates to a period of 50000/(210*64) = 3.72Hz
uint32_t am_counter = lfo_am_counter++;
if (am_counter >= 210*64 - 1)
lfo_am_counter = 0;
// low 8 bits are fractional; depth 0 is divided by 2, while depth 1 is times 2
int shift = 9 - 2 * am_depth;
// AM value is the upper bits of the value, inverted across the midpoint
// to produce a triangle
lfo_am = ((am_counter < 105*64) ? am_counter : (210*64+63 - am_counter)) >> shift;
// the PM LFO has 8192 steps, or a nominal period of 6.1Hz
uint32_t pm_counter = lfo_pm_counter++;
// PM LFO is broken into 8 chunks, each lasting 1024 steps; the PM value
// depends on the upper bits of FNUM, so this value is a fraction and
// sign to apply to that value, as a 1.3 value
static int8_t const pm_scale[8] = { 8, 4, 0, -4, -8, -4, 0, 4 };
return pm_scale[bitfield(pm_counter, 10, 3)] >> (pm_depth ^ 1);
}
template<int Revision>
int32_t opl_registers_base<Revision>::clock_noise_and_lfo()
{
return opl_clock_noise_and_lfo(m_noise_lfsr, m_lfo_am_counter, m_lfo_pm_counter, m_lfo_am, lfo_am_depth(), lfo_pm_depth());
}
//-------------------------------------------------
// cache_operator_data - fill the operator cache
// with prefetched data; note that this code is
// also used by ymopna_registers, so it must
// handle upper channels cleanly
//-------------------------------------------------
template<int Revision>
void opl_registers_base<Revision>::cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache)
{
// set up the easy stuff
cache.waveform = &m_waveform[op_waveform(opoffs) % WAVEFORMS][0];
// get frequency from the channel
uint32_t block_freq = cache.block_freq = ch_block_freq(choffs);
// compute the keycode: block_freq is:
//
// 111 |
// 21098|76543210
// BBBFF|FFFFFFFF
// ^^^??
//
// the 4-bit keycode uses the top 3 bits plus one of the next two bits
uint32_t keycode = bitfield(block_freq, 10, 3) << 1;
// lowest bit is determined by note_select(); note that it is
// actually reversed from what the manual says, however
keycode |= bitfield(block_freq, 9 - note_select(), 1);
// no detune adjustment on OPL
cache.detune = 0;
// multiple value, as an x.1 value (0 means 0.5)
// replace the low bit with a table lookup to give 0,1,2,3,4,5,6,7,8,9,10,10,12,12,15,15
uint32_t multiple = op_multiple(opoffs);
cache.multiple = ((multiple & 0xe) | bitfield(0xc2aa, multiple)) * 2;
if (cache.multiple == 0)
cache.multiple = 1;
// phase step, or PHASE_STEP_DYNAMIC if PM is active; this depends on block_freq, detune,
// and multiple, so compute it after we've done those
if (op_lfo_pm_enable(opoffs) == 0)
cache.phase_step = compute_phase_step(choffs, opoffs, cache, 0);
else
cache.phase_step = opdata_cache::PHASE_STEP_DYNAMIC;
// total level, scaled by 8
cache.total_level = op_total_level(opoffs) << 3;
// pre-add key scale level
uint32_t ksl = op_ksl(opoffs);
if (ksl != 0)
cache.total_level += opl_key_scale_atten(bitfield(block_freq, 10, 3), bitfield(block_freq, 6, 4)) << ksl;
// 4-bit sustain level, but 15 means 31 so effectively 5 bits
cache.eg_sustain = op_sustain_level(opoffs);
cache.eg_sustain |= (cache.eg_sustain + 1) & 0x10;
cache.eg_sustain <<= 5;
// determine KSR adjustment for enevlope rates
uint32_t ksrval = keycode >> (2 * (op_ksr(opoffs) ^ 1));
cache.eg_rate[EG_ATTACK] = effective_rate(op_attack_rate(opoffs) * 4, ksrval);
cache.eg_rate[EG_DECAY] = effective_rate(op_decay_rate(opoffs) * 4, ksrval);
cache.eg_rate[EG_SUSTAIN] = op_eg_sustain(opoffs) ? 0 : effective_rate(op_release_rate(opoffs) * 4, ksrval);
cache.eg_rate[EG_RELEASE] = effective_rate(op_release_rate(opoffs) * 4, ksrval);
cache.eg_rate[EG_DEPRESS] = 0x3f;
}
//-------------------------------------------------
// compute_phase_step - compute the phase step
//-------------------------------------------------
static uint32_t opl_compute_phase_step(uint32_t block_freq, uint32_t multiple, int32_t lfo_raw_pm)
{
// OPL phase calculation has no detuning, but uses FNUMs like
// the OPN version, and computes PM a bit differently
// extract frequency number as a 12-bit fraction
uint32_t fnum = bitfield(block_freq, 0, 10) << 2;
// apply the phase adjustment based on the upper 3 bits
// of FNUM and the PM depth parameters
fnum += (lfo_raw_pm * bitfield(block_freq, 7, 3)) >> 1;
// keep fnum to 12 bits
fnum &= 0xfff;
// apply block shift to compute phase step
uint32_t block = bitfield(block_freq, 10, 3);
uint32_t phase_step = (fnum << block) >> 2;
// apply frequency multiplier (which is cached as an x.1 value)
return (phase_step * multiple) >> 1;
}
template<int Revision>
uint32_t opl_registers_base<Revision>::compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm)
{
return opl_compute_phase_step(cache.block_freq, cache.multiple, op_lfo_pm_enable(opoffs) ? lfo_raw_pm : 0);
}
//-------------------------------------------------
// log_keyon - log a key-on event
//-------------------------------------------------
template<int Revision>
std::string opl_registers_base<Revision>::log_keyon(uint32_t choffs, uint32_t opoffs)
{
uint32_t chnum = (choffs & 15) + 9 * bitfield(choffs, 8);
uint32_t opnum = (opoffs & 31) - 2 * ((opoffs & 31) / 8) + 18 * bitfield(opoffs, 8);
char buffer[256];
char *end = &buffer[0];
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, "%2u.%02u freq=%04X fb=%u alg=%X mul=%X tl=%02X ksr=%u ns=%u ksl=%u adr=%X/%X/%X sl=%X sus=%u",
chnum, opnum,
ch_block_freq(choffs),
ch_feedback(choffs),
ch_algorithm(choffs),
op_multiple(opoffs),
op_total_level(opoffs),
op_ksr(opoffs),
note_select(),
op_ksl(opoffs),
op_attack_rate(opoffs),
op_decay_rate(opoffs),
op_release_rate(opoffs),
op_sustain_level(opoffs),
op_eg_sustain(opoffs));
if (OUTPUTS > 1)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " out=%c%c%c%c",
ch_output_0(choffs) ? 'L' : '-',
ch_output_1(choffs) ? 'R' : '-',
ch_output_2(choffs) ? '0' : '-',
ch_output_3(choffs) ? '1' : '-');
if (op_lfo_am_enable(opoffs) != 0)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " am=%u", lfo_am_depth());
if (op_lfo_pm_enable(opoffs) != 0)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " pm=%u", lfo_pm_depth());
if (waveform_enable() && op_waveform(opoffs) != 0)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " wf=%u", op_waveform(opoffs));
if (is_rhythm(choffs))
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " rhy=1");
if (DYNAMIC_OPS)
{
operator_mapping map;
operator_map(map);
if (bitfield(map.chan[chnum], 16, 8) != 0xff)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " 4op");
}
return buffer;
}
//*********************************************************
// OPLL SPECIFICS
//*********************************************************
//-------------------------------------------------
// opll_registers - constructor
//-------------------------------------------------
opll_registers::opll_registers() :
m_lfo_am_counter(0),
m_lfo_pm_counter(0),
m_noise_lfsr(1),
m_lfo_am(0)
{
// create the waveforms
for (uint32_t index = 0; index < WAVEFORM_LENGTH; index++)
m_waveform[0][index] = abs_sin_attenuation(index) | (bitfield(index, 9) << 15);
uint16_t zeroval = m_waveform[0][0];
for (uint32_t index = 0; index < WAVEFORM_LENGTH; index++)
m_waveform[1][index] = bitfield(index, 9) ? zeroval : m_waveform[0][index];
// initialize the instruments to something sane
for (uint32_t choffs = 0; choffs < CHANNELS; choffs++)
m_chinst[choffs] = &m_regdata[0];
for (uint32_t opoffs = 0; opoffs < OPERATORS; opoffs++)
m_opinst[opoffs] = &m_regdata[bitfield(opoffs, 0)];
}
//-------------------------------------------------
// reset - reset to initial state
//-------------------------------------------------
void opll_registers::reset()
{
std::fill_n(&m_regdata[0], REGISTERS, 0);
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void opll_registers::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_lfo_am_counter);
state.save_restore(m_lfo_pm_counter);
state.save_restore(m_lfo_am);
state.save_restore(m_noise_lfsr);
state.save_restore(m_regdata);
}
//-------------------------------------------------
// operator_map - return an array of operator
// indices for each channel; for OPLL this is fixed
//-------------------------------------------------
void opll_registers::operator_map(operator_mapping &dest) const
{
static const operator_mapping s_fixed_map =
{ {
operator_list( 0, 1 ), // Channel 0 operators
operator_list( 2, 3 ), // Channel 1 operators
operator_list( 4, 5 ), // Channel 2 operators
operator_list( 6, 7 ), // Channel 3 operators
operator_list( 8, 9 ), // Channel 4 operators
operator_list( 10, 11 ), // Channel 5 operators
operator_list( 12, 13 ), // Channel 6 operators
operator_list( 14, 15 ), // Channel 7 operators
operator_list( 16, 17 ), // Channel 8 operators
} };
dest = s_fixed_map;
}
//-------------------------------------------------
// write - handle writes to the register array;
// note that this code is also used by
// ymopl3_registers, so it must handle upper
// channels cleanly
//-------------------------------------------------
bool opll_registers::write(uint16_t index, uint8_t data, uint32_t &channel, uint32_t &opmask)
{
// unclear the address is masked down to 6 bits or if writes above
// the register top are ignored; assuming the latter for now
if (index >= REGISTERS)
return false;
// write the new data
m_regdata[index] = data;
// handle writes to the rhythm keyons
if (index == 0x0e)
{
channel = RHYTHM_CHANNEL;
opmask = bitfield(data, 5) ? bitfield(data, 0, 5) : 0;
return true;
}
// handle writes to the channel keyons
if ((index & 0xf0) == 0x20)
{
channel = index & 0x0f;
if (channel < CHANNELS)
{
opmask = bitfield(data, 4) ? 3 : 0;
return true;
}
}
return false;
}
//-------------------------------------------------
// clock_noise_and_lfo - clock the noise and LFO,
// handling clock division, depth, and waveform
// computations
//-------------------------------------------------
int32_t opll_registers::clock_noise_and_lfo()
{
// implementation is the same as OPL with fixed depths
return opl_clock_noise_and_lfo(m_noise_lfsr, m_lfo_am_counter, m_lfo_pm_counter, m_lfo_am, 1, 1);
}
//-------------------------------------------------
// cache_operator_data - fill the operator cache
// with prefetched data; note that this code is
// also used by ymopna_registers, so it must
// handle upper channels cleanly
//-------------------------------------------------
void opll_registers::cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache)
{
// first set up the instrument data
uint32_t instrument = ch_instrument(choffs);
if (rhythm_enable() && choffs >= 6)
m_chinst[choffs] = &m_instdata[8 * (15 + (choffs - 6))];
else
m_chinst[choffs] = (instrument == 0) ? &m_regdata[0] : &m_instdata[8 * (instrument - 1)];
m_opinst[opoffs] = m_chinst[choffs] + bitfield(opoffs, 0);
// set up the easy stuff
cache.waveform = &m_waveform[op_waveform(opoffs) % WAVEFORMS][0];
// get frequency from the channel
uint32_t block_freq = cache.block_freq = ch_block_freq(choffs);
// compute the keycode: block_freq is:
//
// 11 |
// 1098|76543210
// BBBF|FFFFFFFF
// ^^^^
//
// the 4-bit keycode uses the top 4 bits
uint32_t keycode = bitfield(block_freq, 8, 4);
// no detune adjustment on OPLL
cache.detune = 0;
// multiple value, as an x.1 value (0 means 0.5)
// replace the low bit with a table lookup to give 0,1,2,3,4,5,6,7,8,9,10,10,12,12,15,15
uint32_t multiple = op_multiple(opoffs);
cache.multiple = ((multiple & 0xe) | bitfield(0xc2aa, multiple)) * 2;
if (cache.multiple == 0)
cache.multiple = 1;
// phase step, or PHASE_STEP_DYNAMIC if PM is active; this depends on
// block_freq, detune, and multiple, so compute it after we've done those
if (op_lfo_pm_enable(opoffs) == 0)
cache.phase_step = compute_phase_step(choffs, opoffs, cache, 0);
else
cache.phase_step = opdata_cache::PHASE_STEP_DYNAMIC;
// total level, scaled by 8; for non-rhythm operator 0, this is the total
// level from the instrument data; for other operators it is 4*volume
if (bitfield(opoffs, 0) == 1 || (rhythm_enable() && choffs >= 7))
cache.total_level = op_volume(opoffs) * 4;
else
cache.total_level = ch_total_level(choffs);
cache.total_level <<= 3;
// pre-add key scale level
uint32_t ksl = op_ksl(opoffs);
if (ksl != 0)
cache.total_level += opl_key_scale_atten(bitfield(block_freq, 9, 3), bitfield(block_freq, 5, 4)) << ksl;
// 4-bit sustain level, but 15 means 31 so effectively 5 bits
cache.eg_sustain = op_sustain_level(opoffs);
cache.eg_sustain |= (cache.eg_sustain + 1) & 0x10;
cache.eg_sustain <<= 5;
// The envelope diagram in the YM2413 datasheet gives values for these
// in ms from 0->48dB. The attack/decay tables give values in ms from
// 0->96dB, so to pick an equivalent decay rate, we want to find the
// closest match that is 2x the 0->48dB value:
//
// DP = 10ms (0->48db) -> 20ms (0->96db); decay of 12 gives 19.20ms
// RR = 310ms (0->48db) -> 620ms (0->96db); decay of 7 gives 613.76ms
// RS = 1200ms (0->48db) -> 2400ms (0->96db); decay of 5 gives 2455.04ms
//
// The envelope diagram for percussive sounds (eg_sustain() == 0) also uses
// "RR" to mean both the constant RR above and the Release Rate specified in
// the instrument data. In this case, Relief Pitcher's credit sound bears out
// that the Release Rate is used during sustain, and that the constant RR
// (or RS) is used during the release phase.
constexpr uint8_t DP = 12 * 4;
constexpr uint8_t RR = 7 * 4;
constexpr uint8_t RS = 5 * 4;
// determine KSR adjustment for envelope rates
uint32_t ksrval = keycode >> (2 * (op_ksr(opoffs) ^ 1));
cache.eg_rate[EG_DEPRESS] = DP;
cache.eg_rate[EG_ATTACK] = effective_rate(op_attack_rate(opoffs) * 4, ksrval);
cache.eg_rate[EG_DECAY] = effective_rate(op_decay_rate(opoffs) * 4, ksrval);
if (op_eg_sustain(opoffs))
{
cache.eg_rate[EG_SUSTAIN] = 0;
cache.eg_rate[EG_RELEASE] = ch_sustain(choffs) ? RS : effective_rate(op_release_rate(opoffs) * 4, ksrval);
}
else
{
cache.eg_rate[EG_SUSTAIN] = effective_rate(op_release_rate(opoffs) * 4, ksrval);
cache.eg_rate[EG_RELEASE] = ch_sustain(choffs) ? RS : RR;
}
}
//-------------------------------------------------
// compute_phase_step - compute the phase step
//-------------------------------------------------
uint32_t opll_registers::compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm)
{
// phase step computation is the same as OPL but the block_freq has one
// more bit, which we shift in
return opl_compute_phase_step(cache.block_freq << 1, cache.multiple, op_lfo_pm_enable(opoffs) ? lfo_raw_pm : 0);
}
//-------------------------------------------------
// log_keyon - log a key-on event
//-------------------------------------------------
std::string opll_registers::log_keyon(uint32_t choffs, uint32_t opoffs)
{
uint32_t chnum = choffs;
uint32_t opnum = opoffs;
char buffer[256];
char *end = &buffer[0];
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, "%u.%02u freq=%04X inst=%X fb=%u mul=%X",
chnum, opnum,
ch_block_freq(choffs),
ch_instrument(choffs),
ch_feedback(choffs),
op_multiple(opoffs));
if (bitfield(opoffs, 0) == 1 || (is_rhythm(choffs) && choffs >= 6))
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " vol=%X", op_volume(opoffs));
else
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " tl=%02X", ch_total_level(choffs));
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " ksr=%u ksl=%u adr=%X/%X/%X sl=%X sus=%u/%u",
op_ksr(opoffs),
op_ksl(opoffs),
op_attack_rate(opoffs),
op_decay_rate(opoffs),
op_release_rate(opoffs),
op_sustain_level(opoffs),
op_eg_sustain(opoffs),
ch_sustain(choffs));
if (op_lfo_am_enable(opoffs))
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " am=1");
if (op_lfo_pm_enable(opoffs))
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " pm=1");
if (op_waveform(opoffs) != 0)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " wf=1");
if (is_rhythm(choffs))
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " rhy=1");
return buffer;
}
//*********************************************************
// YM3526
//*********************************************************
//-------------------------------------------------
// ym3526 - constructor
//-------------------------------------------------
ym3526::ym3526(ymfm_interface &intf) :
m_address(0),
m_fm(intf)
{
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ym3526::reset()
{
// reset the engines
m_fm.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ym3526::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
m_fm.save_restore(state);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ym3526::read_status()
{
return m_fm.status() | 0x06;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ym3526::read(uint32_t offset)
{
uint8_t result = 0xff;
switch (offset & 1)
{
case 0: // status port
result = read_status();
break;
case 1: // when A0=1 datasheet says "the data on the bus are not guaranteed"
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ym3526::write_address(uint8_t data)
{
// YM3526 doesn't expose a busy signal, and the datasheets don't indicate
// delays, but all other OPL chips need 12 cycles for address writes
m_fm.intf().ymfm_set_busy_end(12 * m_fm.clock_prescale());
// just set the address
m_address = data;
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym3526::write_data(uint8_t data)
{
// YM3526 doesn't expose a busy signal, and the datasheets don't indicate
// delays, but all other OPL chips need 84 cycles for data writes
m_fm.intf().ymfm_set_busy_end(84 * m_fm.clock_prescale());
// write to FM
m_fm.write(m_address, data);
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym3526::write(uint32_t offset, uint8_t data)
{
switch (offset & 1)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
}
}
//-------------------------------------------------
// generate - generate samples of sound
//-------------------------------------------------
void ym3526::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// update the FM content; mixing details for YM3526 need verification
m_fm.output(output->clear(), 1, 32767, fm_engine::ALL_CHANNELS);
// YM3526 uses an external DAC (YM3014) with mantissa/exponent format
// convert to 10.3 floating point value and back to simulate truncation
output->roundtrip_fp();
}
}
//*********************************************************
// Y8950
//*********************************************************
//-------------------------------------------------
// y8950 - constructor
//-------------------------------------------------
y8950::y8950(ymfm_interface &intf) :
m_address(0),
m_io_ddr(0),
m_fm(intf),
m_adpcm_b(intf)
{
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void y8950::reset()
{
// reset the engines
m_fm.reset();
m_adpcm_b.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void y8950::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
state.save_restore(m_io_ddr);
m_fm.save_restore(state);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t y8950::read_status()
{
// start with current FM status, masking out bits we might set
uint8_t status = m_fm.status() & ~(STATUS_ADPCM_B_EOS | STATUS_ADPCM_B_BRDY | STATUS_ADPCM_B_PLAYING);
// insert the live ADPCM status bits
uint8_t adpcm_status = m_adpcm_b.status();
if ((adpcm_status & adpcm_b_channel::STATUS_EOS) != 0)
status |= STATUS_ADPCM_B_EOS;
if ((adpcm_status & adpcm_b_channel::STATUS_BRDY) != 0)
status |= STATUS_ADPCM_B_BRDY;
if ((adpcm_status & adpcm_b_channel::STATUS_PLAYING) != 0)
status |= STATUS_ADPCM_B_PLAYING;
// run it through the FM engine to handle interrupts for us
return m_fm.set_reset_status(status, ~status);
}
//-------------------------------------------------
// read_data - read the data port
//-------------------------------------------------
uint8_t y8950::read_data()
{
uint8_t result = 0xff;
switch (m_address)
{
case 0x05: // keyboard in
result = m_fm.intf().ymfm_external_read(ACCESS_IO, 1);
break;
case 0x09: // ADPCM data
case 0x1a:
result = m_adpcm_b.read(m_address - 0x07);
break;
case 0x19: // I/O data
result = m_fm.intf().ymfm_external_read(ACCESS_IO, 0);
break;
default:
debug::log_unexpected_read_write("Unexpected read from Y8950 data port %02X\n", m_address);
break;
}
return result;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t y8950::read(uint32_t offset)
{
uint8_t result = 0xff;
switch (offset & 1)
{
case 0: // status port
result = read_status();
break;
case 1: // when A0=1 datasheet says "the data on the bus are not guaranteed"
result = read_data();
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void y8950::write_address(uint8_t data)
{
// Y8950 doesn't expose a busy signal, but it does indicate that
// address writes should be no faster than every 12 clocks
m_fm.intf().ymfm_set_busy_end(12 * m_fm.clock_prescale());
// just set the address
m_address = data;
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void y8950::write_data(uint8_t data)
{
// Y8950 doesn't expose a busy signal, but it does indicate that
// data writes should be no faster than every 12 clocks for
// registers 00-1A, or every 84 clocks for other registers
m_fm.intf().ymfm_set_busy_end(((m_address <= 0x1a) ? 12 : 84) * m_fm.clock_prescale());
// handle special addresses
switch (m_address)
{
case 0x04: // IRQ control
m_fm.write(m_address, data);
read_status();
break;
case 0x06: // keyboard out
m_fm.intf().ymfm_external_write(ACCESS_IO, 1, data);
break;
case 0x08: // split FM/ADPCM-B
m_adpcm_b.write(m_address - 0x07, (data & 0x0f) | 0x80);
m_fm.write(m_address, data & 0xc0);
break;
case 0x07: // ADPCM-B registers
case 0x09:
case 0x0a:
case 0x0b:
case 0x0c:
case 0x0d:
case 0x0e:
case 0x0f:
case 0x10:
case 0x11:
case 0x12:
case 0x15:
case 0x16:
case 0x17:
m_adpcm_b.write(m_address - 0x07, data);
break;
case 0x18: // I/O direction
m_io_ddr = data & 0x0f;
break;
case 0x19: // I/O data
m_fm.intf().ymfm_external_write(ACCESS_IO, 0, data & m_io_ddr);
break;
default: // everything else to FM
m_fm.write(m_address, data);
break;
}
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void y8950::write(uint32_t offset, uint8_t data)
{
switch (offset & 1)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
}
}
//-------------------------------------------------
// generate - generate samples of sound
//-------------------------------------------------
void y8950::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
m_adpcm_b.clock();
// update the FM content; clipping need verification
m_fm.output(output->clear(), 1, 32767, fm_engine::ALL_CHANNELS);
// mix in the ADPCM; ADPCM-B is stereo, but only one channel
// not sure how it's wired up internally
m_adpcm_b.output(*output, 3);
// Y8950 uses an external DAC (YM3014) with mantissa/exponent format
// convert to 10.3 floating point value and back to simulate truncation
output->roundtrip_fp();
}
}
//*********************************************************
// YM3812
//*********************************************************
//-------------------------------------------------
// ym3812 - constructor
//-------------------------------------------------
ym3812::ym3812(ymfm_interface &intf) :
m_address(0),
m_fm(intf)
{
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ym3812::reset()
{
// reset the engines
m_fm.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ym3812::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
m_fm.save_restore(state);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ym3812::read_status()
{
return m_fm.status() | 0x06;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ym3812::read(uint32_t offset)
{
uint8_t result = 0xff;
switch (offset & 1)
{
case 0: // status port
result = read_status();
break;
case 1: // "inhibit" according to datasheet
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ym3812::write_address(uint8_t data)
{
// YM3812 doesn't expose a busy signal, but it does indicate that
// address writes should be no faster than every 12 clocks
m_fm.intf().ymfm_set_busy_end(12 * m_fm.clock_prescale());
// just set the address
m_address = data;
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym3812::write_data(uint8_t data)
{
// YM3812 doesn't expose a busy signal, but it does indicate that
// data writes should be no faster than every 84 clocks
m_fm.intf().ymfm_set_busy_end(84 * m_fm.clock_prescale());
// write to FM
m_fm.write(m_address, data);
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym3812::write(uint32_t offset, uint8_t data)
{
switch (offset & 1)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
}
}
//-------------------------------------------------
// generate - generate samples of sound
//-------------------------------------------------
void ym3812::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// update the FM content; mixing details for YM3812 need verification
m_fm.output(output->clear(), 1, 32767, fm_engine::ALL_CHANNELS);
// YM3812 uses an external DAC (YM3014) with mantissa/exponent format
// convert to 10.3 floating point value and back to simulate truncation
output->roundtrip_fp();
}
}
//*********************************************************
// YMF262
//*********************************************************
//-------------------------------------------------
// ymf262 - constructor
//-------------------------------------------------
ymf262::ymf262(ymfm_interface &intf) :
m_address(0),
m_fm(intf)
{
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ymf262::reset()
{
// reset the engines
m_fm.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ymf262::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
m_fm.save_restore(state);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ymf262::read_status()
{
return m_fm.status();
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ymf262::read(uint32_t offset)
{
uint8_t result = 0xff;
switch (offset & 3)
{
case 0: // status port
result = read_status();
break;
case 1:
case 2:
case 3:
debug::log_unexpected_read_write("Unexpected read from YMF262 offset %d\n", offset & 3);
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ymf262::write_address(uint8_t data)
{
// YMF262 doesn't expose a busy signal, but it does indicate that
// address writes should be no faster than every 32 clocks
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
// just set the address
m_address = data;
}
//-------------------------------------------------
// write_data - handle a write to the data
// register
//-------------------------------------------------
void ymf262::write_data(uint8_t data)
{
// YMF262 doesn't expose a busy signal, but it does indicate that
// data writes should be no faster than every 32 clocks
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
// write to FM
m_fm.write(m_address, data);
}
//-------------------------------------------------
// write_address_hi - handle a write to the upper
// address register
//-------------------------------------------------
void ymf262::write_address_hi(uint8_t data)
{
// YMF262 doesn't expose a busy signal, but it does indicate that
// address writes should be no faster than every 32 clocks
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
// just set the address
m_address = data | 0x100;
// tests reveal that in compatibility mode, upper bit is masked
// except for register 0x105
if (m_fm.regs().newflag() == 0 && m_address != 0x105)
m_address &= 0xff;
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ymf262::write(uint32_t offset, uint8_t data)
{
switch (offset & 3)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
case 2: // address port
write_address_hi(data);
break;
case 3: // data port
write_data(data);
break;
}
}
//-------------------------------------------------
// generate - generate samples of sound
//-------------------------------------------------
void ymf262::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// update the FM content; mixing details for YMF262 need verification
m_fm.output(output->clear(), 0, 32767, fm_engine::ALL_CHANNELS);
// YMF262 output is 16-bit offset serial via YAC512 DAC
output->clamp16();
}
}
//*********************************************************
// YMF289B
//*********************************************************
// YMF289B is a YMF262 with the following changes:
// * "Power down" mode added
// * Bulk register clear added
// * Busy flag added to the status register
// * Shorter busy times
// * All registers can be read
// * Only 2 outputs exposed
//-------------------------------------------------
// ymf289b - constructor
//-------------------------------------------------
ymf289b::ymf289b(ymfm_interface &intf) :
m_address(0),
m_fm(intf)
{
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ymf289b::reset()
{
// reset the engines
m_fm.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ymf289b::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
m_fm.save_restore(state);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ymf289b::read_status()
{
uint8_t result = m_fm.status();
// YMF289B adds a busy flag
if (ymf289b_mode() && m_fm.intf().ymfm_is_busy())
result |= STATUS_BUSY_FLAGS;
return result;
}
//-------------------------------------------------
// read_data - read the data register
//-------------------------------------------------
uint8_t ymf289b::read_data()
{
uint8_t result = 0xff;
// YMF289B can read register data back
if (ymf289b_mode())
result = m_fm.regs().read(m_address);
return result;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ymf289b::read(uint32_t offset)
{
uint8_t result = 0xff;
switch (offset & 3)
{
case 0: // status port
result = read_status();
break;
case 1: // data port
result = read_data();
break;
case 2:
case 3:
debug::log_unexpected_read_write("Unexpected read from YMF289B offset %d\n", offset & 3);
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ymf289b::write_address(uint8_t data)
{
m_address = data;
// count busy time
m_fm.intf().ymfm_set_busy_end(56);
}
//-------------------------------------------------
// write_data - handle a write to the data
// register
//-------------------------------------------------
void ymf289b::write_data(uint8_t data)
{
// write to FM
m_fm.write(m_address, data);
// writes to 0x108 with the CLR flag set clear the registers
if (m_address == 0x108 && bitfield(data, 2) != 0)
m_fm.regs().reset();
// count busy time
m_fm.intf().ymfm_set_busy_end(56);
}
//-------------------------------------------------
// write_address_hi - handle a write to the upper
// address register
//-------------------------------------------------
void ymf289b::write_address_hi(uint8_t data)
{
// just set the address
m_address = data | 0x100;
// tests reveal that in compatibility mode, upper bit is masked
// except for register 0x105
if (m_fm.regs().newflag() == 0 && m_address != 0x105)
m_address &= 0xff;
// count busy time
m_fm.intf().ymfm_set_busy_end(56);
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ymf289b::write(uint32_t offset, uint8_t data)
{
switch (offset & 3)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
case 2: // address port
write_address_hi(data);
break;
case 3: // data port
write_data(data);
break;
}
}
//-------------------------------------------------
// generate - generate samples of sound
//-------------------------------------------------
void ymf289b::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// update the FM content; mixing details for YMF262 need verification
fm_engine::output_data full;
m_fm.output(full.clear(), 0, 32767, fm_engine::ALL_CHANNELS);
// YMF278B output is 16-bit offset serial via YAC512 DAC, but
// only 2 of the 4 outputs are exposed
output->data[0] = full.data[0];
output->data[1] = full.data[1];
output->clamp16();
}
}
//*********************************************************
// YMF278B
//*********************************************************
//-------------------------------------------------
// ymf278b - constructor
//-------------------------------------------------
ymf278b::ymf278b(ymfm_interface &intf) :
m_address(0),
m_fm_pos(0),
m_load_remaining(0),
m_next_status_id(false),
m_fm(intf),
m_pcm(intf)
{
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ymf278b::reset()
{
// reset the engines
m_fm.reset();
m_pcm.reset();
// next status read will return ID
m_next_status_id = true;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ymf278b::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
state.save_restore(m_fm_pos);
state.save_restore(m_load_remaining);
state.save_restore(m_next_status_id);
m_fm.save_restore(state);
m_pcm.save_restore(state);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ymf278b::read_status()
{
uint8_t result;
// first status read after initialization returns a chip ID, which
// varies based on the "new" flags, indicating the mode
if (m_next_status_id)
{
if (m_fm.regs().new2flag())
result = 0x02;
else if (m_fm.regs().newflag())
result = 0x00;
else
result = 0x06;
m_next_status_id = false;
}
else
{
result = m_fm.status();
if (m_fm.intf().ymfm_is_busy())
result |= STATUS_BUSY;
if (m_load_remaining != 0)
result |= STATUS_LD;
// if new2 flag is not set, we're in OPL2 or OPL3 mode
if (!m_fm.regs().new2flag())
result &= ~(STATUS_BUSY | STATUS_LD);
}
return result;
}
//-------------------------------------------------
// write_data_pcm - handle a write to the PCM data
// register
//-------------------------------------------------
uint8_t ymf278b::read_data_pcm()
{
// read from PCM
if (bitfield(m_address, 9) != 0)
{
uint8_t result = m_pcm.read(m_address & 0xff);
if ((m_address & 0xff) == 0x02)
result |= 0x20;
return result;
}
return 0;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ymf278b::read(uint32_t offset)
{
uint8_t result = 0xff;
switch (offset & 7)
{
case 0: // status port
result = read_status();
break;
case 5: // PCM data port
result = read_data_pcm();
break;
default:
debug::log_unexpected_read_write("Unexpected read from ymf278b offset %d\n", offset & 3);
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ymf278b::write_address(uint8_t data)
{
// just set the address
m_address = data;
}
//-------------------------------------------------
// write_data - handle a write to the data
// register
//-------------------------------------------------
void ymf278b::write_data(uint8_t data)
{
// write to FM
if (bitfield(m_address, 9) == 0)
{
uint8_t old = m_fm.regs().new2flag();
m_fm.write(m_address, data);
// changing NEW2 from 0->1 causes the next status read to
// return the chip ID
if (old == 0 && m_fm.regs().new2flag() != 0)
m_next_status_id = true;
}
// BUSY goes for 56 clocks on FM writes
m_fm.intf().ymfm_set_busy_end(56);
}
//-------------------------------------------------
// write_address_hi - handle a write to the upper
// address register
//-------------------------------------------------
void ymf278b::write_address_hi(uint8_t data)
{
// just set the address
m_address = data | 0x100;
// YMF262, in compatibility mode, treats the upper bit as masked
// except for register 0x105; assuming YMF278B works the same way?
if (m_fm.regs().newflag() == 0 && m_address != 0x105)
m_address &= 0xff;
}
//-------------------------------------------------
// write_address_pcm - handle a write to the upper
// address register
//-------------------------------------------------
void ymf278b::write_address_pcm(uint8_t data)
{
// just set the address
m_address = data | 0x200;
}
//-------------------------------------------------
// write_data_pcm - handle a write to the PCM data
// register
//-------------------------------------------------
void ymf278b::write_data_pcm(uint8_t data)
{
// ignore data writes if new2 is not yet set
if (m_fm.regs().new2flag() == 0)
return;
// write to FM
if (bitfield(m_address, 9) != 0)
{
uint8_t addr = m_address & 0xff;
m_pcm.write(addr, data);
// writes to the waveform number cause loads to happen for "about 300usec"
// which is ~13 samples at the nominal output frequency of 44.1kHz
if (addr >= 0x08 && addr <= 0x1f)
m_load_remaining = 13;
}
// BUSY goes for 88 clocks on PCM writes
m_fm.intf().ymfm_set_busy_end(88);
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ymf278b::write(uint32_t offset, uint8_t data)
{
switch (offset & 7)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
case 2: // address port
write_address_hi(data);
break;
case 3: // data port
write_data(data);
break;
case 4: // PCM address port
write_address_pcm(data);
break;
case 5: // PCM address port
write_data_pcm(data);
break;
default:
debug::log_unexpected_read_write("Unexpected write to ymf278b offset %d\n", offset & 7);
break;
}
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void ymf278b::generate(output_data *output, uint32_t numsamples)
{
static const int16_t s_mix_scale[8] = { 0x7fa, 0x5a4, 0x3fd, 0x2d2, 0x1fe, 0x169, 0xff, 0 };
int32_t const pcm_l = s_mix_scale[m_pcm.regs().mix_pcm_l()];
int32_t const pcm_r = s_mix_scale[m_pcm.regs().mix_pcm_r()];
int32_t const fm_l = s_mix_scale[m_pcm.regs().mix_fm_l()];
int32_t const fm_r = s_mix_scale[m_pcm.regs().mix_fm_r()];
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm_pos += FM_EXTRA_SAMPLE_STEP;
if (m_fm_pos >= FM_EXTRA_SAMPLE_THRESH)
{
m_fm.clock(fm_engine::ALL_CHANNELS);
m_fm_pos -= FM_EXTRA_SAMPLE_THRESH;
}
m_fm.clock(fm_engine::ALL_CHANNELS);
m_pcm.clock(pcm_engine::ALL_CHANNELS);
// update the FM content; mixing details for YMF278B need verification
fm_engine::output_data fmout;
m_fm.output(fmout.clear(), 0, 32767, fm_engine::ALL_CHANNELS);
// update the PCM content
pcm_engine::output_data pcmout;
m_pcm.output(pcmout.clear(), pcm_engine::ALL_CHANNELS);
// DO0 output: FM channels 2+3 only
output->data[0] = fmout.data[2];
output->data[1] = fmout.data[3];
// DO1 output: wavetable channels 2+3 only
output->data[2] = pcmout.data[2];
output->data[3] = pcmout.data[3];
// DO2 output: mixed FM channels 0+1 and wavetable channels 0+1
output->data[4] = (fmout.data[0] * fm_l + pcmout.data[0] * pcm_l) >> 11;
output->data[5] = (fmout.data[1] * fm_r + pcmout.data[1] * pcm_r) >> 11;
// YMF278B output is 16-bit 2s complement serial
output->clamp16();
}
// decrement the load waiting count
if (m_load_remaining > 0)
m_load_remaining -= std::min(m_load_remaining, numsamples);
}
//*********************************************************
// OPLL BASE
//*********************************************************
//-------------------------------------------------
// opll_base - constructor
//-------------------------------------------------
opll_base::opll_base(ymfm_interface &intf, uint8_t const *instrument_data) :
m_address(0),
m_fm(intf)
{
m_fm.regs().set_instrument_data(instrument_data);
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void opll_base::reset()
{
// reset the engines
m_fm.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void opll_base::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
m_fm.save_restore(state);
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void opll_base::write_address(uint8_t data)
{
// OPLL doesn't expose a busy signal, but datasheets are pretty consistent
// in indicating that address writes should be no faster than every 12 clocks
m_fm.intf().ymfm_set_busy_end(12);
// just set the address
m_address = data;
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void opll_base::write_data(uint8_t data)
{
// OPLL doesn't expose a busy signal, but datasheets are pretty consistent
// in indicating that address writes should be no faster than every 84 clocks
m_fm.intf().ymfm_set_busy_end(84);
// write to FM
m_fm.write(m_address, data);
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void opll_base::write(uint32_t offset, uint8_t data)
{
switch (offset & 1)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
}
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void opll_base::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// update the FM content; OPLL has a built-in 9-bit DAC
m_fm.output(output->clear(), 5, 256, fm_engine::ALL_CHANNELS);
// final output is multiplexed; we don't simulate that here except
// to average over everything
output->data[0] = (output->data[0] * 128) / 9;
output->data[1] = (output->data[1] * 128) / 9;
}
}
//*********************************************************
// YM2413
//*********************************************************
//-------------------------------------------------
// ym2413 - constructor
//-------------------------------------------------
ym2413::ym2413(ymfm_interface &intf, uint8_t const *instrument_data) :
opll_base(intf, (instrument_data != nullptr) ? instrument_data : s_default_instruments)
{
};
uint8_t const ym2413::s_default_instruments[] =
{
//April 2015 David Viens, tweaked May 19-21th 2015 Hubert Lamontagne
0x71, 0x61, 0x1E, 0x17, 0xEF, 0x7F, 0x00, 0x17, //Violin
0x13, 0x41, 0x1A, 0x0D, 0xF8, 0xF7, 0x23, 0x13, //Guitar
0x13, 0x01, 0x99, 0x00, 0xF2, 0xC4, 0x11, 0x23, //Piano
0x31, 0x61, 0x0E, 0x07, 0x98, 0x64, 0x70, 0x27, //Flute
0x22, 0x21, 0x1E, 0x06, 0xBF, 0x76, 0x00, 0x28, //Clarinet
0x31, 0x22, 0x16, 0x05, 0xE0, 0x71, 0x0F, 0x18, //Oboe
0x21, 0x61, 0x1D, 0x07, 0x82, 0x8F, 0x10, 0x07, //Trumpet
0x23, 0x21, 0x2D, 0x14, 0xFF, 0x7F, 0x00, 0x07, //Organ
0x41, 0x61, 0x1B, 0x06, 0x64, 0x65, 0x10, 0x17, //Horn
0x61, 0x61, 0x0B, 0x18, 0x85, 0xFF, 0x81, 0x07, //Synthesizer
0x13, 0x01, 0x83, 0x11, 0xFA, 0xE4, 0x10, 0x04, //Harpsichord
0x17, 0x81, 0x23, 0x07, 0xF8, 0xF8, 0x22, 0x12, //Vibraphone
0x61, 0x50, 0x0C, 0x05, 0xF2, 0xF5, 0x29, 0x42, //Synthesizer Bass
0x01, 0x01, 0x54, 0x03, 0xC3, 0x92, 0x03, 0x02, //Acoustic Bass
0x41, 0x41, 0x89, 0x03, 0xF1, 0xE5, 0x11, 0x13, //Electric Guitar
0x01, 0x01, 0x18, 0x0F, 0xDF, 0xF8, 0x6A, 0x6D, //rhythm 1
0x01, 0x01, 0x00, 0x00, 0xC8, 0xD8, 0xA7, 0x48, //rhythm 2
0x05, 0x01, 0x00, 0x00, 0xF8, 0xAA, 0x59, 0x55 //rhythm 3
};
//*********************************************************
// YM2423
//*********************************************************
//-------------------------------------------------
// ym2423 - constructor
//-------------------------------------------------
ym2423::ym2423(ymfm_interface &intf, uint8_t const *instrument_data) :
opll_base(intf, (instrument_data != nullptr) ? instrument_data : s_default_instruments)
{
};
uint8_t const ym2423::s_default_instruments[] =
{
// May 4-6 2016 Hubert Lamontagne
// Doesn't seem to have any diff between opllx-x and opllx-y
// Drums seem identical to regular opll
0x61, 0x61, 0x1B, 0x07, 0x94, 0x5F, 0x10, 0x06, //1 Strings Saw wave with vibrato Violin
0x93, 0xB1, 0x51, 0x04, 0xF3, 0xF2, 0x70, 0xFB, //2 Guitar Jazz GuitarPiano
0x41, 0x21, 0x11, 0x85, 0xF2, 0xF2, 0x70, 0x75, //3 Electric Guitar Same as OPLL No.15 Synth
0x93, 0xB2, 0x28, 0x07, 0xF3, 0xF2, 0x70, 0xB4, //4 Electric Piano 2 Slow attack, tremoloDing-a-ling
0x72, 0x31, 0x97, 0x05, 0x51, 0x6F, 0x60, 0x09, //5 Flute Same as OPLL No.4Clarinet
0x13, 0x30, 0x18, 0x06, 0xF7, 0xF4, 0x50, 0x85, //6 Marimba Also be used as steel drumXyophone
0x51, 0x31, 0x1C, 0x07, 0x51, 0x71, 0x20, 0x26, //7 Trumpet Same as OPLL No.7Trumpet
0x41, 0xF4, 0x1B, 0x07, 0x74, 0x34, 0x00, 0x06, //8 Harmonica Harmonica synth
0x50, 0x30, 0x4D, 0x03, 0x42, 0x65, 0x20, 0x06, //9 Tuba Tuba
0x40, 0x20, 0x10, 0x85, 0xF3, 0xF5, 0x20, 0x04, //10 Synth Brass 2 Synth sweep
0x61, 0x61, 0x1B, 0x07, 0xC5, 0x96, 0xF3, 0xF6, //11 Short Saw Saw wave with short envelopeSynth hit
0xF9, 0xF1, 0xDC, 0x00, 0xF5, 0xF3, 0x77, 0xF2, //12 Vibraphone Bright vibraphoneVibes
0x60, 0xA2, 0x91, 0x03, 0x94, 0xC1, 0xF7, 0xF7, //13 Electric Guitar 2 Clean guitar with feedbackHarmonic bass
0x30, 0x30, 0x17, 0x06, 0xF3, 0xF1, 0xB7, 0xFC, //14 Synth Bass 2Snappy bass
0x31, 0x36, 0x0D, 0x05, 0xF2, 0xF4, 0x27, 0x9C, //15 Sitar Also be used as ShamisenBanjo
0x01, 0x01, 0x18, 0x0F, 0xDF, 0xF8, 0x6A, 0x6D, //rhythm 1
0x01, 0x01, 0x00, 0x00, 0xC8, 0xD8, 0xA7, 0x48, //rhythm 2
0x05, 0x01, 0x00, 0x00, 0xF8, 0xAA, 0x59, 0x55 //rhythm 3
};
//*********************************************************
// YMF281
//*********************************************************
//-------------------------------------------------
// ymf281 - constructor
//-------------------------------------------------
ymf281::ymf281(ymfm_interface &intf, uint8_t const *instrument_data) :
opll_base(intf, (instrument_data != nullptr) ? instrument_data : s_default_instruments)
{
};
uint8_t const ymf281::s_default_instruments[] =
{
// May 14th 2015 Hubert Lamontagne
0x72, 0x21, 0x1A, 0x07, 0xF6, 0x64, 0x01, 0x16, // Clarinet ~~ Electric String Square wave with vibrato
0x00, 0x10, 0x45, 0x00, 0xF6, 0x83, 0x73, 0x63, // Synth Bass ~~ Bow wow Triangular wave
0x13, 0x01, 0x96, 0x00, 0xF1, 0xF4, 0x31, 0x23, // Piano ~~ Electric Guitar Despite of its name, same as Piano of YM2413.
0x71, 0x21, 0x0B, 0x0F, 0xF9, 0x64, 0x70, 0x17, // Flute ~~ Organ Sine wave
0x02, 0x21, 0x1E, 0x06, 0xF9, 0x76, 0x00, 0x28, // Square Wave ~~ Clarinet Same as ones of YM2413.
0x00, 0x61, 0x82, 0x0E, 0xF9, 0x61, 0x20, 0x27, // Space Oboe ~~ Saxophone Saw wave with vibrato
0x21, 0x61, 0x1B, 0x07, 0x84, 0x8F, 0x10, 0x07, // Trumpet ~~ Trumpet Same as ones of YM2413.
0x37, 0x32, 0xCA, 0x02, 0x66, 0x64, 0x47, 0x29, // Wow Bell ~~ Street Organ Calliope
0x41, 0x41, 0x07, 0x03, 0xF5, 0x70, 0x51, 0xF5, // Electric Guitar ~~ Synth Brass Same as Synthesizer of YM2413.
0x36, 0x01, 0x5E, 0x07, 0xF2, 0xF3, 0xF7, 0xF7, // Vibes ~~ Electric Piano Simulate of Rhodes Piano
0x00, 0x00, 0x18, 0x06, 0xC5, 0xF3, 0x20, 0xF2, // Bass ~~ Bass Electric bass
0x17, 0x81, 0x25, 0x07, 0xF7, 0xF3, 0x21, 0xF7, // Vibraphone ~~ Vibraphone Same as ones of YM2413.
0x35, 0x64, 0x00, 0x00, 0xFF, 0xF3, 0x77, 0xF5, // Vibrato Bell ~~ Chime Bell
0x11, 0x31, 0x00, 0x07, 0xDD, 0xF3, 0xFF, 0xFB, // Click Sine ~~ Tom Tom II Tom
0x3A, 0x21, 0x00, 0x07, 0x95, 0x84, 0x0F, 0xF5, // Noise and Tone ~~ Noise for S.E.
0x01, 0x01, 0x18, 0x0F, 0xDF, 0xF8, 0x6A, 0x6D, //rhythm 1
0x01, 0x01, 0x00, 0x00, 0xC8, 0xD8, 0xA7, 0x48, //rhythm 2
0x05, 0x01, 0x00, 0x00, 0xF8, 0xAA, 0x59, 0x55 //rhythm 3
};
//*********************************************************
// DS1001
//*********************************************************
//-------------------------------------------------
// ds1001 - constructor
//-------------------------------------------------
ds1001::ds1001(ymfm_interface &intf, uint8_t const *instrument_data) :
opll_base(intf, (instrument_data != nullptr) ? instrument_data : s_default_instruments)
{
};
uint8_t const ds1001::s_default_instruments[] =
{
// May 15th 2015 Hubert Lamontagne & David Viens
0x03, 0x21, 0x05, 0x06, 0xC8, 0x81, 0x42, 0x27, // Buzzy Bell
0x13, 0x41, 0x14, 0x0D, 0xF8, 0xF7, 0x23, 0x12, // Guitar
0x31, 0x11, 0x08, 0x08, 0xFA, 0xC2, 0x28, 0x22, // Wurly
0x31, 0x61, 0x0C, 0x07, 0xF8, 0x64, 0x60, 0x27, // Flute
0x22, 0x21, 0x1E, 0x06, 0xFF, 0x76, 0x00, 0x28, // Clarinet
0x02, 0x01, 0x05, 0x00, 0xAC, 0xF2, 0x03, 0x02, // Synth
0x21, 0x61, 0x1D, 0x07, 0x82, 0x8F, 0x10, 0x07, // Trumpet
0x23, 0x21, 0x22, 0x17, 0xFF, 0x73, 0x00, 0x17, // Organ
0x15, 0x11, 0x25, 0x00, 0x41, 0x71, 0x00, 0xF1, // Bells
0x95, 0x01, 0x10, 0x0F, 0xB8, 0xAA, 0x50, 0x02, // Vibes
0x17, 0xC1, 0x5E, 0x07, 0xFA, 0xF8, 0x22, 0x12, // Vibraphone
0x71, 0x23, 0x11, 0x06, 0x65, 0x74, 0x10, 0x16, // Tutti
0x01, 0x02, 0xD3, 0x05, 0xF3, 0x92, 0x83, 0xF2, // Fretless
0x61, 0x63, 0x0C, 0x00, 0xA4, 0xFF, 0x30, 0x06, // Synth Bass
0x21, 0x62, 0x0D, 0x00, 0xA1, 0xFF, 0x50, 0x08, // Sweep
0x01, 0x01, 0x18, 0x0F, 0xDF, 0xF8, 0x6A, 0x6D, //rhythm 1
0x01, 0x01, 0x00, 0x00, 0xC8, 0xD8, 0xA7, 0x48, //rhythm 2
0x05, 0x01, 0x00, 0x00, 0xF8, 0xAA, 0x59, 0x55 //rhythm 3
};
//*********************************************************
// EXPLICIT INSTANTIATION
//*********************************************************
template class opl_registers_base<4>;
template class fm_engine_base<opl_registers_base<4>>;
}
``` | /content/code_sandbox/src/sound/ymfm/ymfm_opl.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 19,232 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_FM_H
#define YMFM_FM_H
#pragma once
#define YMFM_DEBUG_LOG_WAVFILES (0)
namespace ymfm
{
//*********************************************************
// GLOBAL ENUMERATORS
//*********************************************************
// three different keyon sources; actual keyon is an OR over all of these
enum keyon_type : uint32_t
{
KEYON_NORMAL = 0,
KEYON_RHYTHM = 1,
KEYON_CSM = 2
};
//*********************************************************
// CORE IMPLEMENTATION
//*********************************************************
// ======================> opdata_cache
// this class holds data that is computed once at the start of clocking
// and remains static during subsequent sound generation
struct opdata_cache
{
// set phase_step to this value to recalculate it each sample; needed
// in the case of PM LFO changes
static constexpr uint32_t PHASE_STEP_DYNAMIC = 1;
uint16_t const *waveform; // base of sine table
uint32_t phase_step; // phase step, or PHASE_STEP_DYNAMIC if PM is active
uint32_t total_level; // total level * 8 + KSL
uint32_t block_freq; // raw block frequency value (used to compute phase_step)
int32_t detune; // detuning value (used to compute phase_step)
uint32_t multiple; // multiple value (x.1, used to compute phase_step)
uint32_t eg_sustain; // sustain level, shifted up to envelope values
uint8_t eg_rate[EG_STATES]; // envelope rate, including KSR
uint8_t eg_shift = 0; // envelope shift amount
};
// ======================> fm_registers_base
// base class for family-specific register classes; this provides a few
// constants, common defaults, and helpers, but mostly each derived class is
// responsible for defining all commonly-called methods
class fm_registers_base
{
public:
// this value is returned from the write() function for rhythm channels
static constexpr uint32_t RHYTHM_CHANNEL = 0xff;
// this is the size of a full sin waveform
static constexpr uint32_t WAVEFORM_LENGTH = 0x400;
//
// the following constants need to be defined per family:
// uint32_t OUTPUTS: The number of outputs exposed (1-4)
// uint32_t CHANNELS: The number of channels on the chip
// uint32_t ALL_CHANNELS: A bitmask of all channels
// uint32_t OPERATORS: The number of operators on the chip
// uint32_t WAVEFORMS: The number of waveforms offered
// uint32_t REGISTERS: The number of 8-bit registers allocated
// uint32_t DEFAULT_PRESCALE: The starting clock prescale
// uint32_t EG_CLOCK_DIVIDER: The clock divider of the envelope generator
// uint32_t CSM_TRIGGER_MASK: Mask of channels to trigger in CSM mode
// uint32_t REG_MODE: The address of the "mode" register controlling timers
// uint8_t STATUS_TIMERA: Status bit to set when timer A fires
// uint8_t STATUS_TIMERB: Status bit to set when tiemr B fires
// uint8_t STATUS_BUSY: Status bit to set when the chip is busy
// uint8_t STATUS_IRQ: Status bit to set when an IRQ is signalled
//
// the following constants are uncommon:
// bool DYNAMIC_OPS: True if ops/channel can be changed at runtime (OPL3+)
// bool EG_HAS_DEPRESS: True if the chip has a DP ("depress"?) envelope stage (OPLL)
// bool EG_HAS_REVERB: True if the chip has a faux reverb envelope stage (OPQ/OPZ)
// bool EG_HAS_SSG: True if the chip has SSG envelope support (OPN)
// bool MODULATOR_DELAY: True if the modulator is delayed by 1 sample (OPL pre-OPL3)
//
static constexpr bool DYNAMIC_OPS = false;
static constexpr bool EG_HAS_DEPRESS = false;
static constexpr bool EG_HAS_REVERB = false;
static constexpr bool EG_HAS_SSG = false;
static constexpr bool MODULATOR_DELAY = false;
// system-wide register defaults
uint32_t status_mask() const { return 0; } // OPL only
uint32_t irq_reset() const { return 0; } // OPL only
uint32_t noise_enable() const { return 0; } // OPM only
uint32_t rhythm_enable() const { return 0; } // OPL only
// per-operator register defaults
uint32_t op_ssg_eg_enable(uint32_t opoffs) const { return 0; } // OPN(A) only
uint32_t op_ssg_eg_mode(uint32_t opoffs) const { return 0; } // OPN(A) only
protected:
// helper to encode four operator numbers into a 32-bit value in the
// operator maps for each register class
static constexpr uint32_t operator_list(uint8_t o1 = 0xff, uint8_t o2 = 0xff, uint8_t o3 = 0xff, uint8_t o4 = 0xff)
{
return o1 | (o2 << 8) | (o3 << 16) | (o4 << 24);
}
// helper to apply KSR to the raw ADSR rate, ignoring ksr if the
// raw value is 0, and clamping to 63
static constexpr uint32_t effective_rate(uint32_t rawrate, uint32_t ksr)
{
return (rawrate == 0) ? 0 : std::min<uint32_t>(rawrate + ksr, 63);
}
};
//*********************************************************
// CORE ENGINE CLASSES
//*********************************************************
// forward declarations
template<class RegisterType> class fm_engine_base;
// ======================> fm_operator
// fm_operator represents an FM operator (or "slot" in FM parlance), which
// produces an output sine wave modulated by an envelope
template<class RegisterType>
class fm_operator
{
// "quiet" value, used to optimize when we can skip doing work
static constexpr uint32_t EG_QUIET = 0x380;
public:
// constructor
fm_operator(fm_engine_base<RegisterType> &owner, uint32_t opoffs);
// save/restore
void save_restore(ymfm_saved_state &state);
// reset the operator state
void reset();
// return the operator/channel offset
uint32_t opoffs() const { return m_opoffs; }
uint32_t choffs() const { return m_choffs; }
// set the current channel
void set_choffs(uint32_t choffs) { m_choffs = choffs; }
// prepare prior to clocking
bool prepare();
// master clocking function
void clock(uint32_t env_counter, int32_t lfo_raw_pm);
// return the current phase value
uint32_t phase() const { return m_phase >> 10; }
// compute operator volume
int32_t compute_volume(uint32_t phase, uint32_t am_offset) const;
// compute volume for the OPM noise channel
int32_t compute_noise_volume(uint32_t am_offset) const;
// key state control
void keyonoff(uint32_t on, keyon_type type);
// return a reference to our registers
RegisterType ®s() const { return m_regs; }
// simple getters for debugging
envelope_state debug_eg_state() const { return m_env_state; }
uint16_t debug_eg_attenuation() const { return m_env_attenuation; }
uint8_t debug_ssg_inverted() const { return m_ssg_inverted; }
opdata_cache &debug_cache() { return m_cache; }
private:
// start the attack phase
void start_attack(bool is_restart = false);
// start the release phase
void start_release();
// clock phases
void clock_keystate(uint32_t keystate);
void clock_ssg_eg_state();
void clock_envelope(uint32_t env_counter);
void clock_phase(int32_t lfo_raw_pm);
// return effective attenuation of the envelope
uint32_t envelope_attenuation(uint32_t am_offset) const;
// internal state
uint32_t m_choffs; // channel offset in registers
uint32_t m_opoffs; // operator offset in registers
uint32_t m_phase; // current phase value (10.10 format)
uint16_t m_env_attenuation; // computed envelope attenuation (4.6 format)
envelope_state m_env_state; // current envelope state
uint8_t m_ssg_inverted; // non-zero if the output should be inverted (bit 0)
uint8_t m_key_state; // current key state: on or off (bit 0)
uint8_t m_keyon_live; // live key on state (bit 0 = direct, bit 1 = rhythm, bit 2 = CSM)
opdata_cache m_cache; // cached values for performance
RegisterType &m_regs; // direct reference to registers
fm_engine_base<RegisterType> &m_owner; // reference to the owning engine
};
// ======================> fm_channel
// fm_channel represents an FM channel which combines the output of 2 or 4
// operators into a final result
template<class RegisterType>
class fm_channel
{
using output_data = ymfm_output<RegisterType::OUTPUTS>;
public:
// constructor
fm_channel(fm_engine_base<RegisterType> &owner, uint32_t choffs);
// save/restore
void save_restore(ymfm_saved_state &state);
// reset the channel state
void reset();
// return the channel offset
uint32_t choffs() const { return m_choffs; }
// assign operators
void assign(uint32_t index, fm_operator<RegisterType> *op)
{
assert(index < array_size(m_op));
m_op[index] = op;
if (op != nullptr)
op->set_choffs(m_choffs);
}
// signal key on/off to our operators
void keyonoff(uint32_t states, keyon_type type, uint32_t chnum);
// prepare prior to clocking
bool prepare();
// master clocking function
void clock(uint32_t env_counter, int32_t lfo_raw_pm);
// specific 2-operator and 4-operator output handlers
void output_2op(output_data &output, uint32_t rshift, int32_t clipmax) const;
void output_4op(output_data &output, uint32_t rshift, int32_t clipmax) const;
// compute the special OPL rhythm channel outputs
void output_rhythm_ch6(output_data &output, uint32_t rshift, int32_t clipmax) const;
void output_rhythm_ch7(uint32_t phase_select, output_data &output, uint32_t rshift, int32_t clipmax) const;
void output_rhythm_ch8(uint32_t phase_select, output_data &output, uint32_t rshift, int32_t clipmax) const;
// are we a 4-operator channel or a 2-operator one?
bool is4op() const
{
if (RegisterType::DYNAMIC_OPS)
return (m_op[2] != nullptr);
return (RegisterType::OPERATORS / RegisterType::CHANNELS == 4);
}
// return a reference to our registers
RegisterType ®s() const { return m_regs; }
// simple getters for debugging
fm_operator<RegisterType> *debug_operator(uint32_t index) const { return m_op[index]; }
private:
// helper to add values to the outputs based on channel enables
void add_to_output(uint32_t choffs, output_data &output, int32_t value) const
{
// create these constants to appease overzealous compilers checking array
// bounds in unreachable code (looking at you, clang)
constexpr int out0_index = 0;
constexpr int out1_index = 1 % RegisterType::OUTPUTS;
constexpr int out2_index = 2 % RegisterType::OUTPUTS;
constexpr int out3_index = 3 % RegisterType::OUTPUTS;
if (RegisterType::OUTPUTS == 1 || m_regs.ch_output_0(choffs))
output.data[out0_index] += value;
if (RegisterType::OUTPUTS >= 2 && m_regs.ch_output_1(choffs))
output.data[out1_index] += value;
if (RegisterType::OUTPUTS >= 3 && m_regs.ch_output_2(choffs))
output.data[out2_index] += value;
if (RegisterType::OUTPUTS >= 4 && m_regs.ch_output_3(choffs))
output.data[out3_index] += value;
}
// internal state
uint32_t m_choffs; // channel offset in registers
int16_t m_feedback[2]; // feedback memory for operator 1
mutable int16_t m_feedback_in; // next input value for op 1 feedback (set in output)
fm_operator<RegisterType> *m_op[4]; // up to 4 operators
RegisterType &m_regs; // direct reference to registers
fm_engine_base<RegisterType> &m_owner; // reference to the owning engine
};
// ======================> fm_engine_base
// fm_engine_base represents a set of operators and channels which together
// form a Yamaha FM core; chips that implement other engines (ADPCM, wavetable,
// etc) take this output and combine it with the others externally
template<class RegisterType>
class fm_engine_base : public ymfm_engine_callbacks
{
public:
// expose some constants from the registers
static constexpr uint32_t OUTPUTS = RegisterType::OUTPUTS;
static constexpr uint32_t CHANNELS = RegisterType::CHANNELS;
static constexpr uint32_t ALL_CHANNELS = RegisterType::ALL_CHANNELS;
static constexpr uint32_t OPERATORS = RegisterType::OPERATORS;
// also expose status flags for consumers that inject additional bits
static constexpr uint8_t STATUS_TIMERA = RegisterType::STATUS_TIMERA;
static constexpr uint8_t STATUS_TIMERB = RegisterType::STATUS_TIMERB;
static constexpr uint8_t STATUS_BUSY = RegisterType::STATUS_BUSY;
static constexpr uint8_t STATUS_IRQ = RegisterType::STATUS_IRQ;
// expose the correct output class
using output_data = ymfm_output<OUTPUTS>;
// constructor
fm_engine_base(ymfm_interface &intf);
// save/restore
void save_restore(ymfm_saved_state &state);
// reset the overall state
void reset();
// master clocking function
uint32_t clock(uint32_t chanmask);
// compute sum of channel outputs
void output(output_data &output, uint32_t rshift, int32_t clipmax, uint32_t chanmask) const;
// write to the OPN registers
void write(uint16_t regnum, uint8_t data);
// return the current status
uint8_t status() const;
// set/reset bits in the status register, updating the IRQ status
uint8_t set_reset_status(uint8_t set, uint8_t reset)
{
m_status = (m_status | set) & ~(reset | STATUS_BUSY);
m_intf.ymfm_sync_check_interrupts();
return m_status & ~m_regs.status_mask();
}
// set the IRQ mask
void set_irq_mask(uint8_t mask) { m_irq_mask = mask; m_intf.ymfm_sync_check_interrupts(); }
// return the current clock prescale
uint32_t clock_prescale() const { return m_clock_prescale; }
// set prescale factor (2/3/6)
void set_clock_prescale(uint32_t prescale) { m_clock_prescale = prescale; }
// compute sample rate
uint32_t sample_rate(uint32_t baseclock) const
{
#if (YMFM_DEBUG_LOG_WAVFILES)
for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
m_wavfile[chnum].set_samplerate(baseclock / (m_clock_prescale * OPERATORS));
#endif
return baseclock / (m_clock_prescale * OPERATORS);
}
// return the owning device
ymfm_interface &intf() const { return m_intf; }
// return a reference to our registers
RegisterType ®s() { return m_regs; }
// invalidate any caches
void invalidate_caches() { m_modified_channels = RegisterType::ALL_CHANNELS; }
// simple getters for debugging
fm_channel<RegisterType> *debug_channel(uint32_t index) const { return m_channel[index].get(); }
fm_operator<RegisterType> *debug_operator(uint32_t index) const { return m_operator[index].get(); }
public:
// timer callback; called by the interface when a timer fires
virtual void engine_timer_expired(uint32_t tnum) override;
// check interrupts; called by the interface after synchronization
virtual void engine_check_interrupts() override;
// mode register write; called by the interface after synchronization
virtual void engine_mode_write(uint8_t data) override;
protected:
// assign the current set of operators to channels
void assign_operators();
// update the state of the given timer
void update_timer(uint32_t which, uint32_t enable, int32_t delta_clocks);
// internal state
ymfm_interface &m_intf; // reference to the system interface
uint32_t m_env_counter; // envelope counter; low 2 bits are sub-counter
uint8_t m_status; // current status register
uint8_t m_clock_prescale; // prescale factor (2/3/6)
uint8_t m_irq_mask; // mask of which bits signal IRQs
uint8_t m_irq_state; // current IRQ state
uint8_t m_timer_running[2]; // current timer running state
uint8_t m_total_clocks; // low 8 bits of the total number of clocks processed
uint32_t m_active_channels; // mask of active channels (computed by prepare)
uint32_t m_modified_channels; // mask of channels that have been modified
uint32_t m_prepare_count; // counter to do periodic prepare sweeps
RegisterType m_regs; // register accessor
std::unique_ptr<fm_channel<RegisterType>> m_channel[CHANNELS]; // channel pointers
std::unique_ptr<fm_operator<RegisterType>> m_operator[OPERATORS]; // operator pointers
#if (YMFM_DEBUG_LOG_WAVFILES)
mutable ymfm_wavfile<1> m_wavfile[CHANNELS]; // for debugging
#endif
};
}
#endif // YMFM_FM_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm_fm.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 4,399 |
```c++
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ymfm_opz.h"
#include "ymfm_fm.ipp"
#define TEMPORARY_DEBUG_PRINTS (0)
//
// OPZ (aka YM2414)
//
// This chip is not officially documented as far as I know. What I have
// comes from this site:
//
// path_to_url
//
// and from reading the TX81Z operator manual, which describes how a number
// of these new features work.
//
// OPZ appears be bsaically OPM with a bunch of extra features.
//
// For starters, there are two LFO generators. I have presumed that they
// operate identically since identical parameters are offered for each. I
// have also presumed the effects are additive between them. The LFOs on
// the OPZ have an extra "sync" option which apparently causes the LFO to
// reset whenever a key on is received.
//
// At the channel level, there is an additional 8-bit volume control. This
// might work as an addition to total level, or some other way. Completely
// unknown, and unimplemented.
//
// At the operator level, there are a number of extra features. First, there
// are 8 different waveforms to choose from. These are different than the
// waveforms introduced in the OPL2 and later chips.
//
// Second, there is an additional "reverb" stage added to the envelope
// generator, which kicks in when the envelope reaches -18dB. It specifies
// a slower decay rate to produce a sort of faux reverb effect.
//
// The envelope generator also supports a 2-bit shift value, which can be
// used to reduce the effect of the envelope attenuation.
//
// OPZ supports a "fixed frequency" mode for each operator, with a 3-bit
// range and 4-bit frequency value, plus a 1-bit enable. Not sure how that
// works at all, so it's not implemented.
//
// There are also several mystery fields in the operators which I have no
// clue about: "fine" (4 bits), "eg_shift" (2 bits), and "rev" (3 bits).
// eg_shift is some kind of envelope generator effect, but how it works is
// unknown.
//
// Also, according to the site above, the panning controls are changed from
// OPM, with a "mono" bit and only one control bit for the right channel.
// Current implementation is just a guess.
//
namespace ymfm
{
//*********************************************************
// OPZ REGISTERS
//*********************************************************
//-------------------------------------------------
// opz_registers - constructor
//-------------------------------------------------
opz_registers::opz_registers() :
m_lfo_counter{ 0, 0 },
m_noise_lfsr(1),
m_noise_counter(0),
m_noise_state(0),
m_noise_lfo(0),
m_lfo_am{ 0, 0 }
{
// create the waveforms
for (uint32_t index = 0; index < WAVEFORM_LENGTH; index++)
m_waveform[0][index] = abs_sin_attenuation(index) | (bitfield(index, 9) << 15);
// we only have the diagrams to judge from, but suspecting waveform 1 (and
// derived waveforms) are sin^2, based on OPX description of similar wave-
// forms; since our sin table is logarithmic, this ends up just being
// 2*existing value
uint16_t zeroval = m_waveform[0][0];
for (uint32_t index = 0; index < WAVEFORM_LENGTH; index++)
m_waveform[1][index] = std::min<uint16_t>(2 * (m_waveform[0][index] & 0x7fff), zeroval) | (bitfield(index, 9) << 15);
// remaining waveforms are just derivations of the 2 main ones
for (uint32_t index = 0; index < WAVEFORM_LENGTH; index++)
{
m_waveform[2][index] = bitfield(index, 9) ? zeroval : m_waveform[0][index];
m_waveform[3][index] = bitfield(index, 9) ? zeroval : m_waveform[1][index];
m_waveform[4][index] = bitfield(index, 9) ? zeroval : m_waveform[0][index * 2];
m_waveform[5][index] = bitfield(index, 9) ? zeroval : m_waveform[1][index * 2];
m_waveform[6][index] = bitfield(index, 9) ? zeroval : m_waveform[0][(index * 2) & 0x1ff];
m_waveform[7][index] = bitfield(index, 9) ? zeroval : m_waveform[1][(index * 2) & 0x1ff];
}
// create the LFO waveforms; AM in the low 8 bits, PM in the upper 8
// waveforms are adjusted to match the pictures in the application manual
for (uint32_t index = 0; index < LFO_WAVEFORM_LENGTH; index++)
{
// waveform 0 is a sawtooth
uint8_t am = index ^ 0xff;
int8_t pm = int8_t(index);
m_lfo_waveform[0][index] = am | (pm << 8);
// waveform 1 is a square wave
am = bitfield(index, 7) ? 0 : 0xff;
pm = int8_t(am ^ 0x80);
m_lfo_waveform[1][index] = am | (pm << 8);
// waveform 2 is a triangle wave
am = bitfield(index, 7) ? (index << 1) : ((index ^ 0xff) << 1);
pm = int8_t(bitfield(index, 6) ? am : ~am);
m_lfo_waveform[2][index] = am | (pm << 8);
// waveform 3 is noise; it is filled in dynamically
}
}
//-------------------------------------------------
// reset - reset to initial state
//-------------------------------------------------
void opz_registers::reset()
{
std::fill_n(&m_regdata[0], REGISTERS, 0);
// enable output on both channels by default
m_regdata[0x30] = m_regdata[0x31] = m_regdata[0x32] = m_regdata[0x33] = 0x01;
m_regdata[0x34] = m_regdata[0x35] = m_regdata[0x36] = m_regdata[0x37] = 0x01;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void opz_registers::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_lfo_counter);
state.save_restore(m_lfo_am);
state.save_restore(m_noise_lfsr);
state.save_restore(m_noise_counter);
state.save_restore(m_noise_state);
state.save_restore(m_noise_lfo);
state.save_restore(m_regdata);
state.save_restore(m_phase_substep);
}
//-------------------------------------------------
// operator_map - return an array of operator
// indices for each channel; for OPZ this is fixed
//-------------------------------------------------
void opz_registers::operator_map(operator_mapping &dest) const
{
// Note that the channel index order is 0,2,1,3, so we bitswap the index.
//
// This is because the order in the map is:
// carrier 1, carrier 2, modulator 1, modulator 2
//
// But when wiring up the connections, the more natural order is:
// carrier 1, modulator 1, carrier 2, modulator 2
static const operator_mapping s_fixed_map =
{ {
operator_list( 0, 16, 8, 24 ), // Channel 0 operators
operator_list( 1, 17, 9, 25 ), // Channel 1 operators
operator_list( 2, 18, 10, 26 ), // Channel 2 operators
operator_list( 3, 19, 11, 27 ), // Channel 3 operators
operator_list( 4, 20, 12, 28 ), // Channel 4 operators
operator_list( 5, 21, 13, 29 ), // Channel 5 operators
operator_list( 6, 22, 14, 30 ), // Channel 6 operators
operator_list( 7, 23, 15, 31 ), // Channel 7 operators
} };
dest = s_fixed_map;
}
//-------------------------------------------------
// write - handle writes to the register array
//-------------------------------------------------
bool opz_registers::write(uint16_t index, uint8_t data, uint32_t &channel, uint32_t &opmask)
{
assert(index < REGISTERS);
// special mappings:
// 0x16 -> 0x188 if bit 7 is set
// 0x19 -> 0x189 if bit 7 is set
// 0x38..0x3F -> 0x180..0x187 if bit 7 is set
// 0x40..0x5F -> 0x100..0x11F if bit 7 is set
// 0xC0..0xDF -> 0x120..0x13F if bit 5 is set
if (index == 0x17 && bitfield(data, 7) != 0)
m_regdata[0x188] = data;
else if (index == 0x19 && bitfield(data, 7) != 0)
m_regdata[0x189] = data;
else if ((index & 0xf8) == 0x38 && bitfield(data, 7) != 0)
m_regdata[0x180 + (index & 7)] = data;
else if ((index & 0xe0) == 0x40 && bitfield(data, 7) != 0)
m_regdata[0x100 + (index & 0x1f)] = data;
else if ((index & 0xe0) == 0xc0 && bitfield(data, 5) != 0)
m_regdata[0x120 + (index & 0x1f)] = data;
else if (index < 0x100)
m_regdata[index] = data;
// preset writes restore some values from a preset memory; not sure
// how this really works but the TX81Z will overwrite the sustain level/
// release rate register and the envelope shift/reverb rate register to
// dampen sound, then write the preset number to register 8 to restore them
if (index == 0x08)
{
int chan = bitfield(data, 0, 3);
if (TEMPORARY_DEBUG_PRINTS)
printf("Loading preset %d\n", chan);
m_regdata[0xe0 + chan + 0] = m_regdata[0x140 + chan + 0];
m_regdata[0xe0 + chan + 8] = m_regdata[0x140 + chan + 8];
m_regdata[0xe0 + chan + 16] = m_regdata[0x140 + chan + 16];
m_regdata[0xe0 + chan + 24] = m_regdata[0x140 + chan + 24];
m_regdata[0x120 + chan + 0] = m_regdata[0x160 + chan + 0];
m_regdata[0x120 + chan + 8] = m_regdata[0x160 + chan + 8];
m_regdata[0x120 + chan + 16] = m_regdata[0x160 + chan + 16];
m_regdata[0x120 + chan + 24] = m_regdata[0x160 + chan + 24];
}
// store the presets under some unknown condition; the pattern of writes
// when setting a new preset is:
//
// 08 (0-7), 80-9F, A0-BF, C0-DF, C0-DF (alt), 20-27, 40-5F, 40-5F (alt),
// C0-DF (alt -- again?), 38-3F, 1B, 18, E0-FF
//
// So it writes 0-7 to 08 to either reset all presets or to indicate
// that we're going to be loading them. Immediately after all the writes
// above, the very next write will be temporary values to blow away the
// values loaded into E0-FF, so somehow it also knows that anything after
// that point is not part of the preset.
//
// For now, try using the 40-5F (alt) writes as flags that presets are
// being loaded until the E0-FF writes happen.
bool is_setting_preset = (bitfield(m_regdata[0x100 + (index & 0x1f)], 7) != 0);
if (is_setting_preset)
{
if ((index & 0xe0) == 0xe0)
{
m_regdata[0x140 + (index & 0x1f)] = data;
m_regdata[0x100 + (index & 0x1f)] &= 0x7f;
}
else if ((index & 0xe0) == 0xc0 && bitfield(data, 5) != 0)
m_regdata[0x160 + (index & 0x1f)] = data;
}
// handle writes to the key on index
if ((index & 0xf8) == 0x20 && bitfield(index, 0, 3) == bitfield(m_regdata[0x08], 0, 3))
{
channel = bitfield(index, 0, 3);
opmask = ch_key_on(channel) ? 0xf : 0;
// according to the TX81Z manual, the sync option causes the LFOs
// to reset at each note on
if (opmask != 0)
{
if (lfo_sync())
m_lfo_counter[0] = 0;
if (lfo2_sync())
m_lfo_counter[1] = 0;
}
return true;
}
return false;
}
//-------------------------------------------------
// clock_noise_and_lfo - clock the noise and LFO,
// handling clock division, depth, and waveform
// computations
//-------------------------------------------------
int32_t opz_registers::clock_noise_and_lfo()
{
// base noise frequency is measured at 2x 1/2 FM frequency; this
// means each tick counts as two steps against the noise counter
uint32_t freq = noise_frequency();
for (int rep = 0; rep < 2; rep++)
{
// evidence seems to suggest the LFSR is clocked continually and just
// sampled at the noise frequency for output purposes; note that the
// low 8 bits are the most recent 8 bits of history while bits 8-24
// contain the 17 bit LFSR state
m_noise_lfsr <<= 1;
m_noise_lfsr |= bitfield(m_noise_lfsr, 17) ^ bitfield(m_noise_lfsr, 14) ^ 1;
// compare against the frequency and latch when we exceed it
if (m_noise_counter++ >= freq)
{
m_noise_counter = 0;
m_noise_state = bitfield(m_noise_lfsr, 17);
}
}
// treat the rate as a 4.4 floating-point step value with implied
// leading 1; this matches exactly the frequencies in the application
// manual, though it might not be implemented exactly this way on chip
uint32_t rate0 = lfo_rate();
uint32_t rate1 = lfo2_rate();
m_lfo_counter[0] += (0x10 | bitfield(rate0, 0, 4)) << bitfield(rate0, 4, 4);
m_lfo_counter[1] += (0x10 | bitfield(rate1, 0, 4)) << bitfield(rate1, 4, 4);
uint32_t lfo0 = bitfield(m_lfo_counter[0], 22, 8);
uint32_t lfo1 = bitfield(m_lfo_counter[1], 22, 8);
// fill in the noise entry 1 ahead of our current position; this
// ensures the current value remains stable for a full LFO clock
// and effectively latches the running value when the LFO advances
uint32_t lfo_noise = bitfield(m_noise_lfsr, 17, 8);
m_lfo_waveform[3][(lfo0 + 1) & 0xff] = lfo_noise | (lfo_noise << 8);
m_lfo_waveform[3][(lfo1 + 1) & 0xff] = lfo_noise | (lfo_noise << 8);
// fetch the AM/PM values based on the waveform; AM is unsigned and
// encoded in the low 8 bits, while PM signed and encoded in the upper
// 8 bits
int32_t ampm0 = m_lfo_waveform[lfo_waveform()][lfo0];
int32_t ampm1 = m_lfo_waveform[lfo2_waveform()][lfo1];
// apply depth to the AM values and store for later
m_lfo_am[0] = ((ampm0 & 0xff) * lfo_am_depth()) >> 7;
m_lfo_am[1] = ((ampm1 & 0xff) * lfo2_am_depth()) >> 7;
// apply depth to the PM values and return them combined into two
int32_t pm0 = ((ampm0 >> 8) * int32_t(lfo_pm_depth())) >> 7;
int32_t pm1 = ((ampm1 >> 8) * int32_t(lfo2_pm_depth())) >> 7;
return (pm0 & 0xff) | (pm1 << 8);
}
//-------------------------------------------------
// lfo_am_offset - return the AM offset from LFO
// for the given channel
//-------------------------------------------------
uint32_t opz_registers::lfo_am_offset(uint32_t choffs) const
{
// not sure how this works for real, but just adding the two
// AM LFOs together
uint32_t result = 0;
// shift value for AM sensitivity is [*, 0, 1, 2],
// mapping to values of [0, 23.9, 47.8, and 95.6dB]
uint32_t am_sensitivity = ch_lfo_am_sens(choffs);
if (am_sensitivity != 0)
result = m_lfo_am[0] << (am_sensitivity - 1);
// QUESTION: see OPN note below for the dB range mapping; it applies
// here as well
// raw LFO AM value on OPZ is 0-FF, which is already a factor of 2
// larger than the OPN below, putting our staring point at 2x theirs;
// this works out since our minimum is 2x their maximum
uint32_t am_sensitivity2 = ch_lfo2_am_sens(choffs);
if (am_sensitivity2 != 0)
result += m_lfo_am[1] << (am_sensitivity2 - 1);
return result;
}
//-------------------------------------------------
// cache_operator_data - fill the operator cache
// with prefetched data
//-------------------------------------------------
void opz_registers::cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache)
{
// TODO: how does fixed frequency mode work? appears to be enabled by
// op_fix_mode(), and controlled by op_fix_range(), op_fix_frequency()
// TODO: what is op_rev()?
// set up the easy stuff
cache.waveform = &m_waveform[op_waveform(opoffs)][0];
// get frequency from the channel
uint32_t block_freq = cache.block_freq = ch_block_freq(choffs);
// compute the keycode: block_freq is:
//
// BBBCCCCFFFFFF
// ^^^^^
//
// the 5-bit keycode is just the top 5 bits (block + top 2 bits
// of the key code)
uint32_t keycode = bitfield(block_freq, 8, 5);
// detune adjustment
cache.detune = detune_adjustment(op_detune(opoffs), keycode);
// multiple value, as an x.4 value (0 means 0.5)
// the "fine" control provides the fractional bits
cache.multiple = op_multiple(opoffs) << 4;
if (cache.multiple == 0)
cache.multiple = 0x08;
cache.multiple |= op_fine(opoffs);
// phase step, or PHASE_STEP_DYNAMIC if PM is active; this depends on
// block_freq, detune, and multiple, so compute it after we've done those;
// note that fix frequency mode is also treated as dynamic
if (!op_fix_mode(opoffs) && (lfo_pm_depth() == 0 || ch_lfo_pm_sens(choffs) == 0) && (lfo2_pm_depth() == 0 || ch_lfo2_pm_sens(choffs) == 0))
cache.phase_step = compute_phase_step(choffs, opoffs, cache, 0);
else
cache.phase_step = opdata_cache::PHASE_STEP_DYNAMIC;
// total level, scaled by 8
// TODO: how does ch_volume() fit into this?
cache.total_level = op_total_level(opoffs) << 3;
// 4-bit sustain level, but 15 means 31 so effectively 5 bits
cache.eg_sustain = op_sustain_level(opoffs);
cache.eg_sustain |= (cache.eg_sustain + 1) & 0x10;
cache.eg_sustain <<= 5;
// determine KSR adjustment for enevlope rates
uint32_t ksrval = keycode >> (op_ksr(opoffs) ^ 3);
cache.eg_rate[EG_ATTACK] = effective_rate(op_attack_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_DECAY] = effective_rate(op_decay_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_SUSTAIN] = effective_rate(op_sustain_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_RELEASE] = effective_rate(op_release_rate(opoffs) * 4 + 2, ksrval);
cache.eg_rate[EG_REVERB] = cache.eg_rate[EG_RELEASE];
uint32_t reverb = op_reverb_rate(opoffs);
if (reverb != 0)
cache.eg_rate[EG_REVERB] = std::min<uint32_t>(effective_rate(reverb * 4 + 2, ksrval), cache.eg_rate[EG_REVERB]);
// set the envelope shift; TX81Z manual says operator 1 shift is fixed at "off"
cache.eg_shift = ((opoffs & 0x18) == 0) ? 0 : op_eg_shift(opoffs);
}
//-------------------------------------------------
// compute_phase_step - compute the phase step
//-------------------------------------------------
uint32_t opz_registers::compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm)
{
// OPZ has a fixed frequency mode; it is unclear whether the
// detune and multiple parameters affect things
uint32_t phase_step;
if (op_fix_mode(opoffs))
{
// the baseline frequency in hz comes from the fix frequency and fine
// registers, which can specify values 8-255Hz in 1Hz increments; that
// value is then shifted up by the 3-bit range
uint32_t freq = op_fix_frequency(opoffs) << 4;
if (freq == 0)
freq = 8;
freq |= op_fine(opoffs);
freq <<= op_fix_range(opoffs);
// there is not enough resolution in the plain phase step to track the
// full range of frequencies, so we keep a per-operator sub step with an
// additional 12 bits of resolution; this calculation gives us, for
// example, a frequency of 8.0009Hz when 8Hz is requested
uint32_t substep = m_phase_substep[opoffs];
substep += 75 * freq;
phase_step = substep >> 12;
m_phase_substep[opoffs] = substep & 0xfff;
// detune/multiple occupy the same space as fix_range/fix_frequency so
// don't apply them in addition
return phase_step;
}
else
{
// start with coarse detune delta; table uses cents value from
// manual, converted into 1/64ths
static const int16_t s_detune2_delta[4] = { 0, (600*64+50)/100, (781*64+50)/100, (950*64+50)/100 };
int32_t delta = s_detune2_delta[op_detune2(opoffs)];
// add in the PM deltas
uint32_t pm_sensitivity = ch_lfo_pm_sens(choffs);
if (pm_sensitivity != 0)
{
// raw PM value is -127..128 which is +/- 200 cents
// manual gives these magnitudes in cents:
// 0, +/-5, +/-10, +/-20, +/-50, +/-100, +/-400, +/-700
// this roughly corresponds to shifting the 200-cent value:
// 0 >> 5, >> 4, >> 3, >> 2, >> 1, << 1, << 2
if (pm_sensitivity < 6)
delta += int8_t(lfo_raw_pm) >> (6 - pm_sensitivity);
else
delta += int8_t(lfo_raw_pm) << (pm_sensitivity - 5);
}
uint32_t pm_sensitivity2 = ch_lfo2_pm_sens(choffs);
if (pm_sensitivity2 != 0)
{
// raw PM value is -127..128 which is +/- 200 cents
// manual gives these magnitudes in cents:
// 0, +/-5, +/-10, +/-20, +/-50, +/-100, +/-400, +/-700
// this roughly corresponds to shifting the 200-cent value:
// 0 >> 5, >> 4, >> 3, >> 2, >> 1, << 1, << 2
if (pm_sensitivity2 < 6)
delta += int8_t(lfo_raw_pm >> 8) >> (6 - pm_sensitivity2);
else
delta += int8_t(lfo_raw_pm >> 8) << (pm_sensitivity2 - 5);
}
// apply delta and convert to a frequency number; this translation is
// the same as OPM so just re-use that helper
phase_step = opm_key_code_to_phase_step(cache.block_freq, delta);
// apply detune based on the keycode
phase_step += cache.detune;
// apply frequency multiplier (which is cached as an x.4 value)
return (phase_step * cache.multiple) >> 4;
}
}
//-------------------------------------------------
// log_keyon - log a key-on event
//-------------------------------------------------
std::string opz_registers::log_keyon(uint32_t choffs, uint32_t opoffs)
{
uint32_t chnum = choffs;
uint32_t opnum = opoffs;
char buffer[256];
char *end = &buffer[0];
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, "%u.%02u", chnum, opnum);
if (op_fix_mode(opoffs))
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " fixfreq=%X fine=%X shift=%X", op_fix_frequency(opoffs), op_fine(opoffs), op_fix_range(opoffs));
else
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " freq=%04X dt2=%u fine=%X", ch_block_freq(choffs), op_detune2(opoffs), op_fine(opoffs));
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " dt=%u fb=%u alg=%X mul=%X tl=%02X ksr=%u adsr=%02X/%02X/%02X/%X sl=%X out=%c%c",
op_detune(opoffs),
ch_feedback(choffs),
ch_algorithm(choffs),
op_multiple(opoffs),
op_total_level(opoffs),
op_ksr(opoffs),
op_attack_rate(opoffs),
op_decay_rate(opoffs),
op_sustain_rate(opoffs),
op_release_rate(opoffs),
op_sustain_level(opoffs),
ch_output_0(choffs) ? 'L' : '-',
ch_output_1(choffs) ? 'R' : '-');
if (op_eg_shift(opoffs) != 0)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " egshift=%u", op_eg_shift(opoffs));
bool am = (lfo_am_depth() != 0 && ch_lfo_am_sens(choffs) != 0 && op_lfo_am_enable(opoffs) != 0);
if (am)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " am=%u/%02X", ch_lfo_am_sens(choffs), lfo_am_depth());
bool pm = (lfo_pm_depth() != 0 && ch_lfo_pm_sens(choffs) != 0);
if (pm)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " pm=%u/%02X", ch_lfo_pm_sens(choffs), lfo_pm_depth());
if (am || pm)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " lfo=%02X/%c", lfo_rate(), "WQTN"[lfo_waveform()]);
bool am2 = (lfo2_am_depth() != 0 && ch_lfo2_am_sens(choffs) != 0 && op_lfo_am_enable(opoffs) != 0);
if (am2)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " am2=%u/%02X", ch_lfo2_am_sens(choffs), lfo2_am_depth());
bool pm2 = (lfo2_pm_depth() != 0 && ch_lfo2_pm_sens(choffs) != 0);
if (pm2)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " pm2=%u/%02X", ch_lfo2_pm_sens(choffs), lfo2_pm_depth());
if (am2 || pm2)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " lfo2=%02X/%c", lfo2_rate(), "WQTN"[lfo2_waveform()]);
if (op_reverb_rate(opoffs) != 0)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " rev=%u", op_reverb_rate(opoffs));
if (op_waveform(opoffs) != 0)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " wf=%u", op_waveform(opoffs));
if (noise_enable() && opoffs == 31)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " noise=1");
return buffer;
}
//*********************************************************
// YM2414
//*********************************************************
//-------------------------------------------------
// ym2414 - constructor
//-------------------------------------------------
ym2414::ym2414(ymfm_interface &intf) :
m_address(0),
m_fm(intf)
{
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ym2414::reset()
{
// reset the engines
m_fm.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ym2414::save_restore(ymfm_saved_state &state)
{
m_fm.save_restore(state);
state.save_restore(m_address);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ym2414::read_status()
{
uint8_t result = m_fm.status();
if (m_fm.intf().ymfm_is_busy())
result |= fm_engine::STATUS_BUSY;
return result;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ym2414::read(uint32_t offset)
{
uint8_t result = 0xff;
switch (offset & 1)
{
case 0: // data port (unused)
debug::log_unexpected_read_write("Unexpected read from YM2414 offset %d\n", offset & 3);
break;
case 1: // status port, YM2203 compatible
result = read_status();
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ym2414::write_address(uint8_t data)
{
// just set the address
m_address = data;
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym2414::write_data(uint8_t data)
{
// write the FM register
m_fm.write(m_address, data);
if (TEMPORARY_DEBUG_PRINTS)
{
switch (m_address & 0xe0)
{
case 0x00:
printf("CTL %02X = %02X\n", m_address, data);
break;
case 0x20:
switch (m_address & 0xf8)
{
case 0x20: printf("R/FBL/ALG %d = %02X\n", m_address & 7, data); break;
case 0x28: printf("KC %d = %02X\n", m_address & 7, data); break;
case 0x30: printf("KF/M %d = %02X\n", m_address & 7, data); break;
case 0x38: printf("PMS/AMS %d = %02X\n", m_address & 7, data); break;
}
break;
case 0x40:
if (bitfield(data, 7) == 0)
printf("DT1/MUL %d.%d = %02X\n", m_address & 7, (m_address >> 3) & 3, data);
else
printf("OW/FINE %d.%d = %02X\n", m_address & 7, (m_address >> 3) & 3, data);
break;
case 0x60:
printf("TL %d.%d = %02X\n", m_address & 7, (m_address >> 3) & 3, data);
break;
case 0x80:
printf("KRS/FIX/AR %d.%d = %02X\n", m_address & 7, (m_address >> 3) & 3, data);
break;
case 0xa0:
printf("A/D1R %d.%d = %02X\n", m_address & 7, (m_address >> 3) & 3, data);
break;
case 0xc0:
if (bitfield(data, 5) == 0)
printf("DT2/D2R %d.%d = %02X\n", m_address & 7, (m_address >> 3) & 3, data);
else
printf("EGS/REV %d.%d = %02X\n", m_address & 7, (m_address >> 3) & 3, data);
break;
case 0xe0:
printf("D1L/RR %d.%d = %02X\n", m_address & 7, (m_address >> 3) & 3, data);
break;
}
}
// special cases
if (m_address == 0x1b)
{
// writes to register 0x1B send the upper 2 bits to the output lines
m_fm.intf().ymfm_external_write(ACCESS_IO, 0, data >> 6);
}
// mark busy for a bit
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym2414::write(uint32_t offset, uint8_t data)
{
switch (offset & 1)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
}
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void ym2414::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// update the FM content; YM2414 is full 14-bit with no intermediate clipping
m_fm.output(output->clear(), 0, 32767, fm_engine::ALL_CHANNELS);
// unsure about YM2414 outputs; assume it is like YM2151
output->roundtrip_fp();
}
}
}
``` | /content/code_sandbox/src/sound/ymfm/ymfm_opz.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 8,706 |
```c++
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ymfm_pcm.h"
#include "ymfm_fm.h"
#include "ymfm_fm.ipp"
namespace ymfm
{
//*********************************************************
// PCM REGISTERS
//*********************************************************
//-------------------------------------------------
// reset - reset the register state
//-------------------------------------------------
void pcm_registers::reset()
{
std::fill_n(&m_regdata[0], REGISTERS, 0);
m_regdata[0xf8] = 0x1b;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void pcm_registers::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_regdata);
}
//-------------------------------------------------
// cache_channel_data - update the cache with
// data from the registers
//-------------------------------------------------
void pcm_registers::cache_channel_data(uint32_t choffs, pcm_cache &cache)
{
// compute step from octave and fnumber; the math here implies
// a .18 fraction but .16 should be perfectly fine
int32_t octave = int8_t(ch_octave(choffs) << 4) >> 4;
uint32_t fnum = ch_fnumber(choffs);
cache.step = ((0x400 | fnum) << (octave + 7)) >> 2;
// total level is computed as a .10 value for interpolation
cache.total_level = ch_total_level(choffs) << 10;
// compute panning values in terms of envelope attenuation
int32_t panpot = int8_t(ch_panpot(choffs) << 4) >> 4;
if (panpot >= 0)
{
cache.pan_left = (panpot == 7) ? 0x3ff : 0x20 * panpot;
cache.pan_right = 0;
}
else if (panpot >= -7)
{
cache.pan_left = 0;
cache.pan_right = (panpot == -7) ? 0x3ff : -0x20 * panpot;
}
else
cache.pan_left = cache.pan_right = 0x3ff;
// determine the LFO stepping value; this how much to add to a running
// x.18 value for the LFO; steps were derived from frequencies in the
// manual and come out very close with these values
static const uint8_t s_lfo_steps[8] = { 1, 12, 19, 25, 31, 35, 37, 42 };
cache.lfo_step = s_lfo_steps[ch_lfo_speed(choffs)];
// AM LFO depth values, derived from the manual; note each has at most
// 2 bits to make the "multiply" easy in hardware
static const uint8_t s_am_depth[8] = { 0, 0x14, 0x20, 0x28, 0x30, 0x40, 0x50, 0x80 };
cache.am_depth = s_am_depth[ch_am_depth(choffs)];
// PM LFO depth values; these are converted from the manual's cents values
// into f-numbers; the computations come out quite cleanly so pretty sure
// these are correct
static const uint8_t s_pm_depth[8] = { 0, 2, 3, 4, 6, 12, 24, 48 };
cache.pm_depth = s_pm_depth[ch_vibrato(choffs)];
// 4-bit sustain level, but 15 means 31 so effectively 5 bits
cache.eg_sustain = ch_sustain_level(choffs);
cache.eg_sustain |= (cache.eg_sustain + 1) & 0x10;
cache.eg_sustain <<= 5;
// compute the key scaling correction factor; 15 means don't do any correction
int32_t correction = ch_rate_correction(choffs);
if (correction == 15)
correction = 0;
else
correction = (octave + correction) * 2 + bitfield(fnum, 9);
// compute the envelope generator rates
cache.eg_rate[EG_ATTACK] = effective_rate(ch_attack_rate(choffs), correction);
cache.eg_rate[EG_DECAY] = effective_rate(ch_decay_rate(choffs), correction);
cache.eg_rate[EG_SUSTAIN] = effective_rate(ch_sustain_rate(choffs), correction);
cache.eg_rate[EG_RELEASE] = effective_rate(ch_release_rate(choffs), correction);
cache.eg_rate[EG_REVERB] = 5;
// if damping is on, override some things; essentially decay at a hardcoded
// rate of 48 until -12db (0x80), then at maximum rate for the rest
if (ch_damp(choffs) != 0)
{
cache.eg_rate[EG_DECAY] = 48;
cache.eg_rate[EG_SUSTAIN] = 63;
cache.eg_rate[EG_RELEASE] = 63;
cache.eg_sustain = 0x80;
}
}
//-------------------------------------------------
// effective_rate - return the effective rate,
// clamping and applying corrections as needed
//-------------------------------------------------
uint32_t pcm_registers::effective_rate(uint32_t raw, uint32_t correction)
{
// raw rates of 0 and 15 just pin to min/max
if (raw == 0)
return 0;
if (raw == 15)
return 63;
// otherwise add the correction and clamp to range
return clamp(raw * 4 + correction, 0, 63);
}
//*********************************************************
// PCM CHANNEL
//*********************************************************
//-------------------------------------------------
// pcm_channel - constructor
//-------------------------------------------------
pcm_channel::pcm_channel(pcm_engine &owner, uint32_t choffs) :
m_choffs(choffs),
m_baseaddr(0),
m_endpos(0),
m_looppos(0),
m_curpos(0),
m_nextpos(0),
m_lfo_counter(0),
m_eg_state(EG_RELEASE),
m_env_attenuation(0x3ff),
m_total_level(0x7f << 10),
m_format(0),
m_key_state(0),
m_regs(owner.regs()),
m_owner(owner)
{
}
//-------------------------------------------------
// reset - reset the channel state
//-------------------------------------------------
void pcm_channel::reset()
{
m_baseaddr = 0;
m_endpos = 0;
m_looppos = 0;
m_curpos = 0;
m_nextpos = 0;
m_lfo_counter = 0;
m_eg_state = EG_RELEASE;
m_env_attenuation = 0x3ff;
m_total_level = 0x7f << 10;
m_format = 0;
m_key_state = 0;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void pcm_channel::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_baseaddr);
state.save_restore(m_endpos);
state.save_restore(m_looppos);
state.save_restore(m_curpos);
state.save_restore(m_nextpos);
state.save_restore(m_lfo_counter);
state.save_restore(m_eg_state);
state.save_restore(m_env_attenuation);
state.save_restore(m_total_level);
state.save_restore(m_format);
state.save_restore(m_key_state);
}
//-------------------------------------------------
// prepare - prepare for clocking
//-------------------------------------------------
bool pcm_channel::prepare()
{
// cache the data
m_regs.cache_channel_data(m_choffs, m_cache);
// clock the key state
if ((m_key_state & KEY_PENDING) != 0)
{
uint8_t oldstate = m_key_state;
m_key_state = (m_key_state >> 1) & KEY_ON;
if (((oldstate ^ m_key_state) & KEY_ON) != 0)
{
if ((m_key_state & KEY_ON) != 0)
start_attack();
else
start_release();
}
}
// set the total level directly if not interpolating
if (m_regs.ch_level_direct(m_choffs))
m_total_level = m_cache.total_level;
// we're active until we're quiet after the release
return (m_eg_state < EG_RELEASE || m_env_attenuation < EG_QUIET);
}
//-------------------------------------------------
// clock - master clocking function
//-------------------------------------------------
void pcm_channel::clock(uint32_t env_counter)
{
// clock the LFO, which is an x.18 value incremented based on the
// LFO speed value
m_lfo_counter += m_cache.lfo_step;
// clock the envelope
clock_envelope(env_counter);
// determine the step after applying vibrato
uint32_t step = m_cache.step;
if (m_cache.pm_depth != 0)
{
// shift the LFO by 1/4 cycle for PM so that it starts at 0
uint32_t lfo_shifted = m_lfo_counter + (1 << 16);
int32_t lfo_value = bitfield(lfo_shifted, 10, 7);
if (bitfield(lfo_shifted, 17) != 0)
lfo_value ^= 0x7f;
lfo_value -= 0x40;
step += (lfo_value * int32_t(m_cache.pm_depth)) >> 7;
}
// advance the sample step and loop as needed
m_curpos = m_nextpos;
m_nextpos = m_curpos + step;
if (m_nextpos >= m_endpos)
m_nextpos += m_looppos - m_endpos;
// interpolate total level if needed
if (m_total_level != m_cache.total_level)
{
// max->min volume takes 156.4ms, or pretty close to 19/1024 per 44.1kHz sample
// min->max volume is half that, so advance by 38/1024 per sample
if (m_total_level < m_cache.total_level)
m_total_level = std::min<int32_t>(m_total_level + 19, m_cache.total_level);
else
m_total_level = std::max<int32_t>(m_total_level - 38, m_cache.total_level);
}
}
//-------------------------------------------------
// output - return the computed output value, with
// panning applied
//-------------------------------------------------
void pcm_channel::output(output_data &output) const
{
// early out if the envelope is effectively off
uint32_t envelope = m_env_attenuation;
if (envelope > EG_QUIET)
return;
// add in LFO AM modulation
if (m_cache.am_depth != 0)
{
uint32_t lfo_value = bitfield(m_lfo_counter, 10, 7);
if (bitfield(m_lfo_counter, 17) != 0)
lfo_value ^= 0x7f;
envelope += (lfo_value * m_cache.am_depth) >> 7;
}
// add in the current interpolated total level value, which is a .10
// value shifted left by 2
envelope += m_total_level >> 8;
// add in panning effect and clamp
uint32_t lenv = std::min<uint32_t>(envelope + m_cache.pan_left, 0x3ff);
uint32_t renv = std::min<uint32_t>(envelope + m_cache.pan_right, 0x3ff);
// convert to volume as a .11 fraction
int32_t lvol = attenuation_to_volume(lenv << 2);
int32_t rvol = attenuation_to_volume(renv << 2);
// fetch current sample and add
int16_t sample = fetch_sample();
uint32_t outnum = m_regs.ch_output_channel(m_choffs) * 2;
output.data[outnum + 0] += (lvol * sample) >> 15;
output.data[outnum + 1] += (rvol * sample) >> 15;
}
//-------------------------------------------------
// keyonoff - signal key on/off
//-------------------------------------------------
void pcm_channel::keyonoff(bool on)
{
// mark the key state as pending
m_key_state |= KEY_PENDING | (on ? KEY_PENDING_ON : 0);
// don't log masked channels
if ((m_key_state & (KEY_PENDING_ON | KEY_ON)) == KEY_PENDING_ON && ((debug::GLOBAL_PCM_CHANNEL_MASK >> m_choffs) & 1) != 0)
{
debug::log_keyon("KeyOn PCM-%02d: num=%3d oct=%2d fnum=%03X level=%02X%c ADSR=%X/%X/%X/%X SL=%X",
m_choffs,
m_regs.ch_wave_table_num(m_choffs),
int8_t(m_regs.ch_octave(m_choffs) << 4) >> 4,
m_regs.ch_fnumber(m_choffs),
m_regs.ch_total_level(m_choffs),
m_regs.ch_level_direct(m_choffs) ? '!' : '/',
m_regs.ch_attack_rate(m_choffs),
m_regs.ch_decay_rate(m_choffs),
m_regs.ch_sustain_rate(m_choffs),
m_regs.ch_release_rate(m_choffs),
m_regs.ch_sustain_level(m_choffs));
if (m_regs.ch_rate_correction(m_choffs) != 15)
debug::log_keyon(" RC=%X", m_regs.ch_rate_correction(m_choffs));
if (m_regs.ch_pseudo_reverb(m_choffs) != 0)
debug::log_keyon(" %s", "REV");
if (m_regs.ch_damp(m_choffs) != 0)
debug::log_keyon(" %s", "DAMP");
if (m_regs.ch_vibrato(m_choffs) != 0 || m_regs.ch_am_depth(m_choffs) != 0)
{
if (m_regs.ch_vibrato(m_choffs) != 0)
debug::log_keyon(" VIB=%d", m_regs.ch_vibrato(m_choffs));
if (m_regs.ch_am_depth(m_choffs) != 0)
debug::log_keyon(" AM=%d", m_regs.ch_am_depth(m_choffs));
debug::log_keyon(" LFO=%d", m_regs.ch_lfo_speed(m_choffs));
}
debug::log_keyon("%s", "\n");
}
}
//-------------------------------------------------
// load_wavetable - load a wavetable by fetching
// its data from external memory
//-------------------------------------------------
void pcm_channel::load_wavetable()
{
// determine the address of the wave table header
uint32_t wavnum = m_regs.ch_wave_table_num(m_choffs);
uint32_t wavheader = 12 * wavnum;
// above 384 it may be in a different bank
if (wavnum >= 384)
{
uint32_t bank = m_regs.wave_table_header();
if (bank != 0)
wavheader = 512*1024 * bank + (wavnum - 384) * 12;
}
// fetch the 22-bit base address and 2-bit format
uint8_t byte = read_pcm(wavheader + 0);
m_format = bitfield(byte, 6, 2);
m_baseaddr = bitfield(byte, 0, 6) << 16;
m_baseaddr |= read_pcm(wavheader + 1) << 8;
m_baseaddr |= read_pcm(wavheader + 2) << 0;
// fetch the 16-bit loop position
m_looppos = read_pcm(wavheader + 3) << 8;
m_looppos |= read_pcm(wavheader + 4);
m_looppos <<= 16;
// fetch the 16-bit end position, which is stored as a negative value
// for some reason that is unclear
m_endpos = read_pcm(wavheader + 5) << 8;
m_endpos |= read_pcm(wavheader + 6);
m_endpos = -int32_t(m_endpos) << 16;
// remaining data values set registers
m_owner.write(0x80 + m_choffs, read_pcm(wavheader + 7));
m_owner.write(0x98 + m_choffs, read_pcm(wavheader + 8));
m_owner.write(0xb0 + m_choffs, read_pcm(wavheader + 9));
m_owner.write(0xc8 + m_choffs, read_pcm(wavheader + 10));
m_owner.write(0xe0 + m_choffs, read_pcm(wavheader + 11));
// reset the envelope so we don't continue playing mid-sample from previous key ons
m_env_attenuation = 0x3ff;
}
//-------------------------------------------------
// read_pcm - read a byte from the external PCM
// memory interface
//-------------------------------------------------
uint8_t pcm_channel::read_pcm(uint32_t address) const
{
return m_owner.intf().ymfm_external_read(ACCESS_PCM, address);
}
//-------------------------------------------------
// start_attack - start the attack phase
//-------------------------------------------------
void pcm_channel::start_attack()
{
// don't change anything if already in attack state
if (m_eg_state == EG_ATTACK)
return;
m_eg_state = EG_ATTACK;
// reset the LFO if requested
if (m_regs.ch_lfo_reset(m_choffs))
m_lfo_counter = 0;
// if the attack rate == 63 then immediately go to max attenuation
if (m_cache.eg_rate[EG_ATTACK] == 63)
m_env_attenuation = 0;
// reset the positions
m_curpos = m_nextpos = 0;
}
//-------------------------------------------------
// start_release - start the release phase
//-------------------------------------------------
void pcm_channel::start_release()
{
// don't change anything if already in release or reverb state
if (m_eg_state >= EG_RELEASE)
return;
m_eg_state = EG_RELEASE;
}
//-------------------------------------------------
// clock_envelope - clock the envelope generator
//-------------------------------------------------
void pcm_channel::clock_envelope(uint32_t env_counter)
{
// handle attack->decay transitions
if (m_eg_state == EG_ATTACK && m_env_attenuation == 0)
m_eg_state = EG_DECAY;
// handle decay->sustain transitions
if (m_eg_state == EG_DECAY && m_env_attenuation >= m_cache.eg_sustain)
m_eg_state = EG_SUSTAIN;
// fetch the appropriate 6-bit rate value from the cache
uint32_t rate = m_cache.eg_rate[m_eg_state];
// compute the rate shift value; this is the shift needed to
// apply to the env_counter such that it becomes a 5.11 fixed
// point number
uint32_t rate_shift = rate >> 2;
env_counter <<= rate_shift;
// see if the fractional part is 0; if not, it's not time to clock
if (bitfield(env_counter, 0, 11) != 0)
return;
// determine the increment based on the non-fractional part of env_counter
uint32_t relevant_bits = bitfield(env_counter, (rate_shift <= 11) ? 11 : rate_shift, 3);
uint32_t increment = attenuation_increment(rate, relevant_bits);
// attack is the only one that increases
if (m_eg_state == EG_ATTACK)
m_env_attenuation += (~m_env_attenuation * increment) >> 4;
// all other cases are similar
else
{
// apply the increment
m_env_attenuation += increment;
// clamp the final attenuation
if (m_env_attenuation >= 0x400)
m_env_attenuation = 0x3ff;
// transition to reverb at -18dB if enabled
if (m_env_attenuation >= 0xc0 && m_eg_state < EG_REVERB && m_regs.ch_pseudo_reverb(m_choffs))
m_eg_state = EG_REVERB;
}
}
//-------------------------------------------------
// fetch_sample - fetch a sample at the current
// position
//-------------------------------------------------
int16_t pcm_channel::fetch_sample() const
{
uint32_t addr = m_baseaddr;
uint32_t pos = m_curpos >> 16;
// 8-bit PCM: shift up by 8
if (m_format == 0)
return read_pcm(addr + pos) << 8;
// 16-bit PCM: assemble from 2 halves
if (m_format == 2)
{
addr += pos * 2;
return (read_pcm(addr) << 8) | read_pcm(addr + 1);
}
// 12-bit PCM: assemble out of half of 3 bytes
addr += (pos / 2) * 3;
if ((pos & 1) == 0)
return (read_pcm(addr + 0) << 8) | ((read_pcm(addr + 1) << 4) & 0xf0);
else
return (read_pcm(addr + 2) << 8) | ((read_pcm(addr + 1) << 0) & 0xf0);
}
//*********************************************************
// PCM ENGINE
//*********************************************************
//-------------------------------------------------
// pcm_engine - constructor
//-------------------------------------------------
pcm_engine::pcm_engine(ymfm_interface &intf) :
m_intf(intf),
m_env_counter(0),
m_modified_channels(ALL_CHANNELS),
m_active_channels(ALL_CHANNELS)
{
// create the channels
for (int chnum = 0; chnum < CHANNELS; chnum++)
m_channel[chnum] = std::make_unique<pcm_channel>(*this, chnum);
}
//-------------------------------------------------
// reset - reset the engine state
//-------------------------------------------------
void pcm_engine::reset()
{
// reset register state
m_regs.reset();
// reset each channel
for (auto &chan : m_channel)
chan->reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void pcm_engine::save_restore(ymfm_saved_state &state)
{
// save our data
state.save_restore(m_env_counter);
// save channel state
for (int chnum = 0; chnum < CHANNELS; chnum++)
m_channel[chnum]->save_restore(state);
}
//-------------------------------------------------
// clock - master clocking function
//-------------------------------------------------
void pcm_engine::clock(uint32_t chanmask)
{
// if something was modified, prepare
// also prepare every 4k samples to catch ending notes
if (m_modified_channels != 0 || m_prepare_count++ >= 4096)
{
// call each channel to prepare
m_active_channels = 0;
for (int chnum = 0; chnum < CHANNELS; chnum++)
if (bitfield(chanmask, chnum))
if (m_channel[chnum]->prepare())
m_active_channels |= 1 << chnum;
// reset the modified channels and prepare count
m_modified_channels = m_prepare_count = 0;
}
// increment the envelope counter; the envelope generator
// only clocks every other sample in order to make the PCM
// envelopes line up with the FM envelopes (after taking into
// account the different FM sampling rate)
m_env_counter++;
// now update the state of all the channels and operators
for (int chnum = 0; chnum < CHANNELS; chnum++)
if (bitfield(chanmask, chnum))
m_channel[chnum]->clock(m_env_counter >> 1);
}
//-------------------------------------------------
// update - master update function
//-------------------------------------------------
void pcm_engine::output(output_data &output, uint32_t chanmask)
{
// mask out some channels for debug purposes
chanmask &= debug::GLOBAL_PCM_CHANNEL_MASK;
// compute the output of each channel
for (int chnum = 0; chnum < CHANNELS; chnum++)
if (bitfield(chanmask, chnum))
m_channel[chnum]->output(output);
}
//-------------------------------------------------
// read - handle reads from the PCM registers
//-------------------------------------------------
uint8_t pcm_engine::read(uint32_t regnum)
{
// handle reads from the data register
if (regnum == 0x06 && m_regs.memory_access_mode() != 0)
return m_intf.ymfm_external_read(ACCESS_PCM, m_regs.memory_address_autoinc());
return m_regs.read(regnum);
}
//-------------------------------------------------
// write - handle writes to the PCM registers
//-------------------------------------------------
void pcm_engine::write(uint32_t regnum, uint8_t data)
{
// handle reads to the data register
if (regnum == 0x06 && m_regs.memory_access_mode() != 0)
{
m_intf.ymfm_external_write(ACCESS_PCM, m_regs.memory_address_autoinc(), data);
return;
}
// for now just mark all channels as modified
m_modified_channels = ALL_CHANNELS;
// most writes are passive, consumed only when needed
m_regs.write(regnum, data);
// however, process keyons immediately
if (regnum >= 0x68 && regnum <= 0x7f)
m_channel[regnum - 0x68]->keyonoff(bitfield(data, 7));
// and also wavetable writes
else if (regnum >= 0x08 && regnum <= 0x1f)
m_channel[regnum - 0x08]->load_wavetable();
}
}
``` | /content/code_sandbox/src/sound/ymfm/ymfm_pcm.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 5,829 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_ADPCM_H
#define YMFM_ADPCM_H
#pragma once
#include "ymfm.h"
namespace ymfm
{
//*********************************************************
// INTERFACE CLASSES
//*********************************************************
// forward declarations
class adpcm_a_engine;
class adpcm_b_engine;
// ======================> adpcm_a_registers
//
// ADPCM-A register map:
//
// System-wide registers:
// 00 x------- Dump (disable=1) or keyon (0) control
// --xxxxxx Mask of channels to dump or keyon
// 01 --xxxxxx Total level
// 02 xxxxxxxx Test register
// 08-0D x------- Pan left
// -x------ Pan right
// ---xxxxx Instrument level
// 10-15 xxxxxxxx Start address (low)
// 18-1D xxxxxxxx Start address (high)
// 20-25 xxxxxxxx End address (low)
// 28-2D xxxxxxxx End address (high)
//
class adpcm_a_registers
{
public:
// constants
static constexpr uint32_t OUTPUTS = 2;
static constexpr uint32_t CHANNELS = 6;
static constexpr uint32_t REGISTERS = 0x30;
static constexpr uint32_t ALL_CHANNELS = (1 << CHANNELS) - 1;
// constructor
adpcm_a_registers() { }
// reset to initial state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// map channel number to register offset
static constexpr uint32_t channel_offset(uint32_t chnum)
{
assert(chnum < CHANNELS);
return chnum;
}
// direct read/write access
void write(uint32_t index, uint8_t data) { m_regdata[index] = data; }
// system-wide registers
uint32_t dump() const { return bitfield(m_regdata[0x00], 7); }
uint32_t dump_mask() const { return bitfield(m_regdata[0x00], 0, 6); }
uint32_t total_level() const { return bitfield(m_regdata[0x01], 0, 6); }
uint32_t test() const { return m_regdata[0x02]; }
// per-channel registers
uint32_t ch_pan_left(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x08], 7); }
uint32_t ch_pan_right(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x08], 6); }
uint32_t ch_instrument_level(uint32_t choffs) const { return bitfield(m_regdata[choffs + 0x08], 0, 5); }
uint32_t ch_start(uint32_t choffs) const { return m_regdata[choffs + 0x10] | (m_regdata[choffs + 0x18] << 8); }
uint32_t ch_end(uint32_t choffs) const { return m_regdata[choffs + 0x20] | (m_regdata[choffs + 0x28] << 8); }
// per-channel writes
void write_start(uint32_t choffs, uint32_t address)
{
write(choffs + 0x10, address);
write(choffs + 0x18, address >> 8);
}
void write_end(uint32_t choffs, uint32_t address)
{
write(choffs + 0x20, address);
write(choffs + 0x28, address >> 8);
}
private:
// internal state
uint8_t m_regdata[REGISTERS]; // register data
};
// ======================> adpcm_a_channel
class adpcm_a_channel
{
public:
// constructor
adpcm_a_channel(adpcm_a_engine &owner, uint32_t choffs, uint32_t addrshift);
// reset the channel state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// signal key on/off
void keyonoff(bool on);
// master clockingfunction
bool clock();
// return the computed output value, with panning applied
template<int NumOutputs>
void output(ymfm_output<NumOutputs> &output) const;
private:
// internal state
uint32_t const m_choffs; // channel offset
uint32_t const m_address_shift; // address bits shift-left
uint32_t m_playing; // currently playing?
uint32_t m_curnibble; // index of the current nibble
uint32_t m_curbyte; // current byte of data
uint32_t m_curaddress; // current address
int32_t m_accumulator; // accumulator
int32_t m_step_index; // index in the stepping table
adpcm_a_registers &m_regs; // reference to registers
adpcm_a_engine &m_owner; // reference to our owner
};
// ======================> adpcm_a_engine
class adpcm_a_engine
{
public:
static constexpr int CHANNELS = adpcm_a_registers::CHANNELS;
// constructor
adpcm_a_engine(ymfm_interface &intf, uint32_t addrshift);
// reset our status
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// master clocking function
uint32_t clock(uint32_t chanmask);
// compute sum of channel outputs
template<int NumOutputs>
void output(ymfm_output<NumOutputs> &output, uint32_t chanmask);
// write to the ADPCM-A registers
void write(uint32_t regnum, uint8_t data);
// set the start/end address for a channel (for hardcoded YM2608 percussion)
void set_start_end(uint8_t chnum, uint16_t start, uint16_t end)
{
uint32_t choffs = adpcm_a_registers::channel_offset(chnum);
m_regs.write_start(choffs, start);
m_regs.write_end(choffs, end);
}
// return a reference to our interface
ymfm_interface &intf() { return m_intf; }
// return a reference to our registers
adpcm_a_registers ®s() { return m_regs; }
private:
// internal state
ymfm_interface &m_intf; // reference to the interface
std::unique_ptr<adpcm_a_channel> m_channel[CHANNELS]; // array of channels
adpcm_a_registers m_regs; // registers
};
// ======================> adpcm_b_registers
//
// ADPCM-B register map:
//
// System-wide registers:
// 00 x------- Start of synthesis/analysis
// -x------ Record
// --x----- External/manual driving
// ---x---- Repeat playback
// ----x--- Speaker off
// -------x Reset
// 01 x------- Pan left
// -x------ Pan right
// ----x--- Start conversion
// -----x-- DAC enable
// ------x- DRAM access (1=8-bit granularity; 0=1-bit)
// -------x RAM/ROM (1=ROM, 0=RAM)
// 02 xxxxxxxx Start address (low)
// 03 xxxxxxxx Start address (high)
// 04 xxxxxxxx End address (low)
// 05 xxxxxxxx End address (high)
// 06 xxxxxxxx Prescale value (low)
// 07 -----xxx Prescale value (high)
// 08 xxxxxxxx CPU data/buffer
// 09 xxxxxxxx Delta-N frequency scale (low)
// 0a xxxxxxxx Delta-N frequency scale (high)
// 0b xxxxxxxx Level control
// 0c xxxxxxxx Limit address (low)
// 0d xxxxxxxx Limit address (high)
// 0e xxxxxxxx DAC data [YM2608/10]
// 0f xxxxxxxx PCM data [YM2608/10]
// 0e xxxxxxxx DAC data high [Y8950]
// 0f xx------ DAC data low [Y8950]
// 10 -----xxx DAC data exponent [Y8950]
//
class adpcm_b_registers
{
public:
// constants
static constexpr uint32_t REGISTERS = 0x11;
// constructor
adpcm_b_registers() { }
// reset to initial state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// direct read/write access
void write(uint32_t index, uint8_t data) { m_regdata[index] = data; }
// system-wide registers
uint32_t execute() const { return bitfield(m_regdata[0x00], 7); }
uint32_t record() const { return bitfield(m_regdata[0x00], 6); }
uint32_t external() const { return bitfield(m_regdata[0x00], 5); }
uint32_t repeat() const { return bitfield(m_regdata[0x00], 4); }
uint32_t speaker() const { return bitfield(m_regdata[0x00], 3); }
uint32_t resetflag() const { return bitfield(m_regdata[0x00], 0); }
uint32_t pan_left() const { return bitfield(m_regdata[0x01], 7); }
uint32_t pan_right() const { return bitfield(m_regdata[0x01], 6); }
uint32_t start_conversion() const { return bitfield(m_regdata[0x01], 3); }
uint32_t dac_enable() const { return bitfield(m_regdata[0x01], 2); }
uint32_t dram_8bit() const { return bitfield(m_regdata[0x01], 1); }
uint32_t rom_ram() const { return bitfield(m_regdata[0x01], 0); }
uint32_t start() const { return m_regdata[0x02] | (m_regdata[0x03] << 8); }
uint32_t end() const { return m_regdata[0x04] | (m_regdata[0x05] << 8); }
uint32_t prescale() const { return m_regdata[0x06] | (bitfield(m_regdata[0x07], 0, 3) << 8); }
uint32_t cpudata() const { return m_regdata[0x08]; }
uint32_t delta_n() const { return m_regdata[0x09] | (m_regdata[0x0a] << 8); }
uint32_t level() const { return m_regdata[0x0b]; }
uint32_t limit() const { return m_regdata[0x0c] | (m_regdata[0x0d] << 8); }
uint32_t dac() const { return m_regdata[0x0e]; }
uint32_t pcm() const { return m_regdata[0x0f]; }
private:
// internal state
uint8_t m_regdata[REGISTERS]; // register data
};
// ======================> adpcm_b_channel
class adpcm_b_channel
{
static constexpr int32_t STEP_MIN = 127;
static constexpr int32_t STEP_MAX = 24576;
public:
static constexpr uint8_t STATUS_EOS = 0x01;
static constexpr uint8_t STATUS_BRDY = 0x02;
static constexpr uint8_t STATUS_PLAYING = 0x04;
// constructor
adpcm_b_channel(adpcm_b_engine &owner, uint32_t addrshift);
// reset the channel state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// signal key on/off
void keyonoff(bool on);
// master clocking function
void clock();
// return the computed output value, with panning applied
template<int NumOutputs>
void output(ymfm_output<NumOutputs> &output, uint32_t rshift) const;
// return the status register
uint8_t status() const { return m_status; }
// handle special register reads
uint8_t read(uint32_t regnum);
// handle special register writes
void write(uint32_t regnum, uint8_t value);
private:
// helper - return the current address shift
uint32_t address_shift() const;
// load the start address
void load_start();
// limit checker; stops at the last byte of the chunk described by address_shift()
bool at_limit() const { return (m_curaddress == (((m_regs.limit() + 1) << address_shift()) - 1)); }
// end checker; stops at the last byte of the chunk described by address_shift()
bool at_end() const { return (m_curaddress == (((m_regs.end() + 1) << address_shift()) - 1)); }
// internal state
uint32_t const m_address_shift; // address bits shift-left
uint32_t m_status; // currently playing?
uint32_t m_curnibble; // index of the current nibble
uint32_t m_curbyte; // current byte of data
uint32_t m_dummy_read; // dummy read tracker
uint32_t m_position; // current fractional position
uint32_t m_curaddress; // current address
int32_t m_accumulator; // accumulator
int32_t m_prev_accum; // previous accumulator (for linear interp)
int32_t m_adpcm_step; // next forecast
adpcm_b_registers &m_regs; // reference to registers
adpcm_b_engine &m_owner; // reference to our owner
};
// ======================> adpcm_b_engine
class adpcm_b_engine
{
public:
// constructor
adpcm_b_engine(ymfm_interface &intf, uint32_t addrshift = 0);
// reset our status
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// master clocking function
void clock();
// compute sum of channel outputs
template<int NumOutputs>
void output(ymfm_output<NumOutputs> &output, uint32_t rshift);
// read from the ADPCM-B registers
uint32_t read(uint32_t regnum) { return m_channel->read(regnum); }
// write to the ADPCM-B registers
void write(uint32_t regnum, uint8_t data);
// status
uint8_t status() const { return m_channel->status(); }
// return a reference to our interface
ymfm_interface &intf() { return m_intf; }
// return a reference to our registers
adpcm_b_registers ®s() { return m_regs; }
private:
// internal state
ymfm_interface &m_intf; // reference to our interface
std::unique_ptr<adpcm_b_channel> m_channel; // channel pointer
adpcm_b_registers m_regs; // registers
};
}
#endif // YMFM_ADPCM_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm_adpcm.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,619 |
```c++
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ymfm_opn.h"
#include "ymfm_fm.ipp"
namespace ymfm
{
//*********************************************************
// OPN/OPNA REGISTERS
//*********************************************************
//-------------------------------------------------
// opn_registers_base - constructor
//-------------------------------------------------
template<bool IsOpnA>
opn_registers_base<IsOpnA>::opn_registers_base() :
m_lfo_counter(0),
m_lfo_am(0)
{
// create the waveforms
for (uint32_t index = 0; index < WAVEFORM_LENGTH; index++)
m_waveform[0][index] = abs_sin_attenuation(index) | (bitfield(index, 9) << 15);
}
//-------------------------------------------------
// reset - reset to initial state
//-------------------------------------------------
template<bool IsOpnA>
void opn_registers_base<IsOpnA>::reset()
{
std::fill_n(&m_regdata[0], REGISTERS, 0);
if (IsOpnA)
{
// enable output on both channels by default
m_regdata[0xb4] = m_regdata[0xb5] = m_regdata[0xb6] = 0xc0;
m_regdata[0x1b4] = m_regdata[0x1b5] = m_regdata[0x1b6] = 0xc0;
}
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
template<bool IsOpnA>
void opn_registers_base<IsOpnA>::save_restore(ymfm_saved_state &state)
{
if (IsOpnA)
{
state.save_restore(m_lfo_counter);
state.save_restore(m_lfo_am);
}
state.save_restore(m_regdata);
}
//-------------------------------------------------
// operator_map - return an array of operator
// indices for each channel; for OPN this is fixed
//-------------------------------------------------
template<>
void opn_registers_base<false>::operator_map(operator_mapping &dest) const
{
// Note that the channel index order is 0,2,1,3, so we bitswap the index.
//
// This is because the order in the map is:
// carrier 1, carrier 2, modulator 1, modulator 2
//
// But when wiring up the connections, the more natural order is:
// carrier 1, modulator 1, carrier 2, modulator 2
static const operator_mapping s_fixed_map =
{ {
operator_list( 0, 6, 3, 9 ), // Channel 0 operators
operator_list( 1, 7, 4, 10 ), // Channel 1 operators
operator_list( 2, 8, 5, 11 ), // Channel 2 operators
} };
dest = s_fixed_map;
}
template<>
void opn_registers_base<true>::operator_map(operator_mapping &dest) const
{
// Note that the channel index order is 0,2,1,3, so we bitswap the index.
//
// This is because the order in the map is:
// carrier 1, carrier 2, modulator 1, modulator 2
//
// But when wiring up the connections, the more natural order is:
// carrier 1, modulator 1, carrier 2, modulator 2
static const operator_mapping s_fixed_map =
{ {
operator_list( 0, 6, 3, 9 ), // Channel 0 operators
operator_list( 1, 7, 4, 10 ), // Channel 1 operators
operator_list( 2, 8, 5, 11 ), // Channel 2 operators
operator_list( 12, 18, 15, 21 ), // Channel 3 operators
operator_list( 13, 19, 16, 22 ), // Channel 4 operators
operator_list( 14, 20, 17, 23 ), // Channel 5 operators
} };
dest = s_fixed_map;
}
//-------------------------------------------------
// write - handle writes to the register array
//-------------------------------------------------
template<bool IsOpnA>
bool opn_registers_base<IsOpnA>::write(uint16_t index, uint8_t data, uint32_t &channel, uint32_t &opmask)
{
assert(index < REGISTERS);
// writes in the 0xa0-af/0x1a0-af region are handled as latched pairs
// borrow unused registers 0xb8-bf/0x1b8-bf as temporary holding locations
if ((index & 0xf0) == 0xa0)
{
if (bitfield(index, 0, 2) == 3)
return false;
uint32_t latchindex = 0xb8 | bitfield(index, 3);
if (IsOpnA)
latchindex |= index & 0x100;
// writes to the upper half just latch (only low 6 bits matter)
if (bitfield(index, 2))
m_regdata[latchindex] = data | 0x80;
// writes to the lower half only commit if the latch is there
else if (bitfield(m_regdata[latchindex], 7))
{
m_regdata[index] = data;
m_regdata[index | 4] = m_regdata[latchindex] & 0x3f;
m_regdata[latchindex] = 0;
}
return false;
}
else if ((index & 0xf8) == 0xb8)
{
// registers 0xb8-0xbf are used internally
return false;
}
// everything else is normal
m_regdata[index] = data;
// handle writes to the key on index
if (index == 0x28)
{
channel = bitfield(data, 0, 2);
if (channel == 3)
return false;
if (IsOpnA)
channel += bitfield(data, 2, 1) * 3;
opmask = bitfield(data, 4, 4);
return true;
}
return false;
}
//-------------------------------------------------
// clock_noise_and_lfo - clock the noise and LFO,
// handling clock division, depth, and waveform
// computations
//-------------------------------------------------
template<bool IsOpnA>
int32_t opn_registers_base<IsOpnA>::clock_noise_and_lfo()
{
// OPN has no noise generation
// if LFO not enabled (not present on OPN), quick exit with 0s
if (!IsOpnA || !lfo_enable())
{
m_lfo_counter = 0;
// special case: if LFO is disabled on OPNA, it basically just keeps the counter
// at 0; since position 0 gives an AM value of 0x3f, it is important to reflect
// that here; for example, MegaDrive Venom plays some notes with LFO globally
// disabled but enabling LFO on the operators, and it expects this added attenutation
m_lfo_am = IsOpnA ? 0x3f : 0x00;
return 0;
}
// this table is based on converting the frequencies in the applications
// manual to clock dividers, based on the assumption of a 7-bit LFO value
static uint8_t const lfo_max_count[8] = { 109, 78, 72, 68, 63, 45, 9, 6 };
uint32_t subcount = uint8_t(m_lfo_counter++);
// when we cross the divider count, add enough to zero it and cause an
// increment at bit 8; the 7-bit value lives from bits 8-14
if (subcount >= lfo_max_count[lfo_rate()])
{
// note: to match the published values this should be 0x100 - subcount;
// however, tests on the hardware and nuked bear out an off-by-one
// error exists that causes the max LFO rate to be faster than published
m_lfo_counter += 0x101 - subcount;
}
// AM value is 7 bits, staring at bit 8; grab the low 6 directly
m_lfo_am = bitfield(m_lfo_counter, 8, 6);
// first half of the AM period (bit 6 == 0) is inverted
if (bitfield(m_lfo_counter, 8+6) == 0)
m_lfo_am ^= 0x3f;
// PM value is 5 bits, starting at bit 10; grab the low 3 directly
int32_t pm = bitfield(m_lfo_counter, 10, 3);
// PM is reflected based on bit 3
if (bitfield(m_lfo_counter, 10+3))
pm ^= 7;
// PM is negated based on bit 4
return bitfield(m_lfo_counter, 10+4) ? -pm : pm;
}
//-------------------------------------------------
// lfo_am_offset - return the AM offset from LFO
// for the given channel
//-------------------------------------------------
template<bool IsOpnA>
uint32_t opn_registers_base<IsOpnA>::lfo_am_offset(uint32_t choffs) const
{
// shift value for AM sensitivity is [7, 3, 1, 0],
// mapping to values of [0, 1.4, 5.9, and 11.8dB]
uint32_t am_shift = (1 << (ch_lfo_am_sens(choffs) ^ 3)) - 1;
// QUESTION: max sensitivity should give 11.8dB range, but this value
// is directly added to an x.8 attenuation value, which will only give
// 126/256 or ~4.9dB range -- what am I missing? The calculation below
// matches several other emulators, including the Nuked implemenation.
// raw LFO AM value on OPN is 0-3F, scale that up by a factor of 2
// (giving 7 bits) before applying the final shift
return (m_lfo_am << 1) >> am_shift;
}
//-------------------------------------------------
// cache_operator_data - fill the operator cache
// with prefetched data
//-------------------------------------------------
template<bool IsOpnA>
void opn_registers_base<IsOpnA>::cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache)
{
// set up the easy stuff
cache.waveform = &m_waveform[0][0];
// get frequency from the channel
uint32_t block_freq = cache.block_freq = ch_block_freq(choffs);
// if multi-frequency mode is enabled and this is channel 2,
// fetch one of the special frequencies
if (multi_freq() && choffs == 2)
{
if (opoffs == 2)
block_freq = cache.block_freq = multi_block_freq(1);
else if (opoffs == 10)
block_freq = cache.block_freq = multi_block_freq(2);
else if (opoffs == 6)
block_freq = cache.block_freq = multi_block_freq(0);
}
// compute the keycode: block_freq is:
//
// BBBFFFFFFFFFFF
// ^^^^???
//
// the 5-bit keycode uses the top 4 bits plus a magic formula
// for the final bit
uint32_t keycode = bitfield(block_freq, 10, 4) << 1;
// lowest bit is determined by a mix of next lower FNUM bits
// according to this equation from the YM2608 manual:
//
// (F11 & (F10 | F9 | F8)) | (!F11 & F10 & F9 & F8)
//
// for speed, we just look it up in a 16-bit constant
keycode |= bitfield(0xfe80, bitfield(block_freq, 7, 4));
// detune adjustment
cache.detune = detune_adjustment(op_detune(opoffs), keycode);
// multiple value, as an x.1 value (0 means 0.5)
cache.multiple = op_multiple(opoffs) * 2;
if (cache.multiple == 0)
cache.multiple = 1;
// phase step, or PHASE_STEP_DYNAMIC if PM is active; this depends on
// block_freq, detune, and multiple, so compute it after we've done those
if (!IsOpnA || lfo_enable() == 0 || ch_lfo_pm_sens(choffs) == 0)
cache.phase_step = compute_phase_step(choffs, opoffs, cache, 0);
else
cache.phase_step = opdata_cache::PHASE_STEP_DYNAMIC;
// total level, scaled by 8
cache.total_level = op_total_level(opoffs) << 3;
// 4-bit sustain level, but 15 means 31 so effectively 5 bits
cache.eg_sustain = op_sustain_level(opoffs);
cache.eg_sustain |= (cache.eg_sustain + 1) & 0x10;
cache.eg_sustain <<= 5;
// determine KSR adjustment for enevlope rates
uint32_t ksrval = keycode >> (op_ksr(opoffs) ^ 3);
cache.eg_rate[EG_ATTACK] = effective_rate(op_attack_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_DECAY] = effective_rate(op_decay_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_SUSTAIN] = effective_rate(op_sustain_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_RELEASE] = effective_rate(op_release_rate(opoffs) * 4 + 2, ksrval);
}
//-------------------------------------------------
// compute_phase_step - compute the phase step
//-------------------------------------------------
template<bool IsOpnA>
uint32_t opn_registers_base<IsOpnA>::compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm)
{
// OPN phase calculation has only a single detune parameter
// and uses FNUMs instead of keycodes
// extract frequency number (low 11 bits of block_freq)
uint32_t fnum = bitfield(cache.block_freq, 0, 11) << 1;
// if there's a non-zero PM sensitivity, compute the adjustment
uint32_t pm_sensitivity = ch_lfo_pm_sens(choffs);
if (pm_sensitivity != 0)
{
// apply the phase adjustment based on the upper 7 bits
// of FNUM and the PM depth parameters
fnum += opn_lfo_pm_phase_adjustment(bitfield(cache.block_freq, 4, 7), pm_sensitivity, lfo_raw_pm);
// keep fnum to 12 bits
fnum &= 0xfff;
}
// apply block shift to compute phase step
uint32_t block = bitfield(cache.block_freq, 11, 3);
uint32_t phase_step = (fnum << block) >> 2;
// apply detune based on the keycode
phase_step += cache.detune;
// clamp to 17 bits in case detune overflows
// QUESTION: is this specific to the YM2612/3438?
phase_step &= 0x1ffff;
// apply frequency multiplier (which is cached as an x.1 value)
return (phase_step * cache.multiple) >> 1;
}
//-------------------------------------------------
// log_keyon - log a key-on event
//-------------------------------------------------
template<bool IsOpnA>
std::string opn_registers_base<IsOpnA>::log_keyon(uint32_t choffs, uint32_t opoffs)
{
uint32_t chnum = (choffs & 3) + 3 * bitfield(choffs, 8);
uint32_t opnum = (opoffs & 15) - ((opoffs & 15) / 4) + 12 * bitfield(opoffs, 8);
uint32_t block_freq = ch_block_freq(choffs);
if (multi_freq() && choffs == 2)
{
if (opoffs == 2)
block_freq = multi_block_freq(1);
else if (opoffs == 10)
block_freq = multi_block_freq(2);
else if (opoffs == 6)
block_freq = multi_block_freq(0);
}
char buffer[256];
char *end = &buffer[0];
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, "%u.%02u freq=%04X dt=%u fb=%u alg=%X mul=%X tl=%02X ksr=%u adsr=%02X/%02X/%02X/%X sl=%X",
chnum, opnum,
block_freq,
op_detune(opoffs),
ch_feedback(choffs),
ch_algorithm(choffs),
op_multiple(opoffs),
op_total_level(opoffs),
op_ksr(opoffs),
op_attack_rate(opoffs),
op_decay_rate(opoffs),
op_sustain_rate(opoffs),
op_release_rate(opoffs),
op_sustain_level(opoffs));
if (OUTPUTS > 1)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " out=%c%c",
ch_output_0(choffs) ? 'L' : '-',
ch_output_1(choffs) ? 'R' : '-');
if (op_ssg_eg_enable(opoffs))
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " ssg=%X", op_ssg_eg_mode(opoffs));
bool am = (op_lfo_am_enable(opoffs) && ch_lfo_am_sens(choffs) != 0);
if (am)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " am=%u", ch_lfo_am_sens(choffs));
bool pm = (ch_lfo_pm_sens(choffs) != 0);
if (pm)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " pm=%u", ch_lfo_pm_sens(choffs));
if (am || pm)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " lfo=%02X", lfo_rate());
if (multi_freq() && choffs == 2)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " multi=1");
return buffer;
}
//*********************************************************
// SSG RESAMPLER
//*********************************************************
//-------------------------------------------------
// add_last - helper to add the last computed
// value to the sums, applying the given scale
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
void ssg_resampler<OutputType, FirstOutput, MixTo1>::add_last(int32_t &sum0, int32_t &sum1, int32_t &sum2, int32_t scale)
{
sum0 += m_last.data[0] * scale;
sum1 += m_last.data[1] * scale;
sum2 += m_last.data[2] * scale;
}
//-------------------------------------------------
// clock_and_add - helper to clock a new value
// and then add it to the sums, applying the
// given scale
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
void ssg_resampler<OutputType, FirstOutput, MixTo1>::clock_and_add(int32_t &sum0, int32_t &sum1, int32_t &sum2, int32_t scale)
{
m_ssg.clock();
m_ssg.output(m_last);
add_last(sum0, sum1, sum2, scale);
}
//-------------------------------------------------
// write_to_output - helper to write the sums to
// the appropriate outputs, applying the given
// divisor to the final result
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
void ssg_resampler<OutputType, FirstOutput, MixTo1>::write_to_output(OutputType *output, int32_t sum0, int32_t sum1, int32_t sum2, int32_t divisor)
{
if (MixTo1)
{
// mixing to one, apply a 2/3 factor to prevent overflow
output->data[FirstOutput] = (sum0 + sum1 + sum2) * 2 / (3 * divisor);
}
else
{
// write three outputs in a row
output->data[FirstOutput + 0] = sum0 / divisor;
output->data[FirstOutput + 1] = sum1 / divisor;
output->data[FirstOutput + 2] = sum2 / divisor;
}
// track the sample index here
m_sampindex++;
}
//-------------------------------------------------
// ssg_resampler - constructor
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
ssg_resampler<OutputType, FirstOutput, MixTo1>::ssg_resampler(ssg_engine &ssg) :
m_ssg(ssg),
m_sampindex(0),
m_resampler(&ssg_resampler::resample_nop)
{
m_last.clear();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
void ssg_resampler<OutputType, FirstOutput, MixTo1>::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_sampindex);
state.save_restore(m_last.data);
}
//-------------------------------------------------
// configure - configure a new ratio
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
void ssg_resampler<OutputType, FirstOutput, MixTo1>::configure(uint8_t outsamples, uint8_t srcsamples)
{
switch (outsamples * 10 + srcsamples)
{
case 4*10 + 1: /* 4:1 */ m_resampler = &ssg_resampler::resample_n_1<4>; break;
case 2*10 + 1: /* 2:1 */ m_resampler = &ssg_resampler::resample_n_1<2>; break;
case 4*10 + 3: /* 4:3 */ m_resampler = &ssg_resampler::resample_4_3; break;
case 1*10 + 1: /* 1:1 */ m_resampler = &ssg_resampler::resample_n_1<1>; break;
case 2*10 + 3: /* 2:3 */ m_resampler = &ssg_resampler::resample_2_3; break;
case 1*10 + 3: /* 1:3 */ m_resampler = &ssg_resampler::resample_1_n<3>; break;
case 2*10 + 9: /* 2:9 */ m_resampler = &ssg_resampler::resample_2_9; break;
case 1*10 + 6: /* 1:6 */ m_resampler = &ssg_resampler::resample_1_n<6>; break;
case 0*10 + 0: /* 0:0 */ m_resampler = &ssg_resampler::resample_nop; break;
default: assert(false); break;
}
}
//-------------------------------------------------
// resample_n_1 - resample SSG output to the
// target at a rate of 1 SSG sample to every
// n output sample
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
template<int Multiplier>
void ssg_resampler<OutputType, FirstOutput, MixTo1>::resample_n_1(OutputType *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
if (m_sampindex % Multiplier == 0)
{
m_ssg.clock();
m_ssg.output(m_last);
}
write_to_output(output, m_last.data[0], m_last.data[1], m_last.data[2]);
}
}
//-------------------------------------------------
// resample_1_n - resample SSG output to the
// target at a rate of n SSG samples to every
// 1 output sample
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
template<int Divisor>
void ssg_resampler<OutputType, FirstOutput, MixTo1>::resample_1_n(OutputType *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
int32_t sum0 = 0, sum1 = 0, sum2 = 0;
for (int rep = 0; rep < Divisor; rep++)
clock_and_add(sum0, sum1, sum2);
write_to_output(output, sum0, sum1, sum2, Divisor);
}
}
//-------------------------------------------------
// resample_2_9 - resample SSG output to the
// target at a rate of 9 SSG samples to every
// 2 output samples
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
void ssg_resampler<OutputType, FirstOutput, MixTo1>::resample_2_9(OutputType *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
int32_t sum0 = 0, sum1 = 0, sum2 = 0;
if (bitfield(m_sampindex, 0) != 0)
add_last(sum0, sum1, sum2, 1);
clock_and_add(sum0, sum1, sum2, 2);
clock_and_add(sum0, sum1, sum2, 2);
clock_and_add(sum0, sum1, sum2, 2);
clock_and_add(sum0, sum1, sum2, 2);
if (bitfield(m_sampindex, 0) == 0)
clock_and_add(sum0, sum1, sum2, 1);
write_to_output(output, sum0, sum1, sum2, 9);
}
}
//-------------------------------------------------
// resample_2_3 - resample SSG output to the
// target at a rate of 3 SSG samples to every
// 2 output samples
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
void ssg_resampler<OutputType, FirstOutput, MixTo1>::resample_2_3(OutputType *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
int32_t sum0 = 0, sum1 = 0, sum2 = 0;
if (bitfield(m_sampindex, 0) == 0)
{
clock_and_add(sum0, sum1, sum2, 2);
clock_and_add(sum0, sum1, sum2, 1);
}
else
{
add_last(sum0, sum1, sum2, 1);
clock_and_add(sum0, sum1, sum2, 2);
}
write_to_output(output, sum0, sum1, sum2, 3);
}
}
//-------------------------------------------------
// resample_4_3 - resample SSG output to the
// target at a rate of 3 SSG samples to every
// 4 output samples
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
void ssg_resampler<OutputType, FirstOutput, MixTo1>::resample_4_3(OutputType *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
int32_t sum0 = 0, sum1 = 0, sum2 = 0;
int32_t step = bitfield(m_sampindex, 0, 2);
add_last(sum0, sum1, sum2, step);
if (step != 3)
clock_and_add(sum0, sum1, sum2, 3 - step);
write_to_output(output, sum0, sum1, sum2, 3);
}
}
//-------------------------------------------------
// resample_nop - no-op resampler
//-------------------------------------------------
template<typename OutputType, int FirstOutput, bool MixTo1>
void ssg_resampler<OutputType, FirstOutput, MixTo1>::resample_nop(OutputType *output, uint32_t numsamples)
{
// nothing to do except increment the sample index
m_sampindex += numsamples;
}
//*********************************************************
// YM2203
//*********************************************************
//-------------------------------------------------
// ym2203 - constructor
//-------------------------------------------------
ym2203::ym2203(ymfm_interface &intf) :
m_fidelity(OPN_FIDELITY_MAX),
m_address(0),
m_fm(intf),
m_ssg(intf),
m_ssg_resampler(m_ssg)
{
m_last_fm.clear();
update_prescale(m_fm.clock_prescale());
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ym2203::reset()
{
// reset the engines
m_fm.reset();
m_ssg.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ym2203::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
state.save_restore(m_last_fm.data);
m_fm.save_restore(state);
m_ssg.save_restore(state);
m_ssg_resampler.save_restore(state);
update_prescale(m_fm.clock_prescale());
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ym2203::read_status()
{
uint8_t result = m_fm.status();
if (m_fm.intf().ymfm_is_busy())
result |= fm_engine::STATUS_BUSY;
return result;
}
//-------------------------------------------------
// read_data - read the data register
//-------------------------------------------------
uint8_t ym2203::read_data()
{
uint8_t result = 0;
if (m_address < 0x10)
{
// 00-0F: Read from SSG
result = m_ssg.read(m_address & 0x0f);
}
return result;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ym2203::read(uint32_t offset)
{
uint8_t result = 0xff;
switch (offset & 1)
{
case 0: // status port
result = read_status();
break;
case 1: // data port (only SSG)
result = read_data();
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ym2203::write_address(uint8_t data)
{
// just set the address
m_address = data;
// special case: update the prescale
if (m_address >= 0x2d && m_address <= 0x2f)
{
// 2D-2F: prescaler select
if (m_address == 0x2d)
update_prescale(6);
else if (m_address == 0x2e && m_fm.clock_prescale() == 6)
update_prescale(3);
else if (m_address == 0x2f)
update_prescale(2);
}
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym2203::write_data(uint8_t data)
{
if (m_address < 0x10)
{
// 00-0F: write to SSG
m_ssg.write(m_address & 0x0f, data);
}
else
{
// 10-FF: write to FM
m_fm.write(m_address, data);
}
// mark busy for a bit
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym2203::write(uint32_t offset, uint8_t data)
{
switch (offset & 1)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
}
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void ym2203::generate(output_data *output, uint32_t numsamples)
{
// FM output is just repeated the prescale number of times; note that
// 0 is a special 1.5 case
if (m_fm_samples_per_output != 0)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
if ((m_ssg_resampler.sampindex() + samp) % m_fm_samples_per_output == 0)
clock_fm();
output->data[0] = m_last_fm.data[0];
}
}
else
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
uint32_t step = (m_ssg_resampler.sampindex() + samp) % 3;
if (step == 0)
clock_fm();
output->data[0] = m_last_fm.data[0];
if (step == 1)
{
clock_fm();
output->data[0] = (output->data[0] + m_last_fm.data[0]) / 2;
}
}
}
// resample the SSG as configured
m_ssg_resampler.resample(output - numsamples, numsamples);
}
//-------------------------------------------------
// update_prescale - update the prescale value,
// recomputing derived values
//-------------------------------------------------
void ym2203::update_prescale(uint8_t prescale)
{
// tell the FM engine
m_fm.set_clock_prescale(prescale);
m_ssg.prescale_changed();
// Fidelity: ---- minimum ---- ---- medium ----- ---- maximum-----
// rate = clock/24 rate = clock/12 rate = clock/4
// Prescale FM rate SSG rate FM rate SSG rate FM rate SSG rate
// 6 3:1 2:3 6:1 4:3 18:1 4:1
// 3 1.5:1 1:3 3:1 2:3 9:1 2:1
// 2 1:1 1:6 2:1 1:3 6:1 1:1
// compute the number of FM samples per output sample, and select the
// resampler function
if (m_fidelity == OPN_FIDELITY_MIN)
{
switch (prescale)
{
default:
case 6: m_fm_samples_per_output = 3; m_ssg_resampler.configure(2, 3); break;
case 3: m_fm_samples_per_output = 0; m_ssg_resampler.configure(1, 3); break;
case 2: m_fm_samples_per_output = 1; m_ssg_resampler.configure(1, 6); break;
}
}
else if (m_fidelity == OPN_FIDELITY_MED)
{
switch (prescale)
{
default:
case 6: m_fm_samples_per_output = 6; m_ssg_resampler.configure(4, 3); break;
case 3: m_fm_samples_per_output = 3; m_ssg_resampler.configure(2, 3); break;
case 2: m_fm_samples_per_output = 2; m_ssg_resampler.configure(1, 3); break;
}
}
else
{
switch (prescale)
{
default:
case 6: m_fm_samples_per_output = 18; m_ssg_resampler.configure(4, 1); break;
case 3: m_fm_samples_per_output = 9; m_ssg_resampler.configure(2, 1); break;
case 2: m_fm_samples_per_output = 6; m_ssg_resampler.configure(1, 1); break;
}
}
// if overriding the SSG, override the configuration with the nop
// resampler to at least keep the sample index moving forward
if (m_ssg.overridden())
m_ssg_resampler.configure(0, 0);
}
//-------------------------------------------------
// clock_fm - clock FM state
//-------------------------------------------------
void ym2203::clock_fm()
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// update the FM content; OPN is full 14-bit with no intermediate clipping
m_fm.output(m_last_fm.clear(), 0, 32767, fm_engine::ALL_CHANNELS);
// convert to 10.3 floating point value for the DAC and back
m_last_fm.roundtrip_fp();
}
//*********************************************************
// YM2608
//*********************************************************
//-------------------------------------------------
// ym2608 - constructor
//-------------------------------------------------
ym2608::ym2608(ymfm_interface &intf) :
m_fidelity(OPN_FIDELITY_MAX),
m_address(0),
m_irq_enable(0x1f),
m_flag_control(0x1c),
m_fm(intf),
m_ssg(intf),
m_ssg_resampler(m_ssg),
m_adpcm_a(intf, 0),
m_adpcm_b(intf)
{
m_last_fm.clear();
update_prescale(m_fm.clock_prescale());
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ym2608::reset()
{
// reset the engines
m_fm.reset();
m_ssg.reset();
m_adpcm_a.reset();
m_adpcm_b.reset();
// configure ADPCM percussion sounds; these are present in an embedded ROM
m_adpcm_a.set_start_end(0, 0x0000, 0x01bf); // bass drum
m_adpcm_a.set_start_end(1, 0x01c0, 0x043f); // snare drum
m_adpcm_a.set_start_end(2, 0x0440, 0x1b7f); // top cymbal
m_adpcm_a.set_start_end(3, 0x1b80, 0x1cff); // high hat
m_adpcm_a.set_start_end(4, 0x1d00, 0x1f7f); // tom tom
m_adpcm_a.set_start_end(5, 0x1f80, 0x1fff); // rim shot
// initialize our special interrupt states, then read the upper status
// register, which updates the IRQs
m_irq_enable = 0x1f;
m_flag_control = 0x1c;
read_status_hi();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ym2608::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
state.save_restore(m_irq_enable);
state.save_restore(m_flag_control);
state.save_restore(m_last_fm.data);
m_fm.save_restore(state);
m_ssg.save_restore(state);
m_ssg_resampler.save_restore(state);
m_adpcm_a.save_restore(state);
m_adpcm_b.save_restore(state);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ym2608::read_status()
{
uint8_t result = m_fm.status() & (fm_engine::STATUS_TIMERA | fm_engine::STATUS_TIMERB);
if (m_fm.intf().ymfm_is_busy())
result |= fm_engine::STATUS_BUSY;
return result;
}
//-------------------------------------------------
// read_data - read the data register
//-------------------------------------------------
uint8_t ym2608::read_data()
{
uint8_t result = 0;
if (m_address < 0x10)
{
// 00-0F: Read from SSG
result = m_ssg.read(m_address & 0x0f);
}
else if (m_address == 0xff)
{
// FF: ID code
result = 1;
}
return result;
}
//-------------------------------------------------
// read_status_hi - read the extended status
// register
//-------------------------------------------------
uint8_t ym2608::read_status_hi()
{
// fetch regular status
uint8_t status = m_fm.status() & ~(STATUS_ADPCM_B_EOS | STATUS_ADPCM_B_BRDY | STATUS_ADPCM_B_PLAYING);
// fetch ADPCM-B status, and merge in the bits
uint8_t adpcm_status = m_adpcm_b.status();
if ((adpcm_status & adpcm_b_channel::STATUS_EOS) != 0)
status |= STATUS_ADPCM_B_EOS;
if ((adpcm_status & adpcm_b_channel::STATUS_BRDY) != 0)
status |= STATUS_ADPCM_B_BRDY;
if ((adpcm_status & adpcm_b_channel::STATUS_PLAYING) != 0)
status |= STATUS_ADPCM_B_PLAYING;
// turn off any bits that have been requested to be masked
status &= ~(m_flag_control & 0x1f);
// update the status so that IRQs are propagated
m_fm.set_reset_status(status, ~status);
// merge in the busy flag
if (m_fm.intf().ymfm_is_busy())
status |= fm_engine::STATUS_BUSY;
return status;
}
//-------------------------------------------------
// read_data_hi - read the upper data register
//-------------------------------------------------
uint8_t ym2608::read_data_hi()
{
uint8_t result = 0;
if ((m_address & 0xff) < 0x10)
{
// 00-0F: Read from ADPCM-B
result = m_adpcm_b.read(m_address & 0x0f);
}
return result;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ym2608::read(uint32_t offset)
{
uint8_t result = 0;
switch (offset & 3)
{
case 0: // status port, YM2203 compatible
result = read_status();
break;
case 1: // data port (only SSG)
result = read_data();
break;
case 2: // status port, extended
result = read_status_hi();
break;
case 3: // ADPCM-B data
result = read_data_hi();
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ym2608::write_address(uint8_t data)
{
// just set the address
m_address = data;
// special case: update the prescale
if (m_address >= 0x2d && m_address <= 0x2f)
{
// 2D-2F: prescaler select
if (m_address == 0x2d)
update_prescale(6);
else if (m_address == 0x2e && m_fm.clock_prescale() == 6)
update_prescale(3);
else if (m_address == 0x2f)
update_prescale(2);
}
}
//-------------------------------------------------
// write - handle a write to the data register
//-------------------------------------------------
void ym2608::write_data(uint8_t data)
{
// ignore if paired with upper address
if (bitfield(m_address, 8))
return;
if (m_address < 0x10)
{
// 00-0F: write to SSG
m_ssg.write(m_address & 0x0f, data);
}
else if (m_address < 0x20)
{
// 10-1F: write to ADPCM-A
m_adpcm_a.write(m_address & 0x0f, data);
}
else if (m_address == 0x29)
{
// 29: special IRQ mask register
m_irq_enable = data;
m_fm.set_irq_mask(m_irq_enable & ~m_flag_control & 0x1f);
}
else
{
// 20-28, 2A-FF: write to FM
m_fm.write(m_address, data);
}
// mark busy for a bit
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
}
//-------------------------------------------------
// write_address_hi - handle a write to the upper
// address register
//-------------------------------------------------
void ym2608::write_address_hi(uint8_t data)
{
// just set the address
m_address = 0x100 | data;
}
//-------------------------------------------------
// write_data_hi - handle a write to the upper
// data register
//-------------------------------------------------
void ym2608::write_data_hi(uint8_t data)
{
// ignore if paired with upper address
if (!bitfield(m_address, 8))
return;
if (m_address < 0x110)
{
// 100-10F: write to ADPCM-B
m_adpcm_b.write(m_address & 0x0f, data);
}
else if (m_address == 0x110)
{
// 110: IRQ flag control
if (bitfield(data, 7))
m_fm.set_reset_status(0, 0xff);
else
{
m_flag_control = data;
m_fm.set_irq_mask(m_irq_enable & ~m_flag_control & 0x1f);
}
}
else
{
// 111-1FF: write to FM
m_fm.write(m_address, data);
}
// mark busy for a bit
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym2608::write(uint32_t offset, uint8_t data)
{
switch (offset & 3)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
case 2: // upper address port
write_address_hi(data);
break;
case 3: // upper data port
write_data_hi(data);
break;
}
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void ym2608::generate(output_data *output, uint32_t numsamples)
{
// FM output is just repeated the prescale number of times; note that
// 0 is a special 1.5 case
if (m_fm_samples_per_output != 0)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
if ((m_ssg_resampler.sampindex() + samp) % m_fm_samples_per_output == 0)
clock_fm_and_adpcm();
output->data[0] = m_last_fm.data[0];
output->data[1] = m_last_fm.data[1];
}
}
else
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
uint32_t step = (m_ssg_resampler.sampindex() + samp) % 3;
if (step == 0)
clock_fm_and_adpcm();
output->data[0] = m_last_fm.data[0];
output->data[1] = m_last_fm.data[1];
if (step == 1)
{
clock_fm_and_adpcm();
output->data[0] = (output->data[0] + m_last_fm.data[0]) / 2;
output->data[1] = (output->data[1] + m_last_fm.data[1]) / 2;
}
}
}
// resample the SSG as configured
m_ssg_resampler.resample(output - numsamples, numsamples);
}
//-------------------------------------------------
// update_prescale - update the prescale value,
// recomputing derived values
//-------------------------------------------------
void ym2608::update_prescale(uint8_t prescale)
{
// tell the FM engine
m_fm.set_clock_prescale(prescale);
m_ssg.prescale_changed();
// Fidelity: ---- minimum ---- ---- medium ----- ---- maximum-----
// rate = clock/48 rate = clock/24 rate = clock/8
// Prescale FM rate SSG rate FM rate SSG rate FM rate SSG rate
// 6 3:1 2:3 6:1 4:3 18:1 4:1
// 3 1.5:1 1:3 3:1 2:3 9:1 2:1
// 2 1:1 1:6 2:1 1:3 6:1 1:1
// compute the number of FM samples per output sample, and select the
// resampler function
if (m_fidelity == OPN_FIDELITY_MIN)
{
switch (prescale)
{
default:
case 6: m_fm_samples_per_output = 3; m_ssg_resampler.configure(2, 3); break;
case 3: m_fm_samples_per_output = 0; m_ssg_resampler.configure(1, 3); break;
case 2: m_fm_samples_per_output = 1; m_ssg_resampler.configure(1, 6); break;
}
}
else if (m_fidelity == OPN_FIDELITY_MED)
{
switch (prescale)
{
default:
case 6: m_fm_samples_per_output = 6; m_ssg_resampler.configure(4, 3); break;
case 3: m_fm_samples_per_output = 3; m_ssg_resampler.configure(2, 3); break;
case 2: m_fm_samples_per_output = 2; m_ssg_resampler.configure(1, 3); break;
}
}
else
{
switch (prescale)
{
default:
case 6: m_fm_samples_per_output = 18; m_ssg_resampler.configure(4, 1); break;
case 3: m_fm_samples_per_output = 9; m_ssg_resampler.configure(2, 1); break;
case 2: m_fm_samples_per_output = 6; m_ssg_resampler.configure(1, 1); break;
}
}
// if overriding the SSG, override the configuration with the nop
// resampler to at least keep the sample index moving forward
if (m_ssg.overridden())
m_ssg_resampler.configure(0, 0);
}
//-------------------------------------------------
// clock_fm_and_adpcm - clock FM and ADPCM state
//-------------------------------------------------
void ym2608::clock_fm_and_adpcm()
{
// top bit of the IRQ enable flags controls 3-channel vs 6-channel mode
uint32_t fmmask = bitfield(m_irq_enable, 7) ? 0x3f : 0x07;
// clock the system
uint32_t env_counter = m_fm.clock(fm_engine::ALL_CHANNELS);
// clock the ADPCM-A engine on every envelope cycle
// (channels 4 and 5 clock every 2 envelope clocks)
if (bitfield(env_counter, 0, 2) == 0)
m_adpcm_a.clock(bitfield(env_counter, 2) ? 0x0f : 0x3f);
// clock the ADPCM-B engine every cycle
m_adpcm_b.clock();
// update the FM content; OPNA is 13-bit with no intermediate clipping
m_fm.output(m_last_fm.clear(), 1, 32767, fmmask);
// mix in the ADPCM and clamp
m_adpcm_a.output(m_last_fm, 0x3f);
m_adpcm_b.output(m_last_fm, 1);
m_last_fm.clamp16();
}
//*********************************************************
// YMF288
//*********************************************************
// YMF288 is a YM2608 with the following changes:
// * ADPCM-B part removed
// * prescaler removed (fixed at 6)
// * CSM removed
// * Low power mode added
// * SSG tone frequency is altered in some way? (explicitly DC for Tp 0-7, also double volume in some cases)
// * I/O ports removed
// * Shorter busy times
// * All registers can be read
//-------------------------------------------------
// ymf288 - constructor
//-------------------------------------------------
ymf288::ymf288(ymfm_interface &intf) :
m_fidelity(OPN_FIDELITY_MAX),
m_address(0),
m_irq_enable(0x03),
m_flag_control(0x03),
m_fm(intf),
m_ssg(intf),
m_ssg_resampler(m_ssg),
m_adpcm_a(intf, 0)
{
m_last_fm.clear();
update_prescale();
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ymf288::reset()
{
// reset the engines
m_fm.reset();
m_ssg.reset();
m_adpcm_a.reset();
// configure ADPCM percussion sounds; these are present in an embedded ROM
m_adpcm_a.set_start_end(0, 0x0000, 0x01bf); // bass drum
m_adpcm_a.set_start_end(1, 0x01c0, 0x043f); // snare drum
m_adpcm_a.set_start_end(2, 0x0440, 0x1b7f); // top cymbal
m_adpcm_a.set_start_end(3, 0x1b80, 0x1cff); // high hat
m_adpcm_a.set_start_end(4, 0x1d00, 0x1f7f); // tom tom
m_adpcm_a.set_start_end(5, 0x1f80, 0x1fff); // rim shot
// initialize our special interrupt states, then read the upper status
// register, which updates the IRQs
m_irq_enable = 0x03;
m_flag_control = 0x00;
read_status_hi();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ymf288::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
state.save_restore(m_irq_enable);
state.save_restore(m_flag_control);
state.save_restore(m_last_fm.data);
m_fm.save_restore(state);
m_ssg.save_restore(state);
m_ssg_resampler.save_restore(state);
m_adpcm_a.save_restore(state);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ymf288::read_status()
{
uint8_t result = m_fm.status() & (fm_engine::STATUS_TIMERA | fm_engine::STATUS_TIMERB);
if (m_fm.intf().ymfm_is_busy())
result |= fm_engine::STATUS_BUSY;
return result;
}
//-------------------------------------------------
// read_data - read the data register
//-------------------------------------------------
uint8_t ymf288::read_data()
{
uint8_t result = 0;
if (m_address < 0x0e)
{
// 00-0D: Read from SSG
result = m_ssg.read(m_address & 0x0f);
}
else if (m_address < 0x10)
{
// 0E-0F: I/O ports not supported
result = 0xff;
}
else if (m_address == 0xff)
{
// FF: ID code
result = 2;
}
else if (ymf288_mode())
{
// registers are readable in YMF288 mode
result = m_fm.regs().read(m_address);
}
return result;
}
//-------------------------------------------------
// read_status_hi - read the extended status
// register
//-------------------------------------------------
uint8_t ymf288::read_status_hi()
{
// fetch regular status
uint8_t status = m_fm.status() & (fm_engine::STATUS_TIMERA | fm_engine::STATUS_TIMERB);
// turn off any bits that have been requested to be masked
status &= ~(m_flag_control & 0x03);
// update the status so that IRQs are propagated
m_fm.set_reset_status(status, ~status);
// merge in the busy flag
if (m_fm.intf().ymfm_is_busy())
status |= fm_engine::STATUS_BUSY;
return status;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ymf288::read(uint32_t offset)
{
uint8_t result = 0;
switch (offset & 3)
{
case 0: // status port, YM2203 compatible
result = read_status();
break;
case 1: // data port
result = read_data();
break;
case 2: // status port, extended
result = read_status_hi();
break;
case 3: // unmapped
debug::log_unexpected_read_write("Unexpected read from YMF288 offset %d\n", offset & 3);
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ymf288::write_address(uint8_t data)
{
// just set the address
m_address = data;
// in YMF288 mode, busy is signaled after address writes too
if (ymf288_mode())
m_fm.intf().ymfm_set_busy_end(16);
}
//-------------------------------------------------
// write - handle a write to the data register
//-------------------------------------------------
void ymf288::write_data(uint8_t data)
{
// ignore if paired with upper address
if (bitfield(m_address, 8))
return;
// wait times are shorter in YMF288 mode
int busy_cycles = ymf288_mode() ? 16 : 32 * m_fm.clock_prescale();
if (m_address < 0x0e)
{
// 00-0D: write to SSG
m_ssg.write(m_address & 0x0f, data);
}
else if (m_address < 0x10)
{
// 0E-0F: I/O ports not supported
}
else if (m_address < 0x20)
{
// 10-1F: write to ADPCM-A
m_adpcm_a.write(m_address & 0x0f, data);
busy_cycles = 32 * m_fm.clock_prescale();
}
else if (m_address == 0x27)
{
// 27: mode register; CSM isn't supported so disable it
data &= 0x7f;
m_fm.write(m_address, data);
}
else if (m_address == 0x29)
{
// 29: special IRQ mask register
m_irq_enable = data;
m_fm.set_irq_mask(m_irq_enable & ~m_flag_control & 0x03);
}
else
{
// 20-27, 2A-FF: write to FM
m_fm.write(m_address, data);
}
// mark busy for a bit
m_fm.intf().ymfm_set_busy_end(busy_cycles);
}
//-------------------------------------------------
// write_address_hi - handle a write to the upper
// address register
//-------------------------------------------------
void ymf288::write_address_hi(uint8_t data)
{
// just set the address
m_address = 0x100 | data;
// in YMF288 mode, busy is signaled after address writes too
if (ymf288_mode())
m_fm.intf().ymfm_set_busy_end(16);
}
//-------------------------------------------------
// write_data_hi - handle a write to the upper
// data register
//-------------------------------------------------
void ymf288::write_data_hi(uint8_t data)
{
// ignore if paired with upper address
if (!bitfield(m_address, 8))
return;
// wait times are shorter in YMF288 mode
int busy_cycles = ymf288_mode() ? 16 : 32 * m_fm.clock_prescale();
if (m_address == 0x110)
{
// 110: IRQ flag control
if (bitfield(data, 7))
m_fm.set_reset_status(0, 0xff);
else
{
m_flag_control = data;
m_fm.set_irq_mask(m_irq_enable & ~m_flag_control & 0x03);
}
}
else
{
// 100-10F,111-1FF: write to FM
m_fm.write(m_address, data);
}
// mark busy for a bit
m_fm.intf().ymfm_set_busy_end(busy_cycles);
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ymf288::write(uint32_t offset, uint8_t data)
{
switch (offset & 3)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
case 2: // upper address port
write_address_hi(data);
break;
case 3: // upper data port
write_data_hi(data);
break;
}
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void ymf288::generate(output_data *output, uint32_t numsamples)
{
// FM output is just repeated the prescale number of times; note that
// 0 is a special 1.5 case
if (m_fm_samples_per_output != 0)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
if ((m_ssg_resampler.sampindex() + samp) % m_fm_samples_per_output == 0)
clock_fm_and_adpcm();
output->data[0] = m_last_fm.data[0];
output->data[1] = m_last_fm.data[1];
}
}
else
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
uint32_t step = (m_ssg_resampler.sampindex() + samp) % 3;
if (step == 0)
clock_fm_and_adpcm();
output->data[0] = m_last_fm.data[0];
output->data[1] = m_last_fm.data[1];
if (step == 1)
{
clock_fm_and_adpcm();
output->data[0] = (output->data[0] + m_last_fm.data[0]) / 2;
output->data[1] = (output->data[1] + m_last_fm.data[1]) / 2;
}
}
}
// resample the SSG as configured
m_ssg_resampler.resample(output - numsamples, numsamples);
}
//-------------------------------------------------
// update_prescale - update the prescale value,
// recomputing derived values
//-------------------------------------------------
void ymf288::update_prescale()
{
// Fidelity: ---- minimum ---- ---- medium ----- ---- maximum-----
// rate = clock/144 rate = clock/144 rate = clock/16
// Prescale FM rate SSG rate FM rate SSG rate FM rate SSG rate
// 6 1:1 2:9 1:1 2:9 9:1 2:1
// compute the number of FM samples per output sample, and select the
// resampler function
if (m_fidelity == OPN_FIDELITY_MIN || m_fidelity == OPN_FIDELITY_MED)
{
m_fm_samples_per_output = 1;
m_ssg_resampler.configure(2, 9);
}
else
{
m_fm_samples_per_output = 9;
m_ssg_resampler.configure(2, 1);
}
// if overriding the SSG, override the configuration with the nop
// resampler to at least keep the sample index moving forward
if (m_ssg.overridden())
m_ssg_resampler.configure(0, 0);
}
//-------------------------------------------------
// clock_fm_and_adpcm - clock FM and ADPCM state
//-------------------------------------------------
void ymf288::clock_fm_and_adpcm()
{
// top bit of the IRQ enable flags controls 3-channel vs 6-channel mode
uint32_t fmmask = bitfield(m_irq_enable, 7) ? 0x3f : 0x07;
// clock the system
uint32_t env_counter = m_fm.clock(fm_engine::ALL_CHANNELS);
// clock the ADPCM-A engine on every envelope cycle
// (channels 4 and 5 clock every 2 envelope clocks)
if (bitfield(env_counter, 0, 2) == 0)
m_adpcm_a.clock(bitfield(env_counter, 2) ? 0x0f : 0x3f);
// update the FM content; OPNA is 13-bit with no intermediate clipping
m_fm.output(m_last_fm.clear(), 1, 32767, fmmask);
// mix in the ADPCM
m_adpcm_a.output(m_last_fm, 0x3f);
}
//*********************************************************
// YM2610
//*********************************************************
//-------------------------------------------------
// ym2610 - constructor
//-------------------------------------------------
ym2610::ym2610(ymfm_interface &intf, uint8_t channel_mask) :
m_fidelity(OPN_FIDELITY_MAX),
m_address(0),
m_fm_mask(channel_mask),
m_eos_status(0x00),
m_flag_mask(EOS_FLAGS_MASK),
m_fm(intf),
m_ssg(intf),
m_ssg_resampler(m_ssg),
m_adpcm_a(intf, 8),
m_adpcm_b(intf, 8)
{
update_prescale();
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ym2610::reset()
{
// reset the engines
m_fm.reset();
m_ssg.reset();
m_adpcm_a.reset();
m_adpcm_b.reset();
// initialize our special interrupt states
m_eos_status = 0x00;
m_flag_mask = EOS_FLAGS_MASK;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ym2610::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
state.save_restore(m_eos_status);
state.save_restore(m_flag_mask);
m_fm.save_restore(state);
m_ssg.save_restore(state);
m_ssg_resampler.save_restore(state);
m_adpcm_a.save_restore(state);
m_adpcm_b.save_restore(state);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ym2610::read_status()
{
uint8_t result = m_fm.status() & (fm_engine::STATUS_TIMERA | fm_engine::STATUS_TIMERB);
if (m_fm.intf().ymfm_is_busy())
result |= fm_engine::STATUS_BUSY;
return result;
}
//-------------------------------------------------
// read_data - read the data register
//-------------------------------------------------
uint8_t ym2610::read_data()
{
uint8_t result = 0;
if (m_address < 0x0e)
{
// 00-0D: Read from SSG
result = m_ssg.read(m_address & 0x0f);
}
else if (m_address < 0x10)
{
// 0E-0F: I/O ports not supported
result = 0xff;
}
else if (m_address == 0xff)
{
// FF: ID code
result = 1;
}
return result;
}
//-------------------------------------------------
// read_status_hi - read the extended status
// register
//-------------------------------------------------
uint8_t ym2610::read_status_hi()
{
return m_eos_status & m_flag_mask;
}
//-------------------------------------------------
// read_data_hi - read the upper data register
//-------------------------------------------------
uint8_t ym2610::read_data_hi()
{
uint8_t result = 0;
return result;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ym2610::read(uint32_t offset)
{
uint8_t result = 0;
switch (offset & 3)
{
case 0: // status port, YM2203 compatible
result = read_status();
break;
case 1: // data port (only SSG)
result = read_data();
break;
case 2: // status port, extended
result = read_status_hi();
break;
case 3: // ADPCM-B data
result = read_data_hi();
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ym2610::write_address(uint8_t data)
{
// just set the address
m_address = data;
}
//-------------------------------------------------
// write - handle a write to the data register
//-------------------------------------------------
void ym2610::write_data(uint8_t data)
{
// ignore if paired with upper address
if (bitfield(m_address, 8))
return;
if (m_address < 0x0e)
{
// 00-0D: write to SSG
m_ssg.write(m_address & 0x0f, data);
}
else if (m_address < 0x10)
{
// 0E-0F: I/O ports not supported
}
else if (m_address < 0x1c)
{
// 10-1B: write to ADPCM-B
// YM2610 effectively forces external mode on, and disables recording
if (m_address == 0x10)
data = (data | 0x20) & ~0x40;
m_adpcm_b.write(m_address & 0x0f, data);
}
else if (m_address == 0x1c)
{
// 1C: EOS flag reset
m_flag_mask = ~data & EOS_FLAGS_MASK;
m_eos_status &= ~(data & EOS_FLAGS_MASK);
}
else
{
// 1D-FF: write to FM
m_fm.write(m_address, data);
}
// mark busy for a bit
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
}
//-------------------------------------------------
// write_address_hi - handle a write to the upper
// address register
//-------------------------------------------------
void ym2610::write_address_hi(uint8_t data)
{
// just set the address
m_address = 0x100 | data;
}
//-------------------------------------------------
// write_data_hi - handle a write to the upper
// data register
//-------------------------------------------------
void ym2610::write_data_hi(uint8_t data)
{
// ignore if paired with upper address
if (!bitfield(m_address, 8))
return;
if (m_address < 0x130)
{
// 100-12F: write to ADPCM-A
m_adpcm_a.write(m_address & 0x3f, data);
}
else
{
// 130-1FF: write to FM
m_fm.write(m_address, data);
}
// mark busy for a bit
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym2610::write(uint32_t offset, uint8_t data)
{
switch (offset & 3)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
case 2: // upper address port
write_address_hi(data);
break;
case 3: // upper data port
write_data_hi(data);
break;
}
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void ym2610::generate(output_data *output, uint32_t numsamples)
{
// FM output is just repeated the prescale number of times
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
if ((m_ssg_resampler.sampindex() + samp) % m_fm_samples_per_output == 0)
clock_fm_and_adpcm();
output->data[0] = m_last_fm.data[0];
output->data[1] = m_last_fm.data[1];
}
// resample the SSG as configured
m_ssg_resampler.resample(output - numsamples, numsamples);
}
//-------------------------------------------------
// update_prescale - update the prescale value,
// recomputing derived values
//-------------------------------------------------
void ym2610::update_prescale()
{
// Fidelity: ---- minimum ---- ---- medium ----- ---- maximum-----
// rate = clock/144 rate = clock/144 rate = clock/16
// Prescale FM rate SSG rate FM rate SSG rate FM rate SSG rate
// 6 1:1 2:9 1:1 2:9 9:1 2:1
// compute the number of FM samples per output sample, and select the
// resampler function
if (m_fidelity == OPN_FIDELITY_MIN || m_fidelity == OPN_FIDELITY_MED)
{
m_fm_samples_per_output = 1;
m_ssg_resampler.configure(2, 9);
}
else
{
m_fm_samples_per_output = 9;
m_ssg_resampler.configure(2, 1);
}
// if overriding the SSG, override the configuration with the nop
// resampler to at least keep the sample index moving forward
if (m_ssg.overridden())
m_ssg_resampler.configure(0, 0);
}
//-------------------------------------------------
// clock_fm_and_adpcm - clock FM and ADPCM state
//-------------------------------------------------
void ym2610::clock_fm_and_adpcm()
{
// clock the system
uint32_t env_counter = m_fm.clock(m_fm_mask);
// clock the ADPCM-A engine on every envelope cycle
if (bitfield(env_counter, 0, 2) == 0)
m_eos_status |= m_adpcm_a.clock(0x3f);
// clock the ADPCM-B engine every cycle
m_adpcm_b.clock();
// we track the last ADPCM-B EOS value in bit 6 (which is hidden from callers);
// if it changed since the last sample, update the visible EOS state in bit 7
uint8_t live_eos = ((m_adpcm_b.status() & adpcm_b_channel::STATUS_EOS) != 0) ? 0x40 : 0x00;
if (((live_eos ^ m_eos_status) & 0x40) != 0)
m_eos_status = (m_eos_status & ~0xc0) | live_eos | (live_eos << 1);
// update the FM content; OPNB is 13-bit with no intermediate clipping
m_fm.output(m_last_fm.clear(), 1, 32767, m_fm_mask);
// mix in the ADPCM and clamp
m_adpcm_a.output(m_last_fm, 0x3f);
m_adpcm_b.output(m_last_fm, 1);
m_last_fm.clamp16();
}
//*********************************************************
// YM2612
//*********************************************************
//-------------------------------------------------
// ym2612 - constructor
//-------------------------------------------------
ym2612::ym2612(ymfm_interface &intf) :
m_address(0),
m_dac_data(0),
m_dac_enable(0),
m_fm(intf)
{
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ym2612::reset()
{
// reset the engines
m_fm.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ym2612::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_address);
state.save_restore(m_dac_data);
state.save_restore(m_dac_enable);
m_fm.save_restore(state);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ym2612::read_status()
{
uint8_t result = m_fm.status();
if (m_fm.intf().ymfm_is_busy())
result |= fm_engine::STATUS_BUSY;
return result;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ym2612::read(uint32_t offset)
{
uint8_t result = 0;
switch (offset & 3)
{
case 0: // status port, YM2203 compatible
result = read_status();
break;
case 1: // data port (unused)
case 2: // status port, extended
case 3: // data port (unused)
debug::log_unexpected_read_write("Unexpected read from YM2612 offset %d\n", offset & 3);
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ym2612::write_address(uint8_t data)
{
// just set the address
m_address = data;
}
//-------------------------------------------------
// write_data - handle a write to the data
// register
//-------------------------------------------------
void ym2612::write_data(uint8_t data)
{
// ignore if paired with upper address
if (bitfield(m_address, 8))
return;
if (m_address == 0x2a)
{
// 2A: DAC data (most significant 8 bits)
m_dac_data = (m_dac_data & ~0x1fe) | ((data ^ 0x80) << 1);
}
else if (m_address == 0x2b)
{
// 2B: DAC enable (bit 7)
m_dac_enable = bitfield(data, 7);
}
else if (m_address == 0x2c)
{
// 2C: test/low DAC bit
m_dac_data = (m_dac_data & ~1) | bitfield(data, 3);
}
else
{
// 00-29, 2D-FF: write to FM
m_fm.write(m_address, data);
}
// mark busy for a bit
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
}
//-------------------------------------------------
// write_address_hi - handle a write to the upper
// address register
//-------------------------------------------------
void ym2612::write_address_hi(uint8_t data)
{
// just set the address
m_address = 0x100 | data;
}
//-------------------------------------------------
// write_data_hi - handle a write to the upper
// data register
//-------------------------------------------------
void ym2612::write_data_hi(uint8_t data)
{
// ignore if paired with upper address
if (!bitfield(m_address, 8))
return;
// 100-1FF: write to FM
m_fm.write(m_address, data);
// mark busy for a bit
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym2612::write(uint32_t offset, uint8_t data)
{
switch (offset & 3)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
case 2: // upper address port
write_address_hi(data);
break;
case 3: // upper data port
write_data_hi(data);
break;
}
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void ym2612::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// sum individual channels to apply DAC discontinuity on each
output->clear();
output_data temp;
// first do FM-only channels; OPN2 is 9-bit with intermediate clipping
int const last_fm_channel = m_dac_enable ? 5 : 6;
for (int chan = 0; chan < last_fm_channel; chan++)
{
m_fm.output(temp.clear(), 5, 256, 1 << chan);
output->data[0] += dac_discontinuity(temp.data[0]);
output->data[1] += dac_discontinuity(temp.data[1]);
}
// add in DAC
if (m_dac_enable)
{
// DAC enabled: start with DAC value then add the first 5 channels only
int32_t dacval = dac_discontinuity(int16_t(m_dac_data << 7) >> 7);
output->data[0] += m_fm.regs().ch_output_0(0x102) ? dacval : dac_discontinuity(0);
output->data[1] += m_fm.regs().ch_output_1(0x102) ? dacval : dac_discontinuity(0);
}
// output is technically multiplexed rather than mixed, but that requires
// a better sound mixer than we usually have, so just average over the six
// channels; also apply a 64/65 factor to account for the discontinuity
// adjustment above
output->data[0] = (output->data[0] * 128) * 64 / (6 * 65);
output->data[1] = (output->data[1] * 128) * 64 / (6 * 65);
}
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void ym3438::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// first do FM-only channels; OPN2C is 9-bit with intermediate clipping
if (!m_dac_enable)
{
// DAC disabled: all 6 channels sum together
m_fm.output(output->clear(), 5, 256, fm_engine::ALL_CHANNELS);
}
else
{
// DAC enabled: start with DAC value then add the first 5 channels only
int32_t dacval = int16_t(m_dac_data << 7) >> 7;
output->data[0] = m_fm.regs().ch_output_0(0x102) ? dacval : 0;
output->data[1] = m_fm.regs().ch_output_1(0x102) ? dacval : 0;
m_fm.output(*output, 5, 256, fm_engine::ALL_CHANNELS ^ (1 << 5));
}
// YM3438 doesn't have the same DAC discontinuity, though its output is
// multiplexed like the YM2612
output->data[0] = (output->data[0] * 128) / 6;
output->data[1] = (output->data[1] * 128) / 6;
}
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void ymf276::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// first do FM-only channels; OPN2L is 14-bit with intermediate clipping
if (!m_dac_enable)
{
// DAC disabled: all 6 channels sum together
m_fm.output(output->clear(), 0, 8191, fm_engine::ALL_CHANNELS);
}
else
{
// DAC enabled: start with DAC value then add the first 5 channels only
int32_t dacval = int16_t(m_dac_data << 7) >> 7;
output->data[0] = m_fm.regs().ch_output_0(0x102) ? dacval : 0;
output->data[1] = m_fm.regs().ch_output_1(0x102) ? dacval : 0;
m_fm.output(*output, 0, 8191, fm_engine::ALL_CHANNELS ^ (1 << 5));
}
// YMF276 is properly mixed; it shifts down 1 bit before clamping
output->data[0] = clamp(output->data[0] >> 1, -32768, 32767);
output->data[1] = clamp(output->data[1] >> 1, -32768, 32767);
}
}
}
``` | /content/code_sandbox/src/sound/ymfm/ymfm_opn.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 19,181 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_OPL_H
#define YMFM_OPL_H
#pragma once
#include "ymfm.h"
#include "ymfm_adpcm.h"
#include "ymfm_fm.h"
#include "ymfm_pcm.h"
namespace ymfm
{
//*********************************************************
// REGISTER CLASSES
//*********************************************************
// ======================> opl_registers_base
//
// OPL/OPL2/OPL3/OPL4 register map:
//
// System-wide registers:
// 01 xxxxxxxx Test register
// --x----- Enable OPL compatibility mode [OPL2 only] (1 = enable)
// 02 xxxxxxxx Timer A value (4 * OPN)
// 03 xxxxxxxx Timer B value
// 04 x------- RST
// -x------ Mask timer A
// --x----- Mask timer B
// ------x- Load timer B
// -------x Load timer A
// 08 x------- CSM mode [OPL/OPL2 only]
// -x------ Note select
// BD x------- AM depth
// -x------ PM depth
// --x----- Rhythm enable
// ---x---- Bass drum key on
// ----x--- Snare drum key on
// -----x-- Tom key on
// ------x- Top cymbal key on
// -------x High hat key on
// 101 --xxxxxx Test register 2 [OPL3 only]
// 104 --x----- Channel 6 4-operator mode [OPL3 only]
// ---x---- Channel 5 4-operator mode [OPL3 only]
// ----x--- Channel 4 4-operator mode [OPL3 only]
// -----x-- Channel 3 4-operator mode [OPL3 only]
// ------x- Channel 2 4-operator mode [OPL3 only]
// -------x Channel 1 4-operator mode [OPL3 only]
// 105 -------x New [OPL3 only]
// ------x- New2 [OPL4 only]
//
// Per-channel registers (channel in address bits 0-3)
// Note that all these apply to address+100 as well on OPL3+
// A0-A8 xxxxxxxx F-number (low 8 bits)
// B0-B8 --x----- Key on
// ---xxx-- Block (octvate, 0-7)
// ------xx F-number (high two bits)
// C0-C8 x------- CHD output (to DO0 pin) [OPL3+ only]
// -x------ CHC output (to DO0 pin) [OPL3+ only]
// --x----- CHB output (mixed right, to DO2 pin) [OPL3+ only]
// ---x---- CHA output (mixed left, to DO2 pin) [OPL3+ only]
// ----xxx- Feedback level for operator 1 (0-7)
// -------x Operator connection algorithm
//
// Per-operator registers (operator in bits 0-5)
// Note that all these apply to address+100 as well on OPL3+
// 20-35 x------- AM enable
// -x------ PM enable (VIB)
// --x----- EG type
// ---x---- Key scale rate
// ----xxxx Multiple value (0-15)
// 40-55 xx------ Key scale level (0-3)
// --xxxxxx Total level (0-63)
// 60-75 xxxx---- Attack rate (0-15)
// ----xxxx Decay rate (0-15)
// 80-95 xxxx---- Sustain level (0-15)
// ----xxxx Release rate (0-15)
// E0-F5 ------xx Wave select (0-3) [OPL2 only]
// -----xxx Wave select (0-7) [OPL3+ only]
//
template<int Revision>
class opl_registers_base : public fm_registers_base
{
static constexpr bool IsOpl2 = (Revision == 2);
static constexpr bool IsOpl2Plus = (Revision >= 2);
static constexpr bool IsOpl3Plus = (Revision >= 3);
static constexpr bool IsOpl4Plus = (Revision >= 4);
public:
// constants
static constexpr uint32_t OUTPUTS = IsOpl3Plus ? 4 : 1;
static constexpr uint32_t CHANNELS = IsOpl3Plus ? 18 : 9;
static constexpr uint32_t ALL_CHANNELS = (1 << CHANNELS) - 1;
static constexpr uint32_t OPERATORS = CHANNELS * 2;
static constexpr uint32_t WAVEFORMS = IsOpl3Plus ? 8 : (IsOpl2Plus ? 4 : 1);
static constexpr uint32_t REGISTERS = IsOpl3Plus ? 0x200 : 0x100;
static constexpr uint32_t REG_MODE = 0x04;
static constexpr uint32_t DEFAULT_PRESCALE = IsOpl4Plus ? 19 : (IsOpl3Plus ? 8 : 4);
static constexpr uint32_t EG_CLOCK_DIVIDER = 1;
static constexpr uint32_t CSM_TRIGGER_MASK = ALL_CHANNELS;
static constexpr bool DYNAMIC_OPS = IsOpl3Plus;
static constexpr bool MODULATOR_DELAY = !IsOpl3Plus;
static constexpr uint8_t STATUS_TIMERA = 0x40;
static constexpr uint8_t STATUS_TIMERB = 0x20;
static constexpr uint8_t STATUS_BUSY = 0;
static constexpr uint8_t STATUS_IRQ = 0x80;
// constructor
opl_registers_base();
// reset to initial state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// map channel number to register offset
static constexpr uint32_t channel_offset(uint32_t chnum)
{
assert(chnum < CHANNELS);
if (!IsOpl3Plus)
return chnum;
else
return (chnum % 9) + 0x100 * (chnum / 9);
}
// map operator number to register offset
static constexpr uint32_t operator_offset(uint32_t opnum)
{
assert(opnum < OPERATORS);
if (!IsOpl3Plus)
return opnum + 2 * (opnum / 6);
else
return (opnum % 18) + 2 * ((opnum % 18) / 6) + 0x100 * (opnum / 18);
}
// return an array of operator indices for each channel
struct operator_mapping { uint32_t chan[CHANNELS]; };
void operator_map(operator_mapping &dest) const;
// OPL4 apparently can read back FM registers?
uint8_t read(uint16_t index) const { return m_regdata[index]; }
// handle writes to the register array
bool write(uint16_t index, uint8_t data, uint32_t &chan, uint32_t &opmask);
// clock the noise and LFO, if present, returning LFO PM value
int32_t clock_noise_and_lfo();
// reset the LFO
void reset_lfo() { m_lfo_am_counter = m_lfo_pm_counter = 0; }
// return the AM offset from LFO for the given channel
// on OPL this is just a fixed value
uint32_t lfo_am_offset(uint32_t choffs) const { return m_lfo_am; }
// return LFO/noise states
uint32_t noise_state() const { return m_noise_lfsr >> 23; }
// caching helpers
void cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache);
// compute the phase step, given a PM value
uint32_t compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm);
// log a key-on event
std::string log_keyon(uint32_t choffs, uint32_t opoffs);
// system-wide registers
uint32_t test() const { return byte(0x01, 0, 8); }
uint32_t waveform_enable() const { return IsOpl2 ? byte(0x01, 5, 1) : (IsOpl3Plus ? 1 : 0); }
uint32_t timer_a_value() const { return byte(0x02, 0, 8) * 4; } // 8->10 bits
uint32_t timer_b_value() const { return byte(0x03, 0, 8); }
uint32_t status_mask() const { return byte(0x04, 0, 8) & 0x78; }
uint32_t irq_reset() const { return byte(0x04, 7, 1); }
uint32_t reset_timer_b() const { return byte(0x04, 7, 1) | byte(0x04, 5, 1); }
uint32_t reset_timer_a() const { return byte(0x04, 7, 1) | byte(0x04, 6, 1); }
uint32_t enable_timer_b() const { return 1; }
uint32_t enable_timer_a() const { return 1; }
uint32_t load_timer_b() const { return byte(0x04, 1, 1); }
uint32_t load_timer_a() const { return byte(0x04, 0, 1); }
uint32_t csm() const { return IsOpl3Plus ? 0 : byte(0x08, 7, 1); }
uint32_t note_select() const { return byte(0x08, 6, 1); }
uint32_t lfo_am_depth() const { return byte(0xbd, 7, 1); }
uint32_t lfo_pm_depth() const { return byte(0xbd, 6, 1); }
uint32_t rhythm_enable() const { return byte(0xbd, 5, 1); }
uint32_t rhythm_keyon() const { return byte(0xbd, 4, 0); }
uint32_t newflag() const { return IsOpl3Plus ? byte(0x105, 0, 1) : 0; }
uint32_t new2flag() const { return IsOpl4Plus ? byte(0x105, 1, 1) : 0; }
uint32_t fourop_enable() const { return IsOpl3Plus ? byte(0x104, 0, 6) : 0; }
// per-channel registers
uint32_t ch_block_freq(uint32_t choffs) const { return word(0xb0, 0, 5, 0xa0, 0, 8, choffs); }
uint32_t ch_feedback(uint32_t choffs) const { return byte(0xc0, 1, 3, choffs); }
uint32_t ch_algorithm(uint32_t choffs) const { return byte(0xc0, 0, 1, choffs) | (IsOpl3Plus ? (8 | (byte(0xc3, 0, 1, choffs) << 1)) : 0); }
uint32_t ch_output_any(uint32_t choffs) const { return newflag() ? byte(0xc0 + choffs, 4, 4) : 1; }
uint32_t ch_output_0(uint32_t choffs) const { return newflag() ? byte(0xc0 + choffs, 4, 1) : 1; }
uint32_t ch_output_1(uint32_t choffs) const { return newflag() ? byte(0xc0 + choffs, 5, 1) : (IsOpl3Plus ? 1 : 0); }
uint32_t ch_output_2(uint32_t choffs) const { return newflag() ? byte(0xc0 + choffs, 6, 1) : 0; }
uint32_t ch_output_3(uint32_t choffs) const { return newflag() ? byte(0xc0 + choffs, 7, 1) : 0; }
// per-operator registers
uint32_t op_lfo_am_enable(uint32_t opoffs) const { return byte(0x20, 7, 1, opoffs); }
uint32_t op_lfo_pm_enable(uint32_t opoffs) const { return byte(0x20, 6, 1, opoffs); }
uint32_t op_eg_sustain(uint32_t opoffs) const { return byte(0x20, 5, 1, opoffs); }
uint32_t op_ksr(uint32_t opoffs) const { return byte(0x20, 4, 1, opoffs); }
uint32_t op_multiple(uint32_t opoffs) const { return byte(0x20, 0, 4, opoffs); }
uint32_t op_ksl(uint32_t opoffs) const { uint32_t temp = byte(0x40, 6, 2, opoffs); return bitfield(temp, 1) | (bitfield(temp, 0) << 1); }
uint32_t op_total_level(uint32_t opoffs) const { return byte(0x40, 0, 6, opoffs); }
uint32_t op_attack_rate(uint32_t opoffs) const { return byte(0x60, 4, 4, opoffs); }
uint32_t op_decay_rate(uint32_t opoffs) const { return byte(0x60, 0, 4, opoffs); }
uint32_t op_sustain_level(uint32_t opoffs) const { return byte(0x80, 4, 4, opoffs); }
uint32_t op_release_rate(uint32_t opoffs) const { return byte(0x80, 0, 4, opoffs); }
uint32_t op_waveform(uint32_t opoffs) const { return IsOpl2Plus ? byte(0xe0, 0, newflag() ? 3 : 2, opoffs) : 0; }
protected:
// return a bitfield extracted from a byte
uint32_t byte(uint32_t offset, uint32_t start, uint32_t count, uint32_t extra_offset = 0) const
{
return bitfield(m_regdata[offset + extra_offset], start, count);
}
// return a bitfield extracted from a pair of bytes, MSBs listed first
uint32_t word(uint32_t offset1, uint32_t start1, uint32_t count1, uint32_t offset2, uint32_t start2, uint32_t count2, uint32_t extra_offset = 0) const
{
return (byte(offset1, start1, count1, extra_offset) << count2) | byte(offset2, start2, count2, extra_offset);
}
// helper to determine if the this channel is an active rhythm channel
bool is_rhythm(uint32_t choffs) const
{
return rhythm_enable() && (choffs >= 6 && choffs <= 8);
}
// internal state
uint16_t m_lfo_am_counter; // LFO AM counter
uint16_t m_lfo_pm_counter; // LFO PM counter
uint32_t m_noise_lfsr; // noise LFSR state
uint8_t m_lfo_am; // current LFO AM value
uint8_t m_regdata[REGISTERS]; // register data
uint16_t m_waveform[WAVEFORMS][WAVEFORM_LENGTH]; // waveforms
};
using opl_registers = opl_registers_base<1>;
using opl2_registers = opl_registers_base<2>;
using opl3_registers = opl_registers_base<3>;
using opl4_registers = opl_registers_base<4>;
// ======================> opll_registers
//
// OPLL register map:
//
// System-wide registers:
// 0E --x----- Rhythm enable
// ---x---- Bass drum key on
// ----x--- Snare drum key on
// -----x-- Tom key on
// ------x- Top cymbal key on
// -------x High hat key on
// 0F xxxxxxxx Test register
//
// Per-channel registers (channel in address bits 0-3)
// 10-18 xxxxxxxx F-number (low 8 bits)
// 20-28 --x----- Sustain on
// ---x---- Key on
// --- xxx- Block (octvate, 0-7)
// -------x F-number (high bit)
// 30-38 xxxx---- Instrument selection
// ----xxxx Volume
//
// User instrument registers (for carrier, modulator operators)
// 00-01 x------- AM enable
// -x------ PM enable (VIB)
// --x----- EG type
// ---x---- Key scale rate
// ----xxxx Multiple value (0-15)
// 02 xx------ Key scale level (carrier, 0-3)
// --xxxxxx Total level (modulator, 0-63)
// 03 xx------ Key scale level (modulator, 0-3)
// ---x---- Rectified wave (carrier)
// ----x--- Rectified wave (modulator)
// -----xxx Feedback level for operator 1 (0-7)
// 04-05 xxxx---- Attack rate (0-15)
// ----xxxx Decay rate (0-15)
// 06-07 xxxx---- Sustain level (0-15)
// ----xxxx Release rate (0-15)
//
// Internal (fake) registers:
// 40-48 xxxxxxxx Current instrument base address
// 4E-5F xxxxxxxx Current instrument base address + operator slot (0/1)
// 70-FF xxxxxxxx Data for instruments (1-16 plus 3 drums)
//
class opll_registers : public fm_registers_base
{
public:
static constexpr uint32_t OUTPUTS = 2;
static constexpr uint32_t CHANNELS = 9;
static constexpr uint32_t ALL_CHANNELS = (1 << CHANNELS) - 1;
static constexpr uint32_t OPERATORS = CHANNELS * 2;
static constexpr uint32_t WAVEFORMS = 2;
static constexpr uint32_t REGISTERS = 0x40;
static constexpr uint32_t REG_MODE = 0x3f;
static constexpr uint32_t DEFAULT_PRESCALE = 4;
static constexpr uint32_t EG_CLOCK_DIVIDER = 1;
static constexpr uint32_t CSM_TRIGGER_MASK = 0;
static constexpr bool EG_HAS_DEPRESS = true;
static constexpr bool MODULATOR_DELAY = true;
static constexpr uint8_t STATUS_TIMERA = 0;
static constexpr uint8_t STATUS_TIMERB = 0;
static constexpr uint8_t STATUS_BUSY = 0;
static constexpr uint8_t STATUS_IRQ = 0;
// OPLL-specific constants
static constexpr uint32_t INSTDATA_SIZE = 0x90;
// constructor
opll_registers();
// reset to initial state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// map channel number to register offset
static constexpr uint32_t channel_offset(uint32_t chnum)
{
assert(chnum < CHANNELS);
return chnum;
}
// map operator number to register offset
static constexpr uint32_t operator_offset(uint32_t opnum)
{
assert(opnum < OPERATORS);
return opnum;
}
// return an array of operator indices for each channel
struct operator_mapping { uint32_t chan[CHANNELS]; };
void operator_map(operator_mapping &dest) const;
// read a register value
uint8_t read(uint16_t index) const { return m_regdata[index]; }
// handle writes to the register array
bool write(uint16_t index, uint8_t data, uint32_t &chan, uint32_t &opmask);
// clock the noise and LFO, if present, returning LFO PM value
int32_t clock_noise_and_lfo();
// reset the LFO
void reset_lfo() { m_lfo_am_counter = m_lfo_pm_counter = 0; }
// return the AM offset from LFO for the given channel
// on OPL this is just a fixed value
uint32_t lfo_am_offset(uint32_t choffs) const { return m_lfo_am; }
// return LFO/noise states
uint32_t noise_state() const { return m_noise_lfsr >> 23; }
// caching helpers
void cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache);
// compute the phase step, given a PM value
uint32_t compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm);
// log a key-on event
std::string log_keyon(uint32_t choffs, uint32_t opoffs);
// set the instrument data
void set_instrument_data(uint8_t const *data)
{
std::copy_n(data, INSTDATA_SIZE, &m_instdata[0]);
}
// system-wide registers
uint32_t rhythm_enable() const { return byte(0x0e, 5, 1); }
uint32_t rhythm_keyon() const { return byte(0x0e, 4, 0); }
uint32_t test() const { return byte(0x0f, 0, 8); }
uint32_t waveform_enable() const { return 1; }
uint32_t timer_a_value() const { return 0; }
uint32_t timer_b_value() const { return 0; }
uint32_t status_mask() const { return 0; }
uint32_t irq_reset() const { return 0; }
uint32_t reset_timer_b() const { return 0; }
uint32_t reset_timer_a() const { return 0; }
uint32_t enable_timer_b() const { return 0; }
uint32_t enable_timer_a() const { return 0; }
uint32_t load_timer_b() const { return 0; }
uint32_t load_timer_a() const { return 0; }
uint32_t csm() const { return 0; }
// per-channel registers
uint32_t ch_block_freq(uint32_t choffs) const { return word(0x20, 0, 4, 0x10, 0, 8, choffs); }
uint32_t ch_sustain(uint32_t choffs) const { return byte(0x20, 5, 1, choffs); }
uint32_t ch_total_level(uint32_t choffs) const { return instchbyte(0x02, 0, 6, choffs); }
uint32_t ch_feedback(uint32_t choffs) const { return instchbyte(0x03, 0, 3, choffs); }
uint32_t ch_algorithm(uint32_t choffs) const { return 0; }
uint32_t ch_instrument(uint32_t choffs) const { return byte(0x30, 4, 4, choffs); }
uint32_t ch_output_any(uint32_t choffs) const { return 1; }
uint32_t ch_output_0(uint32_t choffs) const { return !is_rhythm(choffs); }
uint32_t ch_output_1(uint32_t choffs) const { return is_rhythm(choffs); }
uint32_t ch_output_2(uint32_t choffs) const { return 0; }
uint32_t ch_output_3(uint32_t choffs) const { return 0; }
// per-operator registers
uint32_t op_lfo_am_enable(uint32_t opoffs) const { return instopbyte(0x00, 7, 1, opoffs); }
uint32_t op_lfo_pm_enable(uint32_t opoffs) const { return instopbyte(0x00, 6, 1, opoffs); }
uint32_t op_eg_sustain(uint32_t opoffs) const { return instopbyte(0x00, 5, 1, opoffs); }
uint32_t op_ksr(uint32_t opoffs) const { return instopbyte(0x00, 4, 1, opoffs); }
uint32_t op_multiple(uint32_t opoffs) const { return instopbyte(0x00, 0, 4, opoffs); }
uint32_t op_ksl(uint32_t opoffs) const { return instopbyte(0x02, 6, 2, opoffs); }
uint32_t op_waveform(uint32_t opoffs) const { return instchbyte(0x03, 3 + bitfield(opoffs, 0), 1, opoffs >> 1); }
uint32_t op_attack_rate(uint32_t opoffs) const { return instopbyte(0x04, 4, 4, opoffs); }
uint32_t op_decay_rate(uint32_t opoffs) const { return instopbyte(0x04, 0, 4, opoffs); }
uint32_t op_sustain_level(uint32_t opoffs) const { return instopbyte(0x06, 4, 4, opoffs); }
uint32_t op_release_rate(uint32_t opoffs) const { return instopbyte(0x06, 0, 4, opoffs); }
uint32_t op_volume(uint32_t opoffs) const { return byte(0x30, 4 * bitfield(~opoffs, 0), 4, opoffs >> 1); }
private:
// return a bitfield extracted from a byte
uint32_t byte(uint32_t offset, uint32_t start, uint32_t count, uint32_t extra_offset = 0) const
{
return bitfield(m_regdata[offset + extra_offset], start, count);
}
// return a bitfield extracted from a pair of bytes, MSBs listed first
uint32_t word(uint32_t offset1, uint32_t start1, uint32_t count1, uint32_t offset2, uint32_t start2, uint32_t count2, uint32_t extra_offset = 0) const
{
return (byte(offset1, start1, count1, extra_offset) << count2) | byte(offset2, start2, count2, extra_offset);
}
// helpers to read from instrument channel/operator data
uint32_t instchbyte(uint32_t offset, uint32_t start, uint32_t count, uint32_t choffs) const { return bitfield(m_chinst[choffs][offset], start, count); }
uint32_t instopbyte(uint32_t offset, uint32_t start, uint32_t count, uint32_t opoffs) const { return bitfield(m_opinst[opoffs][offset], start, count); }
// helper to determine if the this channel is an active rhythm channel
bool is_rhythm(uint32_t choffs) const
{
return rhythm_enable() && choffs >= 6;
}
// internal state
uint16_t m_lfo_am_counter; // LFO AM counter
uint16_t m_lfo_pm_counter; // LFO PM counter
uint32_t m_noise_lfsr; // noise LFSR state
uint8_t m_lfo_am; // current LFO AM value
uint8_t const *m_chinst[CHANNELS]; // pointer to instrument data for each channel
uint8_t const *m_opinst[OPERATORS]; // pointer to instrument data for each operator
uint8_t m_regdata[REGISTERS]; // register data
uint8_t m_instdata[INSTDATA_SIZE]; // instrument data
uint16_t m_waveform[WAVEFORMS][WAVEFORM_LENGTH]; // waveforms
};
//*********************************************************
// OPL IMPLEMENTATION CLASSES
//*********************************************************
// ======================> ym3526
class ym3526
{
public:
using fm_engine = fm_engine_base<opl_registers>;
using output_data = fm_engine::output_data;
static constexpr uint32_t OUTPUTS = fm_engine::OUTPUTS;
// constructor
ym3526(ymfm_interface &intf);
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return m_fm.sample_rate(input_clock); }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate samples of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal state
uint8_t m_address; // address register
fm_engine m_fm; // core FM engine
};
// ======================> y8950
class y8950
{
public:
using fm_engine = fm_engine_base<opl_registers>;
using output_data = fm_engine::output_data;
static constexpr uint32_t OUTPUTS = fm_engine::OUTPUTS;
static constexpr uint8_t STATUS_ADPCM_B_PLAYING = 0x01;
static constexpr uint8_t STATUS_ADPCM_B_BRDY = 0x08;
static constexpr uint8_t STATUS_ADPCM_B_EOS = 0x10;
static constexpr uint8_t ALL_IRQS = STATUS_ADPCM_B_BRDY | STATUS_ADPCM_B_EOS | fm_engine::STATUS_TIMERA | fm_engine::STATUS_TIMERB;
// constructor
y8950(ymfm_interface &intf);
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return m_fm.sample_rate(input_clock); }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read_data();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate samples of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal state
uint8_t m_address; // address register
uint8_t m_io_ddr; // data direction register for I/O
fm_engine m_fm; // core FM engine
adpcm_b_engine m_adpcm_b; // ADPCM-B engine
};
//*********************************************************
// OPL2 IMPLEMENTATION CLASSES
//*********************************************************
// ======================> ym3812
class ym3812
{
public:
using fm_engine = fm_engine_base<opl2_registers>;
using output_data = fm_engine::output_data;
static constexpr uint32_t OUTPUTS = fm_engine::OUTPUTS;
// constructor
ym3812(ymfm_interface &intf);
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return m_fm.sample_rate(input_clock); }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate samples of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal state
uint8_t m_address; // address register
fm_engine m_fm; // core FM engine
};
//*********************************************************
// OPL3 IMPLEMENTATION CLASSES
//*********************************************************
// ======================> ymf262
class ymf262
{
public:
using fm_engine = fm_engine_base<opl3_registers>;
using output_data = fm_engine::output_data;
static constexpr uint32_t OUTPUTS = fm_engine::OUTPUTS;
// constructor
ymf262(ymfm_interface &intf);
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return m_fm.sample_rate(input_clock); }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write_address_hi(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate samples of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal state
uint16_t m_address; // address register
fm_engine m_fm; // core FM engine
};
// ======================> ymf289b
class ymf289b
{
static constexpr uint8_t STATUS_BUSY_FLAGS = 0x05;
public:
using fm_engine = fm_engine_base<opl3_registers>;
using output_data = fm_engine::output_data;
static constexpr uint32_t OUTPUTS = 2;
// constructor
ymf289b(ymfm_interface &intf);
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return m_fm.sample_rate(input_clock); }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read_data();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write_address_hi(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate samples of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal helpers
bool ymf289b_mode() { return ((m_fm.regs().read(0x105) & 0x04) != 0); }
// internal state
uint16_t m_address; // address register
fm_engine m_fm; // core FM engine
};
//*********************************************************
// OPL4 IMPLEMENTATION CLASSES
//*********************************************************
// ======================> ymf278b
class ymf278b
{
// Using the nominal datasheet frequency of 33.868MHz, the output of the
// chip will be clock/768 = 44.1kHz. However, the FM engine is clocked
// internally at clock/(19*36), or 49.515kHz, so the FM output needs to
// be downsampled. We treat this as needing to clock the FM engine an
// extra tick every few samples. The exact ratio is 768/(19*36) or
// 768/684 = 192/171. So if we always clock the FM once, we'll have
// 192/171 - 1 = 21/171 left. Thus we count 21 for each sample and when
// it gets above 171, we tick an extra time.
static constexpr uint32_t FM_EXTRA_SAMPLE_THRESH = 171;
static constexpr uint32_t FM_EXTRA_SAMPLE_STEP = 192 - FM_EXTRA_SAMPLE_THRESH;
public:
using fm_engine = fm_engine_base<opl4_registers>;
static constexpr uint32_t OUTPUTS = 6;
using output_data = ymfm_output<OUTPUTS>;
static constexpr uint8_t STATUS_BUSY = 0x01;
static constexpr uint8_t STATUS_LD = 0x02;
// constructor
ymf278b(ymfm_interface &intf);
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return input_clock / 768; }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read_data_pcm();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write_address_hi(uint8_t data);
void write_address_pcm(uint8_t data);
void write_data_pcm(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate samples of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal state
uint16_t m_address; // address register
uint32_t m_fm_pos; // FM resampling position
uint32_t m_load_remaining; // how many more samples until LD flag clears
bool m_next_status_id; // flag to track which status ID to return
fm_engine m_fm; // core FM engine
pcm_engine m_pcm; // core PCM engine
};
//*********************************************************
// OPLL IMPLEMENTATION CLASSES
//*********************************************************
// ======================> opll_base
class opll_base
{
public:
using fm_engine = fm_engine_base<opll_registers>;
using output_data = fm_engine::output_data;
static constexpr uint32_t OUTPUTS = fm_engine::OUTPUTS;
// constructor
opll_base(ymfm_interface &intf, uint8_t const *data);
// configuration
void set_instrument_data(uint8_t const *data) { m_fm.regs().set_instrument_data(data); }
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return m_fm.sample_rate(input_clock); }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access -- doesn't really have any, but provide these for consistency
uint8_t read_status() { return 0x00; }
uint8_t read(uint32_t offset) { return 0x00; }
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate samples of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal state
uint8_t m_address; // address register
fm_engine m_fm; // core FM engine
};
// ======================> ym2413
class ym2413 : public opll_base
{
public:
// constructor
ym2413(ymfm_interface &intf, uint8_t const *instrument_data = nullptr);
private:
// internal state
static uint8_t const s_default_instruments[];
};
// ======================> ym2413
class ym2423 : public opll_base
{
public:
// constructor
ym2423(ymfm_interface &intf, uint8_t const *instrument_data = nullptr);
private:
// internal state
static uint8_t const s_default_instruments[];
};
// ======================> ymf281
class ymf281 : public opll_base
{
public:
// constructor
ymf281(ymfm_interface &intf, uint8_t const *instrument_data = nullptr);
private:
// internal state
static uint8_t const s_default_instruments[];
};
// ======================> ds1001
class ds1001 : public opll_base
{
public:
// constructor
ds1001(ymfm_interface &intf, uint8_t const *instrument_data = nullptr);
private:
// internal state
static uint8_t const s_default_instruments[];
};
}
#endif // YMFM_OPL_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm_opl.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 9,112 |
```c++
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ymfm_opm.h"
#include "ymfm_fm.ipp"
namespace ymfm
{
//*********************************************************
// OPM REGISTERS
//*********************************************************
//-------------------------------------------------
// opm_registers - constructor
//-------------------------------------------------
opm_registers::opm_registers() :
m_lfo_counter(0),
m_noise_lfsr(1),
m_noise_counter(0),
m_noise_state(0),
m_noise_lfo(0),
m_lfo_am(0)
{
// create the waveforms
for (uint32_t index = 0; index < WAVEFORM_LENGTH; index++)
m_waveform[0][index] = abs_sin_attenuation(index) | (bitfield(index, 9) << 15);
// create the LFO waveforms; AM in the low 8 bits, PM in the upper 8
// waveforms are adjusted to match the pictures in the application manual
for (uint32_t index = 0; index < LFO_WAVEFORM_LENGTH; index++)
{
// waveform 0 is a sawtooth
uint8_t am = index ^ 0xff;
int8_t pm = int8_t(index);
m_lfo_waveform[0][index] = am | (pm << 8);
// waveform 1 is a square wave
am = bitfield(index, 7) ? 0 : 0xff;
pm = int8_t(am ^ 0x80);
m_lfo_waveform[1][index] = am | (pm << 8);
// waveform 2 is a triangle wave
am = bitfield(index, 7) ? (index << 1) : ((index ^ 0xff) << 1);
pm = int8_t(bitfield(index, 6) ? am : ~am);
m_lfo_waveform[2][index] = am | (pm << 8);
// waveform 3 is noise; it is filled in dynamically
m_lfo_waveform[3][index] = 0;
}
}
//-------------------------------------------------
// reset - reset to initial state
//-------------------------------------------------
void opm_registers::reset()
{
std::fill_n(&m_regdata[0], REGISTERS, 0);
// enable output on both channels by default
m_regdata[0x20] = m_regdata[0x21] = m_regdata[0x22] = m_regdata[0x23] = 0xc0;
m_regdata[0x24] = m_regdata[0x25] = m_regdata[0x26] = m_regdata[0x27] = 0xc0;
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void opm_registers::save_restore(ymfm_saved_state &state)
{
state.save_restore(m_lfo_counter);
state.save_restore(m_lfo_am);
state.save_restore(m_noise_lfsr);
state.save_restore(m_noise_counter);
state.save_restore(m_noise_state);
state.save_restore(m_noise_lfo);
state.save_restore(m_regdata);
}
//-------------------------------------------------
// operator_map - return an array of operator
// indices for each channel; for OPM this is fixed
//-------------------------------------------------
void opm_registers::operator_map(operator_mapping &dest) const
{
// Note that the channel index order is 0,2,1,3, so we bitswap the index.
//
// This is because the order in the map is:
// carrier 1, carrier 2, modulator 1, modulator 2
//
// But when wiring up the connections, the more natural order is:
// carrier 1, modulator 1, carrier 2, modulator 2
static const operator_mapping s_fixed_map =
{ {
operator_list( 0, 16, 8, 24 ), // Channel 0 operators
operator_list( 1, 17, 9, 25 ), // Channel 1 operators
operator_list( 2, 18, 10, 26 ), // Channel 2 operators
operator_list( 3, 19, 11, 27 ), // Channel 3 operators
operator_list( 4, 20, 12, 28 ), // Channel 4 operators
operator_list( 5, 21, 13, 29 ), // Channel 5 operators
operator_list( 6, 22, 14, 30 ), // Channel 6 operators
operator_list( 7, 23, 15, 31 ), // Channel 7 operators
} };
dest = s_fixed_map;
}
//-------------------------------------------------
// write - handle writes to the register array
//-------------------------------------------------
bool opm_registers::write(uint16_t index, uint8_t data, uint32_t &channel, uint32_t &opmask)
{
assert(index < REGISTERS);
// LFO AM/PM depth are written to the same register (0x19);
// redirect the PM depth to an unused neighbor (0x1a)
if (index == 0x19)
m_regdata[index + bitfield(data, 7)] = data;
else if (index != 0x1a)
m_regdata[index] = data;
// handle writes to the key on index
if (index == 0x08)
{
channel = bitfield(data, 0, 3);
opmask = bitfield(data, 3, 4);
return true;
}
return false;
}
//-------------------------------------------------
// clock_noise_and_lfo - clock the noise and LFO,
// handling clock division, depth, and waveform
// computations
//-------------------------------------------------
int32_t opm_registers::clock_noise_and_lfo()
{
// base noise frequency is measured at 2x 1/2 FM frequency; this
// means each tick counts as two steps against the noise counter
uint32_t freq = noise_frequency();
for (int rep = 0; rep < 2; rep++)
{
// evidence seems to suggest the LFSR is clocked continually and just
// sampled at the noise frequency for output purposes; note that the
// low 8 bits are the most recent 8 bits of history while bits 8-24
// contain the 17 bit LFSR state
m_noise_lfsr <<= 1;
m_noise_lfsr |= bitfield(m_noise_lfsr, 17) ^ bitfield(m_noise_lfsr, 14) ^ 1;
// compare against the frequency and latch when we exceed it
if (m_noise_counter++ >= freq)
{
m_noise_counter = 0;
m_noise_state = bitfield(m_noise_lfsr, 17);
}
}
// treat the rate as a 4.4 floating-point step value with implied
// leading 1; this matches exactly the frequencies in the application
// manual, though it might not be implemented exactly this way on chip
uint32_t rate = lfo_rate();
m_lfo_counter += (0x10 | bitfield(rate, 0, 4)) << bitfield(rate, 4, 4);
// bit 1 of the test register is officially undocumented but has been
// discovered to hold the LFO in reset while active
if (lfo_reset())
m_lfo_counter = 0;
// now pull out the non-fractional LFO value
uint32_t lfo = bitfield(m_lfo_counter, 22, 8);
// fill in the noise entry 1 ahead of our current position; this
// ensures the current value remains stable for a full LFO clock
// and effectively latches the running value when the LFO advances
uint32_t lfo_noise = bitfield(m_noise_lfsr, 17, 8);
m_lfo_waveform[3][(lfo + 1) & 0xff] = lfo_noise | (lfo_noise << 8);
// fetch the AM/PM values based on the waveform; AM is unsigned and
// encoded in the low 8 bits, while PM signed and encoded in the upper
// 8 bits
int32_t ampm = m_lfo_waveform[lfo_waveform()][lfo];
// apply depth to the AM value and store for later
m_lfo_am = ((ampm & 0xff) * lfo_am_depth()) >> 7;
// apply depth to the PM value and return it
return ((ampm >> 8) * int32_t(lfo_pm_depth())) >> 7;
}
//-------------------------------------------------
// lfo_am_offset - return the AM offset from LFO
// for the given channel
//-------------------------------------------------
uint32_t opm_registers::lfo_am_offset(uint32_t choffs) const
{
// OPM maps AM quite differently from OPN
// shift value for AM sensitivity is [*, 0, 1, 2],
// mapping to values of [0, 23.9, 47.8, and 95.6dB]
uint32_t am_sensitivity = ch_lfo_am_sens(choffs);
if (am_sensitivity == 0)
return 0;
// QUESTION: see OPN note below for the dB range mapping; it applies
// here as well
// raw LFO AM value on OPM is 0-FF, which is already a factor of 2
// larger than the OPN below, putting our staring point at 2x theirs;
// this works out since our minimum is 2x their maximum
return m_lfo_am << (am_sensitivity - 1);
}
//-------------------------------------------------
// cache_operator_data - fill the operator cache
// with prefetched data
//-------------------------------------------------
void opm_registers::cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache)
{
// set up the easy stuff
cache.waveform = &m_waveform[0][0];
// get frequency from the channel
uint32_t block_freq = cache.block_freq = ch_block_freq(choffs);
// compute the keycode: block_freq is:
//
// BBBCCCCFFFFFF
// ^^^^^
//
// the 5-bit keycode is just the top 5 bits (block + top 2 bits
// of the key code)
uint32_t keycode = bitfield(block_freq, 8, 5);
// detune adjustment
cache.detune = detune_adjustment(op_detune(opoffs), keycode);
// multiple value, as an x.1 value (0 means 0.5)
cache.multiple = op_multiple(opoffs) * 2;
if (cache.multiple == 0)
cache.multiple = 1;
// phase step, or PHASE_STEP_DYNAMIC if PM is active; this depends on
// block_freq, detune, and multiple, so compute it after we've done those
if (lfo_pm_depth() == 0 || ch_lfo_pm_sens(choffs) == 0)
cache.phase_step = compute_phase_step(choffs, opoffs, cache, 0);
else
cache.phase_step = opdata_cache::PHASE_STEP_DYNAMIC;
// total level, scaled by 8
cache.total_level = op_total_level(opoffs) << 3;
// 4-bit sustain level, but 15 means 31 so effectively 5 bits
cache.eg_sustain = op_sustain_level(opoffs);
cache.eg_sustain |= (cache.eg_sustain + 1) & 0x10;
cache.eg_sustain <<= 5;
// determine KSR adjustment for enevlope rates
uint32_t ksrval = keycode >> (op_ksr(opoffs) ^ 3);
cache.eg_rate[EG_ATTACK] = effective_rate(op_attack_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_DECAY] = effective_rate(op_decay_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_SUSTAIN] = effective_rate(op_sustain_rate(opoffs) * 2, ksrval);
cache.eg_rate[EG_RELEASE] = effective_rate(op_release_rate(opoffs) * 4 + 2, ksrval);
}
//-------------------------------------------------
// compute_phase_step - compute the phase step
//-------------------------------------------------
uint32_t opm_registers::compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm)
{
// OPM logic is rather unique here, due to extra detune
// and the use of key codes (not to be confused with keycode)
// start with coarse detune delta; table uses cents value from
// manual, converted into 1/64ths
static const int16_t s_detune2_delta[4] = { 0, (600*64+50)/100, (781*64+50)/100, (950*64+50)/100 };
int32_t delta = s_detune2_delta[op_detune2(opoffs)];
// add in the PM delta
uint32_t pm_sensitivity = ch_lfo_pm_sens(choffs);
if (pm_sensitivity != 0)
{
// raw PM value is -127..128 which is +/- 200 cents
// manual gives these magnitudes in cents:
// 0, +/-5, +/-10, +/-20, +/-50, +/-100, +/-400, +/-700
// this roughly corresponds to shifting the 200-cent value:
// 0 >> 5, >> 4, >> 3, >> 2, >> 1, << 1, << 2
if (pm_sensitivity < 6)
delta += lfo_raw_pm >> (6 - pm_sensitivity);
else
delta += lfo_raw_pm << (pm_sensitivity - 5);
}
// apply delta and convert to a frequency number
uint32_t phase_step = opm_key_code_to_phase_step(cache.block_freq, delta);
// apply detune based on the keycode
phase_step += cache.detune;
// apply frequency multiplier (which is cached as an x.1 value)
return (phase_step * cache.multiple) >> 1;
}
//-------------------------------------------------
// log_keyon - log a key-on event
//-------------------------------------------------
std::string opm_registers::log_keyon(uint32_t choffs, uint32_t opoffs)
{
uint32_t chnum = choffs;
uint32_t opnum = opoffs;
char buffer[256];
char *end = &buffer[0];
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, "%u.%02u freq=%04X dt2=%u dt=%u fb=%u alg=%X mul=%X tl=%02X ksr=%u adsr=%02X/%02X/%02X/%X sl=%X out=%c%c",
chnum, opnum,
ch_block_freq(choffs),
op_detune2(opoffs),
op_detune(opoffs),
ch_feedback(choffs),
ch_algorithm(choffs),
op_multiple(opoffs),
op_total_level(opoffs),
op_ksr(opoffs),
op_attack_rate(opoffs),
op_decay_rate(opoffs),
op_sustain_rate(opoffs),
op_release_rate(opoffs),
op_sustain_level(opoffs),
ch_output_0(choffs) ? 'L' : '-',
ch_output_1(choffs) ? 'R' : '-');
bool am = (lfo_am_depth() != 0 && ch_lfo_am_sens(choffs) != 0 && op_lfo_am_enable(opoffs) != 0);
if (am)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " am=%u/%02X", ch_lfo_am_sens(choffs), lfo_am_depth());
bool pm = (lfo_pm_depth() != 0 && ch_lfo_pm_sens(choffs) != 0);
if (pm)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " pm=%u/%02X", ch_lfo_pm_sens(choffs), lfo_pm_depth());
if (am || pm)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " lfo=%02X/%c", lfo_rate(), "WQTN"[lfo_waveform()]);
if (noise_enable() && opoffs == 31)
end += snprintf(end, SNPRINTF_BUFFER_SIZE_CALC, " noise=1");
return buffer;
}
//*********************************************************
// YM2151
//*********************************************************
//-------------------------------------------------
// ym2151 - constructor
//-------------------------------------------------
ym2151::ym2151(ymfm_interface &intf, opm_variant variant) :
m_variant(variant),
m_address(0),
m_fm(intf)
{
}
//-------------------------------------------------
// reset - reset the system
//-------------------------------------------------
void ym2151::reset()
{
// reset the engines
m_fm.reset();
}
//-------------------------------------------------
// save_restore - save or restore the data
//-------------------------------------------------
void ym2151::save_restore(ymfm_saved_state &state)
{
m_fm.save_restore(state);
state.save_restore(m_address);
}
//-------------------------------------------------
// read_status - read the status register
//-------------------------------------------------
uint8_t ym2151::read_status()
{
uint8_t result = m_fm.status();
if (m_fm.intf().ymfm_is_busy())
result |= fm_engine::STATUS_BUSY;
return result;
}
//-------------------------------------------------
// read - handle a read from the device
//-------------------------------------------------
uint8_t ym2151::read(uint32_t offset)
{
uint8_t result = 0xff;
switch (offset & 1)
{
case 0: // data port (unused)
debug::log_unexpected_read_write("Unexpected read from YM2151 offset %d\n", offset & 3);
break;
case 1: // status port, YM2203 compatible
result = read_status();
break;
}
return result;
}
//-------------------------------------------------
// write_address - handle a write to the address
// register
//-------------------------------------------------
void ym2151::write_address(uint8_t data)
{
// just set the address
m_address = data;
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym2151::write_data(uint8_t data)
{
// write the FM register
m_fm.write(m_address, data);
// special cases
if (m_address == 0x1b)
{
// writes to register 0x1B send the upper 2 bits to the output lines
m_fm.intf().ymfm_external_write(ACCESS_IO, 0, data >> 6);
}
// mark busy for a bit
m_fm.intf().ymfm_set_busy_end(32 * m_fm.clock_prescale());
}
//-------------------------------------------------
// write - handle a write to the register
// interface
//-------------------------------------------------
void ym2151::write(uint32_t offset, uint8_t data)
{
switch (offset & 1)
{
case 0: // address port
write_address(data);
break;
case 1: // data port
write_data(data);
break;
}
}
//-------------------------------------------------
// generate - generate one sample of sound
//-------------------------------------------------
void ym2151::generate(output_data *output, uint32_t numsamples)
{
for (uint32_t samp = 0; samp < numsamples; samp++, output++)
{
// clock the system
m_fm.clock(fm_engine::ALL_CHANNELS);
// update the FM content; OPM is full 14-bit with no intermediate clipping
m_fm.output(output->clear(), 0, 32767, fm_engine::ALL_CHANNELS);
// YM2151 uses an external DAC (YM3012) with mantissa/exponent format
// convert to 10.3 floating point value and back to simulate truncation
output->roundtrip_fp();
}
}
}
``` | /content/code_sandbox/src/sound/ymfm/ymfm_opm.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 4,693 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_OPM_H
#define YMFM_OPM_H
#pragma once
#include "ymfm.h"
#include "ymfm_fm.h"
namespace ymfm
{
//*********************************************************
// REGISTER CLASSES
//*********************************************************
// ======================> opm_registers
//
// OPM register map:
//
// System-wide registers:
// 01 xxxxxx-x Test register
// ------x- LFO reset
// 08 -x------ Key on/off operator 4
// --x----- Key on/off operator 3
// ---x---- Key on/off operator 2
// ----x--- Key on/off operator 1
// -----xxx Channel select
// 0F x------- Noise enable
// ---xxxxx Noise frequency
// 10 xxxxxxxx Timer A value (upper 8 bits)
// 11 ------xx Timer A value (lower 2 bits)
// 12 xxxxxxxx Timer B value
// 14 x------- CSM mode
// --x----- Reset timer B
// ---x---- Reset timer A
// ----x--- Enable timer B
// -----x-- Enable timer A
// ------x- Load timer B
// -------x Load timer A
// 18 xxxxxxxx LFO frequency
// 19 0xxxxxxx AM LFO depth
// 1xxxxxxx PM LFO depth
// 1B xx------ CT (2 output data lines)
// ------xx LFO waveform
//
// Per-channel registers (channel in address bits 0-2)
// 20-27 x------- Pan right
// -x------ Pan left
// --xxx--- Feedback level for operator 1 (0-7)
// -----xxx Operator connection algorithm (0-7)
// 28-2F -xxxxxxx Key code
// 30-37 xxxxxx-- Key fraction
// 38-3F -xxx---- LFO PM sensitivity
// ------xx LFO AM shift
//
// Per-operator registers (channel in address bits 0-2, operator in bits 3-4)
// 40-5F -xxx---- Detune value (0-7)
// ----xxxx Multiple value (0-15)
// 60-7F -xxxxxxx Total level (0-127)
// 80-9F xx------ Key scale rate (0-3)
// ---xxxxx Attack rate (0-31)
// A0-BF x------- LFO AM enable
// ---xxxxx Decay rate (0-31)
// C0-DF xx------ Detune 2 value (0-3)
// ---xxxxx Sustain rate (0-31)
// E0-FF xxxx---- Sustain level (0-15)
// ----xxxx Release rate (0-15)
//
// Internal (fake) registers:
// 1A -xxxxxxx PM depth
//
class opm_registers : public fm_registers_base
{
// LFO waveforms are 256 entries long
static constexpr uint32_t LFO_WAVEFORM_LENGTH = 256;
public:
// constants
static constexpr uint32_t OUTPUTS = 2;
static constexpr uint32_t CHANNELS = 8;
static constexpr uint32_t ALL_CHANNELS = (1 << CHANNELS) - 1;
static constexpr uint32_t OPERATORS = CHANNELS * 4;
static constexpr uint32_t WAVEFORMS = 1;
static constexpr uint32_t REGISTERS = 0x100;
static constexpr uint32_t DEFAULT_PRESCALE = 2;
static constexpr uint32_t EG_CLOCK_DIVIDER = 3;
static constexpr uint32_t CSM_TRIGGER_MASK = ALL_CHANNELS;
static constexpr uint32_t REG_MODE = 0x14;
static constexpr uint8_t STATUS_TIMERA = 0x01;
static constexpr uint8_t STATUS_TIMERB = 0x02;
static constexpr uint8_t STATUS_BUSY = 0x80;
static constexpr uint8_t STATUS_IRQ = 0;
// constructor
opm_registers();
// reset to initial state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// map channel number to register offset
static constexpr uint32_t channel_offset(uint32_t chnum)
{
assert(chnum < CHANNELS);
return chnum;
}
// map operator number to register offset
static constexpr uint32_t operator_offset(uint32_t opnum)
{
assert(opnum < OPERATORS);
return opnum;
}
// return an array of operator indices for each channel
struct operator_mapping { uint32_t chan[CHANNELS]; };
void operator_map(operator_mapping &dest) const;
// handle writes to the register array
bool write(uint16_t index, uint8_t data, uint32_t &chan, uint32_t &opmask);
// clock the noise and LFO, if present, returning LFO PM value
int32_t clock_noise_and_lfo();
// return the AM offset from LFO for the given channel
uint32_t lfo_am_offset(uint32_t choffs) const;
// return the current noise state, gated by the noise clock
uint32_t noise_state() const { return m_noise_state; }
// caching helpers
void cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache);
// compute the phase step, given a PM value
uint32_t compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm);
// log a key-on event
std::string log_keyon(uint32_t choffs, uint32_t opoffs);
// system-wide registers
uint32_t test() const { return byte(0x01, 0, 8); }
uint32_t lfo_reset() const { return byte(0x01, 1, 1); }
uint32_t noise_frequency() const { return byte(0x0f, 0, 5) ^ 0x1f; }
uint32_t noise_enable() const { return byte(0x0f, 7, 1); }
uint32_t timer_a_value() const { return word(0x10, 0, 8, 0x11, 0, 2); }
uint32_t timer_b_value() const { return byte(0x12, 0, 8); }
uint32_t csm() const { return byte(0x14, 7, 1); }
uint32_t reset_timer_b() const { return byte(0x14, 5, 1); }
uint32_t reset_timer_a() const { return byte(0x14, 4, 1); }
uint32_t enable_timer_b() const { return byte(0x14, 3, 1); }
uint32_t enable_timer_a() const { return byte(0x14, 2, 1); }
uint32_t load_timer_b() const { return byte(0x14, 1, 1); }
uint32_t load_timer_a() const { return byte(0x14, 0, 1); }
uint32_t lfo_rate() const { return byte(0x18, 0, 8); }
uint32_t lfo_am_depth() const { return byte(0x19, 0, 7); }
uint32_t lfo_pm_depth() const { return byte(0x1a, 0, 7); }
uint32_t output_bits() const { return byte(0x1b, 6, 2); }
uint32_t lfo_waveform() const { return byte(0x1b, 0, 2); }
// per-channel registers
uint32_t ch_output_any(uint32_t choffs) const { return byte(0x20, 6, 2, choffs); }
uint32_t ch_output_0(uint32_t choffs) const { return byte(0x20, 6, 1, choffs); }
uint32_t ch_output_1(uint32_t choffs) const { return byte(0x20, 7, 1, choffs); }
uint32_t ch_output_2(uint32_t choffs) const { return 0; }
uint32_t ch_output_3(uint32_t choffs) const { return 0; }
uint32_t ch_feedback(uint32_t choffs) const { return byte(0x20, 3, 3, choffs); }
uint32_t ch_algorithm(uint32_t choffs) const { return byte(0x20, 0, 3, choffs); }
uint32_t ch_block_freq(uint32_t choffs) const { return word(0x28, 0, 7, 0x30, 2, 6, choffs); }
uint32_t ch_lfo_pm_sens(uint32_t choffs) const { return byte(0x38, 4, 3, choffs); }
uint32_t ch_lfo_am_sens(uint32_t choffs) const { return byte(0x38, 0, 2, choffs); }
// per-operator registers
uint32_t op_detune(uint32_t opoffs) const { return byte(0x40, 4, 3, opoffs); }
uint32_t op_multiple(uint32_t opoffs) const { return byte(0x40, 0, 4, opoffs); }
uint32_t op_total_level(uint32_t opoffs) const { return byte(0x60, 0, 7, opoffs); }
uint32_t op_ksr(uint32_t opoffs) const { return byte(0x80, 6, 2, opoffs); }
uint32_t op_attack_rate(uint32_t opoffs) const { return byte(0x80, 0, 5, opoffs); }
uint32_t op_lfo_am_enable(uint32_t opoffs) const { return byte(0xa0, 7, 1, opoffs); }
uint32_t op_decay_rate(uint32_t opoffs) const { return byte(0xa0, 0, 5, opoffs); }
uint32_t op_detune2(uint32_t opoffs) const { return byte(0xc0, 6, 2, opoffs); }
uint32_t op_sustain_rate(uint32_t opoffs) const { return byte(0xc0, 0, 5, opoffs); }
uint32_t op_sustain_level(uint32_t opoffs) const { return byte(0xe0, 4, 4, opoffs); }
uint32_t op_release_rate(uint32_t opoffs) const { return byte(0xe0, 0, 4, opoffs); }
protected:
// return a bitfield extracted from a byte
uint32_t byte(uint32_t offset, uint32_t start, uint32_t count, uint32_t extra_offset = 0) const
{
return bitfield(m_regdata[offset + extra_offset], start, count);
}
// return a bitfield extracted from a pair of bytes, MSBs listed first
uint32_t word(uint32_t offset1, uint32_t start1, uint32_t count1, uint32_t offset2, uint32_t start2, uint32_t count2, uint32_t extra_offset = 0) const
{
return (byte(offset1, start1, count1, extra_offset) << count2) | byte(offset2, start2, count2, extra_offset);
}
// internal state
uint32_t m_lfo_counter; // LFO counter
uint32_t m_noise_lfsr; // noise LFSR state
uint8_t m_noise_counter; // noise counter
uint8_t m_noise_state; // latched noise state
uint8_t m_noise_lfo; // latched LFO noise value
uint8_t m_lfo_am; // current LFO AM value
uint8_t m_regdata[REGISTERS]; // register data
int16_t m_lfo_waveform[4][LFO_WAVEFORM_LENGTH]; // LFO waveforms; AM in low 8, PM in upper 8
uint16_t m_waveform[WAVEFORMS][WAVEFORM_LENGTH]; // waveforms
};
//*********************************************************
// OPM IMPLEMENTATION CLASSES
//*********************************************************
// ======================> ym2151
class ym2151
{
public:
using fm_engine = fm_engine_base<opm_registers>;
using output_data = fm_engine::output_data;
static constexpr uint32_t OUTPUTS = fm_engine::OUTPUTS;
// constructor
ym2151(ymfm_interface &intf) : ym2151(intf, VARIANT_YM2151) { }
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return m_fm.sample_rate(input_clock); }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// variants
enum opm_variant
{
VARIANT_YM2151,
VARIANT_YM2164
};
// internal constructor
ym2151(ymfm_interface &intf, opm_variant variant);
// internal state
opm_variant m_variant; // chip variant
uint8_t m_address; // address register
fm_engine m_fm; // core FM engine
};
//*********************************************************
// OPP IMPLEMENTATION CLASSES
//*********************************************************
// ======================> ym2164
// the YM2164 is almost 100% functionally identical to the YM2151, except
// it apparently has some mystery registers in the 00-07 range, and timer
// B's frequency is half that of the 2151
class ym2164 : public ym2151
{
public:
// constructor
ym2164(ymfm_interface &intf) : ym2151(intf, VARIANT_YM2164) { }
};
}
#endif // YMFM_OPM_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm_opm.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,486 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_OPX_H
#define YMFM_OPX_H
#pragma once
#include "ymfm.h"
#include "ymfm_fm.h"
namespace ymfm
{
//*********************************************************
// REGISTER CLASSES
//*********************************************************
// ======================> opx_registers
//
// OPX register map:
//
// System-wide registers:
//
// Per-channel registers (channel in address bits 0-2)
//
// Per-operator registers (4 banks):
// 00-0F x------- Enable
// -xxxx--- EXT out
// -------x Key on
// 10-1F xxxxxxxx LFO frequency
// 20-2F xx------ AM sensitivity (0-3)
// --xxx--- PM sensitivity (0-7)
// ------xx LFO waveform (0=disable, 1=saw, 2=
// 30-3F -xxx---- Detune (0-7)
// ----xxxx Multiple (0-15)
// 40-4F -xxxxxxx Total level (0-127)
// 50-5F xxx----- Key scale (0-7)
// ---xxxxx Attack rate (0-31)
// 60-6F ---xxxxx Decay rate (0-31)
// 70-7F ---xxxxx Sustain rate (0-31)
// 80-8F xxxx---- Sustain level (0-15)
// ----xxxx Release rate (0-15)
// 90-9F xxxxxxxx Frequency number (low 8 bits)
// A0-AF xxxx---- Block (0-15)
// ----xxxx Frequency number (high 4 bits)
// B0-BF x------- Acc on
// -xxx---- Feedback level (0-7)
// -----xxx Waveform (0-7, 7=PCM)
// C0-CF ----xxxx Algorithm (0-15)
// D0-DF xxxx---- CH0 level (0-15)
// ----xxxx CH1 level (0-15)
// E0-EF xxxx---- CH2 level (0-15)
// ----xxxx CH3 level (0-15)
//
class opx_registers : public fm_registers_base
{
// LFO waveforms are 256 entries long
static constexpr uint32_t LFO_WAVEFORM_LENGTH = 256;
public:
// constants
static constexpr uint32_t OUTPUTS = 8;
static constexpr uint32_t CHANNELS = 24;
static constexpr uint32_t ALL_CHANNELS = (1 << CHANNELS) - 1;
static constexpr uint32_t OPERATORS = CHANNELS * 2;
static constexpr uint32_t WAVEFORMS = 8;
static constexpr uint32_t REGISTERS = 0x800;
static constexpr uint32_t DEFAULT_PRESCALE = 8;
static constexpr uint32_t EG_CLOCK_DIVIDER = 2;
static constexpr uint32_t CSM_TRIGGER_MASK = ALL_CHANNELS;
static constexpr uint32_t REG_MODE = 0x14;
static constexpr uint8_t STATUS_TIMERA = 0x01;
static constexpr uint8_t STATUS_TIMERB = 0x02;
static constexpr uint8_t STATUS_BUSY = 0x80;
static constexpr uint8_t STATUS_IRQ = 0;
// constructor
opz_registers();
// reset to initial state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// map channel number to register offset
static constexpr uint32_t channel_offset(uint32_t chnum)
{
assert(chnum < CHANNELS);
return chnum;
}
// map operator number to register offset
static constexpr uint32_t operator_offset(uint32_t opnum)
{
assert(opnum < OPERATORS);
return opnum;
}
// return an array of operator indices for each channel
struct operator_mapping { uint32_t chan[CHANNELS]; };
void operator_map(operator_mapping &dest) const;
// handle writes to the register array
bool write(uint16_t index, uint8_t data, uint32_t &chan, uint32_t &opmask);
// clock the noise and LFO, if present, returning LFO PM value
int32_t clock_noise_and_lfo();
// return the AM offset from LFO for the given channel
uint32_t lfo_am_offset(uint32_t choffs) const;
// return the current noise state, gated by the noise clock
uint32_t noise_state() const { return m_noise_state; }
// caching helpers
void cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache);
// compute the phase step, given a PM value
uint32_t compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm);
// log a key-on event
std::string log_keyon(uint32_t choffs, uint32_t opoffs);
// system-wide registers
uint32_t noise_frequency() const { return byte(0x0f, 0, 5); }
uint32_t noise_enable() const { return byte(0x0f, 7, 1); }
uint32_t timer_a_value() const { return word(0x10, 0, 8, 0x11, 0, 2); }
uint32_t timer_b_value() const { return byte(0x12, 0, 8); }
uint32_t csm() const { return byte(0x14, 7, 1); }
uint32_t reset_timer_b() const { return byte(0x14, 5, 1); }
uint32_t reset_timer_a() const { return byte(0x14, 4, 1); }
uint32_t enable_timer_b() const { return byte(0x14, 3, 1); }
uint32_t enable_timer_a() const { return byte(0x14, 2, 1); }
uint32_t load_timer_b() const { return byte(0x14, 1, 1); }
uint32_t load_timer_a() const { return byte(0x14, 0, 1); }
uint32_t lfo2_pm_depth() const { return byte(0x148, 0, 7); } // fake
uint32_t lfo2_rate() const { return byte(0x16, 0, 8); }
uint32_t lfo2_am_depth() const { return byte(0x17, 0, 7); }
uint32_t lfo_rate() const { return byte(0x18, 0, 8); }
uint32_t lfo_am_depth() const { return byte(0x19, 0, 7); }
uint32_t lfo_pm_depth() const { return byte(0x149, 0, 7); } // fake
uint32_t output_bits() const { return byte(0x1b, 6, 2); }
uint32_t lfo2_sync() const { return byte(0x1b, 5, 1); }
uint32_t lfo_sync() const { return byte(0x1b, 4, 1); }
uint32_t lfo2_waveform() const { return byte(0x1b, 2, 2); }
uint32_t lfo_waveform() const { return byte(0x1b, 0, 2); }
// per-channel registers
uint32_t ch_volume(uint32_t choffs) const { return byte(0x00, 0, 8, choffs); }
uint32_t ch_output_any(uint32_t choffs) const { return byte(0x20, 7, 1, choffs) | byte(0x30, 0, 1, choffs); }
uint32_t ch_output_0(uint32_t choffs) const { return byte(0x30, 0, 1, choffs); }
uint32_t ch_output_1(uint32_t choffs) const { return byte(0x20, 7, 1, choffs) | byte(0x30, 0, 1, choffs); }
uint32_t ch_output_2(uint32_t choffs) const { return 0; }
uint32_t ch_output_3(uint32_t choffs) const { return 0; }
uint32_t ch_key_on(uint32_t choffs) const { return byte(0x20, 6, 1, choffs); }
uint32_t ch_feedback(uint32_t choffs) const { return byte(0x20, 3, 3, choffs); }
uint32_t ch_algorithm(uint32_t choffs) const { return byte(0x20, 0, 3, choffs); }
uint32_t ch_block_freq(uint32_t choffs) const { return word(0x28, 0, 7, 0x30, 2, 6, choffs); }
uint32_t ch_lfo_pm_sens(uint32_t choffs) const { return byte(0x38, 4, 3, choffs); }
uint32_t ch_lfo_am_sens(uint32_t choffs) const { return byte(0x38, 0, 2, choffs); }
uint32_t ch_lfo2_pm_sens(uint32_t choffs) const { return byte(0x140, 4, 3, choffs); } // fake
uint32_t ch_lfo2_am_sens(uint32_t choffs) const { return byte(0x140, 0, 2, choffs); } // fake
// per-operator registers
uint32_t op_detune(uint32_t opoffs) const { return byte(0x40, 4, 3, opoffs); }
uint32_t op_multiple(uint32_t opoffs) const { return byte(0x40, 0, 4, opoffs); }
uint32_t op_fix_range(uint32_t opoffs) const { return byte(0x40, 4, 3, opoffs); }
uint32_t op_fix_frequency(uint32_t opoffs) const { return byte(0x40, 0, 4, opoffs); }
uint32_t op_waveform(uint32_t opoffs) const { return byte(0x100, 4, 3, opoffs); } // fake
uint32_t op_fine(uint32_t opoffs) const { return byte(0x100, 0, 4, opoffs); } // fake
uint32_t op_total_level(uint32_t opoffs) const { return byte(0x60, 0, 7, opoffs); }
uint32_t op_ksr(uint32_t opoffs) const { return byte(0x80, 6, 2, opoffs); }
uint32_t op_fix_mode(uint32_t opoffs) const { return byte(0x80, 5, 1, opoffs); }
uint32_t op_attack_rate(uint32_t opoffs) const { return byte(0x80, 0, 5, opoffs); }
uint32_t op_lfo_am_enable(uint32_t opoffs) const { return byte(0xa0, 7, 1, opoffs); }
uint32_t op_decay_rate(uint32_t opoffs) const { return byte(0xa0, 0, 5, opoffs); }
uint32_t op_detune2(uint32_t opoffs) const { return byte(0xc0, 6, 2, opoffs); }
uint32_t op_sustain_rate(uint32_t opoffs) const { return byte(0xc0, 0, 5, opoffs); }
uint32_t op_eg_shift(uint32_t opoffs) const { return byte(0x120, 6, 2, opoffs); } // fake
uint32_t op_reverb_rate(uint32_t opoffs) const { return byte(0x120, 0, 3, opoffs); } // fake
uint32_t op_sustain_level(uint32_t opoffs) const { return byte(0xe0, 4, 4, opoffs); }
uint32_t op_release_rate(uint32_t opoffs) const { return byte(0xe0, 0, 4, opoffs); }
protected:
// return a bitfield extracted from a byte
uint32_t byte(uint32_t offset, uint32_t start, uint32_t count, uint32_t extra_offset = 0) const
{
return bitfield(m_regdata[offset + extra_offset], start, count);
}
// return a bitfield extracted from a pair of bytes, MSBs listed first
uint32_t word(uint32_t offset1, uint32_t start1, uint32_t count1, uint32_t offset2, uint32_t start2, uint32_t count2, uint32_t extra_offset = 0) const
{
return (byte(offset1, start1, count1, extra_offset) << count2) | byte(offset2, start2, count2, extra_offset);
}
// internal state
uint32_t m_lfo_counter[2]; // LFO counter
uint32_t m_noise_lfsr; // noise LFSR state
uint8_t m_noise_counter; // noise counter
uint8_t m_noise_state; // latched noise state
uint8_t m_noise_lfo; // latched LFO noise value
uint8_t m_lfo_am[2]; // current LFO AM value
uint8_t m_regdata[REGISTERS]; // register data
uint16_t m_phase_substep[OPERATORS]; // phase substep for fixed frequency
int16_t m_lfo_waveform[4][LFO_WAVEFORM_LENGTH]; // LFO waveforms; AM in low 8, PM in upper 8
uint16_t m_waveform[WAVEFORMS][WAVEFORM_LENGTH]; // waveforms
};
//*********************************************************
// IMPLEMENTATION CLASSES
//*********************************************************
// ======================> ym2414
class ym2414
{
public:
using fm_engine = fm_engine_base<opz_registers>;
static constexpr uint32_t OUTPUTS = fm_engine::OUTPUTS;
using output_data = fm_engine::output_data;
// constructor
ym2414(ymfm_interface &intf);
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return m_fm.sample_rate(input_clock); }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal state
uint8_t m_address; // address register
fm_engine m_fm; // core FM engine
};
}
#endif // YMFM_OPZ_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm_opx.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,655 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_H
#define YMFM_H
#pragma once
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#define SNPRINTF_BUFFER_SIZE_CALC (256 - (end - &buffer[0]))
namespace ymfm
{
//*********************************************************
// DEBUGGING
//*********************************************************
class debug
{
public:
// masks to help isolate specific channels
static constexpr uint32_t GLOBAL_FM_CHANNEL_MASK = 0xffffffff;
static constexpr uint32_t GLOBAL_ADPCM_A_CHANNEL_MASK = 0xffffffff;
static constexpr uint32_t GLOBAL_ADPCM_B_CHANNEL_MASK = 0xffffffff;
static constexpr uint32_t GLOBAL_PCM_CHANNEL_MASK = 0xffffffff;
// types of logging
static constexpr bool LOG_FM_WRITES = false;
static constexpr bool LOG_KEYON_EVENTS = false;
static constexpr bool LOG_UNEXPECTED_READ_WRITES = false;
// helpers to write based on the log type
template<typename... Params> static void log_fm_write(Params &&... args) { if (LOG_FM_WRITES) log(args...); }
template<typename... Params> static void log_keyon(Params &&... args) { if (LOG_KEYON_EVENTS) log(args...); }
template<typename... Params> static void log_unexpected_read_write(Params &&... args) { if (LOG_UNEXPECTED_READ_WRITES) log(args...); }
// downstream helper to output log data; defaults to printf
template<typename... Params> static void log(Params &&... args) { printf(args...); }
};
//*********************************************************
// GLOBAL HELPERS
//*********************************************************
//-------------------------------------------------
// bitfield - extract a bitfield from the given
// value, starting at bit 'start' for a length of
// 'length' bits
//-------------------------------------------------
inline uint32_t bitfield(uint32_t value, int start, int length = 1)
{
return (value >> start) & ((1 << length) - 1);
}
//-------------------------------------------------
// clamp - clamp between the minimum and maximum
// values provided
//-------------------------------------------------
inline int32_t clamp(int32_t value, int32_t minval, int32_t maxval)
{
if (value < minval)
return minval;
if (value > maxval)
return maxval;
return value;
}
//-------------------------------------------------
// array_size - return the size of an array
//-------------------------------------------------
template<typename ArrayType, int ArraySize>
constexpr uint32_t array_size(ArrayType (&array)[ArraySize])
{
return ArraySize;
}
//-------------------------------------------------
// count_leading_zeros - return the number of
// leading zeros in a 32-bit value; CPU-optimized
// versions for various architectures are included
// below
//-------------------------------------------------
#if defined(__GNUC__)
inline uint8_t count_leading_zeros(uint32_t value)
{
if (value == 0)
return 32;
return __builtin_clz(value);
}
#elif defined(_MSC_VER)
inline uint8_t count_leading_zeros(uint32_t value)
{
unsigned long index;
return _BitScanReverse(&index, value) ? uint8_t(31U - index) : 32U;
}
#else
inline uint8_t count_leading_zeros(uint32_t value)
{
if (value == 0)
return 32;
uint8_t count;
for (count = 0; int32_t(value) >= 0; count++)
value <<= 1;
return count;
}
#endif
// Many of the Yamaha FM chips emit a floating-point value, which is sent to
// a DAC for processing. The exact format of this floating-point value is
// documented below. This description only makes sense if the "internal"
// format treats sign as 1=positive and 0=negative, so the helpers below
// presume that.
//
// Internal OPx data 16-bit signed data Exp Sign Mantissa
// ================= ================= === ==== ========
// 1 1xxxxxxxx------ -> 0 1xxxxxxxx------ -> 111 1 1xxxxxxx
// 1 01xxxxxxxx----- -> 0 01xxxxxxxx----- -> 110 1 1xxxxxxx
// 1 001xxxxxxxx---- -> 0 001xxxxxxxx---- -> 101 1 1xxxxxxx
// 1 0001xxxxxxxx--- -> 0 0001xxxxxxxx--- -> 100 1 1xxxxxxx
// 1 00001xxxxxxxx-- -> 0 00001xxxxxxxx-- -> 011 1 1xxxxxxx
// 1 000001xxxxxxxx- -> 0 000001xxxxxxxx- -> 010 1 1xxxxxxx
// 1 000000xxxxxxxxx -> 0 000000xxxxxxxxx -> 001 1 xxxxxxxx
// 0 111111xxxxxxxxx -> 1 111111xxxxxxxxx -> 001 0 xxxxxxxx
// 0 111110xxxxxxxx- -> 1 111110xxxxxxxx- -> 010 0 0xxxxxxx
// 0 11110xxxxxxxx-- -> 1 11110xxxxxxxx-- -> 011 0 0xxxxxxx
// 0 1110xxxxxxxx--- -> 1 1110xxxxxxxx--- -> 100 0 0xxxxxxx
// 0 110xxxxxxxx---- -> 1 110xxxxxxxx---- -> 101 0 0xxxxxxx
// 0 10xxxxxxxx----- -> 1 10xxxxxxxx----- -> 110 0 0xxxxxxx
// 0 0xxxxxxxx------ -> 1 0xxxxxxxx------ -> 111 0 0xxxxxxx
//-------------------------------------------------
// encode_fp - given a 32-bit signed input value
// convert it to a signed 3.10 floating-point
// value
//-------------------------------------------------
inline int16_t encode_fp(int32_t value)
{
// handle overflows first
if (value < -32768)
return (7 << 10) | 0x000;
if (value > 32767)
return (7 << 10) | 0x3ff;
// we need to count the number of leading sign bits after the sign
// we can use count_leading_zeros if we invert negative values
int32_t scanvalue = value ^ (int32_t(value) >> 31);
// exponent is related to the number of leading bits starting from bit 14
int exponent = 7 - count_leading_zeros(scanvalue << 17);
// smallest exponent value allowed is 1
exponent = std::max(exponent, 1);
// mantissa
int32_t mantissa = value >> (exponent - 1);
// assemble into final form, inverting the sign
return ((exponent << 10) | (mantissa & 0x3ff)) ^ 0x200;
}
//-------------------------------------------------
// decode_fp - given a 3.10 floating-point value,
// convert it to a signed 16-bit value
//-------------------------------------------------
inline int16_t decode_fp(int16_t value)
{
// invert the sign and the exponent
value ^= 0x1e00;
// shift mantissa up to 16 bits then apply inverted exponent
return int16_t(value << 6) >> bitfield(value, 10, 3);
}
//-------------------------------------------------
// roundtrip_fp - compute the result of a round
// trip through the encode/decode process above
//-------------------------------------------------
inline int16_t roundtrip_fp(int32_t value)
{
// handle overflows first
if (value < -32768)
return -32768;
if (value > 32767)
return 32767;
// we need to count the number of leading sign bits after the sign
// we can use count_leading_zeros if we invert negative values
int32_t scanvalue = value ^ (int32_t(value) >> 31);
// exponent is related to the number of leading bits starting from bit 14
int exponent = 7 - count_leading_zeros(scanvalue << 17);
// smallest exponent value allowed is 1
exponent = std::max(exponent, 1);
// apply the shift back and forth to zero out bits that are lost
exponent -= 1;
return (value >> exponent) << exponent;
}
//*********************************************************
// HELPER CLASSES
//*********************************************************
// various envelope states
enum envelope_state : uint32_t
{
EG_DEPRESS = 0, // OPLL only; set EG_HAS_DEPRESS to enable
EG_ATTACK = 1,
EG_DECAY = 2,
EG_SUSTAIN = 3,
EG_RELEASE = 4,
EG_REVERB = 5, // OPQ/OPZ only; set EG_HAS_REVERB to enable
EG_STATES = 6
};
// external I/O access classes
enum access_class : uint32_t
{
ACCESS_IO = 0,
ACCESS_ADPCM_A,
ACCESS_ADPCM_B,
ACCESS_PCM,
ACCESS_CLASSES
};
//*********************************************************
// HELPER CLASSES
//*********************************************************
// ======================> ymfm_output
// struct containing an array of output values
template<int NumOutputs>
struct ymfm_output
{
// clear all outputs to 0
ymfm_output &clear()
{
for (uint32_t index = 0; index < NumOutputs; index++)
data[index] = 0;
return *this;
}
// clamp all outputs to a 16-bit signed value
ymfm_output &clamp16()
{
for (uint32_t index = 0; index < NumOutputs; index++)
data[index] = clamp(data[index], -32768, 32767);
return *this;
}
// run each output value through the floating-point processor
ymfm_output &roundtrip_fp()
{
for (uint32_t index = 0; index < NumOutputs; index++)
data[index] = ymfm::roundtrip_fp(data[index]);
return *this;
}
// internal state
int32_t data[NumOutputs];
};
// ======================> ymfm_wavfile
// this class is a debugging helper that accumulates data and writes it to wav files
template<int Channels>
class ymfm_wavfile
{
public:
// construction
ymfm_wavfile(uint32_t samplerate = 44100) :
m_samplerate(samplerate)
{
}
// configuration
ymfm_wavfile &set_index(uint32_t index) { m_index = index; return *this; }
ymfm_wavfile &set_samplerate(uint32_t samplerate) { m_samplerate = samplerate; return *this; }
// destruction
~ymfm_wavfile()
{
if (!m_buffer.empty())
{
// create file
char name[20];
snprintf(name, sizeof(name), "wavlog-%02d.wav", m_index);
FILE *out = fopen(name, "wb");
// make the wav file header
uint8_t header[44];
memcpy(&header[0], "RIFF", 4);
*(uint32_t *)&header[4] = m_buffer.size() * 2 + 44 - 8;
memcpy(&header[8], "WAVE", 4);
memcpy(&header[12], "fmt ", 4);
*(uint32_t *)&header[16] = 16;
*(uint16_t *)&header[20] = 1;
*(uint16_t *)&header[22] = Channels;
*(uint32_t *)&header[24] = m_samplerate;
*(uint32_t *)&header[28] = m_samplerate * 2 * Channels;
*(uint16_t *)&header[32] = 2 * Channels;
*(uint16_t *)&header[34] = 16;
memcpy(&header[36], "data", 4);
*(uint32_t *)&header[40] = m_buffer.size() * 2 + 44 - 44;
// write header then data
fwrite(&header[0], 1, sizeof(header), out);
fwrite(&m_buffer[0], 2, m_buffer.size(), out);
fclose(out);
}
}
// add data to the file
template<int Outputs>
void add(ymfm_output<Outputs> output)
{
int16_t sum[Channels] = { 0 };
for (int index = 0; index < Outputs; index++)
sum[index % Channels] += output.data[index];
for (int index = 0; index < Channels; index++)
m_buffer.push_back(sum[index]);
}
// add data to the file, using a reference
template<int Outputs>
void add(ymfm_output<Outputs> output, ymfm_output<Outputs> const &ref)
{
int16_t sum[Channels] = { 0 };
for (int index = 0; index < Outputs; index++)
sum[index % Channels] += output.data[index] - ref.data[index];
for (int index = 0; index < Channels; index++)
m_buffer.push_back(sum[index]);
}
private:
// internal state
uint32_t m_index;
uint32_t m_samplerate;
std::vector<int16_t> m_buffer;
};
// ======================> ymfm_saved_state
// this class contains a managed vector of bytes that is used to save and
// restore state
class ymfm_saved_state
{
public:
// construction
ymfm_saved_state(std::vector<uint8_t> &buffer, bool saving) :
m_buffer(buffer),
m_offset(saving ? -1 : 0)
{
if (saving)
buffer.resize(0);
}
// are we saving or restoring?
bool saving() const { return (m_offset < 0); }
// generic save/restore
template<typename DataType>
void save_restore(DataType &data)
{
if (saving())
save(data);
else
restore(data);
}
public:
// save data to the buffer
void save(bool &data) { write(data ? 1 : 0); }
void save(int8_t &data) { write(data); }
void save(uint8_t &data) { write(data); }
void save(int16_t &data) { write(uint8_t(data)).write(data >> 8); }
void save(uint16_t &data) { write(uint8_t(data)).write(data >> 8); }
void save(int32_t &data) { write(data).write(data >> 8).write(data >> 16).write(data >> 24); }
void save(uint32_t &data) { write(data).write(data >> 8).write(data >> 16).write(data >> 24); }
void save(envelope_state &data) { write(uint8_t(data)); }
template<typename DataType, int Count>
void save(DataType (&data)[Count]) { for (uint32_t index = 0; index < Count; index++) save(data[index]); }
// restore data from the buffer
void restore(bool &data) { data = read() ? true : false; }
void restore(int8_t &data) { data = read(); }
void restore(uint8_t &data) { data = read(); }
void restore(int16_t &data) { data = read(); data |= read() << 8; }
void restore(uint16_t &data) { data = read(); data |= read() << 8; }
void restore(int32_t &data) { data = read(); data |= read() << 8; data |= read() << 16; data |= read() << 24; }
void restore(uint32_t &data) { data = read(); data |= read() << 8; data |= read() << 16; data |= read() << 24; }
void restore(envelope_state &data) { data = envelope_state(read()); }
template<typename DataType, int Count>
void restore(DataType (&data)[Count]) { for (uint32_t index = 0; index < Count; index++) restore(data[index]); }
// internal helper
ymfm_saved_state &write(uint8_t data) { m_buffer.push_back(data); return *this; }
uint8_t read() { return (m_offset < int32_t(m_buffer.size())) ? m_buffer[m_offset++] : 0; }
// internal state
std::vector<uint8_t> &m_buffer;
int32_t m_offset;
};
//*********************************************************
// INTERFACE CLASSES
//*********************************************************
// ======================> ymfm_engine_callbacks
// this class represents functions in the engine that the ymfm_interface
// needs to be able to call; it is represented here as a separate interface
// that is independent of the actual engine implementation
class ymfm_engine_callbacks
{
public:
virtual ~ymfm_engine_callbacks() = default;
// timer callback; called by the interface when a timer fires
virtual void engine_timer_expired(uint32_t tnum) = 0;
// check interrupts; called by the interface after synchronization
virtual void engine_check_interrupts() = 0;
// mode register write; called by the interface after synchronization
virtual void engine_mode_write(uint8_t data) = 0;
};
// ======================> ymfm_interface
// this class represents the interface between the fm_engine and the outside
// world; it provides hooks for timers, synchronization, and I/O
class ymfm_interface
{
// the engine is our friend
template<typename RegisterType> friend class fm_engine_base;
public:
virtual ~ymfm_interface() = default;
// the following functions must be implemented by any derived classes; the
// default implementations are sufficient for some minimal operation, but will
// likely need to be overridden to integrate with the outside world; they are
// all prefixed with ymfm_ to reduce the likelihood of namespace collisions
//
// timing and synchronizaton
//
// the chip implementation calls this when a write happens to the mode
// register, which could affect timers and interrupts; our responsibility
// is to ensure the system is up to date before calling the engine's
// engine_mode_write() method
virtual void ymfm_sync_mode_write(uint8_t data) { m_engine->engine_mode_write(data); }
// the chip implementation calls this when the chip's status has changed,
// which may affect the interrupt state; our responsibility is to ensure
// the system is up to date before calling the engine's
// engine_check_interrupts() method
virtual void ymfm_sync_check_interrupts() { m_engine->engine_check_interrupts(); }
// the chip implementation calls this when one of the two internal timers
// has changed state; our responsibility is to arrange to call the engine's
// engine_timer_expired() method after the provided number of clocks; if
// duration_in_clocks is negative, we should cancel any outstanding timers
virtual void ymfm_set_timer(uint32_t tnum, int32_t duration_in_clocks) { }
// the chip implementation calls this to indicate that the chip should be
// considered in a busy state until the given number of clocks has passed;
// our responsibility is to compute and remember the ending time based on
// the chip's clock for later checking
virtual void ymfm_set_busy_end(uint32_t clocks) { }
// the chip implementation calls this to see if the chip is still currently
// is a busy state, as specified by a previous call to ymfm_set_busy_end();
// our responsibility is to compare the current time against the previously
// noted busy end time and return true if we haven't yet passed it
virtual bool ymfm_is_busy() { return false; }
virtual uint32_t get_special_flags(void) { return 0x0000; }
//
// I/O functions
//
// the chip implementation calls this when the state of the IRQ signal has
// changed due to a status change; our responsibility is to respond as
// needed to the change in IRQ state, signaling any consumers
virtual void ymfm_update_irq(bool asserted) { }
// the chip implementation calls this whenever data is read from outside
// of the chip; our responsibility is to provide the data requested
virtual uint8_t ymfm_external_read(access_class type, uint32_t address) { return 0; }
// the chip implementation calls this whenever data is written outside
// of the chip; our responsibility is to pass the written data on to any consumers
virtual void ymfm_external_write(access_class type, uint32_t address, uint8_t data) { }
protected:
// pointer to engine callbacks -- this is set directly by the engine at
// construction time
ymfm_engine_callbacks *m_engine;
};
}
#endif // YMFM_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 4,888 |
```objective-c
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YMFM_OPZ_H
#define YMFM_OPZ_H
#pragma once
#include "ymfm.h"
#include "ymfm_fm.h"
namespace ymfm
{
//*********************************************************
// REGISTER CLASSES
//*********************************************************
// ======================> opz_registers
//
// OPZ register map:
//
// System-wide registers:
// 08 -----xxx Load preset (not sure how it gets saved)
// 0F x------- Noise enable
// ---xxxxx Noise frequency
// 10 xxxxxxxx Timer A value (upper 8 bits)
// 11 ------xx Timer A value (lower 2 bits)
// 12 xxxxxxxx Timer B value
// 14 x------- CSM mode
// --x----- Reset timer B
// ---x---- Reset timer A
// ----x--- Enable timer B
// -----x-- Enable timer A
// ------x- Load timer B
// -------x Load timer A
// 16 xxxxxxxx LFO #2 frequency
// 17 0xxxxxxx AM LFO #2 depth
// 1xxxxxxx PM LFO #2 depth
// 18 xxxxxxxx LFO frequency
// 19 0xxxxxxx AM LFO depth
// 1xxxxxxx PM LFO depth
// 1B xx------ CT (2 output data lines)
// --x----- LFO #2 sync
// ---x---- LFO sync
// ----xx-- LFO #2 waveform
// ------xx LFO waveform
//
// Per-channel registers (channel in address bits 0-2)
// 00-07 xxxxxxxx Channel volume
// 20-27 x------- Pan right
// -x------ Key on (0)/off(1)
// --xxx--- Feedback level for operator 1 (0-7)
// -----xxx Operator connection algorithm (0-7)
// 28-2F -xxxxxxx Key code
// 30-37 xxxxxx-- Key fraction
// -------x Mono? mode
// 38-3F 0xxx---- LFO PM sensitivity
// -----0xx LFO AM shift
// 1xxx---- LFO #2 PM sensitivity
// -----1xx LFO #2 AM shift
//
// Per-operator registers (channel in address bits 0-2, operator in bits 3-4)
// 40-5F 0xxx---- Detune value (0-7)
// 0---xxxx Multiple value (0-15)
// 0xxx---- Fix range (0-15)
// 0---xxxx Fix frequency (0-15)
// 1xxx---- Oscillator waveform (0-7)
// 1---xxxx Fine? (0-15)
// 60-7F -xxxxxxx Total level (0-127)
// 80-9F xx------ Key scale rate (0-3)
// --x----- Fix frequency mode
// ---xxxxx Attack rate (0-31)
// A0-BF x------- LFO AM enable
// ---xxxxx Decay rate (0-31)
// C0-DF xx0----- Detune 2 value (0-3)
// --0xxxxx Sustain rate (0-31)
// xx1----- Envelope generator shift? (0-3)
// --1--xxx Rev? (0-7)
// E0-FF xxxx---- Sustain level (0-15)
// ----xxxx Release rate (0-15)
//
// Internal (fake) registers:
// 100-11F -xxx---- Oscillator waveform (0-7)
// ----xxxx Fine? (0-15)
// 120-13F xx------ Envelope generator shift (0-3)
// -----xxx Reverb rate (0-7)
// 140-15F xxxx---- Preset sustain level (0-15)
// ----xxxx Preset release rate (0-15)
// 160-17F xx------ Envelope generator shift (0-3)
// -----xxx Reverb rate (0-7)
// 180-187 -xxx---- LFO #2 PM sensitivity
// ---- xxx LFO #2 AM shift
// 188 -xxxxxxx LFO #2 PM depth
// 189 -xxxxxxx LFO PM depth
//
class opz_registers : public fm_registers_base
{
// LFO waveforms are 256 entries long
static constexpr uint32_t LFO_WAVEFORM_LENGTH = 256;
public:
// constants
static constexpr uint32_t OUTPUTS = 2;
static constexpr uint32_t CHANNELS = 8;
static constexpr uint32_t ALL_CHANNELS = (1 << CHANNELS) - 1;
static constexpr uint32_t OPERATORS = CHANNELS * 4;
static constexpr uint32_t WAVEFORMS = 8;
static constexpr uint32_t REGISTERS = 0x190;
static constexpr uint32_t DEFAULT_PRESCALE = 2;
static constexpr uint32_t EG_CLOCK_DIVIDER = 3;
static constexpr bool EG_HAS_REVERB = true;
static constexpr uint32_t CSM_TRIGGER_MASK = ALL_CHANNELS;
static constexpr uint32_t REG_MODE = 0x14;
static constexpr uint8_t STATUS_TIMERA = 0x01;
static constexpr uint8_t STATUS_TIMERB = 0x02;
static constexpr uint8_t STATUS_BUSY = 0x80;
static constexpr uint8_t STATUS_IRQ = 0;
// constructor
opz_registers();
// reset to initial state
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// map channel number to register offset
static constexpr uint32_t channel_offset(uint32_t chnum)
{
assert(chnum < CHANNELS);
return chnum;
}
// map operator number to register offset
static constexpr uint32_t operator_offset(uint32_t opnum)
{
assert(opnum < OPERATORS);
return opnum;
}
// return an array of operator indices for each channel
struct operator_mapping { uint32_t chan[CHANNELS]; };
void operator_map(operator_mapping &dest) const;
// handle writes to the register array
bool write(uint16_t index, uint8_t data, uint32_t &chan, uint32_t &opmask);
// clock the noise and LFO, if present, returning LFO PM value
int32_t clock_noise_and_lfo();
// return the AM offset from LFO for the given channel
uint32_t lfo_am_offset(uint32_t choffs) const;
// return the current noise state, gated by the noise clock
uint32_t noise_state() const { return m_noise_state; }
// caching helpers
void cache_operator_data(uint32_t choffs, uint32_t opoffs, opdata_cache &cache);
// compute the phase step, given a PM value
uint32_t compute_phase_step(uint32_t choffs, uint32_t opoffs, opdata_cache const &cache, int32_t lfo_raw_pm);
// log a key-on event
std::string log_keyon(uint32_t choffs, uint32_t opoffs);
// system-wide registers
uint32_t noise_frequency() const { return byte(0x0f, 0, 5); }
uint32_t noise_enable() const { return byte(0x0f, 7, 1); }
uint32_t timer_a_value() const { return word(0x10, 0, 8, 0x11, 0, 2); }
uint32_t timer_b_value() const { return byte(0x12, 0, 8); }
uint32_t csm() const { return byte(0x14, 7, 1); }
uint32_t reset_timer_b() const { return byte(0x14, 5, 1); }
uint32_t reset_timer_a() const { return byte(0x14, 4, 1); }
uint32_t enable_timer_b() const { return byte(0x14, 3, 1); }
uint32_t enable_timer_a() const { return byte(0x14, 2, 1); }
uint32_t load_timer_b() const { return byte(0x14, 1, 1); }
uint32_t load_timer_a() const { return byte(0x14, 0, 1); }
uint32_t lfo2_pm_depth() const { return byte(0x188, 0, 7); } // fake
uint32_t lfo2_rate() const { return byte(0x16, 0, 8); }
uint32_t lfo2_am_depth() const { return byte(0x17, 0, 7); }
uint32_t lfo_rate() const { return byte(0x18, 0, 8); }
uint32_t lfo_am_depth() const { return byte(0x19, 0, 7); }
uint32_t lfo_pm_depth() const { return byte(0x189, 0, 7); } // fake
uint32_t output_bits() const { return byte(0x1b, 6, 2); }
uint32_t lfo2_sync() const { return byte(0x1b, 5, 1); }
uint32_t lfo_sync() const { return byte(0x1b, 4, 1); }
uint32_t lfo2_waveform() const { return byte(0x1b, 2, 2); }
uint32_t lfo_waveform() const { return byte(0x1b, 0, 2); }
// per-channel registers
uint32_t ch_volume(uint32_t choffs) const { return byte(0x00, 0, 8, choffs); }
uint32_t ch_output_any(uint32_t choffs) const { return byte(0x20, 7, 1, choffs) | byte(0x30, 0, 1, choffs); }
uint32_t ch_output_0(uint32_t choffs) const { return byte(0x30, 0, 1, choffs); }
uint32_t ch_output_1(uint32_t choffs) const { return byte(0x20, 7, 1, choffs) | byte(0x30, 0, 1, choffs); }
uint32_t ch_output_2(uint32_t choffs) const { return 0; }
uint32_t ch_output_3(uint32_t choffs) const { return 0; }
uint32_t ch_key_on(uint32_t choffs) const { return byte(0x20, 6, 1, choffs); }
uint32_t ch_feedback(uint32_t choffs) const { return byte(0x20, 3, 3, choffs); }
uint32_t ch_algorithm(uint32_t choffs) const { return byte(0x20, 0, 3, choffs); }
uint32_t ch_block_freq(uint32_t choffs) const { return word(0x28, 0, 7, 0x30, 2, 6, choffs); }
uint32_t ch_lfo_pm_sens(uint32_t choffs) const { return byte(0x38, 4, 3, choffs); }
uint32_t ch_lfo_am_sens(uint32_t choffs) const { return byte(0x38, 0, 2, choffs); }
uint32_t ch_lfo2_pm_sens(uint32_t choffs) const { return byte(0x180, 4, 3, choffs); } // fake
uint32_t ch_lfo2_am_sens(uint32_t choffs) const { return byte(0x180, 0, 2, choffs); } // fake
// per-operator registers
uint32_t op_detune(uint32_t opoffs) const { return byte(0x40, 4, 3, opoffs); }
uint32_t op_multiple(uint32_t opoffs) const { return byte(0x40, 0, 4, opoffs); }
uint32_t op_fix_range(uint32_t opoffs) const { return byte(0x40, 4, 3, opoffs); }
uint32_t op_fix_frequency(uint32_t opoffs) const { return byte(0x40, 0, 4, opoffs); }
uint32_t op_waveform(uint32_t opoffs) const { return byte(0x100, 4, 3, opoffs); } // fake
uint32_t op_fine(uint32_t opoffs) const { return byte(0x100, 0, 4, opoffs); } // fake
uint32_t op_total_level(uint32_t opoffs) const { return byte(0x60, 0, 7, opoffs); }
uint32_t op_ksr(uint32_t opoffs) const { return byte(0x80, 6, 2, opoffs); }
uint32_t op_fix_mode(uint32_t opoffs) const { return byte(0x80, 5, 1, opoffs); }
uint32_t op_attack_rate(uint32_t opoffs) const { return byte(0x80, 0, 5, opoffs); }
uint32_t op_lfo_am_enable(uint32_t opoffs) const { return byte(0xa0, 7, 1, opoffs); }
uint32_t op_decay_rate(uint32_t opoffs) const { return byte(0xa0, 0, 5, opoffs); }
uint32_t op_detune2(uint32_t opoffs) const { return byte(0xc0, 6, 2, opoffs); }
uint32_t op_sustain_rate(uint32_t opoffs) const { return byte(0xc0, 0, 5, opoffs); }
uint32_t op_eg_shift(uint32_t opoffs) const { return byte(0x120, 6, 2, opoffs); } // fake
uint32_t op_reverb_rate(uint32_t opoffs) const { return byte(0x120, 0, 3, opoffs); } // fake
uint32_t op_sustain_level(uint32_t opoffs) const { return byte(0xe0, 4, 4, opoffs); }
uint32_t op_release_rate(uint32_t opoffs) const { return byte(0xe0, 0, 4, opoffs); }
protected:
// return a bitfield extracted from a byte
uint32_t byte(uint32_t offset, uint32_t start, uint32_t count, uint32_t extra_offset = 0) const
{
return bitfield(m_regdata[offset + extra_offset], start, count);
}
// return a bitfield extracted from a pair of bytes, MSBs listed first
uint32_t word(uint32_t offset1, uint32_t start1, uint32_t count1, uint32_t offset2, uint32_t start2, uint32_t count2, uint32_t extra_offset = 0) const
{
return (byte(offset1, start1, count1, extra_offset) << count2) | byte(offset2, start2, count2, extra_offset);
}
// internal state
uint32_t m_lfo_counter[2]; // LFO counter
uint32_t m_noise_lfsr; // noise LFSR state
uint8_t m_noise_counter; // noise counter
uint8_t m_noise_state; // latched noise state
uint8_t m_noise_lfo; // latched LFO noise value
uint8_t m_lfo_am[2]; // current LFO AM value
uint8_t m_regdata[REGISTERS]; // register data
uint16_t m_phase_substep[OPERATORS]; // phase substep for fixed frequency
int16_t m_lfo_waveform[4][LFO_WAVEFORM_LENGTH]; // LFO waveforms; AM in low 8, PM in upper 8
uint16_t m_waveform[WAVEFORMS][WAVEFORM_LENGTH]; // waveforms
};
//*********************************************************
// IMPLEMENTATION CLASSES
//*********************************************************
// ======================> ym2414
class ym2414
{
public:
using fm_engine = fm_engine_base<opz_registers>;
static constexpr uint32_t OUTPUTS = fm_engine::OUTPUTS;
using output_data = fm_engine::output_data;
// constructor
ym2414(ymfm_interface &intf);
// reset
void reset();
// save/restore
void save_restore(ymfm_saved_state &state);
// pass-through helpers
uint32_t sample_rate(uint32_t input_clock) const { return m_fm.sample_rate(input_clock); }
void invalidate_caches() { m_fm.invalidate_caches(); }
// read access
uint8_t read_status();
uint8_t read(uint32_t offset);
// write access
void write_address(uint8_t data);
void write_data(uint8_t data);
void write(uint32_t offset, uint8_t data);
// generate one sample of sound
void generate(output_data *output, uint32_t numsamples = 1);
protected:
// internal state
uint8_t m_address; // address register
fm_engine m_fm; // core FM engine
};
}
#endif // YMFM_OPZ_H
``` | /content/code_sandbox/src/sound/ymfm/ymfm_opz.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 4,156 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Handle the platform-side of CDROM/ZIP/MO drives.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/config.h>
#include <86box/timer.h>
#include <86box/device.h>
#include <86box/cassette.h>
#include <86box/cartridge.h>
#include <86box/fdd.h>
#include <86box/hdd.h>
#include <86box/scsi_device.h>
#include <86box/cdrom.h>
#include <86box/mo.h>
#include <86box/zip.h>
#include <86box/scsi_disk.h>
#include <86box/plat.h>
#include <86box/ui.h>
void
cassette_mount(char *fn, uint8_t wp)
{
pc_cas_set_fname(cassette, NULL);
memset(cassette_fname, 0, sizeof(cassette_fname));
cassette_ui_writeprot = wp;
pc_cas_set_fname(cassette, fn);
if (fn != NULL)
memcpy(cassette_fname, fn, MIN(511, strlen(fn)));
ui_sb_update_icon_state(SB_CASSETTE, (fn == NULL) ? 1 : 0);
#if 0
media_menu_update_cassette();
#endif
ui_sb_update_tip(SB_CASSETTE);
config_save();
}
void
cassette_eject(void)
{
pc_cas_set_fname(cassette, NULL);
memset(cassette_fname, 0x00, sizeof(cassette_fname));
ui_sb_update_icon_state(SB_CASSETTE, 1);
#if 0
media_menu_update_cassette();
#endif
ui_sb_update_tip(SB_CASSETTE);
config_save();
}
void
cartridge_mount(uint8_t id, char *fn, uint8_t wp)
{
cart_close(id);
cart_load(id, fn);
ui_sb_update_icon_state(SB_CARTRIDGE | id, strlen(cart_fns[id]) ? 0 : 1);
#if 0
media_menu_update_cartridge(id);
#endif
ui_sb_update_tip(SB_CARTRIDGE | id);
config_save();
}
void
cartridge_eject(uint8_t id)
{
cart_close(id);
ui_sb_update_icon_state(SB_CARTRIDGE | id, 1);
#if 0
media_menu_update_cartridge(id);
#endif
ui_sb_update_tip(SB_CARTRIDGE | id);
config_save();
}
void
floppy_mount(uint8_t id, char *fn, uint8_t wp)
{
fdd_close(id);
ui_writeprot[id] = wp;
fdd_load(id, fn);
ui_sb_update_icon_state(SB_FLOPPY | id, strlen(floppyfns[id]) ? 0 : 1);
#if 0
media_menu_update_floppy(id);
#endif
ui_sb_update_tip(SB_FLOPPY | id);
config_save();
}
void
floppy_eject(uint8_t id)
{
fdd_close(id);
ui_sb_update_icon_state(SB_FLOPPY | id, 1);
#if 0
media_menu_update_floppy(id);
#endif
ui_sb_update_tip(SB_FLOPPY | id);
config_save();
}
void
plat_cdrom_ui_update(uint8_t id, uint8_t reload)
{
cdrom_t *drv = &cdrom[id];
if (drv->image_path[0] == 0x00) {
ui_sb_update_icon_state(SB_CDROM | id, 1);
} else {
ui_sb_update_icon_state(SB_CDROM | id, 0);
}
#if 0
media_menu_update_cdrom(id);
#endif
ui_sb_update_tip(SB_CDROM | id);
}
void
cdrom_mount(uint8_t id, char *fn)
{
strcpy(cdrom[id].prev_image_path, cdrom[id].image_path);
if (cdrom[id].ops && cdrom[id].ops->exit)
cdrom[id].ops->exit(&(cdrom[id]));
cdrom[id].ops = NULL;
memset(cdrom[id].image_path, 0, sizeof(cdrom[id].image_path));
if ((fn != NULL) && (strlen(fn) >= 1) && (fn[strlen(fn) - 1] == '\\'))
fn[strlen(fn) - 1] = '/';
cdrom_image_open(&(cdrom[id]), fn);
/* Signal media change to the emulated machine. */
if (cdrom[id].insert)
cdrom[id].insert(cdrom[id].priv);
if (cdrom[id].image_path[0] == 0x00)
ui_sb_update_icon_state(SB_CDROM | id, 0);
else
ui_sb_update_icon_state(SB_CDROM | id, 1);
#if 0
media_menu_update_cdrom(id);
#endif
ui_sb_update_tip(SB_CDROM | id);
config_save();
}
void
mo_eject(uint8_t id)
{
mo_t *dev = (mo_t *) mo_drives[id].priv;
mo_disk_close(dev);
if (mo_drives[id].bus_type) {
/* Signal disk change to the emulated machine. */
mo_insert(dev);
}
ui_sb_update_icon_state(SB_MO | id, 1);
#if 0
media_menu_update_mo(id);
#endif
ui_sb_update_tip(SB_MO | id);
config_save();
}
void
mo_mount(uint8_t id, char *fn, uint8_t wp)
{
mo_t *dev = (mo_t *) mo_drives[id].priv;
mo_disk_close(dev);
mo_drives[id].read_only = wp;
mo_load(dev, fn);
mo_insert(dev);
ui_sb_update_icon_state(SB_MO | id, strlen(mo_drives[id].image_path) ? 0 : 1);
#if 0
media_menu_update_mo(id);
#endif
ui_sb_update_tip(SB_MO | id);
config_save();
}
void
mo_reload(uint8_t id)
{
mo_t *dev = (mo_t *) mo_drives[id].priv;
mo_disk_reload(dev);
if (strlen(mo_drives[id].image_path) == 0) {
ui_sb_update_icon_state(SB_MO | id, 1);
} else {
ui_sb_update_icon_state(SB_MO | id, 0);
}
#if 0
media_menu_update_mo(id);
#endif
ui_sb_update_tip(SB_MO | id);
config_save();
}
void
zip_eject(uint8_t id)
{
zip_t *dev = (zip_t *) zip_drives[id].priv;
zip_disk_close(dev);
if (zip_drives[id].bus_type) {
/* Signal disk change to the emulated machine. */
zip_insert(dev);
}
ui_sb_update_icon_state(SB_ZIP | id, 1);
#if 0
media_menu_update_zip(id);
#endif
ui_sb_update_tip(SB_ZIP | id);
config_save();
}
void
zip_mount(uint8_t id, char *fn, uint8_t wp)
{
zip_t *dev = (zip_t *) zip_drives[id].priv;
zip_disk_close(dev);
zip_drives[id].read_only = wp;
zip_load(dev, fn);
zip_insert(dev);
ui_sb_update_icon_state(SB_ZIP | id, strlen(zip_drives[id].image_path) ? 0 : 1);
#if 0
media_menu_update_zip(id);
#endif
ui_sb_update_tip(SB_ZIP | id);
config_save();
}
void
zip_reload(uint8_t id)
{
zip_t *dev = (zip_t *) zip_drives[id].priv;
zip_disk_reload(dev);
if (strlen(zip_drives[id].image_path) == 0) {
ui_sb_update_icon_state(SB_ZIP | id, 1);
} else {
ui_sb_update_icon_state(SB_ZIP | id, 0);
}
#if 0
media_menu_update_zip(id);
#endif
ui_sb_update_tip(SB_ZIP | id);
config_save();
}
``` | /content/code_sandbox/src/unix/unix_cdrom.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,906 |
```c
#include <SDL.h>
#include <SDL_messagebox.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/param.h>
/* This #undef is needed because a SDL include header redefines HAVE_STDARG_H. */
#undef HAVE_STDARG_H
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/plat.h>
#include <86box/plat_dynld.h>
#include <86box/video.h>
#include <86box/ui.h>
#include <86box/version.h>
#include <86box/unix_sdl.h>
#define RENDERER_FULL_SCREEN 1
#define RENDERER_HARDWARE 2
#define RENDERER_OPENGL 4
typedef struct sdl_blit_params {
int x;
int y;
int w;
int h;
} sdl_blit_params;
extern sdl_blit_params params;
extern int blitreq;
SDL_Window *sdl_win = NULL;
SDL_Renderer *sdl_render = NULL;
static SDL_Texture *sdl_tex = NULL;
int sdl_w = SCREEN_RES_X;
int sdl_h = SCREEN_RES_Y;
static int sdl_fs;
static int sdl_flags = -1;
static int cur_w;
static int cur_h;
static int cur_wx = 0;
static int cur_wy = 0;
static int cur_ww = 0;
static int cur_wh = 0;
static volatile int sdl_enabled = 1;
static SDL_mutex *sdl_mutex = NULL;
int mouse_capture;
int title_set = 0;
int resize_pending = 0;
int resize_w = 0;
int resize_h = 0;
static void *pixeldata;
extern void RenderImGui(void);
static void
sdl_integer_scale(double *d, double *g)
{
double ratio;
if (*d > *g) {
ratio = floor(*d / *g);
*d = *g * ratio;
} else {
ratio = ceil(*d / *g);
*d = *g / ratio;
}
}
void sdl_reinit_texture(void);
static void
sdl_stretch(int *w, int *h, int *x, int *y)
{
double hw;
double gw;
double hh;
double gh;
double dx;
double dy;
double dw;
double dh;
double gsr;
double hsr;
int real_sdl_w;
int real_sdl_h;
SDL_GL_GetDrawableSize(sdl_win, &real_sdl_w, &real_sdl_h);
hw = (double) real_sdl_w;
hh = (double) real_sdl_h;
gw = (double) *w;
gh = (double) *h;
hsr = hw / hh;
switch (video_fullscreen_scale) {
case FULLSCR_SCALE_FULL:
default:
*w = real_sdl_w;
*h = real_sdl_h;
*x = 0;
*y = 0;
break;
case FULLSCR_SCALE_43:
case FULLSCR_SCALE_KEEPRATIO:
if (video_fullscreen_scale == FULLSCR_SCALE_43)
gsr = 4.0 / 3.0;
else
gsr = gw / gh;
if (gsr <= hsr) {
dw = hh * gsr;
dh = hh;
} else {
dw = hw;
dh = hw / gsr;
}
dx = (hw - dw) / 2.0;
dy = (hh - dh) / 2.0;
*w = (int) dw;
*h = (int) dh;
*x = (int) dx;
*y = (int) dy;
break;
case FULLSCR_SCALE_INT:
gsr = gw / gh;
if (gsr <= hsr) {
dw = hh * gsr;
dh = hh;
} else {
dw = hw;
dh = hw / gsr;
}
sdl_integer_scale(&dw, &gw);
sdl_integer_scale(&dh, &gh);
dx = (hw - dw) / 2.0;
dy = (hh - dh) / 2.0;
*w = (int) dw;
*h = (int) dh;
*x = (int) dx;
*y = (int) dy;
break;
}
}
void
sdl_blit_shim(int x, int y, int w, int h, int monitor_index)
{
params.x = x;
params.y = y;
params.w = w;
params.h = h;
if (!(!sdl_enabled || (x < 0) || (y < 0) || (w <= 0) || (h <= 0) || (w > 2048) || (h > 2048) || (buffer32 == NULL) || (sdl_render == NULL) || (sdl_tex == NULL)) || (monitor_index >= 1))
for (int row = 0; row < h; ++row)
video_copy(&(((uint8_t *) pixeldata)[row * 2048 * sizeof(uint32_t)]), &(buffer32->line[y + row][x]), w * sizeof(uint32_t));
if (monitors[monitor_index].mon_screenshots)
video_screenshot((uint32_t *) pixeldata, 0, 0, 2048);
blitreq = 1;
video_blit_complete_monitor(monitor_index);
}
void ui_window_title_real(void);
void
sdl_real_blit(SDL_Rect *r_src)
{
SDL_Rect r_dst;
int ret;
int winx;
int winy;
SDL_GL_GetDrawableSize(sdl_win, &winx, &winy);
SDL_RenderClear(sdl_render);
r_dst = *r_src;
r_dst.x = r_dst.y = 0;
if (sdl_fs) {
sdl_stretch(&r_dst.w, &r_dst.h, &r_dst.x, &r_dst.y);
} else {
r_dst.w *= ((float) winx / (float) r_dst.w);
r_dst.h *= ((float) winy / (float) r_dst.h);
}
ret = SDL_RenderCopy(sdl_render, sdl_tex, r_src, &r_dst);
if (ret)
fprintf(stderr, "SDL: unable to copy texture to renderer (%s)\n", SDL_GetError());
SDL_RenderPresent(sdl_render);
}
void
sdl_blit(int x, int y, int w, int h)
{
SDL_Rect r_src;
if (!sdl_enabled || (x < 0) || (y < 0) || (w <= 0) || (h <= 0) || (w > 2048) || (h > 2048) || (buffer32 == NULL) || (sdl_render == NULL) || (sdl_tex == NULL)) {
r_src.x = x;
r_src.y = y;
r_src.w = w;
r_src.h = h;
sdl_real_blit(&r_src);
blitreq = 0;
return;
}
SDL_LockMutex(sdl_mutex);
if (resize_pending) {
if (!video_fullscreen)
sdl_resize(resize_w, resize_h);
resize_pending = 0;
}
r_src.x = x;
r_src.y = y;
r_src.w = w;
r_src.h = h;
SDL_UpdateTexture(sdl_tex, &r_src, pixeldata, 2048 * 4);
blitreq = 0;
sdl_real_blit(&r_src);
SDL_UnlockMutex(sdl_mutex);
}
static void
sdl_destroy_window(void)
{
if (sdl_win != NULL) {
if (window_remember) {
SDL_GetWindowSize(sdl_win, &window_w, &window_h);
if (strncasecmp(SDL_GetCurrentVideoDriver(), "wayland", 7) != 0) {
SDL_GetWindowPosition(sdl_win, &window_x, &window_y);
}
}
SDL_DestroyWindow(sdl_win);
sdl_win = NULL;
}
}
static void
sdl_destroy_texture(void)
{
/* SDL_DestroyRenderer also automatically destroys all associated textures. */
if (sdl_render != NULL) {
SDL_DestroyRenderer(sdl_render);
sdl_render = NULL;
}
}
void
sdl_close(void)
{
if (sdl_mutex != NULL)
SDL_LockMutex(sdl_mutex);
/* Unregister our renderer! */
video_setblit(NULL);
if (sdl_enabled)
sdl_enabled = 0;
if (sdl_mutex != NULL) {
SDL_DestroyMutex(sdl_mutex);
sdl_mutex = NULL;
}
sdl_destroy_texture();
sdl_destroy_window();
if (pixeldata != NULL) {
free(pixeldata);
pixeldata = NULL;
}
/* Quit. */
SDL_Quit();
sdl_flags = -1;
}
void
sdl_enable(int enable)
{
if (sdl_flags == -1)
return;
SDL_LockMutex(sdl_mutex);
sdl_enabled = !!enable;
if (enable == 1) {
SDL_SetWindowSize(sdl_win, cur_ww, cur_wh);
sdl_reinit_texture();
}
SDL_UnlockMutex(sdl_mutex);
}
static void
sdl_select_best_hw_driver(void)
{
SDL_RendererInfo renderInfo;
for (int i = 0; i < SDL_GetNumRenderDrivers(); ++i) {
SDL_GetRenderDriverInfo(i, &renderInfo);
if (renderInfo.flags & SDL_RENDERER_ACCELERATED) {
SDL_SetHint(SDL_HINT_RENDER_DRIVER, renderInfo.name);
return;
}
}
}
void
sdl_reinit_texture(void)
{
sdl_destroy_texture();
if (sdl_flags & RENDERER_HARDWARE) {
sdl_render = SDL_CreateRenderer(sdl_win, -1, SDL_RENDERER_ACCELERATED);
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, video_filter_method ? "1" : "0");
} else
sdl_render = SDL_CreateRenderer(sdl_win, -1, SDL_RENDERER_SOFTWARE);
sdl_tex = SDL_CreateTexture(sdl_render, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING, 2048, 2048);
}
void
sdl_set_fs(int fs)
{
SDL_LockMutex(sdl_mutex);
SDL_SetWindowFullscreen(sdl_win, fs ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
SDL_SetRelativeMouseMode((SDL_bool) mouse_capture);
sdl_fs = fs;
if (fs)
sdl_flags |= RENDERER_FULL_SCREEN;
else
sdl_flags &= ~RENDERER_FULL_SCREEN;
sdl_reinit_texture();
SDL_UnlockMutex(sdl_mutex);
}
void
sdl_resize(int x, int y)
{
int ww = 0;
int wh = 0;
int wx = 0;
int wy = 0;
if (video_fullscreen & 2)
return;
if ((x == cur_w) && (y == cur_h))
return;
SDL_LockMutex(sdl_mutex);
ww = x;
wh = y;
cur_w = x;
cur_h = y;
cur_wx = wx;
cur_wy = wy;
cur_ww = ww;
cur_wh = wh;
SDL_SetWindowSize(sdl_win, cur_ww, cur_wh);
SDL_GL_GetDrawableSize(sdl_win, &sdl_w, &sdl_h);
sdl_reinit_texture();
SDL_UnlockMutex(sdl_mutex);
}
void
sdl_reload(void)
{
if (sdl_flags & RENDERER_HARDWARE) {
SDL_LockMutex(sdl_mutex);
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, video_filter_method ? "1" : "0");
sdl_reinit_texture();
SDL_UnlockMutex(sdl_mutex);
}
}
int
plat_vidapi(UNUSED(const char *api))
{
return 0;
}
static int
sdl_init_common(int flags)
{
SDL_version ver;
/* Get and log the version of the DLL we are using. */
SDL_GetVersion(&ver);
fprintf(stderr, "SDL: version %d.%d.%d\n", ver.major, ver.minor, ver.patch);
/* Initialize the SDL system. */
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "SDL: initialization failed (%s)\n", SDL_GetError());
return (0);
}
if (flags & RENDERER_HARDWARE) {
if (flags & RENDERER_OPENGL) {
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "OpenGL");
} else
sdl_select_best_hw_driver();
}
sdl_mutex = SDL_CreateMutex();
sdl_win = SDL_CreateWindow("86Box", strncasecmp(SDL_GetCurrentVideoDriver(), "wayland", 7) != 0 && window_remember ? window_x : SDL_WINDOWPOS_CENTERED, strncasecmp(SDL_GetCurrentVideoDriver(), "wayland", 7) != 0 && window_remember ? window_y : SDL_WINDOWPOS_CENTERED, scrnsz_x, scrnsz_y, SDL_WINDOW_OPENGL | (vid_resize & 1 ? SDL_WINDOW_RESIZABLE : 0));
sdl_set_fs(video_fullscreen);
if (!(video_fullscreen & 1)) {
if (vid_resize & 2)
plat_resize(fixed_size_x, fixed_size_y, 0);
else
plat_resize(scrnsz_x, scrnsz_y, 0);
}
if ((vid_resize < 2) && window_remember) {
SDL_SetWindowSize(sdl_win, window_w, window_h);
}
/* Make sure we get a clean exit. */
atexit(sdl_close);
pixeldata = malloc(2048 * 2048 * 4);
/* Register our renderer! */
video_setblit(sdl_blit_shim);
sdl_enabled = 1;
return (1);
}
int
sdl_inits(void)
{
return sdl_init_common(0);
}
int
sdl_inith(void)
{
return sdl_init_common(RENDERER_HARDWARE);
}
int
sdl_initho(void)
{
return sdl_init_common(RENDERER_HARDWARE | RENDERER_OPENGL);
}
int
sdl_pause(void)
{
return 0;
}
void
plat_mouse_capture(int on)
{
SDL_LockMutex(sdl_mutex);
SDL_SetRelativeMouseMode((SDL_bool) on);
mouse_capture = on;
SDL_UnlockMutex(sdl_mutex);
}
void
plat_resize(int w, int h, UNUSED(int monitor_index))
{
SDL_LockMutex(sdl_mutex);
resize_w = w;
resize_h = h;
resize_pending = 1;
SDL_UnlockMutex(sdl_mutex);
}
wchar_t sdl_win_title[512] = { L'8', L'6', L'B', L'o', L'x', 0 };
SDL_mutex *titlemtx = NULL;
void
ui_window_title_real(void)
{
char *res;
if (sizeof(wchar_t) == 1) {
SDL_SetWindowTitle(sdl_win, (char *) sdl_win_title);
return;
}
res = SDL_iconv_string("UTF-8", sizeof(wchar_t) == 2 ? "UTF-16LE" : "UTF-32LE", (char *) sdl_win_title, wcslen(sdl_win_title) * sizeof(wchar_t) + sizeof(wchar_t));
if (res) {
SDL_SetWindowTitle(sdl_win, res);
SDL_free((void *) res);
}
title_set = 0;
}
extern SDL_threadID eventthread;
/* Only activate threading path on macOS, otherwise it will softlock Xorg.
Wayland doesn't seem to have this issue. */
wchar_t *
ui_window_title(wchar_t *str)
{
if (!str)
return sdl_win_title;
#ifdef __APPLE__
if (eventthread == SDL_ThreadID())
#endif
{
memset(sdl_win_title, 0, sizeof(sdl_win_title));
wcsncpy(sdl_win_title, str, 512);
ui_window_title_real();
return str;
}
#ifdef __APPLE__
memset(sdl_win_title, 0, sizeof(sdl_win_title));
wcsncpy(sdl_win_title, str, 512);
title_set = 1;
#endif
return str;
}
void
ui_init_monitor(int monitor_index)
{
/* No-op. */
}
void
ui_deinit_monitor(int monitor_index)
{
/* No-op. */
}
void
plat_resize_request(int w, int h, int monitor_index)
{
atomic_store((&doresize_monitors[monitor_index]), 1);
}
``` | /content/code_sandbox/src/unix/unix_sdl.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,728 |
```c
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/log.h>
#include <86box/timer.h>
#include <86box/plat.h>
#include <86box/device.h>
#include <86box/plat_netsocket.h>
#include <86box/ui.h>
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <unistd.h>
SOCKET
plat_netsocket_create(int type)
{
SOCKET fd = -1;
int yes = 1;
if (type != NET_SOCKET_TCP)
return -1;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
return -1;
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &yes, sizeof(yes));
return fd;
}
SOCKET
plat_netsocket_create_server(int type, unsigned short port)
{
struct sockaddr_in sock_addr;
SOCKET fd = -1;
int yes = 1;
if (type != NET_SOCKET_TCP)
return -1;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
return -1;
memset(&sock_addr, 0, sizeof(struct sockaddr_in));
sock_addr.sin_family = AF_INET;
sock_addr.sin_addr.s_addr = INADDR_ANY;
sock_addr.sin_port = htons(port);
if (bind(fd, (struct sockaddr *) &sock_addr, sizeof(struct sockaddr_in)) == -1) {
plat_netsocket_close(fd);
return (SOCKET) -1;
}
if (listen(fd, 5) == -1) {
plat_netsocket_close(fd);
return (SOCKET) -1;
}
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &yes, sizeof(yes));
return fd;
}
void
plat_netsocket_close(SOCKET socket)
{
close((SOCKET) socket);
}
SOCKET
plat_netsocket_accept(SOCKET socket)
{
SOCKET clientsocket = accept(socket, NULL, NULL);
if (clientsocket == -1)
return -1;
return clientsocket;
}
int
plat_netsocket_connected(SOCKET socket)
{
struct sockaddr addr;
socklen_t len = sizeof(struct sockaddr);
fd_set wrfds;
struct timeval tv;
int res = -1;
int status = 0;
socklen_t optlen = 4;
FD_ZERO(&wrfds);
FD_SET(socket, &wrfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
res = select(socket + 1, NULL, &wrfds, NULL, &tv);
if (res == -1)
return -1;
if (res == 0 || !(res >= 1 && FD_ISSET(socket, &wrfds)))
return 0;
res = getsockopt(socket, SOL_SOCKET, SO_ERROR, (char *) &status, &optlen);
if (res == -1)
return -1;
if (status != 0)
return -1;
if (getpeername(socket, &addr, &len) == -1)
return -1;
return 1;
}
int
plat_netsocket_connect(SOCKET socket, const char *hostname, unsigned short port)
{
struct sockaddr_in sock_addr;
int res = -1;
sock_addr.sin_family = AF_INET;
sock_addr.sin_addr.s_addr = inet_addr(hostname);
sock_addr.sin_port = htons(port);
if (sock_addr.sin_addr.s_addr == ((in_addr_t) -1) || sock_addr.sin_addr.s_addr == 0) {
struct hostent *hp;
hp = gethostbyname(hostname);
if (hp)
memcpy(&sock_addr.sin_addr.s_addr, hp->h_addr_list[0], hp->h_length);
else
return -1;
}
res = connect(socket, (struct sockaddr *) &sock_addr, sizeof(struct sockaddr_in));
if (res == -1) {
int error = errno;
if (error == EISCONN || error == EWOULDBLOCK || error == EAGAIN || error == EINPROGRESS)
return 0;
res = -1;
}
return res;
}
int
plat_netsocket_send(SOCKET socket, const unsigned char *data, unsigned int size, int *wouldblock)
{
int res = send(socket, (const char *) data, size, 0);
if (res == -1) {
int error = errno;
if (wouldblock)
*wouldblock = !!(error == EWOULDBLOCK || error == EAGAIN);
return -1;
}
return res;
}
int
plat_netsocket_receive(SOCKET socket, unsigned char *data, unsigned int size, int *wouldblock)
{
int res = recv(socket, (char *) data, size, 0);
if (res == -1) {
int error = errno;
if (wouldblock)
*wouldblock = !!(error == EWOULDBLOCK || error == EAGAIN);
return -1;
}
return res;
}
``` | /content/code_sandbox/src/unix/unix_netsocket.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,255 |
```c
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <inttypes.h>
#include <86box/86box.h>
#include <86box/plat.h>
#include <86box/thread.h>
typedef struct event_pthread_t {
pthread_cond_t cond;
pthread_mutex_t mutex;
int state;
} event_pthread_t;
typedef struct thread_param {
void (*thread_rout)(void *);
void *param;
} thread_param;
typedef struct pt_mutex_t {
pthread_mutex_t mutex;
} pt_mutex_t;
void *
thread_run_wrapper(thread_param *arg)
{
thread_param localparam = *arg;
free(arg);
localparam.thread_rout(localparam.param);
return NULL;
}
thread_t *
thread_create_named(void (*thread_rout)(void *param), void *param, const char *name)
{
pthread_t *thread = malloc(sizeof(pthread_t));
thread_param *thrparam = malloc(sizeof(thread_param));
thrparam->thread_rout = thread_rout;
thrparam->param = param;
pthread_create(thread, NULL, (void *(*) (void *) ) thread_run_wrapper, thrparam);
plat_set_thread_name(thread, name);
return thread;
}
int
thread_wait(thread_t *arg)
{
return pthread_join(*(pthread_t *) (arg), NULL);
}
event_t *
thread_create_event(void)
{
event_pthread_t *event = malloc(sizeof(event_pthread_t));
pthread_cond_init(&event->cond, NULL);
pthread_mutex_init(&event->mutex, NULL);
event->state = 0;
return (event_t *) event;
}
void
thread_set_event(event_t *handle)
{
event_pthread_t *event = (event_pthread_t *) handle;
pthread_mutex_lock(&event->mutex);
event->state = 1;
pthread_cond_broadcast(&event->cond);
pthread_mutex_unlock(&event->mutex);
}
void
thread_reset_event(event_t *handle)
{
event_pthread_t *event = (event_pthread_t *) handle;
pthread_mutex_lock(&event->mutex);
event->state = 0;
pthread_mutex_unlock(&event->mutex);
}
int
thread_wait_event(event_t *handle, int timeout)
{
event_pthread_t *event = (event_pthread_t *) handle;
struct timespec abstime;
clock_gettime(CLOCK_REALTIME, &abstime);
abstime.tv_nsec += (timeout % 1000) * 1000000;
abstime.tv_sec += (timeout / 1000);
if (abstime.tv_nsec > 1000000000) {
abstime.tv_nsec -= 1000000000;
abstime.tv_sec++;
}
pthread_mutex_lock(&event->mutex);
if (timeout == -1) {
while (!event->state)
pthread_cond_wait(&event->cond, &event->mutex);
} else if (!event->state)
pthread_cond_timedwait(&event->cond, &event->mutex, &abstime);
pthread_mutex_unlock(&event->mutex);
return 0;
}
void
thread_destroy_event(event_t *handle)
{
event_pthread_t *event = (event_pthread_t *) handle;
pthread_cond_destroy(&event->cond);
pthread_mutex_destroy(&event->mutex);
free(event);
}
mutex_t *
thread_create_mutex(void)
{
pt_mutex_t *mutex = malloc(sizeof(pt_mutex_t));
pthread_mutex_init(&mutex->mutex, NULL);
return mutex;
}
int
thread_wait_mutex(mutex_t *_mutex)
{
if (_mutex == NULL)
return 0;
pt_mutex_t *mutex = (pt_mutex_t *) _mutex;
return pthread_mutex_lock(&mutex->mutex) != 0;
}
int
thread_test_mutex(mutex_t *_mutex)
{
if (_mutex == NULL)
return 0;
pt_mutex_t *mutex = (pt_mutex_t *) _mutex;
return pthread_mutex_trylock(&mutex->mutex) != 0;
}
int
thread_release_mutex(mutex_t *_mutex)
{
if (_mutex == NULL)
return 0;
pt_mutex_t *mutex = (pt_mutex_t *) _mutex;
return pthread_mutex_unlock(&mutex->mutex) != 0;
}
void
thread_close_mutex(mutex_t *_mutex)
{
pt_mutex_t *mutex = (pt_mutex_t *) _mutex;
pthread_mutex_destroy(&mutex->mutex);
free(mutex);
}
``` | /content/code_sandbox/src/unix/unix_thread.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 961 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Win32 CD-ROM support via IOCTL.
*
*
*
* Authors: TheCollector1995, <mariogplayer@gmail.com>,
* Miran Grca, <mgrca8@gmail.com>
*
*/
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/scsi_device.h>
#include <86box/cdrom.h>
#include <86box/plat_unused.h>
#include <86box/plat_cdrom.h>
/* The addresses sent from the guest are absolute, ie. a LBA of 0 corresponds to a MSF of 00:00:00. Otherwise, the counter displayed by the guest is wrong:
there is a seeming 2 seconds in which audio plays but counter does not move, while a data track before audio jumps to 2 seconds before the actual start
of the audio while audio still plays. With an absolute conversion, the counter is fine. */
#define MSFtoLBA(m, s, f) ((((m * 60) + s) * 75) + f)
static int toc_valid = 0;
#ifdef ENABLE_DUMMY_CDROM_IOCTL_LOG
int dummy_cdrom_ioctl_do_log = ENABLE_DUMMY_CDROM_IOCTL_LOG;
void
dummy_cdrom_ioctl_log(const char *fmt, ...)
{
va_list ap;
if (dummy_cdrom_ioctl_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define dummy_cdrom_ioctl_log(fmt, ...)
#endif
static int
plat_cdrom_open(void)
{
return 0;
}
static int
plat_cdrom_load(void)
{
return 0;
}
static void
plat_cdrom_read_toc(void)
{
if (!toc_valid)
toc_valid = 1;
}
int
plat_cdrom_is_track_audio(uint32_t sector)
{
plat_cdrom_read_toc();
const int ret = 0;
dummy_cdrom_ioctl_log("plat_cdrom_is_track_audio(%08X): %i\n", sector, ret);
return ret;
}
int
plat_cdrom_is_track_pre(uint32_t sector)
{
plat_cdrom_read_toc();
const int ret = 0;
dummy_cdrom_ioctl_log("plat_cdrom_is_track_audio(%08X): %i\n", sector, ret);
return ret;
}
uint32_t
plat_cdrom_get_track_start(uint32_t sector, uint8_t *attr, uint8_t *track)
{
plat_cdrom_read_toc();
return 0x00000000;
}
uint32_t
plat_cdrom_get_last_block(void)
{
plat_cdrom_read_toc();
return 0x00000000;
}
int
plat_cdrom_ext_medium_changed(void)
{
int ret = 0;
dummy_cdrom_ioctl_log("plat_cdrom_ext_medium_changed(): %i\n", ret);
return ret;
}
void
plat_cdrom_get_audio_tracks(int *st_track, int *end, TMSF *lead_out)
{
plat_cdrom_read_toc();
*st_track = 1;
*end = 1;
lead_out->min = 0;
lead_out->sec = 0;
lead_out->fr = 2;
dummy_cdrom_ioctl_log("plat_cdrom_get_audio_tracks(): %02i, %02i, %02i:%02i:%02i\n",
*st_track, *end, lead_out->min, lead_out->sec, lead_out->fr);
}
/* This replaces both Info and EndInfo, they are specified by a variable. */
int
plat_cdrom_get_audio_track_info(UNUSED(int end), int track, int *track_num, TMSF *start, uint8_t *attr)
{
plat_cdrom_read_toc();
if ((track < 1) || (track == 0xaa)) {
dummy_cdrom_ioctl_log("plat_cdrom_get_audio_track_info(%02i)\n", track);
return 0;
}
start->min = 0;
start->sec = 0;
start->fr = 2;
*track_num = 1;
*attr = 0x14;
dummy_cdrom_ioctl_log("plat_cdrom_get_audio_track_info(%02i): %02i:%02i:%02i, %02i, %02X\n",
track, start->min, start->sec, start->fr, *track_num, *attr);
return 1;
}
/* TODO: See if track start is adjusted by 150 or not. */
int
plat_cdrom_get_audio_sub(UNUSED(uint32_t sector), uint8_t *attr, uint8_t *track, uint8_t *index, TMSF *rel_pos, TMSF *abs_pos)
{
*track = 1;
*attr = 0x14;
*index = 1;
rel_pos->min = 0;
rel_pos->sec = 0;
rel_pos->fr = 0;
abs_pos->min = 0;
abs_pos->sec = 0;
abs_pos->fr = 2;
dummy_cdrom_ioctl_log("plat_cdrom_get_audio_sub(): %02i, %02X, %02i, %02i:%02i:%02i, %02i:%02i:%02i\n",
*track, *attr, *index, rel_pos->min, rel_pos->sec, rel_pos->fr, abs_pos->min, abs_pos->sec, abs_pos->fr);
return 1;
}
int
plat_cdrom_get_sector_size(UNUSED(uint32_t sector))
{
dummy_cdrom_ioctl_log("BytesPerSector=2048\n");
return 2048;
}
int
plat_cdrom_read_sector(uint8_t *buffer, int raw, uint32_t sector)
{
plat_cdrom_open();
if (raw) {
dummy_cdrom_ioctl_log("Raw\n");
/* Raw */
} else {
dummy_cdrom_ioctl_log("Cooked\n");
/* Cooked */
}
plat_cdrom_close();
dummy_cdrom_ioctl_log("ReadSector sector=%d.\n", sector);
return 0;
}
void
plat_cdrom_eject(void)
{
plat_cdrom_open();
plat_cdrom_close();
}
void
plat_cdrom_close(void)
{
}
int
plat_cdrom_set_drive(const char *drv)
{
plat_cdrom_close();
toc_valid = 0;
plat_cdrom_load();
return 1;
}
``` | /content/code_sandbox/src/unix/dummy_cdrom_ioctl.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,525 |
```objective-c
//
// macOSXGlue.m
// 86BOx MacoSx Glue....
// Todo: so much
// Created by Jerome Vernet on 18/11/2021.
//
#import <Foundation/Foundation.h>
void
getDefaultROMPath(char *Path)
{
NSFileManager *sharedFM = [NSFileManager defaultManager];
NSArray *possibleURLs = [sharedFM URLsForDirectory:NSApplicationSupportDirectory
inDomains:NSUserDomainMask];
NSURL *appSupportDir = nil;
NSURL *appDirectory = nil;
if ([possibleURLs count] >= 1) {
// Use the first directory (if multiple are returned)
appSupportDir = [possibleURLs objectAtIndex:0];
}
// If a valid app support directory exists, add the
// app's bundle ID to it to specify the final directory.
if (appSupportDir) {
NSString *appBundleID = [[NSBundle mainBundle] bundleIdentifier];
appDirectory = [appSupportDir URLByAppendingPathComponent:appBundleID];
appDirectory = [appDirectory URLByAppendingPathComponent:@"roms"];
}
// create ~/Library/Application Support/... stuff
NSError *theError = nil;
if (![sharedFM createDirectoryAtURL:appDirectory
withIntermediateDirectories:YES
attributes:nil
error:&theError]) {
// Handle the error.
NSLog(@"Error creating user library rom path");
} else
NSLog(@"Create user rom path sucessfull");
strcpy(Path, [appDirectory fileSystemRepresentation]);
// return appDirectory;
}
``` | /content/code_sandbox/src/unix/macOSXGlue.m | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 344 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Definitions for platform specific serial to host passthrough
*
*
* Authors: Andreas J. Reichel <webmaster@6th-dimension.com>,
* Jasmine Iwanek <jasmine@iwanek.co.uk>
*
*/
#ifndef __APPLE__
# define _XOPEN_SOURCE 500
# define _DEFAULT_SOURCE 1
# define _BSD_SOURCE 1
#endif
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
# define __BSD_VISIBLE 1
#endif
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/select.h>
#include <stdint.h>
#include <sys/select.h>
#include <86box/86box.h>
#include <86box/log.h>
#include <86box/plat.h>
#include <86box/device.h>
#include <86box/serial_passthrough.h>
#include <86box/plat_serial_passthrough.h>
#include <termios.h>
#include <errno.h>
#define LOG_PREFIX "serial_passthrough: "
int
plat_serpt_read(void *priv, uint8_t *data)
{
serial_passthrough_t *dev = (serial_passthrough_t *) priv;
int res;
struct timeval tv;
fd_set rdfds;
switch (dev->mode) {
case SERPT_MODE_VCON:
case SERPT_MODE_HOSTSER:
FD_ZERO(&rdfds);
FD_SET(dev->master_fd, &rdfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
res = select(dev->master_fd + 1, &rdfds, NULL, NULL, &tv);
if (res <= 0 || !FD_ISSET(dev->master_fd, &rdfds)) {
return 0;
}
if (read(dev->master_fd, data, 1) > 0) {
return 1;
}
break;
default:
break;
}
return 0;
}
void
plat_serpt_close(void *priv)
{
serial_passthrough_t *dev = (serial_passthrough_t *) priv;
if (dev->mode == SERPT_MODE_HOSTSER) {
tcsetattr(dev->master_fd, TCSANOW, (struct termios *) dev->backend_priv);
free(dev->backend_priv);
}
close(dev->master_fd);
}
static void
plat_serpt_write_vcon(serial_passthrough_t *dev, uint8_t data)
{
#if 0
fd_set wrfds;
int res;
#endif
size_t res;
/* We cannot use select here, this would block the hypervisor! */
#if 0
FD_ZERO(&wrfds);
FD_SET(ctx->master_fd, &wrfds);
res = select(ctx->master_fd + 1, NULL, &wrfds, NULL, NULL);
if (res <= 0) {
return;
}
#endif
/* just write it out */
if (dev->mode == SERPT_MODE_HOSTSER) {
do {
res = write(dev->master_fd, &data, 1);
} while (res == 0 || (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)));
} else
res = write(dev->master_fd, &data, 1);
}
void
plat_serpt_set_params(void *priv)
{
serial_passthrough_t *dev = (serial_passthrough_t *) priv;
if (dev->mode == SERPT_MODE_HOSTSER) {
struct termios term_attr;
tcgetattr(dev->master_fd, &term_attr);
#define BAUDRATE_RANGE(baud_rate, min, max, val) \
if (baud_rate >= min && baud_rate < max) { \
cfsetispeed(&term_attr, val); \
cfsetospeed(&term_attr, val); \
}
BAUDRATE_RANGE(dev->baudrate, 50, 75, B50);
BAUDRATE_RANGE(dev->baudrate, 75, 110, B75);
BAUDRATE_RANGE(dev->baudrate, 110, 134, B110);
BAUDRATE_RANGE(dev->baudrate, 134, 150, B134);
BAUDRATE_RANGE(dev->baudrate, 150, 200, B150);
BAUDRATE_RANGE(dev->baudrate, 200, 300, B200);
BAUDRATE_RANGE(dev->baudrate, 300, 600, B300);
BAUDRATE_RANGE(dev->baudrate, 600, 1200, B600);
BAUDRATE_RANGE(dev->baudrate, 1200, 1800, B1200);
BAUDRATE_RANGE(dev->baudrate, 1800, 2400, B1800);
BAUDRATE_RANGE(dev->baudrate, 2400, 4800, B2400);
BAUDRATE_RANGE(dev->baudrate, 4800, 9600, B4800);
BAUDRATE_RANGE(dev->baudrate, 9600, 19200, B9600);
BAUDRATE_RANGE(dev->baudrate, 19200, 38400, B19200);
BAUDRATE_RANGE(dev->baudrate, 38400, 57600, B38400);
BAUDRATE_RANGE(dev->baudrate, 57600, 115200, B57600);
BAUDRATE_RANGE(dev->baudrate, 115200, 0xFFFFFFFF, B115200);
term_attr.c_cflag &= ~CSIZE;
switch (dev->data_bits) {
case 8:
default:
term_attr.c_cflag |= CS8;
break;
case 7:
term_attr.c_cflag |= CS7;
break;
case 6:
term_attr.c_cflag |= CS6;
break;
case 5:
term_attr.c_cflag |= CS5;
break;
}
term_attr.c_cflag &= ~CSTOPB;
if (dev->serial->lcr & 0x04)
term_attr.c_cflag |= CSTOPB;
#if !defined(__linux__)
term_attr.c_cflag &= ~(PARENB | PARODD);
#else
term_attr.c_cflag &= ~(PARENB | PARODD | CMSPAR);
#endif
if (dev->serial->lcr & 0x08) {
term_attr.c_cflag |= PARENB;
if (!(dev->serial->lcr & 0x10))
term_attr.c_cflag |= PARODD;
#if defined(__linux__)
if ((dev->serial->lcr & 0x20))
term_attr.c_cflag |= CMSPAR;
#endif
}
tcsetattr(dev->master_fd, TCSANOW, &term_attr);
#undef BAUDRATE_RANGE
}
}
void
plat_serpt_write(void *priv, uint8_t data)
{
serial_passthrough_t *dev = (serial_passthrough_t *) priv;
switch (dev->mode) {
case SERPT_MODE_VCON:
case SERPT_MODE_HOSTSER:
plat_serpt_write_vcon(dev, data);
break;
default:
break;
}
}
static int
open_pseudo_terminal(serial_passthrough_t *dev)
{
int master_fd = open("/dev/ptmx", O_RDWR | O_NONBLOCK);
char *ptname;
struct termios term_attr_raw;
if (!master_fd) {
return 0;
}
/* get name of slave device */
if (!(ptname = ptsname(master_fd))) {
pclog(LOG_PREFIX "could not get name of slave pseudo terminal");
close(master_fd);
return 0;
}
memset(dev->slave_pt, 0, sizeof(dev->slave_pt));
strncpy(dev->slave_pt, ptname, sizeof(dev->slave_pt) - 1);
fprintf(stderr, LOG_PREFIX "Slave side is %s\n", dev->slave_pt);
if (grantpt(master_fd)) {
pclog(LOG_PREFIX "error in grantpt()\n");
close(master_fd);
return 0;
}
if (unlockpt(master_fd)) {
pclog(LOG_PREFIX "error in unlockpt()\n");
close(master_fd);
return 0;
}
tcgetattr(master_fd, &term_attr_raw);
cfmakeraw(&term_attr_raw);
tcsetattr(master_fd, TCSANOW, &term_attr_raw);
dev->master_fd = master_fd;
return master_fd;
}
static int
open_host_serial_port(serial_passthrough_t *dev)
{
struct termios *term_attr = NULL;
struct termios term_attr_raw = {};
int fd = open(dev->host_serial_path, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1) {
return 0;
}
if (!isatty(fd)) {
return 0;
}
term_attr = calloc(1, sizeof(struct termios));
if (!term_attr) {
close(fd);
return 0;
}
if (tcgetattr(fd, term_attr) == -1) {
free(term_attr);
close(fd);
return 0;
}
term_attr_raw = *term_attr;
/* "Raw" mode. */
cfmakeraw(&term_attr_raw);
term_attr_raw.c_cflag &= CSIZE;
switch (dev->data_bits) {
case 8:
default:
term_attr_raw.c_cflag |= CS8;
break;
case 7:
term_attr_raw.c_cflag |= CS7;
break;
case 6:
term_attr_raw.c_cflag |= CS6;
break;
case 5:
term_attr_raw.c_cflag |= CS5;
break;
}
tcsetattr(fd, TCSANOW, &term_attr_raw);
dev->backend_priv = term_attr;
dev->master_fd = fd;
pclog(LOG_PREFIX "Opened host TTY/serial port %s\n", dev->host_serial_path);
return 1;
}
int
plat_serpt_open_device(void *priv)
{
serial_passthrough_t *dev = (serial_passthrough_t *) priv;
switch (dev->mode) {
case SERPT_MODE_VCON:
if (!open_pseudo_terminal(dev)) {
return 1;
}
break;
case SERPT_MODE_HOSTSER:
if (!open_host_serial_port(dev)) {
return 1;
}
break;
default:
break;
}
return 0;
}
``` | /content/code_sandbox/src/unix/unix_serial_passthrough.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,406 |
```objective-c
//
// macOSXGlue.h
// TestSDL
//
// Created by Jerome Vernet on 18/11/2021.
//
#ifndef macOSXGlue_h
#define macOSXGlue_h
#include <CoreFoundation/CFBase.h>
CF_IMPLICIT_BRIDGING_ENABLED
CF_EXTERN_C_BEGIN
void getDefaultROMPath(char *);
int toto(void);
CF_EXTERN_C_END
CF_IMPLICIT_BRIDGING_DISABLED
#endif /* macOSXGlue_h */
``` | /content/code_sandbox/src/unix/macOSXGlue.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 101 |
```desktop
[Desktop Entry]
Name=86Box
GenericName=Classic PC emulator
Comment=An emulator for classic IBM PC clones
Exec=86Box
Icon=net.86box.86Box
Terminal=false
Type=Application
Categories=System;Emulator;
``` | /content/code_sandbox/src/unix/assets/net.86box.86Box.desktop | desktop | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 56 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the Magitronic B215 XT-FDC Controller.
*
* Authors: Tiseno100
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/io.h>
#include <86box/device.h>
#include <86box/mem.h>
#include <86box/rom.h>
#include <86box/fdd.h>
#include <86box/fdc.h>
#include <86box/fdc_ext.h>
#include <86box/plat_unused.h>
#define ROM_B215 "roms/floppy/magitronic/Magitronic B215 - BIOS ROM.bin"
#define ROM_ADDR (uint32_t)(device_get_config_hex20("bios_addr") & 0x000fffff)
#define DRIVE_SELECT (int) (real_drive(dev->fdc_controller, i))
typedef struct b215_t {
fdc_t *fdc_controller;
rom_t rom;
} b215_t;
static uint8_t
b215_read(UNUSED(uint16_t addr), void *priv)
{
b215_t *dev = (b215_t *) priv;
/*
Register 3F0h
Bit (3-2) for Drive B:
Bit (1-0) for Drive A:
0: 360KB
1: 1.2MB
2: 720KB
3: 1.44MB
4:
*/
int drive_spec[2];
for (uint8_t i = 0; i <= 1; i++) {
if (fdd_is_525(DRIVE_SELECT)) {
if (!fdd_is_dd(DRIVE_SELECT))
drive_spec[i] = 1;
else if (fdd_doublestep_40(DRIVE_SELECT))
drive_spec[i] = 2;
else
drive_spec[i] = 0;
} else {
if (fdd_is_dd(DRIVE_SELECT) && !fdd_is_double_sided(DRIVE_SELECT))
drive_spec[i] = 0;
else if (fdd_is_dd(DRIVE_SELECT) && fdd_is_double_sided(DRIVE_SELECT))
drive_spec[i] = 2;
else
drive_spec[i] = 3;
}
}
return ((drive_spec[1] << 2) | drive_spec[0]) & 0x0f;
}
static void
b215_close(void *priv)
{
b215_t *dev = (b215_t *) priv;
free(dev);
}
static void *
b215_init(UNUSED(const device_t *info))
{
b215_t *dev = (b215_t *) malloc(sizeof(b215_t));
memset(dev, 0, sizeof(b215_t));
rom_init(&dev->rom, ROM_B215, ROM_ADDR, 0x2000, 0x1fff, 0, MEM_MAPPING_EXTERNAL);
dev->fdc_controller = device_add(&fdc_um8398_device);
io_sethandler(FDC_PRIMARY_ADDR, 1, b215_read, NULL, NULL, NULL, NULL, NULL, dev);
return dev;
}
static int
b215_available(void)
{
return rom_present(ROM_B215);
}
static const device_config_t b215_config[] = {
// clang-format off
{
.name = "bios_addr",
.description = "BIOS Address:",
.type = CONFIG_HEX20,
.default_string = "",
.default_int = 0xca000,
.file_filter = "",
.spinner = { 0 },
.selection = {
{ .description = "CA00H", .value = 0xca000 },
{ .description = "CC00H", .value = 0xcc000 },
{ .description = "" }
}
},
{ .name = "", .description = "", .type = CONFIG_END }
// clang-format on
};
const device_t fdc_b215_device = {
.name = "Magitronic B215",
.internal_name = "b215",
.flags = DEVICE_ISA,
.local = 0,
.init = b215_init,
.close = b215_close,
.reset = NULL,
{ .available = b215_available },
.speed_changed = NULL,
.force_redraw = NULL,
.config = b215_config
};
``` | /content/code_sandbox/src/floppy/fdc_magitronic.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,058 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the HxC MFM image format.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <math.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/plat.h>
#include <86box/fdd.h>
#include <86box/fdd_86f.h>
#include <86box/fdd_img.h>
#include <86box/fdd_mfm.h>
#include <86box/fdc.h>
#pragma pack(push, 1)
typedef struct mfm_header_t {
uint8_t hdr_name[7];
uint16_t tracks_no;
uint8_t sides_no;
uint16_t rpm;
uint16_t bit_rate;
uint8_t if_type;
uint32_t track_list_offset;
} mfm_header_t;
typedef struct mfm_track_t {
uint16_t track_no;
uint8_t side_no;
uint32_t track_size;
uint32_t track_offset;
} mfm_track_t;
typedef struct mfm_adv_track_t {
uint16_t track_no;
uint8_t side_no;
uint16_t rpm;
uint16_t bit_rate;
uint32_t track_size;
uint32_t track_offset;
} mfm_adv_track_t;
#pragma pack(pop)
typedef struct mfm_t {
FILE *fp;
mfm_header_t hdr;
mfm_track_t *tracks;
mfm_adv_track_t *adv_tracks;
uint16_t disk_flags;
uint16_t pad;
uint16_t side_flags[2];
int br_rounded;
int rpm_rounded;
int total_tracks;
int cur_track;
uint8_t track_data[2][256 * 1024];
} mfm_t;
static mfm_t *mfm[FDD_NUM];
static fdc_t *mfm_fdc;
#ifdef ENABLE_MFM_LOG
int mfm_do_log = ENABLE_MFM_LOG;
static void
mfm_log(const char *fmt, ...)
{
va_list ap;
if (mfm_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define mfm_log(fmt, ...)
#endif
static int
get_track_index(int drive, int side, int track)
{
const mfm_t *dev = mfm[drive];
int ret = -1;
for (int i = 0; i < dev->total_tracks; i++) {
if ((dev->tracks[i].track_no == track) && (dev->tracks[i].side_no == side)) {
ret = i;
break;
}
}
return ret;
}
static int
get_adv_track_index(int drive, int side, int track)
{
const mfm_t *dev = mfm[drive];
int ret = -1;
for (int i = 0; i < dev->total_tracks; i++) {
if ((dev->adv_tracks[i].track_no == track) && (dev->adv_tracks[i].side_no == side)) {
ret = i;
break;
}
}
return ret;
}
static void
get_adv_track_bitrate(int drive, int side, int track, int *br, int *rpm)
{
const mfm_t *dev = mfm[drive];
int track_index;
double dbr;
track_index = get_adv_track_index(drive, side, track);
if (track_index == -1) {
*br = 250;
*rpm = 300;
} else {
dbr = round(((double) dev->adv_tracks[track_index].bit_rate) / 50.0) * 50.0;
*br = ((int) dbr);
dbr = round(((double) dev->adv_tracks[track_index].rpm) / 60.0) * 60.0;
*rpm = ((int) dbr);
}
}
static void
set_disk_flags(int drive)
{
int br = 250;
int rpm = 300;
mfm_t *dev = mfm[drive];
uint16_t temp_disk_flags = 0x1080; /* We ALWAYS claim to have extra bit cells, even if the actual amount is 0;
Bit 12 = 1, bits 6, 5 = 0 - extra bit cells field specifies the entire
amount of bit cells per track. */
/* If this is the modified MFM format, get bit rate (and RPM) from track 0 instead. */
if (dev->hdr.if_type & 0x80)
get_adv_track_bitrate(drive, 0, 0, &br, &rpm);
else {
br = dev->br_rounded;
rpm = dev->rpm_rounded;
}
switch (br) {
default:
case 250:
case 300:
temp_disk_flags |= 0;
break;
case 500:
temp_disk_flags |= 2;
break;
case 1000:
temp_disk_flags |= 4;
break;
}
if (dev->hdr.sides_no == 2)
temp_disk_flags |= 8;
dev->disk_flags = temp_disk_flags;
}
static uint16_t
disk_flags(int drive)
{
const mfm_t *dev = mfm[drive];
return dev->disk_flags;
}
static void
set_side_flags(int drive, int side)
{
mfm_t *dev = mfm[drive];
uint16_t temp_side_flags = 0;
int br = 250;
int rpm = 300;
if (dev->hdr.if_type & 0x80)
get_adv_track_bitrate(drive, side, dev->cur_track, &br, &rpm);
else {
br = dev->br_rounded;
rpm = dev->rpm_rounded;
}
/* 300 kbps @ 360 rpm = 250 kbps @ 200 rpm */
if ((br == 300) && (rpm == 360)) {
br = 250;
rpm = 300;
}
switch (br) {
case 500:
temp_side_flags = 0;
break;
case 300:
temp_side_flags = 1;
break;
case 250:
default:
temp_side_flags = 2;
break;
case 1000:
temp_side_flags = 3;
break;
}
if (rpm == 360)
temp_side_flags |= 0x20;
/*
* Set the encoding value to match that provided by the FDC.
* Then if it's wrong, it will sector not found anyway.
*/
temp_side_flags |= 0x08;
dev->side_flags[side] = temp_side_flags;
}
static uint16_t
side_flags(int drive)
{
const mfm_t *dev = mfm[drive];
int side;
side = fdd_get_head(drive);
return dev->side_flags[side];
}
static uint32_t
get_raw_size(int drive, int side)
{
const mfm_t *dev = mfm[drive];
int track_index;
int is_300_rpm;
int br = 250;
int rpm = 300;
if (dev->hdr.if_type & 0x80) {
track_index = get_adv_track_index(drive, side, dev->cur_track);
get_adv_track_bitrate(drive, 0, 0, &br, &rpm);
} else {
track_index = get_track_index(drive, side, dev->cur_track);
br = dev->br_rounded;
rpm = dev->rpm_rounded;
}
is_300_rpm = (rpm == 300);
if (track_index == -1) {
mfm_log("MFM: Unable to find track (%i, %i)\n", dev->cur_track, side);
switch (br) {
default:
case 250:
return is_300_rpm ? 100000 : 83333;
case 300:
return is_300_rpm ? 120000 : 100000;
case 500:
return is_300_rpm ? 200000 : 166666;
case 1000:
return is_300_rpm ? 400000 : 333333;
}
}
/* Bit 7 on - my extension of the HxC MFM format to output exact bitcell counts
for each track instead of rounded byte counts. */
if (dev->hdr.if_type & 0x80)
return dev->adv_tracks[track_index].track_size;
else
return dev->tracks[track_index].track_size * 8;
}
static int32_t
extra_bit_cells(int drive, int side)
{
return (int32_t) get_raw_size(drive, side);
}
static uint16_t *
encoded_data(int drive, int side)
{
mfm_t *dev = mfm[drive];
return ((uint16_t *) dev->track_data[side]);
}
void
mfm_read_side(int drive, int side)
{
mfm_t *dev = mfm[drive];
int track_index;
int track_size;
int track_bytes;
int ret;
if (dev->hdr.if_type & 0x80)
track_index = get_adv_track_index(drive, side, dev->cur_track);
else
track_index = get_track_index(drive, side, dev->cur_track);
track_size = get_raw_size(drive, side);
track_bytes = track_size >> 3;
if (track_size & 0x07)
track_bytes++;
if (track_index == -1)
memset(dev->track_data[side], 0x00, track_bytes);
else {
if (dev->hdr.if_type & 0x80)
ret = fseek(dev->fp, dev->adv_tracks[track_index].track_offset, SEEK_SET);
else
ret = fseek(dev->fp, dev->tracks[track_index].track_offset, SEEK_SET);
if (ret == -1)
fatal("mfm_read_side(): Error seeking to the beginning of the file\n");
if (fread(dev->track_data[side], 1, track_bytes, dev->fp) != track_bytes)
fatal("mfm_read_side(): Error reading track bytes\n");
}
mfm_log("drive = %i, side = %i, dev->cur_track = %i, track_index = %i, track_size = %i\n",
drive, side, dev->cur_track, track_index, track_size);
}
void
mfm_seek(int drive, int track)
{
mfm_t *dev = mfm[drive];
mfm_log("mfm_seek(%i, %i)\n", drive, track);
if (fdd_doublestep_40(drive)) {
if (dev->hdr.tracks_no <= 43)
track /= 2;
}
dev->cur_track = track;
d86f_set_cur_track(drive, track);
if (dev->fp == NULL)
return;
if (track < 0)
track = 0;
mfm_read_side(drive, 0);
mfm_read_side(drive, 1);
set_side_flags(drive, 0);
set_side_flags(drive, 1);
}
void
mfm_load(int drive, char *fn)
{
mfm_t *dev;
double dbr;
int size;
writeprot[drive] = fwriteprot[drive] = 1;
/* Allocate a drive block. */
dev = (mfm_t *) malloc(sizeof(mfm_t));
memset(dev, 0x00, sizeof(mfm_t));
dev->fp = plat_fopen(fn, "rb");
if (dev->fp == NULL) {
free(dev);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
}
d86f_unregister(drive);
/* Read the header. */
size = sizeof(mfm_header_t);
if (fread(&dev->hdr, 1, size, dev->fp) != size)
fatal("mfm_load(): Error reading header\n");
/* Calculate tracks * sides, allocate the tracks array, and read it. */
dev->total_tracks = dev->hdr.tracks_no * dev->hdr.sides_no;
if (dev->hdr.if_type & 0x80) {
dev->adv_tracks = (mfm_adv_track_t *) malloc(dev->total_tracks * sizeof(mfm_adv_track_t));
size = dev->total_tracks * sizeof(mfm_adv_track_t);
if (fread(dev->adv_tracks, 1, size, dev->fp) != size)
fatal("mfm_load(): Error reading advanced tracks\n");
} else {
dev->tracks = (mfm_track_t *) malloc(dev->total_tracks * sizeof(mfm_track_t));
size = dev->total_tracks * sizeof(mfm_track_t);
if (fread(dev->tracks, 1, size, dev->fp) != size)
fatal("mfm_load(): Error reading tracks\n");
}
/* The chances of finding a HxC MFM image of a single-sided thin track
disk are much smaller than the chances of finding a HxC MFM image
incorrectly converted from a SCP image, erroneously indicating 1
side and 80+ tracks instead of 2 sides and <= 43 tracks, so if we
have detected such an image, convert the track numbers. */
if ((dev->hdr.tracks_no > 43) && (dev->hdr.sides_no == 1)) {
dev->hdr.tracks_no >>= 1;
dev->hdr.sides_no <<= 1;
for (int i = 0; i < dev->total_tracks; i++) {
if (dev->hdr.if_type & 0x80) {
dev->adv_tracks[i].side_no <<= 1;
dev->adv_tracks[i].side_no |= (dev->adv_tracks[i].track_no & 1);
dev->adv_tracks[i].track_no >>= 1;
} else {
dev->tracks[i].side_no <<= 1;
dev->tracks[i].side_no |= (dev->tracks[i].track_no & 1);
dev->tracks[i].track_no >>= 1;
}
}
}
if (!(dev->hdr.if_type & 0x80)) {
dbr = round(((double) dev->hdr.bit_rate) / 50.0) * 50.0;
dev->br_rounded = (int) dbr;
mfm_log("Rounded bit rate: %i kbps\n", dev->br_rounded);
if (dev->hdr.rpm != 0)
dbr = round(((double) dev->hdr.rpm) / 60.0) * 60.0;
else
dbr = (dev->br_rounded == 300) ? 360.0 : 300.0;
dev->rpm_rounded = (int) dbr;
mfm_log("Rounded RPM: %i rpm\n", dev->rpm_rounded);
}
/* Set up the drive unit. */
mfm[drive] = dev;
set_disk_flags(drive);
/* Attach this format to the D86F engine. */
d86f_handler[drive].disk_flags = disk_flags;
d86f_handler[drive].side_flags = side_flags;
d86f_handler[drive].writeback = null_writeback;
d86f_handler[drive].set_sector = null_set_sector;
d86f_handler[drive].write_data = null_write_data;
d86f_handler[drive].format_conditions = null_format_conditions;
d86f_handler[drive].extra_bit_cells = extra_bit_cells;
d86f_handler[drive].encoded_data = encoded_data;
d86f_handler[drive].read_revolution = common_read_revolution;
d86f_handler[drive].index_hole_pos = null_index_hole_pos;
d86f_handler[drive].get_raw_size = get_raw_size;
d86f_handler[drive].check_crc = 1;
d86f_set_version(drive, D86FVER);
d86f_common_handlers(drive);
drives[drive].seek = mfm_seek;
mfm_log("Loaded as MFM\n");
}
void
mfm_close(int drive)
{
mfm_t *dev = mfm[drive];
if (dev == NULL)
return;
d86f_unregister(drive);
drives[drive].seek = NULL;
if (dev->tracks)
free(dev->tracks);
if (dev->adv_tracks)
free(dev->adv_tracks);
if (dev->fp)
fclose(dev->fp);
/* Release the memory. */
free(dev);
mfm[drive] = NULL;
}
void
mfm_set_fdc(void *fdc)
{
mfm_fdc = (fdc_t *) fdc;
}
``` | /content/code_sandbox/src/floppy/fdd_mfm.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,895 |
```c
#ifdef __linux__
# define _FILE_OFFSET_BITS 64
# define _LARGEFILE64_SOURCE 1
#endif
#include <SDL.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>
#include <inttypes.h>
#include <dlfcn.h>
#include <wchar.h>
#include <pwd.h>
#include <stdatomic.h>
#ifdef __APPLE__
# include "macOSXGlue.h"
#endif
#include <86box/86box.h>
#include <86box/mem.h>
#include <86box/rom.h>
#include <86box/keyboard.h>
#include <86box/mouse.h>
#include <86box/config.h>
#include <86box/path.h>
#include <86box/plat.h>
#include <86box/plat_dynld.h>
#include <86box/thread.h>
#include <86box/device.h>
#include <86box/gameport.h>
#include <86box/unix_sdl.h>
#include <86box/timer.h>
#include <86box/nvr.h>
#include <86box/version.h>
#include <86box/video.h>
#include <86box/ui.h>
#include <86box/gdbstub.h>
#define __USE_GNU 1 /* shouldn't be done, yet it is */
#include <pthread.h>
static int first_use = 1;
static uint64_t StartingTime;
static uint64_t Frequency;
int rctrl_is_lalt;
int update_icons;
int kbd_req_capture;
int hide_status_bar;
int hide_tool_bar;
int fixed_size_x = 640;
int fixed_size_y = 480;
extern int title_set;
extern wchar_t sdl_win_title[512];
plat_joystick_t plat_joystick_state[MAX_PLAT_JOYSTICKS];
joystick_t joystick_state[MAX_JOYSTICKS];
int joysticks_present;
SDL_mutex *blitmtx;
SDL_threadID eventthread;
static int exit_event = 0;
static int fullscreen_pending = 0;
uint32_t lang_id = 0x0409; // Multilangual UI variables, for now all set to LCID of en-US
uint32_t lang_sys = 0x0409; // Multilangual UI variables, for now all set to LCID of en-US
char icon_set[256] = ""; /* name of the iconset to be used */
static const uint16_t sdl_to_xt[0x200] = {
[SDL_SCANCODE_ESCAPE] = 0x01,
[SDL_SCANCODE_1] = 0x02,
[SDL_SCANCODE_2] = 0x03,
[SDL_SCANCODE_3] = 0x04,
[SDL_SCANCODE_4] = 0x05,
[SDL_SCANCODE_5] = 0x06,
[SDL_SCANCODE_6] = 0x07,
[SDL_SCANCODE_7] = 0x08,
[SDL_SCANCODE_8] = 0x09,
[SDL_SCANCODE_9] = 0x0A,
[SDL_SCANCODE_0] = 0x0B,
[SDL_SCANCODE_MINUS] = 0x0C,
[SDL_SCANCODE_EQUALS] = 0x0D,
[SDL_SCANCODE_BACKSPACE] = 0x0E,
[SDL_SCANCODE_TAB] = 0x0F,
[SDL_SCANCODE_Q] = 0x10,
[SDL_SCANCODE_W] = 0x11,
[SDL_SCANCODE_E] = 0x12,
[SDL_SCANCODE_R] = 0x13,
[SDL_SCANCODE_T] = 0x14,
[SDL_SCANCODE_Y] = 0x15,
[SDL_SCANCODE_U] = 0x16,
[SDL_SCANCODE_I] = 0x17,
[SDL_SCANCODE_O] = 0x18,
[SDL_SCANCODE_P] = 0x19,
[SDL_SCANCODE_LEFTBRACKET] = 0x1A,
[SDL_SCANCODE_RIGHTBRACKET] = 0x1B,
[SDL_SCANCODE_RETURN] = 0x1C,
[SDL_SCANCODE_LCTRL] = 0x1D,
[SDL_SCANCODE_A] = 0x1E,
[SDL_SCANCODE_S] = 0x1F,
[SDL_SCANCODE_D] = 0x20,
[SDL_SCANCODE_F] = 0x21,
[SDL_SCANCODE_G] = 0x22,
[SDL_SCANCODE_H] = 0x23,
[SDL_SCANCODE_J] = 0x24,
[SDL_SCANCODE_K] = 0x25,
[SDL_SCANCODE_L] = 0x26,
[SDL_SCANCODE_SEMICOLON] = 0x27,
[SDL_SCANCODE_APOSTROPHE] = 0x28,
[SDL_SCANCODE_GRAVE] = 0x29,
[SDL_SCANCODE_LSHIFT] = 0x2A,
[SDL_SCANCODE_BACKSLASH] = 0x2B,
[SDL_SCANCODE_Z] = 0x2C,
[SDL_SCANCODE_X] = 0x2D,
[SDL_SCANCODE_C] = 0x2E,
[SDL_SCANCODE_V] = 0x2F,
[SDL_SCANCODE_B] = 0x30,
[SDL_SCANCODE_N] = 0x31,
[SDL_SCANCODE_M] = 0x32,
[SDL_SCANCODE_COMMA] = 0x33,
[SDL_SCANCODE_PERIOD] = 0x34,
[SDL_SCANCODE_SLASH] = 0x35,
[SDL_SCANCODE_RSHIFT] = 0x36,
[SDL_SCANCODE_KP_MULTIPLY] = 0x37,
[SDL_SCANCODE_LALT] = 0x38,
[SDL_SCANCODE_SPACE] = 0x39,
[SDL_SCANCODE_CAPSLOCK] = 0x3A,
[SDL_SCANCODE_F1] = 0x3B,
[SDL_SCANCODE_F2] = 0x3C,
[SDL_SCANCODE_F3] = 0x3D,
[SDL_SCANCODE_F4] = 0x3E,
[SDL_SCANCODE_F5] = 0x3F,
[SDL_SCANCODE_F6] = 0x40,
[SDL_SCANCODE_F7] = 0x41,
[SDL_SCANCODE_F8] = 0x42,
[SDL_SCANCODE_F9] = 0x43,
[SDL_SCANCODE_F10] = 0x44,
[SDL_SCANCODE_NUMLOCKCLEAR] = 0x45,
[SDL_SCANCODE_SCROLLLOCK] = 0x46,
[SDL_SCANCODE_HOME] = 0x147,
[SDL_SCANCODE_UP] = 0x148,
[SDL_SCANCODE_PAGEUP] = 0x149,
[SDL_SCANCODE_KP_MINUS] = 0x4A,
[SDL_SCANCODE_LEFT] = 0x14B,
[SDL_SCANCODE_KP_5] = 0x4C,
[SDL_SCANCODE_RIGHT] = 0x14D,
[SDL_SCANCODE_KP_PLUS] = 0x4E,
[SDL_SCANCODE_END] = 0x14F,
[SDL_SCANCODE_DOWN] = 0x150,
[SDL_SCANCODE_PAGEDOWN] = 0x151,
[SDL_SCANCODE_INSERT] = 0x152,
[SDL_SCANCODE_DELETE] = 0x153,
[SDL_SCANCODE_F11] = 0x57,
[SDL_SCANCODE_F12] = 0x58,
[SDL_SCANCODE_KP_ENTER] = 0x11c,
[SDL_SCANCODE_RCTRL] = 0x11d,
[SDL_SCANCODE_KP_DIVIDE] = 0x135,
[SDL_SCANCODE_RALT] = 0x138,
[SDL_SCANCODE_KP_9] = 0x49,
[SDL_SCANCODE_KP_8] = 0x48,
[SDL_SCANCODE_KP_7] = 0x47,
[SDL_SCANCODE_KP_6] = 0x4D,
[SDL_SCANCODE_KP_4] = 0x4B,
[SDL_SCANCODE_KP_3] = 0x51,
[SDL_SCANCODE_KP_2] = 0x50,
[SDL_SCANCODE_KP_1] = 0x4F,
[SDL_SCANCODE_KP_0] = 0x52,
[SDL_SCANCODE_KP_PERIOD] = 0x53,
[SDL_SCANCODE_LGUI] = 0x15B,
[SDL_SCANCODE_RGUI] = 0x15C,
[SDL_SCANCODE_APPLICATION] = 0x15D,
[SDL_SCANCODE_PRINTSCREEN] = 0x137
};
typedef struct sdl_blit_params {
int x;
int y;
int w;
int h;
} sdl_blit_params;
sdl_blit_params params = { 0, 0, 0, 0 };
int blitreq = 0;
void *
dynld_module(const char *name, dllimp_t *table)
{
dllimp_t *imp;
void *modhandle = dlopen(name, RTLD_LAZY | RTLD_GLOBAL);
if (modhandle) {
for (imp = table; imp->name != NULL; imp++) {
if ((*(void **) imp->func = dlsym(modhandle, imp->name)) == NULL) {
dlclose(modhandle);
return NULL;
}
}
}
return modhandle;
}
void
plat_tempfile(char *bufp, char *prefix, char *suffix)
{
struct tm *calendertime;
struct timeval t;
time_t curtime;
if (prefix != NULL)
sprintf(bufp, "%s-", prefix);
else
strcpy(bufp, "");
gettimeofday(&t, NULL);
curtime = time(NULL);
calendertime = localtime(&curtime);
sprintf(&bufp[strlen(bufp)], "%d%02d%02d-%02d%02d%02d-%03ld%s", calendertime->tm_year, calendertime->tm_mon, calendertime->tm_mday, calendertime->tm_hour, calendertime->tm_min, calendertime->tm_sec, t.tv_usec / 1000, suffix);
}
int
plat_getcwd(char *bufp, int max)
{
return getcwd(bufp, max) != 0;
}
int
plat_chdir(char *str)
{
return chdir(str);
}
void
dynld_close(void *handle)
{
dlclose(handle);
}
wchar_t *
plat_get_string(int i)
{
switch (i) {
case STRING_MOUSE_CAPTURE:
return L"Click to capture mouse";
case STRING_MOUSE_RELEASE:
return L"Press CTRL-END to release mouse";
case STRING_MOUSE_RELEASE_MMB:
return L"Press CTRL-END or middle button to release mouse";
case STRING_INVALID_CONFIG:
return L"Invalid configuration";
case STRING_NO_ST506_ESDI_CDROM:
return L"MFM/RLL or ESDI CD-ROM drives never existed";
case STRING_PCAP_ERROR_NO_DEVICES:
return L"No PCap devices found";
case STRING_PCAP_ERROR_INVALID_DEVICE:
return L"Invalid PCap device";
case STRING_GHOSTSCRIPT_ERROR_DESC:
return L"libgs is required for automatic conversion of PostScript files to PDF.\n\nAny documents sent to the generic PostScript printer will be saved as PostScript (.ps) files.";
case STRING_PCAP_ERROR_DESC:
return L"Make sure libpcap is installed and that you are on a libpcap-compatible network connection.";
case STRING_GHOSTSCRIPT_ERROR_TITLE:
return L"Unable to initialize Ghostscript";
case STRING_GHOSTPCL_ERROR_TITLE:
return L"Unable to initialize GhostPCL";
case STRING_GHOSTPCL_ERROR_DESC:
return L"libgpcl6 is required for automatic conversion of PCL files to PDF.\n\nAny documents sent to the generic PCL printer will be saved as Printer Command Language (.pcl) files.";
case STRING_HW_NOT_AVAILABLE_MACHINE:
return L"Machine \"%hs\" is not available due to missing ROMs in the roms/machines directory. Switching to an available machine.";
case STRING_HW_NOT_AVAILABLE_VIDEO:
return L"Video card \"%hs\" is not available due to missing ROMs in the roms/video directory. Switching to an available video card.";
case STRING_HW_NOT_AVAILABLE_TITLE:
return L"Hardware not available";
case STRING_MONITOR_SLEEP:
return L"Monitor in sleep mode";
}
return L"";
}
FILE *
plat_fopen(const char *path, const char *mode)
{
return fopen(path, mode);
}
FILE *
plat_fopen64(const char *path, const char *mode)
{
return fopen(path, mode);
}
int
path_abs(char *path)
{
return path[0] == '/';
}
void
path_normalize(char *path)
{
/* No-op. */
}
void
path_slash(char *path)
{
if (path[strlen(path) - 1] != '/') {
strcat(path, "/");
}
path_normalize(path);
}
const char *
path_get_slash(char *path)
{
char *ret = "";
if (path[strlen(path) - 1] != '/')
ret = "/";
return ret;
}
void
plat_put_backslash(char *s)
{
int c = strlen(s) - 1;
if (s[c] != '/')
s[c] = '/';
}
/* Return the last element of a pathname. */
char *
plat_get_basename(const char *path)
{
int c = (int) strlen(path);
while (c > 0) {
if (path[c] == '/')
return ((char *) &path[c + 1]);
c--;
}
return ((char *) path);
}
char *
path_get_filename(char *s)
{
int c = strlen(s) - 1;
while (c > 0) {
if (s[c] == '/' || s[c] == '\\')
return (&s[c + 1]);
c--;
}
return s;
}
char *
path_get_extension(char *s)
{
int c = strlen(s) - 1;
if (c <= 0)
return s;
while (c && s[c] != '.')
c--;
if (!c)
return (&s[strlen(s)]);
return (&s[c + 1]);
}
void
path_append_filename(char *dest, const char *s1, const char *s2)
{
strcpy(dest, s1);
path_slash(dest);
strcat(dest, s2);
}
int
plat_dir_check(char *path)
{
struct stat dummy;
if (stat(path, &dummy) < 0) {
return 0;
}
return S_ISDIR(dummy.st_mode);
}
int
plat_dir_create(char *path)
{
return mkdir(path, S_IRWXU);
}
void *
plat_mmap(size_t size, uint8_t executable)
{
#if defined __APPLE__ && defined MAP_JIT
void *ret = mmap(0, size, PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0), MAP_ANON | MAP_PRIVATE | (executable ? MAP_JIT : 0), -1, 0);
#else
void *ret = mmap(0, size, PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0), MAP_ANON | MAP_PRIVATE, -1, 0);
#endif
return (ret < 0) ? NULL : ret;
}
void
plat_munmap(void *ptr, size_t size)
{
munmap(ptr, size);
}
uint64_t
plat_timer_read(void)
{
return SDL_GetPerformanceCounter();
}
static uint64_t
plat_get_ticks_common(void)
{
uint64_t EndingTime;
uint64_t ElapsedMicroseconds;
if (first_use) {
Frequency = SDL_GetPerformanceFrequency();
StartingTime = SDL_GetPerformanceCounter();
first_use = 0;
}
EndingTime = SDL_GetPerformanceCounter();
ElapsedMicroseconds = ((EndingTime - StartingTime) * 1000000) / Frequency;
return ElapsedMicroseconds;
}
uint32_t
plat_get_ticks(void)
{
return (uint32_t) (plat_get_ticks_common() / 1000);
}
void
plat_remove(char *path)
{
remove(path);
}
void
ui_sb_update_icon_state(int tag, int state)
{
/* No-op. */
}
void
ui_sb_update_icon(int tag, int active)
{
/* No-op. */
}
void
plat_delay_ms(uint32_t count)
{
SDL_Delay(count);
}
void
ui_sb_update_tip(int arg)
{
/* No-op. */
}
void
ui_sb_update_panes(void)
{
/* No-op. */
}
void
ui_sb_update_text(void)
{
/* No-op. */
}
void
path_get_dirname(char *dest, const char *path)
{
int c = (int) strlen(path);
char *ptr = (char *) path;
while (c > 0) {
if (path[c] == '/' || path[c] == '\\') {
ptr = (char *) &path[c];
break;
}
c--;
}
/* Copy to destination. */
while (path < ptr)
*dest++ = *path++;
*dest = '\0';
}
volatile int cpu_thread_run = 1;
void
ui_sb_set_text_w(wchar_t *wstr)
{
/* No-op. */
}
int
stricmp(const char *s1, const char *s2)
{
return strcasecmp(s1, s2);
}
int
strnicmp(const char *s1, const char *s2, size_t n)
{
return strncasecmp(s1, s2, n);
}
void
main_thread(void *param)
{
uint32_t old_time;
uint32_t new_time;
int drawits;
int frames;
SDL_SetThreadPriority(SDL_THREAD_PRIORITY_HIGH);
framecountx = 0;
// title_update = 1;
old_time = SDL_GetTicks();
drawits = frames = 0;
while (!is_quit && cpu_thread_run) {
/* See if it is time to run a frame of code. */
new_time = SDL_GetTicks();
#ifdef USE_GDBSTUB
if (gdbstub_next_asap && (drawits <= 0))
drawits = 10;
else
#endif
drawits += (new_time - old_time);
old_time = new_time;
if (drawits > 0 && !dopause) {
/* Yes, so do one frame now. */
drawits -= 10;
if (drawits > 50)
drawits = 0;
/* Run a block of code. */
pc_run();
/* Every 200 frames we save the machine status. */
if (++frames >= 200 && nvr_dosave) {
nvr_save();
nvr_dosave = 0;
frames = 0;
}
} else /* Just so we dont overload the host OS. */
SDL_Delay(1);
/* If needed, handle a screen resize. */
if (atomic_load(&doresize_monitors[0]) && !video_fullscreen && !is_quit) {
if (vid_resize & 2)
plat_resize(fixed_size_x, fixed_size_y, 0);
else
plat_resize(scrnsz_x, scrnsz_y, 0);
atomic_store(&doresize_monitors[0], 1);
}
}
is_quit = 1;
}
thread_t *thMain = NULL;
void
do_start(void)
{
/* We have not stopped yet. */
is_quit = 0;
/* Initialize the high-precision timer. */
SDL_InitSubSystem(SDL_INIT_TIMER);
timer_freq = SDL_GetPerformanceFrequency();
/* Start the emulator, really. */
thMain = thread_create(main_thread, NULL);
}
void
do_stop(void)
{
if (SDL_ThreadID() != eventthread) {
exit_event = 1;
return;
}
if (blitreq) {
blitreq = 0;
video_blit_complete();
}
while (SDL_TryLockMutex(blitmtx) == SDL_MUTEX_TIMEDOUT) {
if (blitreq) {
blitreq = 0;
video_blit_complete();
}
}
startblit();
is_quit = 1;
sdl_close();
pc_close(thMain);
thMain = NULL;
}
int
ui_msgbox(int flags, void *message)
{
return ui_msgbox_header(flags, NULL, message);
}
int
ui_msgbox_header(int flags, void *header, void *message)
{
SDL_MessageBoxData msgdata;
SDL_MessageBoxButtonData msgbtn;
if (!header) {
if (flags & MBX_ANSI)
header = (void *) "86Box";
else
header = (void *) L"86Box";
}
msgbtn.buttonid = 1;
msgbtn.text = "OK";
msgbtn.flags = 0;
memset(&msgdata, 0, sizeof(SDL_MessageBoxData));
msgdata.numbuttons = 1;
msgdata.buttons = &msgbtn;
int msgflags = 0;
if (msgflags & MBX_FATAL)
msgflags |= SDL_MESSAGEBOX_ERROR;
else if (msgflags & MBX_ERROR || msgflags & MBX_WARNING)
msgflags |= SDL_MESSAGEBOX_WARNING;
else
msgflags |= SDL_MESSAGEBOX_INFORMATION;
msgdata.flags = msgflags;
if (flags & MBX_ANSI) {
int button = 0;
msgdata.title = header;
msgdata.message = message;
SDL_ShowMessageBox(&msgdata, &button);
return button;
} else {
int button = 0;
char *res = SDL_iconv_string("UTF-8", sizeof(wchar_t) == 2 ? "UTF-16LE" : "UTF-32LE", (char *) message, wcslen(message) * sizeof(wchar_t) + sizeof(wchar_t));
char *res2 = SDL_iconv_string("UTF-8", sizeof(wchar_t) == 2 ? "UTF-16LE" : "UTF-32LE", (char *) header, wcslen(header) * sizeof(wchar_t) + sizeof(wchar_t));
msgdata.message = res;
msgdata.title = res2;
SDL_ShowMessageBox(&msgdata, &button);
free(res);
free(res2);
return button;
}
return 0;
}
void
plat_get_exe_name(char *s, int size)
{
char *basepath = SDL_GetBasePath();
snprintf(s, size, "%s%s", basepath, basepath[strlen(basepath) - 1] == '/' ? "86box" : "/86box");
}
void
plat_power_off(void)
{
confirm_exit_cmdl = 0;
nvr_save();
config_save();
/* Deduct a sufficiently large number of cycles that no instructions will
run before the main thread is terminated */
cycles -= 99999999;
cpu_thread_run = 0;
}
void
ui_sb_bugui(char *str)
{
/* No-op. */
}
extern void sdl_blit(int x, int y, int w, int h);
typedef struct mouseinputdata {
int deltax;
int deltay;
int deltaz;
int mousebuttons;
} mouseinputdata;
SDL_mutex *mousemutex;
int real_sdl_w;
int real_sdl_h;
void
ui_sb_set_ready(int ready)
{
/* No-op. */
}
char *xargv[512];
// From musl.
char *
local_strsep(char **str, const char *sep)
{
char *s = *str;
char *end;
if (!s)
return NULL;
end = s + strcspn(s, sep);
if (*end)
*end++ = 0;
else
end = 0;
*str = end;
return s;
}
void
plat_pause(int p)
{
static wchar_t oldtitle[512];
wchar_t title[512];
if ((!!p) == dopause)
return;
if ((p == 0) && (time_sync & TIME_SYNC_ENABLED))
nvr_time_sync();
do_pause(p);
if (p) {
wcsncpy(oldtitle, ui_window_title(NULL), sizeof_w(oldtitle) - 1);
wcscpy(title, oldtitle);
wcscat(title, L" - PAUSED");
ui_window_title(title);
} else {
ui_window_title(oldtitle);
}
}
void
plat_init_rom_paths(void)
{
#ifndef __APPLE__
if (getenv("XDG_DATA_HOME")) {
char xdg_rom_path[1024] = { 0 };
strncpy(xdg_rom_path, getenv("XDG_DATA_HOME"), 1024);
path_slash(xdg_rom_path);
strncat(xdg_rom_path, "86Box/", 1024);
if (!plat_dir_check(xdg_rom_path))
plat_dir_create(xdg_rom_path);
strcat(xdg_rom_path, "roms/");
if (!plat_dir_check(xdg_rom_path))
plat_dir_create(xdg_rom_path);
rom_add_path(xdg_rom_path);
} else {
char home_rom_path[1024] = { 0 };
snprintf(home_rom_path, 1024, "%s/.local/share/86Box/", getenv("HOME") ? getenv("HOME") : getpwuid(getuid())->pw_dir);
if (!plat_dir_check(home_rom_path))
plat_dir_create(home_rom_path);
strcat(home_rom_path, "roms/");
if (!plat_dir_check(home_rom_path))
plat_dir_create(home_rom_path);
rom_add_path(home_rom_path);
}
if (getenv("XDG_DATA_DIRS")) {
char *xdg_rom_paths = strdup(getenv("XDG_DATA_DIRS"));
char *xdg_rom_paths_orig = xdg_rom_paths;
char *cur_xdg_rom_path = NULL;
if (xdg_rom_paths) {
while (xdg_rom_paths[strlen(xdg_rom_paths) - 1] == ':') {
xdg_rom_paths[strlen(xdg_rom_paths) - 1] = '\0';
}
while ((cur_xdg_rom_path = local_strsep(&xdg_rom_paths, ":")) != NULL) {
char real_xdg_rom_path[1024] = { '\0' };
strcat(real_xdg_rom_path, cur_xdg_rom_path);
path_slash(real_xdg_rom_path);
strcat(real_xdg_rom_path, "86Box/roms/");
rom_add_path(real_xdg_rom_path);
}
}
free(xdg_rom_paths_orig);
} else {
rom_add_path("/usr/local/share/86Box/roms/");
rom_add_path("/usr/share/86Box/roms/");
}
#else
char default_rom_path[1024] = { '\0' };
getDefaultROMPath(default_rom_path);
rom_add_path(default_rom_path);
#endif
}
void
plat_get_global_config_dir(char *outbuf, const uint8_t len)
{
char *prefPath = SDL_GetPrefPath(NULL, "86Box");
strncpy(outbuf, prefPath, len);
path_slash(outbuf);
SDL_free(prefPath);
}
void
plat_get_global_data_dir(char *outbuf, const uint8_t len)
{
char *prefPath = SDL_GetPrefPath(NULL, "86Box");
strncpy(outbuf, prefPath, len);
path_slash(outbuf);
SDL_free(prefPath);
}
void
plat_get_temp_dir(char *outbuf, uint8_t len)
{
const char *tmpdir = getenv("TMPDIR");
if (tmpdir == NULL) {
tmpdir = "/tmp";
}
strncpy(outbuf, tmpdir, len);
path_slash(outbuf);
}
bool
process_media_commands_3(uint8_t *id, char *fn, uint8_t *wp, int cmdargc)
{
bool err = false;
*id = atoi(xargv[1]);
if (xargv[2][0] == '\'' || xargv[2][0] == '"') {
for (int curarg = 2; curarg < cmdargc; curarg++) {
if (strlen(fn) + strlen(xargv[curarg]) >= PATH_MAX) {
err = true;
fprintf(stderr, "Path name too long.\n");
}
strcat(fn, xargv[curarg] + (xargv[curarg][0] == '\'' || xargv[curarg][0] == '"'));
if (fn[strlen(fn) - 1] == '\''
|| fn[strlen(fn) - 1] == '"') {
if (curarg + 1 < cmdargc) {
*wp = atoi(xargv[curarg + 1]);
}
break;
}
strcat(fn, " ");
}
} else {
if (strlen(xargv[2]) < PATH_MAX) {
strcpy(fn, xargv[2]);
*wp = atoi(xargv[3]);
} else {
fprintf(stderr, "Path name too long.\n");
err = true;
}
}
if (fn[strlen(fn) - 1] == '\''
|| fn[strlen(fn) - 1] == '"')
fn[strlen(fn) - 1] = '\0';
return err;
}
char *(*f_readline)(const char *) = NULL;
int (*f_add_history)(const char *) = NULL;
void (*f_rl_callback_handler_remove)(void) = NULL;
#ifdef __APPLE__
# define LIBEDIT_LIBRARY "libedit.dylib"
#else
# define LIBEDIT_LIBRARY "libedit.so"
#endif
uint32_t
timer_onesec(uint32_t interval, void *param)
{
pc_onesec();
return interval;
}
void
monitor_thread(void *param)
{
#ifndef USE_CLI
if (isatty(fileno(stdin)) && isatty(fileno(stdout))) {
char *line = NULL;
size_t n;
printf("86Box monitor console.\n");
while (!exit_event) {
if (feof(stdin))
break;
#ifdef ENABLE_READLINE
if (f_readline)
line = f_readline("(86Box) ");
else {
#endif
printf("(86Box) ");
(void) !getline(&line, &n, stdin);
#ifdef ENABLE_READLINE
}
#endif
if (line) {
int cmdargc = 0;
char *linecpy;
line[strcspn(line, "\r\n")] = '\0';
linecpy = strdup(line);
if (!linecpy) {
free(line);
line = NULL;
continue;
}
if (f_add_history)
f_add_history(line);
memset(xargv, 0, sizeof(xargv));
while (1) {
xargv[cmdargc++] = local_strsep(&linecpy, " ");
if (xargv[cmdargc - 1] == NULL || cmdargc >= 512)
break;
}
cmdargc--;
if (strncasecmp(xargv[0], "help", 4) == 0) {
printf(
"fddload <id> <filename> <wp> - Load floppy disk image into drive <id>.\n"
"cdload <id> <filename> - Load CD-ROM image into drive <id>.\n"
"zipload <id> <filename> <wp> - Load ZIP image into ZIP drive <id>.\n"
"cartload <id> <filename> <wp> - Load cartridge image into cartridge drive <id>.\n"
"moload <id> <filename> <wp> - Load MO image into MO drive <id>.\n\n"
"fddeject <id> - eject disk from floppy drive <id>.\n"
"cdeject <id> - eject disc from CD-ROM drive <id>.\n"
"zipeject <id> - eject ZIP image from ZIP drive <id>.\n"
"carteject <id> - eject cartridge from drive <id>.\n"
"moeject <id> - eject image from MO drive <id>.\n\n"
"hardreset - hard reset the emulated system.\n"
"pause - pause the the emulated system.\n"
"fullscreen - toggle fullscreen.\n"
"version - print version and license information.\n"
"exit - exit 86Box.\n");
} else if (strncasecmp(xargv[0], "exit", 4) == 0) {
exit_event = 1;
} else if (strncasecmp(xargv[0], "version", 7) == 0) {
# ifndef EMU_GIT_HASH
# define EMU_GIT_HASH "0000000"
# endif
# if defined(__arm__) || defined(__TARGET_ARCH_ARM)
# define ARCH_STR "arm"
# elif defined(__aarch64__) || defined(_M_ARM64)
# define ARCH_STR "arm64"
# elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
# define ARCH_STR "i386"
# elif defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(_M_X64)
# define ARCH_STR "x86_64"
# else
# define ARCH_STR "unknown arch"
# endif
# ifdef USE_DYNAREC
# ifdef USE_NEW_DYNAREC
# define DYNAREC_STR "new dynarec"
# else
# define DYNAREC_STR "old dynarec"
# endif
# else
# define DYNAREC_STR "no dynarec"
# endif
printf(
"%s v%s [%s] [%s, %s]\n\n"
"An emulator of old computers\n"
"Authors: Miran Gra (OBattler), RichardG867, Jasmine Iwanek, TC1995, coldbrewed, Teemu Korhonen (Manaatti), "
"Joakim L. Gilje, Adrien Moulin (elyosh), Daniel Balsom (gloriouscow), Cacodemon345, Fred N. van Kempen (waltje), "
"Tiseno100, reenigne, and others.\n"
"With previous core contributions from Sarah Walker, leilei, JohnElliott, greatpsycho, and others.\n\n"
EMU_NAME, EMU_VERSION_FULL, EMU_GIT_HASH, ARCH_STR, DYNAREC_STR);
} else if (strncasecmp(xargv[0], "fullscreen", 10) == 0) {
video_fullscreen = video_fullscreen ? 0 : 1;
fullscreen_pending = 1;
} else if (strncasecmp(xargv[0], "pause", 5) == 0) {
plat_pause(dopause ^ 1);
printf("%s", dopause ? "Paused.\n" : "Unpaused.\n");
} else if (strncasecmp(xargv[0], "hardreset", 9) == 0) {
pc_reset_hard();
} else if (strncasecmp(xargv[0], "cdload", 6) == 0 && cmdargc >= 3) {
uint8_t id;
bool err = false;
char fn[PATH_MAX];
if (!xargv[2] || !xargv[1]) {
free(line);
free(linecpy);
line = NULL;
continue;
}
id = atoi(xargv[1]);
memset(fn, 0, sizeof(fn));
if (xargv[2][0] == '\'' || xargv[2][0] == '"') {
int curarg = 2;
for (curarg = 2; curarg < cmdargc; curarg++) {
if (strlen(fn) + strlen(xargv[curarg]) >= PATH_MAX) {
err = true;
fprintf(stderr, "Path name too long.\n");
}
strcat(fn, xargv[curarg] + (xargv[curarg][0] == '\'' || xargv[curarg][0] == '"'));
if (fn[strlen(fn) - 1] == '\''
|| fn[strlen(fn) - 1] == '"') {
break;
}
strcat(fn, " ");
}
} else {
if (strlen(xargv[2]) < PATH_MAX) {
strcpy(fn, xargv[2]);
} else {
fprintf(stderr, "Path name too long.\n");
}
}
if (!err) {
if (fn[strlen(fn) - 1] == '\''
|| fn[strlen(fn) - 1] == '"')
fn[strlen(fn) - 1] = '\0';
printf("Inserting disc into CD-ROM drive %hhu: %s\n", id, fn);
cdrom_mount(id, fn);
}
} else if (strncasecmp(xargv[0], "fddeject", 8) == 0 && cmdargc >= 2) {
floppy_eject(atoi(xargv[1]));
} else if (strncasecmp(xargv[0], "cdeject", 8) == 0 && cmdargc >= 2) {
cdrom_mount(atoi(xargv[1]), "");
} else if (strncasecmp(xargv[0], "moeject", 8) == 0 && cmdargc >= 2) {
mo_eject(atoi(xargv[1]));
} else if (strncasecmp(xargv[0], "carteject", 8) == 0 && cmdargc >= 2) {
cartridge_eject(atoi(xargv[1]));
} else if (strncasecmp(xargv[0], "zipeject", 8) == 0 && cmdargc >= 2) {
zip_eject(atoi(xargv[1]));
} else if (strncasecmp(xargv[0], "fddload", 7) == 0 && cmdargc >= 4) {
uint8_t id;
uint8_t wp;
bool err = false;
char fn[PATH_MAX];
memset(fn, 0, sizeof(fn));
if (!xargv[2] || !xargv[1]) {
free(line);
free(linecpy);
line = NULL;
continue;
}
err = process_media_commands_3(&id, fn, &wp, cmdargc);
if (!err) {
if (fn[strlen(fn) - 1] == '\''
|| fn[strlen(fn) - 1] == '"')
fn[strlen(fn) - 1] = '\0';
printf("Inserting disk into floppy drive %c: %s\n", id + 'A', fn);
floppy_mount(id, fn, wp);
}
} else if (strncasecmp(xargv[0], "moload", 7) == 0 && cmdargc >= 4) {
uint8_t id;
uint8_t wp;
bool err = false;
char fn[PATH_MAX];
memset(fn, 0, sizeof(fn));
if (!xargv[2] || !xargv[1]) {
free(line);
free(linecpy);
line = NULL;
continue;
}
err = process_media_commands_3(&id, fn, &wp, cmdargc);
if (!err) {
if (fn[strlen(fn) - 1] == '\''
|| fn[strlen(fn) - 1] == '"')
fn[strlen(fn) - 1] = '\0';
printf("Inserting into mo drive %hhu: %s\n", id, fn);
mo_mount(id, fn, wp);
}
} else if (strncasecmp(xargv[0], "cartload", 7) == 0 && cmdargc >= 4) {
uint8_t id;
uint8_t wp;
bool err = false;
char fn[PATH_MAX];
memset(fn, 0, sizeof(fn));
if (!xargv[2] || !xargv[1]) {
free(line);
free(linecpy);
line = NULL;
continue;
}
err = process_media_commands_3(&id, fn, &wp, cmdargc);
if (!err) {
if (fn[strlen(fn) - 1] == '\''
|| fn[strlen(fn) - 1] == '"')
fn[strlen(fn) - 1] = '\0';
printf("Inserting tape into cartridge holder %hhu: %s\n", id, fn);
cartridge_mount(id, fn, wp);
}
} else if (strncasecmp(xargv[0], "zipload", 7) == 0 && cmdargc >= 4) {
uint8_t id;
uint8_t wp;
bool err = false;
char fn[PATH_MAX];
memset(fn, 0, sizeof(fn));
if (!xargv[2] || !xargv[1]) {
free(line);
free(linecpy);
line = NULL;
continue;
}
err = process_media_commands_3(&id, fn, &wp, cmdargc);
if (!err) {
if (fn[strlen(fn) - 1] == '\''
|| fn[strlen(fn) - 1] == '"')
fn[strlen(fn) - 1] = '\0';
printf("Inserting disk into ZIP drive %c: %s\n", id + 'A', fn);
zip_mount(id, fn, wp);
}
}
free(line);
free(linecpy);
line = NULL;
}
}
}
#endif
}
extern int gfxcard[GFXCARD_MAX];
int
main(int argc, char **argv)
{
SDL_Event event;
void *libedithandle;
int ret = 0;
SDL_Init(0);
ret = pc_init(argc, argv);
if (ret == 0)
return 0;
if (!pc_init_modules()) {
ui_msgbox_header(MBX_FATAL, L"No ROMs found.", L"86Box could not find any usable ROM images.\n\nPlease download a ROM set and extract it into the \"roms\" directory.");
SDL_Quit();
return 6;
}
for (uint8_t i = 1; i < GFXCARD_MAX; i++)
gfxcard[i] = 0;
eventthread = SDL_ThreadID();
blitmtx = SDL_CreateMutex();
if (!blitmtx) {
fprintf(stderr, "Failed to create blit mutex: %s", SDL_GetError());
return -1;
}
libedithandle = dlopen(LIBEDIT_LIBRARY, RTLD_LOCAL | RTLD_LAZY);
if (libedithandle) {
f_readline = dlsym(libedithandle, "readline");
f_add_history = dlsym(libedithandle, "add_history");
if (!f_readline) {
fprintf(stderr, "readline in libedit not found, line editing will be limited.\n");
}
f_rl_callback_handler_remove = dlsym(libedithandle, "rl_callback_handler_remove");
} else
fprintf(stderr, "libedit not found, line editing will be limited.\n");
mousemutex = SDL_CreateMutex();
sdl_initho();
if (start_in_fullscreen) {
video_fullscreen = 1;
sdl_set_fs(1);
}
/* Fire up the machine. */
pc_reset_hard_init();
/* Set the PAUSE mode depending on the renderer. */
plat_pause(0);
/* Initialize the rendering window, or fullscreen. */
do_start();
#ifndef USE_CLI
thread_create(monitor_thread, NULL);
#endif
SDL_AddTimer(1000, timer_onesec, NULL);
while (!is_quit) {
static int mouse_inside = 0;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
exit_event = 1;
break;
case SDL_MOUSEWHEEL:
{
if (mouse_capture || video_fullscreen) {
if (event.wheel.direction == SDL_MOUSEWHEEL_FLIPPED) {
event.wheel.x *= -1;
event.wheel.y *= -1;
}
SDL_LockMutex(mousemutex);
mouse_set_z(event.wheel.y);
SDL_UnlockMutex(mousemutex);
}
break;
}
case SDL_MOUSEMOTION:
{
if (mouse_capture || video_fullscreen) {
SDL_LockMutex(mousemutex);
mouse_scale(event.motion.xrel, event.motion.yrel);
SDL_UnlockMutex(mousemutex);
}
break;
}
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
{
if ((event.button.button == SDL_BUTTON_LEFT)
&& !(mouse_capture || video_fullscreen)
&& event.button.state == SDL_RELEASED
&& mouse_inside) {
plat_mouse_capture(1);
break;
}
if (mouse_get_buttons() < 3 && event.button.button == SDL_BUTTON_MIDDLE && !video_fullscreen) {
plat_mouse_capture(0);
break;
}
if (mouse_capture || video_fullscreen) {
int buttonmask = 0;
switch (event.button.button) {
case SDL_BUTTON_LEFT:
buttonmask = 1;
break;
case SDL_BUTTON_RIGHT:
buttonmask = 2;
break;
case SDL_BUTTON_MIDDLE:
buttonmask = 4;
break;
case SDL_BUTTON_X1:
buttonmask = 8;
break;
case SDL_BUTTON_X2:
buttonmask = 16;
break;
}
SDL_LockMutex(mousemutex);
if (event.button.state == SDL_PRESSED)
mouse_set_buttons_ex(mouse_get_buttons_ex() | buttonmask);
else
mouse_set_buttons_ex(mouse_get_buttons_ex() & ~buttonmask);
SDL_UnlockMutex(mousemutex);
}
break;
}
case SDL_RENDER_DEVICE_RESET:
case SDL_RENDER_TARGETS_RESET:
{
extern void sdl_reinit_texture(void);
sdl_reinit_texture();
break;
}
case SDL_KEYDOWN:
case SDL_KEYUP:
{
uint16_t xtkey = 0;
switch (event.key.keysym.scancode) {
default:
xtkey = sdl_to_xt[event.key.keysym.scancode];
break;
}
keyboard_input(event.key.state == SDL_PRESSED, xtkey);
}
case SDL_WINDOWEVENT:
{
switch (event.window.event) {
case SDL_WINDOWEVENT_ENTER:
mouse_inside = 1;
break;
case SDL_WINDOWEVENT_LEAVE:
mouse_inside = 0;
break;
}
}
}
}
if (mouse_capture && keyboard_ismsexit()) {
plat_mouse_capture(0);
}
if (blitreq) {
extern void sdl_blit(int x, int y, int w, int h);
sdl_blit(params.x, params.y, params.w, params.h);
}
if (title_set) {
extern void ui_window_title_real(void);
ui_window_title_real();
}
if (video_fullscreen && keyboard_isfsexit()) {
sdl_set_fs(0);
video_fullscreen = 0;
}
if (fullscreen_pending) {
sdl_set_fs(video_fullscreen);
fullscreen_pending = 0;
}
if (exit_event) {
do_stop();
break;
}
}
printf("\n");
SDL_DestroyMutex(blitmtx);
SDL_DestroyMutex(mousemutex);
SDL_Quit();
if (f_rl_callback_handler_remove)
f_rl_callback_handler_remove();
return 0;
}
char *
plat_vidapi_name(int i)
{
return "default";
}
/* Sets up the program language before initialization. */
uint32_t
plat_language_code(char *langcode)
{
/* or maybe not */
return 0;
}
void
plat_get_cpu_string(char *outbuf, uint8_t len) {
char cpu_string[] = "Unknown";
strncpy(outbuf, cpu_string, len);
}
void
plat_set_thread_name(void *thread, const char *name)
{
#ifdef __APPLE__
if (thread) /* Apple pthread can only set self's name */
return;
char truncated[64];
#else
char truncated[16];
#endif
strncpy(truncated, name, sizeof(truncated) - 1);
#ifdef __APPLE__
pthread_setname_np(truncated);
#else
pthread_setname_np(thread ? *((pthread_t *) thread) : pthread_self(), truncated);
#endif
}
/* Converts back the language code to LCID */
void
plat_language_code_r(uint32_t lcid, char *outbuf, int len)
{
/* or maybe not */
return;
}
void
joystick_init(void)
{
/* No-op. */
}
void
joystick_close(void)
{
/* No-op. */
}
void
joystick_process(void)
{
/* No-op. */
}
void
startblit(void)
{
SDL_LockMutex(blitmtx);
}
void
endblit(void)
{
SDL_UnlockMutex(blitmtx);
}
/* API */
void
ui_sb_mt32lcd(char *str)
{
/* No-op. */
}
void
ui_hard_reset_completed(void)
{
/* No-op. */
}
``` | /content/code_sandbox/src/unix/unix.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 11,031 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the floppy drive emulation.
*
*
*
* Authors: Sarah Walker, <path_to_url
* Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/path.h>
#include <86box/plat.h>
#include <86box/ui.h>
#include <86box/fdd.h>
#include <86box/fdd_86f.h>
#include <86box/fdd_fdi.h>
#include <86box/fdd_imd.h>
#include <86box/fdd_img.h>
#include <86box/fdd_pcjs.h>
#include <86box/fdd_mfm.h>
#include <86box/fdd_td0.h>
#include <86box/fdc.h>
/* Flags:
Bit 0: 300 rpm supported;
Bit 1: 360 rpm supported;
Bit 2: size (0 = 3.5", 1 = 5.25");
Bit 3: sides (0 = 1, 1 = 2);
Bit 4: double density supported;
Bit 5: high density supported;
Bit 6: extended density supported;
Bit 7: double step for 40-track media;
Bit 8: invert DENSEL polarity;
Bit 9: ignore DENSEL;
Bit 10: drive is a PS/2 drive;
*/
#define FLAG_RPM_300 1
#define FLAG_RPM_360 2
#define FLAG_525 4
#define FLAG_DS 8
#define FLAG_HOLE0 16
#define FLAG_HOLE1 32
#define FLAG_HOLE2 64
#define FLAG_DOUBLE_STEP 128
#define FLAG_INVERT_DENSEL 256
#define FLAG_IGNORE_DENSEL 512
#define FLAG_PS2 1024
typedef struct fdd_t {
int type;
int track;
int densel;
int head;
int turbo;
int check_bpb;
} fdd_t;
fdd_t fdd[FDD_NUM];
char floppyfns[FDD_NUM][512];
char *fdd_image_history[FDD_NUM][FLOPPY_IMAGE_HISTORY];
pc_timer_t fdd_poll_time[FDD_NUM];
static int fdd_notfound = 0;
static int driveloaders[FDD_NUM];
int writeprot[FDD_NUM];
int fwriteprot[FDD_NUM];
int fdd_changed[FDD_NUM];
int ui_writeprot[FDD_NUM] = { 0, 0, 0, 0 };
int drive_empty[FDD_NUM] = { 1, 1, 1, 1 };
DRIVE drives[FDD_NUM];
uint64_t motoron[FDD_NUM];
fdc_t *fdd_fdc;
d86f_handler_t d86f_handler[FDD_NUM];
static const struct
{
char *ext;
void (*load)(int drive, char *fn);
void (*close)(int drive);
int size;
} loaders[] = {
{ "001", img_load, img_close, -1},
{ "002", img_load, img_close, -1},
{ "003", img_load, img_close, -1},
{ "004", img_load, img_close, -1},
{ "005", img_load, img_close, -1},
{ "006", img_load, img_close, -1},
{ "007", img_load, img_close, -1},
{ "008", img_load, img_close, -1},
{ "009", img_load, img_close, -1},
{ "010", img_load, img_close, -1},
{ "12", img_load, img_close, -1},
{ "144", img_load, img_close, -1},
{ "360", img_load, img_close, -1},
{ "720", img_load, img_close, -1},
{ "86F", d86f_load, d86f_close, -1},
{ "BIN", img_load, img_close, -1},
{ "CQ", img_load, img_close, -1},
{ "CQM", img_load, img_close, -1},
{ "DDI", img_load, img_close, -1},
{ "DSK", img_load, img_close, -1},
{ "FDI", fdi_load, fdi_close, -1},
{ "FDF", img_load, img_close, -1},
{ "FLP", img_load, img_close, -1},
{ "HDM", img_load, img_close, -1},
{ "IMA", img_load, img_close, -1},
{ "IMD", imd_load, imd_close, -1},
{ "IMG", img_load, img_close, -1},
{ "JSON", pcjs_load, pcjs_close, -1},
{ "MFM", mfm_load, mfm_close, -1},
{ "TD0", td0_load, td0_close, -1},
{ "VFD", img_load, img_close, -1},
{ "XDF", img_load, img_close, -1},
{ 0, 0, 0, 0 }
};
static const struct {
int max_track;
int flags;
const char *name;
const char *internal_name;
} drive_types[] = {
/* None */
{ 0, 0, "None", "none" },
/* 5.25" 1DD */
{ 43, FLAG_RPM_300 | FLAG_525 | FLAG_HOLE0, "5.25\" 180k", "525_1dd" },
/* 5.25" DD */
{ 43, FLAG_RPM_300 | FLAG_525 | FLAG_DS | FLAG_HOLE0, "5.25\" 360k", "525_2dd" },
/* 5.25" QD */
{ 86, FLAG_RPM_300 | FLAG_525 | FLAG_DS | FLAG_HOLE0 | FLAG_DOUBLE_STEP, "5.25\" 720k", "525_2qd" },
/* 5.25" HD PS/2 */
{ 86, FLAG_RPM_360 | FLAG_525 | FLAG_DS | FLAG_HOLE0 | FLAG_HOLE1 | FLAG_DOUBLE_STEP | FLAG_INVERT_DENSEL | FLAG_PS2, "5.25\" 1.2M PS/2", "525_2hd_ps2" },
/* 5.25" HD */
{ 86, FLAG_RPM_360 | FLAG_525 | FLAG_DS | FLAG_HOLE0 | FLAG_HOLE1 | FLAG_DOUBLE_STEP, "5.25\" 1.2M", "525_2hd" },
/* 5.25" HD Dual RPM */
{ 86, FLAG_RPM_300 | FLAG_RPM_360 | FLAG_525 | FLAG_DS | FLAG_HOLE0 | FLAG_HOLE1 | FLAG_DOUBLE_STEP, "5.25\" 1.2M 300/360 RPM", "525_2hd_dualrpm" },
/* 3.5" 1DD */
{ 86, FLAG_RPM_300 | FLAG_HOLE0 | FLAG_DOUBLE_STEP, "3.5\" 360k", "35_1dd" },
/* 3.5" DD, Equivalent to TEAC FD-235F */
{ 86, FLAG_RPM_300 | FLAG_DS | FLAG_HOLE0 | FLAG_DOUBLE_STEP, "3.5\" 720k", "35_2dd" },
/* 3.5" HD PS/2 */
{ 86, FLAG_RPM_300 | FLAG_DS | FLAG_HOLE0 | FLAG_HOLE1 | FLAG_DOUBLE_STEP | FLAG_INVERT_DENSEL | FLAG_PS2, "3.5\" 1.44M PS/2", "35_2hd_ps2" },
/* 3.5" HD, Equivalent to TEAC FD-235HF */
{ 86, FLAG_RPM_300 | FLAG_DS | FLAG_HOLE0 | FLAG_HOLE1 | FLAG_DOUBLE_STEP, "3.5\" 1.44M", "35_2hd" },
/* TODO: 3.5" DD, Equivalent to TEAC FD-235GF */
// { 86, FLAG_RPM_300 | FLAG_RPM_360 | FLAG_DS | FLAG_HOLE0 | FLAG_HOLE1 | FLAG_DOUBLE_STEP, "3.5\" 1.25M", "35_2hd_2mode" },
/* 3.5" HD PC-98 */
{ 86, FLAG_RPM_300 | FLAG_RPM_360 | FLAG_DS | FLAG_HOLE0 | FLAG_HOLE1 | FLAG_DOUBLE_STEP | FLAG_INVERT_DENSEL, "3.5\" 1.25M PC-98", "35_2hd_nec" },
/* 3.5" HD 3-Mode, Equivalent to TEAC FD-235HG */
{ 86, FLAG_RPM_300 | FLAG_RPM_360 | FLAG_DS | FLAG_HOLE0 | FLAG_HOLE1 | FLAG_DOUBLE_STEP, "3.5\" 1.44M 300/360 RPM", "35_2hd_3mode" },
/* 3.5" ED, Equivalent to TEAC FD-235J */
{ 86, FLAG_RPM_300 | FLAG_DS | FLAG_HOLE0 | FLAG_HOLE1 | FLAG_HOLE2 | FLAG_DOUBLE_STEP, "3.5\" 2.88M", "35_2ed" },
/* 3.5" ED Dual RPM, Equivalent to TEAC FD-335J */
{ 86, FLAG_RPM_300 | FLAG_RPM_360 | FLAG_DS | FLAG_HOLE0 | FLAG_HOLE1 | FLAG_HOLE2 | FLAG_DOUBLE_STEP, "3.5\" 2.88M 300/360 RPM", "35_2ed_dualrpm" },
/* End of list */
{ -1, -1, "", "" }
};
#ifdef ENABLE_FDD_LOG
int fdd_do_log = ENABLE_FDD_LOG;
static void
fdd_log(const char *fmt, ...)
{
va_list ap;
if (fdd_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define fdd_log(fmt, ...)
#endif
char *
fdd_getname(int type)
{
return (char *) drive_types[type].name;
}
char *
fdd_get_internal_name(int type)
{
return (char *) drive_types[type].internal_name;
}
int
fdd_get_from_internal_name(char *s)
{
int c = 0;
while (strlen(drive_types[c].internal_name)) {
if (!strcmp((char *) drive_types[c].internal_name, s))
return c;
c++;
}
return 0;
}
/* This is needed for the dump as 86F feature. */
void
fdd_do_seek(int drive, int track)
{
if (drives[drive].seek)
drives[drive].seek(drive, track);
}
void
fdd_forced_seek(int drive, int track_diff)
{
fdd[drive].track += track_diff;
if (fdd[drive].track < 0)
fdd[drive].track = 0;
if (fdd[drive].track > drive_types[fdd[drive].type].max_track)
fdd[drive].track = drive_types[fdd[drive].type].max_track;
fdd_do_seek(drive, fdd[drive].track);
}
void
fdd_seek(int drive, int track_diff)
{
if (!track_diff)
return;
fdd[drive].track += track_diff;
if (fdd[drive].track < 0)
fdd[drive].track = 0;
if (fdd[drive].track > drive_types[fdd[drive].type].max_track)
fdd[drive].track = drive_types[fdd[drive].type].max_track;
fdd_changed[drive] = 0;
fdd_do_seek(drive, fdd[drive].track);
}
int
fdd_track0(int drive)
{
/* If drive is disabled, TRK0 never gets set. */
if (!drive_types[fdd[drive].type].max_track)
return 0;
return !fdd[drive].track;
}
int
fdd_current_track(int drive)
{
return fdd[drive].track;
}
void
fdd_set_densel(int densel)
{
for (uint8_t i = 0; i < FDD_NUM; i++) {
if (drive_types[fdd[i].type].flags & FLAG_INVERT_DENSEL)
fdd[i].densel = densel ^ 1;
else
fdd[i].densel = densel;
}
}
int
fdd_getrpm(int drive)
{
int densel = 0;
int hole;
hole = fdd_hole(drive);
densel = fdd[drive].densel;
if (drive_types[fdd[drive].type].flags & FLAG_INVERT_DENSEL)
densel ^= 1;
if (!(drive_types[fdd[drive].type].flags & FLAG_RPM_360))
return 300;
if (!(drive_types[fdd[drive].type].flags & FLAG_RPM_300))
return 360;
if (drive_types[fdd[drive].type].flags & FLAG_525)
return densel ? 360 : 300;
else {
/* fdd_hole(drive) returns 0 for double density media, 1 for high density, and 2 for extended density. */
if (hole == 1)
return densel ? 300 : 360;
else
return 300;
}
}
int
fdd_can_read_medium(int drive)
{
int hole = fdd_hole(drive);
hole = 1 << (hole + 4);
return !!(drive_types[fdd[drive].type].flags & hole);
}
int
fdd_doublestep_40(int drive)
{
return !!(drive_types[fdd[drive].type].flags & FLAG_DOUBLE_STEP);
}
void
fdd_set_type(int drive, int type)
{
int old_type = fdd[drive].type;
fdd[drive].type = type;
if ((drive_types[old_type].flags ^ drive_types[type].flags) & FLAG_INVERT_DENSEL)
fdd[drive].densel ^= 1;
}
int
fdd_get_type(int drive)
{
return fdd[drive].type;
}
int
fdd_get_flags(int drive)
{
return drive_types[fdd[drive].type].flags;
}
int
fdd_is_525(int drive)
{
return drive_types[fdd[drive].type].flags & FLAG_525;
}
int
fdd_is_dd(int drive)
{
return (drive_types[fdd[drive].type].flags & 0x70) == 0x10;
}
int
fdd_is_hd(int drive)
{
return drive_types[fdd[drive].type].flags & FLAG_HOLE1;
}
int
fdd_is_ed(int drive)
{
return drive_types[fdd[drive].type].flags & FLAG_HOLE2;
}
int
fdd_is_double_sided(int drive)
{
return drive_types[fdd[drive].type].flags & FLAG_DS;
}
void
fdd_set_head(int drive, int head)
{
if (head && !fdd_is_double_sided(drive))
fdd[drive].head = 0;
else
fdd[drive].head = head;
}
int
fdd_get_head(int drive)
{
if (!fdd_is_double_sided(drive))
return 0;
return fdd[drive].head;
}
void
fdd_set_turbo(int drive, int turbo)
{
fdd[drive].turbo = turbo;
}
int
fdd_get_turbo(int drive)
{
return fdd[drive].turbo;
}
void
fdd_set_check_bpb(int drive, int check_bpb)
{
fdd[drive].check_bpb = check_bpb;
}
int
fdd_get_check_bpb(int drive)
{
return fdd[drive].check_bpb;
}
int
fdd_get_densel(int drive)
{
return fdd[drive].densel;
}
void
fdd_load(int drive, char *fn)
{
int c = 0;
int size;
const char *p;
FILE * fp;
fdd_log("FDD: loading drive %d with '%s'\n", drive, fn);
if (!fn)
return;
p = path_get_extension(fn);
if (!p)
return;
fp = plat_fopen(fn, "rb");
if (fp) {
if (fseek(fp, -1, SEEK_END) == -1)
fatal("fdd_load(): Error seeking to the end of the file\n");
size = ftell(fp) + 1;
fclose(fp);
while (loaders[c].ext) {
if (!strcasecmp(p, (char *) loaders[c].ext) && (size == loaders[c].size || loaders[c].size == -1)) {
driveloaders[drive] = c;
if (floppyfns[drive] != fn)
strcpy(floppyfns[drive], fn);
d86f_setup(drive);
loaders[c].load(drive, floppyfns[drive]);
drive_empty[drive] = 0;
fdd_forced_seek(drive, 0);
fdd_changed[drive] = 1;
return;
}
c++;
}
}
fdd_log("FDD: could not load '%s' %s\n", fn, p);
drive_empty[drive] = 1;
fdd_set_head(drive, 0);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
ui_sb_update_icon_state(SB_FLOPPY | drive, 1);
}
void
fdd_close(int drive)
{
fdd_log("FDD: closing drive %d\n", drive);
d86f_stop(drive); /* Call this first of all to make sure the 86F poll is back to idle state. */
if (loaders[driveloaders[drive]].close)
loaders[driveloaders[drive]].close(drive);
drive_empty[drive] = 1;
fdd_set_head(drive, 0);
floppyfns[drive][0] = 0;
drives[drive].hole = NULL;
drives[drive].poll = NULL;
drives[drive].seek = NULL;
drives[drive].readsector = NULL;
drives[drive].writesector = NULL;
drives[drive].comparesector = NULL;
drives[drive].readaddress = NULL;
drives[drive].format = NULL;
drives[drive].byteperiod = NULL;
drives[drive].stop = NULL;
d86f_destroy(drive);
ui_sb_update_icon_state(SB_FLOPPY | drive, 1);
}
int
fdd_hole(int drive)
{
if (drives[drive].hole)
return drives[drive].hole(drive);
else
return 0;
}
static __inline uint64_t
fdd_byteperiod(int drive)
{
if (!fdd_get_turbo(drive) && drives[drive].byteperiod)
return drives[drive].byteperiod(drive);
else
return 32ULL * TIMER_USEC;
}
void
fdd_set_motor_enable(int drive, int motor_enable)
{
/* I think here is where spin-up and spin-down should be implemented. */
if (motor_enable && !motoron[drive])
timer_set_delay_u64(&fdd_poll_time[drive], fdd_byteperiod(drive));
else if (!motor_enable)
timer_disable(&fdd_poll_time[drive]);
motoron[drive] = motor_enable;
}
static void
fdd_poll(void *priv)
{
int drive;
const DRIVE *drv = (DRIVE *) priv;
drive = drv->id;
if (drive >= FDD_NUM)
fatal("Attempting to poll floppy drive %i that is not supposed to be there\n", drive);
timer_advance_u64(&fdd_poll_time[drive], fdd_byteperiod(drive));
if (drv->poll)
drv->poll(drive);
if (fdd_notfound) {
fdd_notfound--;
if (!fdd_notfound)
fdc_noidam(fdd_fdc);
}
}
int
fdd_get_bitcell_period(int rate)
{
int bit_rate = 250;
switch (rate) {
case 0: /*High density*/
bit_rate = 500;
break;
case 1: /*Double density (360 rpm)*/
bit_rate = 300;
break;
case 2: /*Double density*/
bit_rate = 250;
break;
case 3: /*Extended density*/
bit_rate = 1000;
break;
default:
break;
}
return 1000000 / bit_rate * 2; /*Bitcell period in ns*/
}
void
fdd_reset(void)
{
for (uint8_t i = 0; i < FDD_NUM; i++) {
drives[i].id = i;
timer_add(&(fdd_poll_time[i]), fdd_poll, &drives[i], 0);
}
}
void
fdd_readsector(int drive, int sector, int track, int side, int density, int sector_size)
{
if (drives[drive].readsector)
drives[drive].readsector(drive, sector, track, side, density, sector_size);
else
fdd_notfound = 1000;
}
void
fdd_writesector(int drive, int sector, int track, int side, int density, int sector_size)
{
if (drives[drive].writesector)
drives[drive].writesector(drive, sector, track, side, density, sector_size);
else
fdd_notfound = 1000;
}
void
fdd_comparesector(int drive, int sector, int track, int side, int density, int sector_size)
{
if (drives[drive].comparesector)
drives[drive].comparesector(drive, sector, track, side, density, sector_size);
else
fdd_notfound = 1000;
}
void
fdd_readaddress(int drive, int side, int density)
{
if (drives[drive].readaddress)
drives[drive].readaddress(drive, side, density);
}
void
fdd_format(int drive, int side, int density, uint8_t fill)
{
if (drives[drive].format)
drives[drive].format(drive, side, density, fill);
else
fdd_notfound = 1000;
}
void
fdd_stop(int drive)
{
if (drives[drive].stop)
drives[drive].stop(drive);
}
void
fdd_set_fdc(void *fdc)
{
fdd_fdc = (fdc_t *) fdc;
}
void
fdd_init(void)
{
int i;
for (i = 0; i < FDD_NUM; i++) {
drives[i].poll = 0;
drives[i].seek = 0;
drives[i].readsector = 0;
}
img_init();
d86f_init();
td0_init();
imd_init();
pcjs_init();
for (i = 0; i < FDD_NUM; i++) {
fdd_load(i, floppyfns[i]);
}
}
void
fdd_do_writeback(int drive)
{
d86f_handler[drive].writeback(drive);
}
``` | /content/code_sandbox/src/floppy/fdd.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 5,520 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the Teledisk floppy image format.
*
*
*
* Authors: Milodrag Milanovic,
* Haruhiko OKUMURA,
* Haruyasu YOSHIZAKI,
* Kenji RIKITAKE,
* Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
*
* Based on Japanese version 29-NOV-1988
* LZSS coded by Haruhiko OKUMURA
* Adaptive Huffman Coding coded by Haruyasu YOSHIZAKI
* Edited and translated to English by Kenji RIKITAKE
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/plat.h>
#include <86box/fdd.h>
#include <86box/fdd_86f.h>
#include <86box/fdd_td0.h>
#include <86box/fdc.h>
#include "lzw/lzw.h"
#define BUFSZ 512 /* new input buffer */
#define TD0_MAX_BUFSZ (1024UL * 1024UL * 4UL)
/* LZSS Parameters */
#define N 4096 /* Size of string buffer */
#define F 60 /* Size of look-ahead buffer */
#define THRESHOLD 2
#define NIL N /* End of tree's node */
/* Huffman coding parameters */
#define N_CHAR (256 - THRESHOLD + F) /* code (= 0..N_CHAR-1) */
#define T (N_CHAR * 2 - 1) /* Size of table */
#define R (T - 1) /* root position */
#define MAX_FREQ 0x8000
/* update when cumulative frequency */
/* reaches to this value */
typedef struct tdlzhuf_t {
uint16_t r;
uint16_t bufcnt; /* string buffer */
uint16_t bufndx; /* string buffer */
uint16_t bufpos; /* string buffer */
/* the following to allow block reads
from input in next_word() */
uint16_t ibufcnt; /* input buffer counters */
uint16_t ibufndx; /* input buffer counters */
uint8_t inbuf[BUFSZ]; /* input buffer */
} tdlzhuf;
typedef struct td0dsk_t {
FILE *fdd_file;
off_t fdd_file_offset;
tdlzhuf tdctl;
uint8_t text_buf[N + F - 1];
uint16_t freq[T + 1]; /* cumulative freq table */
/*
* pointing parent nodes.
* area [T..(T + N_CHAR - 1)] are pointers for leaves
*/
int16_t prnt[T + N_CHAR];
/* pointing children nodes (son[], son[] + 1)*/
int16_t son[T];
uint16_t getbuf;
uint8_t getlen;
} td0dsk_t;
typedef struct td0_sector_t {
uint8_t track;
uint8_t head;
uint8_t sector;
uint8_t size;
uint8_t flags;
uint8_t fm;
uint8_t *data;
} td0_sector_t;
typedef struct td0_t {
FILE *fp;
int tracks;
int track_width;
int sides;
uint16_t disk_flags;
uint16_t default_track_flags;
uint16_t side_flags[256][2];
uint8_t max_sector_size;
uint8_t track_in_file[256][2];
td0_sector_t sects[256][2][256];
uint8_t track_spt[256][2];
uint8_t gap3_len;
uint16_t current_side_flags[2];
int track;
int current_sector_index[2];
uint8_t calculated_gap3_lengths[256][2];
uint8_t xdf_ordered_pos[256][2];
uint8_t interleave_ordered_pos[256][2];
uint8_t *lzw_buf;
uint8_t *imagebuf;
uint8_t *processed_buf;
} td0_t;
/*
* Tables for encoding/decoding upper 6 bits of
* sliding dictionary pointer
*/
static const uint8_t d_code[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,
0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A,
0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B,
0x0C, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D,
0x0E, 0x0E, 0x0E, 0x0E, 0x0F, 0x0F, 0x0F, 0x0F,
0x10, 0x10, 0x10, 0x10, 0x11, 0x11, 0x11, 0x11,
0x12, 0x12, 0x12, 0x12, 0x13, 0x13, 0x13, 0x13,
0x14, 0x14, 0x14, 0x14, 0x15, 0x15, 0x15, 0x15,
0x16, 0x16, 0x16, 0x16, 0x17, 0x17, 0x17, 0x17,
0x18, 0x18, 0x19, 0x19, 0x1A, 0x1A, 0x1B, 0x1B,
0x1C, 0x1C, 0x1D, 0x1D, 0x1E, 0x1E, 0x1F, 0x1F,
0x20, 0x20, 0x21, 0x21, 0x22, 0x22, 0x23, 0x23,
0x24, 0x24, 0x25, 0x25, 0x26, 0x26, 0x27, 0x27,
0x28, 0x28, 0x29, 0x29, 0x2A, 0x2A, 0x2B, 0x2B,
0x2C, 0x2C, 0x2D, 0x2D, 0x2E, 0x2E, 0x2F, 0x2F,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
};
static const uint8_t d_len[256] = {
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
};
static td0_t *td0[FDD_NUM];
#ifdef ENABLE_TD0_LOG
int td0_do_log = ENABLE_TD0_LOG;
static void
td0_log(const char *fmt, ...)
{
va_list ap;
if (td0_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define td0_log(fmt, ...)
#endif
static void
fdd_image_read(int drive, char *buffer, uint32_t offset, uint32_t len)
{
td0_t *dev = td0[drive];
if (fseek(dev->fp, offset, SEEK_SET) == -1)
fatal("fdd_image_read(): Error seeking to the beginning of the file\n");
if (fread(buffer, 1, len, dev->fp) != len)
fatal("fdd_image_read(): Error reading data\n");
}
static int
dsk_identify(int drive)
{
char header[2];
fdd_image_read(drive, header, 0, 2);
if (header[0] == 'T' && header[1] == 'D')
return 1;
else if (header[0] == 't' && header[1] == 'd')
return 1;
return 0;
}
static int
state_data_read(td0dsk_t *state, uint8_t *buf, uint16_t size)
{
uint32_t image_size = 0;
fseek(state->fdd_file, 0, SEEK_END);
image_size = ftell(state->fdd_file);
if (size > image_size - state->fdd_file_offset)
size = (image_size - state->fdd_file_offset) & 0xffff;
if (fseek(state->fdd_file, state->fdd_file_offset, SEEK_SET) == -1)
fatal("TD0: Failed to seek in state_data_read()\n");
if (fread(buf, 1, size, state->fdd_file) != size)
fatal("TD0: Error reading data in state_data_read()\n");
state->fdd_file_offset += size;
return size;
}
static int
state_next_word(td0dsk_t *state)
{
if (state->tdctl.ibufndx >= state->tdctl.ibufcnt) {
state->tdctl.ibufndx = 0;
state->tdctl.ibufcnt = state_data_read(state, state->tdctl.inbuf, BUFSZ);
if (state->tdctl.ibufcnt == 0)
return (-1);
}
while (state->getlen <= 8) { /* typically reads a word at a time */
state->getbuf |= state->tdctl.inbuf[state->tdctl.ibufndx++] << (8 - state->getlen);
state->getlen += 8;
}
return 0;
}
/* get one bit */
static int
state_GetBit(td0dsk_t *state)
{
int16_t i;
if (state_next_word(state) < 0)
return (-1);
i = state->getbuf;
state->getbuf <<= 1;
state->getlen--;
if (i < 0)
return 1;
return 0;
}
/* get a byte */
static int
state_GetByte(td0dsk_t *state)
{
uint16_t i;
if (state_next_word(state) != 0)
return -1;
i = state->getbuf;
state->getbuf <<= 8;
state->getlen -= 8;
i = i >> 8;
return ((int) i);
}
/* initialize freq tree */
static void
state_StartHuff(td0dsk_t *state)
{
int i;
int j;
for (i = 0; i < N_CHAR; i++) {
state->freq[i] = 1;
state->son[i] = i + T;
state->prnt[i + T] = i;
}
i = 0;
j = N_CHAR;
while (j <= R) {
state->freq[j] = state->freq[i] + state->freq[i + 1];
state->son[j] = i;
state->prnt[i] = state->prnt[i + 1] = j;
i += 2;
j++;
}
state->freq[T] = 0xffff;
state->prnt[R] = 0;
}
/* reconstruct freq tree */
static void
state_reconst(td0dsk_t *state)
{
int16_t i;
int16_t j;
int16_t k;
uint16_t f;
uint16_t l;
/* halven cumulative freq for leaf nodes */
j = 0;
for (i = 0; i < T; i++) {
if (state->son[i] >= T) {
state->freq[j] = (state->freq[i] + 1) / 2;
state->son[j] = state->son[i];
j++;
}
}
/* make a tree : first, connect children nodes */
for (i = 0, j = N_CHAR; j < T; i += 2, j++) {
k = i + 1;
f = state->freq[j] = state->freq[i] + state->freq[k];
for (k = j - 1; f < state->freq[k]; k--) { }
k++;
l = (j - k) * 2;
/* These *HAVE* to be memmove's as destination and source
can overlap, which memcpy can't handle. */
memmove(&state->freq[k + 1], &state->freq[k], l);
state->freq[k] = f;
memmove(&state->son[k + 1], &state->son[k], l);
state->son[k] = i;
}
/* connect parent nodes */
for (i = 0; i < T; i++) {
if ((k = state->son[i]) >= T)
state->prnt[k] = i;
else
state->prnt[k] = state->prnt[k + 1] = i;
}
}
/* update freq tree */
static void
state_update(td0dsk_t *state, int c)
{
int i;
int j;
int k;
int l;
if (state->freq[R] == MAX_FREQ)
state_reconst(state);
c = state->prnt[c + T];
/* do it until reaching the root */
do {
k = ++state->freq[c];
/* swap nodes to keep the tree freq-ordered */
if (k > state->freq[l = c + 1]) {
while (k > state->freq[++l]) { }
l--;
state->freq[c] = state->freq[l];
state->freq[l] = k;
i = state->son[c];
state->prnt[i] = l;
if (i < T)
state->prnt[i + 1] = l;
j = state->son[l];
state->son[l] = i;
state->prnt[j] = c;
if (j < T)
state->prnt[j + 1] = c;
state->son[c] = j;
c = l;
}
} while ((c = state->prnt[c]) != 0);
}
static int16_t
state_DecodeChar(td0dsk_t *state)
{
int ret;
uint16_t c;
c = state->son[R];
/*
* start searching tree from the root to leaves.
* choose node #(son[]) if input bit == 0
* else choose #(son[]+1) (input bit == 1)
*/
while (c < T) {
if ((ret = state_GetBit(state)) < 0)
return (-1);
c += (unsigned) ret;
c = state->son[c];
}
c -= T;
state_update(state, c);
return c;
}
static int16_t
state_DecodePosition(td0dsk_t *state)
{
int16_t bit;
uint16_t i;
uint16_t j;
uint16_t c;
/* decode upper 6 bits from given table */
if ((bit = state_GetByte(state)) < 0)
return (-1);
i = (uint16_t) bit;
c = (uint16_t) d_code[i] << 6;
j = d_len[i];
/* input lower 6 bits directly */
j -= 2;
while (j--) {
if ((bit = state_GetBit(state)) < 0)
return (-1);
i = (i << 1) + bit;
}
return (c | (i & 0x3f));
}
/* DeCompression - split out initialization code to init_Decode() */
static void
state_init_Decode(td0dsk_t *state)
{
state->getbuf = 0;
state->getlen = 0;
state->tdctl.ibufcnt = state->tdctl.ibufndx = 0; /* input buffer is empty */
state->tdctl.bufcnt = 0;
state_StartHuff(state);
for (uint16_t i = 0; i < N - F; i++)
state->text_buf[i] = ' ';
state->tdctl.r = N - F;
}
/* Decoding/Uncompressing */
static int
state_Decode(td0dsk_t *state, uint8_t *buf, int len)
{
int16_t c;
int16_t pos;
int count; /* was an unsigned long, seems unnecessary */
for (count = 0; count < len;) {
if (state->tdctl.bufcnt == 0) {
if ((c = state_DecodeChar(state)) < 0)
return count; /* fatal error */
if (c < 256) {
*(buf++) = c & 0xff;
state->text_buf[state->tdctl.r++] = c & 0xff;
state->tdctl.r &= (N - 1);
count++;
} else {
if ((pos = state_DecodePosition(state)) < 0)
return count; /* fatal error */
state->tdctl.bufpos = (state->tdctl.r - pos - 1) & (N - 1);
state->tdctl.bufcnt = c - 255 + THRESHOLD;
state->tdctl.bufndx = 0;
}
} else {
/* still chars from last string */
while (state->tdctl.bufndx < state->tdctl.bufcnt && count < len) {
c = state->text_buf[(state->tdctl.bufpos + state->tdctl.bufndx) & (N - 1)];
*(buf++) = c & 0xff;
state->tdctl.bufndx++;
state->text_buf[state->tdctl.r++] = c & 0xff;
state->tdctl.r &= (N - 1);
count++;
}
/* reset bufcnt after copy string from text_buf[] */
if (state->tdctl.bufndx >= state->tdctl.bufcnt)
state->tdctl.bufndx = state->tdctl.bufcnt = 0;
}
}
return count; /* count == len, success */
}
static uint32_t
get_raw_tsize(int side_flags, int slower_rpm)
{
uint32_t size;
switch (side_flags & 0x27) {
case 0x22:
size = slower_rpm ? 5314 : 5208;
break;
default:
case 0x02:
case 0x21:
size = slower_rpm ? 6375 : 6250;
break;
case 0x01:
size = slower_rpm ? 7650 : 7500;
break;
case 0x20:
size = slower_rpm ? 10629 : 10416;
break;
case 0x00:
size = slower_rpm ? 12750 : 12500;
break;
case 0x23:
size = slower_rpm ? 21258 : 20833;
break;
case 0x03:
size = slower_rpm ? 25500 : 25000;
break;
case 0x25:
size = slower_rpm ? 42517 : 41666;
break;
case 0x05:
size = slower_rpm ? 51000 : 50000;
break;
}
return size;
}
static int
td0_initialize(int drive)
{
td0_t *dev = td0[drive];
uint8_t header[12];
int fm;
int head;
int track;
int track_count = 0;
int head_count = 0;
int track_spt;
int track_spt_adjusted;
int offset = 0;
int density = 0;
int temp_rate = 0;
uint32_t file_size;
uint16_t len;
uint16_t rep;
td0dsk_t disk_decode;
const uint8_t *hs;
uint16_t size;
uint8_t *dbuf = dev->processed_buf;
uint32_t total_size = 0;
uint32_t id_field = 0;
uint32_t pre_sector = 0;
int32_t track_size = 0;
int32_t raw_tsize = 0;
uint32_t minimum_gap3 = 0;
uint32_t minimum_gap4 = 0;
int i;
int j;
int k;
int size_diff;
int gap_sum;
if (dev->fp == NULL) {
td0_log("TD0: Attempted to initialize without loading a file first\n");
return 0;
}
fseek(dev->fp, 0, SEEK_END);
file_size = ftell(dev->fp);
if (file_size < 12) {
td0_log("TD0: File is too small to even contain the header\n");
return 0;
}
if (file_size > TD0_MAX_BUFSZ) {
td0_log("TD0: File exceeds the maximum size\n");
return 0;
}
fseek(dev->fp, 0, SEEK_SET);
(void) !fread(header, 1, 12, dev->fp);
head_count = header[9];
if (header[0] == 't') {
if (((header[4] / 10) % 10) == 2) {
td0_log("TD0: File is compressed (TeleDisk 2.x, LZHUF)\n");
disk_decode.fdd_file = dev->fp;
state_init_Decode(&disk_decode);
disk_decode.fdd_file_offset = 12;
state_Decode(&disk_decode, dev->imagebuf, TD0_MAX_BUFSZ);
} else {
td0_log("TD0: File is compressed (TeleDisk 1.x, LZW)\n");
if (fseek(dev->fp, 12, SEEK_SET) == -1)
fatal("td0_initialize(): Error seeking to offet 12\n");
if (fread(dev->lzw_buf, 1, file_size - 12, dev->fp) != (file_size - 12))
fatal("td0_initialize(): Error reading LZW-encoded buffer\n");
LZWDecodeFile((char *) dev->imagebuf, (char *) dev->lzw_buf, NULL, file_size - 12);
}
} else {
td0_log("TD0: File is uncompressed\n");
if (fseek(dev->fp, 12, SEEK_SET) == -1)
fatal("td0_initialize(): Error seeking to offet 12\n");
if (fread(dev->imagebuf, 1, file_size - 12, dev->fp) != (file_size - 12))
fatal("td0_initialize(): Error reading image buffer\n");
}
if (header[7] & 0x80)
offset = 10 + dev->imagebuf[2] + (dev->imagebuf[3] << 8);
track_spt = dev->imagebuf[offset];
if (track_spt == 255) {
/* Empty file? */
td0_log("TD0: File has no tracks\n");
return 0;
}
density = (header[5] >> 1) & 3;
if (density == 3) {
td0_log("TD0: Unknown density\n");
return 0;
}
/*
* We determine RPM from the drive type as well as we possibly can.
* This byte is actually the BIOS floppy drive type read by Teledisk
* from the CMOS.
*/
switch (header[6]) {
case 0: /* 5.25" 360k in 1.2M drive: 360 rpm
CMOS Drive type: None, value probably
reused by Teledisk */
case 2: /* 5.25" 1.2M: 360 rpm */
case 5: /* 8"/5.25"/3.5" 1.25M: 360 rpm */
dev->default_track_flags = (density == 1) ? 0x20 : 0x21;
dev->max_sector_size = (density == 1) ? 6 : 5; /* 8192 or 4096 bytes. */
break;
case 1: /* 5.25" 360k: 300 rpm */
case 3: /* 3.5" 720k: 300 rpm */
dev->default_track_flags = 0x02;
dev->max_sector_size = 5; /* 4096 bytes. */
break;
case 4: /* 3.5" 1.44M: 300 rpm */
dev->default_track_flags = (density == 1) ? 0x00 : 0x02;
dev->max_sector_size = (density == 1) ? 6 : 5; /* 8192 or 4096 bytes. */
break;
case 6: /* 3.5" 2.88M: 300 rpm */
dev->default_track_flags = (density == 1) ? 0x00 : ((density == 2) ? 0x03 : 0x02);
dev->max_sector_size = (density == 1) ? 6 : ((density == 2) ? 7 : 5); /* 16384, 8192, or 4096 bytes. */
break;
default:
break;
}
dev->disk_flags = header[5] & 0x06;
dev->track_width = (header[7] & 1) ^ 1;
for (i = 0; i < 256; i++) {
memset(dev->side_flags[i], 0, 4);
memset(dev->track_in_file[i], 0, 2);
memset(dev->calculated_gap3_lengths[i], 0, 2);
for (j = 0; j < 2; j++)
memset(dev->sects[i][j], 0, sizeof(td0_sector_t));
}
while (track_spt != 255) {
track_spt_adjusted = track_spt;
track = dev->imagebuf[offset + 1];
head = dev->imagebuf[offset + 2] & 1;
fm = (header[5] & 0x80) || (dev->imagebuf[offset + 2] & 0x80); /* ? */
dev->side_flags[track][head] = dev->default_track_flags | (fm ? 0 : 8);
dev->track_in_file[track][head] = 1;
offset += 4;
track_size = fm ? 73 : 146;
if (density == 2)
id_field = fm ? 54 : 63;
else
id_field = fm ? 35 : 44;
pre_sector = id_field + (fm ? 7 : 16);
for (i = 0; i < track_spt; i++) {
hs = &dev->imagebuf[offset];
offset += 6;
dev->sects[track][head][i].track = hs[0];
dev->sects[track][head][i].head = hs[1];
dev->sects[track][head][i].sector = hs[2];
dev->sects[track][head][i].size = hs[3];
dev->sects[track][head][i].flags = hs[4];
dev->sects[track][head][i].fm = !!fm;
dev->sects[track][head][i].data = dbuf;
size = 128 << hs[3];
if ((total_size + size) >= TD0_MAX_BUFSZ) {
td0_log("TD0: Processed buffer overflow\n");
return 0;
}
if (hs[4] & 0x30)
memset(dbuf, (hs[4] & 0x10) ? 0xf6 : 0x00, size);
else {
offset += 3;
switch (hs[8]) {
default:
td0_log("TD0: Image uses an unsupported sector data encoding: %i\n", hs[8]);
return 0;
case 0:
memcpy(dbuf, &dev->imagebuf[offset], size);
offset += size;
break;
case 1:
offset += 4;
k = (hs[9] + (hs[10] << 8)) * 2;
k = (k <= size) ? k : size;
for (j = 0; j < k; j += 2) {
dbuf[j] = hs[11];
dbuf[j + 1] = hs[12];
}
if (k < size)
memset(&(dbuf[k]), 0, size - k);
break;
case 2:
k = 0;
while (k < size) {
len = dev->imagebuf[offset];
rep = dev->imagebuf[offset + 1];
offset += 2;
if (!len) {
memcpy(&(dbuf[k]), &dev->imagebuf[offset], rep);
offset += rep;
k += rep;
} else {
len = (1 << len);
rep = len * rep;
rep = ((rep + k) <= size) ? rep : (size - k);
for (j = 0; j < rep; j += len)
memcpy(&(dbuf[j + k]), &dev->imagebuf[offset], len);
k += rep;
offset += len;
}
}
break;
}
}
dbuf += size;
total_size += size;
if (hs[4] & 0x20) {
track_size += id_field;
track_spt_adjusted--;
} else if (hs[4] & 0x40)
track_size += (pre_sector - id_field + 3);
else {
if ((hs[4] & 0x02) || (hs[3] > (dev->max_sector_size - fm)))
track_size += (pre_sector + 3);
else
track_size += (pre_sector + size + 2);
}
}
if (track > track_count)
track_count = track;
if (track_spt != 255) {
dev->track_spt[track][head] = track_spt;
if ((dev->track_spt[track][head] == 8) && (dev->sects[track][head][0].size == 3))
dev->side_flags[track][head] = (dev->side_flags[track][head] & ~0x67) | 0x20;
raw_tsize = get_raw_tsize(dev->side_flags[track][head], 0);
minimum_gap3 = 12 * track_spt_adjusted;
size_diff = raw_tsize - track_size;
gap_sum = minimum_gap3 + minimum_gap4;
if (size_diff < gap_sum) {
/* If we can't fit the sectors with a reasonable minimum gap at perfect RPM, let's try 2% slower. */
raw_tsize = get_raw_tsize(dev->side_flags[track][head], 1);
/* Set disk flags so that rotation speed is 2% slower. */
dev->disk_flags |= (3 << 5);
size_diff = raw_tsize - track_size;
if ((size_diff < gap_sum) && !fdd_get_turbo(drive)) {
/* If we can't fit the sectors with a reasonable minimum gap even at 2% slower RPM, abort. */
td0_log("TD0: Unable to fit the %i sectors into drive %i, track %i, side %i\n", track_spt_adjusted, drive, track, head);
return 0;
}
}
dev->calculated_gap3_lengths[track][head] = (size_diff - minimum_gap4) / track_spt_adjusted;
track_spt = dev->imagebuf[offset];
}
}
if ((dev->disk_flags & 0x60) == 0x60)
td0_log("TD0: Disk will rotate 2% below perfect RPM\n");
dev->tracks = track_count + 1;
temp_rate = dev->default_track_flags & 7;
if ((dev->default_track_flags & 0x27) == 0x20)
temp_rate = 4;
dev->gap3_len = gap3_sizes[temp_rate][dev->sects[0][0][0].size][dev->track_spt[0][0]];
if (!dev->gap3_len)
dev->gap3_len = dev->calculated_gap3_lengths[0][0]; /* If we can't determine the GAP3 length, assume the smallest one we possibly know of. */
if (head_count == 2)
dev->disk_flags |= 8; /* 2 sides */
if (dev->tracks <= 43)
dev->track_width &= ~1;
dev->sides = head_count;
dev->current_side_flags[0] = dev->side_flags[0][0];
dev->current_side_flags[1] = dev->side_flags[0][1];
td0_log("TD0: File loaded: %i tracks, %i sides, disk flags: %02X, side flags: %02X, %02X, GAP3 length: %02X\n", dev->tracks, dev->sides, dev->disk_flags, dev->current_side_flags[0], dev->current_side_flags[1], dev->gap3_len);
return 1;
}
static uint16_t
disk_flags(int drive)
{
const td0_t *dev = td0[drive];
return (dev->disk_flags);
}
static uint16_t
side_flags(int drive)
{
const td0_t *dev = td0[drive];
int side = 0;
uint16_t sflags = 0;
side = fdd_get_head(drive);
sflags = dev->current_side_flags[side];
return sflags;
}
static void
set_sector(int drive, int side, uint8_t c, uint8_t h, uint8_t r, uint8_t n)
{
td0_t *dev = td0[drive];
int cyl = c;
dev->current_sector_index[side] = 0;
if (cyl != dev->track)
return;
for (uint8_t i = 0; i < dev->track_spt[cyl][side]; i++) {
if ((dev->sects[cyl][side][i].track == c) && (dev->sects[cyl][side][i].head == h) && (dev->sects[cyl][side][i].sector == r) && (dev->sects[cyl][side][i].size == n)) {
dev->current_sector_index[side] = i;
}
}
}
static uint8_t
poll_read_data(int drive, int side, uint16_t pos)
{
const td0_t *dev = td0[drive];
return (dev->sects[dev->track][side][dev->current_sector_index[side]].data[pos]);
}
static int
track_is_xdf(int drive, int side, int track)
{
td0_t *dev = td0[drive];
uint8_t id[4] = { 0, 0, 0, 0 };
int i;
int effective_sectors;
int xdf_sectors;
int high_sectors;
int low_sectors;
int max_high_id;
int expected_high_count;
int expected_low_count;
effective_sectors = xdf_sectors = high_sectors = low_sectors = 0;
memset(dev->xdf_ordered_pos[side], 0, 256);
if (!track) {
if ((dev->track_spt[track][side] == 16) || (dev->track_spt[track][side] == 19)) {
if (!side) {
max_high_id = (dev->track_spt[track][side] == 19) ? 0x8B : 0x88;
expected_high_count = (dev->track_spt[track][side] == 19) ? 0x0B : 0x08;
expected_low_count = 8;
} else {
max_high_id = (dev->track_spt[track][side] == 19) ? 0x93 : 0x90;
expected_high_count = (dev->track_spt[track][side] == 19) ? 0x13 : 0x10;
expected_low_count = 0;
}
for (i = 0; i < dev->track_spt[track][side]; i++) {
id[0] = dev->sects[track][side][i].track;
id[1] = dev->sects[track][side][i].head;
id[2] = dev->sects[track][side][i].sector;
id[3] = dev->sects[track][side][i].size;
if (!(id[0]) && (id[1] == side) && (id[3] == 2)) {
if ((id[2] >= 0x81) && (id[2] <= max_high_id)) {
high_sectors++;
dev->xdf_ordered_pos[id[2]][side] = i;
}
if ((id[2] >= 0x01) && (id[2] <= 0x08)) {
low_sectors++;
dev->xdf_ordered_pos[id[2]][side] = i;
}
}
}
if ((high_sectors == expected_high_count) && (low_sectors == expected_low_count)) {
dev->current_side_flags[side] = (dev->track_spt[track][side] == 19) ? 0x08 : 0x28;
return ((dev->track_spt[track][side] == 19) ? 2 : 1);
}
}
} else {
for (i = 0; i < dev->track_spt[track][side]; i++) {
id[0] = dev->sects[track][side][i].track;
id[1] = dev->sects[track][side][i].head;
id[2] = dev->sects[track][side][i].sector;
id[3] = dev->sects[track][side][i].size;
effective_sectors++;
if ((id[0] == track) && (id[1] == side) && !(id[2]) && !(id[3])) {
effective_sectors--;
}
if ((id[0] == track) && (id[1] == side) && (id[2] == (id[3] | 0x80))) {
xdf_sectors++;
dev->xdf_ordered_pos[id[2]][side] = i;
}
}
if ((effective_sectors == 3) && (xdf_sectors == 3)) {
dev->current_side_flags[side] = 0x28;
return 1; /* 5.25" 2HD XDF */
}
if ((effective_sectors == 4) && (xdf_sectors == 4)) {
dev->current_side_flags[side] = 0x08;
return 2; /* 3.5" 2HD XDF */
}
}
return 0;
}
static int
track_is_interleave(int drive, int side, int track)
{
td0_t *dev = td0[drive];
int i;
int effective_sectors;
int track_spt;
effective_sectors = 0;
for (i = 0; i < 256; i++)
dev->interleave_ordered_pos[i][side] = 0;
track_spt = dev->track_spt[track][side];
if (track_spt != 21)
return 0;
for (i = 0; i < track_spt; i++) {
if ((dev->sects[track][side][i].track == track) && (dev->sects[track][side][i].head == side) && (dev->sects[track][side][i].sector >= 1) && (dev->sects[track][side][i].sector <= track_spt) && (dev->sects[track][side][i].size == 2)) {
effective_sectors++;
dev->interleave_ordered_pos[dev->sects[track][side][i].sector][side] = i;
}
}
if (effective_sectors == track_spt)
return 1;
return 0;
}
static void
td0_seek(int drive, int track)
{
td0_t *dev = td0[drive];
uint8_t id[4] = { 0, 0, 0, 0 };
int sector;
int current_pos;
int ssize = 512;
int track_rate = 0;
int track_gap2 = 22;
int track_gap3 = 12;
int xdf_type = 0;
int interleave_type = 0;
int is_trackx = 0;
int xdf_spt = 0;
int xdf_sector = 0;
int ordered_pos = 0;
int real_sector = 0;
int actual_sector = 0;
int fm;
int sector_adjusted;
if (dev->fp == NULL)
return;
if (!dev->track_width && fdd_doublestep_40(drive))
track /= 2;
d86f_set_cur_track(drive, track);
is_trackx = (track == 0) ? 0 : 1;
dev->track = track;
dev->current_side_flags[0] = dev->side_flags[track][0];
dev->current_side_flags[1] = dev->side_flags[track][1];
d86f_reset_index_hole_pos(drive, 0);
d86f_reset_index_hole_pos(drive, 1);
d86f_destroy_linked_lists(drive, 0);
d86f_destroy_linked_lists(drive, 1);
if (track > dev->tracks) {
d86f_zero_track(drive);
return;
}
for (int side = 0; side < dev->sides; side++) {
track_rate = dev->current_side_flags[side] & 7;
/* Make sure 300 kbps @ 360 rpm is treated the same as 250 kbps @ 300 rpm. */
if (!track_rate && (dev->current_side_flags[side] & 0x20))
track_rate = 4;
if ((dev->current_side_flags[side] & 0x27) == 0x21)
track_rate = 2;
track_gap3 = gap3_sizes[track_rate][dev->sects[track][side][0].size][dev->track_spt[track][side]];
if (!track_gap3)
track_gap3 = dev->calculated_gap3_lengths[track][side];
track_gap2 = ((dev->current_side_flags[side] & 7) >= 3) ? 41 : 22;
xdf_type = track_is_xdf(drive, side, track);
interleave_type = track_is_interleave(drive, side, track);
current_pos = d86f_prepare_pretrack(drive, side, 0);
sector_adjusted = 0;
if (!xdf_type) {
for (sector = 0; sector < dev->track_spt[track][side]; sector++) {
if (interleave_type == 0) {
real_sector = dev->sects[track][side][sector].sector;
actual_sector = sector;
} else {
real_sector = dmf_r[sector];
actual_sector = dev->interleave_ordered_pos[real_sector][side];
}
id[0] = dev->sects[track][side][actual_sector].track;
id[1] = dev->sects[track][side][actual_sector].head;
id[2] = real_sector;
id[3] = dev->sects[track][side][actual_sector].size;
td0_log("track %i, side %i, %i,%i,%i,%i %i\n", track, side, id[0], id[1], id[2], id[3], dev->sects[track][side][actual_sector].flags);
fm = dev->sects[track][side][actual_sector].fm;
if (((dev->sects[track][side][actual_sector].flags & 0x42) || (id[3] > (dev->max_sector_size - fm))) && !fdd_get_turbo(drive))
ssize = 3;
else
ssize = 128 << ((uint32_t) id[3]);
current_pos = d86f_prepare_sector(drive, side, current_pos, id, dev->sects[track][side][actual_sector].data, ssize, track_gap2, track_gap3, dev->sects[track][side][actual_sector].flags);
if (sector_adjusted == 0)
d86f_initialize_last_sector_id(drive, id[0], id[1], id[2], id[3]);
if (!(dev->sects[track][side][actual_sector].flags & 0x40))
sector_adjusted++;
}
} else {
xdf_type--;
xdf_spt = xdf_physical_sectors[xdf_type][is_trackx];
for (sector = 0; sector < xdf_spt; sector++) {
xdf_sector = (side * xdf_spt) + sector;
id[0] = track;
id[1] = side;
id[2] = xdf_disk_layout[xdf_type][is_trackx][xdf_sector].id.r;
id[3] = is_trackx ? (id[2] & 7) : 2;
ordered_pos = dev->xdf_ordered_pos[id[2]][side];
fm = dev->sects[track][side][ordered_pos].fm;
if (((dev->sects[track][side][ordered_pos].flags & 0x42) || (id[3] > (dev->max_sector_size - fm))) && !fdd_get_turbo(drive))
ssize = 3;
else
ssize = 128 << ((uint32_t) id[3]);
if (is_trackx)
current_pos = d86f_prepare_sector(drive, side, xdf_trackx_spos[xdf_type][xdf_sector], id, dev->sects[track][side][ordered_pos].data, ssize, track_gap2, xdf_gap3_sizes[xdf_type][is_trackx], dev->sects[track][side][ordered_pos].flags);
else
current_pos = d86f_prepare_sector(drive, side, current_pos, id, dev->sects[track][side][ordered_pos].data, ssize, track_gap2, xdf_gap3_sizes[xdf_type][is_trackx], dev->sects[track][side][ordered_pos].flags);
if (sector_adjusted == 0)
d86f_initialize_last_sector_id(drive, id[0], id[1], id[2], id[3]);
if (!(dev->sects[track][side][ordered_pos].flags & 0x40))
sector_adjusted++;
}
}
}
}
void
td0_init(void)
{
memset(td0, 0x00, sizeof(td0));
}
void
td0_abort(int drive)
{
td0_t *dev = td0[drive];
if (dev->imagebuf)
free(dev->imagebuf);
if (dev->processed_buf)
free(dev->processed_buf);
if (dev->fp)
fclose(dev->fp);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
td0[drive] = NULL;
}
void
td0_load(int drive, char *fn)
{
td0_t *dev;
uint32_t i;
d86f_unregister(drive);
writeprot[drive] = 1;
dev = (td0_t *) malloc(sizeof(td0_t));
memset(dev, 0x00, sizeof(td0_t));
td0[drive] = dev;
dev->fp = plat_fopen(fn, "rb");
if (dev->fp == NULL) {
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
}
fwriteprot[drive] = writeprot[drive];
if (!dsk_identify(drive)) {
td0_log("TD0: Not a valid Teledisk image\n");
td0_abort(drive);
return;
} else {
td0_log("TD0: Valid Teledisk image\n");
}
/* Allocate the processing buffers. */
i = 1024UL * 1024UL * 4UL;
dev->lzw_buf = (uint8_t *) calloc(1, i);
dev->imagebuf = (uint8_t *) calloc(1, i);
dev->processed_buf = (uint8_t *) calloc(1, i);
if (!td0_initialize(drive)) {
td0_log("TD0: Failed to initialize\n");
td0_abort(drive);
return;
} else {
td0_log("TD0: Initialized successfully\n");
}
/* Attach this format to the D86F engine. */
d86f_handler[drive].disk_flags = disk_flags;
d86f_handler[drive].side_flags = side_flags;
d86f_handler[drive].writeback = null_writeback;
d86f_handler[drive].set_sector = set_sector;
d86f_handler[drive].read_data = poll_read_data;
d86f_handler[drive].write_data = null_write_data;
d86f_handler[drive].format_conditions = null_format_conditions;
d86f_handler[drive].extra_bit_cells = null_extra_bit_cells;
d86f_handler[drive].encoded_data = common_encoded_data;
d86f_handler[drive].read_revolution = common_read_revolution;
d86f_handler[drive].index_hole_pos = null_index_hole_pos;
d86f_handler[drive].get_raw_size = common_get_raw_size;
d86f_handler[drive].check_crc = 1;
d86f_set_version(drive, 0x0063);
drives[drive].seek = td0_seek;
d86f_common_handlers(drive);
}
void
td0_close(int drive)
{
td0_t *dev = td0[drive];
if (dev == NULL)
return;
d86f_unregister(drive);
if (dev->lzw_buf)
free(dev->lzw_buf);
if (dev->imagebuf)
free(dev->imagebuf);
if (dev->processed_buf)
free(dev->processed_buf);
for (uint16_t i = 0; i < 256; i++) {
for (uint8_t j = 0; j < 2; j++) {
for (uint16_t k = 0; k < 256; k++)
dev->sects[i][j][k].data = NULL;
}
}
for (uint16_t i = 0; i < 256; i++) {
memset(dev->side_flags[i], 0, 4);
memset(dev->track_in_file[i], 0, 2);
memset(dev->calculated_gap3_lengths[i], 0, 2);
for (uint8_t j = 0; j < 2; j++)
memset(dev->sects[i][j], 0, sizeof(td0_sector_t));
}
if (dev->fp != NULL)
fclose(dev->fp);
/* Release resources. */
free(dev);
td0[drive] = NULL;
}
``` | /content/code_sandbox/src/floppy/fdd_td0.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 13,949 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the 86F floppy image format (stores the
* data in the form of FM/MFM-encoded transitions) which also
* forms the core of the emulator's floppy disk emulation.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/dma.h>
#include <86box/nvr.h>
#include <86box/random.h>
#include <86box/plat.h>
#include <86box/ui.h>
#include <86box/fdd.h>
#include <86box/fdc.h>
#include <86box/fdd_86f.h>
#ifdef D86F_COMPRESS
# include <lzf.h>
#endif
/*
* Let's give this some more logic:
*
* Bits 4,3 = Read/write (0 = read, 1 = write, 2 = scan, 3 = verify)
* Bits 6,5 = Sector/track (0 = ID, 1 = sector, 2 = deleted sector, 3 = track)
* Bit 7 = State type (0 = idle states, 1 = active states)
*/
enum {
/* 0 ?? ?? ??? */
STATE_IDLE = 0x00,
STATE_SECTOR_NOT_FOUND,
/* 1 00 00 ??? */
STATE_0A_FIND_ID = 0x80, /* READ SECTOR ID */
STATE_0A_READ_ID,
/* 1 01 00 ??? */
STATE_06_FIND_ID = 0xA0, /* READ DATA */
STATE_06_READ_ID,
STATE_06_FIND_DATA,
STATE_06_READ_DATA,
/* 1 01 01 ??? */
STATE_05_FIND_ID = 0xA8, /* WRITE DATA */
STATE_05_READ_ID,
STATE_05_FIND_DATA,
STATE_05_WRITE_DATA,
/* 1 01 10 ??? */
STATE_11_FIND_ID = 0xB0, /* SCAN EQUAL,SCAN LOW/EQUAL,SCAN HIGH/EQUAL */
STATE_11_READ_ID,
STATE_11_FIND_DATA,
STATE_11_SCAN_DATA,
/* 1 01 11 ??? */
STATE_16_FIND_ID = 0xB8, /* VERIFY */
STATE_16_READ_ID,
STATE_16_FIND_DATA,
STATE_16_VERIFY_DATA,
/* 1 10 00 ??? */
STATE_0C_FIND_ID = 0xC0, /* READ DELETED DATA */
STATE_0C_READ_ID,
STATE_0C_FIND_DATA,
STATE_0C_READ_DATA,
/* 1 10 01 ??? */
STATE_09_FIND_ID = 0xC8, /* WRITE DELETED DATA */
STATE_09_READ_ID,
STATE_09_FIND_DATA,
STATE_09_WRITE_DATA,
/* 1 11 00 ??? */
STATE_02_SPIN_TO_INDEX = 0xE0, /* READ TRACK */
STATE_02_FIND_ID,
STATE_02_READ_ID,
STATE_02_FIND_DATA,
STATE_02_READ_DATA,
/* 1 11 01 ??? */
STATE_0D_SPIN_TO_INDEX = 0xE8, /* FORMAT TRACK */
STATE_0D_FORMAT_TRACK,
};
enum {
FMT_PRETRK_GAP0,
FMT_PRETRK_SYNC,
FMT_PRETRK_IAM,
FMT_PRETRK_GAP1,
FMT_SECTOR_ID_SYNC,
FMT_SECTOR_IDAM,
FMT_SECTOR_ID,
FMT_SECTOR_ID_CRC,
FMT_SECTOR_GAP2,
FMT_SECTOR_DATA_SYNC,
FMT_SECTOR_DATAAM,
FMT_SECTOR_DATA,
FMT_SECTOR_DATA_CRC,
FMT_SECTOR_GAP3,
FMT_POSTTRK_CHECK,
FMT_POSTTRK_GAP4
};
typedef struct sliding_buffer_t {
uint8_t buffer[10];
uint32_t pos;
uint32_t len;
} sliding_buffer_t;
typedef struct find_t {
uint32_t bits_obtained;
uint16_t bytes_obtained;
uint16_t sync_marks;
uint32_t sync_pos;
} find_t;
typedef struct split_byte_t {
unsigned nibble0 : 4;
unsigned nibble1 : 4;
} split_byte_t;
typedef union decoded_t {
uint8_t byte;
split_byte_t nibbles;
} decoded_t;
typedef struct sector_t {
uint8_t c;
uint8_t h;
uint8_t r;
uint8_t n;
uint8_t flags;
uint8_t pad;
uint8_t pad0;
uint8_t pad1;
void *prev;
} sector_t;
/* Disk flags:
* Bit 0 Has surface data (1 = yes, 0 = no)
* Bits 2, 1 Hole (3 = ED + 2000 kbps, 2 = ED, 1 = HD, 0 = DD)
* Bit 3 Sides (1 = 2 sides, 0 = 1 side)
* Bit 4 Write protect (1 = yes, 0 = no)
* Bits 6, 5 RPM slowdown (3 = 2%, 2 = 1.5%, 1 = 1%, 0 = 0%)
* Bit 7 Bitcell mode (1 = Extra bitcells count specified after
* disk flags, 0 = No extra bitcells)
* The maximum number of extra bitcells is 1024 (which
* after decoding translates to 64 bytes)
* Bit 8 Disk type (1 = Zoned, 0 = Fixed RPM)
* Bits 10, 9 Zone type (3 = Commodore 64 zoned, 2 = Apple zoned,
* 1 = Pre-Apple zoned #2, 0 = Pre-Apple zoned #1)
* Bit 11 Data and surface bits are stored in reverse byte endianness
* Bit 12 If bits 6, 5 are not 0, they specify % of speedup instead
* of slowdown;
* If bits 6, 5 are 0, and bit 7 is 1, the extra bitcell count
* specifies the entire bitcell count
*/
typedef struct d86f_t {
FILE *fp;
uint8_t state;
uint8_t fill;
uint8_t sector_count;
uint8_t format_state;
uint8_t error_condition;
uint8_t id_found;
uint16_t version;
uint16_t disk_flags;
uint16_t satisfying_bytes;
uint16_t turbo_pos;
uint16_t cur_track;
uint16_t track_encoded_data[2][53048];
uint16_t *track_surface_data[2];
uint16_t thin_track_encoded_data[2][2][53048];
uint16_t *thin_track_surface_data[2][2];
uint16_t side_flags[2];
uint16_t preceding_bit[2];
uint16_t current_byte[2];
uint16_t current_bit[2];
uint16_t last_word[2];
#ifdef D86F_COMPRESS
int is_compressed;
#endif
int32_t extra_bit_cells[2];
uint32_t file_size;
uint32_t index_count;
uint32_t track_pos;
uint32_t datac;
uint32_t id_pos;
uint32_t dma_over;
uint32_t index_hole_pos[2];
uint32_t track_offset[512];
sector_id_t last_sector;
sector_id_t req_sector;
find_t id_find;
find_t data_find;
crc_t calc_crc;
crc_t track_crc;
char original_file_name[2048];
uint8_t *filebuf;
uint8_t *outbuf;
sector_t *last_side_sector[2];
} d86f_t;
static const uint8_t encoded_fm[64] = {
0xaa, 0xab, 0xae, 0xaf, 0xba, 0xbb, 0xbe, 0xbf,
0xea, 0xeb, 0xee, 0xef, 0xfa, 0xfb, 0xfe, 0xff,
0xaa, 0xab, 0xae, 0xaf, 0xba, 0xbb, 0xbe, 0xbf,
0xea, 0xeb, 0xee, 0xef, 0xfa, 0xfb, 0xfe, 0xff,
0xaa, 0xab, 0xae, 0xaf, 0xba, 0xbb, 0xbe, 0xbf,
0xea, 0xeb, 0xee, 0xef, 0xfa, 0xfb, 0xfe, 0xff,
0xaa, 0xab, 0xae, 0xaf, 0xba, 0xbb, 0xbe, 0xbf,
0xea, 0xeb, 0xee, 0xef, 0xfa, 0xfb, 0xfe, 0xff
};
static const uint8_t encoded_mfm[64] = {
0xaa, 0xa9, 0xa4, 0xa5, 0x92, 0x91, 0x94, 0x95,
0x4a, 0x49, 0x44, 0x45, 0x52, 0x51, 0x54, 0x55,
0x2a, 0x29, 0x24, 0x25, 0x12, 0x11, 0x14, 0x15,
0x4a, 0x49, 0x44, 0x45, 0x52, 0x51, 0x54, 0x55,
0xaa, 0xa9, 0xa4, 0xa5, 0x92, 0x91, 0x94, 0x95,
0x4a, 0x49, 0x44, 0x45, 0x52, 0x51, 0x54, 0x55,
0x2a, 0x29, 0x24, 0x25, 0x12, 0x11, 0x14, 0x15,
0x4a, 0x49, 0x44, 0x45, 0x52, 0x51, 0x54, 0x55
};
static d86f_t *d86f[FDD_NUM];
static uint16_t CRCTable[256];
static fdc_t *d86f_fdc;
uint64_t poly = 0x42F0E1EBA9EA3693LL; /* ECMA normal */
uint16_t d86f_side_flags(int drive);
int d86f_is_mfm(int drive);
void d86f_writeback(int drive);
uint8_t d86f_poll_read_data(int drive, int side, uint16_t pos);
void d86f_poll_write_data(int drive, int side, uint16_t pos, uint8_t data);
int d86f_format_conditions(int drive);
#ifdef ENABLE_D86F_LOG
int d86f_do_log = ENABLE_D86F_LOG;
static void
d86f_log(const char *fmt, ...)
{
va_list ap;
if (d86f_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define d86f_log(fmt, ...)
#endif
static void
setup_crc(uint16_t poly)
{
int c = 256;
int bc;
uint16_t temp;
while (c--) {
temp = c << 8;
bc = 8;
while (bc--) {
if (temp & 0x8000)
temp = (temp << 1) ^ poly;
else
temp <<= 1;
CRCTable[c] = temp;
}
}
}
void
d86f_destroy_linked_lists(int drive, int side)
{
d86f_t *dev = d86f[drive];
sector_t *s;
sector_t *t;
if (dev == NULL)
return;
if (dev->last_side_sector[side]) {
s = dev->last_side_sector[side];
while (s) {
t = s->prev;
free(s);
s = NULL;
if (!t)
break;
s = t;
}
dev->last_side_sector[side] = NULL;
}
}
static int
d86f_has_surface_desc(int drive)
{
return (d86f_handler[drive].disk_flags(drive) & 1);
}
int
d86f_get_sides(int drive)
{
return ((d86f_handler[drive].disk_flags(drive) >> 3) & 1) + 1;
}
int
d86f_get_rpm_mode(int drive)
{
return (d86f_handler[drive].disk_flags(drive) & 0x60) >> 5;
}
int
d86f_get_speed_shift_dir(int drive)
{
return (d86f_handler[drive].disk_flags(drive) & 0x1000) >> 12;
}
int
d86f_reverse_bytes(int drive)
{
return (d86f_handler[drive].disk_flags(drive) & 0x800) >> 11;
}
uint16_t
d86f_disk_flags(int drive)
{
const d86f_t *dev = d86f[drive];
return dev->disk_flags;
}
uint32_t
d86f_index_hole_pos(int drive, int side)
{
const d86f_t *dev = d86f[drive];
return dev->index_hole_pos[side];
}
uint32_t
null_index_hole_pos(UNUSED(int drive), UNUSED(int side))
{
return 0;
}
uint16_t
null_disk_flags(UNUSED(int drive))
{
return 0x09;
}
uint16_t
null_side_flags(UNUSED(int drive))
{
return 0x0A;
}
void
null_writeback(UNUSED(int drive))
{
return;
}
void
null_set_sector(UNUSED(int drive), UNUSED(int side), UNUSED(uint8_t c), UNUSED(uint8_t h), UNUSED(uint8_t r), UNUSED(uint8_t n))
{
return;
}
void
null_write_data(UNUSED(int drive), UNUSED(int side), UNUSED(uint16_t pos), UNUSED(uint8_t data))
{
return;
}
int
null_format_conditions(UNUSED(int drive))
{
return 0;
}
int32_t
d86f_extra_bit_cells(int drive, int side)
{
const d86f_t *dev = d86f[drive];
return dev->extra_bit_cells[side];
}
int32_t
null_extra_bit_cells(UNUSED(int drive), UNUSED(int side))
{
return 0;
}
uint16_t *
common_encoded_data(int drive, int side)
{
d86f_t *dev = d86f[drive];
return dev->track_encoded_data[side];
}
void
common_read_revolution(UNUSED(int drive))
{
return;
}
uint16_t
d86f_side_flags(int drive)
{
const d86f_t *dev = d86f[drive];
int side;
side = fdd_get_head(drive);
return dev->side_flags[side];
}
uint16_t
d86f_track_flags(int drive)
{
uint16_t dr;
uint16_t rr;
uint16_t tf;
tf = d86f_handler[drive].side_flags(drive);
rr = tf & 0x67;
dr = fdd_get_flags(drive) & 7;
tf &= ~0x67;
switch (rr) {
case 0x02:
case 0x21:
/* 1 MB unformatted medium, treat these two as equivalent. */
switch (dr) {
case 0x06:
/* 5.25" Single-RPM HD drive, treat as 300 kbps, 360 rpm. */
tf |= 0x21;
break;
default:
/* Any other drive, treat as 250 kbps, 300 rpm. */
tf |= 0x02;
break;
}
break;
default:
tf |= rr;
break;
}
return tf;
}
uint32_t
common_get_raw_size(int drive, int side)
{
double rate = 0.0;
double rpm;
double rpm_diff;
double size = 100000.0;
int mfm;
int rm;
int ssd;
uint32_t extra_bc = 0;
mfm = d86f_is_mfm(drive);
rpm = ((d86f_track_flags(drive) & 0xE0) == 0x20) ? 360.0 : 300.0;
rpm_diff = 1.0;
rm = d86f_get_rpm_mode(drive);
ssd = d86f_get_speed_shift_dir(drive);
/* 0% speed shift and shift direction 1: special case where extra bit cells are the entire track size. */
if (!rm && ssd)
extra_bc = d86f_handler[drive].extra_bit_cells(drive, side);
if (extra_bc)
return extra_bc;
switch (rm) {
case 1:
rpm_diff = 1.01;
break;
case 2:
rpm_diff = 1.015;
break;
case 3:
rpm_diff = 1.02;
break;
default:
rpm_diff = 1.0;
break;
}
if (ssd)
rpm_diff = 1.0 / rpm_diff;
switch (d86f_track_flags(drive) & 7) {
case 0:
rate = 500.0;
break;
case 1:
rate = 300.0;
break;
case 2:
rate = 250.0;
break;
case 3:
rate = 1000.0;
break;
case 5:
rate = 2000.0;
break;
default:
rate = 250.0;
break;
}
if (!mfm)
rate /= 2.0;
size = (size / 250.0) * rate;
size = (size * 300.0) / rpm;
size *= rpm_diff;
/*
* Round down to a multiple of 16 and add the extra bit cells,
* then return.
*/
return ((((uint32_t) size) >> 4) << 4) + d86f_handler[drive].extra_bit_cells(drive, side);
}
void
d86f_set_version(int drive, uint16_t version)
{
d86f_t *dev = d86f[drive];
dev->version = version;
}
void
d86f_unregister(int drive)
{
d86f_t *dev = d86f[drive];
if (dev == NULL)
return;
d86f_handler[drive].disk_flags = null_disk_flags;
d86f_handler[drive].side_flags = null_side_flags;
d86f_handler[drive].writeback = null_writeback;
d86f_handler[drive].set_sector = null_set_sector;
d86f_handler[drive].write_data = null_write_data;
d86f_handler[drive].format_conditions = null_format_conditions;
d86f_handler[drive].extra_bit_cells = null_extra_bit_cells;
d86f_handler[drive].encoded_data = common_encoded_data;
d86f_handler[drive].read_revolution = common_read_revolution;
d86f_handler[drive].index_hole_pos = null_index_hole_pos;
d86f_handler[drive].get_raw_size = common_get_raw_size;
d86f_handler[drive].check_crc = 0;
dev->version = 0x0063; /* Proxied formats report as version 0.99. */
}
void
d86f_register_86f(int drive)
{
d86f_handler[drive].disk_flags = d86f_disk_flags;
d86f_handler[drive].side_flags = d86f_side_flags;
d86f_handler[drive].writeback = d86f_writeback;
d86f_handler[drive].set_sector = null_set_sector;
d86f_handler[drive].write_data = null_write_data;
d86f_handler[drive].format_conditions = d86f_format_conditions;
d86f_handler[drive].extra_bit_cells = d86f_extra_bit_cells;
d86f_handler[drive].encoded_data = common_encoded_data;
d86f_handler[drive].read_revolution = common_read_revolution;
d86f_handler[drive].index_hole_pos = d86f_index_hole_pos;
d86f_handler[drive].get_raw_size = common_get_raw_size;
d86f_handler[drive].check_crc = 1;
}
int
d86f_get_array_size(int drive, int side, int words)
{
int array_size;
int hole;
int rm;
int ssd;
rm = d86f_get_rpm_mode(drive);
ssd = d86f_get_speed_shift_dir(drive);
hole = (d86f_handler[drive].disk_flags(drive) & 6) >> 1;
if (!rm && ssd) /* Special case - extra bit cells size specifies entire array size. */
array_size = 0;
else
switch (hole) {
default:
case 0:
case 1:
array_size = 12500;
switch (rm) {
case 1:
array_size = ssd ? 12376 : 12625;
break;
case 2:
array_size = ssd ? 12315 : 12687;
break;
case 3:
array_size = ssd ? 12254 : 12750;
break;
default:
break;
}
break;
case 2:
array_size = 25000;
switch (rm) {
case 1:
array_size = ssd ? 24752 : 25250;
break;
case 2:
array_size = ssd ? 24630 : 25375;
break;
case 3:
array_size = ssd ? 24509 : 25500;
break;
default:
break;
}
break;
case 3:
array_size = 50000;
switch (rm) {
case 1:
array_size = ssd ? 49504 : 50500;
break;
case 2:
array_size = ssd ? 49261 : 50750;
break;
case 3:
array_size = ssd ? 49019 : 51000;
break;
default:
break;
}
break;
}
array_size <<= 4;
array_size += d86f_handler[drive].extra_bit_cells(drive, side);
if (array_size & 15)
array_size = (array_size >> 4) + 1;
else
array_size = (array_size >> 4);
if (!words)
array_size <<= 1;
return array_size;
}
int
d86f_valid_bit_rate(int drive)
{
int hole;
int rate;
rate = fdc_get_bit_rate(d86f_fdc);
hole = (d86f_handler[drive].disk_flags(drive) & 6) >> 1;
switch (hole) {
case 0: /* DD */
if (!rate && (fdd_get_flags(drive) & 0x10))
return 1;
if ((rate < 1) || (rate > 2))
return 0;
return 1;
case 1: /* HD */
if (rate != 0)
return 0;
return 1;
case 2: /* ED */
if (rate != 3)
return 0;
return 1;
case 3: /* ED with 2000 kbps support */
if (rate < 3)
return 0;
return 1;
default:
break;
}
return 0;
}
int
d86f_hole(int drive)
{
if (((d86f_handler[drive].disk_flags(drive) >> 1) & 3) == 3)
return 2;
return (d86f_handler[drive].disk_flags(drive) >> 1) & 3;
}
uint8_t
d86f_get_encoding(int drive)
{
return (d86f_track_flags(drive) & 0x18) >> 3;
}
uint64_t
d86f_byteperiod(int drive)
{
double dusec = (double) TIMER_USEC;
double p = 2.0;
switch (d86f_track_flags(drive) & 0x0f) {
case 0x02: /* 125 kbps, FM */
p = 4.0;
break;
case 0x01: /* 150 kbps, FM */
p = 20.0 / 6.0;
break;
case 0x0a: /* 250 kbps, MFM */
case 0x00: /* 250 kbps, FM */
default:
p = 2.0;
break;
case 0x09: /* 300 kbps, MFM */
p = 10.0 / 6.0;
break;
case 0x08: /* 500 kbps, MFM */
p = 1.0;
break;
case 0x0b: /* 1000 kbps, MFM */
p = 0.5;
break;
case 0x0d: /* 2000 kbps, MFM */
p = 0.25;
break;
}
return (uint64_t) (p * dusec);
}
int
d86f_is_mfm(int drive)
{
return ((d86f_track_flags(drive) & 0x18) == 0x08) ? 1 : 0;
}
uint32_t
d86f_get_data_len(int drive)
{
const d86f_t *dev = d86f[drive];
uint32_t i;
uint32_t ret = 128;
if (dev->req_sector.id.n)
ret = (uint32_t) 128 << dev->req_sector.id.n;
else if ((i = fdc_get_dtl(d86f_fdc)) < 128)
ret = i;
return ret;
}
uint32_t
d86f_has_extra_bit_cells(int drive)
{
return (d86f_handler[drive].disk_flags(drive) >> 7) & 1;
}
uint32_t
d86f_header_size(UNUSED(int drive))
{
return 8;
}
static uint16_t
d86f_encode_get_data(uint8_t dat)
{
uint16_t temp;
temp = 0;
if (dat & 0x01)
temp |= 1;
if (dat & 0x02)
temp |= 4;
if (dat & 0x04)
temp |= 16;
if (dat & 0x08)
temp |= 64;
if (dat & 0x10)
temp |= 256;
if (dat & 0x20)
temp |= 1024;
if (dat & 0x40)
temp |= 4096;
if (dat & 0x80)
temp |= 16384;
return temp;
}
static uint16_t
d86f_encode_get_clock(uint8_t dat)
{
uint16_t temp;
temp = 0;
if (dat & 0x01)
temp |= 2;
if (dat & 0x02)
temp |= 8;
if (dat & 0x40)
temp |= 32;
if (dat & 0x08)
temp |= 128;
if (dat & 0x10)
temp |= 512;
if (dat & 0x20)
temp |= 2048;
if (dat & 0x40)
temp |= 8192;
if (dat & 0x80)
temp |= 32768;
return temp;
}
int
d86f_format_conditions(int drive)
{
return d86f_valid_bit_rate(drive);
}
int
d86f_wrong_densel(int drive)
{
int is_3mode = 0;
if ((fdd_get_flags(drive) & 7) == 3)
is_3mode = 1;
switch (d86f_hole(drive)) {
default:
case 0:
if (fdd_is_dd(drive))
return 0;
if (fdd_get_densel(drive))
return 1;
else
return 0;
case 1:
if (fdd_is_dd(drive))
return 1;
if (fdd_get_densel(drive))
return 0;
else {
if (is_3mode)
return 0;
else
return 1;
}
case 2:
if (fdd_is_dd(drive) || !fdd_is_ed(drive))
return 1;
if (fdd_get_densel(drive))
return 0;
else
return 1;
}
}
int
d86f_can_format(int drive)
{
int temp;
temp = !writeprot[drive];
temp = temp && !fdc_get_swwp(d86f_fdc);
temp = temp && fdd_can_read_medium(real_drive(d86f_fdc, drive));
temp = temp && d86f_handler[drive].format_conditions(drive); /* Allows proxied formats to add their own extra conditions to formatting. */
temp = temp && !d86f_wrong_densel(drive);
return temp;
}
uint16_t
d86f_encode_byte(int drive, int sync, decoded_t b, decoded_t prev_b)
{
uint8_t encoding = d86f_get_encoding(drive);
uint8_t bits89AB = prev_b.nibbles.nibble0;
uint8_t bits7654 = b.nibbles.nibble1;
uint8_t bits3210 = b.nibbles.nibble0;
uint16_t encoded_7654;
uint16_t encoded_3210;
uint16_t result;
if (encoding > 1)
return 0xffff;
if (sync) {
result = d86f_encode_get_data(b.byte);
if (encoding) {
switch (b.byte) {
case 0xa1:
return result | d86f_encode_get_clock(0x0a);
case 0xc2:
return result | d86f_encode_get_clock(0x14);
case 0xf8:
return result | d86f_encode_get_clock(0x03);
case 0xfb:
case 0xfe:
return result | d86f_encode_get_clock(0x00);
case 0xfc:
return result | d86f_encode_get_clock(0x01);
default:
break;
}
} else {
switch (b.byte) {
case 0xf8:
case 0xfb:
case 0xfe:
return result | d86f_encode_get_clock(0xc7);
case 0xfc:
return result | d86f_encode_get_clock(0xd7);
default:
break;
}
}
}
bits3210 += ((bits7654 & 3) << 4);
bits7654 += ((bits89AB & 3) << 4);
encoded_3210 = (encoding == 1) ? encoded_mfm[bits3210] : encoded_fm[bits3210];
encoded_7654 = (encoding == 1) ? encoded_mfm[bits7654] : encoded_fm[bits7654];
result = (encoded_7654 << 8) | encoded_3210;
return result;
}
static int
d86f_get_bitcell_period(int drive)
{
double rate = 0.0;
int mfm = 0;
int tflags = 0;
double rpm = 0;
double size = 8000.0;
tflags = d86f_track_flags(drive);
mfm = (tflags & 8) ? 1 : 0;
rpm = ((tflags & 0xE0) == 0x20) ? 360.0 : 300.0;
switch (tflags & 7) {
case 0:
rate = 500.0;
break;
case 1:
rate = 300.0;
break;
case 2:
rate = 250.0;
break;
case 3:
rate = 1000.0;
break;
case 5:
rate = 2000.0;
break;
default:
break;
}
if (!mfm)
rate /= 2.0;
size = (size * 250.0) / rate;
size = (size * 300.0) / rpm;
size = (size * fdd_getrpm(real_drive(d86f_fdc, drive))) / 300.0;
return (int) size;
}
int
d86f_can_read_address(int drive)
{
int temp;
temp = (fdc_get_bitcell_period(d86f_fdc) == d86f_get_bitcell_period(drive));
temp = temp && fdd_can_read_medium(real_drive(d86f_fdc, drive));
temp = temp && (fdc_is_mfm(d86f_fdc) == d86f_is_mfm(drive));
temp = temp && (d86f_get_encoding(drive) <= 1);
return temp;
}
void
d86f_get_bit(int drive, int side)
{
d86f_t *dev = d86f[drive];
uint32_t track_word;
uint32_t track_bit;
uint16_t encoded_data;
uint16_t surface_data = 0;
uint16_t current_bit;
uint16_t surface_bit;
track_word = dev->track_pos >> 4;
/* We need to make sure we read the bits from MSB to LSB. */
track_bit = 15 - (dev->track_pos & 15);
if (d86f_reverse_bytes(drive)) {
/* Image is in reverse endianness, read the data as is. */
encoded_data = d86f_handler[drive].encoded_data(drive, side)[track_word];
} else {
/* We store the words as big endian, so we need to convert them to little endian when reading. */
encoded_data = (d86f_handler[drive].encoded_data(drive, side)[track_word] & 0xFF) << 8;
encoded_data |= (d86f_handler[drive].encoded_data(drive, side)[track_word] >> 8);
}
/* In some cases, misindentification occurs so we need to make sure the surface data array is not
not NULL. */
if (d86f_has_surface_desc(drive) && dev->track_surface_data[side]) {
if (d86f_reverse_bytes(drive)) {
surface_data = dev->track_surface_data[side][track_word] & 0xFF;
} else {
surface_data = (dev->track_surface_data[side][track_word] & 0xFF) << 8;
surface_data |= (dev->track_surface_data[side][track_word] >> 8);
}
}
current_bit = (encoded_data >> track_bit) & 1;
dev->last_word[side] <<= 1;
if (d86f_has_surface_desc(drive) && dev->track_surface_data[side]) {
surface_bit = (surface_data >> track_bit) & 1;
if (!surface_bit)
dev->last_word[side] |= current_bit;
else {
/* Bit is either 0 or 1 and is set to fuzzy, we randomly generate it. */
dev->last_word[side] |= (random_generate() & 1);
}
} else
dev->last_word[side] |= current_bit;
}
void
d86f_put_bit(int drive, int side, int bit)
{
d86f_t *dev = d86f[drive];
uint32_t track_word;
uint32_t track_bit;
uint16_t encoded_data;
uint16_t surface_data = 0;
uint16_t current_bit;
uint16_t surface_bit;
if (fdc_get_diswr(d86f_fdc))
return;
track_word = dev->track_pos >> 4;
/* We need to make sure we read the bits from MSB to LSB. */
track_bit = 15 - (dev->track_pos & 15);
if (d86f_reverse_bytes(drive)) {
/* Image is in reverse endianness, read the data as is. */
encoded_data = d86f_handler[drive].encoded_data(drive, side)[track_word];
} else {
/* We store the words as big endian, so we need to convert them to little endian when reading. */
encoded_data = (d86f_handler[drive].encoded_data(drive, side)[track_word] & 0xFF) << 8;
encoded_data |= (d86f_handler[drive].encoded_data(drive, side)[track_word] >> 8);
}
if (d86f_has_surface_desc(drive)) {
if (d86f_reverse_bytes(drive)) {
surface_data = dev->track_surface_data[side][track_word] & 0xFF;
} else {
surface_data = (dev->track_surface_data[side][track_word] & 0xFF) << 8;
surface_data |= (dev->track_surface_data[side][track_word] >> 8);
}
}
current_bit = (encoded_data >> track_bit) & 1;
dev->last_word[side] <<= 1;
if (d86f_has_surface_desc(drive)) {
surface_bit = (surface_data >> track_bit) & 1;
if (!surface_bit) {
dev->last_word[side] |= bit;
current_bit = bit;
} else {
if (current_bit) {
/* Bit is 1 and is set to fuzzy, we overwrite it with a non-fuzzy bit. */
dev->last_word[side] |= bit;
current_bit = bit;
surface_bit = 0;
}
}
surface_data &= ~(1 << track_bit);
surface_data |= (surface_bit << track_bit);
if (d86f_reverse_bytes(drive)) {
dev->track_surface_data[side][track_word] = surface_data;
} else {
dev->track_surface_data[side][track_word] = (surface_data & 0xFF) << 8;
dev->track_surface_data[side][track_word] |= (surface_data >> 8);
}
} else {
dev->last_word[side] |= bit;
current_bit = bit;
}
encoded_data &= ~(1 << track_bit);
encoded_data |= (current_bit << track_bit);
if (d86f_reverse_bytes(drive)) {
d86f_handler[drive].encoded_data(drive, side)[track_word] = encoded_data;
} else {
d86f_handler[drive].encoded_data(drive, side)[track_word] = (encoded_data & 0xFF) << 8;
d86f_handler[drive].encoded_data(drive, side)[track_word] |= (encoded_data >> 8);
}
}
static uint8_t
decodefm(UNUSED(int drive), uint16_t dat)
{
uint8_t temp = 0;
/*
* We write the encoded bytes in big endian, so we
* process the two 8-bit halves swapped here.
*/
if (dat & 0x0001)
temp |= 1;
if (dat & 0x0004)
temp |= 2;
if (dat & 0x0010)
temp |= 4;
if (dat & 0x0040)
temp |= 8;
if (dat & 0x0100)
temp |= 16;
if (dat & 0x0400)
temp |= 32;
if (dat & 0x1000)
temp |= 64;
if (dat & 0x4000)
temp |= 128;
return temp;
}
void
fdd_calccrc(uint8_t byte, crc_t *crc_var)
{
crc_var->word = (crc_var->word << 8) ^ CRCTable[(crc_var->word >> 8) ^ byte];
}
static void
d86f_calccrc(d86f_t *dev, uint8_t byte)
{
fdd_calccrc(byte, &(dev->calc_crc));
}
int
d86f_word_is_aligned(int drive, int side, uint32_t base_pos)
{
const d86f_t *dev = d86f[drive];
uint32_t adjusted_track_pos = dev->track_pos;
if (base_pos == 0xFFFFFFFF)
return 0;
/*
* This is very important, it makes sure alignment is detected
* correctly even across the index hole of a track whose length
* is not divisible by 16.
*/
if (adjusted_track_pos < base_pos)
adjusted_track_pos += d86f_handler[drive].get_raw_size(drive, side);
if ((adjusted_track_pos & 15) == (base_pos & 15))
return 1;
return 0;
}
/* State 1: Find sector ID */
void
d86f_find_address_mark_fm(int drive, int side, find_t *find, uint16_t req_am, uint16_t other_am, uint16_t wrong_am, uint16_t ignore_other_am)
{
d86f_t *dev = d86f[drive];
d86f_get_bit(drive, side);
if (dev->last_word[side] == req_am) {
dev->calc_crc.word = 0xFFFF;
fdd_calccrc(decodefm(drive, dev->last_word[side]), &(dev->calc_crc));
find->sync_marks = find->bits_obtained =
find->bytes_obtained = 0;
find->sync_pos = 0xFFFFFFFF;
dev->preceding_bit[side] = dev->last_word[side] & 1;
dev->state++;
return;
}
if (wrong_am && (dev->last_word[side] == wrong_am)) {
dev->data_find.sync_marks = dev->data_find.bits_obtained =
dev->data_find.bytes_obtained = 0;
dev->error_condition = 0;
dev->state = STATE_IDLE;
fdc_nodataam(d86f_fdc);
return;
}
if ((ignore_other_am & 2) && (dev->last_word[side] == other_am)) {
dev->calc_crc.word = 0xFFFF;
fdd_calccrc(decodefm(drive, dev->last_word[side]), &(dev->calc_crc));
find->sync_marks = find->bits_obtained = find->bytes_obtained = 0;
find->sync_pos = 0xFFFFFFFF;
if (ignore_other_am & 1) {
/* Skip mode, let's go back to finding ID. */
fdc_set_wrong_am(d86f_fdc);
dev->data_find.sync_marks = dev->data_find.bits_obtained = dev->data_find.bytes_obtained = 0;
dev->error_condition = 0;
dev->state = STATE_IDLE;
if (dev->state == STATE_02_READ_DATA)
fdc_track_finishread(d86f_fdc, dev->error_condition);
else if (dev->state == STATE_11_SCAN_DATA)
fdc_sector_finishcompare(d86f_fdc, (dev->satisfying_bytes == ((128 << ((uint32_t) dev->last_sector.id.n)) - 1)) ? 1 : 0);
else
fdc_sector_finishread(d86f_fdc);
} else {
/* Not skip mode, process the sector anyway. */
fdc_set_wrong_am(d86f_fdc);
dev->preceding_bit[side] = dev->last_word[side] & 1;
dev->state++;
}
}
}
/* When writing in FM mode, we find the beginning of the address mark by looking for 352 (22 * 16) set bits (gap fill = 0xFF, 0xFFFF FM-encoded). */
void
d86f_write_find_address_mark_fm(int drive, int side, find_t *find)
{
d86f_t *dev = d86f[drive];
d86f_get_bit(drive, side);
if (dev->last_word[side] & 1) {
find->sync_marks++;
if (find->sync_marks == 352) {
dev->calc_crc.word = 0xFFFF;
dev->preceding_bit[side] = 1;
find->sync_marks = 0;
dev->state++;
return;
}
}
/* If we hadn't found enough set bits but have found a clear bit, null the counter of set bits. */
if (!(dev->last_word[side] & 1)) {
find->sync_marks = find->bits_obtained =
find->bytes_obtained = 0;
find->sync_pos = 0xFFFFFFFF;
}
}
void
d86f_find_address_mark_mfm(int drive, int side, find_t *find, uint16_t req_am, uint16_t other_am, uint16_t wrong_am, uint16_t ignore_other_am)
{
d86f_t *dev = d86f[drive];
d86f_get_bit(drive, side);
if (dev->last_word[side] == 0x4489) {
find->sync_marks++;
find->sync_pos = dev->track_pos;
return;
}
if (wrong_am && (dev->last_word[side] == wrong_am) && (find->sync_marks >= 3)) {
dev->data_find.sync_marks = dev->data_find.bits_obtained =
dev->data_find.bytes_obtained = 0;
dev->error_condition = 0;
dev->state = STATE_IDLE;
fdc_nodataam(d86f_fdc);
return;
}
if ((dev->last_word[side] == req_am) && (find->sync_marks >= 3)) {
if (d86f_word_is_aligned(drive, side, find->sync_pos)) {
dev->calc_crc.word = 0xCDB4;
fdd_calccrc(decodefm(drive, dev->last_word[side]), &(dev->calc_crc));
find->sync_marks = find->bits_obtained = find->bytes_obtained = 0;
find->sync_pos = 0xFFFFFFFF;
dev->preceding_bit[side] = dev->last_word[side] & 1;
dev->state++;
return;
}
}
if ((ignore_other_am & 2) && (dev->last_word[side] == other_am) && (find->sync_marks >= 3)) {
if (d86f_word_is_aligned(drive, side, find->sync_pos)) {
dev->calc_crc.word = 0xCDB4;
fdd_calccrc(decodefm(drive, dev->last_word[side]), &(dev->calc_crc));
find->sync_marks = find->bits_obtained = find->bytes_obtained = 0;
find->sync_pos = 0xFFFFFFFF;
if (ignore_other_am & 1) {
/* Skip mode, let's go back to finding ID. */
fdc_set_wrong_am(d86f_fdc);
dev->data_find.sync_marks = dev->data_find.bits_obtained = dev->data_find.bytes_obtained = 0;
dev->error_condition = 0;
dev->state = STATE_IDLE;
if (dev->state == STATE_02_READ_DATA)
fdc_track_finishread(d86f_fdc, dev->error_condition);
else if (dev->state == STATE_11_SCAN_DATA)
fdc_sector_finishcompare(d86f_fdc, (dev->satisfying_bytes == ((128 << ((uint32_t) dev->last_sector.id.n)) - 1)) ? 1 : 0);
else
fdc_sector_finishread(d86f_fdc);
} else {
/* Not skip mode, process the sector anyway. */
fdc_set_wrong_am(d86f_fdc);
dev->preceding_bit[side] = dev->last_word[side] & 1;
dev->state++;
}
return;
}
}
if (dev->last_word[side] != 0x4489) {
if (d86f_word_is_aligned(drive, side, find->sync_pos)) {
find->sync_marks = find->bits_obtained = find->bytes_obtained = 0;
find->sync_pos = 0xFFFFFFFF;
}
}
}
/* When writing in MFM mode, we find the beginning of the address mark by looking for 3 0xA1 sync bytes. */
void
d86f_write_find_address_mark_mfm(int drive, int side, find_t *find)
{
d86f_t *dev = d86f[drive];
d86f_get_bit(drive, side);
if (dev->last_word[side] == 0x4489) {
find->sync_marks++;
find->sync_pos = dev->track_pos;
if (find->sync_marks == 3) {
dev->calc_crc.word = 0xCDB4;
dev->preceding_bit[side] = 1;
find->sync_marks = 0;
dev->state++;
return;
}
}
/* If we hadn't found enough address mark sync marks, null the counter. */
if (dev->last_word[side] != 0x4489) {
if (d86f_word_is_aligned(drive, side, find->sync_pos)) {
find->sync_marks = find->bits_obtained = find->bytes_obtained = 0;
find->sync_pos = 0xFFFFFFFF;
}
}
}
/* State 2: Read sector ID and CRC*/
void
d86f_read_sector_id(int drive, int side, int match)
{
d86f_t *dev = d86f[drive];
if (dev->id_find.bits_obtained) {
if (!(dev->id_find.bits_obtained & 15)) {
/* We've got a byte. */
if (dev->id_find.bytes_obtained < 4) {
dev->last_sector.byte_array[dev->id_find.bytes_obtained] =
decodefm(drive, dev->last_word[side]);
fdd_calccrc(dev->last_sector.byte_array[dev->id_find.bytes_obtained], &(dev->calc_crc));
} else if ((dev->id_find.bytes_obtained >= 4) && (dev->id_find.bytes_obtained < 6)) {
dev->track_crc.bytes[(dev->id_find.bytes_obtained & 1) ^ 1] =
decodefm(drive, dev->last_word[side]);
}
dev->id_find.bytes_obtained++;
if (dev->id_find.bytes_obtained == 6) {
/* We've got the ID. */
if ((dev->calc_crc.word != dev->track_crc.word) &&
(dev->last_sector.dword == dev->req_sector.dword)) {
dev->id_find.sync_marks = dev->id_find.bits_obtained =
dev->id_find.bytes_obtained = 0;
d86f_log("86F: ID CRC error: %04X != %04X (%08X)\n", dev->track_crc.word,
dev->calc_crc.word, dev->last_sector.dword);
if ((dev->state != STATE_02_READ_ID) && (dev->state != STATE_0A_READ_ID)) {
dev->error_condition = 0;
dev->state = STATE_IDLE;
fdc_headercrcerror(d86f_fdc);
} else if (dev->state == STATE_0A_READ_ID)
dev->state--;
else {
dev->error_condition |= 1; /* Mark that there was an ID CRC error. */
dev->state++;
}
} else if ((dev->calc_crc.word == dev->track_crc.word) && (dev->state == STATE_0A_READ_ID)) {
/* CRC is valid and this is a read sector ID command. */
dev->id_find.sync_marks = dev->id_find.bits_obtained =
dev->id_find.bytes_obtained = dev->error_condition = 0;
fdc_sectorid(d86f_fdc,
dev->last_sector.id.c, dev->last_sector.id.h,
dev->last_sector.id.r, dev->last_sector.id.n, 0, 0);
dev->state = STATE_IDLE;
} else {
/* CRC is valid. */
dev->id_find.sync_marks = dev->id_find.bits_obtained =
dev->id_find.bytes_obtained = 0;
dev->id_found |= 1;
if ((dev->last_sector.dword == dev->req_sector.dword) || !match) {
d86f_handler[drive].set_sector(drive, side,
dev->last_sector.id.c, dev->last_sector.id.h,
dev->last_sector.id.r, dev->last_sector.id.n);
if (dev->state == STATE_02_READ_ID) {
/* READ TRACK command, we need some special handling here. */
/* Code corrected: Only the C, H, and N portions of the
sector ID are compared, the R portion
(the sector number) is ignored. */
if ((dev->last_sector.id.c != fdc_get_read_track_sector(d86f_fdc).id.c) ||
(dev->last_sector.id.h != fdc_get_read_track_sector(d86f_fdc).id.h) ||
(dev->last_sector.id.n != fdc_get_read_track_sector(d86f_fdc).id.n)) {
/* Mark that the sector ID is not the one expected by the FDC. */
dev->error_condition |= 4;
/* Make sure we use the sector size from the FDC. */
dev->last_sector.id.n = fdc_get_read_track_sector(d86f_fdc).id.n;
}
/* If the two ID's are identical, then we do not need to do
anything regarding the sector size. */
}
dev->state++;
} else {
if (dev->last_sector.id.c != dev->req_sector.id.c) {
if (dev->last_sector.id.c == 0xFF) {
dev->error_condition |= 8;
} else {
dev->error_condition |= 0x10;
}
}
dev->state--;
}
}
}
}
}
d86f_get_bit(drive, side);
dev->id_find.bits_obtained++;
}
uint8_t
d86f_get_data(int drive, int base)
{
d86f_t *dev = d86f[drive];
int data;
int byte_count;
if (fdd_get_turbo(drive) && (dev->version == 0x0063))
byte_count = dev->turbo_pos;
else
byte_count = dev->data_find.bytes_obtained;
if (byte_count < (d86f_get_data_len(drive) + base)) {
data = fdc_getdata(d86f_fdc, byte_count == (d86f_get_data_len(drive) + base - 1));
if ((data & DMA_OVER) || (data == -1)) {
dev->dma_over++;
if (data == -1)
data = 0;
else
data &= 0xff;
}
} else {
data = 0;
}
return data;
}
void
d86f_compare_byte(int drive, uint8_t received_byte, uint8_t disk_byte)
{
d86f_t *dev = d86f[drive];
switch (fdc_get_compare_condition(d86f_fdc)) {
case 0: /* SCAN EQUAL */
if ((received_byte == disk_byte) || (received_byte == 0xFF))
dev->satisfying_bytes++;
break;
case 1: /* SCAN LOW OR EQUAL */
if ((received_byte <= disk_byte) || (received_byte == 0xFF))
dev->satisfying_bytes++;
break;
case 2: /* SCAN HIGH OR EQUAL */
if ((received_byte >= disk_byte) || (received_byte == 0xFF))
dev->satisfying_bytes++;
break;
default:
break;
}
}
/* State 4: Read sector data and CRC*/
void
d86f_read_sector_data(int drive, int side)
{
d86f_t *dev = d86f[drive];
int data = 0;
int recv_data = 0;
int read_status = 0;
uint32_t sector_len = dev->last_sector.id.n;
uint32_t crc_pos = 0;
sector_len = 1 << (7 + sector_len);
crc_pos = sector_len + 2;
if (dev->data_find.bits_obtained) {
if (!(dev->data_find.bits_obtained & 15)) {
/* We've got a byte. */
d86f_log("86F: We've got a byte.\n");
if (dev->data_find.bytes_obtained < sector_len) {
if (d86f_handler[drive].read_data != NULL)
data = d86f_handler[drive].read_data(drive, side, dev->data_find.bytes_obtained);
else {
#ifdef HACK_FOR_DBASE_III
if ((dev->last_sector.id.c == 39) && (dev->last_sector.id.h == 0) &&
(dev->last_sector.id.r == 5) && (dev->data_find.bytes_obtained >= 272))
data = (random_generate() & 0xff);
else
#endif
data = decodefm(drive, dev->last_word[side]);
}
if (dev->state == STATE_11_SCAN_DATA) {
/* Scan/compare command. */
recv_data = d86f_get_data(drive, 0);
d86f_compare_byte(drive, recv_data, data);
} else {
if (dev->data_find.bytes_obtained < d86f_get_data_len(drive)) {
if (dev->state != STATE_16_VERIFY_DATA) {
read_status = fdc_data(d86f_fdc, data,
dev->data_find.bytes_obtained ==
(d86f_get_data_len(drive) - 1));
if (read_status == -1)
dev->dma_over++;
}
}
}
fdd_calccrc(data, &(dev->calc_crc));
} else if (dev->data_find.bytes_obtained < crc_pos)
dev->track_crc.bytes[(dev->data_find.bytes_obtained - sector_len) ^ 1] =
decodefm(drive, dev->last_word[side]);
dev->data_find.bytes_obtained++;
if (dev->data_find.bytes_obtained == (crc_pos + fdc_get_gap(d86f_fdc))) {
/* We've got the data. */
if ((dev->calc_crc.word != dev->track_crc.word) && (dev->state != STATE_02_READ_DATA)) {
d86f_log("86F: Data CRC error: %04X != %04X (%08X)\n", dev->track_crc.word,
dev->calc_crc.word, dev->last_sector.dword);
dev->data_find.sync_marks = dev->data_find.bits_obtained =
dev->data_find.bytes_obtained = 0;
dev->error_condition = 0;
dev->state = STATE_IDLE;
fdc_datacrcerror(d86f_fdc);
} else if ((dev->calc_crc.word != dev->track_crc.word) && (dev->state == STATE_02_READ_DATA)) {
dev->data_find.sync_marks = dev->data_find.bits_obtained = dev->data_find.bytes_obtained = 0;
dev->error_condition |= 2; /* Mark that there was a data error. */
dev->state = STATE_IDLE;
fdc_track_finishread(d86f_fdc, dev->error_condition);
} else {
/* CRC is valid. */
d86f_log("86F: Data CRC OK: %04X == %04X (%08X)\n", dev->track_crc.word, dev->calc_crc.word, dev->last_sector.dword);
dev->data_find.sync_marks = dev->data_find.bits_obtained = dev->data_find.bytes_obtained = 0;
dev->error_condition = 0;
dev->state = STATE_IDLE;
if (dev->state == STATE_02_READ_DATA)
fdc_track_finishread(d86f_fdc, dev->error_condition);
else if (dev->state == STATE_11_SCAN_DATA)
fdc_sector_finishcompare(d86f_fdc, (dev->satisfying_bytes == ((128 << ((uint32_t) dev->last_sector.id.n)) - 1)) ? 1 : 0);
else
fdc_sector_finishread(d86f_fdc);
}
}
}
}
d86f_get_bit(drive, side);
dev->data_find.bits_obtained++;
}
void
d86f_write_sector_data(int drive, int side, int mfm, uint16_t am)
{
d86f_t *dev = d86f[drive];
uint16_t bit_pos;
uint16_t temp;
uint32_t sector_len = dev->last_sector.id.n;
uint32_t crc_pos = 0;
sector_len = (1 << (7 + sector_len)) + 1;
crc_pos = sector_len + 2;
if (!(dev->data_find.bits_obtained & 15)) {
if (dev->data_find.bytes_obtained < crc_pos) {
if (!dev->data_find.bytes_obtained) {
/* We're writing the address mark. */
dev->current_byte[side] = am;
} else if (dev->data_find.bytes_obtained < sector_len) {
/* We're in the data field of the sector, read byte from FDC and request new byte. */
dev->current_byte[side] = d86f_get_data(drive, 1);
if (!fdc_get_diswr(d86f_fdc))
d86f_handler[drive].write_data(drive, side, dev->data_find.bytes_obtained - 1, dev->current_byte[side]);
} else {
/* We're in the data field of the sector, use a CRC byte. */
dev->current_byte[side] = dev->calc_crc.bytes[dev->data_find.bytes_obtained & 1];
}
dev->current_bit[side] = (15 - (dev->data_find.bits_obtained & 15)) >> 1;
/* Write the bit. */
temp = (dev->current_byte[side] >> dev->current_bit[side]) & 1;
if ((!temp && !dev->preceding_bit[side]) || !mfm) {
temp |= 2;
}
/* This is an even bit, so write the clock. */
if (!dev->data_find.bytes_obtained) {
/* Address mark, write bit directly. */
d86f_put_bit(drive, side, am >> 15);
} else {
d86f_put_bit(drive, side, temp >> 1);
}
if (dev->data_find.bytes_obtained < sector_len) {
/* This is a data byte, so CRC it. */
if (!dev->data_find.bytes_obtained) {
fdd_calccrc(decodefm(drive, am), &(dev->calc_crc));
} else {
fdd_calccrc(dev->current_byte[side], &(dev->calc_crc));
}
}
}
} else {
if (dev->data_find.bytes_obtained < crc_pos) {
/* Encode the bit. */
bit_pos = 15 - (dev->data_find.bits_obtained & 15);
dev->current_bit[side] = bit_pos >> 1;
temp = (dev->current_byte[side] >> dev->current_bit[side]) & 1;
if ((!temp && !dev->preceding_bit[side]) || !mfm) {
temp |= 2;
}
if (!dev->data_find.bytes_obtained) {
/* Address mark, write directly. */
d86f_put_bit(drive, side, am >> bit_pos);
if (!(bit_pos & 1)) {
dev->preceding_bit[side] = am >> bit_pos;
}
} else {
if (bit_pos & 1) {
/* Clock bit */
d86f_put_bit(drive, side, temp >> 1);
} else {
/* Data bit */
d86f_put_bit(drive, side, temp & 1);
dev->preceding_bit[side] = temp & 1;
}
}
}
if ((dev->data_find.bits_obtained & 15) == 15) {
dev->data_find.bytes_obtained++;
if (dev->data_find.bytes_obtained == (crc_pos + fdc_get_gap(d86f_fdc))) {
/* We've written the data. */
dev->data_find.sync_marks = dev->data_find.bits_obtained = dev->data_find.bytes_obtained = 0;
dev->error_condition = 0;
dev->state = STATE_IDLE;
fdc_sector_finishread(d86f_fdc);
return;
}
}
}
dev->data_find.bits_obtained++;
}
void
d86f_advance_bit(int drive, int side)
{
d86f_t *dev = d86f[drive];
dev->track_pos++;
dev->track_pos %= d86f_handler[drive].get_raw_size(drive, side);
if (dev->track_pos == d86f_handler[drive].index_hole_pos(drive, side)) {
d86f_handler[drive].read_revolution(drive);
if (dev->state != STATE_IDLE)
dev->index_count++;
}
}
void
d86f_advance_word(int drive, int side)
{
d86f_t *dev = d86f[drive];
dev->track_pos += 16;
dev->track_pos %= d86f_handler[drive].get_raw_size(drive, side);
if ((dev->track_pos == d86f_handler[drive].index_hole_pos(drive, side)) && (dev->state != STATE_IDLE))
dev->index_count++;
}
void
d86f_spin_to_index(int drive, int side)
{
d86f_t *dev = d86f[drive];
d86f_get_bit(drive, side);
d86f_get_bit(drive, side ^ 1);
d86f_advance_bit(drive, side);
if (dev->track_pos == d86f_handler[drive].index_hole_pos(drive, side)) {
if (dev->state == STATE_0D_SPIN_TO_INDEX) {
/* When starting format, reset format state to the beginning. */
dev->preceding_bit[side] = 1;
dev->format_state = FMT_PRETRK_GAP0;
}
/* This is to make sure both READ TRACK and FORMAT TRACK command don't end prematurely. */
dev->index_count = 0;
dev->state++;
}
}
void
d86f_write_direct_common(int drive, int side, uint16_t byte, uint8_t type, uint32_t pos)
{
d86f_t *dev = d86f[drive];
uint16_t encoded_byte = 0;
uint16_t mask_data;
uint16_t mask_surface;
uint16_t mask_hole;
uint16_t mask_fuzzy;
decoded_t dbyte;
decoded_t dpbyte;
if (fdc_get_diswr(d86f_fdc))
return;
dbyte.byte = byte & 0xff;
dpbyte.byte = dev->preceding_bit[side] & 0xff;
if (type == 0) {
/* Byte write. */
encoded_byte = d86f_encode_byte(drive, 0, dbyte, dpbyte);
if (!d86f_reverse_bytes(drive)) {
mask_data = encoded_byte >> 8;
encoded_byte &= 0xFF;
encoded_byte <<= 8;
encoded_byte |= mask_data;
}
} else {
/* Word write. */
encoded_byte = byte;
if (d86f_reverse_bytes(drive)) {
mask_data = encoded_byte >> 8;
encoded_byte &= 0xFF;
encoded_byte <<= 8;
encoded_byte |= mask_data;
}
}
dev->preceding_bit[side] = encoded_byte & 1;
if (d86f_has_surface_desc(drive)) {
mask_data = dev->track_encoded_data[side][pos] ^= 0xFFFF;
mask_surface = dev->track_surface_data[side][pos];
mask_hole = (mask_surface & mask_data) ^ 0xFFFF; /* This will retain bits that are both fuzzy and 0, therefore physical holes. */
encoded_byte &= mask_hole; /* Filter out physical hole bits from the encoded data. */
mask_data ^= 0xFFFF; /* Invert back so bits 1 are 1 again. */
mask_fuzzy = (mask_surface & mask_data) ^ 0xFFFF; /* All fuzzy bits are 0. */
dev->track_surface_data[side][pos] &= mask_fuzzy; /* Remove fuzzy bits (but not hole bits) from the surface mask, making them regular again. */
}
dev->track_encoded_data[side][pos] = encoded_byte;
dev->last_word[side] = encoded_byte;
}
void
d86f_write_direct(int drive, int side, uint16_t byte, uint8_t type)
{
const d86f_t *dev = d86f[drive];
d86f_write_direct_common(drive, side, byte, type, dev->track_pos >> 4);
}
uint16_t
endian_swap(uint16_t word)
{
uint16_t temp;
temp = word & 0xff;
temp <<= 8;
temp |= (word >> 8);
return temp;
}
void
d86f_format_finish(int drive, int side, int mfm, UNUSED(uint16_t sc), uint16_t gap_fill, int do_write)
{
d86f_t *dev = d86f[drive];
if (mfm && do_write) {
if (do_write && (dev->track_pos == d86f_handler[drive].index_hole_pos(drive, side))) {
d86f_write_direct_common(drive, side, gap_fill, 0, 0);
}
}
dev->state = STATE_IDLE;
if (do_write)
d86f_handler[drive].writeback(drive);
dev->error_condition = 0;
dev->datac = 0;
fdc_sector_finishread(d86f_fdc);
}
void
d86f_format_turbo_finish(int drive, UNUSED(int side), int do_write)
{
d86f_t *dev = d86f[drive];
dev->state = STATE_IDLE;
if (do_write)
d86f_handler[drive].writeback(drive);
dev->error_condition = 0;
dev->datac = 0;
fdc_sector_finishread(d86f_fdc);
}
void
d86f_format_track(int drive, int side, int do_write)
{
d86f_t *dev = d86f[drive];
int data;
uint16_t max_len;
int mfm;
uint16_t sc = 0;
uint16_t dtl = 0;
int gap_sizes[4] = { 0, 0, 0, 0 };
int am_len = 0;
int sync_len = 0;
uint16_t iam_mfm[4] = { 0x2452, 0x2452, 0x2452, 0x5255 };
uint16_t idam_mfm[4] = { 0x8944, 0x8944, 0x8944, 0x5455 };
uint16_t dataam_mfm[4] = { 0x8944, 0x8944, 0x8944, 0x4555 };
uint16_t iam_fm = 0xFAF7;
uint16_t idam_fm = 0x7EF5;
uint16_t dataam_fm = 0x6FF5;
uint16_t gap_fill = 0x4E;
mfm = d86f_is_mfm(drive);
am_len = mfm ? 4 : 1;
gap_sizes[0] = mfm ? 80 : 40;
gap_sizes[1] = mfm ? 50 : 26;
gap_sizes[2] = fdc_get_gap2(d86f_fdc, real_drive(d86f_fdc, drive));
gap_sizes[3] = fdc_get_gap(d86f_fdc);
sync_len = mfm ? 12 : 6;
sc = fdc_get_format_sectors(d86f_fdc);
dtl = 128 << fdc_get_format_n(d86f_fdc);
gap_fill = mfm ? 0x4E : 0xFF;
switch (dev->format_state) {
case FMT_POSTTRK_GAP4:
max_len = 60000;
if (do_write)
d86f_write_direct(drive, side, gap_fill, 0);
break;
case FMT_PRETRK_GAP0:
max_len = gap_sizes[0];
if (do_write)
d86f_write_direct(drive, side, gap_fill, 0);
break;
case FMT_SECTOR_ID_SYNC:
max_len = sync_len;
if (dev->datac <= 3) {
data = fdc_getdata(d86f_fdc, 0);
if (data != -1)
data &= 0xff;
if ((data == -1) && (dev->datac < 3))
data = 0;
d86f_fdc->format_sector_id.byte_array[dev->datac] = data & 0xff;
if (dev->datac == 3)
fdc_stop_id_request(d86f_fdc);
}
fallthrough;
case FMT_PRETRK_SYNC:
case FMT_SECTOR_DATA_SYNC:
max_len = sync_len;
if (do_write)
d86f_write_direct(drive, side, 0x00, 0);
break;
case FMT_PRETRK_IAM:
max_len = am_len;
if (do_write) {
if (mfm)
d86f_write_direct(drive, side, iam_mfm[dev->datac], 1);
else
d86f_write_direct(drive, side, iam_fm, 1);
}
break;
case FMT_PRETRK_GAP1:
max_len = gap_sizes[1];
if (do_write)
d86f_write_direct(drive, side, gap_fill, 0);
break;
case FMT_SECTOR_IDAM:
max_len = am_len;
if (mfm) {
if (do_write)
d86f_write_direct(drive, side, idam_mfm[dev->datac], 1);
d86f_calccrc(dev, (dev->datac < 3) ? 0xA1 : 0xFE);
} else {
if (do_write)
d86f_write_direct(drive, side, idam_fm, 1);
d86f_calccrc(dev, 0xFE);
}
break;
case FMT_SECTOR_ID:
max_len = 4;
if (do_write) {
d86f_write_direct(drive, side, d86f_fdc->format_sector_id.byte_array[dev->datac], 0);
d86f_calccrc(dev, d86f_fdc->format_sector_id.byte_array[dev->datac]);
} else {
if (dev->datac == 3) {
d86f_handler[drive].set_sector(drive, side, d86f_fdc->format_sector_id.id.c, d86f_fdc->format_sector_id.id.h, d86f_fdc->format_sector_id.id.r, d86f_fdc->format_sector_id.id.n);
}
}
break;
case FMT_SECTOR_ID_CRC:
case FMT_SECTOR_DATA_CRC:
max_len = 2;
if (do_write)
d86f_write_direct(drive, side, dev->calc_crc.bytes[dev->datac ^ 1], 0);
break;
case FMT_SECTOR_GAP2:
max_len = gap_sizes[2];
if (do_write)
d86f_write_direct(drive, side, gap_fill, 0);
break;
case FMT_SECTOR_DATAAM:
max_len = am_len;
if (mfm) {
if (do_write)
d86f_write_direct(drive, side, dataam_mfm[dev->datac], 1);
d86f_calccrc(dev, (dev->datac < 3) ? 0xA1 : 0xFB);
} else {
if (do_write)
d86f_write_direct(drive, side, dataam_fm, 1);
d86f_calccrc(dev, 0xFB);
}
break;
case FMT_SECTOR_DATA:
max_len = dtl;
if (do_write) {
d86f_write_direct(drive, side, dev->fill, 0);
d86f_handler[drive].write_data(drive, side, dev->datac, dev->fill);
}
d86f_calccrc(dev, dev->fill);
break;
case FMT_SECTOR_GAP3:
max_len = gap_sizes[3];
if (do_write)
d86f_write_direct(drive, side, gap_fill, 0);
break;
default:
max_len = 0;
break;
}
dev->datac++;
d86f_advance_word(drive, side);
if ((dev->index_count) && ((dev->format_state < FMT_SECTOR_ID_SYNC) || (dev->format_state > FMT_SECTOR_GAP3))) {
d86f_format_finish(drive, side, mfm, sc, gap_fill, do_write);
return;
}
if (dev->datac >= max_len) {
dev->datac = 0;
dev->format_state++;
switch (dev->format_state) {
case FMT_SECTOR_ID_SYNC:
fdc_request_next_sector_id(d86f_fdc);
break;
case FMT_SECTOR_IDAM:
case FMT_SECTOR_DATAAM:
dev->calc_crc.word = 0xffff;
break;
case FMT_POSTTRK_CHECK:
if (dev->index_count) {
d86f_format_finish(drive, side, mfm, sc, gap_fill, do_write);
return;
}
dev->sector_count++;
if (dev->sector_count < sc) {
/* Sector within allotted amount, change state to SECTOR_ID_SYNC. */
dev->format_state = FMT_SECTOR_ID_SYNC;
fdc_request_next_sector_id(d86f_fdc);
} else {
dev->format_state = FMT_POSTTRK_GAP4;
dev->sector_count = 0;
}
break;
default:
break;
}
}
}
void
d86f_initialize_last_sector_id(int drive, int c, int h, int r, int n)
{
d86f_t *dev = d86f[drive];
dev->last_sector.id.c = c;
dev->last_sector.id.h = h;
dev->last_sector.id.r = r;
dev->last_sector.id.n = n;
}
static uint8_t
d86f_sector_flags(int drive, int side, uint8_t c, uint8_t h, uint8_t r, uint8_t n)
{
const d86f_t *dev = d86f[drive];
sector_t *s;
sector_t *t;
if (dev->last_side_sector[side]) {
s = dev->last_side_sector[side];
while (s) {
if ((s->c == c) && (s->h == h) && (s->r == r) && (s->n == n))
return s->flags;
if (!s->prev)
break;
t = s->prev;
s = t;
}
}
return 0x00;
}
void
d86f_turbo_read(int drive, int side)
{
d86f_t *dev = d86f[drive];
uint8_t dat = 0;
int recv_data = 0;
int read_status = 0;
uint8_t flags = d86f_sector_flags(drive, side, dev->req_sector.id.c, dev->req_sector.id.h, dev->req_sector.id.r, dev->req_sector.id.n);
if (d86f_handler[drive].read_data != NULL)
dat = d86f_handler[drive].read_data(drive, side, dev->turbo_pos);
else
dat = (random_generate() & 0xff);
if (dev->state == STATE_11_SCAN_DATA) {
/* Scan/compare command. */
recv_data = d86f_get_data(drive, 0);
d86f_compare_byte(drive, recv_data, dat);
} else {
if (dev->turbo_pos < (128UL << dev->req_sector.id.n)) {
if (dev->state != STATE_16_VERIFY_DATA) {
read_status = fdc_data(d86f_fdc, dat,
dev->turbo_pos == ((128UL << dev->req_sector.id.n) - 1));
if (read_status == -1)
dev->dma_over++;
}
}
}
dev->turbo_pos++;
if (dev->turbo_pos >= (128UL << dev->req_sector.id.n)) {
dev->data_find.sync_marks = dev->data_find.bits_obtained = dev->data_find.bytes_obtained = 0;
if ((flags & SECTOR_CRC_ERROR) && (dev->state != STATE_02_READ_DATA)) {
#ifdef ENABLE_D86F_LOG
d86f_log("86F: Data CRC error in turbo mode (%02X)\n", dev->state);
#endif
dev->error_condition = 0;
dev->state = STATE_IDLE;
fdc_datacrcerror(d86f_fdc);
} else if ((flags & SECTOR_CRC_ERROR) && (dev->state == STATE_02_READ_DATA)) {
#ifdef ENABLE_D86F_LOG
d86f_log("86F: Data CRC error in turbo mode at READ TRACK command\n");
#endif
dev->error_condition |= 2; /* Mark that there was a data error. */
dev->state = STATE_IDLE;
fdc_track_finishread(d86f_fdc, dev->error_condition);
} else {
/* CRC is valid. */
#ifdef ENABLE_D86F_LOG
d86f_log("86F: Data CRC OK in turbo mode\n");
#endif
dev->error_condition = 0;
dev->state = STATE_IDLE;
if (dev->state == STATE_11_SCAN_DATA)
fdc_sector_finishcompare(d86f_fdc, (dev->satisfying_bytes == ((128 << ((uint32_t) dev->last_sector.id.n)) - 1)) ? 1 : 0);
else
fdc_sector_finishread(d86f_fdc);
}
}
}
void
d86f_turbo_write(int drive, int side)
{
d86f_t *dev = d86f[drive];
uint8_t dat = 0;
dat = d86f_get_data(drive, 1);
d86f_handler[drive].write_data(drive, side, dev->turbo_pos, dat);
dev->turbo_pos++;
if (dev->turbo_pos >= (128 << dev->last_sector.id.n)) {
/* We've written the data. */
dev->data_find.sync_marks = dev->data_find.bits_obtained = dev->data_find.bytes_obtained = 0;
dev->error_condition = 0;
dev->state = STATE_IDLE;
d86f_handler[drive].writeback(drive);
fdc_sector_finishread(d86f_fdc);
}
}
void
d86f_turbo_format(int drive, int side, int nop)
{
d86f_t *dev = d86f[drive];
int dat;
uint16_t sc;
uint16_t dtl;
sc = fdc_get_format_sectors(d86f_fdc);
dtl = 128 << fdc_get_format_n(d86f_fdc);
if (dev->datac <= 3) {
dat = fdc_getdata(d86f_fdc, 0);
if (dat != -1)
dat &= 0xff;
if ((dat == -1) && (dev->datac < 3))
dat = 0;
d86f_fdc->format_sector_id.byte_array[dev->datac] = dat & 0xff;
if (dev->datac == 3) {
fdc_stop_id_request(d86f_fdc);
d86f_handler[drive].set_sector(drive, side, d86f_fdc->format_sector_id.id.c, d86f_fdc->format_sector_id.id.h, d86f_fdc->format_sector_id.id.r, d86f_fdc->format_sector_id.id.n);
}
} else if (dev->datac == 4) {
if (!nop) {
for (uint16_t i = 0; i < dtl; i++)
d86f_handler[drive].write_data(drive, side, i, dev->fill);
}
dev->sector_count++;
}
dev->datac++;
if (dev->datac == 6) {
dev->datac = 0;
if (dev->sector_count < sc) {
/* Sector within allotted amount. */
fdc_request_next_sector_id(d86f_fdc);
} else {
dev->state = STATE_IDLE;
d86f_format_turbo_finish(drive, side, nop);
}
}
}
int
d86f_sector_is_present(int drive, int side, uint8_t c, uint8_t h, uint8_t r, uint8_t n)
{
const d86f_t *dev = d86f[drive];
sector_t *s;
sector_t *t;
if (dev->last_side_sector[side]) {
s = dev->last_side_sector[side];
while (s) {
if ((s->c == c) && (s->h == h) && (s->r == r) && (s->n == n))
return 1;
if (!s->prev)
break;
t = s->prev;
s = t;
}
}
return 0;
}
void
d86f_turbo_poll(int drive, int side)
{
d86f_t *dev = d86f[drive];
if ((dev->state != STATE_IDLE) && (dev->state != STATE_SECTOR_NOT_FOUND) && ((dev->state & 0xF8) != 0xE8)) {
if (!d86f_can_read_address(drive)) {
dev->id_find.sync_marks = dev->id_find.bits_obtained = dev->id_find.bytes_obtained = dev->error_condition = 0;
fdc_noidam(d86f_fdc);
dev->state = STATE_IDLE;
return;
}
}
switch (dev->state) {
case STATE_0D_SPIN_TO_INDEX:
dev->sector_count = 0;
dev->datac = 5;
fallthrough;
case STATE_02_SPIN_TO_INDEX:
dev->state++;
return;
case STATE_02_FIND_ID:
if (!d86f_sector_is_present(drive, side, fdc_get_read_track_sector(d86f_fdc).id.c, fdc_get_read_track_sector(d86f_fdc).id.h,
fdc_get_read_track_sector(d86f_fdc).id.r, fdc_get_read_track_sector(d86f_fdc).id.n)) {
dev->id_find.sync_marks = dev->id_find.bits_obtained = dev->id_find.bytes_obtained = dev->error_condition = 0;
fdc_nosector(d86f_fdc);
dev->state = STATE_IDLE;
return;
}
dev->last_sector.id.c = fdc_get_read_track_sector(d86f_fdc).id.c;
dev->last_sector.id.h = fdc_get_read_track_sector(d86f_fdc).id.h;
dev->last_sector.id.r = fdc_get_read_track_sector(d86f_fdc).id.r;
dev->last_sector.id.n = fdc_get_read_track_sector(d86f_fdc).id.n;
d86f_handler[drive].set_sector(drive, side, dev->last_sector.id.c, dev->last_sector.id.h, dev->last_sector.id.r, dev->last_sector.id.n);
dev->turbo_pos = 0;
dev->state++;
return;
case STATE_05_FIND_ID:
case STATE_09_FIND_ID:
case STATE_06_FIND_ID:
case STATE_0C_FIND_ID:
case STATE_11_FIND_ID:
case STATE_16_FIND_ID:
if (!d86f_sector_is_present(drive, side, dev->req_sector.id.c, dev->req_sector.id.h, dev->req_sector.id.r, dev->req_sector.id.n)) {
dev->id_find.sync_marks = dev->id_find.bits_obtained = dev->id_find.bytes_obtained = dev->error_condition = 0;
fdc_nosector(d86f_fdc);
dev->state = STATE_IDLE;
return;
} else if (d86f_sector_flags(drive, side, dev->req_sector.id.c, dev->req_sector.id.h, dev->req_sector.id.r, dev->req_sector.id.n) & SECTOR_NO_ID) {
dev->id_find.sync_marks = dev->id_find.bits_obtained = dev->id_find.bytes_obtained = dev->error_condition = 0;
fdc_noidam(d86f_fdc);
dev->state = STATE_IDLE;
return;
}
dev->last_sector.id.c = dev->req_sector.id.c;
dev->last_sector.id.h = dev->req_sector.id.h;
dev->last_sector.id.r = dev->req_sector.id.r;
dev->last_sector.id.n = dev->req_sector.id.n;
d86f_handler[drive].set_sector(drive, side, dev->last_sector.id.c, dev->last_sector.id.h, dev->last_sector.id.r, dev->last_sector.id.n);
fallthrough;
case STATE_0A_FIND_ID:
dev->turbo_pos = 0;
dev->state++;
return;
case STATE_0A_READ_ID:
dev->id_find.sync_marks = dev->id_find.bits_obtained = dev->id_find.bytes_obtained = dev->error_condition = 0;
fdc_sectorid(d86f_fdc, dev->last_sector.id.c, dev->last_sector.id.h, dev->last_sector.id.r, dev->last_sector.id.n, 0, 0);
dev->state = STATE_IDLE;
break;
case STATE_02_READ_ID:
case STATE_05_READ_ID:
case STATE_09_READ_ID:
case STATE_06_READ_ID:
case STATE_0C_READ_ID:
case STATE_11_READ_ID:
case STATE_16_READ_ID:
dev->state++;
break;
case STATE_02_FIND_DATA:
case STATE_06_FIND_DATA:
case STATE_11_FIND_DATA:
case STATE_16_FIND_DATA:
case STATE_05_FIND_DATA:
case STATE_09_FIND_DATA:
case STATE_0C_FIND_DATA:
dev->state++;
break;
case STATE_02_READ_DATA:
case STATE_06_READ_DATA:
case STATE_0C_READ_DATA:
case STATE_11_SCAN_DATA:
case STATE_16_VERIFY_DATA:
d86f_turbo_read(drive, side);
break;
case STATE_05_WRITE_DATA:
case STATE_09_WRITE_DATA:
d86f_turbo_write(drive, side);
break;
case STATE_0D_FORMAT_TRACK:
d86f_turbo_format(drive, side, (side && (d86f_get_sides(drive) != 2)));
return;
case STATE_IDLE:
case STATE_SECTOR_NOT_FOUND:
default:
break;
}
}
void
d86f_poll(int drive)
{
d86f_t *dev = d86f[drive];
int mfm;
int side;
side = fdd_get_head(drive);
if (!fdd_is_double_sided(drive))
side = 0;
mfm = fdc_is_mfm(d86f_fdc);
if ((dev->state & 0xF8) == 0xE8) {
if (!d86f_can_format(drive))
dev->state = STATE_SECTOR_NOT_FOUND;
}
if (fdd_get_turbo(drive) && (dev->version == 0x0063)) {
d86f_turbo_poll(drive, side);
return;
}
if ((dev->state != STATE_IDLE) && (dev->state != STATE_SECTOR_NOT_FOUND) && ((dev->state & 0xF8) != 0xE8)) {
if (!d86f_can_read_address(drive))
dev->state = STATE_SECTOR_NOT_FOUND;
}
if ((dev->state != STATE_02_SPIN_TO_INDEX) && (dev->state != STATE_0D_SPIN_TO_INDEX))
d86f_get_bit(drive, side ^ 1);
switch (dev->state) {
case STATE_02_SPIN_TO_INDEX:
case STATE_0D_SPIN_TO_INDEX:
d86f_spin_to_index(drive, side);
return;
case STATE_02_FIND_ID:
case STATE_05_FIND_ID:
case STATE_09_FIND_ID:
case STATE_06_FIND_ID:
case STATE_0A_FIND_ID:
case STATE_0C_FIND_ID:
case STATE_11_FIND_ID:
case STATE_16_FIND_ID:
if (mfm)
d86f_find_address_mark_mfm(drive, side, &(dev->id_find), 0x5554, 0, 0, 0);
else
d86f_find_address_mark_fm(drive, side, &(dev->id_find), 0xF57E, 0, 0, 0);
break;
case STATE_0A_READ_ID:
case STATE_02_READ_ID:
d86f_read_sector_id(drive, side, 0);
break;
case STATE_05_READ_ID:
case STATE_09_READ_ID:
case STATE_06_READ_ID:
case STATE_0C_READ_ID:
case STATE_11_READ_ID:
case STATE_16_READ_ID:
d86f_read_sector_id(drive, side, 1);
break;
case STATE_02_FIND_DATA:
if (mfm)
d86f_find_address_mark_mfm(drive, side, &(dev->data_find), 0x5545, 0x554A, 0x5554, 2);
else
d86f_find_address_mark_fm(drive, side, &(dev->data_find), 0xF56F, 0xF56A, 0xF57E, 2);
break;
case STATE_06_FIND_DATA:
case STATE_11_FIND_DATA:
case STATE_16_FIND_DATA:
if (mfm)
d86f_find_address_mark_mfm(drive, side, &(dev->data_find), 0x5545, 0x554A, 0x5554, fdc_is_sk(d86f_fdc) | 2);
else
d86f_find_address_mark_fm(drive, side, &(dev->data_find), 0xF56F, 0xF56A, 0xF57E, fdc_is_sk(d86f_fdc) | 2);
break;
case STATE_05_FIND_DATA:
case STATE_09_FIND_DATA:
if (mfm)
d86f_write_find_address_mark_mfm(drive, side, &(dev->data_find));
else
d86f_write_find_address_mark_fm(drive, side, &(dev->data_find));
break;
case STATE_0C_FIND_DATA:
if (mfm)
d86f_find_address_mark_mfm(drive, side, &(dev->data_find), 0x554A, 0x5545, 0x5554, fdc_is_sk(d86f_fdc) | 2);
else
d86f_find_address_mark_fm(drive, side, &(dev->data_find), 0xF56A, 0xF56F, 0xF57E, fdc_is_sk(d86f_fdc) | 2);
break;
case STATE_02_READ_DATA:
case STATE_06_READ_DATA:
case STATE_0C_READ_DATA:
case STATE_11_SCAN_DATA:
case STATE_16_VERIFY_DATA:
d86f_read_sector_data(drive, side);
break;
case STATE_05_WRITE_DATA:
if (mfm)
d86f_write_sector_data(drive, side, mfm, 0x5545);
else
d86f_write_sector_data(drive, side, mfm, 0xF56F);
break;
case STATE_09_WRITE_DATA:
if (mfm)
d86f_write_sector_data(drive, side, mfm, 0x554A);
else
d86f_write_sector_data(drive, side, mfm, 0xF56A);
break;
case STATE_0D_FORMAT_TRACK:
if (!(dev->track_pos & 15))
d86f_format_track(drive, side, (!side || (d86f_get_sides(drive) == 2)) && (dev->version == D86FVER));
return;
case STATE_IDLE:
case STATE_SECTOR_NOT_FOUND:
default:
d86f_get_bit(drive, side);
break;
}
d86f_advance_bit(drive, side);
if (d86f_wrong_densel(drive) && (dev->state != STATE_IDLE)) {
dev->state = STATE_IDLE;
fdc_noidam(d86f_fdc);
return;
}
if ((dev->index_count == 2) && (dev->state != STATE_IDLE)) {
switch (dev->state) {
case STATE_0A_FIND_ID:
case STATE_SECTOR_NOT_FOUND:
dev->state = STATE_IDLE;
fdc_noidam(d86f_fdc);
break;
case STATE_02_FIND_DATA:
case STATE_06_FIND_DATA:
case STATE_11_FIND_DATA:
case STATE_16_FIND_DATA:
case STATE_05_FIND_DATA:
case STATE_09_FIND_DATA:
case STATE_0C_FIND_DATA:
dev->state = STATE_IDLE;
fdc_nodataam(d86f_fdc);
break;
case STATE_02_SPIN_TO_INDEX:
case STATE_02_READ_DATA:
case STATE_05_WRITE_DATA:
case STATE_06_READ_DATA:
case STATE_09_WRITE_DATA:
case STATE_0C_READ_DATA:
case STATE_0D_SPIN_TO_INDEX:
case STATE_0D_FORMAT_TRACK:
case STATE_11_SCAN_DATA:
case STATE_16_VERIFY_DATA:
/* In these states, we should *NEVER* care about how many index pulses there have been. */
break;
default:
dev->state = STATE_IDLE;
if (dev->id_found) {
if (dev->error_condition & 0x18) {
if ((dev->error_condition & 0x18) == 0x08)
fdc_badcylinder(d86f_fdc);
if ((dev->error_condition & 0x10) == 0x10)
fdc_wrongcylinder(d86f_fdc);
else
fdc_nosector(d86f_fdc);
} else
fdc_nosector(d86f_fdc);
} else
fdc_noidam(d86f_fdc);
break;
}
}
}
void
d86f_reset_index_hole_pos(int drive, int side)
{
d86f_t *dev = d86f[drive];
dev->index_hole_pos[side] = 0;
}
uint16_t
d86f_prepare_pretrack(int drive, int side, int iso)
{
d86f_t *dev = d86f[drive];
uint16_t pos;
int mfm;
int real_gap0_len;
int sync_len;
int real_gap1_len;
uint16_t gap_fill;
uint32_t raw_size;
uint16_t iam_fm = 0xFAF7;
uint16_t iam_mfm = 0x5255;
mfm = d86f_is_mfm(drive);
real_gap0_len = mfm ? 80 : 40;
sync_len = mfm ? 12 : 6;
real_gap1_len = mfm ? 50 : 26;
gap_fill = mfm ? 0x4E : 0xFF;
raw_size = d86f_handler[drive].get_raw_size(drive, side);
if (raw_size & 15)
raw_size = (raw_size >> 4) + 1;
else
raw_size = (raw_size >> 4);
dev->index_hole_pos[side] = 0;
d86f_destroy_linked_lists(drive, side);
for (uint32_t i = 0; i < raw_size; i++)
d86f_write_direct_common(drive, side, gap_fill, 0, i);
pos = 0;
if (!iso) {
for (int i = 0; i < real_gap0_len; i++) {
d86f_write_direct_common(drive, side, gap_fill, 0, pos);
pos = (pos + 1) % raw_size;
}
for (int i = 0; i < sync_len; i++) {
d86f_write_direct_common(drive, side, 0, 0, pos);
pos = (pos + 1) % raw_size;
}
if (mfm) {
for (uint8_t i = 0; i < 3; i++) {
d86f_write_direct_common(drive, side, 0x2452, 1, pos);
pos = (pos + 1) % raw_size;
}
}
d86f_write_direct_common(drive, side, mfm ? iam_mfm : iam_fm, 1, pos);
pos = (pos + 1) % raw_size;
}
for (int i = 0; i < real_gap1_len; i++) {
d86f_write_direct_common(drive, side, gap_fill, 0, pos);
pos = (pos + 1) % raw_size;
}
return pos;
}
uint16_t
d86f_prepare_sector(int drive, int side, int prev_pos, uint8_t *id_buf, uint8_t *data_buf, int data_len, int gap2, int gap3, int flags)
{
d86f_t *dev = d86f[drive];
uint16_t pos;
int i;
sector_t *s;
int real_gap2_len = gap2;
int real_gap3_len = gap3;
int mfm;
int sync_len;
uint16_t gap_fill;
uint32_t raw_size;
uint16_t idam_fm = 0x7EF5;
uint16_t dataam_fm = 0x6FF5;
uint16_t datadam_fm = 0x6AF5;
uint16_t idam_mfm = 0x5455;
uint16_t dataam_mfm = 0x4555;
uint16_t datadam_mfm = 0x4A55;
if (fdd_get_turbo(drive) && (dev->version == 0x0063)) {
s = (sector_t *) malloc(sizeof(sector_t));
memset(s, 0, sizeof(sector_t));
s->c = id_buf[0];
s->h = id_buf[1];
s->r = id_buf[2];
s->n = id_buf[3];
s->flags = flags;
if (dev->last_side_sector[side])
s->prev = dev->last_side_sector[side];
dev->last_side_sector[side] = s;
}
mfm = d86f_is_mfm(drive);
gap_fill = mfm ? 0x4E : 0xFF;
raw_size = d86f_handler[drive].get_raw_size(drive, side);
if (raw_size & 15)
raw_size = (raw_size >> 4) + 1;
else
raw_size = (raw_size >> 4);
pos = prev_pos;
sync_len = mfm ? 12 : 6;
if (!(flags & SECTOR_NO_ID)) {
for (i = 0; i < sync_len; i++) {
d86f_write_direct_common(drive, side, 0, 0, pos);
pos = (pos + 1) % raw_size;
}
dev->calc_crc.word = 0xffff;
if (mfm) {
for (i = 0; i < 3; i++) {
d86f_write_direct_common(drive, side, 0x8944, 1, pos);
pos = (pos + 1) % raw_size;
d86f_calccrc(dev, 0xA1);
}
}
d86f_write_direct_common(drive, side, mfm ? idam_mfm : idam_fm, 1, pos);
pos = (pos + 1) % raw_size;
d86f_calccrc(dev, 0xFE);
for (i = 0; i < 4; i++) {
d86f_write_direct_common(drive, side, id_buf[i], 0, pos);
pos = (pos + 1) % raw_size;
d86f_calccrc(dev, id_buf[i]);
}
for (i = 1; i >= 0; i--) {
d86f_write_direct_common(drive, side, dev->calc_crc.bytes[i], 0, pos);
pos = (pos + 1) % raw_size;
}
for (i = 0; i < real_gap2_len; i++) {
d86f_write_direct_common(drive, side, gap_fill, 0, pos);
pos = (pos + 1) % raw_size;
}
}
if (!(flags & SECTOR_NO_DATA)) {
for (i = 0; i < sync_len; i++) {
d86f_write_direct_common(drive, side, 0, 0, pos);
pos = (pos + 1) % raw_size;
}
dev->calc_crc.word = 0xffff;
if (mfm) {
for (i = 0; i < 3; i++) {
d86f_write_direct_common(drive, side, 0x8944, 1, pos);
pos = (pos + 1) % raw_size;
d86f_calccrc(dev, 0xA1);
}
}
d86f_write_direct_common(drive, side, mfm ? ((flags & SECTOR_DELETED_DATA) ? datadam_mfm : dataam_mfm) : ((flags & SECTOR_DELETED_DATA) ? datadam_fm : dataam_fm), 1, pos);
pos = (pos + 1) % raw_size;
d86f_calccrc(dev, (flags & SECTOR_DELETED_DATA) ? 0xF8 : 0xFB);
if (data_len > 0) {
for (i = 0; i < data_len; i++) {
d86f_write_direct_common(drive, side, data_buf[i], 0, pos);
pos = (pos + 1) % raw_size;
d86f_calccrc(dev, data_buf[i]);
}
if (!(flags & SECTOR_CRC_ERROR)) {
for (i = 1; i >= 0; i--) {
d86f_write_direct_common(drive, side, dev->calc_crc.bytes[i], 0, pos);
pos = (pos + 1) % raw_size;
}
}
for (i = 0; i < real_gap3_len; i++) {
d86f_write_direct_common(drive, side, gap_fill, 0, pos);
pos = (pos + 1) % raw_size;
}
}
}
return pos;
}
/*
* Note on handling of tracks on thick track drives:
*
* - On seek, encoded data is constructed from both (track << 1) and
* ((track << 1) + 1);
*
* - Any bits that differ are treated as thus:
* - Both are regular but contents differ -> Output is fuzzy;
* - One is regular and one is fuzzy -> Output is fuzzy;
* - Both are fuzzy -> Output is fuzzy;
* - Both are physical holes -> Output is a physical hole;
* - One is regular and one is a physical hole -> Output is fuzzy,
* the hole half is handled appropriately on writeback;
* - One is fuzzy and one is a physical hole -> Output is fuzzy,
* the hole half is handled appropriately on writeback;
* - On write back, apart from the above notes, the final two tracks
* are written;
* - Destination ALWAYS has surface data even if the image does not.
*
* In case of a thin track drive, tracks are handled normally.
*/
void
d86f_construct_encoded_buffer(int drive, int side)
{
d86f_t *dev = d86f[drive];
/* *_fuzm are fuzzy bit masks, *_holm are hole masks, dst_neim are masks is mask for bits that are neither fuzzy nor holes in both,
and src1_d and src2_d are filtered source data. */
uint16_t src1_fuzm;
uint16_t src2_fuzm;
uint16_t dst_fuzm;
uint16_t src1_holm;
uint16_t src2_holm;
uint16_t dst_holm;
uint16_t dst_neim;
uint16_t src1_d;
uint16_t src2_d;
uint32_t len;
uint16_t *dst = dev->track_encoded_data[side];
uint16_t *dst_s = dev->track_surface_data[side];
const uint16_t *src1 = dev->thin_track_encoded_data[0][side];
const uint16_t *src1_s = dev->thin_track_surface_data[0][side];
const uint16_t *src2 = dev->thin_track_encoded_data[1][side];
const uint16_t *src2_s = dev->thin_track_surface_data[1][side];
len = d86f_get_array_size(drive, side, 1);
for (uint32_t i = 0; i < len; i++) {
/* The two bits differ. */
if (d86f_has_surface_desc(drive)) {
/* Source image has surface description data, so we have some more handling to do. */
src1_fuzm = src1[i] & src1_s[i];
src2_fuzm = src2[i] & src2_s[i];
dst_fuzm = src1_fuzm | src2_fuzm; /* The bits that remain set are fuzzy in either one or
the other or both. */
src1_holm = src1[i] | (src1_s[i] ^ 0xffff);
src2_holm = src2[i] | (src2_s[i] ^ 0xffff);
dst_holm = (src1_holm & src2_holm) ^ 0xffff; /* The bits that remain set are holes in both. */
dst_neim = (dst_fuzm | dst_holm) ^ 0xffff; /* The bits that remain set are those that are neither
fuzzy nor are holes in both. */
src1_d = src1[i] & dst_neim;
src2_d = src2[i] & dst_neim;
dst_s[i] = (dst_neim ^ 0xffff); /* The set bits are those that are either fuzzy or are
holes in both. */
dst[i] = (src1_d | src2_d); /* Initial data is remaining data from Source 1 and
Source 2. */
dst[i] |= dst_fuzm; /* Add to it the fuzzy bytes (holes have surface bit set
but data bit clear). */
} else {
/* No surface data, the handling is much simpler - a simple OR. */
dst[i] = src1[i] | src2[i];
dst_s[i] = 0;
}
}
}
/* Decomposition is easier since we at most have to care about the holes. */
void
d86f_decompose_encoded_buffer(int drive, int side)
{
d86f_t *dev = d86f[drive];
uint16_t temp;
uint16_t temp2;
uint32_t len;
const uint16_t *dst = dev->track_encoded_data[side];
uint16_t *src1 = dev->thin_track_encoded_data[0][side];
uint16_t *src1_s = dev->thin_track_surface_data[0][side];
uint16_t *src2 = dev->thin_track_encoded_data[1][side];
uint16_t *src2_s = dev->thin_track_surface_data[1][side];
dst = d86f_handler[drive].encoded_data(drive, side);
len = d86f_get_array_size(drive, side, 1);
for (uint32_t i = 0; i < len; i++) {
if (d86f_has_surface_desc(drive)) {
/* Source image has surface description data, so we have some more handling to do.
We need hole masks for both buffers. Holes have data bit clear and surface bit set. */
temp = src1[i] & (src1_s[i] ^ 0xffff);
temp2 = src2[i] & (src2_s[i] ^ 0xffff);
src1[i] = dst[i] & temp;
src1_s[i] = temp ^ 0xffff;
src2[i] = dst[i] & temp2;
src2_s[i] = temp2 ^ 0xffff;
} else {
src1[i] = src2[i] = dst[i];
}
}
}
int
d86f_track_header_size(int drive)
{
int temp = 6;
if (d86f_has_extra_bit_cells(drive))
temp += 4;
return temp;
}
void
d86f_read_track(int drive, int track, int thin_track, int side, uint16_t *da, uint16_t *sa)
{
d86f_t *dev = d86f[drive];
int logical_track = 0;
int array_size = 0;
if (d86f_get_sides(drive) == 2)
logical_track = ((track + thin_track) << 1) + side;
else
logical_track = track + thin_track;
if (dev->track_offset[logical_track]) {
if (!thin_track) {
if (fseek(dev->fp, dev->track_offset[logical_track], SEEK_SET) == -1)
fatal("d86f_read_track(): Error seeking to offset dev->track_offset[logical_track]\n");
if (fread(&(dev->side_flags[side]), 1, 2, dev->fp) != 2)
fatal("d86f_read_track(): Error reading side flags\n");
if (d86f_has_extra_bit_cells(drive)) {
if (fread(&(dev->extra_bit_cells[side]), 1, 4, dev->fp) != 4)
fatal("d86f_read_track(): Error reading number of extra bit cells\n");
/* If RPM shift is 0% and direction is 1, do not adjust extra bit cells,
as that is the whole track length. */
if (d86f_get_rpm_mode(drive) || !d86f_get_speed_shift_dir(drive)) {
if (dev->extra_bit_cells[side] < -32768)
dev->extra_bit_cells[side] = -32768;
if (dev->extra_bit_cells[side] > 32768)
dev->extra_bit_cells[side] = 32768;
}
} else
dev->extra_bit_cells[side] = 0;
(void) !fread(&(dev->index_hole_pos[side]), 4, 1, dev->fp);
} else
fseek(dev->fp, dev->track_offset[logical_track] + d86f_track_header_size(drive), SEEK_SET);
array_size = d86f_get_array_size(drive, side, 0);
(void) !fread(da, 1, array_size, dev->fp);
if (d86f_has_surface_desc(drive))
(void) !fread(sa, 1, array_size, dev->fp);
} else {
if (!thin_track) {
switch ((dev->disk_flags >> 1) & 3) {
default:
case 0:
dev->side_flags[side] = 0x0A;
break;
case 1:
dev->side_flags[side] = 0x00;
break;
case 2:
case 3:
dev->side_flags[side] = 0x03;
break;
}
dev->extra_bit_cells[side] = 0;
}
}
}
void
d86f_zero_track(int drive)
{
d86f_t *dev = d86f[drive];
int sides;
sides = d86f_get_sides(drive);
for (int side = 0; side < sides; side++) {
if (d86f_has_surface_desc(drive))
memset(dev->track_surface_data[side], 0, 106096);
memset(dev->track_encoded_data[side], 0, 106096);
}
}
void
d86f_seek(int drive, int track)
{
d86f_t *dev = d86f[drive];
int sides;
int side;
int thin_track;
sides = d86f_get_sides(drive);
/* If the drive has thick tracks, shift the track number by 1. */
if (!fdd_doublestep_40(drive)) {
track <<= 1;
for (thin_track = 0; thin_track < sides; thin_track++) {
for (side = 0; side < sides; side++) {
if (d86f_has_surface_desc(drive))
memset(dev->thin_track_surface_data[thin_track][side], 0, 106096);
memset(dev->thin_track_encoded_data[thin_track][side], 0, 106096);
}
}
}
d86f_zero_track(drive);
dev->cur_track = track;
if (!fdd_doublestep_40(drive)) {
for (side = 0; side < sides; side++) {
for (thin_track = 0; thin_track < 2; thin_track++)
d86f_read_track(drive, track, thin_track, side, dev->thin_track_encoded_data[thin_track][side], dev->thin_track_surface_data[thin_track][side]);
d86f_construct_encoded_buffer(drive, side);
}
} else {
for (side = 0; side < sides; side++)
d86f_read_track(drive, track, 0, side, dev->track_encoded_data[side], dev->track_surface_data[side]);
}
dev->state = STATE_IDLE;
}
void
d86f_write_track(int drive, FILE **fp, int side, uint16_t *da0, uint16_t *sa0)
{
uint32_t array_size = d86f_get_array_size(drive, side, 0);
uint16_t side_flags = d86f_handler[drive].side_flags(drive);
uint32_t extra_bit_cells = d86f_handler[drive].extra_bit_cells(drive, side);
uint32_t index_hole_pos = d86f_handler[drive].index_hole_pos(drive, side);
fwrite(&side_flags, 1, 2, *fp);
if (d86f_has_extra_bit_cells(drive))
fwrite(&extra_bit_cells, 1, 4, *fp);
fwrite(&index_hole_pos, 1, 4, *fp);
fwrite(da0, 1, array_size, *fp);
if (d86f_has_surface_desc(drive))
fwrite(sa0, 1, array_size, *fp);
}
int
d86f_get_track_table_size(int drive)
{
int temp = 2048;
if (d86f_get_sides(drive) == 1)
temp >>= 1;
return temp;
}
void
d86f_set_cur_track(int drive, int track)
{
d86f_t *dev = d86f[drive];
dev->cur_track = track;
}
void
d86f_write_tracks(int drive, FILE **fp, uint32_t *track_table)
{
d86f_t *dev = d86f[drive];
int sides;
int fdd_side;
int side;
int logical_track = 0;
uint32_t *tbl;
tbl = dev->track_offset;
fdd_side = fdd_get_head(drive);
sides = d86f_get_sides(drive);
if (track_table != NULL)
tbl = track_table;
if (!fdd_doublestep_40(drive)) {
d86f_decompose_encoded_buffer(drive, 0);
if (sides == 2)
d86f_decompose_encoded_buffer(drive, 1);
for (uint8_t thin_track = 0; thin_track < 2; thin_track++) {
for (side = 0; side < sides; side++) {
fdd_set_head(drive, side);
if (sides == 2)
logical_track = ((dev->cur_track + thin_track) << 1) + side;
else
logical_track = dev->cur_track + thin_track;
if (track_table && !tbl[logical_track]) {
fseek(*fp, 0, SEEK_END);
tbl[logical_track] = ftell(*fp);
}
if (tbl[logical_track]) {
fseek(*fp, tbl[logical_track], SEEK_SET);
d86f_write_track(drive, fp, side, dev->thin_track_encoded_data[thin_track][side], dev->thin_track_surface_data[thin_track][side]);
}
}
}
} else {
for (side = 0; side < sides; side++) {
fdd_set_head(drive, side);
if (sides == 2)
logical_track = (dev->cur_track << 1) + side;
else
logical_track = dev->cur_track;
if (track_table && !tbl[logical_track]) {
fseek(*fp, 0, SEEK_END);
tbl[logical_track] = ftell(*fp);
}
if (tbl[logical_track]) {
if (fseek(*fp, tbl[logical_track], SEEK_SET) == -1)
fatal("d86f_write_tracks(): Error seeking to offset tbl[logical_track]\n");
d86f_write_track(drive, fp, side, d86f_handler[drive].encoded_data(drive, side), dev->track_surface_data[side]);
}
}
}
fdd_set_head(drive, fdd_side);
}
void
d86f_writeback(int drive)
{
d86f_t *dev = d86f[drive];
uint8_t header[32];
int header_size;
int size;
#ifdef D86F_COMPRESS
uint32_t len;
int ret = 0;
FILE *cf;
#endif
header_size = d86f_header_size(drive);
if (!dev->fp)
return;
/* First write the track offsets table. */
if (fseek(dev->fp, 0, SEEK_SET) == -1)
fatal("86F write_back(): Error seeking to the beginning of the file\n");
if (fread(header, 1, header_size, dev->fp) != header_size)
fatal("86F write_back(): Error reading header size\n");
if (fseek(dev->fp, 8, SEEK_SET) == -1)
fatal("86F write_back(): Error seeking\n");
size = d86f_get_track_table_size(drive);
if (fwrite(dev->track_offset, 1, size, dev->fp) != size)
fatal("86F write_back(): Error writing data\n");
d86f_write_tracks(drive, &dev->fp, NULL);
#ifdef D86F_COMPRESS
if (dev->is_compressed) {
/* The image is compressed. */
/* Open the original, compressed file. */
cf = plat_fopen(dev->original_file_name, L"wb");
/* Write the header to the original file. */
fwrite(header, 1, header_size, cf);
fseek(dev->fp, 0, SEEK_END);
len = ftell(dev->fp);
len -= header_size;
fseek(dev->fp, header_size, SEEK_SET);
/* Compress data from the temporary uncompressed file to the original, compressed file. */
dev->filebuf = (uint8_t *) malloc(len);
dev->outbuf = (uint8_t *) malloc(len - 1);
fread(dev->filebuf, 1, len, dev->fp);
ret = lzf_compress(dev->filebuf, len, dev->outbuf, len - 1);
if (!ret)
d86f_log("86F: Error compressing file\n");
fwrite(dev->outbuf, 1, ret, cf);
free(dev->outbuf);
free(dev->filebuf);
}
#endif
}
void
d86f_stop(int drive)
{
d86f_t *dev = d86f[drive];
if (dev)
dev->state = STATE_IDLE;
}
int
d86f_common_command(int drive, int sector, int track, int side, UNUSED(int rate), int sector_size)
{
d86f_t *dev = d86f[drive];
d86f_log("d86f_common_command (drive %i): fdc_period=%i img_period=%i rate=%i sector=%i track=%i side=%i\n", drive, fdc_get_bitcell_period(d86f_fdc), d86f_get_bitcell_period(drive), rate, sector, track, side);
dev->req_sector.id.c = track;
dev->req_sector.id.h = side;
if (sector == SECTOR_FIRST)
dev->req_sector.id.r = 1;
else if (sector == SECTOR_NEXT)
dev->req_sector.id.r++;
else
dev->req_sector.id.r = sector;
dev->req_sector.id.n = sector_size;
if (fdd_get_head(drive) && (d86f_get_sides(drive) == 1)) {
fdc_noidam(d86f_fdc);
dev->state = STATE_IDLE;
dev->index_count = 0;
return 0;
}
dev->id_find.sync_marks = dev->id_find.bits_obtained = dev->id_find.bytes_obtained = 0;
dev->data_find.sync_marks = dev->data_find.bits_obtained = dev->data_find.bytes_obtained = 0;
dev->index_count = dev->error_condition = dev->satisfying_bytes = 0;
dev->id_found = 0;
dev->dma_over = 0;
return 1;
}
void
d86f_readsector(int drive, int sector, int track, int side, int rate, int sector_size)
{
d86f_t *dev = d86f[drive];
int ret = 0;
ret = d86f_common_command(drive, sector, track, side, rate, sector_size);
if (!ret)
return;
if (sector == SECTOR_FIRST)
dev->state = STATE_02_SPIN_TO_INDEX;
else if (sector == SECTOR_NEXT)
dev->state = STATE_02_FIND_ID;
else
dev->state = fdc_is_deleted(d86f_fdc) ? STATE_0C_FIND_ID : (fdc_is_verify(d86f_fdc) ? STATE_16_FIND_ID : STATE_06_FIND_ID);
}
void
d86f_writesector(int drive, int sector, int track, int side, int rate, int sector_size)
{
d86f_t *dev = d86f[drive];
int ret = 0;
if (writeprot[drive]) {
fdc_writeprotect(d86f_fdc);
dev->state = STATE_IDLE;
dev->index_count = 0;
return;
}
ret = d86f_common_command(drive, sector, track, side, rate, sector_size);
if (!ret)
return;
dev->state = fdc_is_deleted(d86f_fdc) ? STATE_09_FIND_ID : STATE_05_FIND_ID;
}
void
d86f_comparesector(int drive, int sector, int track, int side, int rate, int sector_size)
{
d86f_t *dev = d86f[drive];
int ret = 0;
ret = d86f_common_command(drive, sector, track, side, rate, sector_size);
if (!ret)
return;
dev->state = STATE_11_FIND_ID;
}
void
d86f_readaddress(int drive, UNUSED(int side), UNUSED(int rate))
{
d86f_t *dev = d86f[drive];
if (fdd_get_head(drive) && (d86f_get_sides(drive) == 1)) {
fdc_noidam(d86f_fdc);
dev->state = STATE_IDLE;
dev->index_count = 0;
return;
}
dev->id_find.sync_marks = dev->id_find.bits_obtained = dev->id_find.bytes_obtained = 0;
dev->data_find.sync_marks = dev->data_find.bits_obtained = dev->data_find.bytes_obtained = 0;
dev->index_count = dev->error_condition = dev->satisfying_bytes = 0;
dev->id_found = 0;
dev->dma_over = 0;
dev->state = STATE_0A_FIND_ID;
}
void
d86f_add_track(int drive, int track, int side)
{
d86f_t *dev = d86f[drive];
uint32_t array_size;
int logical_track;
array_size = d86f_get_array_size(drive, side, 0);
if (d86f_get_sides(drive) == 2) {
logical_track = (track << 1) + side;
} else {
if (side)
return;
logical_track = track;
}
if (!dev->track_offset[logical_track]) {
/* Track is absent from the file, let's add it. */
dev->track_offset[logical_track] = dev->file_size;
dev->file_size += (array_size + 6);
if (d86f_has_extra_bit_cells(drive))
dev->file_size += 4;
if (d86f_has_surface_desc(drive))
dev->file_size += array_size;
}
}
void
d86f_common_format(int drive, int side, UNUSED(int rate), uint8_t fill, int proxy)
{
d86f_t *dev = d86f[drive];
uint16_t temp;
uint16_t temp2;
uint32_t array_size;
if (writeprot[drive]) {
fdc_writeprotect(d86f_fdc);
dev->state = STATE_IDLE;
dev->index_count = 0;
return;
}
if (!d86f_can_format(drive)) {
fdc_cannotformat(d86f_fdc);
dev->state = STATE_IDLE;
dev->index_count = 0;
return;
}
if (!side || (d86f_get_sides(drive) == 2)) {
if (!proxy) {
d86f_reset_index_hole_pos(drive, side);
if (dev->cur_track > 256) {
fdc_writeprotect(d86f_fdc);
dev->state = STATE_IDLE;
dev->index_count = 0;
return;
}
array_size = d86f_get_array_size(drive, side, 0);
if (d86f_has_surface_desc(drive)) {
/* Preserve the physical holes but get rid of the fuzzy bytes. */
for (uint32_t i = 0; i < array_size; i++) {
temp = dev->track_encoded_data[side][i] ^ 0xffff;
temp2 = dev->track_surface_data[side][i];
temp &= temp2;
dev->track_surface_data[side][i] = temp;
}
}
/* Zero the data buffer. */
memset(dev->track_encoded_data[side], 0, array_size);
d86f_add_track(drive, dev->cur_track, side);
if (!fdd_doublestep_40(drive))
d86f_add_track(drive, dev->cur_track + 1, side);
}
}
dev->fill = fill;
if (!proxy) {
dev->side_flags[side] = 0;
dev->side_flags[side] |= (fdd_getrpm(real_drive(d86f_fdc, drive)) == 360) ? 0x20 : 0;
dev->side_flags[side] |= fdc_get_bit_rate(d86f_fdc);
dev->side_flags[side] |= fdc_is_mfm(d86f_fdc) ? 8 : 0;
dev->index_hole_pos[side] = 0;
}
dev->id_find.sync_marks = dev->id_find.bits_obtained = dev->id_find.bytes_obtained = 0;
dev->data_find.sync_marks = dev->data_find.bits_obtained = dev->data_find.bytes_obtained = 0;
dev->index_count = dev->error_condition = dev->satisfying_bytes = dev->sector_count = 0;
dev->dma_over = 0;
dev->state = STATE_0D_SPIN_TO_INDEX;
}
void
d86f_proxy_format(int drive, int side, int rate, uint8_t fill)
{
d86f_common_format(drive, side, rate, fill, 1);
}
void
d86f_format(int drive, int side, int rate, uint8_t fill)
{
d86f_common_format(drive, side, rate, fill, 0);
}
void
d86f_common_handlers(int drive)
{
drives[drive].readsector = d86f_readsector;
drives[drive].writesector = d86f_writesector;
drives[drive].comparesector = d86f_comparesector;
drives[drive].readaddress = d86f_readaddress;
drives[drive].byteperiod = d86f_byteperiod;
drives[drive].poll = d86f_poll;
drives[drive].format = d86f_proxy_format;
drives[drive].stop = d86f_stop;
}
int
d86f_export(int drive, char *fn)
{
uint32_t tt[512];
d86f_t *dev = d86f[drive];
d86f_t *temp86;
FILE *fp;
int tracks = 86;
int inc = 1;
uint32_t magic = 0x46423638;
uint16_t version = 0x020C;
uint16_t disk_flags = d86f_handler[drive].disk_flags(drive);
memset(tt, 0, 512 * sizeof(uint32_t));
fp = plat_fopen(fn, "wb");
if (!fp)
return 0;
/* Allocate a temporary drive for conversion. */
temp86 = (d86f_t *) malloc(sizeof(d86f_t));
memcpy(temp86, dev, sizeof(d86f_t));
fwrite(&magic, 4, 1, fp);
fwrite(&version, 2, 1, fp);
fwrite(&disk_flags, 2, 1, fp);
fwrite(tt, 1, ((d86f_get_sides(drive) == 2) ? 2048 : 1024), fp);
/* In the case of a thick track drive, always increment track
by two, since two tracks are going to get output at once. */
if (!fdd_doublestep_40(drive))
inc = 2;
for (int i = 0; i < tracks; i += inc) {
if (inc == 2)
fdd_do_seek(drive, i >> 1);
else
fdd_do_seek(drive, i);
dev->cur_track = i;
d86f_write_tracks(drive, &fp, tt);
}
fclose(fp);
fp = plat_fopen(fn, "rb+");
fseek(fp, 8, SEEK_SET);
fwrite(tt, 1, ((d86f_get_sides(drive) == 2) ? 2048 : 1024), fp);
fclose(fp);
fdd_do_seek(drive, fdd_current_track(drive));
/* Restore the drive from temp. */
memcpy(dev, temp86, sizeof(d86f_t));
free(temp86);
return 1;
}
void
d86f_load(int drive, char *fn)
{
d86f_t *dev = d86f[drive];
uint32_t magic = 0;
uint32_t len = 0;
#ifdef D86F_COMPRESS
char temp_file_name[2048];
uint16_t temp = 0;
FILE *tf;
#endif
d86f_unregister(drive);
writeprot[drive] = 0;
dev->fp = plat_fopen(fn, "rb+");
if (!dev->fp) {
dev->fp = plat_fopen(fn, "rb");
if (!dev->fp) {
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
return;
}
writeprot[drive] = 1;
}
if (ui_writeprot[drive]) {
writeprot[drive] = 1;
}
fwriteprot[drive] = writeprot[drive];
fseek(dev->fp, 0, SEEK_END);
len = ftell(dev->fp);
fseek(dev->fp, 0, SEEK_SET);
(void) !fread(&magic, 4, 1, dev->fp);
if (len < 16) {
/* File is WAY too small, abort. */
fclose(dev->fp);
dev->fp = NULL;
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
return;
}
if ((magic != 0x46423638) && (magic != 0x66623638)) {
/* File is not of the valid format, abort. */
d86f_log("86F: Unrecognized magic bytes: %08X\n", magic);
fclose(dev->fp);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
return;
}
if (fread(&(dev->version), 1, 2, dev->fp) != 2)
fatal("d86f_load(): Error reading format version\n");
if (dev->version != D86FVER) {
/* File is not of a recognized format version, abort. */
if (dev->version == 0x0063) {
d86f_log("86F: File has emulator-internal version 0.99, this version is not valid in a file\n");
} else if ((dev->version >= 0x0100) && (dev->version < D86FVER)) {
d86f_log("86F: No longer supported development file version: %i.%02i\n", dev->version >> 8, dev->version & 0xff);
} else {
d86f_log("86F: Unrecognized file version: %i.%02i\n", dev->version >> 8, dev->version & 0xff);
}
fclose(dev->fp);
dev->fp = NULL;
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
return;
} else {
d86f_log("86F: Recognized file version: %i.%02i\n", dev->version >> 8, dev->version & 0xff);
}
(void) !fread(&(dev->disk_flags), 2, 1, dev->fp);
if (d86f_has_surface_desc(drive)) {
for (uint8_t i = 0; i < 2; i++)
dev->track_surface_data[i] = (uint16_t *) malloc(53048 * sizeof(uint16_t));
for (uint8_t i = 0; i < 2; i++) {
for (uint8_t j = 0; j < 2; j++)
dev->thin_track_surface_data[i][j] = (uint16_t *) malloc(53048 * sizeof(uint16_t));
}
}
#ifdef D86F_COMPRESS
dev->is_compressed = (magic == 0x66623638) ? 1 : 0;
if ((len < 51052) && !dev->is_compressed) {
#else
if (len < 51052) {
#endif
/* File too small, abort. */
fclose(dev->fp);
dev->fp = NULL;
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
return;
}
#ifdef DO_CRC64
fseek(dev->fp, 8, SEEK_SET);
fread(&read_crc64, 1, 8, dev->fp);
fseek(dev->fp, 0, SEEK_SET);
crc64 = 0xffffffffffffffff;
dev->filebuf = malloc(len);
fread(dev->filebuf, 1, len, dev->fp);
*(uint64_t *) &(dev->filebuf[8]) = 0xffffffffffffffff;
crc64 = (uint64_t) crc64speed(0, dev->filebuf, len);
free(dev->filebuf);
if (crc64 != read_crc64) {
d86f_log("86F: CRC64 error\n");
fclose(dev->fp);
dev->fp = NULL;
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
return;
}
#endif
#ifdef D86F_COMPRESS
if (dev->is_compressed) {
memcpy(temp_file_name, drive ? nvr_path("TEMP$$$1.$$$") : nvr_path("TEMP$$$0.$$$"), 256);
memcpy(dev->original_file_name, fn, strlen(fn) + 1);
fclose(dev->fp);
dev->fp = NULL;
dev->fp = plat_fopen(temp_file_name, "wb");
if (!dev->fp) {
d86f_log("86F: Unable to create temporary decompressed file\n");
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
return;
}
tf = plat_fopen(fn, "rb");
for (uint8_t i = 0; i < 8; i++) {
fread(&temp, 1, 2, tf);
fwrite(&temp, 1, 2, dev->fp);
}
dev->filebuf = (uint8_t *) malloc(len);
dev->outbuf = (uint8_t *) malloc(67108864);
fread(dev->filebuf, 1, len, tf);
temp = lzf_decompress(dev->filebuf, len, dev->outbuf, 67108864);
if (temp) {
fwrite(dev->outbuf, 1, temp, dev->fp);
}
free(dev->outbuf);
free(dev->filebuf);
fclose(tf);
fclose(dev->fp);
dev->fp = NULL;
if (!temp) {
d86f_log("86F: Error decompressing file\n");
plat_remove(temp_file_name);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
return;
}
dev->fp = plat_fopen(temp_file_name, "rb+");
}
#endif
if (dev->disk_flags & 0x100) {
/* Zoned disk. */
d86f_log("86F: Disk is zoned (Apple or Sony)\n");
fclose(dev->fp);
dev->fp = NULL;
#ifdef D86F_COMPRESS
if (dev->is_compressed)
plat_remove(temp_file_name);
#endif
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
return;
}
if (dev->disk_flags & 0x600) {
/* Zone type is not 0 but the disk is fixed-RPM. */
d86f_log("86F: Disk is fixed-RPM but zone type is not 0\n");
fclose(dev->fp);
dev->fp = NULL;
#ifdef D86F_COMPRESS
if (dev->is_compressed)
plat_remove(temp_file_name);
#endif
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
return;
}
if (!writeprot[drive]) {
writeprot[drive] = (dev->disk_flags & 0x10) ? 1 : 0;
fwriteprot[drive] = writeprot[drive];
}
if (writeprot[drive]) {
fclose(dev->fp);
dev->fp = NULL;
#ifdef D86F_COMPRESS
if (dev->is_compressed)
dev->fp = plat_fopen(temp_file_name, "rb");
else
#endif
dev->fp = plat_fopen(fn, "rb");
}
/* OK, set the drive data, other code needs it. */
d86f[drive] = dev;
fseek(dev->fp, 8, SEEK_SET);
(void) !fread(dev->track_offset, 1, d86f_get_track_table_size(drive), dev->fp);
if (!(dev->track_offset[0])) {
/* File has no track 0 side 0, abort. */
d86f_log("86F: No Track 0 side 0\n");
fclose(dev->fp);
dev->fp = NULL;
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
d86f[drive] = NULL;
return;
}
if ((d86f_get_sides(drive) == 2) && !(dev->track_offset[1])) {
/* File is 2-sided but has no track 0 side 1, abort. */
d86f_log("86F: No Track 0 side 1\n");
fclose(dev->fp);
dev->fp = NULL;
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
d86f[drive] = NULL;
return;
}
/* Load track 0 flags as default. */
if (fseek(dev->fp, dev->track_offset[0], SEEK_SET) == -1)
fatal("d86f_load(): Track 0: Error seeking to the beginning of the file\n");
if (fread(&(dev->side_flags[0]), 1, 2, dev->fp) != 2)
fatal("d86f_load(): Track 0: Error reading side flags\n");
if (dev->disk_flags & 0x80) {
if (fread(&(dev->extra_bit_cells[0]), 1, 4, dev->fp) != 4)
fatal("d86f_load(): Track 0: Error reading the amount of extra bit cells\n");
if ((dev->disk_flags & 0x1060) != 0x1000) {
if (dev->extra_bit_cells[0] < -32768)
dev->extra_bit_cells[0] = -32768;
if (dev->extra_bit_cells[0] > 32768)
dev->extra_bit_cells[0] = 32768;
}
} else {
dev->extra_bit_cells[0] = 0;
}
if (d86f_get_sides(drive) == 2) {
if (fseek(dev->fp, dev->track_offset[1], SEEK_SET) == -1)
fatal("d86f_load(): Track 1: Error seeking to the beginning of the file\n");
if (fread(&(dev->side_flags[1]), 1, 2, dev->fp) != 2)
fatal("d86f_load(): Track 1: Error reading side flags\n");
if (dev->disk_flags & 0x80) {
if (fread(&(dev->extra_bit_cells[1]), 1, 4, dev->fp) != 4)
fatal("d86f_load(): Track 4: Error reading the amount of extra bit cells\n");
if ((dev->disk_flags & 0x1060) != 0x1000) {
if (dev->extra_bit_cells[1] < -32768)
dev->extra_bit_cells[1] = -32768;
if (dev->extra_bit_cells[1] > 32768)
dev->extra_bit_cells[1] = 32768;
}
} else {
dev->extra_bit_cells[1] = 0;
}
} else {
switch ((dev->disk_flags >> 1) >> 3) {
default:
case 0:
dev->side_flags[1] = 0x0a;
break;
case 1:
dev->side_flags[1] = 0x00;
break;
case 2:
case 3:
dev->side_flags[1] = 0x03;
break;
}
dev->extra_bit_cells[1] = 0;
}
fseek(dev->fp, 0, SEEK_END);
dev->file_size = ftell(dev->fp);
fseek(dev->fp, 0, SEEK_SET);
d86f_register_86f(drive);
drives[drive].seek = d86f_seek;
d86f_common_handlers(drive);
drives[drive].format = d86f_format;
#ifdef D86F_COMPRESS
d86f_log("86F: Disk is %scompressed and does%s have surface description data\n",
dev->is_compressed ? "" : "not ",
d86f_has_surface_desc(drive) ? "" : " not");
#else
d86f_log("86F: Disk does%s have surface description data\n",
d86f_has_surface_desc(drive) ? "" : " not");
#endif
}
void
d86f_init(void)
{
setup_crc(0x1021);
for (uint8_t i = 0; i < FDD_NUM; i++)
d86f[i] = NULL;
}
void
d86f_set_fdc(void *fdc)
{
d86f_fdc = (fdc_t *) fdc;
}
void
d86f_close(int drive)
{
char temp_file_name[2048];
d86f_t *dev = d86f[drive];
/* Make sure the drive is alive. */
if (dev == NULL)
return;
memcpy(temp_file_name, drive ? nvr_path("TEMP$$$1.$$$") : nvr_path("TEMP$$$0.$$$"), 26);
if (d86f_has_surface_desc(drive)) {
for (uint8_t i = 0; i < 2; i++) {
if (dev->track_surface_data[i]) {
free(dev->track_surface_data[i]);
dev->track_surface_data[i] = NULL;
}
}
for (uint8_t i = 0; i < 2; i++) {
for (uint8_t j = 0; j < 2; j++) {
if (dev->thin_track_surface_data[i][j]) {
free(dev->thin_track_surface_data[i][j]);
dev->thin_track_surface_data[i][j] = NULL;
}
}
}
}
if (dev->fp) {
fclose(dev->fp);
dev->fp = NULL;
}
#ifdef D86F_COMPRESS
if (dev->is_compressed)
plat_remove(temp_file_name);
#endif
}
/* When an FDD is mounted, set up the D86F data structures. */
void
d86f_setup(int drive)
{
d86f_t *dev;
/* Allocate a drive structure. */
dev = (d86f_t *) malloc(sizeof(d86f_t));
memset(dev, 0x00, sizeof(d86f_t));
dev->state = STATE_IDLE;
dev->last_side_sector[0] = NULL;
dev->last_side_sector[1] = NULL;
/* Set the drive as active. */
d86f[drive] = dev;
}
/* If an FDD is unmounted, unlink the D86F data structures. */
void
d86f_destroy(int drive)
{
d86f_t *dev = d86f[drive];
if (dev == NULL)
return;
if (d86f_has_surface_desc(drive)) {
for (uint8_t i = 0; i < 2; i++) {
if (dev->track_surface_data[i]) {
free(dev->track_surface_data[i]);
dev->track_surface_data[i] = NULL;
}
}
for (uint8_t i = 0; i < 2; i++) {
for (uint8_t j = 0; j < 2; j++) {
if (dev->thin_track_surface_data[i][j]) {
free(dev->thin_track_surface_data[i][j]);
dev->thin_track_surface_data[i][j] = NULL;
}
}
}
}
d86f_destroy_linked_lists(drive, 0);
d86f_destroy_linked_lists(drive, 1);
free(d86f[drive]);
d86f[drive] = NULL;
d86f_handler[drive].read_data = NULL;
}
``` | /content/code_sandbox/src/floppy/fdd_86f.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 35,269 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Emulation of Sergey Kiselev's Monster Floppy Disk Controller.
*
*
*
* Authors: Jasmine Iwanek, <jasmine@iwanek.co.uk>
* Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/io.h>
#include <86box/mem.h>
#include <86box/timer.h>
#include <86box/nvr.h>
#include <86box/rom.h>
#include <86box/machine.h>
#include <86box/timer.h>
#include <86box/fdd.h>
#include <86box/fdc.h>
#include <86box/fdc_ext.h>
#include <86box/plat_unused.h>
#define BIOS_ADDR (uint32_t)(device_get_config_hex20("bios_addr") & 0x000fffff)
#define ROM_MONSTER_FDC "roms/floppy/monster-fdc/floppy_bios.bin"
typedef struct monster_fdc_t {
rom_t bios_rom;
fdc_t *fdc_pri;
fdc_t *fdc_sec;
char nvr_path[64];
} monster_fdc_t;
static void
rom_write(uint32_t addr, uint8_t val, void *priv)
{
const rom_t *rom = (rom_t *) priv;
#ifdef ROM_TRACE
if (rom->mapping.base == ROM_TRACE)
rom_log("ROM: read byte from BIOS at %06lX\n", addr);
#endif
if (addr < rom->mapping.base)
return;
if (addr >= (rom->mapping.base + rom->sz))
return;
rom->rom[(addr - rom->mapping.base) & rom->mask] = val;
}
static void
rom_writew(uint32_t addr, uint16_t val, void *priv)
{
rom_t *rom = (rom_t *) priv;
#ifdef ROM_TRACE
if (rom->mapping.base == ROM_TRACE)
rom_log("ROM: read word from BIOS at %06lX\n", addr);
#endif
if (addr < (rom->mapping.base - 1))
return;
if (addr >= (rom->mapping.base + rom->sz))
return;
*(uint16_t *) &rom->rom[(addr - rom->mapping.base) & rom->mask] = val;
}
static void
rom_writel(uint32_t addr, uint32_t val, void *priv)
{
rom_t *rom = (rom_t *) priv;
#ifdef ROM_TRACE
if (rom->mapping.base == ROM_TRACE)
rom_log("ROM: read long from BIOS at %06lX\n", addr);
#endif
if (addr < (rom->mapping.base - 3))
return;
if (addr >= (rom->mapping.base + rom->sz))
return;
*(uint32_t *) &rom->rom[(addr - rom->mapping.base) & rom->mask] = val;
}
static void
monster_fdc_close(void *priv)
{
monster_fdc_t *dev = (monster_fdc_t *) priv;
if (dev->nvr_path[0] != 0x00) {
FILE *fp = nvr_fopen(dev->nvr_path, "wb");
if (fp != NULL) {
fwrite(dev->bios_rom.rom, 1, 0x2000, fp);
fclose(fp);
}
}
free(dev);
}
static void *
monster_fdc_init(UNUSED(const device_t *info))
{
monster_fdc_t *dev;
dev = (monster_fdc_t *) calloc(1, sizeof(monster_fdc_t));
#if 0
uint8_t sec_irq = device_get_config_int("sec_irq");
uint8_t sec_dma = device_get_config_int("sec_dma");
#endif
if (BIOS_ADDR != 0)
rom_init(&dev->bios_rom, ROM_MONSTER_FDC, BIOS_ADDR, 0x2000, 0x1ffff, 0, MEM_MAPPING_EXTERNAL);
// Primary FDC
dev->fdc_pri = device_add(&fdc_at_device);
#if 0
// Secondary FDC
uint8_t sec_enabled = device_get_config_int("sec_enabled");
if (sec_enabled)
dev->fdc_sec = device_add(&fdc_at_sec_device);
fdc_set_irq(dev->fdc_sec, sec_irq);
fdc_set_dma_ch(dev->fdc_sec, sec_dma);
#endif
uint8_t rom_writes_enabled = device_get_config_int("rom_writes_enabled");
if (rom_writes_enabled) {
mem_mapping_set_write_handler(&dev->bios_rom.mapping, rom_write, rom_writew, rom_writel);
sprintf(dev->nvr_path, "monster_fdc_%i.nvr", device_get_instance());
FILE *fp = nvr_fopen(dev->nvr_path, "rb");
if (fp != NULL) {
(void) !fread(dev->bios_rom.rom, 1, 0x2000, fp);
fclose(fp);
}
}
return dev;
}
static int
monster_fdc_available(void)
{
return rom_present(ROM_MONSTER_FDC);
}
static const device_config_t monster_fdc_config[] = {
// clang-format off
#if 0
{
.name = "sec_enabled",
.description = "Enable Secondary Controller",
.type = CONFIG_BINARY,
.default_string = "",
.default_int = 0
},
{
.name = "sec_irq",
.description = "Secondary Controller IRQ",
.type = CONFIG_SELECTION,
.default_string = "",
.default_int = 6,
.file_filter = "",
.spinner = { 0 },
.selection = {
{
.description = "IRQ 2",
.value = 2
},
{
.description = "IRQ 3",
.value = 3
},
{
.description = "IRQ 4",
.value = 4
},
{
.description = "IRQ 5",
.value = 5
},
{
.description = "IRQ 6",
.value = 6
},
{
.description = "IRQ 7",
.value = 7
},
{ .description = "" }
}
},
{
.name = "sec_dma",
.description = "Secondary Controller DMA",
.type = CONFIG_SELECTION,
.default_string = "",
.default_int = 2,
.file_filter = "",
.spinner = { 0 },
.selection = {
{
.description = "DMA 1",
.value = 1
},
{
.description = "DMA 2",
.value = 2
},
{
.description = "DMA 3",
.value = 3
},
{ .description = "" }
}
},
#endif
{
.name = "bios_addr",
.description = "BIOS Address:",
.type = CONFIG_HEX20,
.default_string = "",
.default_int = 0xc8000,
.file_filter = "",
.spinner = { 0 },
.selection = {
{ .description = "Disabled", .value = 0 },
{ .description = "C000H", .value = 0xc0000 },
{ .description = "C800H", .value = 0xc8000 },
{ .description = "D000H", .value = 0xd0000 },
{ .description = "D800H", .value = 0xd8000 },
{ .description = "E000H", .value = 0xe0000 },
{ .description = "E800H", .value = 0xe8000 },
{ .description = "" }
}
},
#if 0
{
.name = "bios_size",
.description = "BIOS Size:",
.type = CONFIG_HEX20,
.default_string = "32",
.default_int = 0xc8000,
.file_filter = "",
.spinner = { 0 },
.selection = {
{ .description = "8K", .value = 8 },
{ .description = "32K", .value = 32 },
{ .description = "" }
}
},
#endif
{
.name = "rom_writes_enabled",
.description = "Enable BIOS extension ROM Writes",
.type = CONFIG_BINARY,
.default_string = "",
.default_int = 0
},
{ .name = "", .description = "", .type = CONFIG_END }
// clang-format on
};
const device_t fdc_monster_device = {
.name = "Monster FDC Floppy Drive Controller",
.internal_name = "monster_fdc",
.flags = DEVICE_ISA,
.local = 0,
.init = monster_fdc_init,
.close = monster_fdc_close,
.reset = NULL,
{ .available = monster_fdc_available },
.speed_changed = NULL,
.force_redraw = NULL,
.config = monster_fdc_config
};
``` | /content/code_sandbox/src/floppy/fdc_monster.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,124 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* FDI to raw bit stream converter
* FDI format created by Vincent "ApH" Joguin
* Tiny changes - function type fixes, multiple drives,
* addition of get_last_head and C++ callability by Thomas
* Harte.
*
*
*
* Authors: Toni Wilen, <twilen@arabuusimiehet.com>
* and Vincent Joguin,
* Thomas Harte, <T.Harte@excite.co.uk>
*
*/
#define STATIC_INLINE
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define xmalloc malloc
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <fdi2raw.h>
#include <86box/plat_unused.h>
#ifdef DEBUG
#undef DEBUG
#endif
#define VERBOSE
#undef VERBOSE
#ifdef ENABLE_FDI2RAW_LOG
int fdi2raw_do_log = ENABLE_FDI2RAW_LOG;
static void
fdi2raw_log(const char *fmt, ...)
{
va_list ap;
if (fdi2raw_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define fdi2raw_log(fmt, ...)
#endif
#ifdef ENABLE_FDI2RAW_LOG
# ifdef DEBUG
static char *
datalog(uint8_t *src, int len)
{
static char buf[1000];
static int offset;
int i = 0;
int offset2;
offset2 = offset;
buf[offset++] = '\'';
while (len--) {
sprintf(buf + offset, "%02.2X", src[i]);
offset += 2;
i++;
if (i > 10)
break;
}
buf[offset++] = '\'';
buf[offset++] = 0;
if (offset >= 900)
offset = 0;
return buf + offset2;
}
# else
static char *
datalog(uint8_t *src, int len)
{
return "";
}
# endif
static int fdi_allocated;
#endif
#ifdef DEBUG
static void
fdi_free(void *priv)
{
int size;
if (!priv)
return;
size = ((int *) priv)[-1];
fdi_allocated -= size;
write_log("%d freed (%d)\n", size, fdi_allocated);
free((int *) priv - 1);
}
static void *
fdi_malloc(int size)
{
void *priv = xmalloc(size + sizeof(int));
((int *) prv)[0] = size;
fdi_allocated += size;
write_log("%d allocated (%d)\n", size, fdi_allocated);
return (int *) priv + 1;
}
#else
# define fdi_free free
# define fdi_malloc xmalloc
#endif
#define MAX_SRC_BUFFER 4194304
#define MAX_DST_BUFFER 40000
#define MAX_MFM_SYNC_BUFFER 60000
#define MAX_TIMING_BUFFER 400000
#define MAX_TRACKS 166
struct fdi_cache {
uint32_t *avgp, *minp, *maxp;
uint8_t *idxp;
int avg_free, idx_free, min_free, max_free;
uint32_t totalavg, pulses, maxidx, indexoffset;
int weakbits;
int lowlevel;
};
struct fdi {
uint8_t *track_src_buffer;
uint8_t *track_src;
int32_t track_src_len;
uint8_t *track_dst_buffer;
uint8_t *track_dst;
uint16_t *track_dst_buffer_timing;
uint8_t track_len;
uint8_t track_type;
int current_track;
int last_track;
int last_head;
int rotation_speed;
int bit_rate;
int disk_type;
bool write_protect;
int reversed_side;
int err;
uint8_t header[2048];
int32_t track_offsets[MAX_TRACKS];
FILE *file;
int out;
int mfmsync_offset;
int *mfmsync_buffer;
/* sector described only */
int index_offset;
int encoding_type;
/* bit handling */
int nextdrop;
struct fdi_cache cache[MAX_TRACKS];
};
#define get_u32(x) ((((x)[0]) << 24) | (((x)[1]) << 16) | (((x)[2]) << 8) | ((x)[3]))
#define get_u24(x) ((((x)[0]) << 16) | (((x)[1]) << 8) | ((x)[2]))
STATIC_INLINE void
put_u32(uint8_t *d, uint32_t v)
{
d[0] = v >> 24;
d[1] = v >> 16;
d[2] = v >> 8;
d[3] = v;
}
struct node {
uint16_t v;
struct node *left;
struct node *right;
};
typedef struct node NODE;
static uint8_t temp;
static uint8_t temp2;
static uint8_t *
expand_tree(uint8_t *stream, NODE *node)
{
if (temp & temp2) {
if (node->left) {
fdi_free(node->left);
node->left = 0;
}
if (node->right) {
fdi_free(node->right);
node->right = 0;
}
temp2 >>= 1;
if (!temp2) {
temp = *stream++;
temp2 = 0x80;
}
return stream;
} else {
uint8_t *stream_temp;
temp2 >>= 1;
if (!temp2) {
temp = *stream++;
temp2 = 0x80;
}
node->left = fdi_malloc(sizeof(NODE));
memset(node->left, 0, sizeof(NODE));
stream_temp = expand_tree(stream, node->left);
node->right = fdi_malloc(sizeof(NODE));
memset(node->right, 0, sizeof(NODE));
return expand_tree(stream_temp, node->right);
}
}
static uint8_t *
values_tree8(uint8_t *stream, NODE *node)
{
if (node->left == 0) {
node->v = *stream++;
return stream;
} else {
uint8_t *stream_temp = values_tree8(stream, node->left);
return values_tree8(stream_temp, node->right);
}
}
static uint8_t *
values_tree16(uint8_t *stream, NODE *node)
{
if (node->left == 0) {
uint16_t high_8_bits = (*stream++) << 8;
node->v = high_8_bits | (*stream++);
return stream;
} else {
uint8_t *stream_temp = values_tree16(stream, node->left);
return values_tree16(stream_temp, node->right);
}
}
static void
free_nodes(NODE *node)
{
if (node) {
free_nodes(node->left);
free_nodes(node->right);
fdi_free(node);
}
}
/// @returns the 32-bit sign extended version of the 16-bit value in the low part of @c v.
static uint32_t
sign_extend16(uint32_t v)
{
if (v & 0x8000)
v |= 0xffff0000;
return v;
}
/// @returns the 32-bit sign extended version of the 8-bit value in the low part of @c v.
static uint32_t
sign_extend8(uint32_t v)
{
if (v & 0x80)
v |= 0xffffff00;
return v;
}
static void
fdi_decode(uint8_t *stream, int size, uint8_t *out)
{
uint8_t sign_extend;
uint8_t sixteen_bit;
uint8_t sub_stream_shift;
NODE root;
NODE *current_node;
memset(out, 0, size * 4);
sub_stream_shift = 1;
while (sub_stream_shift) {
/* sub-stream header decode */
sign_extend = *stream++;
sub_stream_shift = sign_extend & 0x7f;
sign_extend &= 0x80;
sixteen_bit = (*stream++) & 0x80;
/* huffman tree architecture decode */
temp = *stream++;
temp2 = 0x80;
stream = expand_tree(stream, &root);
if (temp2 == 0x80)
stream--;
/* huffman output values decode */
if (sixteen_bit)
stream = values_tree16(stream, &root);
else
stream = values_tree8(stream, &root);
/* sub-stream data decode */
temp2 = 0;
for (int i = 0; i < size; i++) {
uint32_t v;
uint8_t decode = 1;
current_node = &root;
while (decode) {
if (current_node->left == 0) {
decode = 0;
} else {
temp2 >>= 1;
if (!temp2) {
temp2 = 0x80;
temp = *stream++;
}
if (temp & temp2)
current_node = current_node->right;
else
current_node = current_node->left;
}
}
v = ((uint32_t *) out)[i];
if (sign_extend) {
if (sixteen_bit)
v |= sign_extend16(current_node->v) << sub_stream_shift;
else
v |= sign_extend8(current_node->v) << sub_stream_shift;
} else {
v |= current_node->v << sub_stream_shift;
}
((uint32_t *) out)[i] = v;
}
free_nodes(root.left);
root.left = 0;
free_nodes(root.right);
root.right = 0;
}
}
static int
decode_raw_track(FDI *fdi)
{
int size = get_u32(fdi->track_src);
memcpy(fdi->track_dst, fdi->track_src, (size + 7) >> 3);
fdi->track_src += (size + 7) >> 3;
return size;
}
/* unknown track */
static void
zxx(UNUSED(FDI *fdi))
{
fdi2raw_log("track %d: unknown track type 0x%02.2X\n", fdi->current_track, fdi->track_type);
}
/* unsupported track */
#if 0
static void zyy (FDI *fdi)
{
fdi2raw_log("track %d: unsupported track type 0x%02.2X\n", fdi->current_track, fdi->track_type);
}
#endif
/* empty track */
static void
track_empty(UNUSED(FDI *fdi))
{
return;
}
/* unknown sector described type */
static void
dxx(FDI *fdi)
{
fdi2raw_log("\ntrack %d: unknown sector described type 0x%02.2X\n", fdi->current_track, fdi->track_type);
fdi->err = 1;
}
/* add position of mfm sync bit */
static void
add_mfm_sync_bit(FDI *fdi)
{
if (fdi->nextdrop) {
fdi->nextdrop = 0;
return;
}
fdi->mfmsync_buffer[fdi->mfmsync_offset++] = fdi->out;
if (fdi->out == 0) {
fdi2raw_log("illegal position for mfm sync bit, offset=%d\n", fdi->out);
fdi->err = 1;
}
if (fdi->mfmsync_offset >= MAX_MFM_SYNC_BUFFER) {
fdi->mfmsync_offset = 0;
fdi2raw_log("mfmsync buffer overflow\n");
fdi->err = 1;
}
fdi->out++;
}
#define BIT_BYTEOFFSET ((fdi->out) >> 3)
#define BIT_BITOFFSET (7 - ((fdi->out) & 7))
/* add one bit */
static void
bit_add(FDI *fdi, int bit)
{
if (fdi->nextdrop) {
fdi->nextdrop = 0;
return;
}
fdi->track_dst[BIT_BYTEOFFSET] &= ~(1 << BIT_BITOFFSET);
if (bit)
fdi->track_dst[BIT_BYTEOFFSET] |= (1 << BIT_BITOFFSET);
fdi->out++;
if (fdi->out >= MAX_DST_BUFFER * 8) {
fdi2raw_log("destination buffer overflow\n");
fdi->err = 1;
fdi->out = 1;
}
}
/* add bit and mfm sync bit */
static void
bit_mfm_add(FDI *fdi, int bit)
{
add_mfm_sync_bit(fdi);
bit_add(fdi, bit);
}
/* remove following bit */
static void
bit_drop_next(FDI *fdi)
{
if (fdi->nextdrop > 0) {
fdi2raw_log("multiple bit_drop_next() called");
} else if (fdi->nextdrop < 0) {
fdi->nextdrop = 0;
fdi2raw_log(":DNN:");
return;
}
fdi2raw_log(":DN:");
fdi->nextdrop = 1;
}
/* ignore next bit_drop_next() */
static void
bit_dedrop(FDI *fdi)
{
if (fdi->nextdrop) {
fdi2raw_log("bit_drop_next called before bit_dedrop");
}
fdi->nextdrop = -1;
fdi2raw_log(":BDD:");
}
/* add one byte */
static void
byte_add(FDI *fdi, uint8_t v)
{
for (int8_t i = 7; i >= 0; i--)
bit_add(fdi, v & (1 << i));
}
/* add one word */
static void
word_add(FDI *fdi, uint16_t v)
{
byte_add(fdi, (uint8_t) (v >> 8));
byte_add(fdi, (uint8_t) v);
}
/* add one byte and mfm encode it */
static void
byte_mfm_add(FDI *fdi, uint8_t v)
{
for (int8_t i = 7; i >= 0; i--)
bit_mfm_add(fdi, v & (1 << i));
}
/* add multiple bytes and mfm encode them */
static void
bytes_mfm_add(FDI *fdi, uint8_t v, int len)
{
for (int i = 0; i < len; i++)
byte_mfm_add(fdi, v);
}
/* add one mfm encoded word and re-mfm encode it */
static void
word_post_mfm_add(FDI *fdi, uint16_t v)
{
for (int8_t i = 14; i >= 0; i -= 2)
bit_mfm_add(fdi, v & (1 << i));
}
/* bit 0 */
static void
s00(FDI *fdi)
{
bit_add(fdi, 0);
}
/* bit 1*/
static void
s01(FDI *fdi)
{
bit_add(fdi, 1);
}
/* 4489 */
static void
s02(FDI *fdi)
{
word_add(fdi, 0x4489);
}
/* 5224 */
static void
s03(FDI *fdi)
{
word_add(fdi, 0x5224);
}
/* mfm sync bit */
static void
s04(FDI *fdi)
{
add_mfm_sync_bit(fdi);
}
/* RLE MFM-encoded data */
static void
s08(FDI *fdi)
{
int bytes = *fdi->track_src++;
uint8_t byte = *fdi->track_src++;
if (bytes == 0)
bytes = 256;
fdi2raw_log("s08:len=%d,data=%02.2X", bytes, byte);
while (bytes--)
byte_add(fdi, byte);
}
/* RLE MFM-decoded data */
static void
s09(FDI *fdi)
{
int bytes = *fdi->track_src++;
uint8_t byte = *fdi->track_src++;
if (bytes == 0)
bytes = 256;
bit_drop_next(fdi);
fdi2raw_log("s09:len=%d,data=%02.2X", bytes, byte);
while (bytes--)
byte_mfm_add(fdi, byte);
}
/* MFM-encoded data */
static void
s0a(FDI *fdi)
{
int i;
int bits = (fdi->track_src[0] << 8) | fdi->track_src[1];
uint8_t b;
fdi->track_src += 2;
fdi2raw_log("s0a:bits=%d,data=%s", bits, datalog(fdi->track_src, (bits + 7) / 8));
while (bits >= 8) {
byte_add(fdi, *fdi->track_src++);
bits -= 8;
}
if (bits > 0) {
i = 7;
b = *fdi->track_src++;
while (bits--) {
bit_add(fdi, b & (1 << i));
i--;
}
}
}
/* MFM-encoded data */
static void
s0b(FDI *fdi)
{
int i;
int bits = ((fdi->track_src[0] << 8) | fdi->track_src[1]) + 65536;
uint8_t b;
fdi->track_src += 2;
fdi2raw_log("s0b:bits=%d,data=%s", bits, datalog(fdi->track_src, (bits + 7) / 8));
while (bits >= 8) {
byte_add(fdi, *fdi->track_src++);
bits -= 8;
}
if (bits > 0) {
i = 7;
b = *fdi->track_src++;
while (bits--) {
bit_add(fdi, b & (1 << i));
i--;
}
}
}
/* MFM-decoded data */
static void
s0c(FDI *fdi)
{
int i;
int bits = (fdi->track_src[0] << 8) | fdi->track_src[1];
uint8_t b;
fdi->track_src += 2;
bit_drop_next(fdi);
fdi2raw_log("s0c:bits=%d,data=%s", bits, datalog(fdi->track_src, (bits + 7) / 8));
while (bits >= 8) {
byte_mfm_add(fdi, *fdi->track_src++);
bits -= 8;
}
if (bits > 0) {
i = 7;
b = *fdi->track_src++;
while (bits--) {
bit_mfm_add(fdi, b & (1 << i));
i--;
}
}
}
/* MFM-decoded data */
static void
s0d(FDI *fdi)
{
int i;
int bits = ((fdi->track_src[0] << 8) | fdi->track_src[1]) + 65536;
uint8_t b;
fdi->track_src += 2;
bit_drop_next(fdi);
fdi2raw_log("s0d:bits=%d,data=%s", bits, datalog(fdi->track_src, (bits + 7) / 8));
while (bits >= 8) {
byte_mfm_add(fdi, *fdi->track_src++);
bits -= 8;
}
if (bits > 0) {
i = 7;
b = *fdi->track_src++;
while (bits--) {
bit_mfm_add(fdi, b & (1 << i));
i--;
}
}
}
/* ***** */
/* AMIGA */
/* ***** */
/* just for testing integrity of Amiga sectors */
#if 0
static void
rotateonebit (uint8_t *start, uint8_t *end, int shift)
{
if (shift == 0)
return;
while (start <= end) {
start[0] <<= shift;
start[0] |= start[1] >> (8 - shift);
start++;
}
}
static uint16_t
getmfmword (uint8_t *mbuf)
{
uint32_t v;
v = (mbuf[0] << 8) | (mbuf[1] << 0);
if (check_offset == 0)
return (uint16_t)v;
v <<= 8;
v |= mbuf[2];
v >>= check_offset;
return (uint16_t)v;
}
#define MFMMASK 0x55555555
static uint32_t
getmfmlong (uint8_t * mbuf)
{
return ((getmfmword (mbuf) << 16) | getmfmword (mbuf + 2)) & MFMMASK;
}
#endif
#if 0
static int amiga_check_track (FDI *fdi)
{
int i, j, secwritten = 0;
int fwlen = fdi->out / 8;
int length = 2 * fwlen;
int drvsec = 11;
uint32_t odd, even, chksum, id, dlong;
uint8_t *secdata;
uint8_t secbuf[544];
uint8_t bigmfmbuf[60000];
uint8_t *mbuf, *mbuf2, *mend;
char sectable[22];
uint8_t *raw = fdi->track_dst_buffer;
int slabel, off;
int ok = 1;
memset (bigmfmbuf, 0, sizeof (bigmfmbuf));
mbuf = bigmfmbuf;
check_offset = 0;
for (i = 0; i < (fdi->out + 7) / 8; i++)
*mbuf++ = raw[i];
off = fdi->out & 7;
# if 1
if (off > 0) {
mbuf--;
*mbuf &= ~((1 << (8 - off)) - 1);
}
j = 0;
while (i < (fdi->out + 7) / 8 + 600) {
*mbuf++ |= (raw[j] >> off) | ((raw[j + 1]) << (8 - off));
j++;
i++;
}
# endif
mbuf = bigmfmbuf;
memset (sectable, 0, sizeof (sectable));
mend = bigmfmbuf + length;
mend -= (4 + 16 + 8 + 512);
while (secwritten < drvsec) {
int trackoffs;
for (;;) {
rotateonebit (bigmfmbuf, mend, 1);
if (getmfmword (mbuf) == 0)
break;
if (secwritten == 10) {
mbuf[0] = 0x44;
mbuf[1] = 0x89;
}
if (check_offset > 7) {
check_offset = 0;
mbuf++;
if (mbuf >= mend || *mbuf == 0)
break;
}
if (getmfmword (mbuf) == 0x4489)
break;
}
if (mbuf >= mend || *mbuf == 0)
break;
rotateonebit (bigmfmbuf, mend, check_offset);
check_offset = 0;
while (getmfmword (mbuf) == 0x4489)
mbuf+= 1 * 2;
mbuf2 = mbuf + 8;
odd = getmfmlong (mbuf);
even = getmfmlong (mbuf + 2 * 2);
mbuf += 4 * 2;
id = (odd << 1) | even;
trackoffs = (id & 0xff00) >> 8;
if (trackoffs + 1 > drvsec) {
fdi2raw_log("illegal sector offset %d\n",trackoffs);
ok = 0;
mbuf = mbuf2;
continue;
}
if ((id >> 24) != 0xff) {
fdi2raw_log("sector %d format type %02.2X?\n", trackoffs, id >> 24);
ok = 0;
}
chksum = odd ^ even;
slabel = 0;
for (i = 0; i < 4; i++) {
odd = getmfmlong (mbuf);
even = getmfmlong (mbuf + 8 * 2);
mbuf += 2* 2;
dlong = (odd << 1) | even;
if (dlong) slabel = 1;
chksum ^= odd ^ even;
}
mbuf += 8 * 2;
odd = getmfmlong (mbuf);
even = getmfmlong (mbuf + 2 * 2);
mbuf += 4 * 2;
if (((odd << 1) | even) != chksum) {
fdi2raw_log("sector %d header crc error\n", trackoffs);
ok = 0;
mbuf = mbuf2;
continue;
}
fdi2raw_log("sector %d header crc ok\n", trackoffs);
if (((id & 0x00ff0000) >> 16) != (uint32_t)fdi->current_track) {
fdi2raw_log("illegal track number %d <> %d\n",fdi->current_track,(id & 0x00ff0000) >> 16);
ok++;
mbuf = mbuf2;
continue;
}
odd = getmfmlong (mbuf);
even = getmfmlong (mbuf + 2 * 2);
mbuf += 4 * 2;
chksum = (odd << 1) | even;
secdata = secbuf + 32;
for (i = 0; i < 128; i++) {
odd = getmfmlong (mbuf);
even = getmfmlong (mbuf + 256 * 2);
mbuf += 2 * 2;
dlong = (odd << 1) | even;
*secdata++ = (uint8_t) (dlong >> 24);
*secdata++ = (uint8_t) (dlong >> 16);
*secdata++ = (uint8_t) (dlong >> 8);
*secdata++ = (uint8_t) dlong;
chksum ^= odd ^ even;
}
mbuf += 256 * 2;
if (chksum) {
fdi2raw_log("sector %d data checksum error\n",trackoffs);
ok = 0;
} else if (sectable[trackoffs]) {
fdi2raw_log("sector %d already found?\n", trackoffs);
mbuf = mbuf2;
} else {
fdi2raw_log("sector %d ok\n",trackoffs);
if (slabel) fdi2raw_log("(non-empty sector header)\n");
sectable[trackoffs] = 1;
secwritten++;
if (trackoffs == 9)
mbuf += 0x228;
}
}
for (i = 0; i < drvsec; i++) {
if (!sectable[i]) {
fdi2raw_log("sector %d missing\n", i);
ok = 0;
}
}
return ok;
}
#endif
static void
amiga_data_raw(FDI *fdi, uint8_t *secbuf, uint8_t *crc, int len)
{
int i;
uint8_t crcbuf[4];
if (!crc) {
memset(crcbuf, 0, 4);
} else {
memcpy(crcbuf, crc, 4);
}
for (i = 0; i < 4; i++)
byte_mfm_add(fdi, crcbuf[i]);
for (i = 0; i < len; i++)
byte_mfm_add(fdi, secbuf[i]);
}
static void
amiga_data(FDI *fdi, uint8_t *secbuf)
{
uint16_t mfmbuf[4 + 512];
uint32_t dodd;
uint32_t deven;
uint32_t dck;
for (uint16_t i = 0; i < 512; i += 4) {
deven = ((secbuf[i + 0] << 24) | (secbuf[i + 1] << 16)
| (secbuf[i + 2] << 8) | (secbuf[i + 3]));
dodd = deven >> 1;
deven &= 0x55555555;
dodd &= 0x55555555;
mfmbuf[(i >> 1) + 4] = (uint16_t) (dodd >> 16);
mfmbuf[(i >> 1) + 5] = (uint16_t) dodd;
mfmbuf[(i >> 1) + 256 + 4] = (uint16_t) (deven >> 16);
mfmbuf[(i >> 1) + 256 + 5] = (uint16_t) deven;
}
dck = 0;
for (uint32_t i = 4; i < 4 + 512; i += 2)
dck ^= (mfmbuf[i] << 16) | mfmbuf[i + 1];
deven = dodd = dck;
dodd >>= 1;
deven &= 0x55555555;
dodd &= 0x55555555;
mfmbuf[0] = (uint16_t) (dodd >> 16);
mfmbuf[1] = (uint16_t) dodd;
mfmbuf[2] = (uint16_t) (deven >> 16);
mfmbuf[3] = (uint16_t) deven;
for (uint32_t i = 0; i < 4 + 512; i++)
word_post_mfm_add(fdi, mfmbuf[i]);
}
static void
amiga_sector_header(FDI *fdi, uint8_t *header, uint8_t *data, int sector, int untilgap)
{
uint8_t headerbuf[4];
uint8_t databuf[16];
uint32_t deven;
uint32_t dodd;
uint32_t hck;
uint16_t mfmbuf[24];
byte_mfm_add(fdi, 0);
byte_mfm_add(fdi, 0);
word_add(fdi, 0x4489);
word_add(fdi, 0x4489);
if (header) {
memcpy(headerbuf, header, 4);
} else {
headerbuf[0] = 0xff;
headerbuf[1] = (uint8_t) fdi->current_track;
headerbuf[2] = (uint8_t) sector;
headerbuf[3] = (uint8_t) untilgap;
}
if (data)
memcpy(databuf, data, 16);
else
memset(databuf, 0, 16);
deven = ((headerbuf[0] << 24) | (headerbuf[1] << 16)
| (headerbuf[2] << 8) | (headerbuf[3]));
dodd = deven >> 1;
deven &= 0x55555555;
dodd &= 0x55555555;
mfmbuf[0] = (uint16_t) (dodd >> 16);
mfmbuf[1] = (uint16_t) dodd;
mfmbuf[2] = (uint16_t) (deven >> 16);
mfmbuf[3] = (uint16_t) deven;
for (uint8_t i = 0; i < 16; i += 4) {
deven = ((databuf[i] << 24) | (databuf[i + 1] << 16)
| (databuf[i + 2] << 8) | (databuf[i + 3]));
dodd = deven >> 1;
deven &= 0x55555555;
dodd &= 0x55555555;
mfmbuf[(i >> 1) + 0 + 4] = (uint16_t) (dodd >> 16);
mfmbuf[(i >> 1) + 0 + 5] = (uint16_t) dodd;
mfmbuf[(i >> 1) + 8 + 4] = (uint16_t) (deven >> 16);
mfmbuf[(i >> 1) + 8 + 5] = (uint16_t) deven;
}
hck = 0;
for (uint32_t i = 0; i < 4 + 16; i += 2)
hck ^= (mfmbuf[i] << 16) | mfmbuf[i + 1];
deven = dodd = hck;
dodd >>= 1;
deven &= 0x55555555;
dodd &= 0x55555555;
mfmbuf[20] = (uint16_t) (dodd >> 16);
mfmbuf[21] = (uint16_t) dodd;
mfmbuf[22] = (uint16_t) (deven >> 16);
mfmbuf[23] = (uint16_t) deven;
for (uint32_t i = 0; i < 4 + 16 + 4; i++)
word_post_mfm_add(fdi, mfmbuf[i]);
}
/* standard super-extended Amiga sector header */
static void
s20(FDI *fdi)
{
bit_drop_next(fdi);
fdi2raw_log("s20:header=%s,data=%s", datalog(fdi->track_src, 4), datalog(fdi->track_src + 4, 16));
amiga_sector_header(fdi, fdi->track_src, fdi->track_src + 4, 0, 0);
fdi->track_src += 4 + 16;
}
/* standard extended Amiga sector header */
static void
s21(FDI *fdi)
{
bit_drop_next(fdi);
fdi2raw_log("s21:header=%s", datalog(fdi->track_src, 4));
amiga_sector_header(fdi, fdi->track_src, 0, 0, 0);
fdi->track_src += 4;
}
/* standard Amiga sector header */
static void
s22(FDI *fdi)
{
bit_drop_next(fdi);
fdi2raw_log("s22:sector=%d,untilgap=%d", fdi->track_src[0], fdi->track_src[1]);
amiga_sector_header(fdi, 0, 0, fdi->track_src[0], fdi->track_src[1]);
fdi->track_src += 2;
}
/* standard 512-byte, CRC-correct Amiga data */
static void
s23(FDI *fdi)
{
fdi2raw_log("s23:data=%s", datalog(fdi->track_src, 512));
amiga_data(fdi, fdi->track_src);
fdi->track_src += 512;
}
/* not-decoded, 128*2^x-byte, CRC-correct Amiga data */
static void
s24(FDI *fdi)
{
int shift = *fdi->track_src++;
fdi2raw_log("s24:shift=%d,data=%s", shift, datalog(fdi->track_src, 128 << shift));
amiga_data_raw(fdi, fdi->track_src, 0, 128 << shift);
fdi->track_src += 128 << shift;
}
/* not-decoded, 128*2^x-byte, CRC-incorrect Amiga data */
static void
s25(FDI *fdi)
{
int shift = *fdi->track_src++;
fdi2raw_log("s25:shift=%d,crc=%s,data=%s", shift, datalog(fdi->track_src, 4), datalog(fdi->track_src + 4, 128 << shift));
amiga_data_raw(fdi, fdi->track_src + 4, fdi->track_src, 128 << shift);
fdi->track_src += 4 + (128 << shift);
}
/* standard extended Amiga sector */
static void
s26(FDI *fdi)
{
s21(fdi);
fdi2raw_log("s26:data=%s", datalog(fdi->track_src, 512));
amiga_data(fdi, fdi->track_src);
fdi->track_src += 512;
}
/* standard short Amiga sector */
static void
s27(FDI *fdi)
{
s22(fdi);
fdi2raw_log("s27:data=%s", datalog(fdi->track_src, 512));
amiga_data(fdi, fdi->track_src);
fdi->track_src += 512;
}
/* *** */
/* IBM */
/* *** */
static uint16_t
ibm_crc(uint8_t byte, int reset)
{
static uint16_t crc;
if (reset)
crc = 0xcdb4;
for (uint8_t i = 0; i < 8; i++) {
if (crc & 0x8000) {
crc <<= 1;
if (!(byte & 0x80))
crc ^= 0x1021;
} else {
crc <<= 1;
if (byte & 0x80)
crc ^= 0x1021;
}
byte <<= 1;
}
return crc;
}
static void
ibm_data(FDI *fdi, uint8_t *data, uint8_t *crc, int len)
{
uint8_t crcbuf[2];
uint16_t crcv = 0;
word_add(fdi, 0x4489);
word_add(fdi, 0x4489);
word_add(fdi, 0x4489);
byte_mfm_add(fdi, 0xfb);
ibm_crc(0xfb, 1);
for (int i = 0; i < len; i++) {
byte_mfm_add(fdi, data[i]);
crcv = ibm_crc(data[i], 0);
}
if (!crc) {
crc = crcbuf;
crc[0] = (uint8_t) (crcv >> 8);
crc[1] = (uint8_t) crcv;
}
byte_mfm_add(fdi, crc[0]);
byte_mfm_add(fdi, crc[1]);
}
static void
ibm_sector_header(FDI *fdi, uint8_t *data, uint8_t *crc, int secnum, int pre)
{
uint8_t secbuf[5];
uint8_t crcbuf[2];
uint16_t crcv;
if (pre)
bytes_mfm_add(fdi, 0, 12);
word_add(fdi, 0x4489);
word_add(fdi, 0x4489);
word_add(fdi, 0x4489);
secbuf[0] = 0xfe;
if (secnum >= 0) {
secbuf[1] = (uint8_t) (fdi->current_track / 2);
secbuf[2] = (uint8_t) (fdi->current_track % 2);
secbuf[3] = (uint8_t) secnum;
secbuf[4] = 2;
} else {
memcpy(secbuf + 1, data, 4);
}
ibm_crc(secbuf[0], 1);
ibm_crc(secbuf[1], 0);
ibm_crc(secbuf[2], 0);
ibm_crc(secbuf[3], 0);
crcv = ibm_crc(secbuf[4], 0);
if (crc) {
memcpy(crcbuf, crc, 2);
} else {
crcbuf[0] = (uint8_t) (crcv >> 8);
crcbuf[1] = (uint8_t) crcv;
}
/* data */
for (uint8_t i = 0; i < 5; i++)
byte_mfm_add(fdi, secbuf[i]);
/* crc */
byte_mfm_add(fdi, crcbuf[0]);
byte_mfm_add(fdi, crcbuf[1]);
}
/* standard IBM index address mark */
static void
s10(FDI *fdi)
{
bit_drop_next(fdi);
bytes_mfm_add(fdi, 0, 12);
word_add(fdi, 0x5224);
word_add(fdi, 0x5224);
word_add(fdi, 0x5224);
byte_mfm_add(fdi, 0xfc);
}
/* standard IBM pre-gap */
static void
s11(FDI *fdi)
{
bit_drop_next(fdi);
bytes_mfm_add(fdi, 0x4e, 78);
bit_dedrop(fdi);
s10(fdi);
bytes_mfm_add(fdi, 0x4e, 50);
}
/* standard ST pre-gap */
static void
s12(FDI *fdi)
{
bit_drop_next(fdi);
bytes_mfm_add(fdi, 0x4e, 78);
}
/* standard extended IBM sector header */
static void
s13(FDI *fdi)
{
bit_drop_next(fdi);
fdi2raw_log("s13:header=%s", datalog(fdi->track_src, 4));
ibm_sector_header(fdi, fdi->track_src, 0, -1, 1);
fdi->track_src += 4;
}
/* standard mini-extended IBM sector header */
static void
s14(FDI *fdi)
{
fdi2raw_log("s14:header=%s", datalog(fdi->track_src, 4));
ibm_sector_header(fdi, fdi->track_src, 0, -1, 0);
fdi->track_src += 4;
}
/* standard short IBM sector header */
static void
s15(FDI *fdi)
{
bit_drop_next(fdi);
fdi2raw_log("s15:sector=%d", *fdi->track_src);
ibm_sector_header(fdi, 0, 0, *fdi->track_src++, 1);
}
/* standard mini-short IBM sector header */
static void
s16(FDI *fdi)
{
fdi2raw_log("s16:track=%d", *fdi->track_src);
ibm_sector_header(fdi, 0, 0, *fdi->track_src++, 0);
}
/* standard CRC-incorrect mini-extended IBM sector header */
static void
s17(FDI *fdi)
{
fdi2raw_log("s17:header=%s,crc=%s", datalog(fdi->track_src, 4), datalog(fdi->track_src + 4, 2));
ibm_sector_header(fdi, fdi->track_src, fdi->track_src + 4, -1, 0);
fdi->track_src += 4 + 2;
}
/* standard CRC-incorrect mini-short IBM sector header */
static void
s18(FDI *fdi)
{
fdi2raw_log("s18:sector=%d,header=%s", *fdi->track_src, datalog(fdi->track_src + 1, 4));
ibm_sector_header(fdi, 0, fdi->track_src + 1, *fdi->track_src, 0);
fdi->track_src += 1 + 4;
}
/* standard 512-byte CRC-correct IBM data */
static void
s19(FDI *fdi)
{
fdi2raw_log("s19:data=%s", datalog(fdi->track_src, 512));
ibm_data(fdi, fdi->track_src, 0, 512);
fdi->track_src += 512;
}
/* standard 128*2^x-byte-byte CRC-correct IBM data */
static void
s1a(FDI *fdi)
{
int shift = *fdi->track_src++;
fdi2raw_log("s1a:shift=%d,data=%s", shift, datalog(fdi->track_src, 128 << shift));
ibm_data(fdi, fdi->track_src, 0, 128 << shift);
fdi->track_src += 128 << shift;
}
/* standard 128*2^x-byte-byte CRC-incorrect IBM data */
static void
s1b(FDI *fdi)
{
int shift = *fdi->track_src++;
fdi2raw_log("s1b:shift=%d,crc=%s,data=%s", shift, datalog(fdi->track_src + (128 << shift), 2), datalog(fdi->track_src, 128 << shift));
ibm_data(fdi, fdi->track_src, fdi->track_src + (128 << shift), 128 << shift);
fdi->track_src += (128 << shift) + 2;
}
/* standard extended IBM sector */
static void
s1c(FDI *fdi)
{
int shift = fdi->track_src[3];
s13(fdi);
bytes_mfm_add(fdi, 0x4e, 22);
bytes_mfm_add(fdi, 0x00, 12);
ibm_data(fdi, fdi->track_src, 0, 128 << shift);
fdi->track_src += 128 << shift;
}
/* standard short IBM sector */
static void
s1d(FDI *fdi)
{
s15(fdi);
bytes_mfm_add(fdi, 0x4e, 22);
bytes_mfm_add(fdi, 0x00, 12);
s19(fdi);
}
/* end marker */
static void
sff(UNUSED(FDI *fdi))
{
}
typedef void (*decode_described_track_func)(FDI *);
static decode_described_track_func decode_sectors_described_track[] = {
s00, s01, s02, s03, s04, dxx, dxx, dxx, s08, s09, s0a, s0b, s0c, s0d, dxx, dxx, /* 00-0F */
s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s1a, s1b, s1c, s1d, dxx, dxx, /* 10-1F */
s20, s21, s22, s23, s24, s25, s26, s27, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* 20-2F */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* 30-3F */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* 40-4F */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* 50-5F */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* 60-6F */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* 70-7F */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* 80-8F */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* 90-9F */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* A0-AF */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* B0-BF */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* C0-CF */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* D0-DF */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, /* E0-EF */
dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, dxx, sff /* F0-FF */
};
static void
track_amiga(struct fdi *fdi, int first_sector, int max_sector)
{
bit_add(fdi, 0);
bit_drop_next(fdi);
for (int i = 0; i < max_sector; i++) {
amiga_sector_header(fdi, 0, 0, first_sector, max_sector - i);
amiga_data(fdi, fdi->track_src + first_sector * 512);
first_sector++;
if (first_sector >= max_sector)
first_sector = 0;
}
bytes_mfm_add(fdi, 0, 260); /* gap */
}
static void
track_atari_st(struct fdi *fdi, int max_sector)
{
int gap3 = 0;
uint8_t *p = fdi->track_src;
switch (max_sector) {
case 9:
gap3 = 40;
break;
case 10:
gap3 = 24;
break;
default:
break;
}
s15(fdi);
for (int i = 0; i < max_sector; i++) {
byte_mfm_add(fdi, 0x4e);
byte_mfm_add(fdi, 0x4e);
ibm_sector_header(fdi, 0, 0, fdi->current_track, 1);
ibm_data(fdi, p + i * 512, 0, 512);
bytes_mfm_add(fdi, 0x4e, gap3);
}
bytes_mfm_add(fdi, 0x4e, 660 - gap3);
fdi->track_src += fdi->track_len * 256;
}
static void
track_pc(struct fdi *fdi, int max_sector)
{
int gap3;
uint8_t *p = fdi->track_src;
switch (max_sector) {
case 8:
gap3 = 116;
break;
case 9:
gap3 = 54;
break;
default:
gap3 = 100; /* fixme */
break;
}
s11(fdi);
for (int i = 0; i < max_sector; i++) {
byte_mfm_add(fdi, 0x4e);
byte_mfm_add(fdi, 0x4e);
ibm_sector_header(fdi, 0, 0, fdi->current_track, 1);
ibm_data(fdi, p + i * 512, 0, 512);
bytes_mfm_add(fdi, 0x4e, gap3);
}
bytes_mfm_add(fdi, 0x4e, 600 - gap3);
fdi->track_src += fdi->track_len * 256;
}
/* amiga dd */
static void
track_amiga_dd(struct fdi *fdi)
{
uint8_t *p = fdi->track_src;
track_amiga(fdi, fdi->track_len >> 4, 11);
fdi->track_src = p + (fdi->track_len & 15) * 512;
}
/* amiga hd */
static void
track_amiga_hd(struct fdi *fdi)
{
uint8_t *p = fdi->track_src;
track_amiga(fdi, 0, 22);
fdi->track_src = p + fdi->track_len * 256;
}
/* atari st 9 sector */
static void
track_atari_st_9(struct fdi *fdi)
{
track_atari_st(fdi, 9);
}
/* atari st 10 sector */
static void
track_atari_st_10(struct fdi *fdi)
{
track_atari_st(fdi, 10);
}
/* pc 8 sector */
static void
track_pc_8(struct fdi *fdi)
{
track_pc(fdi, 8);
}
/* pc 9 sector */
static void
track_pc_9(struct fdi *fdi)
{
track_pc(fdi, 9);
}
/* pc 15 sector */
static void
track_pc_15(struct fdi *fdi)
{
track_pc(fdi, 15);
}
/* pc 18 sector */
static void
track_pc_18(struct fdi *fdi)
{
track_pc(fdi, 18);
}
/* pc 36 sector */
static void
track_pc_36(struct fdi *fdi)
{
track_pc(fdi, 36);
}
typedef void (*decode_normal_track_func)(FDI *);
static decode_normal_track_func decode_normal_track[] = {
track_empty, /* 0 */
track_amiga_dd, track_amiga_hd, /* 1-2 */
track_atari_st_9, track_atari_st_10, /* 3-4 */
track_pc_8, track_pc_9, track_pc_15, track_pc_18, track_pc_36, /* 5-9 */
zxx, zxx, zxx, zxx, zxx /* A-F */
};
static void
fix_mfm_sync(FDI *fdi)
{
int pos;
int off1;
int off2;
int off3;
int mask1;
int mask2;
int mask3;
for (int i = 0; i < fdi->mfmsync_offset; i++) {
pos = fdi->mfmsync_buffer[i];
off1 = (pos - 1) >> 3;
off2 = (pos + 1) >> 3;
off3 = pos >> 3;
mask1 = 1 << (7 - ((pos - 1) & 7));
mask2 = 1 << (7 - ((pos + 1) & 7));
mask3 = 1 << (7 - (pos & 7));
if (!(fdi->track_dst[off1] & mask1) && !(fdi->track_dst[off2] & mask2))
fdi->track_dst[off3] |= mask3;
else
fdi->track_dst[off3] &= ~mask3;
}
}
static int
handle_sectors_described_track(FDI *fdi)
{
#ifdef ENABLE_FDI2RAW_LOG
int oldout;
uint8_t *start_src = fdi->track_src;
#endif
fdi->encoding_type = *fdi->track_src++;
fdi->index_offset = get_u32(fdi->track_src);
fdi->index_offset >>= 8;
fdi->track_src += 3;
fdi2raw_log("sectors_described, index offset: %d\n", fdi->index_offset);
do {
fdi->track_type = *fdi->track_src++;
fdi2raw_log("%06.6X %06.6X %02.2X:", fdi->track_src - start_src + 0x200, fdi->out / 8, fdi->track_type);
#ifdef ENABLE_FDI2RAW_LOG
oldout = fdi->out;
#endif
decode_sectors_described_track[fdi->track_type](fdi);
fdi2raw_log(" %d\n", fdi->out - oldout);
#ifdef ENABLE_FDI2RAW_LOG
oldout = fdi->out;
#endif
if (fdi->out < 0 || fdi->err) {
fdi2raw_log("\nin %d bytes, out %d bits\n", fdi->track_src - fdi->track_src_buffer, fdi->out);
return -1;
}
if (fdi->track_src - fdi->track_src_buffer >= fdi->track_src_len) {
fdi2raw_log("source buffer overrun, previous type: %02.2X\n", fdi->track_type);
return -1;
}
} while (fdi->track_type != 0xff);
fdi2raw_log("\n");
fix_mfm_sync(fdi);
return fdi->out;
}
static uint8_t *
fdi_decompress(int pulses, uint8_t *sizep, uint8_t *src, int *dofree)
{
uint32_t size = get_u24(sizep);
uint32_t *dst2;
int len = size & 0x3fffff;
uint8_t *dst;
int mode = size >> 22;
*dofree = 0;
if (mode == 0 && pulses * 2 > len)
mode = 1;
if (mode == 0) {
dst2 = (uint32_t *) src;
dst = src;
for (int i = 0; i < pulses; i++) {
*dst2++ = get_u32(src);
src += 4;
}
} else if (mode == 1) {
dst = fdi_malloc(pulses * 4);
*dofree = 1;
fdi_decode(src, pulses, dst);
} else {
dst = 0;
}
return dst;
}
static void
dumpstream(UNUSED(int track), UNUSED(uint8_t *stream), UNUSED(int len))
{
#if 0
char name[100];
FILE *fp;
sprintf (name, "track_%d.raw", track);
fp = fopen(name, "wb");
fwrite (stream, 1, len * 4, fp);
fclose (fp);
#endif
}
static int bitoffset;
static inline void
addbit(uint8_t *p, int bit)
{
int off1 = bitoffset / 8;
int off2 = bitoffset % 8;
p[off1] |= bit << (7 - off2);
bitoffset++;
}
struct pulse_sample {
uint32_t size;
int number_of_bits;
};
#define FDI_MAX_ARRAY 10 /* change this value as you want */
static int pulse_limitval = 15; /* tolerance of 15% */
static struct pulse_sample psarray[FDI_MAX_ARRAY];
static int array_index;
static uint32_t total;
static int totaldiv;
static void
init_array(uint32_t standard_MFM_2_bit_cell_size, int nb_of_bits)
{
for (uint8_t i = 0; i < FDI_MAX_ARRAY; i++) {
psarray[i].size = standard_MFM_2_bit_cell_size; /* That is (total track length / 50000) for Amiga double density */
total += psarray[i].size;
psarray[i].number_of_bits = nb_of_bits;
totaldiv += psarray[i].number_of_bits;
}
array_index = 0;
}
#if 0
static void fdi2_decode (FDI *fdi, uint32_t totalavg, uint32_t *avgp, uint32_t *minp, uint32_t *maxp, uint8_t *idx, int maxidx, int *indexoffsetp, int pulses, int mfm)
{
uint32_t adjust;
uint32_t adjusted_pulse;
uint32_t standard_MFM_2_bit_cell_size = totalavg / 50000;
uint32_t standard_MFM_8_bit_cell_size = totalavg / 12500;
int real_size, i, j, eodat, outstep;
int indexoffset = *indexoffsetp;
uint8_t *d = fdi->track_dst_buffer;
uint16_t *pt = fdi->track_dst_buffer_timing;
uint32_t ref_pulse, pulse;
/* detects a long-enough stable pulse coming just after another stable pulse */
i = 1;
while ( (i < pulses) && ( (idx[i] < maxidx)
|| (idx[i - 1] < maxidx)
|| (avgp[i] < (standard_MFM_2_bit_cell_size - (standard_MFM_2_bit_cell_size / 4))) ) )
i++;
if (i == pulses) {
fdi2raw_log("No stable and long-enough pulse in track.\n");
return;
}
i--;
eodat = i;
adjust = 0;
total = 0;
totaldiv = 0;
init_array(standard_MFM_2_bit_cell_size, 2);
bitoffset = 0;
ref_pulse = 0;
outstep = 0;
while (outstep < 2) {
/* calculates the current average bitrate from previous decoded data */
uint32_t avg_size = (total << 3) / totaldiv; /* this is the new average size for one MFM bit */
/* uint32_t avg_size = (uint32_t)((((float)total)*8.0) / ((float)totaldiv)); */
/* you can try tighter ranges than 25%, or wider ranges. I would probably go for tighter... */
if ((avg_size < (standard_MFM_8_bit_cell_size - (pulse_limitval * standard_MFM_8_bit_cell_size / 100))) ||
(avg_size > (standard_MFM_8_bit_cell_size + (pulse_limitval * standard_MFM_8_bit_cell_size / 100)))) {
avg_size = standard_MFM_8_bit_cell_size;
}
/* this is to prevent the average value from going too far
* from the theoretical value, otherwise it could progressively go to (2 *
* real value), or (real value / 2), etc. */
/* gets the next long-enough pulse (this may require more than one pulse) */
pulse = 0;
while (pulse < ((avg_size / 4) - (avg_size / 16))) {
int indx;
i++;
if (i >= pulses)
i = 0;
indx = idx[i];
if (rand() <= (indx * RAND_MAX) / maxidx) {
pulse += avgp[i] - ref_pulse;
if (indx >= maxidx)
ref_pulse = 0;
else
ref_pulse = avgp[i];
}
if (i == eodat)
outstep++;
if (outstep == 1 && indexoffset == i)
*indexoffsetp = bitoffset;
}
/* gets the size in bits from the pulse width, considering the current average bitrate */
adjusted_pulse = pulse;
real_size = 0;
while (adjusted_pulse >= avg_size) {
real_size += 4;
adjusted_pulse -= avg_size / 2;
}
adjusted_pulse <<= 3;
while (adjusted_pulse >= ((avg_size * 4) + (avg_size / 4))) {
real_size += 2;
adjusted_pulse -= avg_size * 2;
}
if (adjusted_pulse >= ((avg_size * 3) + (avg_size / 4))) {
if (adjusted_pulse <= ((avg_size * 4) - (avg_size / 4))) {
if ((2 * ((adjusted_pulse >> 2) - adjust)) <= ((2 * avg_size) - (avg_size / 4)))
real_size += 3;
else
real_size += 4;
} else
real_size += 4;
} else {
if (adjusted_pulse > ((avg_size * 3) - (avg_size / 4))) {
real_size += 3;
} else {
if (adjusted_pulse >= ((avg_size * 2) + (avg_size / 4))) {
if ((2 * ((adjusted_pulse >> 2) - adjust)) < (avg_size + (avg_size / 4)))
real_size += 2;
else
real_size += 3;
} else
real_size += 2;
}
}
if (outstep == 1) {
for (j = real_size; j > 1; j--)
addbit (d, 0);
addbit (d, 1);
for (j = 0; j < real_size; j++)
*pt++ = (uint16_t)(pulse / real_size);
}
/* prepares for the next pulse */
adjust = ((real_size * avg_size)/8) - pulse;
total -= psarray[array_index].size;
totaldiv -= psarray[array_index].number_of_bits;
psarray[array_index].size = pulse;
psarray[array_index].number_of_bits = real_size;
total += pulse;
totaldiv += real_size;
array_index++;
if (array_index >= FDI_MAX_ARRAY)
array_index = 0;
}
fdi->out = bitoffset;
}
#else
static void
fdi2_decode(FDI *fdi, uint32_t totalavg, uint32_t *avgp, uint32_t *minp, uint32_t *maxp, uint8_t *idx, int maxidx, int *indexoffsetp, int pulses, int mfm)
{
uint32_t adjust;
uint32_t adjusted_pulse;
uint32_t standard_MFM_2_bit_cell_size = totalavg / 50000;
uint32_t standard_MFM_8_bit_cell_size = totalavg / 12500;
int real_size;
int i;
int j;
int nexti;
int eodat;
int outstep;
int randval;
int indexoffset = *indexoffsetp;
uint8_t *d = fdi->track_dst_buffer;
uint16_t *pt = fdi->track_dst_buffer_timing;
uint32_t ref_pulse;
uint32_t pulse;
int32_t jitter;
/* detects a long-enough stable pulse coming just after another stable pulse */
i = 1;
while ((i < pulses) && ((idx[i] < maxidx) || (idx[i - 1] < maxidx) || (minp[i] < (standard_MFM_2_bit_cell_size - (standard_MFM_2_bit_cell_size / 4)))))
i++;
if (i == pulses) {
fdi2raw_log("FDI: No stable and long-enough pulse in track.\n");
return;
}
nexti = i;
eodat = i;
i--;
adjust = 0;
total = 0;
totaldiv = 0;
init_array(standard_MFM_2_bit_cell_size, 1 + mfm);
bitoffset = 0;
ref_pulse = 0;
jitter = 0;
outstep = -1;
while (outstep < 2) {
/* calculates the current average bitrate from previous decoded data */
uint32_t avg_size = (uint32_t) ((total << (2 + mfm)) / totaldiv); /* this is the new average size for one MFM bit */
#if 0
uint32_t avg_size = (uint32_t)((((float)total)*((float)(mfm+1))*4.0) / ((float)totaldiv));
#endif
/* you can try tighter ranges than 25%, or wider ranges. I would probably go for tighter... */
if ((avg_size < (standard_MFM_8_bit_cell_size - (pulse_limitval * standard_MFM_8_bit_cell_size / 100))) || (avg_size > (standard_MFM_8_bit_cell_size + (pulse_limitval * standard_MFM_8_bit_cell_size / 100)))) {
avg_size = standard_MFM_8_bit_cell_size;
}
/* this is to prevent the average value from going too far
* from the theoretical value, otherwise it could progressively go to (2 *
* real value), or (real value / 2), etc. */
/* gets the next long-enough pulse (this may require more than one pulse) */
pulse = 0;
while (pulse < ((avg_size / 4) - (avg_size / 16))) {
uint32_t avg_pulse;
uint32_t min_pulse;
uint32_t max_pulse;
i++;
if (i >= pulses)
i = 0;
if (i == nexti) {
do {
nexti++;
if (nexti >= pulses)
nexti = 0;
} while (idx[nexti] < maxidx);
}
if (idx[i] >= maxidx) { /* stable pulse */
avg_pulse = avgp[i] - jitter;
min_pulse = minp[i];
max_pulse = maxp[i];
if (jitter >= 0)
max_pulse -= jitter;
else
min_pulse -= jitter;
if ((maxp[nexti] - avgp[nexti]) < (avg_pulse - min_pulse))
min_pulse = avg_pulse - (maxp[nexti] - avgp[nexti]);
if ((avgp[nexti] - minp[nexti]) < (max_pulse - avg_pulse))
max_pulse = avg_pulse + (avgp[nexti] - minp[nexti]);
if (min_pulse < ref_pulse)
min_pulse = ref_pulse;
randval = rand();
if (randval < (RAND_MAX / 2)) {
if (randval > (RAND_MAX / 4)) {
if (randval <= ((3LL * (uint64_t) RAND_MAX) / 8))
randval = (2 * randval) - (RAND_MAX / 4);
else
randval = (4 * randval) - RAND_MAX;
}
jitter = 0 - (randval * (avg_pulse - min_pulse)) / RAND_MAX;
} else {
randval -= RAND_MAX / 2;
if (randval > (RAND_MAX / 4)) {
if (randval <= ((3LL * (uint64_t) RAND_MAX) / 8))
randval = (2 * randval) - (RAND_MAX / 4);
else
randval = (4 * randval) - RAND_MAX;
}
jitter = (randval * (max_pulse - avg_pulse)) / RAND_MAX;
}
avg_pulse += jitter;
if ((avg_pulse < min_pulse) || (avg_pulse > max_pulse)) {
fdi2raw_log("FDI: avg_pulse outside bounds! avg=%u min=%u max=%u\n", avg_pulse, min_pulse, max_pulse);
fdi2raw_log("FDI: avgp=%u (%u) minp=%u (%u) maxp=%u (%u) jitter=%d i=%d ni=%d\n",
avgp[i], avgp[nexti], minp[i], minp[nexti], maxp[i], maxp[nexti], jitter, i, nexti);
}
if (avg_pulse < ref_pulse)
fdi2raw_log("FDI: avg_pulse < ref_pulse! (%u < %u)\n", avg_pulse, ref_pulse);
pulse += avg_pulse - ref_pulse;
ref_pulse = 0;
if (i == eodat)
outstep++;
} else if (rand() <= ((idx[i] * RAND_MAX) / maxidx)) {
avg_pulse = avgp[i];
min_pulse = minp[i];
max_pulse = maxp[i];
randval = rand();
if (randval < (RAND_MAX / 2)) {
if (randval > (RAND_MAX / 4)) {
if (randval <= ((3LL * (uint64_t) RAND_MAX) / 8))
randval = (2 * randval) - (RAND_MAX / 4);
else
randval = (4 * randval) - RAND_MAX;
}
avg_pulse -= (randval * (avg_pulse - min_pulse)) / RAND_MAX;
} else {
randval -= RAND_MAX / 2;
if (randval > (RAND_MAX / 4)) {
if (randval <= ((3LL * (uint64_t) RAND_MAX) / 8))
randval = (2 * randval) - (RAND_MAX / 4);
else
randval = (4 * randval) - RAND_MAX;
}
avg_pulse += (randval * (max_pulse - avg_pulse)) / RAND_MAX;
}
if ((avg_pulse > ref_pulse) && (avg_pulse < (avgp[nexti] - jitter))) {
pulse += avg_pulse - ref_pulse;
ref_pulse = avg_pulse;
}
}
if (outstep == 1 && indexoffset == i)
*indexoffsetp = bitoffset;
}
/* gets the size in bits from the pulse width, considering the current average bitrate */
adjusted_pulse = pulse;
real_size = 0;
if (mfm) {
while (adjusted_pulse >= avg_size) {
real_size += 4;
adjusted_pulse -= avg_size / 2;
}
adjusted_pulse <<= 3;
while (adjusted_pulse >= ((avg_size * 4) + (avg_size / 4))) {
real_size += 2;
adjusted_pulse -= avg_size * 2;
}
if (adjusted_pulse >= ((avg_size * 3) + (avg_size / 4))) {
if (adjusted_pulse <= ((avg_size * 4) - (avg_size / 4))) {
if ((2 * ((adjusted_pulse >> 2) - adjust)) <= ((2 * avg_size) - (avg_size / 4)))
real_size += 3;
else
real_size += 4;
} else
real_size += 4;
} else {
if (adjusted_pulse > ((avg_size * 3) - (avg_size / 4))) {
real_size += 3;
} else {
if (adjusted_pulse >= ((avg_size * 2) + (avg_size / 4))) {
if ((2 * ((adjusted_pulse >> 2) - adjust)) < (avg_size + (avg_size / 4)))
real_size += 2;
else
real_size += 3;
} else
real_size += 2;
}
}
} else {
while (adjusted_pulse >= (2 * avg_size)) {
real_size += 4;
adjusted_pulse -= avg_size;
}
adjusted_pulse <<= 2;
while (adjusted_pulse >= ((avg_size * 3) + (avg_size / 4))) {
real_size += 2;
adjusted_pulse -= avg_size * 2;
}
if (adjusted_pulse >= ((avg_size * 2) + (avg_size / 4))) {
if (adjusted_pulse <= ((avg_size * 3) - (avg_size / 4))) {
if (((adjusted_pulse >> 1) - adjust) < (avg_size + (avg_size / 4)))
real_size += 2;
else
real_size += 3;
} else
real_size += 3;
} else {
if (adjusted_pulse > ((avg_size * 2) - (avg_size / 4)))
real_size += 2;
else {
if (adjusted_pulse >= (avg_size + (avg_size / 4))) {
if (((adjusted_pulse >> 1) - adjust) <= (avg_size - (avg_size / 4)))
real_size++;
else
real_size += 2;
} else
real_size++;
}
}
}
/* after one pass to correctly initialize the average bitrate, outputs the bits */
if (outstep == 1) {
for (j = real_size; j > 1; j--)
addbit(d, 0);
addbit(d, 1);
for (j = 0; j < real_size; j++)
*pt++ = (uint16_t) (pulse / real_size);
}
/* prepares for the next pulse */
adjust = ((real_size * avg_size) / (4 << mfm)) - pulse;
total -= psarray[array_index].size;
totaldiv -= psarray[array_index].number_of_bits;
psarray[array_index].size = pulse;
psarray[array_index].number_of_bits = real_size;
total += pulse;
totaldiv += real_size;
array_index++;
if (array_index >= FDI_MAX_ARRAY)
array_index = 0;
}
fdi->out = bitoffset;
}
#endif
static void
fdi2_celltiming(FDI *fdi, uint32_t totalavg, int bitoffset, uint16_t *out)
{
const uint16_t *pt2;
uint16_t *pt;
double avg_bit_len;
avg_bit_len = (double) totalavg / (double) bitoffset;
pt2 = fdi->track_dst_buffer_timing;
pt = out;
for (int i = 0; i < bitoffset / 8; i++) {
double v = (pt2[0] + pt2[1] + pt2[2] + pt2[3] + pt2[4] + pt2[5] + pt2[6] + pt2[7]) / 8.0;
v = 1000.0 * v / avg_bit_len;
*pt++ = (uint16_t) v;
pt2 += 8;
}
*pt++ = out[0];
*pt = out[0];
}
static int
decode_lowlevel_track(FDI *fdi, int track, struct fdi_cache *cache)
{
uint8_t *p1;
const uint32_t *p2;
uint32_t *avgp;
uint32_t *minp = 0;
uint32_t *maxp = 0;
uint8_t *idxp = 0;
uint32_t maxidx;
uint32_t totalavg;
uint32_t weakbits;
int j;
int k;
int len;
int pulses;
int indexoffset;
int avg_free;
int min_free = 0;
int max_free = 0;
int idx_free;
int idx_off1 = 0;
int idx_off2 = 0;
int idx_off3 = 0;
p1 = fdi->track_src;
pulses = get_u32(p1);
if (!pulses)
return -1;
p1 += 4;
len = 12;
avgp = (uint32_t *) fdi_decompress(pulses, p1 + 0, p1 + len, &avg_free);
dumpstream(track, (uint8_t *) avgp, pulses);
len += get_u24(p1 + 0) & 0x3fffff;
if (!avgp)
return -1;
if (get_u24(p1 + 3) && get_u24(p1 + 6)) {
minp = (uint32_t *) fdi_decompress(pulses, p1 + 3, p1 + len, &min_free);
len += get_u24(p1 + 3) & 0x3fffff;
maxp = (uint32_t *) fdi_decompress(pulses, p1 + 6, p1 + len, &max_free);
len += get_u24(p1 + 6) & 0x3fffff;
/* Computes the real min and max values */
for (int i = 0; i < pulses; i++) {
maxp[i] = avgp[i] + minp[i] - maxp[i];
minp[i] = avgp[i] - minp[i];
}
} else {
minp = avgp;
maxp = avgp;
}
if (get_u24(p1 + 9)) {
idx_off1 = 0;
idx_off2 = 1;
idx_off3 = 2;
idxp = fdi_decompress(pulses, p1 + 9, p1 + len, &idx_free);
if (idx_free) {
if (idxp[0] == 0 && idxp[1] == 0) {
idx_off1 = 2;
idx_off2 = 3;
} else {
idx_off1 = 1;
idx_off2 = 0;
}
idx_off3 = 4;
}
} else {
idxp = fdi_malloc(pulses * 2);
idx_free = 1;
for (int i = 0; i < pulses; i++) {
idxp[i * 2 + 0] = 2;
idxp[i * 2 + 1] = 0;
}
idxp[0] = 1;
idxp[1] = 1;
}
maxidx = 0;
indexoffset = 0;
p1 = idxp;
for (int i = 0; i < pulses; i++) {
if ((uint32_t) p1[idx_off1] + (uint32_t) p1[idx_off2] > maxidx)
maxidx = p1[idx_off1] + p1[idx_off2];
p1 += idx_off3;
}
p1 = idxp;
for (k = 0; (k < pulses) && (p1[idx_off2] != 0); k++) /* falling edge, replace with idx_off1 for rising edge */
p1 += idx_off3;
if (k < pulses) {
j = k;
do {
k++;
p1 += idx_off3;
if (k >= pulses) {
k = 0;
p1 = idxp;
}
} while ((k != j) && (p1[idx_off2] == 0)); /* falling edge, replace with idx_off1 for rising edge */
if (k != j) /* index pulse detected */
{
while ((k != j) && (p1[idx_off1] > p1[idx_off2])) { /* falling edge, replace with "<" for rising edge */
k++;
p1 += idx_off3;
if (k >= pulses) {
k = 0;
p1 = idxp;
}
}
if (k != j)
indexoffset = k; /* index position detected */
}
}
p1 = idxp;
p2 = avgp;
totalavg = 0;
weakbits = 0;
for (int i = 0; i < pulses; i++) {
uint32_t sum = p1[idx_off1] + p1[idx_off2];
if (sum >= maxidx) {
totalavg += *p2;
} else {
weakbits++;
}
p2++;
p1 += idx_off3;
idxp[i] = sum;
}
len = totalavg / 100000;
#if 0
fdi2raw_log("totalavg=%u index=%d (%d) maxidx=%d weakbits=%d len=%d\n",
totalavg, indexoffset, maxidx, weakbits, len);
#endif
cache->avgp = avgp;
cache->idxp = idxp;
cache->minp = minp;
cache->maxp = maxp;
cache->avg_free = avg_free;
cache->idx_free = idx_free;
cache->min_free = min_free;
cache->max_free = max_free;
cache->totalavg = totalavg;
cache->pulses = pulses;
cache->maxidx = maxidx;
cache->indexoffset = indexoffset;
cache->weakbits = weakbits;
cache->lowlevel = 1;
return 1;
}
static unsigned char fdiid[] = { "Formatted Disk Image file" };
static int bit_rate_table[16] = { 125, 150, 250, 300, 500, 1000 };
void
fdi2raw_header_free(FDI *fdi)
{
fdi_free(fdi->mfmsync_buffer);
fdi_free(fdi->track_src_buffer);
fdi_free(fdi->track_dst_buffer);
fdi_free(fdi->track_dst_buffer_timing);
for (uint8_t i = 0; i < MAX_TRACKS; i++) {
struct fdi_cache *c = &fdi->cache[i];
if (c->idx_free)
fdi_free(c->idxp);
if (c->avg_free)
fdi_free(c->avgp);
if (c->min_free)
fdi_free(c->minp);
if (c->max_free)
fdi_free(c->maxp);
}
fdi_free(fdi);
fdi2raw_log("FREE: memory allocated %d\n", fdi_allocated);
}
int
fdi2raw_get_last_track(FDI *fdi)
{
return fdi->last_track;
}
int
fdi2raw_get_num_sector(FDI *fdi)
{
if (fdi->header[152] == 0x02)
return 22;
return 11;
}
int
fdi2raw_get_last_head(FDI *fdi)
{
return fdi->last_head;
}
int
fdi2raw_get_rotation(FDI *fdi)
{
return fdi->rotation_speed;
}
int
fdi2raw_get_bit_rate(FDI *fdi)
{
return fdi->bit_rate;
}
FDI2RawDiskType
fdi2raw_get_type(FDI *fdi)
{
return fdi->disk_type;
}
bool
fdi2raw_get_write_protect(FDI *fdi)
{
return fdi->write_protect;
}
int
fdi2raw_get_tpi(FDI *fdi)
{
return fdi->header[148];
}
FDI *
fdi2raw_header(FILE *fp)
{
long i;
long offset;
long oldseek;
uint8_t type;
uint8_t size;
FDI *fdi;
fdi2raw_log("ALLOC: memory allocated %d\n", fdi_allocated);
fdi = fdi_malloc(sizeof(FDI));
memset(fdi, 0, sizeof(FDI));
fdi->file = fp;
oldseek = ftell(fdi->file);
if (oldseek == -1) {
fdi_free(fdi);
return NULL;
}
if (fseek(fdi->file, 0, SEEK_SET) == -1)
fatal("fdi2raw_header(): Error seeking to the beginning of the file\n");
if (fread(fdi->header, 1, 2048, fdi->file) != 2048)
fatal("fdi2raw_header(): Error reading header\n");
if (fseek(fdi->file, oldseek, SEEK_SET) == -1)
fatal("fdi2raw_header(): Error seeking to offset oldseek\n");
if (memcmp(fdiid, fdi->header, strlen((char *) fdiid))) {
fdi_free(fdi);
return NULL;
}
if ((fdi->header[140] != 1 && fdi->header[140] != 2) || (fdi->header[141] != 0 && !(fdi->header[140] == 2 && fdi->header[141] == 1))) {
fdi_free(fdi);
return NULL;
}
fdi->mfmsync_buffer = fdi_malloc(MAX_MFM_SYNC_BUFFER * sizeof(int));
fdi->track_src_buffer = fdi_malloc(MAX_SRC_BUFFER);
fdi->track_dst_buffer = fdi_malloc(MAX_DST_BUFFER);
fdi->track_dst_buffer_timing = fdi_malloc(MAX_TIMING_BUFFER);
fdi->last_track = ((fdi->header[142] << 8) + fdi->header[143]) + 1;
fdi->last_track *= fdi->header[144] + 1;
if (fdi->last_track > MAX_TRACKS)
fdi->last_track = MAX_TRACKS;
fdi->last_head = fdi->header[144];
fdi->disk_type = fdi->header[145];
fdi->rotation_speed = fdi->header[146] + 128;
fdi->write_protect = !!(fdi->header[147] & 1);
fdi2raw_log("FDI version %d.%d\n", fdi->header[140], fdi->header[141]);
fdi2raw_log("last_track=%d rotation_speed=%d\n", fdi->last_track, fdi->rotation_speed);
offset = 512;
i = fdi->last_track;
if (i > 180) {
offset += 512;
i -= 180;
while (i > 256) {
offset += 512;
i -= 256;
}
}
for (i = 0; i < fdi->last_track; i++) {
fdi->track_offsets[i] = offset;
type = fdi->header[152 + i * 2];
size = fdi->header[152 + i * 2 + 1];
if (type == 1)
offset += (size & 15) * 512;
else if ((type & 0xc0) == 0x80)
offset += (((type & 0x3f) << 8) | size) * 256;
else
offset += size * 256;
}
fdi->track_offsets[i] = offset;
return fdi;
}
static int
fdi2raw_loadrevolution_2(FDI *fdi, uint16_t *mfmbuf, uint16_t *tracktiming, int track, int *tracklength, int *indexoffsetp, int *multirev, int mfm)
{
struct fdi_cache *cache = &fdi->cache[track];
int len;
int idx;
memset(fdi->track_dst_buffer, 0, MAX_DST_BUFFER);
idx = cache->indexoffset;
fdi2_decode(fdi, cache->totalavg,
cache->avgp, cache->minp, cache->maxp, cache->idxp,
cache->maxidx, &idx, cache->pulses, mfm);
#if 0
fdi2raw_log("track %d: nbits=%d avg len=%.2f weakbits=%d idx=%d\n",
track, bitoffset, (double)cache->totalavg / bitoffset, cache->weakbits, cache->indexoffset);
#endif
len = fdi->out;
if (cache->weakbits >= 10 && multirev)
*multirev = 1;
*tracklength = len;
for (int i = 0; i < (len + 15) / (2 * 8); i++) {
const uint8_t *data = fdi->track_dst_buffer + i * 2;
*mfmbuf++ = 256 * *data + *(data + 1);
}
fdi2_celltiming(fdi, cache->totalavg, len, tracktiming);
if (indexoffsetp)
*indexoffsetp = idx;
return 1;
}
int
fdi2raw_loadrevolution(FDI *fdi, uint16_t *mfmbuf, uint16_t *tracktiming, int track, int *tracklength, int mfm)
{
track ^= fdi->reversed_side;
return fdi2raw_loadrevolution_2(fdi, mfmbuf, tracktiming, track, tracklength, 0, 0, mfm);
}
int
fdi2raw_loadtrack(FDI *fdi, uint16_t *mfmbuf, uint16_t *tracktiming, int track, int *tracklength, int *indexoffsetp, int *multirev, int mfm)
{
const uint8_t *p;
int outlen;
struct fdi_cache *cache = &fdi->cache[track];
track ^= fdi->reversed_side;
if (cache->lowlevel)
return fdi2raw_loadrevolution_2(fdi, mfmbuf, tracktiming, track, tracklength, indexoffsetp, multirev, mfm);
fdi->err = 0;
fdi->track_src_len = fdi->track_offsets[track + 1] - fdi->track_offsets[track];
if (fseek(fdi->file, fdi->track_offsets[track], SEEK_SET) == -1)
fatal("fdi2raw_loadtrack(): Error seeking to the beginning of the file\n");
if (fread(fdi->track_src_buffer, 1, fdi->track_src_len, fdi->file) != fdi->track_src_len)
fatal("fdi2raw_loadtrack(): Error reading data\n");
memset(fdi->track_dst_buffer, 0, MAX_DST_BUFFER);
fdi->track_dst_buffer_timing[0] = 0;
fdi->current_track = track;
fdi->track_src = fdi->track_src_buffer;
fdi->track_dst = fdi->track_dst_buffer;
p = fdi->header + 152 + fdi->current_track * 2;
fdi->track_type = *p++;
fdi->track_len = *p++;
fdi->bit_rate = 0;
fdi->out = 0;
fdi->mfmsync_offset = 0;
if ((fdi->track_type & 0xf0) == 0xf0 || (fdi->track_type & 0xf0) == 0xe0)
fdi->bit_rate = bit_rate_table[fdi->track_type & 0x0f];
else
fdi->bit_rate = 250;
#if 0
fdi2raw_log("track %d: srclen: %d track_type: %02.2X, bitrate: %d\n",
fdi->current_track, fdi->track_src_len, fdi->track_type, fdi->bit_rate);
#endif
if ((fdi->track_type & 0xc0) == 0x80) {
outlen = decode_lowlevel_track(fdi, track, cache);
} else if ((fdi->track_type & 0xf0) == 0xf0) {
outlen = decode_raw_track(fdi);
} else if ((fdi->track_type & 0xf0) == 0xe0) {
outlen = handle_sectors_described_track(fdi);
} else if (fdi->track_type & 0xf0) {
zxx(fdi);
outlen = -1;
} else if (fdi->track_type < 0x0f) {
decode_normal_track[fdi->track_type](fdi);
fix_mfm_sync(fdi);
outlen = fdi->out;
} else {
zxx(fdi);
outlen = -1;
}
if (fdi->err)
return 0;
if (outlen > 0) {
if (cache->lowlevel)
return fdi2raw_loadrevolution_2(fdi, mfmbuf, tracktiming, track, tracklength, indexoffsetp, multirev, mfm);
*tracklength = fdi->out;
for (int i = 0; i < ((*tracklength) + 15) / (2 * 8); i++) {
const uint8_t *data = fdi->track_dst_buffer + i * 2;
*mfmbuf++ = 256 * *data + *(data + 1);
}
}
return outlen;
}
``` | /content/code_sandbox/src/floppy/fdi2raw.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 22,011 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the FDI floppy stream image format
* interface to the FDI2RAW module.
*
*
*
* Authors: Sarah Walker, <path_to_url
* Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/plat.h>
#include <86box/fdd.h>
#include <86box/fdd_86f.h>
#include <86box/fdd_img.h>
#include <86box/fdd_fdi.h>
#include <86box/fdc.h>
#include <fdi2raw.h>
typedef struct fdi_t {
FILE *fp;
FDI *h;
int lasttrack;
int sides;
int track;
int tracklen[2][4];
int trackindex[2][4];
uint8_t track_data[2][4][256 * 1024];
uint8_t track_timing[2][4][256 * 1024];
} fdi_t;
static fdi_t *fdi[FDD_NUM];
static fdc_t *fdi_fdc;
#ifdef ENABLE_FDI_LOG
int fdi_do_log = ENABLE_FDI_LOG;
static void
fdi_log(const char *fmt, ...)
{
va_list ap;
if (fdi_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define fdi_log(fmt, ...)
#endif
static uint16_t
disk_flags(int drive)
{
fdi_t *dev = fdi[drive];
uint16_t temp_disk_flags = 0x80; /* We ALWAYS claim to have extra bit cells, even if the actual amount is 0. */
switch (fdi2raw_get_bit_rate(dev->h)) {
case 500:
temp_disk_flags |= 2;
break;
case 300:
case 250:
temp_disk_flags |= 0;
break;
case 1000:
temp_disk_flags |= 4;
break;
default:
temp_disk_flags |= 0;
}
if (dev->sides == 2)
temp_disk_flags |= 8;
/*
* Tell the 86F handler that we will handle our
* data to handle it in reverse byte endianness.
*/
temp_disk_flags |= 0x800;
return temp_disk_flags;
}
static uint16_t
side_flags(int drive)
{
fdi_t *dev = fdi[drive];
uint16_t temp_side_flags = 0;
switch (fdi2raw_get_bit_rate(dev->h)) {
case 500:
temp_side_flags = 0;
break;
case 300:
temp_side_flags = 1;
break;
case 250:
temp_side_flags = 2;
break;
case 1000:
temp_side_flags = 3;
break;
default:
temp_side_flags = 2;
}
if (fdi2raw_get_rotation(dev->h) == 360)
temp_side_flags |= 0x20;
/*
* Set the encoding value to match that provided by the FDC.
* Then if it's wrong, it will sector not found anyway.
*/
temp_side_flags |= 0x08;
return temp_side_flags;
}
static int
fdi_density(void)
{
if (!fdc_is_mfm(fdi_fdc))
return 0;
switch (fdc_get_bit_rate(fdi_fdc)) {
case 0:
return 2;
case 1:
return 1;
case 2:
return 1;
case 3:
case 5:
return 3;
default:
break;
}
return 1;
}
static int32_t
extra_bit_cells(int drive, int side)
{
const fdi_t *dev = fdi[drive];
int density = 0;
int raw_size = 0;
int is_300_rpm = 0;
density = fdi_density();
is_300_rpm = (fdd_getrpm(drive) == 300);
switch (fdc_get_bit_rate(fdi_fdc)) {
case 0:
raw_size = is_300_rpm ? 200000 : 166666;
break;
case 1:
raw_size = is_300_rpm ? 120000 : 100000;
break;
case 2:
raw_size = is_300_rpm ? 100000 : 83333;
break;
case 3:
case 5:
raw_size = is_300_rpm ? 400000 : 333333;
break;
default:
raw_size = is_300_rpm ? 100000 : 83333;
}
return (dev->tracklen[side][density] - raw_size);
}
static void
read_revolution(int drive)
{
fdi_t *dev = fdi[drive];
int c;
int den;
int track = dev->track;
if (track > dev->lasttrack) {
for (den = 0; den < 4; den++) {
memset(dev->track_data[0][den], 0, 106096);
memset(dev->track_data[1][den], 0, 106096);
dev->tracklen[0][den] = dev->tracklen[1][den] = 100000;
}
return;
}
for (den = 0; den < 4; den++) {
for (int side = 0; side < dev->sides; side++) {
c = fdi2raw_loadtrack(dev->h,
(uint16_t *) dev->track_data[side][den],
(uint16_t *) dev->track_timing[side][den],
(track * dev->sides) + side,
&dev->tracklen[side][den],
&dev->trackindex[side][den], NULL, den);
if (!c)
memset(dev->track_data[side][den], 0, dev->tracklen[side][den]);
}
if (dev->sides == 1) {
memset(dev->track_data[1][den], 0, 106096);
dev->tracklen[1][den] = 100000;
}
}
}
static uint32_t
index_hole_pos(int drive, int side)
{
const fdi_t *dev = fdi[drive];
int density;
density = fdi_density();
return (dev->trackindex[side][density]);
}
static uint32_t
get_raw_size(int drive, int side)
{
const fdi_t *dev = fdi[drive];
int density;
density = fdi_density();
return (dev->tracklen[side][density]);
}
static uint16_t *
encoded_data(int drive, int side)
{
fdi_t *dev = fdi[drive];
int density = 0;
density = fdi_density();
return ((uint16_t *) dev->track_data[side][density]);
}
void
fdi_seek(int drive, int track)
{
fdi_t *dev = fdi[drive];
if (fdd_doublestep_40(drive)) {
if (fdi2raw_get_tpi(dev->h) < 2)
track /= 2;
}
d86f_set_cur_track(drive, track);
if (dev->fp == NULL)
return;
if (track < 0)
track = 0;
#if 0
if (track > dev->lasttrack)
track = dev->lasttrack - 1;
#endif
dev->track = track;
read_revolution(drive);
}
void
fdi_load(int drive, char *fn)
{
char header[26];
fdi_t *dev;
writeprot[drive] = fwriteprot[drive] = 1;
/* Allocate a drive block. */
dev = (fdi_t *) malloc(sizeof(fdi_t));
if (dev == NULL) {
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
}
memset(dev, 0x00, sizeof(fdi_t));
d86f_unregister(drive);
dev->fp = plat_fopen(fn, "rb");
if (fread(header, 1, 25, dev->fp) != 25)
fatal("fdi_load(): Error reading header\n");
if (fseek(dev->fp, 0, SEEK_SET) == -1)
fatal("fdi_load(): Error seeking to the beginning of the file\n");
header[25] = 0;
if (strcmp(header, "Formatted Disk Image file") != 0) {
/* This is a Japanese FDI file. */
fdi_log("fdi_load(): Japanese FDI file detected, redirecting to IMG loader\n");
fclose(dev->fp);
free(dev);
img_load(drive, fn);
return;
}
/* Set up the drive unit. */
fdi[drive] = dev;
dev->h = fdi2raw_header(dev->fp);
dev->lasttrack = fdi2raw_get_last_track(dev->h);
dev->sides = fdi2raw_get_last_head(dev->h) + 1;
/* Attach this format to the D86F engine. */
d86f_handler[drive].disk_flags = disk_flags;
d86f_handler[drive].side_flags = side_flags;
d86f_handler[drive].writeback = null_writeback;
d86f_handler[drive].set_sector = null_set_sector;
d86f_handler[drive].write_data = null_write_data;
d86f_handler[drive].format_conditions = null_format_conditions;
d86f_handler[drive].extra_bit_cells = extra_bit_cells;
d86f_handler[drive].encoded_data = encoded_data;
d86f_handler[drive].read_revolution = read_revolution;
d86f_handler[drive].index_hole_pos = index_hole_pos;
d86f_handler[drive].get_raw_size = get_raw_size;
d86f_handler[drive].check_crc = 1;
d86f_set_version(drive, D86FVER);
d86f_common_handlers(drive);
drives[drive].seek = fdi_seek;
fdi_log("Loaded as FDI\n");
}
void
fdi_close(int drive)
{
fdi_t *dev = fdi[drive];
if (dev == NULL)
return;
d86f_unregister(drive);
drives[drive].seek = NULL;
if (dev->h)
fdi2raw_header_free(dev->h);
if (dev->fp)
fclose(dev->fp);
/* Release the memory. */
free(dev);
fdi[drive] = NULL;
}
void
fdi_set_fdc(void *fdc)
{
fdi_fdc = (fdc_t *) fdc;
}
``` | /content/code_sandbox/src/floppy/fdd_fdi.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,581 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the raw sector-based floppy image format,
* as well as the Japanese FDI, CopyQM, and FDF formats.
*
* NOTE: This file is still a disaster, needs to be cleaned up and
* re-merged with the other files. Much of it is generic to
* all formats.
*
*
*
* Authors: Sarah Walker, <path_to_url
* Miran Grca, <mgrca8@gmail.com>
* Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/config.h>
#include <86box/path.h>
#include <86box/plat.h>
#include <86box/fdd.h>
#include <86box/fdd_86f.h>
#include <86box/fdd_img.h>
#include <86box/fdc.h>
typedef struct img_t {
FILE *fp;
uint8_t track_data[2][688128];
int sectors, tracks, sides;
uint8_t sector_size;
int xdf_type; /* 0 = not XDF, 1-5 = one of the five XDF types */
int dmf;
int track;
int track_width;
uint32_t base;
uint8_t gap2_size;
uint8_t gap3_size;
uint16_t disk_flags;
uint16_t track_flags;
uint8_t sector_pos_side[256][256];
uint16_t sector_pos[256][256];
uint8_t current_sector_pos_side;
uint16_t current_sector_pos;
uint8_t *disk_data;
uint8_t is_cqm;
uint8_t disk_at_once;
uint8_t interleave;
uint8_t skew;
} img_t;
static img_t *img[FDD_NUM];
static fdc_t *img_fdc;
static double bit_rate_300;
static char *ext;
static uint8_t first_byte;
static uint8_t second_byte;
static uint8_t third_byte;
static uint8_t fourth_byte;
static uint8_t fdf_suppress_final_byte = 0; /* This is hard-coded to 0 -
* if you really need to read
* those NT 3.1 Beta floppy
* images, change this to 1
* and recompile.
*/
const uint8_t dmf_r[21] = { 12, 2, 13, 3, 14, 4, 15, 5, 16, 6, 17, 7, 18, 8, 19, 9, 20, 10, 21, 11, 1 };
static const uint8_t xdf_logical_sectors[2][2] = { { 38, 6 }, { 46, 8 } };
const uint8_t xdf_physical_sectors[2][2] = { { 16, 3 }, { 19, 4 } };
const uint8_t xdf_gap3_sizes[2][2] = { { 60, 69 }, { 60, 50 } };
const uint16_t xdf_trackx_spos[2][8] = { { 0xA7F, 0xF02, 0x11B7, 0xB66, 0xE1B, 0x129E }, { 0x302, 0x7E2, 0xA52, 0x12DA, 0x572, 0xDFA, 0x106A, 0x154A } };
/* XDF: Layout of the sectors in the image. */
const xdf_sector_t xdf_img_layout[2][2][46] = {
{
{
{0x8100}, {0x8200}, {0x8300}, {0x8400}, {0x8500}, {0x8600}, {0x8700}, {0x8800},
{0x8101}, {0x8201}, {0x0100}, {0x0200}, {0x0300}, {0x0400}, {0x0500}, {0x0600},
{0x0700}, {0x0800}, { 0},
{0x8301}, {0x8401}, {0x8501}, {0x8601}, {0x8701}, {0x8801}, {0x8901}, {0x8A01},
{0x8B01}, {0x8C01}, {0x8D01}, {0x8E01}, {0x8F01}, {0x9001}, { 0}, { 0},
{ 0}, { 0}, { 0}
},
{ {0x8300}, {0x8600}, {0x8201}, {0x8200}, {0x8601}, {0x8301} }
}, /* 5.25" 2HD */
{
{
{0x8100}, {0x8200}, {0x8300}, {0x8400}, {0x8500}, {0x8600}, {0x8700}, {0x8800},
{0x8900}, {0x8A00}, {0x8B00}, {0x8101}, {0x0100}, {0x0200}, {0x0300}, {0x0400},
{0x0500}, {0x0600}, {0x0700}, {0x0800}, { 0}, { 0}, { 0},
{0x8201}, {0x8301}, {0x8401}, {0x8501}, {0x8601}, {0x8701}, {0x8801}, {0x8901},
{0x8A01}, {0x8B01}, {0x8C01}, {0x8D01}, {0x8E01}, {0x8F01}, { 0}, { 0},
{ 0}, { 0}, { 0}, {0x9001}, {0x9101}, {0x9201}, {0x9301}
},
{ {0x8300}, {0x8400}, {0x8601}, {0x8200}, {0x8201}, {0x8600}, {0x8401}, {0x8301} }
} /* 3.5" 2HD */
};
/* XDF: Layout of the sectors on the disk's track. */
const xdf_sector_t xdf_disk_layout[2][2][38] = {
{
{
{0x0100}, {0x0200}, {0x8100}, {0x8800}, {0x8200}, {0x0300}, {0x8300}, {0x0400},
{0x8400}, {0x0500}, {0x8500}, {0x0600}, {0x8600}, {0x0700}, {0x8700}, {0x0800},
{0x8D01}, {0x8501}, {0x8E01}, {0x8601}, {0x8F01}, {0x8701}, {0x9001}, {0x8801},
{0x8101}, {0x8901}, {0x8201}, {0x8A01}, {0x8301}, {0x8B01}, {0x8401}, {0x8C01}
},
{ {0x8300}, {0x8200}, {0x8600}, {0x8201}, {0x8301}, {0x8601} }
}, /* 5.25" 2HD */
{
{
{0x0100}, {0x8A00}, {0x8100}, {0x8B00}, {0x8200}, {0x0200}, {0x8300}, {0x0300},
{0x8400}, {0x0400}, {0x8500}, {0x0500}, {0x8600}, {0x0600}, {0x8700}, {0x0700},
{0x8800}, {0x0800}, {0x8900},
{0x9001}, {0x8701}, {0x9101}, {0x8801}, {0x9201}, {0x8901}, {0x9301}, {0x8A01},
{0x8101}, {0x8B01}, {0x8201}, {0x8C01}, {0x8301}, {0x8D01}, {0x8401}, {0x8E01},
{0x8501}, {0x8F01}, {0x8601}
},
{ {0x8300}, {0x8200}, {0x8400}, {0x8600}, {0x8401}, {0x8201}, {0x8301}, {0x8601} },
}, /* 3.5" 2HD */
};
/* First dimension is possible sector sizes (0 = 128, 7 = 16384), second is possible bit rates (250/360, 250, 300, 500/360, 500, 1000). */
/* Disks formatted at 250 kbps @ 360 RPM can be read with a 360 RPM single-RPM 5.25" drive by setting the rate to 250 kbps.
Disks formatted at 300 kbps @ 300 RPM can be read with any 300 RPM single-RPM drive by setting the rate rate to 300 kbps. */
static const uint8_t maximum_sectors[8][6] = {
{ 26, 31, 38, 53, 64, 118 }, /* 128 */
{ 15, 19, 23, 32, 38, 73 }, /* 256 */
{ 7, 10, 12, 17, 22, 41 }, /* 512 */
{ 3, 5, 6, 9, 11, 22 }, /* 1024 */
{ 2, 2, 3, 4, 5, 11 }, /* 2048 */
{ 1, 1, 1, 2, 2, 5 }, /* 4096 */
{ 0, 0, 0, 1, 1, 3 }, /* 8192 */
{ 0, 0, 0, 0, 0, 1 } /* 16384 */
};
static const uint8_t xdf_sectors[8][6] = {
{ 0, 0, 0, 0, 0, 0 }, /* 128 */
{ 0, 0, 0, 0, 0, 0 }, /* 256 */
{ 0, 0, 0, 19, 23, 0 }, /* 512 */
{ 0, 0, 0, 0, 0, 0 }, /* 1024 */
{ 0, 0, 0, 0, 0, 0 }, /* 2048 */
{ 0, 0, 0, 0, 0, 0 }, /* 4096 */
{ 0, 0, 0, 0, 0, 0 }, /* 8192 */
{ 0, 0, 0, 0, 0, 0 } /* 16384 */
};
static const uint8_t xdf_types[8][6] = {
{ 0, 0, 0, 0, 0, 0 }, /* 128 */
{ 0, 0, 0, 0, 0, 0 }, /* 256 */
{ 0, 0, 0, 1, 2, 0 }, /* 512 */
{ 0, 0, 0, 0, 0, 0 }, /* 1024 */
{ 0, 0, 0, 0, 0, 0 }, /* 2048 */
{ 0, 0, 0, 0, 0, 0 }, /* 4096 */
{ 0, 0, 0, 0, 0, 0 }, /* 8192 */
{ 0, 0, 0, 0, 0, 0 } /* 16384 */
};
static const double bit_rates_300[6] = { (250.0 * 300.0) / 360.0, 250.0, 300.0, (500.0 * 300.0) / 360.0, 500.0, 1000.0 };
static const uint8_t rates[6] = { 2, 2, 1, 4, 0, 3 };
static const uint8_t holes[6] = { 0, 0, 0, 1, 1, 2 };
const int gap3_sizes[5][8][48] = {
{
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [0][0] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
},
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [0][1] */
0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [0][2] */
0x00, 0x00, 0x6C, 0x48, 0x2A, 0x08, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x83, 0x26, 0x00, 0x00, 0x00, 0x00, /* [0][3] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [0][4] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [0][5] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [0][6] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [0][7] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
},
{
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [1][0] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [1][1] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x1C, 0x0E, 0x00, 0x00, /* [1][2] */
0x00, 0x00, 0x6C, 0x48, 0x2A, 0x08, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [1][3] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [1][4] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [1][5] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [1][6] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [1][7] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
},
{
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [2][0] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x0C, 0x00, 0x00, 0x00, 0x36, /* [2][1] */
0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x50, 0x2E, 0x00, 0x00, 0x00, 0x00, 0x00, /* [2][2] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0xF0, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [2][3] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [2][4] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [2][5] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [2][6] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [2][7] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
},
{
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [3][0] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [3][1] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [3][2] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x53, 0x4E, 0x3D, 0x2C, 0x1C, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [3][3] */
0x00, 0x00, 0xF7, 0xAF, 0x6F, 0x55, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [3][4] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [3][5] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [3][6] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [3][7] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
},
{
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [4][0] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [4][1] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x92, 0x54, /* [4][2] */
0x38, 0x23, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [4][3] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [4][4] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [4][5] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [4][6] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* [4][7] */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
}
};
#ifdef ENABLE_IMG_LOG
int img_do_log = ENABLE_IMG_LOG;
static void
img_log(const char *fmt, ...)
{
va_list ap;
if (img_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define img_log(fmt, ...)
#endif
/* Generic */
static int
sector_size_code(int sector_size)
{
switch (sector_size) {
case 128:
return 0;
case 256:
return 1;
default:
case 512:
return 2;
case 1024:
return 3;
case 2048:
return 4;
case 4096:
return 5;
case 8192:
return 6;
case 16384:
return 7;
}
}
static int
bps_is_valid(uint16_t bps)
{
for (uint8_t i = 0; i <= 8; i++) {
if (bps == (128 << i))
return 1;
}
return 0;
}
static int
first_byte_is_valid(uint8_t first_byte)
{
switch (first_byte) {
case 0x60:
case 0xE9:
case 0xEB:
return 1;
default:
break;
}
return 0;
}
#define xdf_img_sector xdf_img_layout[current_xdft][!is_t0][sector]
#define xdf_disk_sector xdf_disk_layout[current_xdft][!is_t0][array_sector]
static int
interleave(int sector, int skew, int track_spt)
{
uint32_t skewed_i;
uint32_t adjusted_r;
uint32_t add = (track_spt & 1);
uint32_t adjust = (track_spt >> 1);
skewed_i = (sector + skew) % track_spt;
adjusted_r = (skewed_i >> 1) + 1;
if (skewed_i & 1)
adjusted_r += (adjust + add);
return adjusted_r;
}
static void
write_back(int drive)
{
img_t *dev = img[drive];
int ssize = 128 << ((int) dev->sector_size);
int size;
if (dev->fp == NULL)
return;
if (dev->disk_at_once)
return;
if (fseek(dev->fp, dev->base + (dev->track * dev->sectors * ssize * dev->sides), SEEK_SET) == -1)
pclog("IMG write_back(): Error seeking to the beginning of the file\n");
for (int side = 0; side < dev->sides; side++) {
size = dev->sectors * ssize;
if (fwrite(dev->track_data[side], 1, size, dev->fp) != size)
fatal("IMG write_back(): Error writing data\n");
}
}
static uint16_t
disk_flags(int drive)
{
const img_t *dev = img[drive];
return (dev->disk_flags);
}
static uint16_t
side_flags(int drive)
{
const img_t *dev = img[drive];
return (dev->track_flags);
}
static void
set_sector(int drive, UNUSED(int side), UNUSED(uint8_t c), uint8_t h, uint8_t r, UNUSED(uint8_t n))
{
img_t *dev = img[drive];
dev->current_sector_pos_side = dev->sector_pos_side[h][r];
dev->current_sector_pos = dev->sector_pos[h][r];
}
static uint8_t
poll_read_data(int drive, UNUSED(int side), uint16_t pos)
{
const img_t *dev = img[drive];
return (dev->track_data[dev->current_sector_pos_side][dev->current_sector_pos + pos]);
}
static void
poll_write_data(int drive, UNUSED(int side), uint16_t pos, uint8_t data)
{
img_t *dev = img[drive];
dev->track_data[dev->current_sector_pos_side][dev->current_sector_pos + pos] = data;
}
static int
format_conditions(int drive)
{
const img_t *dev = img[drive];
int temp = (fdc_get_format_sectors(img_fdc) == dev->sectors);
temp = temp && (fdc_get_format_n(img_fdc) == dev->sector_size);
temp = temp && (dev->xdf_type == 0);
return temp;
}
static void
img_seek(int drive, int track)
{
img_t *dev = img[drive];
int side;
int current_xdft = dev->xdf_type - 1;
int read_bytes = 0;
uint8_t id[4] = { 0, 0, 0, 0 };
int is_t0;
int sector;
int current_pos;
int img_pos;
int sr;
int sside;
int total;
int array_sector;
int buf_side;
int buf_pos;
int ssize = 128 << ((int) dev->sector_size);
uint32_t cur_pos = 0;
if (dev->fp == NULL)
return;
if (!dev->track_width && fdd_doublestep_40(drive))
track /= 2;
dev->track = track;
d86f_set_cur_track(drive, track);
is_t0 = (track == 0) ? 1 : 0;
if (!dev->disk_at_once) {
if (fseek(dev->fp, dev->base + (track * dev->sectors * ssize * dev->sides), SEEK_SET) == -1)
fatal("img_seek(): Error seeking\n");
}
for (side = 0; side < dev->sides; side++) {
if (dev->disk_at_once) {
cur_pos = (track * dev->sectors * ssize * dev->sides) + (side * dev->sectors * ssize);
memcpy(dev->track_data[side], dev->disk_data + cur_pos, (size_t) dev->sectors * ssize);
} else {
read_bytes = fread(dev->track_data[side], 1, (size_t) dev->sectors * ssize, dev->fp);
if (read_bytes < (dev->sectors * ssize))
memset(dev->track_data[side] + read_bytes, 0xf6, (dev->sectors * ssize) - read_bytes);
}
}
d86f_reset_index_hole_pos(drive, 0);
d86f_reset_index_hole_pos(drive, 1);
d86f_destroy_linked_lists(drive, 0);
d86f_destroy_linked_lists(drive, 1);
if (track > dev->tracks) {
d86f_zero_track(drive);
return;
}
if (!dev->xdf_type || dev->is_cqm) {
for (side = 0; side < dev->sides; side++) {
current_pos = d86f_prepare_pretrack(drive, side, 0);
for (sector = 0; sector < dev->sectors; sector++) {
if (dev->is_cqm) {
if (dev->interleave)
sr = interleave(sector, dev->skew, dev->sectors);
else {
sr = sector + 1;
sr += dev->skew;
if (sr > dev->sectors)
sr -= dev->sectors;
}
} else {
if (dev->gap3_size < 68)
sr = interleave(sector, 1, dev->sectors);
else
sr = dev->dmf ? (dmf_r[sector]) : (sector + 1);
}
id[0] = track;
id[1] = side;
id[2] = sr;
id[3] = dev->sector_size;
dev->sector_pos_side[side][sr] = side;
dev->sector_pos[side][sr] = (sr - 1) * ssize;
current_pos = d86f_prepare_sector(drive, side, current_pos, id, &dev->track_data[side][(sr - 1) * ssize], ssize, dev->gap2_size, dev->gap3_size, 0);
if (sector == 0)
d86f_initialize_last_sector_id(drive, id[0], id[1], id[2], id[3]);
}
}
} else {
total = dev->sectors;
img_pos = 0;
sside = 0;
/* Pass 1, get sector positions in the image. */
for (sector = 0; sector < xdf_logical_sectors[current_xdft][!is_t0]; sector++) {
if (is_t0) {
img_pos = (sector % total) << 9;
sside = (sector >= total) ? 1 : 0;
}
if (xdf_img_sector.word) {
dev->sector_pos_side[xdf_img_sector.id.h][xdf_img_sector.id.r] = sside;
dev->sector_pos[xdf_img_sector.id.h][xdf_img_sector.id.r] = img_pos;
}
if (!is_t0) {
img_pos += (128 << (xdf_img_sector.id.r & 7));
if (img_pos >= (total << 9))
sside = 1;
img_pos %= (total << 9);
}
}
/* Pass 2, prepare the actual track. */
for (side = 0; side < dev->sides; side++) {
current_pos = d86f_prepare_pretrack(drive, side, 0);
for (sector = 0; sector < xdf_physical_sectors[current_xdft][!is_t0]; sector++) {
array_sector = (side * xdf_physical_sectors[current_xdft][!is_t0]) + sector;
buf_side = dev->sector_pos_side[xdf_disk_sector.id.h][xdf_disk_sector.id.r];
buf_pos = dev->sector_pos[xdf_disk_sector.id.h][xdf_disk_sector.id.r];
id[0] = track;
id[1] = xdf_disk_sector.id.h;
id[2] = xdf_disk_sector.id.r;
if (is_t0) {
id[3] = 2;
current_pos = d86f_prepare_sector(drive, side, current_pos, id, &dev->track_data[buf_side][buf_pos], ssize, dev->gap2_size, xdf_gap3_sizes[current_xdft][!is_t0], 0);
} else {
id[3] = id[2] & 7;
ssize = (128 << id[3]);
current_pos = d86f_prepare_sector(drive, side, xdf_trackx_spos[current_xdft][array_sector], id, &dev->track_data[buf_side][buf_pos], ssize, dev->gap2_size, xdf_gap3_sizes[current_xdft][!is_t0], 0);
}
if (sector == 0)
d86f_initialize_last_sector_id(drive, id[0], id[1], id[2], id[3]);
}
}
}
}
void
img_init(void)
{
memset(img, 0x00, sizeof(img));
}
int
is_divisible(uint16_t total, uint8_t what)
{
if ((total != 0) && (what != 0))
return ((total % what) == 0);
else
return 0;
}
void
img_load(int drive, char *fn)
{
uint16_t bpb_bps;
uint16_t bpb_total;
uint8_t bpb_mid; /* Media type ID. */
uint8_t bpb_sectors;
uint8_t bpb_sides;
uint8_t cqm;
uint8_t ddi;
uint8_t fdf;
uint8_t fdi;
uint16_t comment_len = 0;
int16_t block_len = 0;
uint32_t cur_pos = 0;
uint8_t rep_byte = 0;
uint8_t run = 0;
uint8_t real_run = 0;
uint8_t *bpos;
uint16_t track_bytes = 0;
uint8_t *literal;
img_t *dev;
int temp_rate = 0;
int guess = 0;
int size;
ext = path_get_extension(fn);
d86f_unregister(drive);
writeprot[drive] = 0;
/* Allocate a drive block. */
dev = (img_t *) malloc(sizeof(img_t));
memset(dev, 0x00, sizeof(img_t));
dev->fp = plat_fopen(fn, "rb+");
if (dev->fp == NULL) {
dev->fp = plat_fopen(fn, "rb");
if (dev->fp == NULL) {
free(dev);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
}
writeprot[drive] = 1;
}
if (ui_writeprot[drive])
writeprot[drive] = 1;
fwriteprot[drive] = writeprot[drive];
cqm = ddi = fdf = fdi = 0;
dev->interleave = dev->skew = 0;
if (!strcasecmp(ext, "DDI")) {
ddi = 1;
dev->base = 0x2400;
} else
dev->base = 0;
if (!strcasecmp(ext, "FDI")) {
/* This is a Japanese FDI image, so let's read the header */
img_log("img_load(): File is a Japanese FDI image...\n");
fseek(dev->fp, 0x10, SEEK_SET);
(void) !fread(&bpb_bps, 1, 2, dev->fp);
fseek(dev->fp, 0x0C, SEEK_SET);
(void) !fread(&size, 1, 4, dev->fp);
bpb_total = size / bpb_bps;
fseek(dev->fp, 0x08, SEEK_SET);
(void) !fread(&(dev->base), 1, 4, dev->fp);
fseek(dev->fp, dev->base + 0x15, SEEK_SET);
bpb_mid = fgetc(dev->fp);
if (bpb_mid < 0xF0)
bpb_mid = 0xF0;
fseek(dev->fp, 0x14, SEEK_SET);
bpb_sectors = fgetc(dev->fp);
fseek(dev->fp, 0x18, SEEK_SET);
bpb_sides = fgetc(dev->fp);
fseek(dev->fp, dev->base, SEEK_SET);
first_byte = fgetc(dev->fp);
fdi = 1;
cqm = 0;
dev->disk_at_once = 0;
fdf = 0;
} else {
/* Read the first four bytes. */
fseek(dev->fp, 0x00, SEEK_SET);
first_byte = fgetc(dev->fp);
fseek(dev->fp, 0x01, SEEK_SET);
second_byte = fgetc(dev->fp);
fseek(dev->fp, 0x02, SEEK_SET);
third_byte = fgetc(dev->fp);
fseek(dev->fp, 0x03, SEEK_SET);
fourth_byte = fgetc(dev->fp);
if ((first_byte == 0x1A) && (second_byte == 'F') && (third_byte == 'D') && (fourth_byte == 'F')) {
/* This is a FDF image. */
img_log("img_load(): File is a FDF image...\n");
fwriteprot[drive] = writeprot[drive] = 1;
fclose(dev->fp);
dev->fp = plat_fopen(fn, "rb");
fdf = 1;
cqm = 0;
dev->disk_at_once = 1;
fseek(dev->fp, 0x50, SEEK_SET);
(void) !fread(&dev->tracks, 1, 4, dev->fp);
/* Decode the entire file - pass 1, no write to buffer, determine length. */
fseek(dev->fp, 0x80, SEEK_SET);
size = 0;
track_bytes = 0;
bpos = dev->disk_data;
while (!feof(dev->fp)) {
if (!track_bytes) {
/* Skip first 3 bytes - their meaning is unknown to us but could be a checksum. */
first_byte = fgetc(dev->fp);
(void) !fread(&track_bytes, 1, 2, dev->fp);
img_log("Block header: %02X %04X ", first_byte, track_bytes);
/* Read the length of encoded data block. */
(void) !fread(&track_bytes, 1, 2, dev->fp);
img_log("%04X\n", track_bytes);
}
if (feof(dev->fp))
break;
if (first_byte == 0xFF)
break;
if (first_byte) {
run = fgetc(dev->fp);
/* I *HAVE* to read something because fseek tries to be smart and never hits EOF, causing an infinite loop. */
track_bytes--;
if (run & 0x80) {
/* Repeat. */
track_bytes--;
rep_byte = fgetc(dev->fp);
} else {
/* Literal. */
track_bytes -= (run & 0x7f);
literal = (uint8_t *) malloc(run & 0x7f);
(void) !fread(literal, 1, (run & 0x7f), dev->fp);
free(literal);
}
size += (run & 0x7f);
if (!track_bytes)
size -= fdf_suppress_final_byte;
} else {
/* Literal block. */
size += (track_bytes - fdf_suppress_final_byte);
literal = (uint8_t *) malloc(track_bytes);
(void) !fread(literal, 1, track_bytes, dev->fp);
free(literal);
track_bytes = 0;
}
if (feof(dev->fp))
break;
}
/* Allocate the buffer. */
dev->disk_data = (uint8_t *) malloc(size);
/* Decode the entire file - pass 2, write to buffer. */
fseek(dev->fp, 0x80, SEEK_SET);
track_bytes = 0;
bpos = dev->disk_data;
while (!feof(dev->fp)) {
if (!track_bytes) {
/* Skip first 3 bytes - their meaning is unknown to us but could be a checksum. */
first_byte = fgetc(dev->fp);
(void) !fread(&track_bytes, 1, 2, dev->fp);
img_log("Block header: %02X %04X ", first_byte, track_bytes);
/* Read the length of encoded data block. */
(void) !fread(&track_bytes, 1, 2, dev->fp);
img_log("%04X\n", track_bytes);
}
if (feof(dev->fp))
break;
if (first_byte == 0xFF)
break;
if (first_byte) {
run = fgetc(dev->fp);
real_run = (run & 0x7f);
/* I *HAVE* to read something because fseek tries to be smart and never hits EOF, causing an infinite loop. */
track_bytes--;
if (run & 0x80) {
/* Repeat. */
track_bytes--;
if (!track_bytes)
real_run -= fdf_suppress_final_byte;
rep_byte = fgetc(dev->fp);
if (real_run)
memset(bpos, rep_byte, real_run);
} else {
/* Literal. */
track_bytes -= real_run;
literal = (uint8_t *) malloc(real_run);
(void) !fread(literal, 1, real_run, dev->fp);
if (!track_bytes)
real_run -= fdf_suppress_final_byte;
if (run & 0x7f)
memcpy(bpos, literal, real_run);
free(literal);
}
bpos += real_run;
} else {
/* Literal block. */
literal = (uint8_t *) malloc(track_bytes);
(void) !fread(literal, 1, track_bytes, dev->fp);
memcpy(bpos, literal, track_bytes - fdf_suppress_final_byte);
free(literal);
bpos += (track_bytes - fdf_suppress_final_byte);
track_bytes = 0;
}
if (feof(dev->fp))
break;
}
first_byte = *dev->disk_data;
bpb_bps = *(uint16_t *) (dev->disk_data + 0x0B);
bpb_total = *(uint16_t *) (dev->disk_data + 0x13);
bpb_mid = *(dev->disk_data + 0x15);
bpb_sectors = *(dev->disk_data + 0x18);
bpb_sides = *(dev->disk_data + 0x1A);
/* Jump ahead to determine the image's geometry. */
goto jump_if_fdf;
}
if (((first_byte == 'C') && (second_byte == 'Q')) || ((first_byte == 'c') && (second_byte == 'q'))) {
img_log("img_load(): File is a CopyQM image...\n");
fwriteprot[drive] = writeprot[drive] = 1;
fclose(dev->fp);
dev->fp = plat_fopen(fn, "rb");
fseek(dev->fp, 0x03, SEEK_SET);
(void) !fread(&bpb_bps, 1, 2, dev->fp);
#if 0
fseek(dev->fp, 0x0B, SEEK_SET);
(void) !fread(&bpb_total, 1, 2, dev->fp);
#endif
fseek(dev->fp, 0x10, SEEK_SET);
bpb_sectors = fgetc(dev->fp);
fseek(dev->fp, 0x12, SEEK_SET);
bpb_sides = fgetc(dev->fp);
fseek(dev->fp, 0x5B, SEEK_SET);
dev->tracks = fgetc(dev->fp);
bpb_total = ((uint16_t) bpb_sectors) * ((uint16_t) bpb_sides) * dev->tracks;
fseek(dev->fp, 0x74, SEEK_SET);
dev->interleave = fgetc(dev->fp);
fseek(dev->fp, 0x76, SEEK_SET);
dev->skew = fgetc(dev->fp);
dev->disk_data = (uint8_t *) malloc(((uint32_t) bpb_total) * ((uint32_t) bpb_bps));
memset(dev->disk_data, 0xf6, ((uint32_t) bpb_total) * ((uint32_t) bpb_bps));
fseek(dev->fp, 0x6F, SEEK_SET);
(void) !fread(&comment_len, 1, 2, dev->fp);
fseek(dev->fp, -1, SEEK_END);
size = ftell(dev->fp) + 1;
fseek(dev->fp, 133 + comment_len, SEEK_SET);
cur_pos = 0;
while (!feof(dev->fp)) {
(void) !fread(&block_len, 1, 2, dev->fp);
if (!feof(dev->fp)) {
if (block_len < 0) {
rep_byte = fgetc(dev->fp);
block_len = -block_len;
if ((cur_pos + block_len) > ((uint32_t) bpb_total) * ((uint32_t) bpb_bps)) {
block_len = ((uint32_t) bpb_total) * ((uint32_t) bpb_bps) - cur_pos;
memset(dev->disk_data + cur_pos, rep_byte, block_len);
break;
} else {
memset(dev->disk_data + cur_pos, rep_byte, block_len);
cur_pos += block_len;
}
} else if (block_len > 0) {
if ((cur_pos + block_len) > ((uint32_t) bpb_total) * ((uint32_t) bpb_bps)) {
block_len = ((uint32_t) bpb_total) * ((uint32_t) bpb_bps) - cur_pos;
(void) !fread(dev->disk_data + cur_pos, 1, block_len, dev->fp);
break;
} else {
(void) !fread(dev->disk_data + cur_pos, 1, block_len, dev->fp);
cur_pos += block_len;
}
}
}
}
img_log("Finished reading CopyQM image data\n");
cqm = 1;
dev->disk_at_once = 1;
fdf = 0;
first_byte = *dev->disk_data;
} else {
dev->disk_at_once = 0;
/* Read the BPB */
if (ddi) {
img_log("img_load(): File is a DDI image...\n");
fwriteprot[drive] = writeprot[drive] = 1;
} else
img_log("img_load(): File is a raw image...\n");
fseek(dev->fp, dev->base + 0x0B, SEEK_SET);
(void) !fread(&bpb_bps, 1, 2, dev->fp);
fseek(dev->fp, dev->base + 0x13, SEEK_SET);
(void) !fread(&bpb_total, 1, 2, dev->fp);
fseek(dev->fp, dev->base + 0x15, SEEK_SET);
bpb_mid = fgetc(dev->fp);
fseek(dev->fp, dev->base + 0x18, SEEK_SET);
bpb_sectors = fgetc(dev->fp);
fseek(dev->fp, dev->base + 0x1A, SEEK_SET);
bpb_sides = fgetc(dev->fp);
cqm = 0;
}
fseek(dev->fp, -1, SEEK_END);
size = ftell(dev->fp) + 1;
if (ddi)
size -= 0x2400;
jump_if_fdf:
if (!ddi)
dev->base = 0;
fdi = 0;
}
dev->sides = 2;
dev->sector_size = 2;
img_log("BPB reports %i sides and %i bytes per sector (%i sectors total)\n",
bpb_sides, bpb_bps, bpb_total);
/* Invalid conditions: */
guess = (bpb_sides < 1); /* Sides < 1; */
guess = guess || (bpb_sides > 2); /* Sides > 2; */
guess = guess || !bps_is_valid(bpb_bps); /* Invalid number of bytes per sector; */
guess = guess || !first_byte_is_valid(first_byte); /* Invalid first bytes; */
guess = guess || !is_divisible(bpb_total, bpb_sectors); /* Total sectors not divisible by sectors per track; */
guess = guess || !is_divisible(bpb_total, bpb_sides); /* Total sectors not divisible by sides. */
guess = guess || !fdd_get_check_bpb(drive);
guess = guess && !fdi;
guess = guess && !cqm;
if (guess) {
/*
* The BPB is giving us a wacky number of sides and/or bytes
* per sector, therefore it is most probably not a BPB at all,
* so we have to guess the parameters from file size.
*/
if (size <= (160 * 1024)) {
dev->sectors = 8;
dev->tracks = 40;
dev->sides = 1;
} else if (size <= (180 * 1024)) {
dev->sectors = 9;
dev->tracks = 40;
dev->sides = 1;
} else if (size <= (315 * 1024)) {
dev->sectors = 9;
dev->tracks = 70;
dev->sides = 1;
} else if (size <= (320 * 1024)) {
dev->sectors = 8;
dev->tracks = 40;
} else if (size <= (360 * 1024)) { /*DD 360K*/
dev->sectors = 9;
dev->tracks = 40;
} else if (size <= (400 * 1024)) { /*DEC RX50*/
dev->sectors = 10;
dev->tracks = 80;
dev->sides = 1;
} else if (size <= (640 * 1024)) { /*DD 640K*/
dev->sectors = 8;
dev->tracks = 80;
} else if (size <= (720 * 1024)) { /*DD 720K*/
dev->sectors = 9;
dev->tracks = 80;
} else if (size <= (800 * 1024)) { /*DD*/
dev->sectors = 10;
dev->tracks = 80;
} else if (size <= (880 * 1024)) { /*DD*/
dev->sectors = 11;
dev->tracks = 80;
} else if (size <= (960 * 1024)) { /*DD*/
dev->sectors = 12;
dev->tracks = 80;
} else if (size <= (1040 * 1024)) { /*DD*/
dev->sectors = 13;
dev->tracks = 80;
} else if (size <= (1120 * 1024)) { /*DD*/
dev->sectors = 14;
dev->tracks = 80;
} else if (size <= 1228800) { /*HD 1.2MB*/
dev->sectors = 15;
dev->tracks = 80;
} else if (size <= 1261568) { /*HD 1.25MB Japanese*/
dev->sectors = 8;
dev->tracks = 77;
dev->sector_size = 3;
} else if (size <= 1474560) { /*HD 1.44MB*/
dev->sectors = 18;
dev->tracks = 80;
} else if (size <= 1556480) { /*HD*/
dev->sectors = 19;
dev->tracks = 80;
} else if (size <= 1638400) { /*HD 1024 sector*/
dev->sectors = 10;
dev->tracks = 80;
dev->sector_size = 3;
} else if (size <= 1720320) { /*DMF (Windows 95) */
dev->sectors = 21;
dev->tracks = 80;
} else if (size <= 1741824) {
dev->sectors = 21;
dev->tracks = 81;
} else if (size <= 1763328) {
dev->sectors = 21;
dev->tracks = 82;
} else if (size <= 1802240) { /*HD 1024 sector*/
dev->sectors = 22;
dev->tracks = 80;
dev->sector_size = 3;
} else if (size == 1884160) { /*XDF (OS/2 Warp)*/
dev->sectors = 23;
dev->tracks = 80;
} else if (size <= 2949120) { /*ED*/
dev->sectors = 36;
dev->tracks = 80;
} else if (size <= 3194880) { /*ED*/
dev->sectors = 39;
dev->tracks = 80;
} else if (size <= 3276800) { /*ED*/
dev->sectors = 40;
dev->tracks = 80;
} else if (size <= 3358720) { /*ED, maximum possible size*/
dev->sectors = 41;
dev->tracks = 80;
} else if (size <= 3440640) { /*ED, maximum possible size*/
dev->sectors = 42;
dev->tracks = 80;
#if 0
} else if (size <= 3440640) { /*HD 1024 sector*/
dev->sectors = 21;
dev->tracks = 80;
dev->sector_size = 3;
#endif
} else if (size <= 3604480) { /*HD 1024 sector*/
dev->sectors = 22;
dev->tracks = 80;
dev->sector_size = 3;
} else if (size <= 3610624) { /*ED, maximum possible size*/
dev->sectors = 41;
dev->tracks = 86;
} else if (size <= 3698688) { /*ED, maximum possible size*/
dev->sectors = 42;
dev->tracks = 86;
} else {
img_log("Image is bigger than can fit on an ED floppy, ejecting...\n");
fclose(dev->fp);
free(dev);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
}
bpb_sides = dev->sides;
bpb_sectors = dev->sectors;
bpb_total = size >> (dev->sector_size + 7);
} else {
/* The BPB readings appear to be valid, so let's set the values. */
if (fdi) {
/* The image is a Japanese FDI, therefore we read the number of tracks from the header. */
if (fseek(dev->fp, 0x1C, SEEK_SET) == -1)
fatal("Japanese FDI: Failed when seeking to 0x1C\n");
(void) !fread(&(dev->tracks), 1, 4, dev->fp);
} else {
if (!cqm && !fdf) {
/* Number of tracks = number of total sectors divided by sides times sectors per track. */
dev->tracks = ((uint32_t) bpb_total) / (((uint32_t) bpb_sides) * ((uint32_t) bpb_sectors));
}
}
/* The rest we just set directly from the BPB. */
dev->sectors = bpb_sectors;
dev->sides = bpb_sides;
/* The sector size. */
dev->sector_size = sector_size_code(bpb_bps);
temp_rate = 0xFF;
}
for (uint8_t i = 0; i < 6; i++) {
if ((dev->sectors <= maximum_sectors[dev->sector_size][i]) || (dev->sectors == xdf_sectors[dev->sector_size][i])) {
bit_rate_300 = bit_rates_300[i];
temp_rate = rates[i];
dev->disk_flags = holes[i] << 1;
dev->xdf_type = (dev->sectors == xdf_sectors[dev->sector_size][i]) ? xdf_types[dev->sector_size][i] : 0;
if ((bit_rate_300 == 500.0) && (dev->sectors == 21) && (dev->sector_size == 2) && (dev->tracks >= 80) && (dev->tracks <= 82) && (dev->sides == 2)) {
/* This is a DMF floppy, set the flag so we know to interleave the sectors. */
dev->dmf = 1;
} else {
if ((bit_rate_300 == 500.0) && (dev->sectors == 22) && (dev->sector_size == 2) && (dev->tracks >= 80) && (dev->tracks <= 82) && (dev->sides == 2)) {
/* This is marked specially because of the track flag (a RPM slow down is needed). */
dev->interleave = 2;
}
dev->dmf = 0;
}
img_log("Image parameters: bit rate 300: %f, temporary rate: %i, hole: %i, DMF: %i, XDF type: %i\n", bit_rate_300, temp_rate, dev->disk_flags >> 1, dev->dmf, dev->xdf_type);
break;
}
}
if (temp_rate == 0xFF) {
img_log("Image is bigger than can fit on an ED floppy, ejecting...\n");
fclose(dev->fp);
free(dev);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
}
dev->gap2_size = (temp_rate == 3) ? 41 : 22;
if (dev->dmf)
dev->gap3_size = 8;
else {
if (dev->sectors == -1)
dev->gap3_size = 8;
else
dev->gap3_size = gap3_sizes[temp_rate][dev->sector_size][dev->sectors];
}
if (!dev->gap3_size) {
img_log("ERROR: Floppy image of unknown format was inserted into drive %c:!\n", drive + 0x41);
fclose(dev->fp);
free(dev);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
}
dev->track_width = 0;
if (dev->tracks > 43)
dev->track_width = 1; /* If the image has more than 43 tracks, then the tracks are thin (96 tpi). */
if (dev->sides == 2)
dev->disk_flags |= 8; /* If the has 2 sides, mark it as such. */
if (dev->interleave == 2) {
dev->interleave = 1;
dev->disk_flags |= 0x60;
}
dev->track_flags = 0x08; /* IMG files are always assumed to be MFM-encoded. */
dev->track_flags |= temp_rate & 3; /* Data rate. */
if (temp_rate & 4)
dev->track_flags |= 0x20; /* RPM. */
dev->is_cqm = cqm;
img_log("Disk flags: %i, track flags: %i\n",
dev->disk_flags, dev->track_flags);
/* Set up the drive unit. */
img[drive] = dev;
/* Attach this format to the D86F engine. */
d86f_handler[drive].disk_flags = disk_flags;
d86f_handler[drive].side_flags = side_flags;
d86f_handler[drive].writeback = write_back;
d86f_handler[drive].set_sector = set_sector;
d86f_handler[drive].read_data = poll_read_data;
d86f_handler[drive].write_data = poll_write_data;
d86f_handler[drive].format_conditions = format_conditions;
d86f_handler[drive].extra_bit_cells = null_extra_bit_cells;
d86f_handler[drive].encoded_data = common_encoded_data;
d86f_handler[drive].read_revolution = common_read_revolution;
d86f_handler[drive].index_hole_pos = null_index_hole_pos;
d86f_handler[drive].get_raw_size = common_get_raw_size;
d86f_handler[drive].check_crc = 1;
d86f_set_version(drive, 0x0063);
drives[drive].seek = img_seek;
d86f_common_handlers(drive);
}
void
img_close(int drive)
{
img_t *dev = img[drive];
if (dev == NULL)
return;
d86f_unregister(drive);
if (dev->fp != NULL) {
fclose(dev->fp);
dev->fp = NULL;
}
if (dev->disk_data != NULL)
free(dev->disk_data);
/* Release the memory. */
free(dev);
img[drive] = NULL;
}
void
img_set_fdc(void *fdc)
{
img_fdc = (fdc_t *) fdc;
}
``` | /content/code_sandbox/src/floppy/fdd_img.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 22,522 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the IMD floppy image format.
*
*
*
* Authors: Fred N. van Kempen, <decwiz@yahoo.com>
* Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/plat.h>
#include <86box/fdd.h>
#include <86box/fdd_86f.h>
#include <86box/fdd_imd.h>
#include <86box/fdc.h>
typedef struct imd_track_t {
uint8_t is_present;
uint32_t file_offs;
uint8_t params[5];
uint32_t r_map_offs;
uint32_t c_map_offs;
uint32_t h_map_offs;
uint32_t n_map_offs;
uint32_t data_offs;
uint32_t sector_data_offs[255];
uint32_t sector_data_size[255];
uint32_t gap3_len;
uint16_t side_flags;
uint8_t max_sector_size;
uint8_t spt;
} imd_track_t;
typedef struct imd_t {
FILE *fp;
char *buffer;
uint32_t start_offs;
int track_count;
int sides;
int track;
uint16_t disk_flags;
int track_width;
imd_track_t tracks[256][2];
uint16_t current_side_flags[2];
uint8_t xdf_ordered_pos[256][2];
uint8_t interleave_ordered_pos[256][2];
char *current_data[2];
uint8_t track_buffer[2][25000];
} imd_t;
static imd_t *imd[FDD_NUM];
static fdc_t *imd_fdc;
#ifdef ENABLE_IMD_LOG
int imd_do_log = ENABLE_IMD_LOG;
static void
imd_log(const char *fmt, ...)
{
va_list ap;
if (imd_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define imd_log(fmt, ...)
#endif
static uint32_t
get_raw_tsize(int side_flags, int slower_rpm)
{
uint32_t size;
switch (side_flags & 0x27) {
case 0x22:
size = slower_rpm ? 5314 : 5208;
break;
default:
case 0x02:
case 0x21:
size = slower_rpm ? 6375 : 6250;
break;
case 0x01:
size = slower_rpm ? 7650 : 7500;
break;
case 0x20:
size = slower_rpm ? 10629 : 10416;
break;
case 0x00:
size = slower_rpm ? 12750 : 12500;
break;
case 0x23:
size = slower_rpm ? 21258 : 20833;
break;
case 0x03:
size = slower_rpm ? 25500 : 25000;
break;
case 0x25:
size = slower_rpm ? 42517 : 41666;
break;
case 0x05:
size = slower_rpm ? 51000 : 50000;
break;
}
return size;
}
static int
track_is_xdf(int drive, int side, int track)
{
imd_t *dev = imd[drive];
int effective_sectors;
int xdf_sectors;
int high_sectors;
int low_sectors;
int max_high_id;
int expected_high_count;
int expected_low_count;
const uint8_t *r_map;
const uint8_t *n_map;
effective_sectors = xdf_sectors = high_sectors = low_sectors = 0;
for (uint16_t i = 0; i < 256; i++)
dev->xdf_ordered_pos[i][side] = 0;
if (dev->tracks[track][side].params[2] & 0xC0)
return 0;
if ((dev->tracks[track][side].params[3] != 16) && (dev->tracks[track][side].params[3] != 19))
return 0;
r_map = (uint8_t *) (dev->buffer + dev->tracks[track][side].r_map_offs);
if (!track) {
if (dev->tracks[track][side].params[4] != 2)
return 0;
if (!side) {
max_high_id = (dev->tracks[track][side].params[3] == 19) ? 0x8B : 0x88;
expected_high_count = (dev->tracks[track][side].params[3] == 19) ? 0x0B : 0x08;
expected_low_count = 8;
} else {
max_high_id = (dev->tracks[track][side].params[3] == 19) ? 0x93 : 0x90;
expected_high_count = (dev->tracks[track][side].params[3] == 19) ? 0x13 : 0x10;
expected_low_count = 0;
}
for (uint8_t i = 0; i < dev->tracks[track][side].params[3]; i++) {
if ((r_map[i] >= 0x81) && (r_map[i] <= max_high_id)) {
high_sectors++;
dev->xdf_ordered_pos[(int) r_map[i]][side] = i;
}
if ((r_map[i] >= 0x01) && (r_map[i] <= 0x08)) {
low_sectors++;
dev->xdf_ordered_pos[(int) r_map[i]][side] = i;
}
if ((high_sectors == expected_high_count) && (low_sectors == expected_low_count)) {
dev->current_side_flags[side] = (dev->tracks[track][side].params[3] == 19) ? 0x08 : 0x28;
return ((dev->tracks[track][side].params[3] == 19) ? 2 : 1);
}
}
return 0;
} else {
if (dev->tracks[track][side].params[4] != 0xFF)
return 0;
n_map = (uint8_t *) (dev->buffer + dev->tracks[track][side].n_map_offs);
for (uint8_t i = 0; i < dev->tracks[track][side].params[3]; i++) {
effective_sectors++;
if (!(r_map[i]) && !(n_map[i]))
effective_sectors--;
if (r_map[i] == (n_map[i] | 0x80)) {
xdf_sectors++;
dev->xdf_ordered_pos[(int) r_map[i]][side] = i;
}
}
if ((effective_sectors == 3) && (xdf_sectors == 3)) {
dev->current_side_flags[side] = 0x28;
return 1; /* 5.25" 2HD XDF */
}
if ((effective_sectors == 4) && (xdf_sectors == 4)) {
dev->current_side_flags[side] = 0x08;
return 2; /* 3.5" 2HD XDF */
}
return 0;
}
}
static int
track_is_interleave(int drive, int side, int track)
{
imd_t *dev = imd[drive];
int effective_sectors;
const char *r_map;
int track_spt;
effective_sectors = 0;
for (uint16_t i = 0; i < 256; i++)
dev->interleave_ordered_pos[i][side] = 0;
track_spt = dev->tracks[track][side].params[3];
r_map = dev->buffer + dev->tracks[track][side].r_map_offs;
if (dev->tracks[track][side].params[2] & 0xC0)
return 0;
if (track_spt != 21)
return 0;
if (dev->tracks[track][side].params[4] != 2)
return 0;
for (int i = 0; i < track_spt; i++) {
if ((r_map[i] >= 1) && (r_map[i] <= track_spt)) {
effective_sectors++;
dev->interleave_ordered_pos[(int) r_map[i]][side] = i;
}
}
if (effective_sectors == track_spt)
return 1;
return 0;
}
static void
sector_to_buffer(int drive, int track, int side, uint8_t *buffer, int sector, int len)
{
const imd_t *dev = imd[drive];
int type = dev->buffer[dev->tracks[track][side].sector_data_offs[sector]];
uint8_t fill_char;
if (type == 0)
memset(buffer, 0x00, len);
else {
if (type & 1)
memcpy(buffer, &(dev->buffer[dev->tracks[track][side].sector_data_offs[sector] + 1]), len);
else {
fill_char = dev->buffer[dev->tracks[track][side].sector_data_offs[sector] + 1];
memset(buffer, fill_char, len);
}
}
}
static void
imd_seek(int drive, int track)
{
uint32_t track_buf_pos[2] = { 0, 0 };
uint8_t id[4] = { 0, 0, 0, 0 };
uint8_t type;
imd_t *dev = imd[drive];
int sector;
int current_pos;
int c = 0;
int h;
int n;
int ssize = 512;
int track_rate = 0;
int track_gap2 = 22;
int track_gap3 = 12;
int xdf_type = 0;
int interleave_type = 0;
int is_trackx = 0;
int xdf_spt = 0;
int xdf_sector = 0;
int ordered_pos = 0;
int real_sector = 0;
int actual_sector = 0;
const char *c_map = NULL;
const char *h_map = NULL;
const char *r_map;
const char *n_map = NULL;
uint8_t *data;
int flags = 0x00;
if (dev->fp == NULL)
return;
if (!dev->track_width && fdd_doublestep_40(drive))
track /= 2;
d86f_set_cur_track(drive, track);
is_trackx = (track == 0) ? 0 : 1;
dev->track = track;
dev->current_side_flags[0] = dev->tracks[track][0].side_flags;
dev->current_side_flags[1] = dev->tracks[track][1].side_flags;
d86f_reset_index_hole_pos(drive, 0);
d86f_reset_index_hole_pos(drive, 1);
d86f_destroy_linked_lists(drive, 0);
d86f_destroy_linked_lists(drive, 1);
d86f_zero_track(drive);
if (track > dev->track_count)
return;
for (int side = 0; side < dev->sides; side++) {
if (!dev->tracks[track][side].is_present)
continue;
track_rate = dev->current_side_flags[side] & 7;
if (!track_rate && (dev->current_side_flags[side] & 0x20))
track_rate = 4;
if ((dev->current_side_flags[side] & 0x27) == 0x21)
track_rate = 2;
r_map = dev->buffer + dev->tracks[track][side].r_map_offs;
h = dev->tracks[track][side].params[2];
if (h & 0x80)
c_map = dev->buffer + dev->tracks[track][side].c_map_offs;
else
c = dev->tracks[track][side].params[1];
if (h & 0x40)
h_map = dev->buffer + dev->tracks[track][side].h_map_offs;
n = dev->tracks[track][side].params[4];
if (n == 0xFF) {
n_map = dev->buffer + dev->tracks[track][side].n_map_offs;
track_gap3 = gap3_sizes[track_rate][(int) n_map[0]][dev->tracks[track][side].params[3]];
} else {
track_gap3 = gap3_sizes[track_rate][n][dev->tracks[track][side].params[3]];
}
if (!track_gap3)
track_gap3 = dev->tracks[track][side].gap3_len;
xdf_type = track_is_xdf(drive, side, track);
interleave_type = track_is_interleave(drive, side, track);
current_pos = d86f_prepare_pretrack(drive, side, 0);
if (!xdf_type) {
for (sector = 0; sector < dev->tracks[track][side].params[3]; sector++) {
if (interleave_type == 0) {
real_sector = r_map[sector];
actual_sector = sector;
} else {
real_sector = dmf_r[sector];
actual_sector = dev->interleave_ordered_pos[real_sector][side];
}
id[0] = (h & 0x80) ? c_map[actual_sector] : c;
id[1] = (h & 0x40) ? h_map[actual_sector] : (h & 1);
id[2] = real_sector;
id[3] = (n == 0xFF) ? n_map[actual_sector] : n;
data = dev->track_buffer[side] + track_buf_pos[side];
type = dev->buffer[dev->tracks[track][side].sector_data_offs[actual_sector]];
type = (type >> 1) & 7;
flags = 0x00;
if ((type == 2) || (type == 4))
flags |= SECTOR_DELETED_DATA;
if ((type == 3) || (type == 4))
flags |= SECTOR_CRC_ERROR;
if (((flags & 0x02) || (id[3] > dev->tracks[track][side].max_sector_size)) && !fdd_get_turbo(drive))
ssize = 3;
else
ssize = 128 << ((uint32_t) id[3]);
sector_to_buffer(drive, track, side, data, actual_sector, ssize);
current_pos = d86f_prepare_sector(drive, side, current_pos, id, data, ssize, 22, track_gap3, flags);
track_buf_pos[side] += ssize;
if (sector == 0)
d86f_initialize_last_sector_id(drive, id[0], id[1], id[2], id[3]);
}
} else {
xdf_type--;
xdf_spt = xdf_physical_sectors[xdf_type][is_trackx];
for (sector = 0; sector < xdf_spt; sector++) {
xdf_sector = (side * xdf_spt) + sector;
id[0] = track;
id[1] = side;
id[2] = xdf_disk_layout[xdf_type][is_trackx][xdf_sector].id.r;
id[3] = is_trackx ? (id[2] & 7) : 2;
ordered_pos = dev->xdf_ordered_pos[id[2]][side];
data = dev->track_buffer[side] + track_buf_pos[side];
type = dev->buffer[dev->tracks[track][side].sector_data_offs[ordered_pos]];
type = ((type - 1) >> 1) & 7;
flags = 0x00;
if (type & 0x01)
flags |= SECTOR_DELETED_DATA;
if (type & 0x02)
flags |= SECTOR_CRC_ERROR;
if (((flags & 0x02) || (id[3] > dev->tracks[track][side].max_sector_size)) && !fdd_get_turbo(drive))
ssize = 3;
else
ssize = 128 << ((uint32_t) id[3]);
sector_to_buffer(drive, track, side, data, ordered_pos, ssize);
if (is_trackx)
current_pos = d86f_prepare_sector(drive, side, xdf_trackx_spos[xdf_type][xdf_sector], id, data, ssize, track_gap2, xdf_gap3_sizes[xdf_type][is_trackx], flags);
else
current_pos = d86f_prepare_sector(drive, side, current_pos, id, data, ssize, track_gap2, xdf_gap3_sizes[xdf_type][is_trackx], flags);
track_buf_pos[side] += ssize;
if (sector == 0)
d86f_initialize_last_sector_id(drive, id[0], id[1], id[2], id[3]);
}
}
}
}
static uint16_t
disk_flags(int drive)
{
const imd_t *dev = imd[drive];
return (dev->disk_flags);
}
static uint16_t
side_flags(int drive)
{
const imd_t *dev = imd[drive];
int side = 0;
uint16_t sflags = 0;
side = fdd_get_head(drive);
sflags = dev->current_side_flags[side];
return sflags;
}
static void
set_sector(int drive, int side, uint8_t c, uint8_t h, uint8_t r, uint8_t n)
{
imd_t *dev = imd[drive];
int track = dev->track;
int sc;
int sh;
int sn;
const char *c_map = NULL;
const char *h_map = NULL;
const char *r_map = NULL;
const char *n_map = NULL;
uint8_t id[4] = { 0, 0, 0, 0 };
sc = dev->tracks[track][side].params[1];
sh = dev->tracks[track][side].params[2];
sn = dev->tracks[track][side].params[4];
if (sh & 0x80)
c_map = dev->buffer + dev->tracks[track][side].c_map_offs;
if (sh & 0x40)
h_map = dev->buffer + dev->tracks[track][side].h_map_offs;
r_map = dev->buffer + dev->tracks[track][side].r_map_offs;
if (sn == 0xFF)
n_map = dev->buffer + dev->tracks[track][side].n_map_offs;
if (c != dev->track)
return;
for (uint8_t i = 0; i < dev->tracks[track][side].params[3]; i++) {
id[0] = (sh & 0x80) ? c_map[i] : sc;
id[1] = (sh & 0x40) ? h_map[i] : (sh & 1);
id[2] = r_map[i];
id[3] = (sn == 0xFF) ? n_map[i] : sn;
if ((id[0] == c) && (id[1] == h) && (id[2] == r) && (id[3] == n)) {
dev->current_data[side] = dev->buffer + dev->tracks[track][side].sector_data_offs[i];
}
}
}
static void
imd_writeback(int drive)
{
imd_t *dev = imd[drive];
int track = dev->track;
const char *n_map = 0;
uint8_t h;
uint8_t n;
uint8_t spt;
uint32_t ssize;
if (writeprot[drive])
return;
for (int side = 0; side < dev->sides; side++) {
if (dev->tracks[track][side].is_present) {
fseek(dev->fp, dev->tracks[track][side].file_offs, SEEK_SET);
h = dev->tracks[track][side].params[2];
spt = dev->tracks[track][side].params[3];
n = dev->tracks[track][side].params[4];
fwrite(dev->tracks[track][side].params, 1, 5, dev->fp);
if (h & 0x80)
fwrite(dev->buffer + dev->tracks[track][side].c_map_offs, 1, spt, dev->fp);
if (h & 0x40)
fwrite(dev->buffer + dev->tracks[track][side].h_map_offs, 1, spt, dev->fp);
if (n == 0xFF) {
n_map = dev->buffer + dev->tracks[track][side].n_map_offs;
fwrite(n_map, 1, spt, dev->fp);
}
for (uint8_t i = 0; i < spt; i++) {
ssize = (n == 0xFF) ? n_map[i] : n;
ssize = 128 << ssize;
fwrite(dev->buffer + dev->tracks[track][side].sector_data_offs[i], 1, ssize, dev->fp);
}
}
}
}
static uint8_t
poll_read_data(int drive, int side, uint16_t pos)
{
const imd_t *dev = imd[drive];
int type = dev->current_data[side][0];
if ((type == 0) || (type > 8))
return 0xf6; /* Should never happen. */
if (type & 1)
return (dev->current_data[side][pos + 1]);
else
return (dev->current_data[side][1]);
}
static void
poll_write_data(int drive, int side, uint16_t pos, uint8_t data)
{
const imd_t *dev = imd[drive];
int type = dev->current_data[side][0];
if (writeprot[drive])
return;
if ((type & 1) || (type == 0) || (type > 8))
return; /* Should never happen. */
dev->current_data[side][pos + 1] = data;
}
static int
format_conditions(int drive)
{
const imd_t *dev = imd[drive];
int track = dev->track;
int side;
int temp;
side = fdd_get_head(drive);
temp = (fdc_get_format_sectors(imd_fdc) == dev->tracks[track][side].params[3]);
temp = temp && (fdc_get_format_n(imd_fdc) == dev->tracks[track][side].params[4]);
return temp;
}
void
imd_init(void)
{
memset(imd, 0x00, sizeof(imd));
}
void
imd_load(int drive, char *fn)
{
uint32_t magic = 0;
uint32_t fsize = 0;
const char *buffer;
const char *buffer2;
imd_t *dev;
int track_spt = 0;
int sector_size = 0;
int track = 0;
int side = 0;
int extra = 0;
uint32_t last_offset = 0;
uint32_t data_size = 512;
uint32_t mfm = 0;
uint32_t pre_sector = 0;
uint32_t track_total = 0;
uint32_t raw_tsize = 0;
uint32_t minimum_gap3 = 0;
uint32_t minimum_gap4 = 0;
uint8_t converted_rate;
uint8_t type;
int size_diff;
int gap_sum;
d86f_unregister(drive);
writeprot[drive] = 0;
/* Allocate a drive block. */
dev = (imd_t *) malloc(sizeof(imd_t));
memset(dev, 0x00, sizeof(imd_t));
dev->fp = plat_fopen(fn, "rb+");
if (dev->fp == NULL) {
dev->fp = plat_fopen(fn, "rb");
if (dev->fp == NULL) {
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
free(dev);
return;
}
writeprot[drive] = 1;
}
if (ui_writeprot[drive])
writeprot[drive] = 1;
fwriteprot[drive] = writeprot[drive];
if (fseek(dev->fp, 0, SEEK_SET) == -1)
fatal("imd_load(): Error seeking to the beginning of the file\n");
if (fread(&magic, 1, 4, dev->fp) != 4)
fatal("imd_load(): Error reading the magic number\n");
if (magic != 0x20444D49) {
imd_log("IMD: Not a valid ImageDisk image\n");
fclose(dev->fp);
free(dev);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
} else
imd_log("IMD: Valid ImageDisk image\n");
if (fseek(dev->fp, 0, SEEK_END) == -1)
fatal("imd_load(): Error seeking to the end of the file\n");
fsize = ftell(dev->fp);
if (fsize <= 0) {
imd_log("IMD: Too small ImageDisk image\n");
fclose(dev->fp);
free(dev);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
}
if (fseek(dev->fp, 0, SEEK_SET) == -1)
fatal("imd_load(): Error seeking to the beginning of the file again\n");
dev->buffer = malloc(fsize);
if (fread(dev->buffer, 1, fsize, dev->fp) != fsize)
fatal("imd_load(): Error reading data\n");
buffer = dev->buffer;
buffer2 = memchr(buffer, 0x1A, fsize);
if (buffer2 == NULL) {
imd_log("IMD: No ASCII EOF character\n");
fclose(dev->fp);
free(dev);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
} else {
imd_log("IMD: ASCII EOF character found at offset %08X\n", buffer2 - buffer);
}
buffer2++;
if ((buffer2 - buffer) == fsize) {
imd_log("IMD: File ends after ASCII EOF character\n");
fclose(dev->fp);
free(dev);
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
} else {
imd_log("IMD: File continues after ASCII EOF character\n");
}
dev->start_offs = (buffer2 - buffer);
dev->disk_flags = 0x00;
dev->track_count = 0;
dev->sides = 1;
/* Set up the drive unit. */
imd[drive] = dev;
while (1) {
imd_log("In : %02X %02X %02X %02X %02X\n",
buffer2[0], buffer2[1], buffer2[2], buffer2[3], buffer2[4]);
track = buffer2[1];
side = buffer2[2];
if (side & 1)
dev->sides = 2;
extra = side & 0xC0;
side &= 0x3F;
track_spt = buffer2[3];
dev->tracks[track][side].spt = track_spt;
sector_size = buffer2[4];
dev->tracks[track][side].side_flags = (buffer2[0] % 3);
if ((track_spt != 0x00) && (!dev->tracks[track][side].side_flags))
dev->disk_flags |= 0x02;
dev->tracks[track][side].side_flags |=
(!(buffer2[0] - dev->tracks[track][side].side_flags) ? 0 : 8);
mfm = dev->tracks[track][side].side_flags & 8;
track_total = mfm ? 146 : 73;
pre_sector = mfm ? 60 : 42;
imd_log("Out : %02X %02X %02X %02X %02X\n", buffer2[0], track, side, track_spt, sector_size);
if ((track_spt == 15) && (sector_size == 2))
dev->tracks[track][side].side_flags |= 0x20;
if ((track_spt == 16) && (sector_size == 2))
dev->tracks[track][side].side_flags |= 0x20;
if ((track_spt == 17) && (sector_size == 2))
dev->tracks[track][side].side_flags |= 0x20;
if ((track_spt == 8) && (sector_size == 3))
dev->tracks[track][side].side_flags |= 0x20;
if ((dev->tracks[track][side].side_flags & 7) == 1)
dev->tracks[track][side].side_flags |= 0x20;
if ((dev->tracks[track][side].side_flags & 0x07) == 0x00)
dev->tracks[track][side].max_sector_size = 6;
else
dev->tracks[track][side].max_sector_size = 5;
if (!mfm)
dev->tracks[track][side].max_sector_size--;
imd_log("Side flags for (%02i)(%01i): %02X\n", track, side, dev->tracks[track] [side].side_flags);
dev->tracks[track][side].is_present = 1;
dev->tracks[track][side].file_offs = (buffer2 - buffer);
memcpy(dev->tracks[track][side].params, buffer2, 5);
dev->tracks[track][side].r_map_offs = dev->tracks[track][side].file_offs + 5;
last_offset = dev->tracks[track][side].r_map_offs + track_spt;
if (extra & 0x80) {
dev->tracks[track][side].c_map_offs = last_offset;
last_offset += track_spt;
}
if (extra & 0x40) {
dev->tracks[track][side].h_map_offs = last_offset;
last_offset += track_spt;
}
if (track_spt == 0x00) {
buffer2 = buffer + last_offset;
last_offset += track_spt;
dev->tracks[track][side].is_present = 0;
} else if (sector_size == 0xFF) {
dev->tracks[track][side].n_map_offs = last_offset;
buffer2 = buffer + last_offset;
last_offset += track_spt;
dev->tracks[track][side].data_offs = last_offset;
for (int i = 0; i < track_spt; i++) {
data_size = buffer2[i];
data_size = 128 << data_size;
dev->tracks[track][side].sector_data_offs[i] = last_offset;
dev->tracks[track][side].sector_data_size[i] = 1;
if (dev->buffer[dev->tracks[track][side].sector_data_offs[i]] > 0x08) {
/* Invalid sector data type, possibly a malformed HxC IMG image (it outputs data errored
sectors with a variable amount of bytes, against the specification). */
imd_log("IMD: Invalid sector data type %02X\n", dev->buffer[dev->tracks[track][side].sector_data_offs[i]]);
fclose(dev->fp);
free(dev);
imd[drive] = NULL;
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
}
if (buffer[dev->tracks[track][side].sector_data_offs[i]] != 0)
dev->tracks[track][side].sector_data_size[i] += (buffer[dev->tracks[track][side].sector_data_offs[i]] & 1) ? data_size : 1;
last_offset += dev->tracks[track][side].sector_data_size[i];
if (!(buffer[dev->tracks[track][side].sector_data_offs[i]] & 1))
fwriteprot[drive] = writeprot[drive] = 1;
type = dev->buffer[dev->tracks[track][side].sector_data_offs[i]];
if (type != 0x00) {
type = ((type - 1) >> 1) & 7;
if (data_size > (128 << dev->tracks[track][side].max_sector_size))
track_total += (pre_sector + 3);
else
track_total += (pre_sector + data_size + 2);
}
}
} else {
dev->tracks[track][side].data_offs = last_offset;
for (int i = 0; i < track_spt; i++) {
data_size = sector_size;
data_size = 128 << data_size;
dev->tracks[track][side].sector_data_offs[i] = last_offset;
dev->tracks[track][side].sector_data_size[i] = 1;
if (dev->buffer[dev->tracks[track][side].sector_data_offs[i]] > 0x08) {
/* Invalid sector data type, possibly a malformed HxC IMG image (it outputs data errored
sectors with a variable amount of bytes, against the specification). */
imd_log("IMD: Invalid sector data type %02X\n", dev->buffer[dev->tracks[track][side].sector_data_offs[i]]);
fclose(dev->fp);
free(dev);
imd[drive] = NULL;
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
}
if (buffer[dev->tracks[track][side].sector_data_offs[i]] != 0)
dev->tracks[track][side].sector_data_size[i] += (buffer[dev->tracks[track][side].sector_data_offs[i]] & 1) ? data_size : 1;
last_offset += dev->tracks[track][side].sector_data_size[i];
if (!(buffer[dev->tracks[track][side].sector_data_offs[i]] & 1))
fwriteprot[drive] = writeprot[drive] = 1;
type = dev->buffer[dev->tracks[track][side].sector_data_offs[i]];
if (type != 0x00) {
type = ((type - 1) >> 1) & 7;
if (data_size > (128 << dev->tracks[track][side].max_sector_size))
track_total += (pre_sector + 3);
else
track_total += (pre_sector + data_size + 2);
}
}
}
buffer2 = buffer + last_offset;
/* Leaving even GAP4: 80 : 40 */
/* Leaving only GAP1: 96 : 47 */
/* Not leaving even GAP1: 146 : 73 */
raw_tsize = get_raw_tsize(dev->tracks[track][side].side_flags, 0);
minimum_gap3 = 12 * track_spt;
if ((dev->tracks[track][side].side_flags == 0x0A) || (dev->tracks[track][side].side_flags == 0x29))
converted_rate = 2;
else if (dev->tracks[track][side].side_flags == 0x28)
converted_rate = 4;
else
converted_rate = dev->tracks[track][side].side_flags & 0x03;
if ((track_spt != 0x00) && (gap3_sizes[converted_rate][sector_size][track_spt] == 0x00)) {
size_diff = raw_tsize - track_total;
gap_sum = minimum_gap3 + minimum_gap4;
if (size_diff < gap_sum) {
/* If we can't fit the sectors with a reasonable minimum gap at perfect RPM, let's try 2% slower. */
raw_tsize = get_raw_tsize(dev->tracks[track][side].side_flags, 1);
/* Set disk flags so that rotation speed is 2% slower. */
dev->disk_flags |= (3 << 5);
size_diff = raw_tsize - track_total;
if (size_diff < gap_sum) {
/* If we can't fit the sectors with a reasonable minimum gap even at 2% slower RPM, abort. */
imd_log("IMD: Unable to fit the %i sectors in a track\n", track_spt);
fclose(dev->fp);
free(dev);
imd[drive] = NULL;
memset(floppyfns[drive], 0, sizeof(floppyfns[drive]));
return;
}
}
dev->tracks[track][side].gap3_len = (size_diff - minimum_gap4) / track_spt;
} else
dev->tracks[track][side].gap3_len = gap3_sizes[converted_rate][sector_size][track_spt];
/* imd_log("GAP3 length for (%02i)(%01i): %i bytes\n", track, side, dev->tracks[track][side].gap3_len); */
if (track > dev->track_count)
dev->track_count = track;
if (last_offset >= fsize)
break;
}
/* If more than 43 tracks, then the tracks are thin (96 tpi). */
dev->track_count++;
imd_log("In : dev->track_count = %i\n", dev->track_count);
int empty_tracks = 0;
for (int i = 0; i < dev->track_count; i++) {
if ((dev->sides == 2) && (dev->tracks[i][0].spt == 0x00) && (dev->tracks[i][1].spt == 0x00))
empty_tracks++;
else if ((dev->sides == 1) && (dev->tracks[i][0].spt == 0x00))
empty_tracks++;
}
imd_log("empty_tracks = %i\n", empty_tracks);
if (empty_tracks >= (dev->track_count >> 1)) {
for (int i = 0; i < dev->track_count; i += 2) {
imd_log("Thick %02X = Thin %02X\n", i >> 1, i);
dev->tracks[i >> 1][0] = dev->tracks[i][0];
dev->tracks[i >> 1][1] = dev->tracks[i][1];
}
for (int i = (dev->track_count >> 1); i < dev->track_count; i++) {
imd_log("Emptying %02X....\n", i);
memset(&(dev->tracks[i][0]), 1, sizeof(imd_track_t));
memset(&(dev->tracks[i][1]), 1, sizeof(imd_track_t));
}
dev->track_count >>= 1;
}
imd_log("Out: dev->track_count = %i\n", dev->track_count);
dev->track_width = 0;
if (dev->track_count > 43)
dev->track_width = 1;
/* If 2 sides, mark it as such. */
if (dev->sides == 2)
dev->disk_flags |= 8;
#if 0
imd_log("%i tracks, %i sides\n", dev->track_count, dev->sides);
#endif
/* Attach this format to the D86F engine. */
d86f_handler[drive].disk_flags = disk_flags;
d86f_handler[drive].side_flags = side_flags;
d86f_handler[drive].writeback = imd_writeback;
d86f_handler[drive].set_sector = set_sector;
d86f_handler[drive].read_data = poll_read_data;
d86f_handler[drive].write_data = poll_write_data;
d86f_handler[drive].format_conditions = format_conditions;
d86f_handler[drive].extra_bit_cells = null_extra_bit_cells;
d86f_handler[drive].encoded_data = common_encoded_data;
d86f_handler[drive].read_revolution = common_read_revolution;
d86f_handler[drive].index_hole_pos = null_index_hole_pos;
d86f_handler[drive].get_raw_size = common_get_raw_size;
d86f_handler[drive].check_crc = 1;
d86f_set_version(drive, 0x0063);
drives[drive].seek = imd_seek;
d86f_common_handlers(drive);
}
void
imd_close(int drive)
{
imd_t *dev = imd[drive];
if (dev == NULL)
return;
d86f_unregister(drive);
if (dev->fp != NULL) {
free(dev->buffer);
fclose(dev->fp);
}
/* Release the memory. */
free(dev);
imd[drive] = NULL;
}
void
imd_set_fdc(void *fdc)
{
imd_fdc = (fdc_t *) fdc;
}
``` | /content/code_sandbox/src/floppy/fdd_imd.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 9,690 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.