SoundView.java

package ui.oscilloscope;

import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.image.WritableImage;
import libsidutils.oscilloscope.ScopeSnapshot;
import libsidutils.sound.SoundSetup;
import libsidutils.sound.SignalState;
import libsidutils.sound.OutputSettings;
import libsidutils.sound.OutputEffects;
import sidplay.Player;
import ui.common.C64VBox;
import ui.common.C64Window;
import ui.common.UIPart;

import java.nio.ByteBuffer;
import java.text.MessageFormat;
import java.util.ResourceBundle;

/** Renders existing scope snapshots and immutable applied settings; never reads or clocks a SID. */
public final class SoundView extends C64VBox implements UIPart {
    @FXML
    private TitledPane border;
    @FXML
    private ComboBox<Integer> selector;
    @FXML
    private Label setupText, liveText;
    @FXML
    private Canvas canvas;
    @FXML
    private VBox content;
    @FXML
    private VBox signalPaths;
    @FXML
    private Label waveform1, waveform2, waveform3, route1, route2, route3, status1, status2, status3;
    @FXML
    private Label linksTitle, linksText, voice3Notice, modifiersText;
    @FXML
    private Label outputText, outputSizeCenter, outputSizeLeft, outputSizeRight;
    @FXML
    private Label moreSidsText;
    @FXML
    private Label effectsText, effectsSize;
    @FXML
    private Button effectsDetails;
    @FXML
    private Tooltip effectsTooltip;
    @FXML
    private Label waveformSize1, waveformSize2, waveformSize3, routeSize1, routeSize2, routeSize3,
            statusSize1, statusSize2, statusSize3, liveSizeBypass, liveSizeNoMode, linksSize, modifiersSize;

    private ResourceBundle bundle;
    private SoundSetup[] offered;
    private OutputSettings[] outputs;
    private OutputSettings currentOutput;
    private OutputEffects offeredEffects, currentEffects;
    private int offeredSidCount, displayedSidCount;
    private boolean[] enabled;
    private volatile boolean requested;
    private SoundSetup current;
    private double[] curve;
    private int cutoff;
    private boolean bypassed;
    private WritableImage background;
    private double backgroundWidth;
    private SoundSetup backgroundSetup;
    private boolean backgroundBypassed;
    private Label[] waveforms, routes, statuses;
    private long signalSignature, pulseSignature;

    public SoundView() {
        super();
    }

    public SoundView(C64Window window, Player player) {
        super(window, player);
    }

    @FXML
    @Override
    protected void initialize() {
        bundle = util.getBundle();
        offered = new SoundSetup[3];
        outputs = new OutputSettings[3];
        enabled = new boolean[3];
        requested = border.isExpanded();
        waveforms = new Label[]{waveform1, waveform2, waveform3};
        routes = new Label[]{route1, route2, route3};
        statuses = new Label[]{status1, status2, status3};
        reserveTextSlots();
        selector.setConverter(new javafx.util.StringConverter<>() {
            @Override public String toString(Integer chip) { return chip == null ? "" : "SID " + (chip + 1); }
            @Override public Integer fromString(String value) { return 0; }
        });
        selector.getSelectionModel().select(Integer.valueOf(0));
        selector.valueProperty().addListener((o, a, chip) -> {
            // Selection also works while playback is paused; never leave the previous chip's marker visible.
            current = chip == null ? null : offered[chip];
            curve = current == null ? null : current.curve();
            bypassed = chip != null && !enabled[chip];
            cutoff = -1;
            hideSignals();
            setupText.setText(current == null ? bundle.getString("SOUND_WAITING") : describe(current));
            showOutput(current == null || chip == null ? null : outputs[chip]);
            liveText.setText(bundle.getString("SOUND_WAITING"));
            draw();
        });
        canvas.widthProperty().bind(javafx.beans.binding.Bindings.max(100, content.widthProperty().subtract(28)));
        canvas.widthProperty().addListener((o, a, b) -> draw());
        border.expandedProperty().addListener((o, a, b) -> {
            requested = b;
            if (!b) effectsTooltip.hide();
        });
        reset();
    }

    public boolean isRequested() { return requested; }

