Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Stop the queue moving on its own

Lelonioa5ef251c1d6f
diff --git a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
index d9b36de..073d346 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -67,6 +67,11 @@ class LibrespotPlayer(
private fun pushQueue(startPlaying: Boolean, positionMs: Int = 0) {
val uris = queue.items.map { it.uri }
if (uris.isEmpty()) return
+ // From here until the engine is on this queue, what it says it is
+ // playing is the past; see [ownQueuePending].
+ ownQueuePending = true
+ handler.removeCallbacks(giveUpOnOwnQueue)
+ handler.postDelayed(giveUpOnOwnQueue, OWN_QUEUE_MS)
val index = queue.currentIndex
val contextUri = queue.contextUri.orEmpty()
// Never as a context, whatever it is.
@@ -757,6 +762,11 @@ class LibrespotPlayer(
.onFailure { android.util.Log.w("SquarePlayer", "could not take over", it) }
}
+ android.util.Log.i(
+ "SquarePlayer",
+ "queue set: ${mediaItems.size} items at $startIndex, " +
+ "first=${mediaItems.getOrNull(startIndex)?.mediaId}",
+ )
queue.replaceFromMediaItems(mediaItems, startIndex)
// A new queue: whatever the engine was playing is no longer at any
// index of this one.
@@ -892,6 +902,25 @@ class LibrespotPlayer(
*/
private var awaitingEngine = false
+ /**
+ * True between handing the engine a queue and it playing from that queue.
+ *
+ * A queue takes a moment to land, and in that moment the engine goes on
+ * reporting the track it is still on — the one being replaced. That track
+ * is not in the new queue, which reads exactly like another device having
+ * chosen something this app knows nothing about, and the answer to that is
+ * to adopt what the engine is playing. So opening the app on a paused song
+ * and tapping a track in a playlist wiped the queue just chosen and put the
+ * old one back: the new song played, and the screen showed the old one.
+ *
+ * Nothing is adopted while this is set. It is only ever the app's own queue
+ * arriving, and there is nothing to learn from it.
+ */
+ private var ownQueuePending = false
+
+ /** A push that never landed must not switch adoption off for good. */
+ private val giveUpOnOwnQueue = Runnable { ownQueuePending = false }
+
fun restore(
tracks: List<PlayQueue.Track>,
shuffleOrder: List<Int>?,
@@ -964,6 +993,10 @@ class LibrespotPlayer(
fun handOverToEngine() {
if (!awaitingEngine) return
awaitingEngine = false
+ android.util.Log.i(
+ "SquarePlayer",
+ "handing over ${queue.items.size} tracks at ${queue.currentIndex}, play=$wantPlay",
+ )
if (queue.items.isEmpty()) {
playbackState = Player.STATE_IDLE
invalidateState()
@@ -995,6 +1028,14 @@ class LibrespotPlayer(
playing: Boolean,
) {
if (tracks.isEmpty()) return
+ // The second line of the same defence as [ownQueuePending]: reading a
+ // context takes seconds, and a listener who has chosen something in
+ // those seconds has said what they want more recently than the engine
+ // has.
+ if (ownQueuePending) {
+ android.util.Log.i("SquarePlayer", "not adopting: a queue of ours is on its way")
+ return
+ }
android.util.Log.i("SquarePlayer", "adopting ${tracks.size} tracks at $index")
queue.restoreContext(contextUri, contextUri != null, contextLabel)
@@ -1107,6 +1148,20 @@ class LibrespotPlayer(
private fun applyEvent(type: String, uri: String, eventPositionMs: Long) {
if (released) return
+ // One line per track change, and nothing for the events that arrive
+ // several times a second. What a skip that nobody asked for looks like
+ // afterwards is a sequence of these, and without them the only record
+ // of it is the engine's own log — which says what the engine did, not
+ // what this side made of it.
+ if (type != "position" && type != "progress") {
+ android.util.Log.i(
+ "SquarePlayer",
+ "engine $type $uri at ${eventPositionMs}ms " +
+ "(queue ${queue.currentIndex}/${queue.items.size}, engine $engineIndex, " +
+ "sounding=$sounding, skipPending=$skipPending, own=$ownQueuePending)",
+ )
+ }
+
// Nothing is coming out of the speaker any more, so the next load is a
// real move rather than a head start on what is coming.
if (type == "stopped" || type == "end_of_track" || type == "unavailable") {
@@ -1118,15 +1173,24 @@ class LibrespotPlayer(
// device and a local one all arrive here the same way.
if (uri.isNotEmpty()) {
val index = queue.nearestIndexOf(uri, engineIndex.takeIf { it >= 0 } ?: queue.currentIndex)
- if (index < 0 && (type == "playing" || type == "loading") && unknownAsked != uri) {
+ if (
+ index < 0 && !ownQueuePending &&
+ (type == "playing" || type == "loading") && unknownAsked != uri
+ ) {
// Not ours: somebody else chose it. Asked for once per track,
// and only on a track that is actually starting, so a position
// report on a queue mid-rebuild does not set this going.
+ android.util.Log.i(
+ "SquarePlayer",
+ "engine is $type $uri, which is not in this queue of ${queue.items.size}",
+ )
unknownAsked = uri
onUnknownTrack?.invoke(uri)
}
if (index >= 0) {
unknownAsked = null
+ ownQueuePending = false
+ handler.removeCallbacks(giveUpOnOwnQueue)
engineIndex = index
if (index == queue.currentIndex) {
// The engine is where it was asked to be.
@@ -1336,6 +1400,16 @@ class LibrespotPlayer(
*/
const val SKIP_CONFIRM_MS = 8_000L
+ /**
+ * How long a queue is given to reach the engine; see [ownQueuePending].
+ *
+ * Measured at about seven hundred milliseconds from the tap to the
+ * first event about the new track, on a cold session that was still
+ * connecting. This is that with room to spare, and short enough that a
+ * queue which never arrived leaves adoption working again.
+ */
+ const val OWN_QUEUE_MS = 6_000L
+
/** Ducked volume, as a fraction of the current one. */
const val DUCK_FACTOR = 0.3
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
index c6cfffd..845606f 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -461,6 +461,30 @@ class PlaybackService : MediaLibraryService() {
AudioEffects.speed.value,
AudioEffects.pitch.value,
)
+ // A video that ends is a song that ended.
+ //
+ // This player holds one item — the video — and knows
+ // nothing about the queue, so reaching the end of it left
+ // the app sitting in silence on the last frame while a
+ // whole queue waited behind it. What happens instead is
+ // what happens when a song finishes: back to the audio
+ // player, on to the next track.
+ built.addListener(object : androidx.media3.common.Player.Listener {
+ override fun onPlaybackStateChanged(state: Int) {
+ if (state != androidx.media3.common.Player.STATE_ENDED) return
+ if (playerKind != PlayerKind.VIDEO) return
+ scope.launch {
+ runCatching {
+ playVideoRequest(
+ dev.lelonio.square.backend.spotify.SpotifyVideoMode
+ .Request.Skip(forward = true),
+ )
+ }.onFailure {
+ android.util.Log.w(TAG, "after the video: $it")
+ }
+ }
+ }
+ })
}
}
@@ -668,7 +692,19 @@ class PlaybackService : MediaLibraryService() {
val saved = runCatching { playbackStore.load() }.getOrNull() ?: return
val first = saved.tracks.firstOrNull()?.uri ?: return
if (!dev.lelonio.square.data.LocalLibrary.isLocal(first)) return
- scope.launch { swapPlayer(PlayerKind.LOCAL, restore = true) }
+ scope.launch {
+ // Not if something has started in the meantime.
+ //
+ // This is queued at startup and runs whenever the engine has
+ // finished coming up, which can be after the listener has already
+ // opened a playlist and tapped a song. Swapping then put the local
+ // player — holding the file that was paused when the app was last
+ // closed — in front of a session that was playing something else:
+ // the new song came out of the speaker while the screen showed the
+ // old one, paused.
+ if (player.mediaItemCount > 0) return@launch
+ swapPlayer(PlayerKind.LOCAL, restore = true)
+ }
}
/**
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 41fa7c3..7d8acff 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -1532,6 +1532,11 @@ fn transport(
via_spirc: impl FnOnce(&Bundle) -> Result<(), librespot_core::Error>,
via_player: impl FnOnce(&Bundle),
) -> EngineResult<()> {
+ // LOCAL PATCH: every command this side sends, so a skip nobody asked for
+ // can be told from one this app asked for. See spirc.rs, which says the
+ // same about the commands that arrive from the account.
+ log::info!("this device asks to {what}");
+
// Asked before trying, not after failing.
//
// A command sent to a Spirc task that has already ended does not come back
@@ -1705,6 +1710,7 @@ pub fn previous() -> EngineResult<()> {
transport("previous", |e| e.spirc.prev(), |e| e.player.stop())
}
+
/// Shuts the output until the track being played is a different one.
///
/// A skip is a message to the Connect device and the music changes about a
diff --git a/native/src/sink.rs b/native/src/sink.rs
index 4019cf6..7475e6c 100644
--- a/native/src/sink.rs
+++ b/native/src/sink.rs
@@ -132,6 +132,29 @@ impl Sink for AndroidSink {
fn write(&mut self, packet: AudioPacket, converter: &mut Converter) -> SinkResult<()> {
if self.stale() {
+ // LOCAL PATCH: dropped, but at the speed it would have played.
+ //
+ // Throwing the packet away and returning is what a muted output
+ // should do — and returning *immediately* is what made a song be
+ // skipped a second after it started. Writing to the AudioTrack is
+ // what paces the whole player: it blocks until the hardware has
+ // room. With nothing to block on, the decoder ran flat out and the
+ // track's position went up twenty times faster than the sound
+ // would have: eight seconds in, the engine believed it was three
+ // minutes and thirteen seconds into a three-minute-twenty song, so
+ // it announced the end and the queue moved on. The listener heard
+ // the song start and vanish, having touched nothing.
+ //
+ // Sleeping for exactly as long as this packet would have taken
+ // keeps time honest while the output is shut.
+ let frames = match &packet {
+ AudioPacket::Samples(samples) => samples.len() / NUM_CHANNELS as usize,
+ AudioPacket::Raw(data) => data.len() / (2 * NUM_CHANNELS as usize),
+ };
+ if frames > 0 {
+ let nanos = (frames as u64 * 1_000_000_000) / SAMPLE_RATE as u64;
+ std::thread::sleep(std::time::Duration::from_nanos(nanos));
+ }
return Ok(());
}
diff --git a/native/vendor/librespot-connect/src/spirc.rs b/native/vendor/librespot-connect/src/spirc.rs
index 148380d..a1ea9d3 100644
--- a/native/vendor/librespot-connect/src/spirc.rs
+++ b/native/vendor/librespot-connect/src/spirc.rs
@@ -41,7 +41,7 @@ use std::{
future::Future,
sync::Arc,
sync::atomic::{AtomicUsize, Ordering},
- time::{Duration, SystemTime, UNIX_EPOCH},
+ time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use thiserror::Error;
use tokio::{sync::mpsc, time::sleep};
@@ -85,6 +85,9 @@ struct SpircTask {
play_request_id: Option<u64>,
play_status: SpircPlayStatus,
+ /// LOCAL PATCH: when the queue last moved on, whatever moved it. See
+ /// [`SpircTask::advanced_recently`].
+ last_advance: Option<Instant>,
connection_id_update: BoxedStreamResult<String>,
connect_state_update: BoxedStreamResult<ClusterUpdate>,
@@ -305,6 +308,7 @@ impl Spirc {
play_request_id: None,
play_status: SpircPlayStatus::Stopped,
+ last_advance: None,
connection_id_update,
connect_state_update,
@@ -847,7 +851,22 @@ impl SpircTask {
SpircCommand::PlayPause => self.handle_play_pause(),
SpircCommand::Pause => self.handle_pause(),
SpircCommand::Prev => self.handle_prev()?,
- SpircCommand::Next => self.handle_next(None)?,
+ SpircCommand::Next => {
+ // LOCAL PATCH: not if the queue has just moved on its own.
+ //
+ // With a crossfade, the end of a song is announced seconds
+ // before it arrives, and a listener who presses skip in those
+ // seconds is asking for the thing that is already happening.
+ // Obeying both moves the queue twice and the song in between is
+ // never heard. Only an advance the queue made by itself is
+ // swallowed this way; two presses in a row are two skips, which
+ // is what pressing twice means.
+ if self.advanced_recently() {
+ debug!("the queue has just advanced by itself, taking this skip as that one");
+ return Ok(());
+ }
+ self.handle_next(None)?
+ }
SpircCommand::VolumeUp => self.handle_volume_up(),
SpircCommand::VolumeDown => self.handle_volume_down(),
SpircCommand::Shuffle(shuffle) => self.handle_shuffle(shuffle)?,
@@ -914,7 +933,34 @@ impl SpircTask {
}
match event {
- PlayerEvent::EndOfTrack { .. } => {
+ PlayerEvent::EndOfTrack { track_id, .. } => {
+ // LOCAL PATCH: only the track that is still current can end.
+ //
+ // The end of a song and a listener skipping it are the same
+ // thing to whoever owns the queue — both mean "play the next
+ // one" — and with a crossfade they can happen at once: the fade
+ // announces the end of the song, the listener presses skip a
+ // moment earlier or later, and the queue moves twice for one
+ // intention. What is between them is a song nobody heard.
+ //
+ // The play request id above cannot tell them apart, because the
+ // announcement and the skip belong to the same one. The current
+ // track can: once the queue has moved, an announcement about
+ // the song it moved off is news about the past.
+ let ended = track_id.to_string();
+ let current = self.connect_state.current_track(|t| t.uri.clone());
+ if !ended.is_empty() && !current.is_empty() && ended != current {
+ debug!("<{ended}> finished, but <{current}> is the current track now");
+ return Ok(());
+ }
+
+ // And the same the other way round: the listener skipped and
+ // the fade announced this song's end a moment later.
+ if self.advanced_recently() {
+ debug!("the queue has just advanced, so this ending has been dealt with");
+ return Ok(());
+ }
+
let next_track = self
.connect_state
.repeat_track()
@@ -1175,6 +1221,13 @@ impl SpircTask {
async fn handle_request(&mut self, request: Request) -> Result<(), Error> {
use Command::*;
+ // LOCAL PATCH: who asked, and for what.
+ //
+ // A queue that moves on its own has two possible authors — this device
+ // and the account — and from the events alone they look the same. This
+ // says when the instruction came over the wire.
+ info!("connect asked for {:?}", request.command);
+
match request.command {
// errors and unknown commands
Transfer(transfer) if transfer.data.is_none() => {
@@ -1822,8 +1875,29 @@ impl SpircTask {
self.context_resolver.add(resolve);
}
+ /// LOCAL PATCH: whether the queue moved on in the last moment.
+ ///
+ /// Long enough to cover a fade announcing an ending and a listener pressing
+ /// skip about the same thing, short enough that two deliberate presses are
+ /// still two skips: measured at 150 ms between the two in the case this was
+ /// written for.
+ fn advanced_recently(&self) -> bool {
+ const TOGETHER: Duration = Duration::from_millis(700);
+ self.last_advance
+ .map(|at| at.elapsed() < TOGETHER)
+ .unwrap_or(false)
+ }
+
fn handle_next(&mut self, track_uri: Option<String>) -> Result<(), Error> {
+ self.last_advance = Some(Instant::now());
let continue_playing = self.connect_state.is_playing();
+ // LOCAL PATCH: every advance, so a burst of them is visible as a burst,
+ // and what the queue believed about itself when it made this one — a
+ // track loaded paused after a skip is this having said "no".
+ info!(
+ "advancing to the next track (playing={continue_playing}, status={:?})",
+ self.play_status
+ );
let current_uri = self.connect_state.current_track(|t| &t.uri);
let mut has_next_track =
diff --git a/native/vendor/librespot-core/src/audio_key.rs b/native/vendor/librespot-core/src/audio_key.rs
index 457a13a..aefcf97 100644
--- a/native/vendor/librespot-core/src/audio_key.rs
+++ b/native/vendor/librespot-core/src/audio_key.rs
@@ -1,4 +1,8 @@
-use std::{collections::HashMap, io::Write, time::Duration};
+use std::{
+ collections::HashMap,
+ io::Write,
+ time::{Duration, Instant},
+};
use byteorder::{BigEndian, ByteOrder, WriteBytesExt};
use bytes::Bytes;
@@ -36,13 +40,33 @@ impl From<AudioKeyError> for Error {
}
}
+// LOCAL PATCH: `cool_off_until` is when the next key may be asked for, and
+// `cool_off` how long the wait becomes if that one is refused too. The macro
+// takes no doc comments on its fields, hence this note; see
+// [AudioKeyManager::request] for what they are for.
component! {
AudioKeyManager : AudioKeyManagerInner {
sequence: SeqGenerator<u32> = SeqGenerator::new(0),
pending: HashMap<u32, oneshot::Sender<Result<AudioKey, Error>>> = HashMap::new(),
+ cool_off_until: Option<Instant> = None,
+ cool_off: Duration = FIRST_COOL_OFF,
}
}
+/// LOCAL PATCH: how long to leave the key service alone after it refuses one.
+///
+/// Spotify meters these: a burst of requests — a run of skips, a preload
+/// landing on top of a load, a failed load being tried again — is answered by
+/// refusing everything for around a minute, and every retry inside that minute
+/// makes it worse rather than better. Measured on this app: thirty-nine
+/// requests in seventy seconds, four different tracks, none of them playable,
+/// and everything fine on either side of the window.
+///
+/// So a refusal puts the whole session on hold, doubling until the cap, and one
+/// key that comes back clears it.
+const FIRST_COOL_OFF: Duration = Duration::from_secs(3);
+const MAX_COOL_OFF: Duration = Duration::from_secs(30);
+
impl AudioKeyManager {
pub(crate) fn dispatch(&self, cmd: PacketType, mut data: Bytes) -> Result<(), Error> {
let seq = BigEndian::read_u32(data.split_to(4).as_ref());
@@ -93,14 +117,29 @@ impl AudioKeyManager {
/// would just add latency to an error that is not going to change.
pub async fn request(&self, track: SpotifyId, file: FileId) -> Result<AudioKey, Error> {
const ATTEMPTS: usize = 3;
- const FIRST_BACKOFF: Duration = Duration::from_millis(250);
- let mut backoff = FIRST_BACKOFF;
let mut last = None;
for attempt in 0..ATTEMPTS {
+ // Whatever is left of the hold from the last refusal, whoever it
+ // was that ran into it.
+ if let Some(wait) = self.lock(|inner| {
+ inner
+ .cool_off_until
+ .and_then(|until| until.checked_duration_since(Instant::now()))
+ }) {
+ debug!("waiting {wait:?} before asking for another audio key");
+ tokio::time::sleep(wait).await;
+ }
+
match self.request_once(track, file).await {
- Ok(key) => return Ok(key),
+ Ok(key) => {
+ self.lock(|inner| {
+ inner.cool_off_until = None;
+ inner.cool_off = FIRST_COOL_OFF;
+ });
+ return Ok(key);
+ }
Err(e) => {
// Through the boxed cause, not the wrapper. This `Error` is
// librespot's own: a `kind` plus the error it was built
@@ -109,13 +148,22 @@ impl AudioKeyManager {
e.error.downcast_ref::<AudioKeyError>(),
Some(AudioKeyError::AesKey) | Some(AudioKeyError::Timeout)
);
+ if transient {
+ // The hold belongs to the session, not to this request:
+ // the next track is about to ask for one too, and it
+ // will be refused for the same reason.
+ self.lock(|inner| {
+ let wait = inner.cool_off;
+ inner.cool_off_until = Some(Instant::now() + wait);
+ inner.cool_off = (wait * 2).min(MAX_COOL_OFF);
+ warn!("audio key refused, holding off for {wait:?}");
+ });
+ }
if !transient || attempt + 1 == ATTEMPTS {
return Err(e);
}
debug!("audio key attempt {} failed, retrying", attempt + 1);
last = Some(e);
- tokio::time::sleep(backoff).await;
- backoff *= 2;
}
}
}
diff --git a/native/vendor/librespot-playback/src/player.rs b/native/vendor/librespot-playback/src/player.rs
index fd3f0b9..678ff74 100644
--- a/native/vendor/librespot-playback/src/player.rs
+++ b/native/vendor/librespot-playback/src/player.rs
@@ -53,6 +53,21 @@ const LOAD_RETRY_BACKOFF: Duration = Duration::from_millis(900);
const PRELOAD_NEXT_TRACK_BEFORE_END_DURATION_MS: u32 = 30000;
+/// LOCAL PATCH: how far from the end of a track its stream can run out and
+/// still count as the track having ended.
+///
+/// Three seconds. Decoders and metadata disagree about the last fraction of a
+/// second, and a track cut three seconds short is something a listener hears.
+const SHORT_END_TOLERANCE_MS: i64 = 3_000;
+
+
+
+/// LOCAL PATCH: how many times a track whose stream keeps running out early is
+/// put back on before it is allowed to end. See [SHORT_END_TOLERANCE_MS].
+const MAX_SHORT_END_RELOADS: u8 = 2;
+
+
+
/// LOCAL PATCH: the largest value that survives conversion to signed 16 bit.
///
/// Full scale is asymmetric: -32768 exists, +32768 does not, so a mix that
@@ -115,6 +130,16 @@ struct PlayerInternal {
fade_out: Option<FadeOut>,
/// LOCAL PATCH: the play request whose end has already been announced early.
early_end: Option<u64>,
+ /// LOCAL PATCH: the play request that has been heard playing before its own
+ /// fade window, and so may have its end announced early. See the use of it.
+ fade_armed: Option<u64>,
+ /// LOCAL PATCH: how many times a play request has had its stream run out
+ /// before the end of the track, so a stream that never completes gives up
+ /// instead of putting the same song back on for ever.
+ short_end: Option<(u64, u8)>,
+ /// LOCAL PATCH: the play request whose end has already been announced, by
+ /// whichever of the paths announces one. See `announce_end`.
+ ended: Option<u64>,
/// LOCAL PATCH: how many times the track being loaded has been retried, and
/// from what position, so a retry resumes the same load. See the failure
/// branch of the loading state in `poll`.
@@ -551,6 +576,9 @@ impl Player {
fade_out: None,
early_end: None,
+ fade_armed: None,
+ short_end: None,
+ ended: None,
load_attempt: 0,
load_position_ms: 0,
normalisation_peaks: [0.0; 2],
@@ -620,6 +648,7 @@ impl Player {
self.command(PlayerCommand::Stop)
}
+
pub fn seek(&self, position_ms: u32) {
self.command(PlayerCommand::Seek(position_ms));
}
@@ -802,6 +831,45 @@ impl PlayerState {
/// LOCAL PATCH: where the track had got to, for reloading it after a
/// failure. Zero when nothing is loaded, which is the right answer for a
/// reload that will start from the beginning anyway.
+ /// LOCAL PATCH: what is playing, where it is, and how long it is.
+ /// LOCAL PATCH: which play request this state belongs to, if any.
+ fn play_request_id(&self) -> Option<u64> {
+ use self::PlayerState::*;
+ match *self {
+ Loading {
+ play_request_id, ..
+ }
+ | Paused {
+ play_request_id, ..
+ }
+ | Playing {
+ play_request_id, ..
+ }
+ | EndOfTrack {
+ play_request_id, ..
+ } => Some(play_request_id),
+ Stopped | Invalid => None,
+ }
+ }
+
+ fn playing_progress(&self) -> Option<(SpotifyUri, u64, u32, u32)> {
+ match *self {
+ PlayerState::Playing {
+ ref track_id,
+ play_request_id,
+ stream_position_ms,
+ duration_ms,
+ ..
+ } => Some((
+ track_id.clone(),
+ play_request_id,
+ stream_position_ms,
+ duration_ms,
+ )),
+ _ => None,
+ }
+ }
+
fn stream_position_ms(&self) -> u32 {
use self::PlayerState::*;
match *self {
@@ -1790,17 +1858,35 @@ impl Future for PlayerInternal {
// being dropped. Nothing here decides what plays next, which is
// what keeps the Connect device the only thing that does.
let crossfade_ms = self.config.crossfade_duration_ms as i64;
- if crossfade_ms > 0
- && self.early_end != Some(play_request_id)
- && self.state.is_playing()
- && duration_ms > 0
- && (duration_ms as i64 - stream_position_ms as i64) <= crossfade_ms
- {
- self.early_end = Some(play_request_id);
- self.send_event(PlayerEvent::EndOfTrack {
- track_id,
- play_request_id,
- });
+ let position = stream_position_ms as i64;
+ let duration = duration_ms as i64;
+ if crossfade_ms > 0 && duration > crossfade_ms {
+ if position < duration - crossfade_ms {
+ // LOCAL PATCH: the track has been heard playing outside
+ // its own ending, so its ending means something.
+ //
+ // Both numbers below come from the decoder, and a track
+ // that arrives already inside the fade window is a
+ // track whose numbers cannot be trusted: a duration
+ // read before the stream was open, or a position left
+ // over from the song that just finished. Announcing an
+ // end from those is heard as a song playing for a
+ // second and then being passed over, because whoever
+ // owns the queue is being told — truthfully, as far as
+ // it knows — that the song is over. Armed here, this
+ // can only happen to a track that was playing normally
+ // a moment ago.
+ self.fade_armed = Some(play_request_id);
+ } else if self.early_end != Some(play_request_id)
+ && self.fade_armed == Some(play_request_id)
+ && self.state.is_playing()
+ {
+ info!(
+ "crossfade: {position} ms of {duration} ms played, announcing the end of <{track_id:?}>"
+ );
+ self.early_end = Some(play_request_id);
+ self.announce_end(track_id, play_request_id);
+ }
}
}
@@ -2193,6 +2279,37 @@ impl PlayerInternal {
}
None => {
+ // LOCAL PATCH: a stream that runs out early is not a track that
+ // ended.
+ //
+ // The decoder having nothing left is how a song finishes, and it
+ // is also what a truncated file or a connection dropped mid-track
+ // looks like from here. Upstream cannot tell the two apart, so it
+ // reports the end of the track either way and whoever owns the
+ // queue plays the next song — which is heard as a song starting
+ // and being passed over a moment later, on a song that plays
+ // perfectly well when it is chosen again.
+ //
+ // Far enough from where the track really ends, this is a failure,
+ // and the answer to a failure is the one below: put it back on
+ // from where it stopped. Bounded, because a stream that truly
+ // cannot be read to the end would otherwise never let go.
+ if let Some((track_id, play_request_id, position, duration)) =
+ self.state.playing_progress()
+ {
+ let short = duration > 0
+ && (position as i64) + SHORT_END_TOLERANCE_MS < duration as i64;
+ let attempts = match self.short_end {
+ Some((request, count)) if request == play_request_id => count,
+ _ => 0,
+ };
+ if short && attempts < MAX_SHORT_END_RELOADS {
+ warn!("the stream for <{track_id:?}> ended at {position} ms of {duration} ms, putting it back on");
+ self.short_end = Some((play_request_id, attempts + 1));
+ self.reload_track(track_id, play_request_id, position);
+ return;
+ }
+ }
self.state.playing_to_end_of_track();
if let PlayerState::EndOfTrack {
ref track_id,
@@ -2200,10 +2317,8 @@ impl PlayerInternal {
..
} = self.state
{
- self.send_event(PlayerEvent::EndOfTrack {
- track_id: track_id.clone(),
- play_request_id,
- })
+ let track_id = track_id.clone();
+ self.announce_end(track_id, play_request_id)
} else {
error!("PlayerInternal handle_packet: Invalid PlayerState");
exit(1);
@@ -2305,6 +2420,27 @@ impl PlayerInternal {
let play_request_id =
play_request_id_option.unwrap_or(self.play_request_id_generator.get());
+ // LOCAL PATCH: whatever was playing is being replaced, so nothing more
+ // is going to be said about it.
+ //
+ // A fade announces the end of a song a few seconds before it arrives,
+ // and a listener who skips inside those seconds leaves that
+ // announcement in flight: it lands after the queue has already moved,
+ // and is heard as the song after this one being passed over, or as two
+ // songs playing at once while the one that was replaced insists it is
+ // still finishing. The song being left has no end worth reporting — it
+ // is not ending, it is being replaced.
+ //
+ // Only the announcing is stopped. `early_end` stays exactly as it is,
+ // because it is also what tells `begin_fade_out` that this song is
+ // owed a fade: clearing it here left every crossfade to end as a cut,
+ // which is worse than the thing this was fixing.
+ if let Some(previous) = self.state.play_request_id() {
+ if previous != play_request_id {
+ self.ended = Some(previous);
+ }
+ }
+
self.send_event(PlayerEvent::PlayRequestIdChanged { play_request_id });
if !self.config.gapless {
@@ -2736,10 +2872,7 @@ impl PlayerInternal {
warn!(
"Currently loaded track is explicit, which client setting forbids -- skipping to next track."
);
- self.send_event(PlayerEvent::EndOfTrack {
- track_id,
- play_request_id,
- })
+ self.announce_end(track_id, play_request_id)
}
}
}
@@ -2749,6 +2882,26 @@ impl PlayerInternal {
Ok(())
}
+ /// LOCAL PATCH: says a track has finished, once and only once.
+ ///
+ /// A track can reach its end by more than one road — the crossfade
+ /// announcing it early, the stream running out, a filter refusing to play
+ /// it — and on a track whose file is shorter than its metadata says, two of
+ /// them arrive within a fraction of a second. Whoever owns the queue obeys
+ /// each one, so two announcements are two songs skipped: one heard for an
+ /// instant and one not heard at all.
+ fn announce_end(&mut self, track_id: SpotifyUri, play_request_id: u64) {
+ if self.ended == Some(play_request_id) {
+ debug!("<{track_id:?}> has already been announced as finished");
+ return;
+ }
+ self.ended = Some(play_request_id);
+ self.send_event(PlayerEvent::EndOfTrack {
+ track_id,
+ play_request_id,
+ });
+ }
+
fn send_event(&mut self, event: PlayerEvent) {
self.event_senders
.retain(|sender| sender.send(event.clone()).is_ok());