diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 5c6a750..ac7f3ea 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -50,6 +50,48 @@ pub extern "system" fn getPlaybackPosition(_env: JNIEnv, _class: JClass) -> jlon } } +const FILETIME_UNIX_EPOCH: i64 = 116_444_736_000_000_000; // 1970-01-01 in 100ns ticks since 1601-01-01 + +// one TimelineProperties snapshot -> Position and LastUpdatedTime cannot tear +// Spotify only pushes the timeline on pause/seek/track change -> java adds now - LastUpdatedTime while playing +// out_updated_unix_ms is -1 when LastUpdatedTime is not set +#[no_mangle] +pub extern "system" fn getPlaybackTimeline( + out_position_ms: *mut i64, + out_updated_unix_ms: *mut i64, +) -> i32 { + if out_position_ms.is_null() || out_updated_unix_ms.is_null() { + return 0; // false + } + let result = std::panic::catch_unwind(|| { + block_on(async { + match get_spotify_session()? { + Some(session) => { + let timeline = session.GetTimelineProperties()?; + let position = timeline.Position()?.Duration / 10_000; + let updated = timeline.LastUpdatedTime()?.UniversalTime; // FILETIME ticks, UTC + let updated_unix_ms = if updated > FILETIME_UNIX_EPOCH { + (updated - FILETIME_UNIX_EPOCH) / 10_000 + } else { + -1 + }; + Ok((position, updated_unix_ms)) + } + _ => Err(Error::new(E_FAIL, "Spotify session not found")), + } + }) + }); + + match result { + Ok(Ok((position, updated_unix_ms))) => unsafe { + *out_position_ms = position; + *out_updated_unix_ms = updated_unix_ms; + 1 // true + }, + _ => 0, // false + } +} + #[no_mangle] pub extern "system" fn getTrackDuration(_env: JNIEnv, _class: JClass) -> jlong { let result = std::panic::catch_unwind(|| { diff --git a/src/main/java/de/labystudio/spotifyapi/config/SpotifyConfiguration.java b/src/main/java/de/labystudio/spotifyapi/config/SpotifyConfiguration.java index 6e11fde..331dcaa 100644 --- a/src/main/java/de/labystudio/spotifyapi/config/SpotifyConfiguration.java +++ b/src/main/java/de/labystudio/spotifyapi/config/SpotifyConfiguration.java @@ -13,15 +13,18 @@ public class SpotifyConfiguration { private final long exceptionReconnectDelay; private final boolean autoReconnect; private final Path nativesDirectory; + private final long tickInterval; private SpotifyConfiguration( long exceptionReconnectDelay, boolean autoReconnect, - Path nativesDirectory + Path nativesDirectory, + long tickInterval ) { this.exceptionReconnectDelay = exceptionReconnectDelay; this.autoReconnect = autoReconnect; this.nativesDirectory = nativesDirectory; + this.tickInterval = tickInterval; } public long getExceptionReconnectDelay() { @@ -36,6 +39,10 @@ public Path getNativesDirectory() { return this.nativesDirectory; } + public long getTickInterval() { + return this.tickInterval; + } + /** * Builder to create a new spotify configuration */ @@ -44,6 +51,7 @@ public static class Builder { private long exceptionReconnectDelay = 1000 * 10L; private boolean autoReconnect = true; private Path nativesDirectory = Paths.get(System.getProperty("java.io.tmpdir"), "spotify-api-natives"); + private long tickInterval = 1000L; /** * Set the delay between reconnects when an exception occurs @@ -79,11 +87,24 @@ public Builder nativesDirectory(Path nativesDirectory) { return this; } + /** + * Set how often Spotify is polled for track, playback state and position changes. + * A lower interval detects seeks, pauses and track changes sooner but queries Spotify more often. + * + * @param tickInterval The interval in milliseconds, at least 50 + * @return The builder instance + */ + public Builder tickInterval(long tickInterval) { + this.tickInterval = Math.max(50L, tickInterval); + return this; + } + public SpotifyConfiguration build() { return new SpotifyConfiguration( this.exceptionReconnectDelay, this.autoReconnect, - this.nativesDirectory + this.nativesDirectory, + this.tickInterval ); } } diff --git a/src/main/java/de/labystudio/spotifyapi/platform/AbstractTickSpotifyAPI.java b/src/main/java/de/labystudio/spotifyapi/platform/AbstractTickSpotifyAPI.java index 0576add..6e5e079 100644 --- a/src/main/java/de/labystudio/spotifyapi/platform/AbstractTickSpotifyAPI.java +++ b/src/main/java/de/labystudio/spotifyapi/platform/AbstractTickSpotifyAPI.java @@ -19,7 +19,7 @@ */ public abstract class AbstractTickSpotifyAPI implements SpotifyAPI { - protected static final long TICK_INTERVAL = 1000L; // 1 second + protected static final long TICK_INTERVAL = 1000L; // default, see SpotifyConfiguration#getTickInterval /** * The list of all Spotify listeners. @@ -30,6 +30,8 @@ public abstract class AbstractTickSpotifyAPI implements SpotifyAPI { protected SpotifyConfiguration configuration; + protected final PlaybackClock clock = new PlaybackClock(); + private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(runnable -> { Thread thread = new Thread(runnable, "spotify-api-tick"); thread.setDaemon(true); @@ -42,7 +44,7 @@ public abstract class AbstractTickSpotifyAPI implements SpotifyAPI { /** * Initialize the SpotifyAPI abstract tick implementation. - * It will create a task that will update the current track and position every second. + * It will create a task that will update the current track and position every tick interval. * * @return the initialized SpotifyAPI * @throws IllegalStateException if the API is already initialized or has been shutdown @@ -62,11 +64,10 @@ public SpotifyAPI initialize(SpotifyConfiguration configuration) { this.onInitialized(); - // Start task to update every second this.task = this.executor.scheduleWithFixedDelay( this::onInternalTick, 0L, - TICK_INTERVAL, + configuration.getTickInterval(), TimeUnit.MILLISECONDS ); @@ -106,6 +107,20 @@ protected synchronized void onInternalTick() { protected abstract void onTick() throws Exception; + /** + * Feed a measured position into the playback clock and fire {@link SpotifyListener#onPositionChanged(int)} on a seek. + * + * @param position the measured position in milliseconds + * @param sampledAtNanos the {@link PlaybackClock#now()} value the measurement belongs to + * @param playing true if the track was playing at that time + */ + protected void updatePosition(long position, long sampledAtNanos, boolean playing) { + if (this.clock.update(position, sampledAtNanos, playing)) { + int current = (int) this.clock.getPosition(); + this.listeners.forEach(listener -> listener.onPositionChanged(current)); + } + } + @Override public void registerListener(SpotifyListener listener) { this.listeners.add(listener); diff --git a/src/main/java/de/labystudio/spotifyapi/platform/PlaybackClock.java b/src/main/java/de/labystudio/spotifyapi/platform/PlaybackClock.java new file mode 100644 index 0000000..aaa3ddb --- /dev/null +++ b/src/main/java/de/labystudio/spotifyapi/platform/PlaybackClock.java @@ -0,0 +1,92 @@ +package de.labystudio.spotifyapi.platform; + +import java.util.function.LongSupplier; + +public class PlaybackClock { + + public static final long SEEK_THRESHOLD = 1000L; // ms, a bigger drift counts as a seek + public static final long RESYNC_THRESHOLD = 60L; // ms, below this we only nudge the anchor + + private final LongSupplier nanoTime; + + private long anchorPosition = -1; // ms, -1 = unknown + private long anchorNanos; + private boolean playing; + private boolean resync; // next update re-anchors and reports, set on track change + private long length = -1; // ms, -1 = no clamp + + public PlaybackClock() { + this(System::nanoTime); + } + + public PlaybackClock(LongSupplier nanoTime) { + this.nanoTime = nanoTime; + } + + public long now() { + return this.nanoTime.getAsLong(); + } + + /** + * Feed a position measured at the given time. + * + * @param position the measured position in milliseconds + * @param sampledAtNanos the {@link #now()} value the measurement belongs to + * @param playing true if the track was playing at that time + * @return true if the position was unknown before or jumped by more than {@link #SEEK_THRESHOLD} + */ + public synchronized boolean update(long position, long sampledAtNanos, boolean playing) { + if (this.anchorPosition < 0 || this.resync) { + this.anchor(position, sampledAtNanos, playing); + return true; + } + + long drift = position - this.positionAt(sampledAtNanos); + if (playing != this.playing || Math.abs(drift) > RESYNC_THRESHOLD) { + this.anchor(position, sampledAtNanos, playing); + } else { + this.anchorPosition += drift / 4; // smooths out query jitter + } + return Math.abs(drift) > SEEK_THRESHOLD; + } + + public synchronized void setLength(long length) { + this.length = length; + } + + public synchronized void resync() { + this.resync = true; + } + + public synchronized void reset() { + this.anchorPosition = -1; + this.playing = false; + this.resync = false; + } + + public synchronized boolean hasPosition() { + return this.anchorPosition >= 0; + } + + public synchronized long getPosition() { + if (this.anchorPosition < 0) { + return -1; + } + return this.positionAt(this.nanoTime.getAsLong()); + } + + private void anchor(long position, long sampledAtNanos, boolean playing) { + this.anchorPosition = Math.max(0, position); + this.anchorNanos = sampledAtNanos; + this.playing = playing; + this.resync = false; + } + + private long positionAt(long nanos) { + if (!this.playing) { + return this.anchorPosition; + } + long position = this.anchorPosition + (nanos - this.anchorNanos) / 1_000_000L; + return this.length > 0 ? Math.min(position, this.length) : position; + } +} diff --git a/src/main/java/de/labystudio/spotifyapi/platform/linux/LinuxSpotifyApi.java b/src/main/java/de/labystudio/spotifyapi/platform/linux/LinuxSpotifyApi.java index 22c178a..75e2f68 100644 --- a/src/main/java/de/labystudio/spotifyapi/platform/linux/LinuxSpotifyApi.java +++ b/src/main/java/de/labystudio/spotifyapi/platform/linux/LinuxSpotifyApi.java @@ -24,11 +24,8 @@ public class LinuxSpotifyApi extends AbstractTickSpotifyAPI { private boolean connected = false; private Track currentTrack; - private int currentPosition = -1; private boolean isPlaying; - private long lastTimePositionUpdated; - private final MPRISCommunicator mediaPlayer = new MPRISCommunicator(); @Override @@ -50,18 +47,13 @@ protected void onTick() throws Exception { int trackLength = metadata.getTrackLength(); BufferedImage coverArt = this.toBufferedImage(metadata.getArtUrl()); - boolean isFirstTrack = !this.hasTrack(); - Track track = new Track(trackId, trackName, trackArtist, trackLength, coverArt); this.currentTrack = track; + this.clock.setLength(trackLength); + this.clock.resync(); // Fire on track changed this.listeners.forEach(listener -> listener.onTrackChanged(track)); - - // Reset position on song change - if (!isFirstTrack) { - this.updatePosition(0); - } } // Handle is playing changes @@ -74,10 +66,10 @@ protected void onTick() throws Exception { } // Handle position changes + long before = this.clock.now(); int position = this.mediaPlayer.readPosition(); - if (!this.hasPosition() || Math.abs(position - this.getPosition()) >= 1000) { - this.updatePosition(position); - } + long after = this.clock.now(); + this.updatePosition(position, before + (after - before) / 2, isPlaying); // half the round trip // Fire keep alive this.listeners.forEach(SpotifyListener::onSync); @@ -89,22 +81,8 @@ public void stop() { this.connected = false; this.currentTrack = null; - this.currentPosition = -1; this.isPlaying = false; - this.lastTimePositionUpdated = 0; - } - - private void updatePosition(int position) { - if (position == this.currentPosition) { - return; - } - - // Update position known state - this.currentPosition = position; - this.lastTimePositionUpdated = System.currentTimeMillis(); - - // Fire on position changed - this.listeners.forEach(listener -> listener.onPositionChanged(position)); + this.clock.reset(); } @Override @@ -132,14 +110,7 @@ public int getPosition() { if (!this.hasPosition()) { throw new IllegalStateException("Position is not known yet"); } - - if (this.isPlaying) { - // Interpolate position - long timePassed = System.currentTimeMillis() - this.lastTimePositionUpdated; - return this.currentPosition + (int) timePassed; - } else { - return this.currentPosition; - } + return (int) this.clock.getPosition(); } @Override @@ -159,7 +130,7 @@ public boolean isConnected() { @Override public boolean hasPosition() { - return this.currentPosition != -1; + return this.clock.hasPosition(); } private BufferedImage toBufferedImage(String artUrl) { diff --git a/src/main/java/de/labystudio/spotifyapi/platform/osx/OSXSpotifyApi.java b/src/main/java/de/labystudio/spotifyapi/platform/osx/OSXSpotifyApi.java index 2306975..2220546 100644 --- a/src/main/java/de/labystudio/spotifyapi/platform/osx/OSXSpotifyApi.java +++ b/src/main/java/de/labystudio/spotifyapi/platform/osx/OSXSpotifyApi.java @@ -21,11 +21,8 @@ public class OSXSpotifyApi extends AbstractTickSpotifyAPI { private boolean connected = false; private Track currentTrack; - private int currentPosition = -1; private boolean isPlaying; - private long lastTimePositionUpdated; - @Override protected void onTick() throws Exception { String trackId = this.appleScript.getTrackId(); @@ -42,8 +39,6 @@ protected void onTick() throws Exception { String trackArtist = this.appleScript.getTrackArtist(); int trackLength = this.appleScript.getTrackLength(); - boolean isFirstTrack = !this.hasTrack(); - Track track = new Track( trackId, trackName, @@ -52,14 +47,10 @@ protected void onTick() throws Exception { null // TODO: Add cover art support if possible ); this.currentTrack = track; + this.clock.resync(); // Fire on track changed this.listeners.forEach(listener -> listener.onTrackChanged(track)); - - // Reset position on song change - if (!isFirstTrack) { - this.updatePosition(0); - } } // Handle is playing changes @@ -72,10 +63,10 @@ protected void onTick() throws Exception { } // Handle position changes + long before = this.clock.now(); int position = this.appleScript.getPlayerPosition(); - if (!this.hasPosition() || Math.abs(position - this.getPosition()) > 1000) { - this.updatePosition(position); - } + long after = this.clock.now(); + this.updatePosition(position, before + (after - before) / 2, isPlaying); // half the round trip // Fire keep alive this.listeners.forEach(SpotifyListener::onSync); @@ -87,22 +78,8 @@ public void stop() { this.connected = false; this.currentTrack = null; - this.currentPosition = -1; this.isPlaying = false; - this.lastTimePositionUpdated = 0; - } - - private void updatePosition(int position) { - if (position == this.currentPosition) { - return; - } - - // Update position known state - this.currentPosition = position; - this.lastTimePositionUpdated = System.currentTimeMillis(); - - // Fire on position changed - this.listeners.forEach(listener -> listener.onPositionChanged(position)); + this.clock.reset(); } @Override @@ -130,14 +107,7 @@ public int getPosition() { if (!this.hasPosition()) { throw new IllegalStateException("Position is not known yet"); } - - if (this.isPlaying) { - // Interpolate position - long timePassed = System.currentTimeMillis() - this.lastTimePositionUpdated; - return this.currentPosition + (int) timePassed; - } else { - return this.currentPosition; - } + return (int) this.clock.getPosition(); } @Override @@ -157,7 +127,7 @@ public boolean isConnected() { @Override public boolean hasPosition() { - return this.currentPosition != -1; + return this.clock.hasPosition(); } } diff --git a/src/main/java/de/labystudio/spotifyapi/platform/windows/WinSpotifyAPI.java b/src/main/java/de/labystudio/spotifyapi/platform/windows/WinSpotifyAPI.java index 796f82d..83c6eae 100644 --- a/src/main/java/de/labystudio/spotifyapi/platform/windows/WinSpotifyAPI.java +++ b/src/main/java/de/labystudio/spotifyapi/platform/windows/WinSpotifyAPI.java @@ -33,12 +33,10 @@ public class WinSpotifyAPI extends AbstractTickSpotifyAPI { private SpotifyProcess process; private Track currentTrack; - private int currentPosition = -1; - private boolean hasTrackPosition = false; private boolean isPlaying; - private long lastTimePositionUpdated; private long prevLastReportedPosition = -1; + private long pausedTimestamp = -1; // LastUpdatedTime seen while paused @Override protected void onInitialized() { @@ -127,6 +125,8 @@ protected void onTick() { coverArt ); this.currentTrack = track; + this.clock.setLength(track.getLength()); + this.clock.resync(); // Fire on track changed this.listeners.forEach(listener -> listener.onTrackChanged(track)); @@ -135,7 +135,8 @@ protected void onTick() { // Handle is playing changes boolean isPlaying = accessor.isPlaying(); - if (isPlaying != this.isPlaying) { + boolean playbackChanged = isPlaying != this.isPlaying; + if (playbackChanged) { this.isPlaying = isPlaying; // Fire on play back changed @@ -143,31 +144,26 @@ protected void onTick() { } if (accessor.hasTrackPosition()) { - this.hasTrackPosition = true; - + long now = this.clock.now(); int lastReportedPosition = accessor.getPosition(); - - if (this.prevLastReportedPosition != lastReportedPosition) { - this.prevLastReportedPosition = lastReportedPosition; - - // Get the daemon position (Last reported position + relative time) - int expectedPosition = this.getPosition(); - - // Compare if the expected position based on time and the last reported position are close enough - boolean seeked = Math.abs(lastReportedPosition - expectedPosition) > TICK_INTERVAL; - - this.currentPosition = lastReportedPosition; - this.lastTimePositionUpdated = System.currentTimeMillis(); - - // Fire on position changed - if (seeked) { - this.listeners.forEach(listener -> listener.onPositionChanged(this.currentPosition)); - } + long reportedAt = accessor.getPositionTimestamp(); + + // GSMTC Position is only pushed on pause/seek/track change, LastUpdatedTime says when + // a resume might not push one (idk) -> the timestamp from the pause would count the paused time + if (reportedAt > 0 && reportedAt != this.pausedTimestamp) { + long age = System.currentTimeMillis() - reportedAt; + long position = isPlaying && age > 0 ? lastReportedPosition + age : lastReportedPosition; + this.updatePosition(position, now, isPlaying); + } else if (playbackChanged + || this.prevLastReportedPosition != lastReportedPosition + || !this.clock.hasPosition()) { + // no usable LastUpdatedTime (old dll or resumed) -> the change is only seen at tick time + this.updatePosition(lastReportedPosition, now, isPlaying); } + this.prevLastReportedPosition = lastReportedPosition; + this.pausedTimestamp = isPlaying ? this.pausedTimestamp : reportedAt; } else { - this.currentPosition = -1; - this.hasTrackPosition = false; - this.lastTimePositionUpdated = System.currentTimeMillis(); + this.clock.reset(); } // Fire keep alive @@ -184,20 +180,7 @@ public int getPosition() { if (!this.hasPosition()) { throw new IllegalStateException("Position is not known yet. Pause the song for a second and try again."); } - - if (this.isPlaying) { - // Interpolate position - long timePassed = System.currentTimeMillis() - this.lastTimePositionUpdated; - long interpolatedPosition = this.currentPosition + timePassed; - - if (this.hasTrack()) { - return (int) Math.min(interpolatedPosition, this.currentTrack.getLength()); - } else { - return (int) interpolatedPosition; - } - } else { - return this.currentPosition; - } + return (int) this.clock.getPosition(); } @Override @@ -205,7 +188,7 @@ public boolean hasPosition() { if (!this.isConnected()) { return false; } - return this.hasTrackPosition; + return this.clock.hasPosition(); } @Override @@ -250,11 +233,10 @@ public void stop() { } this.currentTrack = null; - this.currentPosition = -1; - this.hasTrackPosition = false; this.isPlaying = false; - this.lastTimePositionUpdated = 0; this.prevLastReportedPosition = -1; + this.pausedTimestamp = -1; + this.clock.reset(); } private BufferedImage toBufferedImage(byte[] data) { diff --git a/src/main/java/de/labystudio/spotifyapi/platform/windows/api/jna/WindowsMediaControl.java b/src/main/java/de/labystudio/spotifyapi/platform/windows/api/jna/WindowsMediaControl.java index 95037d4..9984b76 100644 --- a/src/main/java/de/labystudio/spotifyapi/platform/windows/api/jna/WindowsMediaControl.java +++ b/src/main/java/de/labystudio/spotifyapi/platform/windows/api/jna/WindowsMediaControl.java @@ -3,6 +3,7 @@ import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Pointer; +import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.NativeLongByReference; import com.sun.jna.ptr.PointerByReference; @@ -14,6 +15,8 @@ public interface WindowsMediaControl extends Library { long getPlaybackPosition(); + boolean getPlaybackTimeline(LongByReference outPositionMs, LongByReference outUpdatedUnixMs); + long getTrackDuration(); Pointer getTrackTitle(); diff --git a/src/main/java/de/labystudio/spotifyapi/platform/windows/api/playback/PlaybackAccessor.java b/src/main/java/de/labystudio/spotifyapi/platform/windows/api/playback/PlaybackAccessor.java index c647313..fdd939b 100644 --- a/src/main/java/de/labystudio/spotifyapi/platform/windows/api/playback/PlaybackAccessor.java +++ b/src/main/java/de/labystudio/spotifyapi/platform/windows/api/playback/PlaybackAccessor.java @@ -12,6 +12,16 @@ public interface PlaybackAccessor { int getPosition(); + /** + * Returns the time the position was reported at, as unix epoch milliseconds. + * Returns -1 if the source has no timestamp for the position. + * + * @return the time the position was reported at or -1 + */ + default long getPositionTimestamp() { + return -1; + } + boolean isPlaying(); String getTitle(); diff --git a/src/main/java/de/labystudio/spotifyapi/platform/windows/api/playback/source/MediaControlPlaybackAccessor.java b/src/main/java/de/labystudio/spotifyapi/platform/windows/api/playback/source/MediaControlPlaybackAccessor.java index 59593b9..6aadaa4 100644 --- a/src/main/java/de/labystudio/spotifyapi/platform/windows/api/playback/source/MediaControlPlaybackAccessor.java +++ b/src/main/java/de/labystudio/spotifyapi/platform/windows/api/playback/source/MediaControlPlaybackAccessor.java @@ -1,6 +1,7 @@ package de.labystudio.spotifyapi.platform.windows.api.playback.source; import com.sun.jna.Pointer; +import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.NativeLongByReference; import com.sun.jna.ptr.PointerByReference; import de.labystudio.spotifyapi.platform.windows.api.jna.WindowsMediaControl; @@ -17,6 +18,8 @@ public class MediaControlPlaybackAccessor implements PlaybackAccessor { private final WindowsMediaControl mediaControl; private long playbackPosition; + private long positionTimestamp = -1; + private boolean hasTimeline = true; // false once an older dll without getPlaybackTimeline is loaded private long trackDuration; private boolean isPlaying; @@ -34,7 +37,7 @@ public MediaControlPlaybackAccessor(WindowsMediaControl mediaControl) { @Override public void updatePlayback() { - this.playbackPosition = this.mediaControl.getPlaybackPosition(); + this.readPosition(); if (this.playbackPosition == -1) { throw new IllegalStateException("Playback information unavailable"); } @@ -46,6 +49,27 @@ public void updatePlayback() { this.isPlaying = isPlaying == 1; // Convert to boolean (1 = playing, 0 = not playing) } + private void readPosition() { + if (this.hasTimeline) { + LongByReference position = new LongByReference(); + LongByReference updated = new LongByReference(); + try { + if (this.mediaControl.getPlaybackTimeline(position, updated)) { + this.playbackPosition = position.getValue(); + this.positionTimestamp = updated.getValue(); + } else { + this.playbackPosition = -1; + this.positionTimestamp = -1; + } + return; + } catch (UnsatisfiedLinkError e) { + this.hasTimeline = false; + } + } + this.playbackPosition = this.mediaControl.getPlaybackPosition(); + this.positionTimestamp = -1; + } + @Override public void updateTrack() { this.trackDuration = this.mediaControl.getTrackDuration(); @@ -100,6 +124,11 @@ public int getPosition() { return (int) this.playbackPosition; } + @Override + public long getPositionTimestamp() { + return this.positionTimestamp; + } + @Override public boolean isPlaying() { return this.isPlaying; diff --git a/src/main/resources/natives/windows-x64/windowsmediacontrol.dll b/src/main/resources/natives/windows-x64/windowsmediacontrol.dll index 9988079..ccfab3b 100644 Binary files a/src/main/resources/natives/windows-x64/windowsmediacontrol.dll and b/src/main/resources/natives/windows-x64/windowsmediacontrol.dll differ diff --git a/src/test/java/platform/PlaybackClockTest.java b/src/test/java/platform/PlaybackClockTest.java new file mode 100644 index 0000000..c00442d --- /dev/null +++ b/src/test/java/platform/PlaybackClockTest.java @@ -0,0 +1,66 @@ +package platform; + +import de.labystudio.spotifyapi.platform.PlaybackClock; + +public class PlaybackClockTest { + + private static long nanos = 1_000_000_000L; + + public static void main(String[] args) { + PlaybackClock clock = new PlaybackClock(() -> nanos); + + check(!clock.hasPosition(), "unknown at start"); + check(clock.getPosition() == -1, "unknown position is -1"); + + check(clock.update(10_000, nanos, true), "first update reports"); + advance(500); + check(clock.getPosition() == 10_500, "interpolates while playing, got " + clock.getPosition()); + + // sampled 20ms ago, query jitter of +20ms -> nudged by a quarter, no jump + check(!clock.update(10_500, nanos - ms(20), true), "jitter does not report"); + check(clock.getPosition() == 10_505, "jitter nudges by a quarter, got " + clock.getPosition()); + + // 200ms off -> silent re-anchor + check(!clock.update(10_300, nanos, true), "resync does not report"); + check(clock.getPosition() == 10_300, "resync re-anchors, got " + clock.getPosition()); + + check(clock.update(60_000, nanos, true), "seek reports"); + advance(250); + check(clock.getPosition() == 60_250, "seek re-anchors, got " + clock.getPosition()); + + // pause noticed 400ms late, the measured position wins + check(!clock.update(59_850, nanos, false), "pause within the seek threshold does not report"); + advance(3000); + check(clock.getPosition() == 59_850, "paused holds, got " + clock.getPosition()); + + check(!clock.update(59_850, nanos, true), "resume does not report"); + advance(100); + check(clock.getPosition() == 59_950, "resume interpolates, got " + clock.getPosition()); + + clock.resync(); + check(clock.update(59_960, nanos, true), "update after resync reports"); + + clock.setLength(60_000); + advance(5000); + check(clock.getPosition() == 60_000, "clamped to the track length, got " + clock.getPosition()); + + clock.reset(); + check(!clock.hasPosition(), "reset forgets the position"); + + System.out.println("PlaybackClockTest passed"); + } + + private static void advance(long millis) { + nanos += ms(millis); + } + + private static long ms(long millis) { + return millis * 1_000_000L; + } + + private static void check(boolean condition, String message) { + if (!condition) { + throw new IllegalStateException(message); + } + } +}