InspectionService.java

package libsidutils.debug;

import libsidplay.C64;
import libsidplay.common.Event;
import libsidplay.common.Event.Phase;
import libsidplay.common.EventScheduler;
import libsidplay.components.mos656x.IPALEmulation;
import libsidplay.components.mos656x.VIC;
import libsidplay.components.mos656x.VICInspection;
import libsidplay.components.mos656x.VICInspection.State;
import libsidplay.components.pla.PLA;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * Demand-driven inspection and visual breakpoints, shared by desktop and TeaVM. All methods run on the emulation
 * thread. The normal VIC, CPU and scheduler paths contain no debug callbacks. Live collection adds one scheduled event
 * at 10 Hz. Only armed state rules schedule phase-level probes; raster rules schedule their next position directly.
 * Probes read scalar state and allocate a packet only on a hit. There is no implicit history recording.
 */
public final class InspectionService {
    public static final int STATE = 1, SPRITES = 2, CHARACTERS = 4, SCREEN = 8, VIDEO = 16, ALL = 31;
    public static final int VERSION = 1;
    private static final int[] EMPTY = new int[0];
    private static final int MAX_BREAKPOINTS = 16;

    public enum BreakpointType {
        RASTER, SPRITE_BACKGROUND_COLLISION, SPRITE_SPRITE_COLLISION, SPRITE_DMA, VIC_REGISTER, VIC_BANK, DISPLAY_MODE
    }

    /**
     * RASTER: target=line, value=core cycle. VIC_REGISTER: target=register offset, value/mask=matching bits.
     * Collision/DMA: mask=participating sprite bits. Bank/mode: any change. Rules are one-shot by default in the UI.
     */
    public record Breakpoint(BreakpointType type, int target, int value, int mask, boolean oneShot) {
    }

    private static final class Armed {
        final int id;
        final Breakpoint rule;
        int previous;
        long lastHitTime = Long.MIN_VALUE;

        Armed(int id, Breakpoint rule, int previous) {
            this.id = id;
            this.rule = rule;
            this.previous = previous;
        }
    }

    public final class Subscription implements AutoCloseable {
        private final int channels;
        private final Consumer<InspectionSnapshot> listener;

        private Subscription(int channels, Consumer<InspectionSnapshot> listener) {
            this.channels = channels;
            this.listener = listener;
        }

        @Override
        public void close() {
            if (subscribers.remove(this)) updateEvents();
        }
    }

    /**
     * A visible view needs every frame rendered, even with periodic snapshots switched off.
     */
    public final class VideoSubscription implements AutoCloseable {
        private boolean closed;

        private VideoSubscription() {
            videoViews++;
            updateVideoDemand();
        }

        @Override
        public void close() {
            if (!closed) {
                closed = true;
                videoViews--;
                updateVideoDemand();
            }
        }
    }

    private final C64 c64;
    private final EventScheduler scheduler;
    private final List<Subscription> subscribers = new ArrayList<>();
    private final List<Armed> breakpoints = new ArrayList<>();
    private final Event sampler = Event.of("Inspection live snapshot", event -> sample());
    private final Event phi1Probe = Event.of("Inspection VIC breakpoint", event -> probe(Phase.PHI1));
    private final Event phi2Probe = Event.of("Inspection CPU breakpoint", event -> probe(Phase.PHI2));
    private final Event rasterProbe = Event.of("Inspection raster breakpoint", event -> rasterProbe());
    private Consumer<InspectionSnapshot> pauseHandler = snapshot -> {
    };
    private Consumer<String> statusListener = status -> {
    };
    private volatile InspectionSnapshot latest;
    private volatile boolean paused;
    private boolean stopped;
    private int generation, nextBreakpointId;
    private long captures;
    private int videoViews;
    private IPALEmulation inspectedRenderer;
    private TimelineRecorder timelineRecorder;
    private volatile InspectionTimeline timeline;

    public InspectionService(C64 c64) {
        this.c64 = c64;
        scheduler = c64.getEventScheduler();
    }

    public Subscription subscribe(int channels, Consumer<InspectionSnapshot> listener) {
        if ((channels & ~ALL) != 0 || listener == null) {
            throw new IllegalArgumentException("Invalid inspection subscription");
        }
        Subscription subscription = new Subscription(channels | STATE, listener);
        subscribers.add(subscription);
        if (paused && latest != null) listener.accept(latest);
        updateEvents();
        return subscription;
    }

    public void setPauseHandler(Consumer<InspectionSnapshot> handler) {
        pauseHandler = handler;
    }

    public VideoSubscription watchVideo() {
        return new VideoSubscription();
    }

    public void setStatusListener(Consumer<String> listener) {
        statusListener = listener;
        publishStatus();
    }

