SameThreadC1541Runner.java

package libsidplay.components.c1541;

import libsidplay.common.Event;
import libsidplay.common.EventScheduler;

/**
 * Runs the drive scheduler on the C64 emulation thread until both clock domains are synchronized.
 */
public class SameThreadC1541Runner extends C1541Runner {
    protected boolean notTerminated;
    /**
     * Absolute drive scheduler cycle at which the current synchronization run stops.
     */
    private long deadline;

    private final Event terminationEvent = Event.of("Pause C1541", event -> notTerminated = false);

    public SameThreadC1541Runner(final EventScheduler c64Context, final EventScheduler c1541Context) {
        super(c64Context, c1541Context);
    }

    private void clockC1541Context(int targetTime) {
        if (targetTime <= 0) {
            return;
        }

        deadline = c1541Context.getTime(Event.Phase.PHI2) + targetTime;
        c1541Context.scheduleAbsoluteBefore(terminationEvent, deadline, Event.Phase.PHI2);
        notTerminated = true;

        try {
            while (notTerminated) {
                c1541Context.clock();
            }
        } catch (final InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Rescale an active synchronization deadline before changing the drive CPU frequency.
     *
     * @param frequency new drive CPU frequency in Hz
     */
    @Override
    public void setDriveFrequency(double frequency) {
        if (notTerminated) {
            long now = c1541Context.getTime(Event.Phase.PHI2);
            deadline = now + super.setDriveFrequency(frequency, Math.max(0, deadline - now));
            c1541Context.cancel(terminationEvent);
            c1541Context.scheduleAbsoluteBefore(terminationEvent, deadline, Event.Phase.PHI2);
        } else {
            super.setDriveFrequency(frequency);
        }
    }

    @Override
    public void reset() {
        cancel();
        super.reset();
        c64Context.schedule(this, 0, Event.Phase.PHI2);
    }

    @Override
    public void cancel() {
        c64Context.cancel(this);

        c1541Context.cancel(terminationEvent);
    }

    /**
     * Synchronize C1541 and C64 schedulers. Called by C64; C1541 will be sleeping and in sync once we return.
     */
    @Override
    public void synchronize(long offset) {
        clockC1541Context(updateSlaveTicks(offset));
    }

    /** Advance to the CIA's write phase plus the modeled IEC output delay. */
    public void synchronizeIecWrite(int nanos) {
        clockC1541Context(updateSlaveTicks(0, true, nanos));
    }

    /** The CIA sample sees drive PHI2 accesses strictly before this deadline. */
    public long iecReadDeadline(int nanos) {
        return slaveReadDeadline(nanos);
    }

    @Override
    public void event() throws InterruptedException {
        synchronize(0);
        c64Context.schedule(this, 2000);
    }

}