Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(|| {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -36,6 +39,10 @@ public Path getNativesDirectory() {
return this.nativesDirectory;
}

public long getTickInterval() {
return this.tickInterval;
}

/**
* Builder to create a new spotify configuration
*/
Expand All @@ -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
Expand Down Expand Up @@ -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
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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);
Expand All @@ -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
Expand All @@ -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
);

Expand Down Expand Up @@ -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);
Expand Down
92 changes: 92 additions & 0 deletions src/main/java/de/labystudio/spotifyapi/platform/PlaybackClock.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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);
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -159,7 +130,7 @@ public boolean isConnected() {

@Override
public boolean hasPosition() {
return this.currentPosition != -1;
return this.clock.hasPosition();
}

private BufferedImage toBufferedImage(String artUrl) {
Expand Down
Loading