    public boolean isPaused() {
        return paused;
    }

    public boolean isArmed() {
        return !breakpoints.isEmpty();
    }

    public InspectionSnapshot latest() {
        return latest;
    }

    public long captures() {
        return captures;
    }

    public int breakpointCount() {
        return breakpoints.size();
    }

    public InspectionTimeline timeline() {
        return timeline;
    }

    public boolean isRecordingTimeline() {
        return timelineRecorder != null;
    }

    public void recordTimeline(Consumer<InspectionTimeline> listener) {
        if (listener == null) throw new IllegalArgumentException("A timeline listener is required");
        if (paused || stopped) throw new IllegalStateException("Resume playback before recording a frame");
        if (timelineRecorder != null) throw new IllegalStateException("A frame is already being recorded");
        timelineRecorder = new TimelineRecorder(c64, generation, result -> {
            timeline = result;
            if (!result.recording()) timelineRecorder = null;
            publishStatus();
            listener.accept(result);
        });
        timelineRecorder.start();
    }

    public void cancelTimeline() {
        finishTimeline("CANCELLED", true);
    }

    public void clearTimeline() {
        if (timelineRecorder != null) timelineRecorder.discard();
        timelineRecorder = null;
        timeline = null;
        publishStatus();
    }

    private void finishTimeline(String status, boolean observe) {
        if (timelineRecorder != null) timelineRecorder.finish(status, observe);
    }

    public int arm(Breakpoint rule) {
        validate(rule);
        if (breakpoints.size() >= MAX_BREAKPOINTS) {
            throw new IllegalStateException("At most 16 visual breakpoints may be armed");
        }
        Armed armed = new Armed(++nextBreakpointId, rule, conditionValue(rule));
        breakpoints.add(armed);
        updateEvents();
        return armed.id;
    }

    public void disarm() {
        breakpoints.clear();
        updateEvents();
    }

    public void removeBreakpoint(int id) {
        breakpoints.removeIf(armed -> armed.id == id);
        updateEvents();
    }

    public InspectionSnapshot snapshot(int channels) {
        return capture(channels | STATE, "SNAPSHOT", null);
    }

    public InspectionSnapshot freeze(int channels) {
        paused = true;
        cancelEvents();
        finishTimeline("INTERRUPTED", true);
        InspectionSnapshot snapshot = capture(channels | STATE, "FREEZE", null);
        publish(snapshot);
        publishStatus();
        pauseHandler.accept(snapshot);
        return snapshot;
    }

    public void resume() {
        paused = false;
        updateEvents();
    }

    /**
     * Called after the machine reset, whose scheduler has discarded all inspection events. Rules never cross resets.
     */
    public void reset() {
        cancelEvents();
        clearTimeline();
        breakpoints.clear();
        paused = false;
        stopped = false;
        latest = null;
        generation++;
        updateEvents();
    }

    /**
     * Stop host playback without retaining active probes. View subscriptions may resume after the next reset.
     */
    public void stop() {
        cancelEvents();
        clearTimeline();
        breakpoints.clear();
        paused = false;
        stopped = true;
        latest = null;
        updateVideoDemand();
        publishStatus();
    }

    /**
     * Browser/embedding loop: stop inside the current batch, before executing another scheduled event after a hit.
     */
    public void clock(int events) throws InterruptedException {
        for (int i = 0; i < events && !paused; i++) {
            scheduler.clock();
        }
    }

    private void validate(Breakpoint rule) {
        if (rule == null || rule.type() == null) throw new IllegalArgumentException("Breakpoint type is required");
        VIC vic = c64.getVIC();
        int lines = vic.getCyclesPerFrame() / vic.getCyclesPerLine();
        if (rule.type() == BreakpointType.RASTER && (rule.target() < 0 || rule.target() >= lines
                || rule.value() < 1 || rule.value() > vic.getCyclesPerLine())) {
            throw new IllegalArgumentException("Raster or core cycle is outside the active VIC model");
        }
        if (rule.type() == BreakpointType.VIC_REGISTER && (rule.target() < 0 || rule.target() >= 64
                || rule.value() < 0 || rule.value() > 255 || rule.mask() < 1 || rule.mask() > 255)) {
            throw new IllegalArgumentException("Register offset, value or mask is outside its range");
        }
        if ((rule.type() == BreakpointType.SPRITE_BACKGROUND_COLLISION
                || rule.type() == BreakpointType.SPRITE_SPRITE_COLLISION || rule.type() == BreakpointType.SPRITE_DMA)
                && (rule.mask() < 1 || rule.mask() > 255)) {
            throw new IllegalArgumentException("A nonempty sprite mask is required");
        }
    }

