Skip to content

feat(sonos): add experimental local playback targets - #391

Closed
mrzhbr wants to merge 6 commits into
LargeModGames:mainfrom
mrzhbr:feat/sonos-current
Closed

mrzhbr wants to merge 6 commits into
LargeModGames:mainfrom
mrzhbr:feat/sonos-current

Conversation

@mrzhbr

@mrzhbr mrzhbr commented Jul 19, 2026

Copy link
Copy Markdown

Summary

  • discover Sonos S1/S2 rooms over local SSDP/UPnP and expose them alongside Spotify Connect devices
  • persist room selection as sonos:<UUID> and route local transport, seek, volume, metadata, CLI, and playbar behavior through a dedicated Sonos backend
  • resolve grouped-room transport and queue operations through the group coordinator while keeping room volume local
  • replace stale Sonos queues for new playback, preserve playlist context offsets, and start explicit URI lists immediately while continuation tracks preload asynchronously with cancellation and serialized queue mutations
  • pause Sonos explicitly when native, decoded, CLI-selected, or other Spotify playback takes ownership
  • validate LAN endpoints, disable redirects, bound response sizes, and provide credential-free SOAP diagnostics

Hardware validation

Validated on standalone S1 and S2 rooms, including multiple-room selection:

  • playlist playback and continuation
  • Liked Songs playback and continuation
  • next/previous, seek, pause/play, and volume
  • queue replacement and queue-add behavior
  • Sonos-to-native playback handoff
  • restart and persisted-room behavior

Grouped-room coordinator behavior is covered by mock integration tests but could not be hardware-tested. Sonos queue viewing and Sonos shuffle/repeat remain intentionally unsupported.

Verification

  • cargo fmt --all --check
  • cargo clippy --no-default-features --features telemetry -- -D warnings
  • cargo test --no-default-features --features telemetry — 519 passed
  • cargo clippy -- -D warnings
  • cargo test — 738 passed
  • cargo clippy --features all-sources -- -D warnings
  • LSP diagnostics: clean

Related to #251.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d406a762-42e8-4c6b-b243-1c47c0dfd05a

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
✨ Simplify code
  • Create PR with simplified code

Comment @coderabbitai help to get the list of available commands.

@mylesagray

Copy link
Copy Markdown

@mrzhbr Do you have any logging to enable debugging?

I have a firewalled network, and tested this out with logging on my router - i'm not seeing the SSDP discovery packet from Spotatui.

I can use the Sonos S2 app and it is receiving SSDP messages on the same laptop, at the same time that spotatui isn't finding the players, however is uses both 255.255.255.255:1900 as well as the 239.255.255.250:1900 that you have configured.

When looking at tcpdump while hitting d to enter devices view:

14:09:12.426613 IP (tos 0x0, ttl 1, id 3922, offset 0, flags [none], proto UDP (17), length 129)
    172.16.200.189.55473 > 239.255.255.250.ssdp: [udp sum ok] UDP, length 101
E....R....ER...........l.m.+M-SEARCH * HTTP/1.1
HOST: 239.255.255.250:1900
MAN: "ssdp:discover"
MX: 1
ST: upnp:rootdevice


14:09:12.426902 IP (tos 0x0, ttl 1, id 11026, offset 0, flags [none], proto UDP (17), length 122)
    172.16.200.189.55473 > 239.255.255.250.ssdp: [udp sum ok] UDP, length 94
E..z+.....)............l.fn.M-SEARCH * HTTP/1.1
HOST: 239.255.255.250:1900
MAN: "ssdp:discover"
MX: 1
ST: ssdp:all

I get some responses like this after a few seconds:

14:10:35.127591 IP (tos 0x0, ttl 1, id 0, offset 0, flags [DF], proto UDP (17), length 798)
    172.16.250.96.45479 > 239.255.255.250.ssdp: [udp sum ok] UDP, length 770
