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.

Start a song in a second instead of five

Lelonio258297ea3750
diff --git a/native/Cargo.lock b/native/Cargo.lock
index 0c1f8f3..e386c8d 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -2334,6 +2334,7 @@ dependencies = [
"futures-util",
"http",
"jni",
+ "librespot-audio",
"librespot-connect",
"librespot-core",
"librespot-metadata",
diff --git a/native/Cargo.toml b/native/Cargo.toml
index a92b1fc..1daab3c 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -18,6 +18,10 @@ librespot-playback = { version = "0.8", default-features = false, features = ["r
# are only recorded in their history — because this publishes state; nothing
# about decoding audio requires it.
librespot-connect = { version = "0.8", default-features = false, features = ["rustls-tls-webpki-roots"] }
+# Only for its fetch parameters: how big a block is asked for, and how long the
+# player waits before it starts. The defaults are tuned for a desktop on a fixed
+# line; see `engine::tune_fetching`.
+librespot-audio = { version = "0.8", default-features = false, features = ["rustls-tls-webpki-roots"] }
librespot-metadata = { version = "0.8", default-features = false, features = ["rustls-tls-webpki-roots"] }
librespot-protocol = { version = "0.8", default-features = false }
protobuf = "3"
diff --git a/native/src/engine.rs b/native/src/engine.rs
index a0ed811..41fa7c3 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -95,6 +95,54 @@ pub(crate) fn playback_armed() -> bool {
PLAYBACK_ARMED.load(Ordering::SeqCst) || uptime_ms() >= ARM_BY_MS.load(Ordering::SeqCst)
}
+/// How a track is fetched, which is most of how long it takes to start.
+///
+/// While a track is being opened the file is in random-access mode: every read
+/// the decoder makes that lands on bytes nobody has yet asks the CDN for a
+/// block and waits for it. Symphonia makes several of those — the Ogg headers,
+/// Spotify's own normalisation packet, then the seek to the starting position —
+/// and with librespot's default block of 64 KiB each one is a separate request
+/// with a full round trip in front of it. Measured on this phone, on a healthy
+/// connection: the download itself took 300 ms and opening the decoder took two
+/// seconds, all of it waiting for those small blocks.
+///
+/// What is left here are the waits, not the sizes: a phone on wifi is not half
+/// a second away from a CDN, and half a second of audio in hand is enough to
+/// start on. The block size is the crate's own; see the note beside it.
+///
+/// Set once for the process; a second call is refused by the crate and ignored
+/// here, which is right — the first player's numbers are as good as the next's.
+fn tune_fetching() {
+ use std::time::Duration;
+
+ // Back at the crate's own size, and deliberately.
+ //
+ // Raising it looked obvious — fewer requests for the same bytes — and made
+ // things worse: while a track is opening, every read the decoder makes on
+ // bytes nobody has fetches a whole block and waits for it, so a bigger
+ // block is a longer wait at each of those. What actually cost the time was
+ // the seek that is no longer done at all; see the note in player.rs.
+ let minimum_download_size = 64 * 1024;
+ let minimum_throughput = 8 * 1024;
+ let _ = librespot_audio::AudioFetchParams::set(librespot_audio::AudioFetchParams {
+ minimum_download_size,
+ minimum_throughput,
+ // A phone on wifi is not half a second away from a CDN, and assuming it
+ // is makes the loader hold back on the prefetch that would hide the
+ // next round trip.
+ initial_ping_time_estimate: Duration::from_millis(150),
+ maximum_assumed_ping_time: Duration::from_millis(800),
+ // What has to be in hand before the first sample is played. A second is
+ // a second of waiting on every track; half of one is still several
+ // blocks at this size.
+ read_ahead_before_playback: Duration::from_millis(500),
+ read_ahead_during_playback: Duration::from_secs(5),
+ prefetch_threshold_factor: 4.0,
+ // A block that has not arrived in fifteen seconds is not going to.
+ download_timeout: Duration::from_secs(15),
+ });
+}
+
/// Shuts the output until `gate` is satisfied.
fn shut(gate: Gate) {
if let Ok(mut current) = GATE.lock() {
@@ -285,6 +333,8 @@ pub fn start(
crossfade_ms: i32,
listener: GlobalRef,
) -> EngineResult<()> {
+ tune_fetching();
+
let mut guard = ENGINE.lock().map_err(|_| "engine mutex poisoned")?;
if guard.is_some() {
return Err("engine already started".into());
diff --git a/native/vendor/librespot-playback/src/player.rs b/native/vendor/librespot-playback/src/player.rs
index 717976c..fd3f0b9 100644
--- a/native/vendor/librespot-playback/src/player.rs
+++ b/native/vendor/librespot-playback/src/player.rs
@@ -1067,6 +1067,7 @@ impl PlayerTrackLoader {
}
};
+ let began = Instant::now();
let audio_item = match AudioItem::get_file(&self.session, track_uri).await {
Ok(audio) => match self.find_available_alternative(audio).await {
Some(audio) => audio,
@@ -1088,6 +1089,8 @@ impl PlayerTrackLoader {
"Loading <{}> with Spotify URI <{}>",
audio_item.name, audio_item.uri
);
+ // LOCAL PATCH: where the wait before a song starts actually goes.
+ let after_metadata = began.elapsed();
// (Most) podcasts seem to support only 96 kbps Ogg Vorbis, so fall back to it
let formats = match self.config.bitrate {
@@ -1163,6 +1166,7 @@ impl PlayerTrackLoader {
};
let is_cached = encrypted_file.is_cached();
+ let after_open = began.elapsed();
let stream_loader_controller = encrypted_file.get_stream_loader_controller().ok()?;
@@ -1203,6 +1207,7 @@ impl PlayerTrackLoader {
}
};
+ let after_key = began.elapsed();
let mut decrypted_file = AudioDecrypt::new(key, encrypted_file);
let is_ogg_vorbis = AudioFiles::is_ogg_vorbis(format);
@@ -1302,13 +1307,33 @@ impl PlayerTrackLoader {
// the cursor may have been moved by parsing normalisation data. This may not
// matter for playback (but won't hurt either), but may be useful for the
// passthrough decoder.
- let stream_position_ms = match decoder.seek(position_ms) {
- Ok(new_position_ms) => new_position_ms,
- Err(e) => {
- error!(
- "PlayerTrackLoader::load_track error seeking to starting position {position_ms}: {e}"
- );
- return None;
+ // LOCAL PATCH: a track that starts at the beginning is already there.
+ //
+ // Upstream seeks unconditionally, and the note above says why: the
+ // cursor may have moved while the normalisation packet was read.
+ // That read happens on the stream *before* the decoder is built,
+ // and the decoder is built on a fresh view of the file, so a new
+ // decoder is at the first audio packet already.
+ //
+ // What the seek costs is the whole point of this patch. Symphonia
+ // is asked for an accurate seek, which on an Ogg stream is a
+ // bisection: it reads pages at scattered offsets to find the one
+ // holding the target. Over a network file that is not yet
+ // downloaded, every one of those reads asks the CDN for a block and
+ // waits — measured on this phone at between eight hundred
+ // milliseconds and twelve seconds, on every single track, to arrive
+ // at a position the decoder was already sitting on.
+ let stream_position_ms = if position_ms == 0 {
+ 0
+ } else {
+ match decoder.seek(position_ms) {
+ Ok(new_position_ms) => new_position_ms,
+ Err(e) => {
+ error!(
+ "PlayerTrackLoader::load_track error seeking to starting position {position_ms}: {e}"
+ );
+ return None;
+ }
}
};
@@ -1317,7 +1342,18 @@ impl PlayerTrackLoader {
let is_explicit = audio_item.is_explicit;
- info!("<{}> ({} ms) loaded", audio_item.name, duration_ms);
+ info!(
+ "<{}> ({} ms) loaded in {} ms (metadata {} ms, stream {} ms, key {} ms, decode {} ms{})",
+ audio_item.name,
+ duration_ms,
+ began.elapsed().as_millis(),
+ after_metadata.as_millis(),
+ (after_open - after_metadata).as_millis(),
+ (after_key - after_open).as_millis(),
+ (began.elapsed() - after_key).as_millis(),
+ if is_cached { ", from the cache" } else { "" },
+ );
+
return Some(PlayerLoadedTrackData {
decoder,