Timer.java

package sidplay.player;

import libsidplay.common.Event;
import libsidplay.common.Event.Phase;
import libsidplay.common.EventScheduler;
import libsidplay.config.ISidPlay2Section;
import libsidplay.sidtune.AudioTune;
import libsidplay.sidtune.SidTune;
import libsidplay.sidtune.SidTuneInfo;

import java.util.function.DoubleSupplier;

import static libsidplay.sidtune.SidTune.RESET;

/**
 * The timer contains the start and end time of a currently played song. It notifies about reaching the start and end
 * time by calling start/stop methods. Additionally, the fade-in and fade-out start time notification has been added.
 */
public abstract class Timer {

    /**
     * Timer start time in seconds.
     */
    private double start;

    /**
     * Timer ends in seconds
     */
    private double end;

    /**
     * Fade-in time in seconds (0 means no fade-in).
     */
    private double fadeIn;

    /**
     * Fade-out time in seconds (0 means no fade-out).
     */
    private double fadeOut;

    /**
     * Limited song length in s, if song length is unknown.
     */
    private double defaultLength;

    private boolean forceCheckSongLength;
    private boolean songLengthKnown;
    private boolean silenceDetectionSupported;
    private boolean endRequested;

    /**
     * Tune start time has been reached
     */
    private final Event startTimeEvent = Event.of("Timer Start", event -> start());

    /**
     * Tune end time has been reached
     */
    private final Event endTimeEvent = Event.of("Timer End", event -> {
        endRequested = true;
        end();
    });

    /**
     * Tune fade-in time has been reached
     */
    private final Event fadeInStartTimeEvent = Event.of("Fade-in Start", event -> fadeInStart(fadeIn));

    /**
     * Tune fade-out time has been reached
     */
    private final Event fadeOutStartTimeEvent = Event.of("Fade-out Start", event -> fadeOutStart(fadeOut));

    /**
     * The player.
     */
    private final EventScheduler context;

    private final ISidPlay2Section sidplay2Section;

    private final DoubleSupplier lengthFnct;

    /**
     * Create a song length timer for the player
     *
     * @param sidplay2Section configuration
     * @param context         event scheduler
     * @param lengthFnct      SID database length function
     */
    public Timer(ISidPlay2Section sidplay2Section, EventScheduler context, DoubleSupplier lengthFnct) {
        this.sidplay2Section = sidplay2Section;
        this.context = context;
        this.lengthFnct = lengthFnct;
    }

    /**
     * Set tune start time
     *
     * @param start start time
     */
    public final void setStart(final double start) {
        this.start = start;
    }

    public void setDefaultLength(double defaultLength) {
        this.defaultLength = defaultLength;
    }

    public double getDefaultLength() {
        return defaultLength;
    }

    public void setForceCheckSongLength(boolean forceCheckSongLength) {
        this.forceCheckSongLength = forceCheckSongLength;
    }

    /**
     * Reset timer events
     */
    public final void reset(SidTune tune) {
        endRequested = false;
        fadeIn = sidplay2Section.getFadeInTime();
        fadeOut = sidplay2Section.getFadeOutTime();
        schedule(tune, start, startTimeEvent);
        if (tune != RESET && fadeIn != 0) {
            schedule(tune, start, fadeInStartTimeEvent);
        }
        updateEnd(tune);
    }

    /**
     * Update timer end.
     * <UL>
     * <LI>MP3 tune? We always play forever
     * <LI>SLDB enabled and song length well known? Use song length
     * <LI>default length? Use default length relative to start
     * <LI>default length == 0? Play forever
     * </UL>
     */
    public final void updateEnd(SidTune tune) {
        end = 0;
        songLengthKnown = false;
        silenceDetectionSupported = false;
        // cancel last stop time event
        cancel(endTimeEvent);
        if (fadeOut != 0) {
            cancel(fadeOutStartTimeEvent);
        }
        // MP3 tune length is undetermined; therefore, we always play forever
        if (tune instanceof AudioTune) {
            return;
        }
        silenceDetectionSupported = tune != RESET;
        // Only for tunes: check tune song length
        if (tune != SidTune.RESET) {
            // use song length contained in a tune ...
            SidTuneInfo tuneInfo = tune.getInfo();
            double songLength = tuneInfo.isSongLengthsIncluded() ? tuneInfo.getSongLength() / 1000. : 0;
            // use song length of a song length database ...
            if (songLength == 0 && sidplay2Section.isEnableDatabase()) {
                songLength = lengthFnct.getAsDouble();
            }
            if (songLength > 0) {
                songLengthKnown = true;
                // use song length contained in a tune or of a song length database ...
                end = schedule(tune, start + songLength, endTimeEvent);
                if (fadeOut != 0) {
                    schedule(tune, end - fadeOut, fadeOutStartTimeEvent);
                }
                return;
            }
        }
        // ... or play the default length (0 means forever)
        end = tune != SidTune.RESET || forceCheckSongLength ? defaultLength : 0;
        if (end > 0) {
            // use default length (is meant to be relative to start)
            end = schedule(tune, start + end, endTimeEvent);
            if (fadeOut != 0) {
                schedule(tune, end - fadeOut, fadeOutStartTimeEvent);
            }
        }
    }

    /**
     * Initialization delay before playback; cartridge boots can begin immediately.
     */
    protected long getInitDelay(SidTune tune) {
        return SidTune.getInitDelay(tune);
    }

    /**
     * Schedule start or end timer event.<BR> Note: If the event is in the past: trigger immediately
     *
     * @param seconds absolute schedule time in seconds
     * @param event   timer event to schedule
     */
    private double schedule(SidTune tune, final double seconds, final Event event) {
        long initDelay = getInitDelay(tune);

        long absoluteCycles = (long) (initDelay + seconds * context.getCyclesPerSecond());
        if (absoluteCycles < context.getTime(Phase.PHI1)) {
            // event is in the past? Trigger immediately!
            context.schedule(event, 0, Phase.PHI1);
        } else {
            // event is in the future
            context.scheduleAbsolute(event, absoluteCycles, Phase.PHI1);
        }
        return seconds;
    }

    /**
     * Cancel event.
     *
     * @param event event to cancel
     */
    private void cancel(final Event event) {
        context.cancel(event);
    }

    /**
     * Get tune end time in cycles
     *
     * @return tune end time
     */
    public final double getEnd() {
        return end;
    }

    public final boolean hasKnownLength() {
        return songLengthKnown;
    }

    public final boolean isSilenceDetectionAllowed() {
        return silenceDetectionSupported && !songLengthKnown;
    }

    /** Finish once through the normal callback, without changing the default play length. */
    public final void requestEnd(SidTune tune) {
        if (endRequested) return;
        endRequested = true;
        cancel(endTimeEvent);
        cancel(fadeOutStartTimeEvent);
        end = Math.max(0, (context.getTime(Phase.PHI1) - SidTune.getInitDelay(tune)) / context.getCyclesPerSecond());
        context.schedule(endTimeEvent, 0, Phase.PHI1);
    }

    /**
     * Notification of tune start
     */
    public abstract void start();

    /**
     * Notification of the tune end
     */
    public abstract void end();

    /**
     * Notification of tune fade-in start
     */
    public abstract void fadeInStart(double fadeIn);

    /**
     * Notification of tune fade-out start
     */
    public abstract void fadeOutStart(double fadeOut);

}