ThrottlingDriver.java

package sidplay.audio;

import libsidplay.common.CPUClock;
import libsidplay.common.Event.Phase;
import libsidplay.common.EventScheduler;
import libsidplay.config.IAudioSection;

import javax.sound.sampled.LineUnavailableException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.function.LongSupplier;
import java.util.logging.Level;
import java.util.logging.Logger;

import static java.lang.Short.BYTES;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static libsidplay.config.IAudioSystemProperties.MAX_TIME_GAP;
import static libsidplay.config.IAudioSystemProperties.SLEEP_DRIVER_SLEEP_TIME;

/**
 * No sound output, but paces audio/video production against a monotonic clock.
 * Browser feedback can add backpressure; it never disables real-time pacing.
 *
 * @author ken
 *
 */
public class ThrottlingDriver implements AudioDriver {

    private static final Logger THROTTLING_DRIVER = Logger.getLogger(ThrottlingDriver.class.getName());

    @FunctionalInterface
    interface NanoSleeper {
        void sleep(long nanos) throws InterruptedException;
    }

    private final LongSupplier nanoTime;
    private final NanoSleeper sleeper;
    private final long maxSleepNanos;

    public ThrottlingDriver() {
        this(System::nanoTime, NANOSECONDS::sleep);
    }

    ThrottlingDriver(LongSupplier nanoTime, NanoSleeper sleeper) {
        if (SLEEP_DRIVER_SLEEP_TIME <= 0) {
            throw new IllegalArgumentException("jsidplay2.sleep_driver.sleep_time must be positive");
        }
        this.nanoTime = nanoTime;
        this.sleeper = sleeper;
        maxSleepNanos = MILLISECONDS.toNanos(SLEEP_DRIVER_SLEEP_TIME);
    }

    private EventScheduler context;
    private double nanosPerCycle;

    /**
     * Emulation time and wall time at the preceding paced submission. Rebased
     * after waiting so slow production or backpressure cannot create catchup credit.
     */
    private long lastC64Time, lastWriteNanos;
    private boolean started;

    private record ClientTiming(long currentTime, long bufferedEnd) {
    }

    /** A single snapshot keeps values from successive keep-alives together. */
    private volatile ClientTiming clientTiming;

    private ByteBuffer sampleBuffer;

    @Override
    public void open(IAudioSection audioSection, String recordingFilename, CPUClock cpuClock, EventScheduler context)
            throws IOException, LineUnavailableException, InterruptedException {
        this.context = context;
        nanosPerCycle = 1e9 / cpuClock.getCpuFrequency();
        AudioConfig cfg = new AudioConfig(audioSection);

        started = false;
        lastC64Time = 0;
        lastWriteNanos = 0;
        clientTiming = null;
        sampleBuffer = ByteBuffer.allocateDirect(cfg.getChunkFrames() * BYTES * cfg.getChannels()).order(LITTLE_ENDIAN);
    }

    @Override
    public void write() throws InterruptedException {
        pace(context.getTime(Phase.PHI2));
    }

    @Override
    public void write(long firstCycle, long lastCycle, long sampleOffset, int frames) throws InterruptedException {
        // The scheduler may already be beyond the end of this PCM chunk.
        pace(lastCycle);
    }

    private void pace(long c64Time) throws InterruptedException {
        if (started && c64Time >= lastC64Time) {
            long mediaNanos = (long) ((c64Time - lastC64Time) * nanosPerCycle);
            sleepUntil(lastWriteNanos + mediaNanos);
        }

        // Read after pacing so a keep-alive received during the wait is used.
        ClientTiming timing = clientTiming;
        if (timing != null) {
            long gap = timing.bufferedEnd() - timing.currentTime();
            if (gap > MAX_TIME_GAP) {
                long sleepTime = Math.min(gap - MAX_TIME_GAP, SLEEP_DRIVER_SLEEP_TIME);

                if (THROTTLING_DRIVER.isLoggable(Level.FINE)) {
                    THROTTLING_DRIVER.fine(String.format(
                            "clientTime=%dms, bufferedEnd=%dms, gap=%dms, additionalSleep=%dms",
                            timing.currentTime(), timing.bufferedEnd(), gap, sleepTime));
                }
                sleepUntil(nanoTime.getAsLong() + MILLISECONDS.toNanos(sleepTime));
            }
        }

        lastC64Time = c64Time;
        lastWriteNanos = nanoTime.getAsLong();
        started = true;
    }

    private void sleepUntil(long deadline) throws InterruptedException {
        long remaining;
        while ((remaining = deadline - nanoTime.getAsLong()) > 0) {
            sleeper.sleep(Math.min(remaining, maxSleepNanos));
        }
    }

    public void setClientTime(Long clientTime, Long bufferedEnd) {
        clientTiming = clientTime != null && bufferedEnd != null ? new ClientTiming(clientTime, bufferedEnd) : null;
    }

    @Override
    public void close() {
    }

    @Override
    public ByteBuffer buffer() {
        return sampleBuffer;
    }

    @Override
    public boolean isRecording() {
        return false;
    }

}