    /** Natural text sizing reserves every playback variant without clipping translations or measuring frames. */
    private void reserveTextSlots() {
        String waveform = String.join(" + ", bundle.getString("SOUND_WAVE0"), bundle.getString("SOUND_WAVE1"),
                bundle.getString("SOUND_WAVE2"), bundle.getString("SOUND_WAVE3")) + " · "
                + MessageFormat.format(bundle.getString("SOUND_PULSE_DUTY"), "100.0");
        String route = MessageFormat.format(bundle.getString("SOUND_ROUTE_FILTER"), "LP + BP + HP")
                + " · " + bundle.getString("SOUND_FILTER_BYPASS");
        String status = String.join(" · ", bundle.getString("SOUND_PLAYER_MUTE"), bundle.getString("SOUND_GATE_OFF"),
                bundle.getString("SOUND_TEST"), bundle.getString("SOUND_RING_INACTIVE"));
        for (Label label : new Label[]{waveformSize1, waveformSize2, waveformSize3}) label.setText(waveform);
        for (Label label : new Label[]{routeSize1, routeSize2, routeSize3}) label.setText(route);
        for (Label label : new Label[]{statusSize1, statusSize2, statusSize3}) label.setText(status);
        String live = MessageFormat.format(bundle.getString("SOUND_LIVE"), "8888", 88, "1 + 2 + 3 + EXT",
                bundle.getString("SOUND_NO_MODE") + " / LP + BP + HP");
        liveSizeBypass.setText(live + "\n" + bundle.getString("SOUND_BYPASSED"));
        liveSizeNoMode.setText(live + "\n" + bundle.getString("SOUND_NO_MODE_HELP"));
        java.util.List<String> links = new java.util.ArrayList<>();
        for (int voice = 1; voice <= 3; voice++) for (String type : new String[]{"SYNC", "RING"})
            links.add(MessageFormat.format(bundle.getString("SOUND_LINK"), (voice + 1) % 3 + 1, type, voice));
        linksSize.setText(String.join("    |    ", links));
        modifiersSize.setText(MessageFormat.format(bundle.getString("SOUND_SID_VOLUME"), 15) + "    |    "
                + bundle.getString("SOUND_DIGI_BOOST_OFF") + "    |    " + bundle.getString("SOUND_SAMPLE_MUTE"));
        outputSizeCenter.setText(describeOutput(new OutputSettings(6, .5, 50)));
        outputSizeLeft.setText(describeOutput(new OutputSettings(6, 0, 50)));
        outputSizeRight.setText(describeOutput(new OutputSettings(6, 1, 50)));
        effectsSize.setText(effectsSummary(new OutputEffects(false, 0, 0, 0, 0, false, 0, 0)));
    }

    /** Called on the emulation thread before the corresponding scope frame is published. */
    public void offer(int chip, SoundSetup setup, boolean filterEnabled, OutputSettings output, int sidCount) {
        if (requested && chip < offered.length) {
            offered[chip] = setup;
            enabled[chip] = filterEnabled;
            outputs[chip] = output;
            offeredSidCount = sidCount;
        }
    }

    /** One shared snapshot for the whole mix, independent of the selected SID. */
    public void offerEffects(OutputEffects effects) {
        if (requested) offeredEffects = effects;
    }

    public void reset() {
        java.util.Arrays.fill(offered, null);
        java.util.Arrays.fill(outputs, null);
        offeredSidCount = displayedSidCount = 0;
        offeredEffects = null;
        showEffects(null);
        effectsTooltip.hide();
        moreSidsText.setVisible(false);
        moreSidsText.setManaged(false);
        selector.getItems().clear();
        selector.setValue(0);
        current = null;
        curve = null;
        cutoff = -1;
        hideSignals();
        setupText.setText(bundle.getString("SOUND_WAITING"));
        liveText.setText("");
        showOutput(null);
        draw();
    }

