Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,15 @@ interface AudioPlayer {
/** Apply a linear gain in [0.0, 1.0] derived from the perceptual volume curve. */
fun setVolume(gain: Float)
}

/** Discards every call. Used when a host does not advertise [OptionalRole.PLAYER]. */
object NoOpAudioPlayer : AudioPlayer {
override val isPlaying = false
override val droppedDecodeFrames = 0L
override fun configure(format: StreamFormat) {}
override fun start() {}
override fun flush() {}
override fun stop() {}
override fun transition(format: StreamFormat) {}
override fun setVolume(gain: Float) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,20 @@ data class DiagnosticsSnapshot(
val isAudioPlaying: Boolean = false,
)

/**
* Roles a host can advertise in `client/hello`. The spec makes every role conditional, including
* `player@v1`, so a controller-only or metadata-only host can leave [PLAYER] out.
* Declaration order is the wire order of `supported_roles`.
*/
enum class OptionalRole(val roleName: String) {
PLAYER("player@v1"),
METADATA("metadata@v1"),
ARTWORK("artwork@v1"),
CONTROLLER("controller@v1"),
COLOR("color@v1"),
VISUALIZER("visualizer@v1"),
}

/**
* Core SendSpin WebSocket client.
*
Expand All @@ -62,6 +76,19 @@ data class ClientPreferences(
val supportedFormats: List<AudioFormat>,
val artworkChannels: List<ArtworkChannel>,
val visualizerSupport: VisualizerSupport? = null,
/** Advertised `player@v1_support.buffer_capacity`. Defaults match [PlayerSupport]. */
val playerBufferCapacity: Int = 262144,
/** Advertised `player@v1_support.supported_commands`. Defaults match [PlayerSupport]. */
val playerSupportedCommands: List<String> = listOf("volume", "mute"),
/**
* Roles to advertise in `client/hello`. A role that is absent here is omitted from
* `supported_roles` together with its `*_support` block.
* Defaults to every role — reduce the set for a host that implements only a subset,
* or for a server that rejects a hello carrying roles it doesn't expect.
* [OptionalRole.PLAYER] also needs a `SendSpinClient` audioPlayerFactory, and
* [OptionalRole.VISUALIZER] a non-null [visualizerSupport], to take effect.
*/
val supportedOptionalRoles: Set<OptionalRole> = OptionalRole.entries.toSet(),
)

