core icon indicating copy to clipboard operation
core copied to clipboard

Spotify: a track Soloist refuses takes the next one down with it (picking a playlist's first track plays its third)

Open sebastienfouss opened this issue 6 days ago • 2 comments

Version: a build of dev at 745a81ff (4.0.0-beta.24 + 39 commits) in a private fork that adds an output. The code involved here is not changed in the fork, and it is the same on today's dev (0fd45d23). All line references below are to 0fd45d23. Everything described happens before any audio reaches an output.

Summary

In one Spotify playlist, picking the first track in the Loxone app plays the third. It happened 4 times out of 4. Picking the second track directly plays it.

  • The Soloist --single-track run for track 1 reports that it is playing. About 0.15 s later it logs single-track: player error (22) and exits 1.
  • sonn skips track 1 (skipping unplayable queue item) and starts track 2 about 50 ms after the exit. That run logs single-track: player error (24) right after logged in and exits 1.
  • sonn skips track 2 too, and track 3 plays.

So a track the engine refuses takes the next track down with it, even though that next track plays fine.

Steps to reproduce

  1. Use a Spotify playlist whose first track the engine refuses. Here the first track is from a compilation album. Why the engine refuses it is not known (see below).
  2. Pick the first track in the Loxone app.
  3. The third track plays.

What the log shows (zone 5; account, playlist and track ids removed; engine lines trimmed to their message)

22:41:04.959Z [DEBUG][LoxoneHttp|Processor] [command="audio/5/serviceplay/spotify/<account>/<track 1>/parentpath/<playlist>/0/noshuffle/…"] command received
22:41:04.963Z [DEBUG][Zones|Manager] [authority=local items=42 startIndex=0 target=<track 1>] queue rebuilt
22:41:05.181Z [DEBUG][Audio|SoloistProcess] [line="restoring session"] soloist
22:41:05.490Z [DEBUG][Audio|SoloistProcess] [line="logged in as <user>"] soloist
22:41:05.494Z [INFO][Input|SoloistTrack] [uri=<track 1>] soloist is playing a track for this zone
22:41:05.494Z [DEBUG][Audio|SoloistProcess] [line="became active device"] soloist
22:41:05.636Z [DEBUG][Audio|SoloistProcess] [line="single-track: player error (22)"] soloist
22:41:05.699Z [DEBUG][Audio|SoloistProcess] [code=1 what=track] soloist exited
22:41:05.699Z [WARN][Input|Soloist] [detail="exit 1" uri=<track 1>] spotify playback stopped for this room
22:41:05.702Z [INFO][Zones|Manager] [audiopath=<track 1> fromIndex=0 nextIndex=1] skipping unplayable queue item; advancing to next
22:41:05.751Z [DEBUG][Audio|SoloistProcess] soloist preferences applied
22:41:05.835Z [DEBUG][Audio|SoloistProcess] [line="restoring session"] soloist
22:41:06.147Z [DEBUG][Audio|SoloistProcess] [line="logged in as <user>"] soloist
22:41:06.149Z [DEBUG][Audio|SoloistProcess] [line="single-track: player error (24)"] soloist
22:41:06.149Z [INFO][Input|SoloistTrack] [uri=<track 2>] soloist is playing a track for this zone
22:41:06.150Z [DEBUG][Audio|SoloistProcess] [line="became active device"] soloist
22:41:06.190Z [DEBUG][Audio|SoloistProcess] [code=1 what=track] soloist exited
22:41:06.191Z [INFO][Zones|Manager] [audiopath=<track 2> fromIndex=1 nextIndex=2] skipping unplayable queue item; advancing to next
22:41:06.618Z [INFO][Input|SoloistTrack] [uri=<track 3>] soloist is playing a track for this zone
22:41:06.789Z [INFO][Audio|Manager] [source=spotify] playback started

Between two of the tries, audio/5/serviceplay/…/<track 2>/parentpath/<playlist>/1/… played track 2 straight away.

What is known, and what is not

  • The codes. 22 and 24 are the engine's own codes. sonn's code does not name them, and neither do the engine's strings (single-track: player error (%d), single-track: ignoring player error after start (%d)). Why track 1 is refused is not known.
  • It is not the gap between runs. After a run stopped normally (reason=stopped, exit 0), the next run starts just as fast (7 ms in one case, against about 50 ms after a refusal), and track 2 picked right after such a stop played. After a run refused with 22, the next one fails with 24. After a run that failed with 24, the next one plays. It looks as if a refusal leaves something behind that the next run on the same account inherits. That is my reading of the logs, not an established fact. If you know what 24 means, there may be a better fix than the one below.
  • Where it happens. It is in SoloistPlaybackService and the queue's skip loop (playRequestService.ts:577). A run that says it is playing and then exits before its stream opens is reported through onTrackEnded (soloistPlaybackService.ts:1161). getPlaybackSource then returns null (:1136), and the loop moves on to the next item.

Proposed fix

The change is in SoloistPlaybackService. Two commits, each with tests.

1. A track refused right after another refusal gets a second go.

  • When it applies. The account's last run failed at once, before a sound, and the next track's run fails the same way. That next track then gets one second go.
  • What "failed at once, before a sound" means. Either the run exited with an error before its stream was taken, within 5 s of saying it was playing. Or the engine exited before ever saying it was playing (no_start), within 5 s of the start.
  • The first go does not stop the room. For a go that will be retried, onTrackEnded skips its transport(zoneId, 'stop'), because the same track is about to start again. When the retry fails, the room is stopped as before.
  • Limits. A track that plays clears the account. A second go is all a track gets: a track that fails both goes is skipped as before.
  • Code shape. getPlaybackSource (soloistPlaybackService.ts:1038) becomes a short wrapper around the existing body, renamed playTrack. playTrack tells a refusal apart from the other ways of returning null.

2. The 5 s count from when the engine says it is playing, not from the start. On the server, the first run after a restart took 15.5 s before the engine printed its first line (a cold start). Counted from the start, that refusal fell outside the window, and the third track played again. An engine that never says it is playing is still timed from the start.

Diff (src only, against 0fd45d23)
diff --git a/src/adapters/inputs/spotify/soloist/soloistPlaybackService.ts b/src/adapters/inputs/spotify/soloist/soloistPlaybackService.ts
index 468ca059..bd5250f7 100644
--- a/src/adapters/inputs/spotify/soloist/soloistPlaybackService.ts
+++ b/src/adapters/inputs/spotify/soloist/soloistPlaybackService.ts
@@ -65,6 +65,16 @@ const STORE_WAIT_MS = 1500;
  */
 const STREAM_WAIT_MS = 20_000;
 
+/**
+ * How soon a run has to fail, without a sound, for the failure to count as a refusal: counted from
+ * when its engine said it was playing, or from the start for an engine that never said so.
+ *
+ * Measured: a track Spotify would not play ended its run a sixth of a second after the engine said
+ * it was playing, and the run started straight after it failed as fast. Not from the start: the
+ * first run after a restart took 15 s just to bring its engine up, and its refusal went uncounted.
+ */
+const REFUSED_AT_ONCE_MS = 5000;
+
 /** Everything that has to be true before an account can play, named so the UI can say which is not. */
 export type SoloistReadiness =
   | { ready: true }
@@ -271,6 +281,16 @@ export class SoloistPlaybackService {
   private readonly draining = new Map<string, Promise<void>>();
   /** Why the last track would not start, so the screen can say something better than "no". */
   private lastFailure: TrackRunFailure | null = null;
+  /**
+   * Accounts whose last run was refused at once, before a sound, so that their next one gets a
+   * second go.
+   *
+   * Measured on a playlist whose first track Spotify would not play here ("player error (22)"),
+   * four times out of four: the run started straight after it failed too ("player error (24)"), on
+   * a track that played when picked on its own, and the run after that one played. So a queue lost
+   * the refused track and the good one behind it. Kept by account, like the store the runs share.
+   */
+  private readonly refusedAtOnce = new Set<string>();
   private readonly starting = new Map<number, Promise<ZoneRunner | null>>();
   /** Track lengths as Soloist reported them, so a position update can carry one. */
   private readonly durations = new Map<number, number>();
@@ -1042,6 +1062,39 @@ export class SoloistPlaybackService {
     accountId?: string,
   ): Promise<PlaybackSource | null> {
     const account = accountId ?? (await this.defaultAccount());
+    const followsRefusal = this.refusedAtOnce.has(account);
+    let played = await this.playTrack(zoneId, uri, seekPositionMs, account, followsRefusal);
+    if (played === 'refused_at_once' && followsRefusal) {
+      // Once more is enough: what was measured is one run failing after a refusal, not two.
+      this.log.info('spotify refused this track right after another refusal; trying it again', {
+        zoneId,
+        uri,
+      });
+      played = await this.playTrack(zoneId, uri, seekPositionMs, account, false);
+    }
+    if (played === 'refused_at_once') {
+      this.refusedAtOnce.add(account);
+      return null;
+    }
+    if (played) {
+      this.refusedAtOnce.delete(account);
+    }
+    return played;
+  }
+
+  /**
+   * One go at a track, telling apart a run that failed at once, before a sound.
+   *
+   * `willRetry` is for a go that is tried again if it fails that way: its failure stops nothing,
+   * since the room is about to hear the same track from the next go.
+   */
+  private async playTrack(
+    zoneId: number,
+    uri: string,
+    seekPositionMs: number,
+    account: string,
+    willRetry: boolean,
+  ): Promise<PlaybackSource | null | 'refused_at_once'> {
     const ready = await this.readiness(account);
     if (!ready.ready) {
       this.log.warn('soloist cannot play this track yet', { zoneId, reason: ready.reason, account });
@@ -1077,8 +1130,15 @@ export class SoloistPlaybackService {
     // even connected.
     this.audio.forgetSpec(zoneId);
 
-    const start = async (): Promise<Awaited<ReturnType<typeof SoloistTrackRun.start>>> =>
-      SoloistTrackRun.start({
+    // When the run was started and when its engine said it was playing, and whether it then failed
+    // before its stream was taken: what makes a failure a refusal (see `refusedAtOnce`).
+    let startedAt = 0;
+    let playingAt = 0;
+    let handedOver = false;
+    let refused = false;
+    const start = async (): Promise<Awaited<ReturnType<typeof SoloistTrackRun.start>>> => {
+      startedAt = Date.now();
+      return SoloistTrackRun.start({
         zoneId,
         uri,
         accountId: account,
@@ -1091,8 +1151,16 @@ export class SoloistPlaybackService {
         normalize: this.settings.normalize !== false,
         seekPositionMs,
         env: await this.audio.childEnv(zoneId),
-        onEnd: (end) => this.onTrackEnded(zoneId, uri, end),
+        onEnd: (end) => {
+          // Not set yet when the engine went in the same moment as it said it was playing.
+          const sincePlaying = playingAt ? Date.now() - playingAt : 0;
+          const refusal =
+            end.reason === 'failed' && !handedOver && sincePlaying < REFUSED_AT_ONCE_MS;
+          refused ||= refusal;
+          this.onTrackEnded(zoneId, uri, end, refusal && willRetry);
+        },
       });
+    };
     let started = await start();
     if (!started.ok && started.failure === 'store_busy') {
       // Every run this server knows of has been put down and waited for by now, so a store still
@@ -1116,9 +1184,12 @@ export class SoloistPlaybackService {
         // tomorrow — and there is no point retrying this one: the room has already waited.
         void this.updateBuild('expired');
       }
-      return null;
+      return started.failure === 'no_start' && Date.now() - startedAt < REFUSED_AT_ONCE_MS
+        ? 'refused_at_once'
+        : null;
     }
     this.lastFailure = null;
+    playingAt = Date.now();
     if (runner) {
       runner.track = started.run;
     } else {
@@ -1135,14 +1206,16 @@ export class SoloistPlaybackService {
     ]);
     if (this.trackRunFor(zoneId) !== started.run) {
       // Another track was asked for while this one was still loading. Its stream is not ours to
-      // take, and this run has already been put down by whoever replaced it.
-      return null;
+      // take, and this run has already been put down by whoever replaced it. Or the run failed
+      // before a sound.
+      return refused ? 'refused_at_once' : null;
     }
     const opened = this.openAudio(zoneId);
     if (!opened) {
       started.run.stop();
       return null;
     }
+    handedOver = true;
     if (runner) {
       runner.stream = opened.stream;
     }
@@ -1158,7 +1231,7 @@ export class SoloistPlaybackService {
    * it. The other endings are not endings at all: the room would sit in silence for the rest of a
    * track that has stopped arriving, so it is told.
    */
-  private onTrackEnded(zoneId: number, uri: string, end: TrackRunEnd): void {
+  private onTrackEnded(zoneId: number, uri: string, end: TrackRunEnd, willRetry = false): void {
     const runner = this.runners.get(zoneId);
     const current = runner?.track ?? this.orphanRuns.get(zoneId) ?? null;
     if (current && current.uri !== uri) {
@@ -1183,6 +1256,16 @@ export class SoloistPlaybackService {
       this.controller?.transport(zoneId, 'stop');
       return;
     }
+    if (willRetry) {
+      // Nothing has sounded, and the same track is about to be started again: stopping the room
+      // here would stop it under that start.
+      this.log.debug('spotify refused this track before a sound; it is tried again', {
+        zoneId,
+        uri,
+        detail: end.detail,
+      });
+      return;
+    }
     this.log.warn('spotify playback stopped for this room', { zoneId, uri, detail: end.detail });
     this.controller?.transport(zoneId, 'stop');
   }

Tests

All 7 are in tests/soloistRefusedTrack.test.ts. They use a stand-in for SoloistTrackRun.start and a clock moved by hand.

  • a track refused right after a refused track gets a second go, and plays. This test also checks that the room is not stopped under the second go.
  • a refusal after a track that played gets no second go
  • a second go is all a track gets
  • an engine that exits before it plays counts as refusing the track
  • a track that fails once it is sounding still stops the room
  • a refusal counts from when the engine said it was playing, however slow its start
  • a run that fails a while after saying it plays is not a refusal

Mutation check. Each of these 8 mutations makes at least one test fail:

  • no second go;
  • every refusal gets a second go;
  • the refused first go stops the room;
  • a failure after the stream was taken counts as a refusal;
  • a track that played does not clear the account;
  • an engine exiting before it plays is not a refusal;
  • the window counted from the start;
  • no time bound at all.

Verified

  • On 0fd45d23, with the two commits cherry-picked: npm test 2153/2153, eslint and tsc clean. The only conflict was the test registration line. This was run with the fork's node_modules, which has node-sonos 0.3.0 where dev asks for ^0.3.1.
  • On the hardware, running the fork's image with the same code: picking track 1 now plays track 2, including as the first Spotify request after a restart.
23:32:35.453Z [DEBUG][Audio|SoloistProcess] [line="single-track: player error (22)"] soloist
23:32:35.558Z [INFO][Zones|Manager] [audiopath=<track 1> fromIndex=0 nextIndex=1] skipping unplayable queue item; advancing to next
23:32:36.024Z [DEBUG][Audio|SoloistProcess] [line="single-track: player error (24)"] soloist
23:32:36.082Z [DEBUG][Input|Soloist] [detail="exit 1" uri=<track 2>] spotify refused this track before a sound; it is tried again
23:32:36.082Z [INFO][Input|Soloist] [uri=<track 2>] spotify refused this track right after another refusal; trying it again
23:32:36.551Z [INFO][Input|SoloistTrack] [uri=<track 2>] soloist is playing a track for this zone
23:32:38.182Z [INFO][Audio|Manager] [source=spotify] playback started

Not covered

  • Why the engine refuses track 1 in the first place (22).
  • The first refusal still stops the zone, as it did before the fix, while the skip loop moves on to the next item.

I can follow up with a pull request containing the two commits and their tests if that helps.

sebastienfouss avatar Nov 28 '26 23:11 sebastienfouss

A follow-up on why track 1 is refused.

The track does not appear in this playlist at all in the Spotify app, signed in to the same account. The app hides the tracks it cannot play for the account. So track 1 is most likely not available in the account's country, and player error (22) is how the engine refuses such a track.

sonn lists the track anyway. Its playlist listing never reads whether a track is playable:

  • fetchPlaylistTracks uses pathfinder, and mapTrack keeps the name, artists, album, cover and duration.
  • The Web API fallback (/playlists/{id}/items) does the same.

If the listing could tell which tracks are playable, sonn could hide or mark the ones that are not, as the Spotify app does. Picking them would then no longer go through a refusal at all. The second go proposed above would still be needed, for any track that comes right after a refusal.

sebastienfouss avatar Nov 28 '26 23:11 sebastienfouss

Thanks for the analysis and the follow-up on why track 1 is refused. Your second-go approach is on dev now (e3b1cce), with you as co-author: a track refused at once right after another refusal on the same account gets one more go, that first go doesn't stop the zone, and the window counts from when the engine says it's playing. Marking tracks the account can't play in the listing, as the Spotify app does, is a good idea; I'll keep that for later.

rudyberends avatar Nov 30 '26 10:11 rudyberends