    public void renderSnapshot(ByteBuffer frame) {
        if (!requested) return;
        showEffects(offeredEffects);
        if (displayedSidCount != offeredSidCount) {
            displayedSidCount = offeredSidCount;
            moreSidsText.setText(MessageFormat.format(bundle.getString("SOUND_MORE_SIDS"), displayedSidCount));
            moreSidsText.setVisible(displayedSidCount > 3);
            moreSidsText.setManaged(displayedSidCount > 3);
        }
        for (int chip = 0; chip < offered.length; chip++) {
            if (ScopeSnapshot.sidOffset(frame, chip) < 0) {
                offered[chip] = null;
                outputs[chip] = null;
                selector.getItems().remove(Integer.valueOf(chip));
                continue;
            }
            if (offered[chip] != null && !selector.getItems().contains(chip)) selector.getItems().add(chip);
        }
        Integer selected = selector.getValue();
        int chip = selected == null ? 0 : selected;
        SoundSetup setup = offered[chip];
        if (setup == null) {
            current = null;
            curve = null;
            cutoff = -1;
            hideSignals();
            setupText.setText(bundle.getString("SOUND_UNAVAILABLE"));
            liveText.setText("");
            showOutput(null);
            draw();
            return;
        }
        if (current != setup) {
            current = setup;
            curve = setup.curve();
            cutoff = -1;
            hideSignals();
            setupText.setText(describe(setup));
        }
        showOutput(outputs[chip]);
        int flags = ScopeSnapshot.playbackFlags(frame, chip);
        if ((flags & SignalState.KNOWN) == 0) flags = enabled[chip] ? SignalState.FILTER_ENABLED : 0;
        bypassed = (flags & SignalState.FILTER_ENABLED) == 0;
        int base = ScopeSnapshot.sidOffset(frame, chip);
        if (base < 0 || frame.getLong(24) < setup.appliedAt) {
            cutoff = -1;
            hideSignals();
            liveText.setText(bundle.getString("SOUND_WAITING"));
        } else {
            int routing = frame.get(base + 0x17) & 255, mode = frame.get(base + 0x18) & 255;
            cutoff = (frame.get(base + 0x15) & 7) | (frame.get(base + 0x16) & 255) << 3;
            StringBuilder voices = new StringBuilder(), modes = new StringBuilder();
            for (int voice = 0; voice < 3; voice++) if ((routing & 1 << voice) != 0) {
                if (!voices.isEmpty()) voices.append(" + ");
                voices.append(voice + 1);
            }
            if ((routing & 8) != 0) voices.append(voices.isEmpty() ? "EXT" : " + EXT");
            String[] names = {"LP", "BP", "HP"};
            for (int i = 0; i < 3; i++) if ((mode & 16 << i) != 0) {
                if (!modes.isEmpty()) modes.append(" + ");
                modes.append(names[i]);
            }
            String text = MessageFormat.format(bundle.getString("SOUND_LIVE"), String.valueOf(cutoff), routing >> 4,
                    voices.isEmpty() ? bundle.getString("SOUND_NONE") : voices,
                    modes.isEmpty() ? bundle.getString("SOUND_NO_MODE") : modes);
            if (bypassed) text += "\n" + bundle.getString("SOUND_BYPASSED");
            else if (modes.isEmpty() && !voices.isEmpty()) text += "\n" + bundle.getString("SOUND_NO_MODE_HELP");
            liveText.setText(text);
            renderSignals(frame, base, flags);
        }
        draw();
    }

    private void hideSignals() {
        signalPaths.setVisible(false);
        signalPaths.setManaged(false);
    }

    private void showOutput(OutputSettings output) {
        if (java.util.Objects.equals(currentOutput, output) && !outputText.getText().isEmpty()) return;
        currentOutput = output;
        outputText.setText(output == null ? bundle.getString("SOUND_OUTPUT_UNAVAILABLE") : describeOutput(output));
    }

    private String describeOutput(OutputSettings output) {
        int amount = (int) Math.round(Math.abs(output.balance() - .5) * 200);
        String position = amount == 0 ? bundle.getString("SOUND_OUTPUT_CENTER") : MessageFormat.format(
                bundle.getString(output.balance() < .5 ? "SOUND_OUTPUT_LEFT" : "SOUND_OUTPUT_RIGHT"), amount);
        double level = Math.abs(output.levelDb()) < .05 ? 0 : output.levelDb();
        return MessageFormat.format(bundle.getString("SOUND_OUTPUT"),
                String.format(java.util.Locale.ROOT, level > 0 ? "+%.1f" : "%.1f", level), position,
                String.valueOf(Math.round(output.delayMs())));
    }

    private String effectsSummary(OutputEffects effects) {
        return MessageFormat.format(bundle.getString("SOUND_EFFECTS"),
                bundle.getString(effects.echoEnabled() ? "SOUND_EFFECT_ON" : "SOUND_EFFECT_OFF"),
                bundle.getString(effects.reverbEnabled() ? "SOUND_EFFECT_ON" : "SOUND_EFFECT_OFF"));
    }

    private void showEffects(OutputEffects effects) {
        if (java.util.Objects.equals(currentEffects, effects) && !effectsText.getText().isEmpty()) return;
        currentEffects = effects;
        effectsDetails.setDisable(effects == null);
        effectsText.setText(effects == null ? bundle.getString("SOUND_EFFECTS_UNAVAILABLE") : effectsSummary(effects));
        String details = bundle.getString("SOUND_EFFECTS_HELP");
        if (effects != null) {
            details += "\n\n" + MessageFormat.format(bundle.getString("SOUND_ECHO_DETAILS"),
                    String.valueOf(effects.echoDelayMs()), effects.echoDryPercent(), effects.echoWetPercent(),
                    effects.echoFeedbackPercent());
            details += "\n" + MessageFormat.format(bundle.getString("SOUND_REVERB_DETAILS"),
                    Math.round(effects.reverbWetPercent()), String.valueOf(Math.round(effects.reverbSustainMs())));
        }
        effectsTooltip.setText(details);
        effectsDetails.setAccessibleHelp(details);
    }