    private int requestedChannels() {
        int channels = STATE;
        for (Subscription subscriber : subscribers) channels |= subscriber.channels;
        return channels;
    }

    private void updateEvents() {
        updateVideoDemand();
        if (paused && latest != null && latest.armed() != breakpoints.size()) {
            latest = latest.withArmed(breakpoints.size());
        }
        scheduler.cancel(phi1Probe);
        scheduler.cancel(phi2Probe);
        scheduler.cancel(rasterProbe);
        if (paused || stopped || subscribers.isEmpty()) scheduler.cancel(sampler);
        if (!paused && !stopped) {
            if (!subscribers.isEmpty() && !scheduler.isPending(sampler)) scheduler.schedule(sampler, 0, Phase.PHI2);
            boolean phi1 = false, phi2 = false, raster = false;
            for (Armed armed : breakpoints) {
                switch (armed.rule.type()) {
                    case RASTER -> raster = true;
                    case SPRITE_DMA -> phi1 = true;
                    case SPRITE_BACKGROUND_COLLISION, SPRITE_SPRITE_COLLISION -> {
                        // Observe both VIC assertions and CPU collision-register clears between assertions.
                        phi1 = phi2 = true;
                    }
                    default -> phi2 = true;
                }
            }
            if (phi1) scheduler.schedule(phi1Probe, 0, Phase.PHI1);
            if (phi2) scheduler.schedule(phi2Probe, 0, Phase.PHI2);
            if (raster) scheduler.schedule(rasterProbe, 0, Phase.PHI1);
        }
        publishStatus();
    }

    private void cancelEvents() {
        scheduler.cancel(sampler);
        scheduler.cancel(phi1Probe);
        scheduler.cancel(phi2Probe);
        scheduler.cancel(rasterProbe);
    }

    private void updateVideoDemand() {
        IPALEmulation renderer = c64.getVIC().getPalEmulation();
        if (inspectedRenderer != null && inspectedRenderer != renderer) inspectedRenderer.setInspectionRendering(false);
        inspectedRenderer = renderer;
        boolean needed = videoViews > 0 || !breakpoints.isEmpty();
        for (Subscription subscriber : subscribers) needed |= (subscriber.channels & VIDEO) != 0;
        if (renderer != null) renderer.setInspectionRendering(!stopped && needed);
    }

    private void publishStatus() {
        statusListener.accept(stopped ? "OFF" : paused ? "PAUSED" : !breakpoints.isEmpty() ? "ARMED"
                : timelineRecorder != null ? "RECORDING" : !subscribers.isEmpty() ? "LIVE" : "OFF");
    }

    private void sample() {
        if (paused || subscribers.isEmpty()) return;
        publish(capture(requestedChannels() & ~VIDEO, "LIVE", null));
        if (!paused && !stopped && !subscribers.isEmpty() && !scheduler.isPending(sampler)) {
            scheduler.schedule(sampler, Math.max(1, (long) (c64.getClock().getCpuFrequency() / 10)), Phase.PHI2);
        }
    }

    private void publish(InspectionSnapshot snapshot) {
        latest = snapshot;
        for (Subscription subscriber : new ArrayList<>(subscribers)) subscriber.listener.accept(snapshot);
    }

    private void probe(Phase phase) {
        if (paused) return;
        for (Armed armed : breakpoints) {
            Breakpoint rule = armed.rule;
            if (rule.type() == BreakpointType.RASTER
                    || phase == Phase.PHI1 && rule.type() != BreakpointType.SPRITE_DMA
                    && rule.type() != BreakpointType.SPRITE_BACKGROUND_COLLISION
                    && rule.type() != BreakpointType.SPRITE_SPRITE_COLLISION
                    || phase == Phase.PHI2 && rule.type() == BreakpointType.SPRITE_DMA) continue;
            int current = conditionValue(rule);
            boolean matches = switch (rule.type()) {
                case SPRITE_BACKGROUND_COLLISION, SPRITE_SPRITE_COLLISION, SPRITE_DMA ->
                        (current & ~armed.previous & rule.mask()) != 0;
                case VIC_REGISTER -> (current & rule.mask()) == (rule.value() & rule.mask())
                        && (armed.previous & rule.mask()) != (rule.value() & rule.mask());
                default -> current != armed.previous;
            };
            if (matches) {
                hit(armed);
                armed.previous = current;
                return;
            }
            armed.previous = current;
        }
        scheduler.schedule(phase == Phase.PHI1 ? phi1Probe : phi2Probe, 1, phase);
    }

