NetSIDDevBuilder.java
package builder.netsiddev;
import builder.netsiddev.commands.*;
import libsidplay.common.*;
import libsidplay.components.cart.Cartridge;
import libsidplay.components.cart.supported.ISfxSoundExpander;
import libsidplay.components.cart.supported.SFXSoundExpander;
import libsidplay.config.IAudioSection;
import libsidplay.config.IConfig;
import libsidplay.config.IEmulationSection;
import libsidplay.sidtune.SidTune;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static libsidplay.config.ISidPlay2SystemProperties.MAX_SIDS;
import static libsidplay.sidtune.SidTune.RESET;
import static server.netsiddev.NetworkSIDProtocol.*;
/**
*
* Support of network-enabled SID devices using the network SID protocol.
*
* @author ken
*
*/
public class NetSIDDevBuilder implements SIDBuilder, Mixer, ISfxSoundExpander {
/**
* SID filter/volume register; setting it to zero silences an unused physical slot.
*/
private static final byte SID_VOLUME_REGISTER = 0x18;
/**
* Zero SID master volume, used when releasing chips without erasing their local caches.
*/
private static final byte SILENT_VOLUME = 0x00;
private final IConfig config;
private final CPUClock cpuClock;
private final NetSIDClient client;
/**
* Indexed protocol slots, accessed on the emulation thread. Position is the physical SID number: [SID 0, null, SID
* 2] must never be compacted. Null means an unused, silent slot; only trailing nulls may be trimmed. The remote
* count covers the highest occupied index, while mixer mono detection counts live entries. Fake stereo may skip
* holes only inside its original mirror group.
*/
private final List<NetSIDDev> sids = new ArrayList<>();
private final boolean fmOpl;
private SidTune currentTune = RESET;
public NetSIDDevBuilder(EventScheduler context, IConfig config, CPUClock cpuClock, Cartridge cartridge) {
this.config = config;
this.cpuClock = cpuClock;
this.client = new NetSIDClient(context, config.getEmulationSection());
if (cartridge instanceof SFXSoundExpander sfxSountExpander) {
this.fmOpl = true;
sfxSountExpander.setSfxSoundExpanderImpl(this);
} else {
fmOpl = false;
}
}
@Override
public SIDEmu lock(SIDEmu sidEmu, int sidNum, SidTune tune) {
currentTune = tune;
IAudioSection audioSection = config.getAudioSection();
IEmulationSection emulationSection = config.getEmulationSection();
ChipModel chipModel = ChipModel.getChipModel(emulationSection, tune, sidNum);
int sidCount = 1;
for (int chip = 1; chip < MAX_SIDS; chip++) {
if (SidTune.isSIDUsed(emulationSection, tune, chip)) {
sidCount = chip + 1;
}
}
if (sidNum == 0) {
// C64.insertSIDChips locks chips in ascending order. Reset the whole device
// once, before restoring any chip's registers; later locks must retain them.
configureDevice(sidCount, audioSection);
if (sids.size() > sidCount) {
for (NetSIDDev obsolete : sids.subList(sidCount, sids.size())) {
if (obsolete != null) {
obsolete.deactivate();
}
}
sids.subList(sidCount, sids.size()).clear();
}
// Some devices recreate every chip when any model changes. Complete
// all configuration before replaying the first physical register bank.
for (int chip = 0; chip < sidCount; chip++) {
if (SidTune.isSIDUsed(emulationSection, tune, chip)) {
configureSID(chip, ChipModel.getChipModel(emulationSection, tune, chip));
}
}
for (int chip = 0; chip < sidCount; chip++) {
if (!SidTune.isSIDUsed(emulationSection, tune, chip)) {
silenceSlot(chip);
}
}
}
final NetSIDDev sid = createSID(emulationSection, chipModel, tune, sidNum);
// Apply each physical chip's bypass before replaying the tune's original filter-routing register.
sid.setFilterEnable(emulationSection, sidNum);
if (sidEmu != null) {
sid.restoreRegisters(sidEmu);
} else if (sid instanceof NetSIDDev.FakeStereo && sidNum - 1 < sids.size()
&& sids.get(sidNum - 1) != null) {
// A newly enabled mirror starts with the already playing chip's registers.
sid.restoreRegisters(sids.get(sidNum - 1));
}
// A forced third SID does not require SID 1 to be enabled. Keep holes so
// mixer and fake-stereo lookups still use the physical protocol index.
while (sids.size() <= sidNum) {
sids.add(null);
}
NetSIDDev previous = sids.set(sidNum, sid);
if (previous != null) {
previous.deactivate();
}
updateMixer(audioSection);
return sid;
}
@Override
public void unlock(SIDEmu device) {
if (!(device instanceof NetSIDDev sid)) {
return;
}
int sidNum = sids.indexOf(sid);
if (sidNum < 0) {
// A count reduction already removed this slot while locking SID 0.
return;
}
// Retire the object as well as its slot: a C64 bank can still hold the old
// reference until its own remapping finishes, including a fake-stereo wrapper.
sids.set(sidNum, null);
sid.deactivate();
while (!sids.isEmpty() && sids.getLast() == null) {
sids.removeLast();
}
if (NetSIDDevConnection.getInstance().isDisconnected()) {
return;
}
try {
IAudioSection audioSection = config.getAudioSection();
if (sids.isEmpty()) {
// The protocol requires at least one allocated chip, even with no user.
client.configureSids(1);
client.init(SILENT_VOLUME);
client.softFlush();
} else if (sids.size() != client.getSidCount()) {
// A count change may recreate every remote chip. Reapply configuration
// and each surviving chip's own registers before resuming playback.
configureDevice(sids.size(), audioSection);
for (int chip = 0; chip < sids.size(); chip++) {
NetSIDDev retained = sids.get(chip);
if (retained != null) {
configureSID(chip, retained.getChipModel());
}
}
for (int chip = 0; chip < sids.size(); chip++) {
NetSIDDev retained = sids.get(chip);
if (retained == null) {
silenceSlot(chip);
} else {
retained.restoreRegisters(retained);
}
}
updateMixer(audioSection);
} else {
// An interior hole cannot reduce the count or renumber later SIDs.
silenceSlot(sidNum);
updateMixer(audioSection);
}
} catch (RuntimeException failure) {
// softFlush closes a failed connection. Local retirement is already done;
// a server disappearing during synchronization must not stop later unlocks.
if (!NetSIDDevConnection.getInstance().isDisconnected()) {
throw failure;
}
}
}
private void configureDevice(int sidCount, IAudioSection audioSection) {
client.configureSids(sidCount);
client.configureProtocolV1(ChipModel.getChipModel(config.getEmulationSection(), currentTune, 0),
audioSection.getSampling(), cpuClock);
client.init(RESET_VOLUME);
if (client.getVersion() >= METADATA_VERSION && currentTune != RESET && currentTune.getPSidHeader() != null) {
client.add(new SetSidHeader(currentTune.getPSidHeader()));
}
if (client.getVersion() >= CONFIGURATION_VERSION) {
client.add(new TrySetSampling(audioSection.getSampling()));
client.add(new SetClocking(cpuClock.getCpuFrequency()));
}
if (client.getVersion() >= EXTENDED_ADDRESS_VERSION) {
client.add(new TrySetFmOpl(fmOpl));
}
}
private void configureSID(int sidNum, ChipModel chipModel) {
IEmulationSection emulationSection = config.getEmulationSection();
String filterName = emulationSection.getFilterName(sidNum, Engine.NETSID, Emulation.DEFAULT, chipModel);
// An empty filter selection still needs a configuration for the requested chip model.
if (client.getVersion() >= CONFIGURATION_VERSION) {
client.addAndSend(new TrySetSidModel((byte) sidNum, chipModel, filterName));
}
for (byte voice = 0; voice < (client.getVersion() < DIGI_MUTE_VERSION ? DIGI_VOICE : DIGI_VOICE + 1); voice++) {
client.add(new Mute((byte) sidNum, voice, emulationSection.isMuteVoice(sidNum, voice)));
}
client.softFlush();
}
private void silenceSlot(int sidNum) {
client.write((byte) sidNum, SID_VOLUME_REGISTER, SILENT_VOLUME);
}
private NetSIDDev createSID(IEmulationSection emulationSection, ChipModel chipModel, SidTune tune, int sidNum) {
if (SidTune.isFakeStereoSid(emulationSection, tune, sidNum)) {
return new NetSIDDev.FakeStereo(client, sidNum, chipModel, config, sids);
} else {
return new NetSIDDev(client, sidNum, chipModel);
}
}
private void updateMixer(IAudioSection audioSection) {
boolean tunePanning = SidTune.hasHeaderPanning(currentTune);
for (int sidNum = 0; sidNum < sids.size(); sidNum++) {
if (sids.get(sidNum) == null) {
continue;
}
setVolume(sidNum, audioSection.getVolume(sidNum));
setBalance(sidNum, tunePanning ? currentTune.getInfo().getChannel(sidNum) : audioSection.getBalance(sidNum));
setDelay(sidNum, audioSection.getDelay(sidNum));
}
client.softFlush();
}
@Override
public void start() {
client.start();
}
@Override
public void fadeIn(double fadeIn) {
if (client.getVersion() >= METADATA_VERSION) {
client.add(new SetFadeIn(fadeIn));
}
}
@Override
public void fadeOut(double fadeOut) {
if (client.getVersion() >= METADATA_VERSION) {
client.add(new SetFadeOut(fadeOut));
}
}
@Override
public void setVolume(int sidNum, float volume) {
if (!Float.isFinite(volume) || volume < Byte.MIN_VALUE / (float) LEVEL_STEPS_PER_DB
|| volume > Byte.MAX_VALUE / (float) LEVEL_STEPS_PER_DB) {
throw new IllegalArgumentException("Network SID volume must be between -25.6 and 25.4 dB");
}
if (client.getVersion() >= CONFIGURATION_VERSION) {
client.add(new SetSidLevel((byte) sidNum, (byte) Math.round(volume * LEVEL_STEPS_PER_DB)));
}
}
@Override
public void setBalance(int sidNum, float balance) {
if (!Float.isFinite(balance) || balance < 0 || balance > 1) {
throw new IllegalArgumentException("Balance must be between 0 and 1");
}
if (client.getVersion() < CONFIGURATION_VERSION) {
return;
}
boolean isMono = sids.stream().filter(Objects::nonNull).count() <= 1;
if (isMono) {
client.add(new SetSidPosition((byte) sidNum, (byte) POSITION_CENTER));
} else {
float position = POSITION_LEFT + balance * (POSITION_RIGHT - POSITION_LEFT);
client.add(new SetSidPosition((byte) sidNum, (byte) position));
}
}
@Override
public void setDelay(int sidNum, int delay) {
if (delay < 0 || delay > MAX_OUTPUT_DELAY_MILLIS) {
throw new IllegalArgumentException("Network SID output delay must be between 0 and 255 ms");
}
if (client.getVersion() >= METADATA_VERSION) {
client.add(new SetDelay((byte) sidNum, (byte) delay));
}
}
@Override
public void fastForward() {
client.fastForward();
}
@Override
public void normalSpeed() {
client.normalSpeed();
}
@Override
public boolean isFastForward() {
return client.isFastForward();
}
@Override
public int getFastForwardFactor() {
return client.getFastForwardFactor();
}
@Override
public int getFastForwardBitMask() {
return client.getFastForwardBitMask();
}
@Override
public void pause() {
client.addAndSend(new Flush());
}
@Override
public byte read(int addr) {
return (byte) 0xff;
}
@Override
public void write(int addr, byte val) {
client.write(addr, val);
}
@Override
public void clock(int piece) {
}
@Override
public void reset() {
}
}