OscilloscopeService.java
package libsidutils.oscilloscope;
import builder.resid.ReSIDBase;
import libsidplay.C64;
import libsidplay.common.Event;
import libsidplay.common.SIDEmu;
import libsidutils.sound.SoundSetup;
import libsidplay.components.cart.supported.ReSfxSoundExpander;
import libsidplay.components.cart.supported.SFXSoundExpander;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* The sole sampler and history owner for one C64. View subscriptions share the emulation-thread event instead of
* clocking or accumulating each SID twice. Renderers receive snapshots and never advance these histories themselves.
*/
public final class OscilloscopeService {
public static final int WAV = 0, ENV = 3, FRQ = 6, VOL = 9, RES = 10, FIL = 11;
private static final float[] ENVELOPES = new float[256], FREQUENCIES = new float[65536];
static {
for (int i = 0; i < ENVELOPES.length; i++) {
ENVELOPES[i] = 1 + (i == 0 ? -48 : (float) (Math.log(i / 255f) / Math.log(10) * 20)) / 48f;
}
for (int i = 0; i < FREQUENCIES.length; i++) {
FREQUENCIES[i] = 1 + (i == 0 ? 84 : (float) (Math.log(i / 65535.0f) / Math.log(2) * 12)) / 84f;
}
}
/**
* Allocate SID histories only when a subscribed view needs that chip.
*/
private static final class SidHistories {
volatile TraceHistory[] traces;
synchronized TraceHistory[] get() {
if (traces == null) {
TraceHistory[] initialized = new TraceHistory[12];
for (int i = 0; i < initialized.length; i++) {
initialized[i] = new TraceHistory(32768);
}
traces = initialized;
}
return traces;
}
void reset() {
TraceHistory[] current = traces;
if (current != null) {
for (TraceHistory trace : current) {
trace.reset();
}
}
}
}
private final C64 c64;
private final SIDEmu[] sidChips = new SIDEmu[3];
private final SidHistories[] sidHistories = {new SidHistories(), new SidHistories(), new SidHistories()};
private final List<OscilloscopeUtil> listeners = new ArrayList<>();
private final Event sampler = Event.of("Shared Oscilloscope Sampler", event -> sample());
private ReSfxSoundExpander oplSource;
private OplOscilloscope oplHistories;
private int sampleCounter, generation, sequence;
private long lastFrameCycle;
public OscilloscopeService(C64 c64) {
this.c64 = c64;
}
public TraceHistory sidHistory(int chip, int trace) {
return sidHistories[chip].get()[trace];
}
void subscribe(OscilloscopeUtil listener) {
if (!listener.isRequested() || listeners.contains(listener)) {
return;
}
if (listeners.isEmpty()) {
for (SidHistories chip : sidHistories) {
chip.reset();
}
sampleCounter = sequence = 0;
generation++;
}
listeners.add(listener);
listener.updateSources(oplSource == null ? -1 : oplSource.getType(), generation);
if (!c64.getEventScheduler().isPending(sampler)) {
lastFrameCycle = c64.getEventScheduler().getTime(Event.Phase.PHI2);
c64.getEventScheduler().schedule(sampler, 0);
}
}
void unsubscribe(OscilloscopeUtil listener) {
listeners.remove(listener);
if (listeners.isEmpty()) {
c64.getEventScheduler().cancel(sampler);
detachOpl();
}
}
/** Invalidate presentation packets after a SID/preset change. No scheduler or synthesis state is changed. */
public void sidConfigurationChanged() {
if (listeners.isEmpty()) return;
generation++;
for (OscilloscopeUtil listener : listeners) {
listener.updateSources(oplSource == null ? -1 : oplSource.getType(), generation);
}
}
private void detachOpl() {
if (oplSource != null) {
oplSource.setObserver(null);
}
oplSource = null;
oplHistories = null;
}
public void reset() {
c64.getEventScheduler().cancel(sampler);
detachOpl();
Arrays.fill(sidChips, null);
generation++;
sampleCounter = sequence = 0;
for (SidHistories chip : sidHistories) {
chip.reset();
}
listeners.removeIf(listener -> !listener.isRequested());
for (OscilloscopeUtil listener : listeners) {
listener.updateSources(-1, generation);
}
lastFrameCycle = c64.getEventScheduler().getTime(Event.Phase.PHI2);
if (!listeners.isEmpty()) {
c64.getEventScheduler().schedule(sampler, 0);
}
}
private void refreshSources() {
// A configured cartridge is not necessarily running. Attach only to a
// prepared, started emulator, and release all OPL histories when unused.
boolean requested = false;
for (OscilloscopeUtil listener : listeners) {
requested |= listener.isOplEnabled();
}
ReSfxSoundExpander source = requested && c64.getCartridge() instanceof SFXSoundExpander cart && cart.isStarted() ? cart.getEmulator() : null;
if (source != null && !source.isPrepared()) {
source = null;
}
if (source == oplSource) {
return;
}
detachOpl();
if (source != null && source.isPrepared()) {
oplSource = source;
oplHistories = new OplOscilloscope();
source.setObserver(oplHistories);
}
generation++;
for (OscilloscopeUtil listener : listeners) {
listener.updateSources(oplSource == null ? -1 : oplSource.getType(), generation);
}
}
private void sample() {
for (int i = listeners.size() - 1; i >= 0; i--) {
if (!listeners.get(i).isRequested()) {
listeners.remove(i);
}
}
if (listeners.isEmpty()) {
detachOpl();
return;
}
long time = c64.getEventScheduler().getTime(Event.Phase.PHI2);
boolean frame = time - lastFrameCycle >= c64.getCyclesPerFrame();
Arrays.fill(sidChips, null);
c64.configureSIDs((chip, emulator) -> {
emulator.clock();
if (chip < sidChips.length) {
sidChips[chip] = emulator;
}
sampleSid(chip, emulator, (sampleCounter & 127) == 0);
if (frame) {
for (OscilloscopeUtil listener : listeners) {
if (listener.acceptsFrame(sequence)) {
listener.updateGauges(time, chip, emulator);
}
}
}
});
if (frame) {
lastFrameCycle += c64.getCyclesPerFrame();
refreshSources();
if (oplHistories != null) {
c64.getCartridge().clock();
oplSource.copyObserverState();
for (OscilloscopeUtil listener : listeners) {
if (listener.acceptsFrame(sequence)) {
listener.updateOplGauges(time, oplHistories, oplSource.getType(), generation, sequence);
}
}
}
for (OscilloscopeUtil listener : listeners) {
if (listener.acceptsFrame(sequence)) {
listener.updateFrame(time, this, generation, sequence);
}
}
sequence++;
}
sampleCounter++;
// Wave/volume histories advance every sample; the slower SID gauges
// advance every 128 samples, preserving the original display time scales.
c64.getEventScheduler().schedule(sampler, 128);
}
public int sidMask() {
int mask = 0;
for (int i = 0; i < sidChips.length; i++) {
if (sidChips[i] != null && sidChips[i] != SIDEmu.NONE) {
mask |= 1 << i;
}
}
return mask;
}
public int snapshotBytes(int width, int detailMask) {
return ScopeSnapshot.bytes(width, sidMask(), oplHistories == null ? 0 : OplOscilloscope.frameBytes(width, detailMask));
}
/**
* Copies current traces into caller-owned transport/presentation storage.
*/
public void writeSnapshot(ByteBuffer target, long time, int generation, int sequence, int width, int detailMask) {
target.clear().order(ByteOrder.LITTLE_ENDIAN);
int mask = sidMask(), oplBytes = oplHistories == null ? 0 : OplOscilloscope.frameBytes(width, detailMask);
target.putInt(ScopeSnapshot.VERSION).putInt(generation).putInt(sequence).putInt(width).putInt(mask).putInt(oplBytes).putLong(time);
for (int chip = 0; chip < sidChips.length; chip++) {
if ((mask & 1 << chip) != 0) {
for (int reg = 0; reg < 32; reg++) {
target.put(sidChips[chip].readInternalRegister(reg));
}
for (TraceHistory trace : sidHistories[chip].get()) {
for (int x = 0; x < width; x++) {
target.putFloat(trace.minimum(width - x)).putFloat(trace.maximum(width - x));
}
}
target.putInt(sidChips[chip] instanceof ReSIDBase software ? SoundSetup.playbackFlags(software) : 0);
}
}
if (oplHistories != null) {
ByteBuffer region = target.slice().order(ByteOrder.LITTLE_ENDIAN);
oplHistories.writeFrame(region, time, generation, sequence, width, detailMask, oplSource.getType());
target.position(target.position() + oplBytes);
}
target.flip();
}
private void sampleSid(int chip, SIDEmu emulator, boolean lowerResolution) {
if (chip >= 3) {
return; // Existing desktop/web displays support up to three SIDs.
}
ReSIDBase software = emulator instanceof ReSIDBase ? (ReSIDBase) emulator : null;
TraceHistory[] traces = sidHistories[chip].traces;
if (traces == null) {
traces = sidHistories[chip].get();
}
for (int voice = 0; voice < 3; voice++) {
traces[WAV + voice].accumulate(software == null ? 0 : (software.readOSC(voice) & 255) / 255f);
traces[WAV + voice].advance();
traces[ENV + voice].accumulate(software == null ? 0 : ENVELOPES[software.readENV(voice) & 255]);
int frequency = (emulator.readInternalRegister(voice * 7 + 1) & 255) << 8 |
emulator.readInternalRegister(voice * 7) & 255;
traces[FRQ + voice].accumulate(FREQUENCIES[frequency]);
}
traces[VOL].accumulate((emulator.readInternalRegister(0x18) & 15) / 15f);
traces[VOL].advance();
traces[RES].accumulate((emulator.readInternalRegister(0x17) >> 4 & 15) / 15f);
traces[FIL].accumulate(((emulator.readInternalRegister(0x15) & 7) |
(emulator.readInternalRegister(0x16) & 255) << 3) / 2047f);
if (lowerResolution) {
for (int i = ENV; i <= FRQ + 2; i++) {
traces[i].advance();
}
traces[RES].advance();
traces[FIL].advance();
}
}
}