    private int conditionValue(Breakpoint rule) {
        byte[] registers = c64.getVIC().getRegisters();
        return switch (rule.type()) {
            case RASTER -> 0;
            case SPRITE_BACKGROUND_COLLISION -> registers[0x1f] & 255;
            case SPRITE_SPRITE_COLLISION -> registers[0x1e] & 255;
            case SPRITE_DMA -> VICInspection.dmaMask(c64.getVIC());
            case VIC_REGISTER -> registers[rule.target()] & 255;
            case VIC_BANK -> c64.getVicMemBase();
            case DISPLAY_MODE -> (registers[0x11] & 0x60) >> 4 | (registers[0x16] & 0x10) >> 4;
        };
    }

    private void rasterProbe() {
        if (paused) return;
        VIC vic = c64.getVIC();
        int cycle = VICInspection.cycle(vic), raster = VICInspection.raster(vic);
        int lineCycles = vic.getCyclesPerLine(), frameCycles = vic.getCyclesPerFrame();
        int current = raster * lineCycles + (cycle + lineCycles - 10) % lineCycles;
        int next = frameCycles;
        for (Armed armed : breakpoints) {
            if (armed.rule.type() != BreakpointType.RASTER) continue;
            if (raster == armed.rule.target() && cycle == armed.rule.value()
                    && armed.lastHitTime != scheduler.getTime(scheduler.phase())) {
                hit(armed);
                return;
            }
            int target = armed.rule.target() * lineCycles + (armed.rule.value() + lineCycles - 10) % lineCycles;
            int delta = (target - current + frameCycles) % frameCycles;
            next = Math.min(next, delta == 0 ? frameCycles : delta);
        }
        scheduler.schedule(rasterProbe, next, Phase.PHI1);
    }

    private void hit(Armed armed) {
        paused = true;
        armed.lastHitTime = scheduler.getTime(scheduler.phase());
        if (armed.rule.oneShot()) breakpoints.remove(armed);
        cancelEvents();
        finishTimeline("INTERRUPTED", true);
        InspectionSnapshot snapshot = capture(ALL, "BREAKPOINT", armed);
        updateVideoDemand();
        publish(snapshot);
        publishStatus();
        pauseHandler.accept(snapshot);
    }

    private InspectionSnapshot capture(int channels, String reason, Armed armed) {
        if ((channels & ~ALL) != 0) throw new IllegalArgumentException("Unknown inspection channel");
        captures++;
        VIC vic = c64.getVIC();
        State state = VICInspection.capture(vic);
        PLA pla = c64.getCartridge().pla;
        int[] pointers = EMPTY, sprites = EMPTY, characters = EMPTY, screen = EMPTY, colors = EMPTY, bitmap = EMPTY;
        if ((channels & SPRITES) != 0) {
            pointers = memory(pla, state.screenAddress() | 0x3f8, 8, false);
            sprites = new int[8 * 64];
            for (int sprite = 0; sprite < 8; sprite++)
                for (int i = 0; i < 64; i++) {
                    sprites[sprite * 64 + i] = pointers[sprite] < 0 ? -1
                            : pla.peekVicMemory(pointers[sprite] * 64 + i, false);
                }
        }
        if ((channels & CHARACTERS) != 0) characters = memory(pla, state.characterAddress(), 2048, false);
        if ((channels & SCREEN) != 0) {
            screen = memory(pla, state.screenAddress(), 1000, true);
            colors = new int[1000];
            for (int i = 0; i < colors.length; i++) colors[i] = pla.peekColorMemory(i);
            if ((state.registers()[0x11] & 0x20) != 0) bitmap = memory(pla, state.bitmapAddress(), 8000, false);
        }
        Phase phase = scheduler.phase();
        long time = scheduler.getTime(phase);
        Breakpoint rule = armed == null ? null : armed.rule;
        return new InspectionSnapshot(VERSION, generation, time, time / vic.getCyclesPerFrame(), phase.name(),
                c64.getModel().name(), c64.getConfiguredVicModel().name(), c64.getClock().name(), vic.getCyclesPerLine(),
                vic.getCyclesPerFrame() / vic.getCyclesPerLine(), channels, paused, breakpoints.size(), reason,
                armed == null ? 0 : armed.id, rule == null ? "NONE" : rule.type().name(),
                rule == null ? 0 : rule.target(), rule == null ? 0 : rule.value(), rule == null ? 0 : rule.mask(),
                armed == null ? 0 : armed.previous, rule == null ? 0 : conditionValue(rule),
                c64.getVicMemBase(), pla.getBusState(), state, pointers, sprites, characters, screen, colors, bitmap,
                (channels & VIDEO) != 0 ? InspectionFrame.capture(vic, time) : null);
    }

    private static int[] memory(PLA pla, int address, int length, boolean phi2) {
        int[] bytes = new int[length];
        for (int i = 0; i < length; i++) bytes[i] = pla.peekVicMemory(address + i, phi2);
        return bytes;
    }
}