@OptIn(ExperimentalCoroutinesApi::class)
Expand All @@ -75,14 +102,20 @@ class SendSpinClient(
private val productName: String,
private val softwareVersion: String,
private val macAddress: String? = null,
audioPlayerFactory: (AudioBuffer, ClockSync) -> AudioPlayer,
/** Omit only for a host that leaves [OptionalRole.PLAYER] out of its preferences. */
audioPlayerFactory: ((AudioBuffer, ClockSync) -> AudioPlayer)? = null,
/** Set to false to prevent automatic reconnection on disconnect (e.g. in conformance tests). */
private val reconnectEnabled: Boolean = true,
private val settingsStore: ClientSettingsStore = NoOpClientSettingsStore,
) {
val clockSync = ClockSync()
val audioBuffer = AudioBuffer(clockSync)
val audioPlayer: AudioPlayer = audioPlayerFactory(audioBuffer, clockSync)
val audioPlayer: AudioPlayer = audioPlayerFactory?.invoke(audioBuffer, clockSync) ?: run {
require(OptionalRole.PLAYER !in preferences.supportedOptionalRoles) {
"player@v1 is in supportedOptionalRoles but no audioPlayerFactory was provided"
}
NoOpAudioPlayer
}

private val parser = MessageParser(moshi)
private val clientHelloAdapter = moshi.adapter(ClientHello::class.java)
Expand Down Expand Up @@ -673,24 +706,35 @@ class SendSpinClient(

// ── Hello ─────────────────────────────────────────────────────────────────

/** VISUALIZER needs both signals to agree: the role opt-in and a non-null support block. */
private fun advertises(role: OptionalRole): Boolean =
role in preferences.supportedOptionalRoles &&
(role != OptionalRole.VISUALIZER || preferences.visualizerSupport != null)

private fun buildClientHello(): ClientHello {
val roles = buildList {
add("player@v1"); add("metadata@v1"); add("artwork@v1"); add("controller@v1"); add("color@v1")
if (preferences.visualizerSupport != null) add("visualizer@v1")
}
// Iterate the enum, not the caller's Set, so wire order stays deterministic.
val roles = OptionalRole.entries.filter { advertises(it) }.map { it.roleName }
return ClientHello(
payload = ClientHelloPayload(
clientId = clientId,
name = clientName,
deviceInfo = DeviceInfo(manufacturer, productName, softwareVersion),
macAddress = macAddress,
supportedRoles = roles,
playerSupport = PlayerSupport(supportedFormats = preferences.supportedFormats),
metadataSupport = MetadataSupport(),
artworkSupport = ArtworkSupport(channels = preferences.artworkChannels),
controllerSupport = ControllerSupport(),
colorSupport = ColorSupport(),
visualizerSupport = preferences.visualizerSupport,
playerSupport = if (advertises(OptionalRole.PLAYER)) {
PlayerSupport(
supportedFormats = preferences.supportedFormats,
bufferCapacity = preferences.playerBufferCapacity,
supportedCommands = preferences.playerSupportedCommands,
)
} else null,
metadataSupport = if (advertises(OptionalRole.METADATA)) MetadataSupport() else null,
artworkSupport = if (advertises(OptionalRole.ARTWORK)) {
ArtworkSupport(channels = preferences.artworkChannels)
} else null,
controllerSupport = if (advertises(OptionalRole.CONTROLLER)) ControllerSupport() else null,
colorSupport = if (advertises(OptionalRole.COLOR)) ColorSupport() else null,
visualizerSupport = preferences.visualizerSupport.takeIf { advertises(OptionalRole.VISUALIZER) },
)
)
}
Expand Down Expand Up @@ -742,7 +786,10 @@ class SendSpinClient(

private fun sendClientState() {
val activeRoles = _serverHello.value?.activeRoles
val playerActive = activeRoles == null || activeRoles.any { it == "player@v1" || it == "player" }
// activeRoles is null before the server hello, when the volume/mute/delay setters can
// already report state — so gate on our own advertisement too.
val playerActive = advertises(OptionalRole.PLAYER) &&
(activeRoles == null || activeRoles.any { it == "player@v1" || it == "player" })
val player = if (playerActive) {
PlayerStatePayload(
volume = playerVolume,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ class ClientStatePlayerRoleTest {
override fun close(code: Int, reason: String?) {}
}

private fun buildClient() = SendSpinClient(
private fun buildClient(preferences: ClientPreferences = defaultPreferences) = SendSpinClient(
okHttpClient = OkHttpClient.Builder().build(),
moshi = moshi,
preferences = defaultPreferences,
preferences = preferences,
clientId = "test-id",
clientName = "Test",
manufacturer = "Acme",
Expand Down Expand Up @@ -85,6 +85,20 @@ class ClientStatePlayerRoleTest {
assertTrue("client/state should carry a player object for an active player role: $json", json.contains(""""player""""))
}

@Test
fun `client-state omits player object when the client never advertised the player role`() {
val client = buildClient(
defaultPreferences.copy(supportedOptionalRoles = setOf(OptionalRole.METADATA)),
)
val socket = RecordingSocket()
client.acceptIncomingConnection(
socket,
ServerHello(serverId = "srv-1", name = "Test Server", version = 1, activeRoles = listOf("player@v1")),
)
val json = firstClientStateJson(socket)
assertFalse("client/state should not carry a player object we never advertised: $json", json.contains(""""player""""))
}

@Test
fun `client-state includes player object when unversioned player role is active`() {
val client = buildClient()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import okhttp3.OkHttpClient
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test

Expand Down Expand Up @@ -50,6 +51,7 @@ class SendSpinClientHelloTest {
macAddress: String? = null,
preferences: ClientPreferences = defaultPreferences,
settingsStore: ClientSettingsStore = NoOpClientSettingsStore,
audioPlayerFactory: ((AudioBuffer, ClockSync) -> AudioPlayer)? = noOpPlayerFactory,
) = SendSpinClient(
okHttpClient = OkHttpClient.Builder().build(),
moshi = moshi,
Expand All @@ -60,7 +62,7 @@ class SendSpinClientHelloTest {
productName = productName,
softwareVersion = softwareVersion,
macAddress = macAddress,
audioPlayerFactory = noOpPlayerFactory,
audioPlayerFactory = audioPlayerFactory,
settingsStore = settingsStore,
)

Expand Down Expand Up @@ -205,6 +207,145 @@ class SendSpinClientHelloTest {
assertNull("visualizerStreamConfig should be null after stream/end with visualizer@v1", client.visualizerStreamConfig.value)
}

@Test
fun `empty supportedOptionalRoles advertises no role and omits every support block`() {
val json = buildClient(
preferences = defaultPreferences.copy(
visualizerSupport = VisualizerSupport(listOf("loudness"), 65536, 60),
supportedOptionalRoles = emptySet(),
),
).buildClientHelloJson()
val payload = parseHello(json).payload

assertEquals("no role should be advertised", emptyList<String>(), payload.supportedRoles)
assertNull("player support should be omitted", payload.playerSupport)
assertNull("metadata support should be omitted", payload.metadataSupport)
assertNull("artwork support should be omitted", payload.artworkSupport)
assertNull("controller support should be omitted", payload.controllerSupport)
assertNull("color support should be omitted", payload.colorSupport)
assertNull("visualizer support should be omitted", payload.visualizerSupport)
}

@Test
fun `supportedOptionalRoles defaults to the full set and advertises the optional roles`() {
val payload = parseHello(buildClient().buildClientHelloJson()).payload
assertEquals(
"default hello wire output must not move",
listOf("player@v1", "metadata@v1", "artwork@v1", "controller@v1", "color@v1"),
payload.supportedRoles,
)
assertNotNull(payload.playerSupport)
assertNotNull(payload.metadataSupport)
assertNotNull(payload.artworkSupport)
assertNotNull(payload.controllerSupport)
assertNotNull(payload.colorSupport)
}

@Test
fun `supportedOptionalRoles advertises only the selected subset in enum order`() {
val json = buildClient(
preferences = defaultPreferences.copy(
supportedOptionalRoles = setOf(OptionalRole.CONTROLLER, OptionalRole.METADATA),
),
).buildClientHelloJson()
val payload = parseHello(json).payload

assertEquals(
listOf("metadata@v1", "controller@v1"),
payload.supportedRoles,
)
assertNotNull("metadata support should be advertised", payload.metadataSupport)
assertNotNull("controller support should be advertised", payload.controllerSupport)
assertNull("player support should be omitted", payload.playerSupport)
assertNull("artwork support should be omitted", payload.artworkSupport)
assertNull("color support should be omitted", payload.colorSupport)
assertNull("visualizer support should be omitted", payload.visualizerSupport)
}

@Test
fun `VISUALIZER in supportedOptionalRoles without visualizerSupport omits the role`() {
val json = buildClient(
preferences = defaultPreferences.copy(
visualizerSupport = null,
supportedOptionalRoles = setOf(OptionalRole.VISUALIZER),
),
).buildClientHelloJson()
val payload = parseHello(json).payload

assertEquals("no role should be advertised", emptyList<String>(), payload.supportedRoles)
assertNull("visualizer support should be omitted", payload.visualizerSupport)
}

@Test
fun `visualizerSupport without VISUALIZER in supportedOptionalRoles omits the role`() {
val json = buildClient(
preferences = defaultPreferences.copy(
visualizerSupport = VisualizerSupport(listOf("loudness"), 65536, 60),
supportedOptionalRoles = setOf(OptionalRole.METADATA),
),
).buildClientHelloJson()
val payload = parseHello(json).payload

assertEquals(listOf("metadata@v1"), payload.supportedRoles)
assertNull("visualizer support should be omitted", payload.visualizerSupport)
}

@Test
fun `PLAYER absent from supportedOptionalRoles omits player@v1 and its support block`() {
val json = buildClient(
preferences = defaultPreferences.copy(
supportedOptionalRoles = setOf(OptionalRole.CONTROLLER),
),
).buildClientHelloJson()
val payload = parseHello(json).payload

assertEquals(listOf("controller@v1"), payload.supportedRoles)
assertNull("player@v1_support should be omitted", payload.playerSupport)
}

@Test
fun `omitted audioPlayerFactory with PLAYER advertised fails fast`() {
val error = assertThrows(IllegalArgumentException::class.java) {
buildClient(audioPlayerFactory = null)
}
assertTrue(
"message should name the conflicting settings, was: ${error.message}",
error.message!!.contains("supportedOptionalRoles") &&
error.message!!.contains("audioPlayerFactory"),
)
}

@Test
fun `omitted audioPlayerFactory without PLAYER falls back to NoOpAudioPlayer`() {
val client = buildClient(
preferences = defaultPreferences.copy(
supportedOptionalRoles = setOf(OptionalRole.CONTROLLER),
),
audioPlayerFactory = null,
)
assertEquals(NoOpAudioPlayer, client.audioPlayer)
}

@Test
fun `player support advertises buffer_capacity and supported_commands from preferences`() {
val json = buildClient(
preferences = defaultPreferences.copy(
playerBufferCapacity = 524288,
playerSupportedCommands = listOf("volume", "mute", "seek"),
),
).buildClientHelloJson()
val support = parseHello(json).payload.playerSupport!!
assertEquals(524288, support.bufferCapacity)
assertEquals(listOf("volume", "mute", "seek"), support.supportedCommands)
}

@Test
fun `player support defaults preserve buffer_capacity and volume-mute commands`() {
val support = parseHello(buildClient().buildClientHelloJson()).payload.playerSupport!!
assertEquals(262144, support.bufferCapacity)
assertEquals(listOf("volume", "mute"), support.supportedCommands)
}

@Test
fun `buildClientHelloJson advertises exactly FLAC, Opus, PCM at 48kHz 16-bit in that order`() {
val json = buildClient().buildClientHelloJson()
Expand Down
Loading