[email protected]...`.......l.
:.NOTIFY * HTTP/1.1
HOST: 239.255.255.250:1900
CACHE-CONTROL: max-age = 3600
LOCATION: http://172.16.250.96:1400/xml/group_description.xml
NT: urn:smartspeaker-audio:service:SpeakerGroup:1
NTS: ssdp:alive
SERVER: Linux UPnP/1.0 Sonos/86.8-78270 (ZPS1)
USN: uuid:RINCON_5CAAFD2D43F601400::urn:smartspeaker-audio:service:SpeakerGroup:1
BOOTID.UPNP.ORG: 294
CONFIGID.UPNP.ORG: 1
GROUPINFO.SMARTSPEAKER.AUDIO: gc=1; gid=RINCON_5CAAFD2D43F601400:812652129; gname="Room"
WEBSOCK.SMARTSPEAKER.AUDIO: wss://172.16.250.96:1443/websocket/api
HOUSEHOLD.SMARTSPEAKER.AUDIO: Sonos_xDv1a7V0KQzLDtkTi5BvST81Pa.7YOCuu7wBOMMHqeoeJbF
LOCATION.SMARTSPEAKER.AUDIO: lc_0c656699647543709c18b7c646eb989a
APIVER.SMARTSPEAKER.AUDIO: 1.53.1
MINAPIVER.SMARTSPEAKER.AUDIO: 1.1.0

Which seems to match your code for device filtering:

https://github.com/LargeModGames/spotatui/pull/391/changes#diff-71d6aca72d30690c4067a4117b3dcfcfcb35790b6f096c196fdb8067cbe48e88R152-R157

However nothing is showing up in the devices pane.

@Wassergeist

Copy link
Copy Markdown
Contributor

Hi @mrzhbr, thanks a lot for this. Your SOAP transport and the Spotify URI/DIDL mapping saved me a lot of digging. I tested #391 against my S2 setup. Five rooms (one of them a Beam + Sub + 2× One SL home-theater set), reached from another VLAN.

What I found with the PR as is

  • Discovery: SSDP doesn't cross my VLAN boundary, so nothing showed up (likely the same thing @mylesagray hit, and maybe what made speakers vanish on the old sonosWIP branch). mDNS (_sonos._tcp) does work through an mDNS reflector, and every record carries the location= URL.
  • Home-theater set: the Sub and both surrounds show up as separate "Wohnzimmer" rooms. GetZoneGroupState marks them as <Satellite Invisible="1">.
  • Room switch: selecting a second room leaves the first one playing.
  • The big one: multiple Spotify accounts. My wife and I both have Spotify linked in Sonos (sn=1 and sn=8). On S2, AddURIToQueue always lands on the first linked account, whatever sn or cdudn token you send. So spotatui played on her account and paused her phone. While she was listening, our stream stopped after ~30 s, which I think explains the "track restarts / jumps back" you saw. /status/accounts is empty on S2, so there's no way to pick the right account over UPnP.

What works: the local WebSocket API (wss://<ip>:1443/websocket/api)
I verified all of this on hardware:

  • playback:1 loadContent with id: {serviceId: "9", objectId: "spotify:…", accountId: "sn_8"} loads under the chosen account. Her phone kept playing. I tested track, album and playlist.
  • Push events (playback, playbackMetadata, groupVolume) arrive within ~20 ms, so no polling is needed.
  • groups:1 getGroups gives the real rooms, and modifyGroupMembers (add the target, remove the source) moves playback between rooms seamlessly.
  • It takes over a Spotify Connect session. The Connect metadata also exposes the accountId, which pairs the logged-in Spotify user with an sn automatically.
  • Some gaps stay on UPnP, and your code still covers them: a queue offset (Seek TRACK_NR), and appending / play-next (token-free DIDL keeps the right sn).

Proposal
Since #391 is ~370 commits behind main (the App/runtime split, PlaybackOwner, the Apple Music remote pattern), I'd like to rebuild on current main with your infra/sonos module as the base. Your import commit keeps you as its author, and you'd be co-author on the rest. Rough split:

  • S2: WebSocket for rooms, loading, control and events.
  • S1 / fallback: your UPnP path. I don't have an S1. @mrzhbr, could you check on S1 whether the sn in the URI is respected with two linked Spotify accounts? If it isn't, spotatui should refuse to start there instead of guessing an account.

I have this running locally on current main, behind an off-by-default sonos feature: rooms found over mDNS/SSDP and shown in the device picker (the home-theater set as one room), playback of playlists, albums, Liked Songs, search results and single tracks under the chosen account, play/pause, skip, seek, volume, shuffle/repeat, media keys over MPRIS, live playbar from the room's events, hand-back to the native player, and recovery from a lost connection and from regrouping in the Sonos app. I can own the hardware testing and follow-up for S2. @mrzhbr, would you be up for covering the S1 side?

Platforms: tested on Linux. The macOS and Windows media-key routing follows the Apple Music pattern (thin mapping onto the same App methods), but I have neither a Mac nor a Windows build environment: macOS would be compiled by the macos CI job once sonos is added there; Windows is neither built nor tested by me.

@LargeModGames, three questions before I open anything:

  1. Is this direction OK, behind a sonos feature that's off by default? It's a sizeable change overall, so I'd split it into small PRs (discovery first, then playback, then the S1/UPnP path), as you asked for Apple Music in Apple Music source on macOS (via the Music app) #586. If you'd rather review it in one go, I can also open it as a single PR.
  2. API key. The WebSocket API requires an X-Sonos-Api-Key header, but the speaker doesn't validate it. On my S2 a random UUID works for every call I tested (including loadContent); only a missing or empty header gets a 400. So nothing third-party would ship: spotatui would generate a random UUID per install (kept in state.yml, so there's no shared value to block), with an optional user-supplied key via config / SPOTATUI_SONOS_API_KEY, the same pattern as dj_api_key and the Last.fm key in Similar tracks for own-app users via an external provider (Last.fm first) #714. That's only a fallback in case Sonos ever starts enforcing keys. Does that work for you?
  3. mDNS: I tested both the mdns-sd crate (+4 crates: mdns-sd, flume, if-addrs, socket-pktinfo) and a small built-in IPv4-only browser (~150 lines). Both found all 8 players. To be transparent: I had AI write the built-in one quickly, just for this comparison. I'd rather rely on a well-maintained dependency for network protocol code than carry a hand-rolled parser, so I'd go with mdns-sd. If you'd rather avoid the extra crates, I'll polish and keep the built-in one instead.

@LargeModGames

Copy link
Copy Markdown
Owner

Closing this in favor of #795. It lists speakers on the network as normal Spotify Connect devices on your own account, so Sonos needs no separate backend there. Sonos still needs the authorization_code login, and @Wassergeist is helping test it on S2. Thanks @mrzhbr for the work here, the UPnP findings showed us the multi-account problem.

LargeModGames added a commit that referenced this pull request Oct 13, 2026
# Summary

spotatui only listed devices that were already logged in to the account,
so speakers on the local network showed up only after the official app
had used them. This finds them with an mDNS browse (`mdns-sd`) and logs
them in when you pick one, the way the official client does:

- **Google Cast** (`_googlecast._tcp`): a small CASTV2 client starts the
Spotify receiver (`CC32E753`), then `getInfo` and `addUser` with a token
from `/device-auth/v1/refresh`.
- **Spotify Connect speakers** (`_spotify-connect._tcp`): zeroconf
`getInfo` and `addUser` with a token from the Connect token exchange
(`accounts.spotify.com/api/token`,
`resource=urn:spotify:resources:connect`, `audience` = the speaker's
client id). Speakers that ask for `tokenType: accesstoken` get an access
token; Sonos asks for `authorization_code` and gets an auth code from
the same exchange.
- **Sonos rooms** are also found over `_sonos._tcp` at
`:1400/spotifyzc`, for networks that only pass that record. A room that
both services announce is listed once.

Picking a speaker logs it in, waits for it to join the cluster, then
does the normal transfer. The audio goes from Spotify to the speaker
directly, on your own account. No TUI or GUI change: the devices appear
in the existing device list.

Replaces #391. Closes #251.

# Testing

- `cargo fmt --all -- --check`: exit 0
- `cargo clippy --locked -- -D warnings`, and with
`--no-default-features` for `telemetry,tui`, `telemetry`,
`telemetry,streaming` and the `gui` leg: exit 0 on all five
- `cargo test --locked --no-default-features --features telemetry,tui`:
1538 passed, 0 failed
- `cargo test --locked`: 2007 passed, 0 failed, 7 ignored
- `cargo clippy --manifest-path desktop/Cargo.toml -- -D warnings`: exit
0; `cargo test --manifest-path desktop/Cargo.toml`: 6 passed
- Live on Windows: a Google Nest Mini and a Denon Home Sound Bar 550,
logged in from the device list and played on at 10% volume, from probes
and from the TUI.
- Live on Linux (NixOS), by @Wassergeist: Sonos S2 (4× One, 1× Beam)
behind a VLAN that only passes `_sonos._tcp`. Rooms, groups and the Beam
home-theater set show up once; idle rooms log in and play on his own
account; play, pause, skip, volume and switching back work. Details in
the comment below.

# Additional notes

- macOS is CI-only so far.
- Not yet: speakers that want the encrypted `default` blob, Cast groups,
DIAL TVs.
- Open from the Sonos test: after a transfer away from spotatui the
playbar keeps "Playback moved to another Spotify device." for a while
and the native player runs a full recovery; a speaker that left the
network stays listed and picking it shows a raw 502 timeout. Not tested
yet: a room last used by a second Spotify account in the same Sonos
household.
- The eSDK zeroconf port changes after each login; the browse picks up
the new one.
- New crates: `mdns-sd` (+ `flume`, `if-addrs`, `socket-pktinfo`);
`rustls` and `tokio-rustls` were already in the lock.
`desktop/Cargo.lock` is refreshed here because `mdns-sd` needs a newer
`fastrand` than it pinned.

---
<sub>💬 Questions or want to chat with other contributors? Join the
[spotatui Discord](https://spotatui.com/discord).</sub>


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* Spotify now discovers compatible Google Cast and Spotify Connect
speakers on your local network and includes them in the available device
list.
* You can transfer playback to a discovered speaker. If it isn’t
connected yet, Spotify attempts to connect it before completing the
transfer.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants