C1541Runner.java

package libsidplay.components.c1541;

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

/**
 * Synchronizes a floppy drive scheduler with the C64 master clock.
 */
public abstract class C1541Runner extends Event {
    /**
     * C64 master scheduler and independently clocked drive scheduler.
     */
    protected final EventScheduler c64Context, c1541Context;
    /**
     * Drive cycles per C64 cycle in unsigned 32.32 fixed-point representation.
     */
    private long conversionFactor;
    /**
     * C64 clock used to recalculate the divider after a drive clock change.
     */
    private CPUClock masterClock = CPUClock.PAL;
    /**
     * Current drive CPU frequency in Hz.
     */
    protected double driveFrequency = 1_000_000;
    /**
     * Drive-cycle phase carried between synchronization calls in 32.32 fixed-point representation.
     */
    private long accum;
    /**
     * Last C64 cycle through which the drive has already been synchronized.
     */
    private long c64LastTime;
    /**
     * Subcycle offset of the last synchronization target, in 32.32 drive cycles.
     */
    private long c64LastOffset;

    /**
     * Create a runner for the two clock domains.
     *
     * @param c64Context   C64 master scheduler
     * @param c1541Context drive scheduler
     */
    public C1541Runner(final EventScheduler c64Context, final EventScheduler c1541Context) {
        super("C64 permits C1541 to continue");
        this.c64Context = c64Context;
        this.c1541Context = c1541Context;
        this.c64LastTime = c64Context.getTime(Phase.PHI2);
    }

    /**
     * Return the number of clock ticks that the drive should advance.
     *
     * @param offset adjust C64 cycles
     * @return number of drive clock ticks to advance
     */
    protected int updateSlaveTicks(long offset) {
        return updateSlaveTicks(offset, false, 0);
    }

    protected final int updateSlaveTicks(long offset, boolean halfCycle, int nanos) {
        final long target = c64Context.getTime(Phase.PHI2) + offset;
        final long subcycle = (halfCycle ? conversionFactor / 2 : 0) + driveTicksForNanos(nanos);
        // A write may already have synchronized the drive through the next
        // master cycle. A read or periodic callback cannot undo those clocks.
        if (target < c64LastTime || (target == c64LastTime && subcycle <= c64LastOffset)) {
            return 0;
        }
        accum += conversionFactor * (target - c64LastTime) + subcycle - c64LastOffset;
        c64LastTime = target;
        c64LastOffset = subcycle;

        final int wholeClocks = (int) (accum >> 32);
        accum &= 0xffffffffL;

        return wholeClocks;
    }

    /**
     * Exclusive drive PHI2 deadline for the current host cycle minus a read delay.
     * Compute it from the host time so a preceding catch-up can run past the sample.
     */
    protected final long slaveReadDeadline(int nanos) {
        final long delta = c64Context.getTime(Phase.PHI2) - c64LastTime;
        final long phase = accum + conversionFactor * delta - c64LastOffset - driveTicksForNanos(nanos);
        return c1541Context.getTime(Phase.PHI2) + (phase >> 32);
    }

    private long driveTicksForNanos(int nanos) {
        return Math.round(nanos * driveFrequency * (1L << 32) / 1_000_000_000.0);
    }

    /**
     * Set the C64 master clock used for drive-cycle conversion.
     *
     * @param clock C64 clock
     */
    public void setClockDivider(final CPUClock clock) {
        masterClock = clock;
        conversionFactor = Math.round(driveFrequency / clock.getCpuFrequency() * (1L << 32));
    }

    /**
     * Preserve the fractional physical phase across the 1571's clock switch.
     *
     * @param frequency new drive CPU frequency in Hz
     */
    public void setDriveFrequency(double frequency) {
        rescaleDrivePhase(frequency);
    }

    /**
     * Rescale an active catch-up interval together with its fractional tail.
     * Rounding the deadline and fraction separately can leave a whole new-speed
     * clock pending until the next synchronization call.
     *
     * @param frequency new drive CPU frequency in Hz
     * @param remainingTicks whole drive clocks still permitted in the active run
     * @return rescaled whole clocks remaining in the active run
     */
    protected final long setDriveFrequency(double frequency, long remainingTicks) {
        accum += remainingTicks << 32;
        rescaleDrivePhase(frequency);
        final long wholeClocks = accum >> 32;
        accum &= 0xffffffffL;
        return wholeClocks;
    }

    private void rescaleDrivePhase(double frequency) {
        accum = Math.round(accum * frequency / driveFrequency);
        c64LastOffset = Math.round(c64LastOffset * frequency / driveFrequency);
        driveFrequency = frequency;
        setClockDivider(masterClock);
    }

    /**
     * Restart synchronization at the current C64 time and clear the fractional drive cycle.
     */
    public void reset() {
        c64LastTime = c64Context.getTime(Phase.PHI2);
        c64LastOffset = 0;
        accum = 0;
    }

    /**
     * Cancel scheduled drive synchronization.
     */
    public abstract void cancel();

    /**
     * Advance the drive to a C64 bus-access time.
     *
     * @param offset adjustment to the current C64 cycle
     */
    public abstract void synchronize(long offset);
}