    @FXML
    private void showEffectsDetails() {
        if (effectsTooltip.isShowing()) {
            effectsTooltip.hide();
        } else {
            var bounds = effectsDetails.localToScreen(effectsDetails.getBoundsInLocal());
            if (bounds != null) effectsTooltip.show(effectsDetails, bounds.getMinX(), bounds.getMaxY() + 6);
        }
    }

    private void renderSignals(ByteBuffer frame, int base, int flags) {
        long signature = ((long) flags << 40) | ((long) (frame.get(base + 0x18) & 255) << 32)
                | ((long) (frame.get(base + 0x17) & 15) << 24);
        long pulses = 0;
        for (int voice = 0; voice < 3; voice++) {
            signature |= (long) (frame.get(base + voice * 7 + 4) & 255) << (voice * 8);
            pulses |= (long) ((frame.get(base + voice * 7 + 2) & 255)
                    | (frame.get(base + voice * 7 + 3) & 15) << 8) << (voice * 12);
        }
        if (signalPaths.isVisible() && signature == signalSignature && pulses == pulseSignature) return;
        signalSignature = signature;
        pulseSignature = pulses;
        SignalState state = SignalState.decode(frame, base, flags);
        String modes = modesText(state.modes());
        StringBuilder links = new StringBuilder();
        for (SignalState.Voice voice : state.voices()) {
            StringBuilder wave = new StringBuilder();
            for (int bit = 0; bit < 4; bit++) if ((voice.waveform() & 1 << bit) != 0) {
                if (!wave.isEmpty()) wave.append(" + ");
                wave.append(bundle.getString("SOUND_WAVE" + bit));
            }
            if (wave.isEmpty()) wave.append(bundle.getString("SOUND_NO_WAVEFORM"));
            if ((voice.waveform() & 4) != 0) wave.append(" · ").append(MessageFormat.format(
                    bundle.getString("SOUND_PULSE_DUTY"), String.format(java.util.Locale.ROOT, "%.1f", voice.pulseDuty())));
            waveforms[voice.number() - 1].setText(wave.toString());
            String route = MessageFormat.format(bundle.getString("SOUND_ROUTE_" + voice.route()), modes);
            if (voice.bypassed()) route += " · " + bundle.getString("SOUND_FILTER_BYPASS");
            routes[voice.number() - 1].setText(route);
            java.util.List<String> status = new java.util.ArrayList<>();
            if (state.known() && voice.muted()) status.add(bundle.getString("SOUND_PLAYER_MUTE"));
            if (!voice.gate()) status.add(bundle.getString("SOUND_GATE_OFF"));
            if (voice.test()) status.add(bundle.getString("SOUND_TEST"));
            if (voice.ring() && !voice.ringEffective()) status.add(bundle.getString("SOUND_RING_INACTIVE"));
            statuses[voice.number() - 1].setText(String.join(" · ", status));
            statuses[voice.number() - 1].setVisible(!status.isEmpty());
            statuses[voice.number() - 1].setManaged(!status.isEmpty());
            for (String type : new String[]{"SYNC", "RING"}) {
                if (type.equals("SYNC") ? voice.sync() : voice.ringEffective()) {
                    if (!links.isEmpty()) links.append("    |    ");
                    links.append(MessageFormat.format(bundle.getString("SOUND_LINK"), voice.source(), type, voice.number()));
                }
            }
        }
        linksText.setText(links.isEmpty() ? bundle.getString("SOUND_NONE") : links.toString());
        boolean source = state.voices()[2].route() == SignalState.Route.VOICE3_OFF
                && (state.voices()[0].sync() || state.voices()[0].ringEffective());
        voice3Notice.setVisible(source);
        String modifiers = MessageFormat.format(bundle.getString("SOUND_SID_VOLUME"), state.volume());
        if (state.known() && current.model == libsidplay.common.ChipModel.MOS8580) modifiers += "    |    "
                + bundle.getString(state.digiBoost() ? "SOUND_DIGI_BOOST_ON" : "SOUND_DIGI_BOOST_OFF");
        if (state.known() && state.sampleMute()) modifiers += "    |    " + bundle.getString("SOUND_SAMPLE_MUTE");
        modifiersText.setText(modifiers);
        signalPaths.setVisible(true);
        signalPaths.setManaged(true);
    }

