Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Vendored dependencies
librespot-core
Copy of librespot-core 0.8.0
(MIT, licence retained), wired in through [patch.crates-io] in
native/Cargo.toml so that librespot-playback and librespot-metadata
resolve to this copy as well.
The patches
1. src/mercury — POST with header fields
Spotify builds the account's listening history from events posted to
hm://event-service/v1/events, and that request is a POST carrying
Accept-Language and X-ClientTimeStamp as Mercury header fields. Upstream's
Mercury client has neither: no POST method, and MercuryRequest has nowhere to
put a header field. Both were added — a MercuryMethod::Post, a user_fields
list on the request, and a post() on the manager.
The alternative was building the packet by hand and calling send_packet
directly, which works but throws the reply away: the sequence number would not
be in Mercury's pending table, so there is no way to see whether Spotify
accepted the event. On a format this app reverse-engineered, that answer is
worth the patch.
2. src/config.rs — the advertised OS
One line:
-pub const OS: &str = std::env::consts::OS;
+pub const OS: &str = "linux";
Why
OS decides three things at once: the default client id, the platform field
librespot sends to Spotify, and the HTTP user agent. On Android the real value
makes librespot present itself as the Spotify Android app, while this client
authenticates with the desktop "keymaster" client id — the one whose OAuth flow
accepts a loopback redirect, and therefore the only one usable here.
Spotify checks that the client id and the advertised platform agree. They do not,
so the access point handshake succeeds and then every client-token and login5
request is refused with a generic BAD_REQUEST:
rootlist failed: Invalid state { Login request was denied: BAD_REQUEST }
The comment above OS upstream warns about exactly this: mocking a platform
requires the rest of the identity to match it. Pinning "linux" presents a
consistent desktop identity, which is what the desktop client id expects.
The same fix exists in the librespot fork behind Outify — commit "Fixed login5 errors by mocking linux" — which is how it was found.
3. src/spclient.rs and src/config.rs — the language to answer in
Spotify localises the artwork of its generated playlists: the cover of "Your
All-Time Top Songs" is served from a URL ending in the language, and the
Italian one is a different picture from the English one. librespot sends no
Accept-Language at all, so everything came back English regardless of what
the app was set to.
A language field was added to SessionConfig (default "en", so behaviour
for anyone not setting it is unchanged), and the spclient request builder now
sends it as Accept-Language. The app fills it from the device locale.
Not everything follows it: the charts, daylist, blend and seed-mix covers are picked by the server from the account's own language and stay English.
4. src/session.rs — a non-premium account is not a reason to exit
Upstream refuses to run on a free account, and does it by calling
std::process::exit(1) from inside check_catalogue, with a TODO of its own
saying it should log out instead:
- // TODO: logout instead of exiting
- exit(1);
That ends a command-line daemon tidily. Inside an Android app it takes the whole process down: the service dies mid-login, Android restarts it, the same account authenticates again, and the loop repeats with a growing backoff and no message anywhere. From the outside the app simply vanishes.
The check now only logs, and engine::start reads the type attribute itself
and returns premium account required, which the service turns into a message
and a return to the login screen. The refusal is unchanged; what changed is that
it is an error the caller can handle rather than a process exit.
5. src/audio_key.rs: keys are remembered, and a refusal waits
Every file needs a decryption key, and the account is allowed only so many requests in a stretch. Past that the server stops answering, and upstream has nothing between the request and the caller: a burst of changes turns into a queue of loads that each wait for a key that never comes.
Two changes. A refused key is tried again after a pause that doubles, three seconds, then six, then twelve, rather than being handed straight back as a failure. And the keys already answered for are kept in the component, the last sixty-four of them, so a track heard earlier in the session costs no request at all: going back and forth between two songs asks once for each.
The memory is per session and never written to disk. It holds keys, so it goes when the session does.
A refusal is also reported, through on_playback_refusal, so the app can say
why a song is not starting instead of leaving it at the start with no time on
it. Only refusals that land within ninety seconds of the player asking for a
key are reported, once for a run of them, and the next key that comes back is
reported as the end of it. Downloads refused while nothing is playing say
nothing. When no key at all has come back since the app started and the
refusals have gone on for seventy seconds, the refusal is reported as the
account's instead: Spotify refuses every key to some accounts (librespot#1649),
and for those waiting a few minutes is the wrong advice. The window is longer
than the burst Spotify refuses for, about a minute, and short enough that the
refusals one press of play produces reach it; at two minutes they did not, and
an account refused every key was told to wait.
And a reply of the wrong size is refused rather than trusted. Upstream copies
the key with copy_from_slice and reads the error code by index, both of which
panic on a short packet, on the task that reads every packet of the session.
6. src/cache.rs: credentials are replaced, never emptied
Upstream writes the credentials file with File::create, which empties it
before the new contents are written. A process killed between the two, which
installing an update does, leaves an empty file, and with it a device that
cannot log in and says only that it is offline. The new contents are written to
a file beside it and renamed over it, so the old one stays whole until the new
one is.
Maintenance
Re-apply this patch when bumping librespot-core. If the whole file is replaced,
the marker to look for is LOCAL PATCH in src/config.rs.
librespot-playback
Copy of librespot-playback 0.8.0
(MIT, licence retained), wired in the same way.
The patch: crossfade
Upstream plays one track at a time, start to finish, and the next one begins where the last one stopped. Overlapping them cannot be done from outside the crate: the player owns the decoder and the sink, and nothing it exposes lets a caller reach the samples of two tracks at once.
PlayerConfig gains crossfade_duration_ms, zero by default, which leaves
upstream behaviour exactly as it was.
When it is set, the player announces EndOfTrack a fade's length before the
track really ends. Whoever owns the queue answers with a load, as it always
does, and that load is what starts the fade: instead of dropping the decoder of
the track being replaced, start_playback hands it to fade_out, where it is
read for the length of the fade and then dropped. Nothing in the player decides
what plays next, so the Connect device stays the only thing that does.
The mix is equal power, cos out and sin in, one gain per frame. Two straight
ramps summed dip in the middle, where both tracks are at half; squared cosine
and sine sum to one, so the loudness holds across the overlap. Both sides carry
their own normalisation factor, since normalisation exists to make two masters
sound alike and a fade is the one moment both are heard. The result is clamped
to 32767/32768, because full scale is asymmetric and a mix that reaches 1.0
wraps to the bottom and is heard as a click.
A track shorter than the fade simply drains early: the incoming track goes on rising, over silence rather than over music.
The patch: a slow connection is not a missing track
Upstream gives a load one attempt. If it fails, the player sends Unavailable,
and Connect answers that by skipping to the next track and dropping the failed
one out of the queue. That is right for a track the account cannot play, and
wrong for every other reason a load fails: on a weak signal each track failed in
turn, so the queue ran itself out in seconds without a note being heard, and the
songs it gave up on were gone from the queue for the rest of the session.
The loading state now retries the same track, three times, waiting 0.9s, 1.8s
and 3.6s, and sends a fresh Loading each time so the app can go on saying it
is working. Unavailable is only sent once all of them have failed, which
leaves its meaning intact for the case it was written for.
The counter and the position it retries from live on PlayerInternal and are
reset by handle_command_load, so every new load starts with a full set of
attempts.
The patch: a failed head start is not a missing track
The player fetches the next track while the current one plays, and upstream answers a failed fetch by telling Spirc the track is unavailable, which takes it out of the queue. On a weak link that head start is the first thing to fail, and it fails while the connection is busy carrying the song being listened to: songs were vanishing from the queue before anything had tried to play them.
A failed preload now just forgets the head start. The track is loaded normally when its turn comes, with the retries that path has.
The patch: the quality can change without a new player
The bitrate is read in one place, while a track is being loaded, to put the formats it exists in into order of preference. Upstream keeps it in the player's immutable config all the same, so following a connection as it changes meant building a new session, which costs a second of silence and a Connect device that has to be handed the queue again.
PlayerCommand::SetBitrate and Player::set_bitrate change it in place, and
drop whatever was preloaded, since that was fetched at the old quality. What is
playing keeps the file it started with; the next track gets the new one.
The patch: a refused key ends the load
Spotify hands out a decryption key per file, and it refuses them when it is throttling a session — which says nothing about the track being asked for. Upstream then loads the file anyway, without a key, on the grounds that a file which turns out to be unencrypted still plays and an encrypted one will simply fail to parse.
What that failure looks like from the outside is the whole queue flicking past in silence: the decoder dies on the first frame, the track "ends" in half a second, the engine moves to the next one, and that one is refused too. Nothing in the log says the word key.
A refusal or a timeout now ends the load, which puts it on the retry path with
the rest, and says so if it still cannot be played. So does a key lost because
the session went away mid-request, which answers "channel closed". Any other key
failure keeps upstream's behaviour, since a genuinely unencrypted file has to go
on playing.
See also the retry in librespot-core's audio_key.rs, which is what tries a
refused key again before it gets this far.
The patch: a change of song is dissolved as well
Upstream's crossfade, above, is the end of a track running under the start of the next: one clock, both halves on it, and it can only happen where the player knows the next track already. A listener changing song themselves has neither. The track being left is dropped the moment the load is taken, and if the new one has to be fetched, which is every song picked from a list, there is nothing left to fade by the time it arrives.
PlayerConfig gained skip_fade_ms and the player a SetSkipFade command, so
the app can set it from its own setting. When a load arrives with a track
playing, that track moves into the fade before the state becomes Loading,
which is what keeps its decoder alive, and its tail is written on its own by
pump_fade_out for as long as the load takes. FadeOut gained rising, a
second clock: the arriving track comes up from nothing when it starts making a
sound, whether the wait was half a second or ten, where the crossfade's two
halves go on sharing one clock as before.
Zero, the default, leaves every one of these paths as upstream has it.
The patch: a mixed playlist's transitions
A playlist mixed in Spotify's own app keeps, on the row a transition starts
from, where the song hands over, where the next comes in and how long the two
overlap (read by the app; see catalog::playlist_mix). Player::set_mix_plan
gives the player the one transition that is next. While the song it names is
playing, its end is announced at the transition's point instead of a
crossfade's length before the end, whatever the crossfade setting, and the
fade lasts as long as the transition says. The song it goes into, loaded from
the start, starts at the transition's point instead.
When the transition is beatmatched, the incoming song plays at the speed the
recipe gives it for the overlap and eases back to its own over eight seconds
(TempoRamp). It is resampled, turntable-style, so its key moves with its
tempo, by about a semitone at a typical 6%.
The markers are LOCAL PATCH around MixPlan, mix_plan, mix_fade_ms and
tempo in src/player.rs.
The patch: the DJ talks between the tracks
Spotify's DJ gives some tracks a line to say before them and some a line after,
which the app has synthesised by the time they play (see native/src/dj.rs).
The player is the only place that knows where one track's sound ends and the
next one's begins, so that is where the lines go.
set_narration_provider installs where they come from, and set_narrating
turns them on for a DJ queue. When a track starts playing near its beginning
the player asks for its opening line; when its decoder runs out, before the end
is announced, for its closing one. A line is written to the sink a twentieth of
a second at a time, so commands are still heard between pieces: a seek drops an
opening line, a load drops whatever was being said, and a closing line ends the
track once it has been said. Lines and music are never mixed, as in the
official client.
While a line is written speaking() is true, and the app's sink hands those
packets to the output separately, past the effects that are the listener's
choices about the music. And set_narration_follows says which tracks end in a
line: those are not dissolved into the next, since the crossfade would run the
music under the DJ talking. Every other track of a DJ queue crossfades as usual.
Nothing changes while set_narrating is off, which is the default.
Maintenance
The markers are LOCAL PATCH in src/player.rs and src/config.rs.
librespot-connect
Copy of librespot-connect 0.8.0
(MIT, licence retained), wired in the same way.
The patch: is this device the one playing?
ConnectState knows, and nothing outside the event loop could ask. Spirc now
carries an AtomicBool that the loop republishes every turn, and a
Spirc::is_active() that reads it.
The alternative was reading the cluster, which is a different question wearing the same clothes. When another client hands playback to this device, Spotify sends the transfer and this device starts playing immediately, but the account goes on naming the previous device as active for as long as that device takes to let go. A web player holds on for tens of seconds. Every guard in the engine that asked the cluster therefore got "somebody else is playing" while this phone was the one making the sound, and refused to do its job.
go-librespot keeps the same answer as a single boolean it owns and gates everything on it; this is that boolean, borrowed back out of librespot.
The patch: what is this device playing?
The same shape one step further in. Spirc also carries a PlayingHere behind
a mutex — context uri, track uri, and the previous, current and coming tracks in
playing order — republished by the loop alongside the flag above.
Another client can point this device anywhere: a track from a playlist the app never opened, with no transfer to announce it. Nothing arrives from outside either, because the account does not send a device the cluster update that describes that device, so the owner of the handle was left showing whatever it believed before.
The track list is there for the contexts Spotify makes rather than stores. A daily mix, a radio, "Pop Mix" resolve to nothing for a client that is not Spotify's own, and the only copy of that queue in existence here is the one the account handed the device to play.
The patch: a weak signal must not hold the buttons
The task's select! is the only thing reading the command channel, and one of
its branches tells the account what this device is doing, which is an HTTP
request. Awaiting it inline suspends the whole loop, so a pause sent from the
app sat unread until the request came back: on a weak signal, seconds of music
under a finger that had already asked for silence.
The state update is now bounded by STATE_UPDATE_TIMEOUT, one and a half
seconds, after which the loop goes back to reading commands and leaves the
update flagged so the next turn tries again. The account can be told late. The
listener cannot.
The patch: a new running order, without a reload
Spirc::set_queue_tracks(prev, next) replaces what comes before and after the
current track and publishes the queue revision, leaving playback alone.
The app draws its own shuffle: the order on screen is the order the device is given. Turning shuffle on or off therefore changes the list under a song that is still playing, and upstream has only one way to say so — load the queue again, which restarts the decoder. The listener heard a gap in the middle of the track for a change that was only ever about the tracks after it.
The backing context is replaced with the same running order, at the current track, without loading the decoder. Otherwise refilling the next-track window, or disabling the Connect shuffle flag, restores the old order (#39). The new successor is preloaded and the state is marked for publication.