    private static String modesText(int modes) {
        java.util.List<String> names = new java.util.ArrayList<>();
        if ((modes & 1) != 0) names.add("LP");
        if ((modes & 2) != 0) names.add("BP");
        if ((modes & 4) != 0) names.add("HP");
        return String.join(" + ", names);
    }

    private String describe(SoundSetup setup) {
        String text = setup.model.name().replace("MOS", "") + " · " + bundle.getString("SOUND_SOURCE_" + setup.modelSource)
                + "    |    " + setup.clock + " · " + bundle.getString("SOUND_SOURCE_" + setup.clockSource)
                + "\n" + switch (setup.emulation) {
                    case RESID -> "ReSID";
                    case RESIDFP -> "ReSIDfp";
                    case RESIDFP_CIRCUIT -> "ReSIDfp Circuit";
                    default -> setup.emulation.name();
                } + " · " + setup.filterName() + "    |    $" + Integer.toHexString(setup.address).toUpperCase();
        if ((setup.declaredModel.equals("MOS6581") || setup.declaredModel.equals("MOS8580"))
                && !setup.declaredModel.equals(setup.model.name())) text += "\n" + MessageFormat.format(
                bundle.getString("SOUND_FILE_MODEL"), setup.declaredModel.replace("MOS", ""));
        if ((setup.declaredClock.equals("PAL") || setup.declaredClock.equals("NTSC"))
                && !setup.declaredClock.equals(setup.clock.name())) text += "\n" + MessageFormat.format(
                bundle.getString("SOUND_FILE_CLOCK"), setup.declaredClock);
        return text;
    }

    private double x(int fc) { return 55 + fc / 2047.0 * Math.max(1, canvas.getWidth() - 73); }
    private double y(double hz) { return 198 - Math.log10(Math.max(20, Math.min(30000, hz)) / 20) / Math.log10(1500) * 180; }

    private void draw() {
        GraphicsContext g = canvas.getGraphicsContext2D();
        g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
        if (backgroundWidth != canvas.getWidth() || backgroundSetup != current || backgroundBypassed != bypassed) background = null;
        if (background == null) {
            drawBackground(g);
            if (canvas.getWidth() > 0) {
                var parameters = new javafx.scene.SnapshotParameters();
                parameters.setFill(Color.TRANSPARENT);
                background = canvas.snapshot(parameters, null);
                backgroundWidth = canvas.getWidth();
                backgroundSetup = current;
                backgroundBypassed = bypassed;
            }
        } else {
            g.drawImage(background, 0, 0);
        }
        if (curve == null) return;
        if (!bypassed && cutoff >= 0 && Double.isFinite(curve[cutoff]) && curve[cutoff] >= 0) {
            g.setStroke(Color.web("#f5ce89"));
            g.setLineWidth(1);
            g.strokeLine(x(cutoff), 18, x(cutoff), 198);
            g.setFill(Color.web("#f5ce89"));
            g.fillOval(x(cutoff) - 5, y(curve[cutoff]) - 5, 10, 10);
        }
    }

    private void drawBackground(GraphicsContext g) {
        g.setStroke(Color.web("#3c535b"));
        g.setFill(Color.web("#b3c8c9"));
        g.setLineWidth(1);
        for (int hz : new int[]{20, 100, 1000, 10000, 30000}) {
            g.strokeLine(55, y(hz), canvas.getWidth() - 18, y(hz));
            g.fillText(hz >= 1000 ? hz / 1000 + "k" : String.valueOf(hz), 8, y(hz) + 4);
        }
        g.fillText("Hz", 55, 12);
        g.fillText("0", 55, 223);
        g.fillText("2047", canvas.getWidth() - 48, 223);
        g.fillText(bundle.getString("SOUND_CUTOFF"), Math.max(60, canvas.getWidth() / 2 - 40), 223);
        if (curve == null) return;
        g.setStroke(Color.web(bypassed ? "#496d69" : "#55d7c2"));
        g.setLineWidth(2);
        g.beginPath();
        boolean connected = false;
        for (int fc = 0; fc < curve.length; fc++) {
            if (!Double.isFinite(curve[fc]) || curve[fc] < 0) { connected = false; continue; }
            if (connected) g.lineTo(x(fc), y(curve[fc])); else g.moveTo(x(fc), y(curve[fc]));
            connected = true;
        }
        g.stroke();
    }

}