Skip to content

Native Android client for Spotify, built with Jetpack Compose

Chromecast for extension, downloaded and device songs, without Google Play Services: Cast devices in the device picker, a small CastV2 sender on the Default Media Receiver, songs served from the phone on the LAN behind a per-session token with Range support, downloads decrypted on the fly, playback back on the phone at the same position

kota-zo72fd1a39716c
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 1553ffa1..9c104a50 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -68,3 +68,11 @@ https://github.com/rsms/inter
The Immersive look's typeface (`base/app/src/main/res/font/inter.ttf`), Copyright 2020 The Inter
Project Authors. Cut down to Latin with its weight axis only. Licence text in
`base/licenses/Inter-OFL.txt`.
+
+## Chromium `cast_channel.proto` — BSD-3-Clause
+https://chromium.googlesource.com/chromium/src/+/main/components/cast_channel/proto/cast_channel.proto
+
+Copyright The Chromium Authors. Casting to Google Cast devices
+(`base/app/src/main/java/com/music/spotui/cast/`) is Myspoti's own CastV2 sender, without the
+Google Cast SDK. `CastMessage.kt` codes by hand the `CastMessage` message that this file defines
+(its field numbers and types); no Chromium code is included.
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastChannel.kt b/base/app/src/main/java/com/music/spotui/cast/CastChannel.kt
new file mode 100644
index 00000000..943fa81e
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/cast/CastChannel.kt
@@ -0,0 +1,105 @@
+package com.music.spotui.cast
+
+import android.annotation.SuppressLint
+import org.json.JSONObject
+import java.io.BufferedOutputStream
+import java.io.DataInputStream
+import java.net.InetAddress
+import java.net.InetSocketAddress
+import java.security.cert.X509Certificate
+import java.util.concurrent.Executors
+import java.util.concurrent.ScheduledFuture
+import java.util.concurrent.TimeUnit
+import javax.net.ssl.SSLContext
+import javax.net.ssl.SSLSocket
+import javax.net.ssl.X509TrustManager
+
+/**
+ * One TLS connection to a Cast device (port 8009 as a rule), carrying [CastMessage]s: the
+ * virtual connection to the device, the heartbeat (a PING every 5 s, PONG to its own), and
+ * whatever the caller sends. [onMessage] and [onClosed] run on the reading thread.
+ *
+ * Cast devices present a self-signed certificate: it is accepted without checks. The
+ * optional device authentication (deviceauth namespace) is not used, as for other open senders.
+ */
+class CastChannel(
+ private val host: InetAddress,
+ private val port: Int,
+ private val onMessage: (CastMessage, JSONObject) -> Unit,
+ private val onClosed: (Throwable?) -> Unit,
+) {
+ /** The id Myspoti speaks under on this connection. */
+ val sender = "sender-myspoti-" + Integer.toHexString(java.security.SecureRandom().nextInt())
+ private lateinit var socket: SSLSocket
+ private lateinit var out: BufferedOutputStream
+ @Volatile private var closed = false
+ @Volatile private var lastHeard = 0L
+ private val beat = Executors.newSingleThreadScheduledExecutor { Thread(it, "cast-heartbeat").apply { isDaemon = true } }
+ private var beating: ScheduledFuture<*>? = null
+
+ /** The phone's own address on the network the device is on (the media server listens there). */
+ val localAddress: InetAddress get() = socket.localAddress
+
+ /** Connects (blocks, at most [timeoutMs]), says CONNECT to the device and starts reading and the heartbeat. */
+ fun open(timeoutMs: Int = 5000) {
+ val ctx = SSLContext.getInstance("TLS").apply { init(null, arrayOf(AnyCertificate), java.security.SecureRandom()) }
+ val s = ctx.socketFactory.createSocket() as SSLSocket
+ s.connect(InetSocketAddress(host, port), timeoutMs)
+ s.soTimeout = 0
+ s.tcpNoDelay = true
+ s.startHandshake()
+ socket = s
+ out = BufferedOutputStream(s.outputStream)
+ lastHeard = System.currentTimeMillis()
+ send(CastProtocol.RECEIVER, CastProtocol.NS_CONNECTION, CastProtocol.connect())
+ Thread({ readLoop(DataInputStream(s.inputStream.buffered())) }, "cast-read").apply { isDaemon = true }.start()
+ beating = beat.scheduleWithFixedDelay({
+ if (closed) return@scheduleWithFixedDelay
+ // Nothing heard for long (each PING is answered): the device or the Wi-Fi is gone.
+ if (System.currentTimeMillis() - lastHeard > 20_000) { close(java.io.IOException("no answer for 20 s")); return@scheduleWithFixedDelay }
+ runCatching { send(CastProtocol.RECEIVER, CastProtocol.NS_HEARTBEAT, CastProtocol.type("PING")) }
+ }, 5, 5, TimeUnit.SECONDS)
+ }
+
+ fun send(destination: String, namespace: String, json: JSONObject) {
+ if (closed) throw java.io.IOException("cast: connection closed")
+ val m = CastMessage(sender, destination, namespace, json.toString())
+ synchronized(this) { CastMessage.write(out, m) }
+ }
+
+ private fun readLoop(input: DataInputStream) {
+ try {
+ while (!closed) {
+ val m = CastMessage.read(input)
+ lastHeard = System.currentTimeMillis()
+ if (m.binary != null) continue
+ val json = runCatching { JSONObject(m.payload) }.getOrNull() ?: continue
+ if (m.namespace == CastProtocol.NS_HEARTBEAT) {
+ if (json.optString("type") == "PING") runCatching { send(m.source, CastProtocol.NS_HEARTBEAT, CastProtocol.type("PONG")) }
+ continue
+ }
+ onMessage(m, json)
+ }
+ } catch (t: Throwable) {
+ close(t)
+ }
+ }
+
+ /** Closes the connection; [onClosed] hears it once ([why] null: asked by Myspoti). */
+ fun close(why: Throwable? = null) {
+ if (closed) return
+ closed = true
+ beating?.cancel(false)
+ beat.shutdown()
+ if (why == null) runCatching { synchronized(this) { CastMessage.write(out, CastMessage(sender, CastProtocol.RECEIVER, CastProtocol.NS_CONNECTION, CastProtocol.type("CLOSE").toString())) } }
+ runCatching { socket.close() }
+ onClosed(why)
+ }
+
+ @SuppressLint("CustomX509TrustManager", "TrustAllX509TrustManager")
+ private object AnyCertificate : X509TrustManager {
+ override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
+ override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
+ override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastDeviceRows.kt b/base/app/src/main/java/com/music/spotui/cast/CastDeviceRows.kt
new file mode 100644
index 00000000..9fce94be
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/cast/CastDeviceRows.kt
@@ -0,0 +1,91 @@
+package com.music.spotui.cast
+
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Cast
+import androidx.compose.material.icons.filled.CastConnected
+import androidx.compose.material.icons.filled.Smartphone
+import androidx.compose.material.icons.filled.VolumeUp
+import androidx.compose.material3.Icon
+import androidx.compose.material3.Slider
+import androidx.compose.material3.SliderDefaults
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import app.myspoti.engine.R
+import com.music.spotui.di.LocalPlayer
+import com.music.spotui.ui.theme.AppAccent
+import com.music.spotui.ui.theme.AppMuted
+import com.music.spotui.ui.theme.AppText
+
+/**
+ * The Cast devices of the network in the device picker, under the Spotify Connect devices: Myspoti's
+ * own songs (extensions, downloads, the phone's files) are cast to them. While a Spotify song
+ * plays they are shown greyed: Spotify Connect casts those. While casting: back to this phone,
+ * and the device's volume.
+ */
+@Composable
+fun CastDeviceRows(onDismiss: () -> Unit) {
+ val context = LocalContext.current
+ DisposableEffect(Unit) {
+ CastDiscovery.start(context)
+ onDispose { CastDiscovery.stop() }
+ }
+ val casting = CastPlayback.device.value
+ val ownSong = LocalPlayer.active.value
+ if (casting != null) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 4.dp)) {
+ Icon(Icons.Default.VolumeUp, contentDescription = null, tint = AppMuted, modifier = Modifier.size(22.dp))
+ Slider(
+ value = CastPlayback.volume.floatValue,
+ onValueChange = { CastPlayback.setVolume(it) },
+ colors = SliderDefaults.colors(thumbColor = AppAccent, activeTrackColor = AppAccent),
+ modifier = Modifier.padding(start = 12.dp).weight(1f),
+ )
+ }
+ CastRow(Icons.Default.Smartphone, stringResource(R.string.connect_phone_is_self), null) {
+ CastPlayback.stop(back = true); onDismiss()
+ }
+ }
+ CastDiscovery.devices.filter { it.id != casting?.id }.forEach { d ->
+ val detail = when {
+ !ownSong -> stringResource(R.string.cast_spotify_via_connect)
+ else -> d.model.ifBlank { stringResource(R.string.cast_device_detail) }
+ }
+ CastRow(Icons.Default.Cast, d.name, detail, enabled = ownSong) { CastPlayback.start(d); onDismiss() }
+ }
+ if (casting != null && CastPlayback.connecting.value)
+ CastRow(Icons.Default.CastConnected, casting.name, stringResource(R.string.cast_connecting), current = true) {}
+}
+
+@Composable
+private fun CastRow(icon: ImageVector, name: String, detail: String?, current: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().clickable(enabled = enabled, onClick = onClick)
+ .alpha(if (enabled) 1f else 0.5f).padding(horizontal = 20.dp, vertical = 14.dp),
+ ) {
+ Icon(icon, contentDescription = null, tint = if (current) AppAccent else AppText, modifier = Modifier.size(28.dp))
+ Spacer(Modifier.width(16.dp))
+ Column {
+ Text(name, color = if (current) AppAccent else AppText, fontSize = 16.sp, fontWeight = FontWeight.Medium)
+ if (detail != null) Text(detail, color = AppMuted, fontSize = 13.sp)
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastDiscovery.kt b/base/app/src/main/java/com/music/spotui/cast/CastDiscovery.kt
new file mode 100644
index 00000000..1b539446
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/cast/CastDiscovery.kt
@@ -0,0 +1,97 @@
+package com.music.spotui.cast
+
+import android.content.Context
+import android.net.nsd.NsdManager
+import android.net.nsd.NsdServiceInfo
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import androidx.compose.runtime.mutableStateListOf
+import java.net.Inet4Address
+import java.net.InetAddress
+
+/** A Cast device found on the network. [id] is the device's own (TXT `id`), stable across addresses. */
+data class CastDevice(val id: String, val name: String, val model: String, val host: InetAddress, val port: Int, val service: String)
+
+/**
+ * Finds the Cast devices of the local network (mDNS / DNS-SD `_googlecast._tcp`, through
+ * Android's NsdManager, which needs no extra permission), while the device picker is open.
+ * Groups of speakers are listed too (they answer on their own port).
+ */
+object CastDiscovery {
+ private const val TYPE = "_googlecast._tcp"
+ /** The devices found, newest last (main thread). */
+ val devices = mutableStateListOf<CastDevice>()
+ private val main = Handler(Looper.getMainLooper())
+ private var nsd: NsdManager? = null
+ private var listener: NsdManager.DiscoveryListener? = null
+ private var users = 0
+ /** Before Android 14 NsdManager resolves one service at a time: the others wait here. */
+ private val waiting = ArrayDeque<NsdServiceInfo>()
+ private var resolving = false
+
+ /** Starts looking (each [start] wants one [stop]). Main thread. */
+ fun start(context: Context) {
+ if (users++ > 0) return
+ val m = context.applicationContext.getSystemService(Context.NSD_SERVICE) as? NsdManager ?: return
+ nsd = m
+ // Found anew each time: a device switched off since is not offered.
+ devices.clear()
+ val l = object : NsdManager.DiscoveryListener {
+ override fun onDiscoveryStarted(serviceType: String) = log("looking for Cast devices")
+ override fun onDiscoveryStopped(serviceType: String) = log("stopped looking for Cast devices")
+ override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) = log("discovery failed to start (error $errorCode)")
+ override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit
+ override fun onServiceFound(info: NsdServiceInfo) = main.post { waiting.addLast(info); next() }.let { }
+ override fun onServiceLost(info: NsdServiceInfo) = main.post {
+ if (devices.removeAll { it.service == info.serviceName }) log("a Cast device left (${devices.size} left)")
+ }.let { }
+ }
+ listener = l
+ runCatching { m.discoverServices(TYPE, NsdManager.PROTOCOL_DNS_SD, l) }
+ .onFailure { log("discovery not available: ${it.javaClass.simpleName}"); listener = null }
+ }
+
+ fun stop() {
+ if (users == 0 || --users > 0) return
+ listener?.let { l -> runCatching { nsd?.stopServiceDiscovery(l) } }
+ listener = null
+ waiting.clear()
+ }
+
+ @Suppress("DEPRECATION")
+ private fun next() {
+ if (resolving || listener == null) return
+ val info = waiting.removeFirstOrNull() ?: return
+ val m = nsd ?: return
+ resolving = true
+ val done = { main.post { resolving = false; next() }; Unit }
+ runCatching {
+ m.resolveService(info, object : NsdManager.ResolveListener {
+ override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {
+ log("a Cast device could not be resolved (error $errorCode)")
+ done()
+ }
+ override fun onServiceResolved(s: NsdServiceInfo) {
+ found(s)
+ done()
+ }
+ })
+ }.onFailure { done() }
+ }
+
+ @Suppress("DEPRECATION")
+ private fun found(s: NsdServiceInfo) {
+ val host = if (Build.VERSION.SDK_INT >= 34) s.hostAddresses.let { a -> a.firstOrNull { it is Inet4Address } ?: a.firstOrNull() } else s.host
+ host ?: return
+ fun attr(k: String) = s.attributes[k]?.let { String(it, Charsets.UTF_8) }.orEmpty()
+ val id = attr("id").ifBlank { s.serviceName }
+ val d = CastDevice(id, attr("fn").ifBlank { s.serviceName }, attr("md"), host, s.port, s.serviceName)
+ main.post {
+ val at = devices.indexOfFirst { it.id == d.id }
+ if (at >= 0) devices[at] = d else { devices += d; log("found a Cast device: ${d.model.ifBlank { "unknown model" }} (${devices.size} in all)") }
+ }
+ }
+
+ private fun log(line: String) = app.myspoti.host.android.Logbook.log("cast: $line")
+}
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastHttp.kt b/base/app/src/main/java/com/music/spotui/cast/CastHttp.kt
new file mode 100644
index 00000000..8ac8930f
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/cast/CastHttp.kt
@@ -0,0 +1,91 @@
+package com.music.spotui.cast
+
+/** What part of a song a Cast device asked the phone's server for (its `Range` header). */
+sealed class ByteRange {
+ /** The whole file: no Range, one the server ignores (several ranges, a length not known), or a bad one. */
+ object Full : ByteRange()
+ /** Bytes [start] to [end], both included. */
+ data class Part(val start: Long, val end: Long) : ByteRange() { val length get() = end - start + 1 }
+ /** Starts past the end of the file: 416. */
+ object Unsatisfiable : ByteRange()
+
+ companion object {
+ /**
+ * The range [header] asks of a file of [total] bytes (negative: not known, then only the
+ * whole file is served). `bytes=a-b`, `bytes=a-` and `bytes=-n` (the last n bytes).
+ */
+ fun parse(header: String?, total: Long): ByteRange {
+ val h = header?.trim() ?: return Full
+ if (!h.startsWith("bytes=", ignoreCase = true)) return Full
+ val spec = h.substring(6).trim()
+ if (spec.contains(',')) return Full
+ val dash = spec.indexOf('-')
+ if (dash < 0) return Full
+ val a = spec.substring(0, dash).trim()
+ val b = spec.substring(dash + 1).trim()
+ if (total < 0) return Full
+ if (a.isEmpty()) {
+ val n = b.toLongOrNull()?.takeIf { it >= 0 } ?: return Full
+ if (n == 0L || total == 0L) return Unsatisfiable
+ return Part((total - n).coerceAtLeast(0), total - 1)
+ }
+ val start = a.toLongOrNull()?.takeIf { it >= 0 } ?: return Full
+ val end = if (b.isEmpty()) total - 1 else (b.toLongOrNull()?.takeIf { it >= start } ?: return Full).coerceAtMost(total - 1)
+ if (start >= total) return Unsatisfiable
+ return Part(start, end)
+ }
+ }
+}
+
+/** The audio type of a song from its first bytes, as the Cast device needs it in the load. */
+object CastFormats {
+ /** Bytes to read for [mime]. */
+ const val HEAD = 16
+
+ /** The size of an ID3v2 tag at the start of [head] (its 10-byte header included), or 0 without one. */
+ fun id3Size(head: ByteArray): Long {
+ if (head.size < 10 || head[0] != 'I'.code.toByte() || head[1] != 'D'.code.toByte() || head[2] != '3'.code.toByte()) return 0
+ var n = 0L
+ for (k in 6..9) n = (n shl 7) or (head[k].toLong() and 0x7F)
+ val footer = if (head[5].toInt() and 0x10 != 0) 10 else 0
+ return 10 + n + footer
+ }
+
+ /** The MIME type of audio starting with [head], or null when not known (see [byName]). */
+ fun mime(head: ByteArray): String? {
+ fun at(i: Int, s: String) = head.size >= i + s.length && s.indices.all { head[i + it] == s[it].code.toByte() }
+ val b0 = head.getOrNull(0)?.toInt()?.and(0xFF) ?: return null
+ val b1 = head.getOrNull(1)?.toInt()?.and(0xFF) ?: 0
+ return when {
+ at(0, "fLaC") -> "audio/flac"
+ at(0, "OggS") -> "audio/ogg"
+ at(4, "ftyp") -> "audio/mp4"
+ at(0, "RIFF") && at(8, "WAVE") -> "audio/wav"
+ b0 == 0x1A && b1 == 0x45 && head.getOrNull(2) == 0xDF.toByte() && head.getOrNull(3) == 0xA3.toByte() -> "audio/webm"
+ // ADTS (AAC): sync, then layer 00.
+ b0 == 0xFF && (b1 and 0xF6) == 0xF0 -> "audio/aac"
+ // MPEG audio frame sync (MP3).
+ b0 == 0xFF && (b1 and 0xE0) == 0xE0 -> "audio/mpeg"
+ at(0, "ID3") -> "audio/mpeg"
+ else -> null
+ }
+ }
+
+ /** The MIME type a file name says, the last resort. */
+ fun byName(name: String): String = when (name.substringAfterLast('.', "").lowercase()) {
+ "flac" -> "audio/flac"
+ "ogg", "oga", "opus" -> "audio/ogg"
+ "m4a", "mp4", "aac" -> "audio/mp4"
+ "wav" -> "audio/wav"
+ "webm", "weba" -> "audio/webm"
+ else -> "audio/mpeg"
+ }
+
+ /** The image type of a cover from its first bytes. */
+ fun imageMime(head: ByteArray): String = when {
+ head.size >= 2 && head[0] == 0xFF.toByte() && head[1] == 0xD8.toByte() -> "image/jpeg"
+ head.size >= 4 && head[0] == 0x89.toByte() && head[1] == 'P'.code.toByte() -> "image/png"
+ head.size >= 12 && String(head, 8, 4, Charsets.US_ASCII) == "WEBP" -> "image/webp"
+ else -> "image/jpeg"
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastMessage.kt b/base/app/src/main/java/com/music/spotui/cast/CastMessage.kt
new file mode 100644
index 00000000..237710eb
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/cast/CastMessage.kt
@@ -0,0 +1,116 @@
+package com.music.spotui.cast
+
+import java.io.ByteArrayOutputStream
+import java.io.DataInputStream
+import java.io.IOException
+import java.io.OutputStream
+
+/**
+ * One message of the Cast protocol (CastV2): the `CastMessage` protobuf of Chromium's
+ * `cast_channel.proto` (BSD-3-Clause, The Chromium Authors), coded by hand here, since it has
+ * only seven fields. On the wire each message is a 4-byte big-endian length and the message.
+ *
+ * Fields: 1 protocol_version (enum, CASTV2_1_0 = 0), 2 source_id, 3 destination_id,
+ * 4 namespace, 5 payload_type (STRING = 0, BINARY = 1), 6 payload_utf8, 7 payload_binary.
+ */
+data class CastMessage(
+ val source: String,
+ val destination: String,
+ val namespace: String,
+ val payload: String = "",
+ val binary: ByteArray? = null,
+) {
+ fun encode(): ByteArray {
+ val out = ByteArrayOutputStream(64 + payload.length)
+ // proto2 "required" fields are written even when they hold their default.
+ out.tag(1, 0); out.varint(0)
+ out.text(2, source)
+ out.text(3, destination)
+ out.text(4, namespace)
+ out.tag(5, 0); out.varint(if (binary != null) 1 else 0)
+ if (binary != null) { out.tag(7, 2); out.varint(binary.size.toLong()); out.write(binary) } else out.text(6, payload)
+ return out.toByteArray()
+ }
+
+ override fun equals(other: Any?): Boolean = other is CastMessage && source == other.source &&
+ destination == other.destination && namespace == other.namespace && payload == other.payload &&
+ (binary?.contentEquals(other.binary ?: return false) ?: (other.binary == null))
+
+ override fun hashCode(): Int = ((source.hashCode() * 31 + destination.hashCode()) * 31 + namespace.hashCode()) * 31 + payload.hashCode()
+
+ companion object {
+ /** The protocol's limit for one message. */
+ const val MAX_SIZE = 64 * 1024
+
+ fun decode(bytes: ByteArray): CastMessage {
+ var i = 0
+ fun varint(): Long {
+ var shift = 0; var v = 0L
+ while (true) {
+ if (i >= bytes.size) throw IOException("cast: truncated varint")
+ val b = bytes[i++].toInt() and 0xFF
+ v = v or ((b and 0x7F).toLong() shl shift)
+ if (b < 0x80) return v
+ shift += 7
+ if (shift > 63) throw IOException("cast: varint too long")
+ }
+ }
+ fun chunk(): ByteArray {
+ val n = varint()
+ if (n < 0 || i + n > bytes.size) throw IOException("cast: truncated field")
+ return bytes.copyOfRange(i, (i + n).toInt()).also { i += n.toInt() }
+ }
+ var source = ""; var destination = ""; var namespace = ""; var payload = ""; var binary: ByteArray? = null
+ while (i < bytes.size) {
+ val key = varint()
+ val field = (key ushr 3).toInt()
+ when (val wire = (key and 7).toInt()) {
+ 0 -> varint()
+ 1 -> i += 8
+ 5 -> i += 4
+ 2 -> {
+ val b = chunk()
+ when (field) {
+ 2 -> source = String(b, Charsets.UTF_8)
+ 3 -> destination = String(b, Charsets.UTF_8)
+ 4 -> namespace = String(b, Charsets.UTF_8)
+ 6 -> payload = String(b, Charsets.UTF_8)
+ 7 -> binary = b
+ }
+ }
+ else -> throw IOException("cast: wire type $wire")
+ }
+ }
+ if (i > bytes.size) throw IOException("cast: truncated field")
+ return CastMessage(source, destination, namespace, payload, binary)
+ }
+
+ /** Writes [m] with its length before it. */
+ fun write(out: OutputStream, m: CastMessage) {
+ val body = m.encode()
+ val head = byteArrayOf((body.size ushr 24).toByte(), (body.size ushr 16).toByte(), (body.size ushr 8).toByte(), body.size.toByte())
+ out.write(head + body)
+ out.flush()
+ }
+
+ /** Reads the next message (blocks); an end of stream or a length past [MAX_SIZE] is an [IOException]. */
+ fun read(input: DataInputStream): CastMessage {
+ val n = input.readInt()
+ if (n < 0 || n > MAX_SIZE) throw IOException("cast: message of $n bytes")
+ val body = ByteArray(n)
+ input.readFully(body)
+ return decode(body)
+ }
+
+ private fun OutputStream.varint(value: Long) {
+ var v = value
+ while (v and 0x7FL.inv() != 0L) { write(((v and 0x7F) or 0x80).toInt()); v = v ushr 7 }
+ write(v.toInt())
+ }
+ private fun OutputStream.tag(field: Int, wire: Int) = varint(((field shl 3) or wire).toLong())
+ private fun OutputStream.text(field: Int, s: String) {
+ val b = s.toByteArray(Charsets.UTF_8)
+ tag(field, 2); varint(b.size.toLong()); write(b)
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastPlayback.kt b/base/app/src/main/java/com/music/spotui/cast/CastPlayback.kt
new file mode 100644
index 00000000..0e126cc4
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/cast/CastPlayback.kt
@@ -0,0 +1,487 @@
+package com.music.spotui.cast
+
+import android.content.Context
+import android.net.Uri
+import android.os.Handler
+import android.os.Looper
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableStateOf
+import com.music.spotui.data.local.LocalTrack
+import com.music.spotui.di.Graph
+import com.music.spotui.di.LocalPlayer
+import org.json.JSONObject
+import java.util.concurrent.Executors
+import java.util.concurrent.TimeUnit
+
+/**
+ * Myspoti's own player on a Cast device: the songs [LocalPlayer] plays (extension streams,
+ * downloads, the phone's files) go to the Default Media Receiver of the chosen device, fetched
+ * from the phone's [CastServer]. Spotify's songs are not cast here: Spotify Connect does that.
+ *
+ * [LocalPlayer] keeps the queue and its rules (shuffle, repeat, song radio); while casting its
+ * ExoPlayer is stopped, and each song it moves to is loaded on the device ([follow]). The
+ * device's status (position, play/pause, end of song) comes back to it, so the player screens,
+ * the media notification and the controls go on as for the phone. No crossfade while casting.
+ *
+ * All the protocol work runs on one thread ([worker]); the public calls come from the main thread.
+ */
+object CastPlayback {
+ /** The device the songs go to (or being connected to); null while they play on the phone. */
+ val device = mutableStateOf<CastDevice?>(null)
+ /** Connecting to [device], the songs still on the phone. */
+ val connecting = mutableStateOf(false)
+ /** The device's volume, 0 to 1. */
+ val volume = mutableFloatStateOf(1f)
+ /** The songs play on the device: LocalPlayer's own player is stopped and routes its controls here. */
+ @Volatile var active = false
+ private set
+
+ private val main = Handler(Looper.getMainLooper())
+ private val worker = Executors.newSingleThreadScheduledExecutor { Thread(it, "cast").apply { isDaemon = true } }
+
+ private enum class Phase { NONE, LAUNCHING, RECONNECTING, READY }
+
+ // ── Worker-thread state ──
+ private var channel: CastChannel? = null
+ private var phase = Phase.NONE
+ private var session: CastProtocol.App? = null
+ private var requestId = 0
+ private var loadRequest = -1
+ private var mediaSessionId = -1
+ private var finishedFor = -1
+ /** After a load: the play state the user wants is set once the device has the song. */
+ private var settleAfterLoad = false
+ /** The song the device has (its LOAD sent). */
+ private var loaded: LocalTrack? = null
+ /** Songs whose direct address the device could not play: proxied by the phone instead. */
+ private val directFailed = java.util.Collections.newSetFromMap(java.util.IdentityHashMap<LocalTrack, Boolean>())
+ private var lastLoadDirect = false
+ private var failures = 0
+ private var reconnects = 0
+ private var launchRequest = -1
+ private var launchAnswered = false
+ /** The media server restarted on another address at the last connection. */
+ private var serverMoved = false
+ /** The generation whose status polling runs. */
+ private var polling = -1
+
+ // ── Read from the main thread ──
+ /** Each start and end makes a new generation: what an older one left running stops. */
+ @Volatile private var generation = 0
+ /** The song the device has or is about to get. */
+ @Volatile var track: LocalTrack? = null
+ private set
+ /** Where to start [track] when its load is still to be sent. */
+ @Volatile private var startMs = 0L
+ @Volatile private var wantPlaying = false
+ @Volatile private var playerState = "IDLE"
+ @Volatile private var posMs = 0L
+ @Volatile private var posAt = 0L
+
+ private var wifiLock: android.net.wifi.WifiManager.WifiLock? = null
+ private var wakeLock: android.os.PowerManager.WakeLock? = null
+
+ // ── Calls from the app (main thread) ──
+
+ /** Sends the songs to [d] (only Myspoti's own player: [LocalPlayer] must be playing). */
+ fun start(d: CastDevice) {
+ if (!LocalPlayer.active.value) { log("not cast: a Spotify song plays (Spotify Connect casts those)"); return }
+ if (device.value?.id == d.id) return
+ val gen = ++generation
+ device.value = d
+ connecting.value = true
+ hold(true)
+ log("connecting to a ${d.model.ifBlank { "Cast device" }}")
+ worker.execute { connect(gen, d, Phase.LAUNCHING) }
+ // Not ready in time: back to the phone (it never stopped playing there unless the device was ready).
+ worker.schedule({ if (gen == generation && phase != Phase.READY) fail(gen, "no answer from the device in 15 s") }, 15, TimeUnit.SECONDS)
+ }
+
+ /** Back to the phone where the device was ([back] false: the songs stop, Spotify takes over). */
+ fun stop(back: Boolean = true) {
+ if (device.value == null && !active) return
+ val wasActive = active
+ val at = position()
+ val playing = wantPlaying
+ val gen = ++generation
+ active = false
+ device.value = null
+ connecting.value = false
+ track = null
+ hold(false)
+ log(if (back) "stopped casting: back on the phone at ${at / 1000} s" else "stopped casting")
+ worker.execute { teardown(stopApp = true); if (gen == generation) CastServer.stop() }
+ if (back && wasActive) LocalPlayer.castEnded(at, playing)
+ }
+
+ /** [t] is the current song of [LocalPlayer] (from [atMs] when it is a new one; [playing]: also the play state wanted). */
+ fun follow(t: LocalTrack?, atMs: Long, playing: Boolean? = null) {
+ if (!active || t == null) return
+ if (playing != null) wantPlaying = playing
+ if (t === track) return
+ track = t
+ startMs = atMs.coerceAtLeast(0)
+ posMs = startMs; posAt = now(); playerState = "BUFFERING"
+ val gen = generation
+ worker.execute { load(gen, t) }
+ }
+
+ /** The same song again from its start (repeat one, a list of one song). */
+ fun replay() {
+ val t = track ?: return
+ track = null
+ follow(t, 0, true)
+ }
+
+ fun play() {
+ wantPlaying = true
+ worker.execute { command("PLAY") }
+ }
+
+ fun pause() {
+ wantPlaying = false
+ if (playerState == "PLAYING") { posMs = position(); posAt = now() }
+ worker.execute { command("PAUSE") }
+ }
+
+ fun seek(ms: Long) {
+ posMs = ms.coerceAtLeast(0); posAt = now()
+ if (loaded !== track) startMs = posMs
+ worker.execute {
+ val id = mediaSessionId
+ if (phase == Phase.READY && id >= 0 && loaded === track) send(CastProtocol.NS_MEDIA, CastProtocol.seek(++requestId, id, ms))
+ }
+ }
+
+ fun setVolume(level: Float) {
+ volume.floatValue = level.coerceIn(0f, 1f)
+ worker.execute { if (phase == Phase.READY) send(CastProtocol.NS_RECEIVER, CastProtocol.setVolume(++requestId, level.toDouble()), CastProtocol.RECEIVER) }
+ }
+
+ fun position(): Long = if (playerState == "PLAYING") posMs + (now() - posAt) else posMs
+ fun isPlaying() = playerState == "PLAYING"
+ fun playWhenReady() = wantPlaying
+ fun isBuffering() = playerState == "BUFFERING" || (active && loaded !== track)
+ fun state(): String = "cast ${playerState.lowercase()}"
+
+ // ── Worker thread ──
+
+ private fun connect(gen: Int, d: CastDevice, then: Phase) {
+ if (gen != generation) return
+ // A new device (or the first): the receiver of the one before is stopped.
+ if (then == Phase.LAUNCHING) teardown(stopApp = true) else { channel?.close(); channel = null }
+ val c = CastChannel(d.host, d.port,
+ onMessage = { m, json -> worker.execute { if (gen == generation) heard(gen, m, json) } },
+ onClosed = { why -> worker.execute { if (gen == generation && why != null) lost(gen, d, why) } })
+ try {
+ c.open()
+ serverMoved = CastServer.start(c.localAddress)
+ } catch (t: Throwable) {
+ c.close()
+ log("connection failed: ${t.javaClass.simpleName}")
+ if (then == Phase.RECONNECTING) retry(gen, d) else fail(gen, "connection failed")
+ return
+ }
+ channel = c
+ phase = then
+ if (then == Phase.LAUNCHING) {
+ log("connected, launching the Default Media Receiver")
+ launch()
+ } else {
+ log("connected again, asking the device what it plays")
+ send(CastProtocol.NS_RECEIVER, CastProtocol.type("GET_STATUS").put("requestId", ++requestId), CastProtocol.RECEIVER)
+ }
+ }
+
+ private fun heard(gen: Int, m: CastMessage, json: JSONObject) {
+ val type = json.optString("type")
+ when (m.namespace) {
+ CastProtocol.NS_RECEIVER -> when (type) {
+ "RECEIVER_STATUS" -> receiverStatus(gen, CastProtocol.receiver(json), json.optInt("requestId", 0))
+ "LAUNCH_ERROR" -> fail(gen, "the device refused to launch the receiver (${json.optString("reason")})")
+ }
+ CastProtocol.NS_CONNECTION -> if (type == "CLOSE" && m.source == session?.transportId && phase == Phase.READY) {
+ log("the receiver closed the connection")
+ endFromDevice(gen)
+ }
+ CastProtocol.NS_MEDIA -> when (type) {
+ "MEDIA_STATUS" -> mediaStatus(gen, json)
+ "LOAD_FAILED" -> loadFailed(gen, "load failed")
+ "LOAD_CANCELLED" -> log("load cancelled (a newer one replaced it)")
+ "INVALID_REQUEST" -> log("invalid request: ${json.optString("reason")}")
+ }
+ }
+ }
+
+ private fun receiverStatus(gen: Int, r: CastProtocol.Receiver, request: Int) {
+ r.volume?.let { v -> main.post { if (gen == generation) volume.floatValue = v.toFloat() } }
+ when (phase) {
+ Phase.LAUNCHING -> {
+ // The answer to the launch (a receiver another phone had running may show before it).
+ if (request == launchRequest) launchAnswered = true
+ else if (request != 0 || !launchAnswered) return
+ val a = r.app?.takeIf { it.transportId.isNotBlank() } ?: return
+ session = a
+ joinApp()
+ log("receiver running")
+ ready(gen, reload = active)
+ }
+ Phase.RECONNECTING -> {
+ val a = r.app
+ if (a != null && a.sessionId == session?.sessionId) {
+ joinApp()
+ reconnects = 0
+ log("reconnected to the same receiver session")
+ // The phone's address changed (another network): the song's address died with it.
+ if (serverMoved) ready(gen, reload = true)
+ else send(CastProtocol.NS_MEDIA, CastProtocol.type("GET_STATUS").put("requestId", ++requestId))
+ } else {
+ log("the receiver session is gone: launching it again")
+ session = null
+ phase = Phase.LAUNCHING
+ launch()
+ }
+ }
+ Phase.READY -> if (r.app == null || r.app.sessionId != session?.sessionId) {
+ log("the receiver stopped on the device or another app took it")
+ endFromDevice(gen)
+ }
+ Phase.NONE -> Unit
+ }
+ }
+
+ private fun launch() {
+ launchRequest = ++requestId
+ launchAnswered = false
+ send(CastProtocol.NS_RECEIVER, CastProtocol.launch(launchRequest), CastProtocol.RECEIVER)
+ }
+
+ /** The virtual connection to the receiver app, needed before any media message. */
+ private fun joinApp() {
+ val a = session ?: return
+ phase = Phase.READY
+ send(CastProtocol.NS_CONNECTION, CastProtocol.connect(), a.transportId)
+ }
+
+ /** The receiver runs: the songs move to it (first time), or the song is loaded again (it restarted). */
+ private fun ready(gen: Int, reload: Boolean) {
+ schedulePoll(gen)
+ if (reload) {
+ loaded = null
+ val t = track ?: return
+ startMs = position()
+ load(gen, t)
+ return
+ }
+ main.post {
+ if (gen != generation) return@post
+ active = true
+ connecting.value = false
+ log("casting")
+ LocalPlayer.castStarted()
+ }
+ }
+
+ private fun load(gen: Int, t: LocalTrack) {
+ if (gen != generation || track !== t || phase != Phase.READY) return
+ val a = session ?: return
+ val entry = try {
+ CastServer.probe(t.uri, t.uri.lastPathSegment.orEmpty())
+ } catch (e: Throwable) {
+ log("could not open the song for the device: ${e.javaClass.simpleName}")
+ if (track === t) loadFailed(gen, "song not readable")
+ return
+ }
+ // Skipped again while the song was opened (an extension may take seconds).
+ if (gen != generation || track !== t || phase != Phase.READY) return
+ val direct = directUrl(t)
+ val url = direct ?: CastServer.publish(entry)
+ val cover = coverUrl(t)
+ loadRequest = ++requestId
+ mediaSessionId = -1
+ settleAfterLoad = true
+ loaded = t
+ lastLoadDirect = direct != null
+ val at = startMs
+ send(CastProtocol.NS_MEDIA, CastProtocol.load(loadRequest, a.sessionId, url, entry.mime, t.durationMs,
+ t.title, t.artist, t.album, cover, at, wantPlaying))
+ log("load sent: ${entry.mime}, ${if (entry.length >= 0) "${entry.length / 1024} KB" else "length unknown"}, " +
+ "${if (direct != null) "direct address" else "through the phone"}, from ${at / 1000} s${if (wantPlaying) "" else ", paused"}")
+ }
+
+ /** An extension's plain address (no headers, no DASH) the device can fetch itself, or null. */
+ private fun directUrl(t: LocalTrack): String? {
+ if (t.uri.scheme != com.music.spotui.extensions.ExtensionAudio.SCHEME || t in directFailed) return null
+ val s = runCatching { com.music.spotui.extensions.ExtensionAudio.resolve(t.uri) }.getOrNull() ?: return null
+ return s.url.takeIf { s.manifest == null && s.headers.isEmpty() && (it.startsWith("https://") || it.startsWith("http://")) }
+ }
+
+ private fun coverUrl(t: LocalTrack): String? {
+ val art = t.artUri.toString().takeIf { it.isNotBlank() } ?: return null
+ val large = runCatching { app.myspoti.host.android.Covers.large(art) }.getOrDefault(art)
+ if (large.startsWith("https://") || large.startsWith("http://")) return large
+ val u = Uri.parse(large)
+ return if (u.scheme == "content" || u.scheme == "file" || u.scheme == "android.resource")
+ runCatching { CastServer.publish(CastServer.Entry(u, "", -1, cover = true)) }.getOrNull() else null
+ }
+
+ private fun mediaStatus(gen: Int, json: JSONObject) {
+ val s = CastProtocol.media(json) ?: return
+ val forLoad = json.optInt("requestId", 0).let { it != 0 && it == loadRequest }
+ when {
+ forLoad -> mediaSessionId = s.mediaSessionId
+ // Waiting for the load's answer: the song before may still speak.
+ mediaSessionId < 0 || s.mediaSessionId < mediaSessionId -> return
+ // Loaded by another sender meanwhile: followed.
+ s.mediaSessionId > mediaSessionId -> mediaSessionId = s.mediaSessionId
+ }
+ playerState = s.playerState
+ posMs = s.positionMs; posAt = now()
+ if (s.playerState == "PLAYING") failures = 0
+ if (settleAfterLoad && s.playerState != "IDLE") {
+ settleAfterLoad = false
+ if (wantPlaying && s.playerState == "PAUSED") command("PLAY")
+ else if (!wantPlaying && s.playerState != "PAUSED") command("PAUSE")
+ } else if (!settleAfterLoad) {
+ // Paused or played from the device itself (or another phone): the app shows it.
+ if (s.playerState == "PAUSED") wantPlaying = false
+ if (s.playerState == "PLAYING") wantPlaying = true
+ }
+ if (s.playerState == "IDLE") when (s.idleReason) {
+ "FINISHED" -> if (finishedFor != s.mediaSessionId && loaded === track) {
+ finishedFor = s.mediaSessionId
+ log("song ended on the device")
+ main.post { if (gen == generation && active) LocalPlayer.castFinished() }
+ }
+ "ERROR" -> loadFailed(gen, "the device could not play the song")
+ }
+ main.post { if (gen == generation && active) LocalPlayer.castChanged() }
+ }
+
+ private fun loadFailed(gen: Int, why: String) {
+ val t = loaded ?: track ?: return
+ if (lastLoadDirect && t === track) {
+ log("$why from its direct address: through the phone instead")
+ directFailed += t
+ loaded = null
+ startMs = position()
+ load(gen, t)
+ return
+ }
+ failures++
+ playerState = "IDLE"
+ log("$why (failure $failures in a row)")
+ main.post {
+ if (gen != generation || !active) return@post
+ if (failures < 3) LocalPlayer.next()
+ else { wantPlaying = false; LocalPlayer.castChanged(); toast(app.myspoti.engine.R.string.cast_failed) }
+ }
+ }
+
+ private fun command(type: String) {
+ val id = mediaSessionId
+ if (phase != Phase.READY || id < 0 || loaded !== track) return
+ send(CastProtocol.NS_MEDIA, CastProtocol.media(type, ++requestId, id))
+ }
+
+ /** The device does not say where it is while it plays: asked every 5 s (the position between is counted here). */
+ private fun schedulePoll(gen: Int) {
+ if (polling == gen) return
+ polling = gen
+ poll(gen)
+ }
+
+ private fun poll(gen: Int) {
+ worker.schedule({
+ if (gen != generation) return@schedule
+ if (phase == Phase.READY && mediaSessionId >= 0 && playerState != "IDLE")
+ send(CastProtocol.NS_MEDIA, CastProtocol.type("GET_STATUS").put("mediaSessionId", mediaSessionId).put("requestId", ++requestId))
+ poll(gen)
+ }, 5, TimeUnit.SECONDS)
+ }
+
+ /** The connection dropped (Wi-Fi, device restart): connected again, at most 4 tries over about 15 s. */
+ private fun lost(gen: Int, d: CastDevice, why: Throwable) {
+ log("connection lost: ${why.javaClass.simpleName}")
+ channel = null
+ if (phase == Phase.NONE) return
+ phase = Phase.RECONNECTING
+ retry(gen, d)
+ }
+
+ private fun retry(gen: Int, d: CastDevice) {
+ if (gen != generation) return
+ if (++reconnects > 4) {
+ log("could not connect again: back on the phone")
+ main.post { if (gen == generation) { toast(app.myspoti.engine.R.string.cast_lost); stop(back = true) } }
+ return
+ }
+ val delay = longArrayOf(1, 2, 4, 8)[reconnects - 1]
+ log("connecting again in $delay s (try $reconnects)")
+ worker.schedule({ if (gen == generation) connect(gen, d, Phase.RECONNECTING) }, delay, TimeUnit.SECONDS)
+ }
+
+ private fun fail(gen: Int, why: String) {
+ log("cast failed: $why")
+ teardown(stopApp = false)
+ main.post {
+ if (gen != generation) return@post
+ toast(app.myspoti.engine.R.string.cast_failed)
+ stop(back = true)
+ }
+ }
+
+ /** The device ended the session itself: the songs come back to the phone, paused where they were. */
+ private fun endFromDevice(gen: Int) {
+ phase = Phase.NONE
+ wantPlaying = false
+ main.post { if (gen == generation) stop(back = true) }
+ }
+
+ private fun teardown(stopApp: Boolean) {
+ val c = channel
+ if (c != null && stopApp && phase == Phase.READY) session?.let { a ->
+ runCatching { c.send(CastProtocol.RECEIVER, CastProtocol.NS_RECEIVER, CastProtocol.stopApp(++requestId, a.sessionId)) }
+ }
+ c?.close()
+ channel = null
+ phase = Phase.NONE
+ session = null
+ loaded = null
+ mediaSessionId = -1; loadRequest = -1; finishedFor = -1
+ reconnects = 0; failures = 0
+ directFailed.clear()
+ playerState = "IDLE"
+ }
+
+ private fun send(namespace: String, json: JSONObject, destination: String? = null) {
+ val c = channel ?: return
+ val to = destination ?: session?.transportId ?: return
+ try { c.send(to, namespace, json) } catch (e: Throwable) { log("send failed: ${e.javaClass.simpleName}") }
+ }
+
+ /** Keeps the Wi-Fi and the CPU awake while the device fetches from the phone. */
+ @Suppress("DEPRECATION")
+ private fun hold(on: Boolean) {
+ runCatching {
+ if (on) {
+ if (wifiLock == null) wifiLock = (Graph.app.applicationContext.getSystemService(Context.WIFI_SERVICE) as android.net.wifi.WifiManager)
+ .createWifiLock(android.net.wifi.WifiManager.WIFI_MODE_FULL_HIGH_PERF, "myspoti:cast").apply { setReferenceCounted(false) }
+ if (wakeLock == null) wakeLock = (Graph.app.getSystemService(Context.POWER_SERVICE) as android.os.PowerManager)
+ .newWakeLock(android.os.PowerManager.PARTIAL_WAKE_LOCK, "myspoti:cast").apply { setReferenceCounted(false) }
+ wifiLock?.acquire(); wakeLock?.acquire(6 * 60 * 60 * 1000L)
+ } else {
+ wifiLock?.takeIf { it.isHeld }?.release(); wakeLock?.takeIf { it.isHeld }?.release()
+ }
+ }
+ }
+
+ private fun toast(res: Int) {
+ val name = device.value?.name.orEmpty()
+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(res, name), android.widget.Toast.LENGTH_SHORT).show()
+ }
+
+ private fun now() = android.os.SystemClock.elapsedRealtime()
+
+ private fun log(line: String) = app.myspoti.host.android.Logbook.log("cast: $line")
+}
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastProtocol.kt b/base/app/src/main/java/com/music/spotui/cast/CastProtocol.kt
new file mode 100644
index 00000000..d5e6bea2
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/cast/CastProtocol.kt
@@ -0,0 +1,69 @@
+package com.music.spotui.cast
+
+import org.json.JSONArray
+import org.json.JSONObject
+
+/**
+ * The JSON messages Myspoti sends a Cast device and reads from it (CastV2 namespaces), for the
+ * Default Media Receiver (no registration needed, plays what an address gives).
+ */
+object CastProtocol {
+ const val NS_CONNECTION = "urn:x-cast:com.google.cast.tp.connection"
+ const val NS_HEARTBEAT = "urn:x-cast:com.google.cast.tp.heartbeat"
+ const val NS_RECEIVER = "urn:x-cast:com.google.cast.receiver"
+ const val NS_MEDIA = "urn:x-cast:com.google.cast.media"
+ const val RECEIVER = "receiver-0"
+ /** Google's Default Media Receiver. */
+ const val DEFAULT_MEDIA_RECEIVER = "CC1AD845"
+
+ fun type(t: String) = JSONObject().put("type", t)
+ fun connect() = type("CONNECT").put("userAgent", "Myspoti").put("origin", JSONObject())
+ fun launch(requestId: Int) = type("LAUNCH").put("appId", DEFAULT_MEDIA_RECEIVER).put("requestId", requestId)
+ fun stopApp(requestId: Int, sessionId: String) = type("STOP").put("sessionId", sessionId).put("requestId", requestId)
+ fun setVolume(requestId: Int, level: Double) =
+ type("SET_VOLUME").put("volume", JSONObject().put("level", level.coerceIn(0.0, 1.0))).put("requestId", requestId)
+ fun media(t: String, requestId: Int, mediaSessionId: Int) = type(t).put("mediaSessionId", mediaSessionId).put("requestId", requestId)
+ fun seek(requestId: Int, mediaSessionId: Int, ms: Long) = media("SEEK", requestId, mediaSessionId).put("currentTime", ms / 1000.0)
+
+ /** What to play: [url] of type [mime], with the song's names and cover, from [startMs]. */
+ fun load(requestId: Int, sessionId: String, url: String, mime: String, durationMs: Long,
+ title: String, artist: String, album: String, cover: String?, startMs: Long, autoplay: Boolean): JSONObject {
+ val meta = JSONObject().put("metadataType", 3).put("title", title).put("artist", artist).put("albumName", album)
+ if (!cover.isNullOrBlank()) meta.put("images", JSONArray().put(JSONObject().put("url", cover)))
+ val media = JSONObject().put("contentId", url).put("contentUrl", url).put("streamType", "BUFFERED")
+ .put("contentType", mime).put("metadata", meta)
+ if (durationMs > 0) media.put("duration", durationMs / 1000.0)
+ return type("LOAD").put("requestId", requestId).put("sessionId", sessionId).put("media", media)
+ .put("autoplay", autoplay).put("currentTime", startMs.coerceAtLeast(0) / 1000.0)
+ }
+
+ /** The Default Media Receiver running on the device, from a RECEIVER_STATUS. */
+ data class App(val sessionId: String, val transportId: String)
+ data class Receiver(val app: App?, val volume: Double?, val muted: Boolean)
+
+ fun receiver(status: JSONObject): Receiver {
+ val s = status.optJSONObject("status") ?: JSONObject()
+ val apps = s.optJSONArray("applications")
+ var app: App? = null
+ if (apps != null) for (k in 0 until apps.length()) {
+ val a = apps.optJSONObject(k) ?: continue
+ if (a.optString("appId") == DEFAULT_MEDIA_RECEIVER) app = App(a.optString("sessionId"), a.optString("transportId"))
+ }
+ val v = s.optJSONObject("volume")
+ return Receiver(app, v?.optDouble("level")?.takeIf { !it.isNaN() }, v?.optBoolean("muted") == true)
+ }
+
+ /** One media session's state, from a MEDIA_STATUS. */
+ data class Media(val mediaSessionId: Int, val playerState: String, val positionMs: Long, val idleReason: String?, val contentId: String?)
+
+ /** The first media status of a MEDIA_STATUS, or null when the receiver has none (nothing loaded). */
+ fun media(message: JSONObject): Media? {
+ val s = message.optJSONArray("status")?.optJSONObject(0) ?: return null
+ val pos = s.optDouble("currentTime", 0.0).let { if (it.isNaN()) 0L else (it * 1000).toLong() }
+ return Media(
+ s.optInt("mediaSessionId", -1), s.optString("playerState", "IDLE"), pos,
+ s.optString("idleReason", "").ifBlank { null },
+ s.optJSONObject("media")?.optString("contentId")?.ifBlank { null },
+ )
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastServer.kt b/base/app/src/main/java/com/music/spotui/cast/CastServer.kt
new file mode 100644
index 00000000..617444f7
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/cast/CastServer.kt
@@ -0,0 +1,235 @@
+package com.music.spotui.cast
+
+import android.net.Uri
+import androidx.annotation.OptIn
+import androidx.media3.common.C
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.datasource.DataSource
+import androidx.media3.datasource.DataSpec
+import com.music.spotui.di.Graph
+import java.io.BufferedInputStream
+import java.io.BufferedOutputStream
+import java.io.IOException
+import java.io.InputStream
+import java.io.OutputStream
+import java.net.Inet6Address
+import java.net.InetAddress
+import java.net.ServerSocket
+import java.net.Socket
+import java.security.MessageDigest
+import java.security.SecureRandom
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicInteger
+
+/**
+ * The phone's small HTTP server a Cast device fetches the song from while it casts: device files,
+ * downloaded songs (decrypted on the fly from the asked offset) and extension streams (read with
+ * their headers, DASH answers as one file), all through the player's own data source
+ * ([com.music.spotui.data.offline.OfflineCrypto.Factory]), so it reads exactly what the phone plays.
+ *
+ * It listens only on the address the phone reaches the Cast device from, on a random port, and
+ * answers only paths under a random token made for each cast session. GET and HEAD, one range
+ * per request (206), Connection: close.
+ */
+@OptIn(UnstableApi::class)
+object CastServer {
+ /** A song (or cover) the device may fetch: [length] -1 when the source does not say it. */
+ class Entry(val uri: Uri, val mime: String, val length: Long, val cover: Boolean = false)
+
+ private var server: ServerSocket? = null
+ @Volatile private var token = ""
+ private val entries = ConcurrentHashMap<Int, Entry>()
+ private val nextId = AtomicInteger()
+ private val pool = Executors.newCachedThreadPool { Thread(it, "cast-http").apply { isDaemon = true } }
+ /** Requests being served, at most this many at once (a device asks two or three ranges at a time). */
+ private val busy = AtomicInteger()
+ private const val MAX_BUSY = 8
+
+ /**
+ * Listens on [address] (a new token and port when it was not listening there: true, the
+ * addresses given before are dead). Blocks briefly.
+ */
+ @Synchronized
+ fun start(address: InetAddress): Boolean {
+ val before = server
+ before?.let { if (!it.isClosed && it.inetAddress == address) return false; runCatching { it.close() } }
+ token = ByteArray(16).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
+ entries.clear()
+ val s = ServerSocket(0, 16, address)
+ server = s
+ log("server listening on port ${s.localPort}")
+ Thread({ accept(s) }, "cast-http-accept").apply { isDaemon = true }.start()
+ return before != null
+ }
+
+ @Synchronized
+ fun stop() {
+ server?.let { runCatching { it.close() }; log("server stopped") }
+ server = null
+ token = ""
+ entries.clear()
+ }
+
+ /** The address of [e] on this server (the older entries are forgotten: their address dies). */
+ fun publish(e: Entry): String {
+ val s = server ?: throw IOException("cast server not started")
+ val id = nextId.incrementAndGet()
+ entries[id] = e
+ entries.keys.filter { it <= id - 8 }.forEach { entries.remove(it) }
+ val a = s.inetAddress
+ val host = if (a is Inet6Address) "[${a.hostAddress?.substringBefore('%')}]" else a.hostAddress
+ return "http://$host:${s.localPort}/$token/${if (e.cover) "c" else "a"}/$id"
+ }
+
+ /**
+ * Opens [uri] as the phone's player would and reads its first bytes: the audio type and the
+ * length the Cast device is told. Blocks (an extension may be asked for the stream).
+ */
+ fun probe(uri: Uri, fallbackName: String): Entry {
+ val head = ByteArray(CastFormats.HEAD)
+ val length: Long
+ var mime: String?
+ source().let { src ->
+ try {
+ val n = src.open(DataSpec.Builder().setUri(uri).build())
+ length = if (n == C.LENGTH_UNSET.toLong()) -1 else n
+ val got = readFully(src, head)
+ mime = CastFormats.mime(head.copyOf(got))
+ } finally { runCatching { src.close() } }
+ }
+ // An ID3 tag first: the type is that of what follows it.
+ val tag = CastFormats.id3Size(head)
+ if (tag > 0 && (length < 0 || tag < length)) runCatching {
+ val src = source()
+ try {
+ src.open(DataSpec.Builder().setUri(uri).setPosition(tag).build())
+ val after = ByteArray(CastFormats.HEAD)
+ CastFormats.mime(after.copyOf(readFully(src, after)))?.let { mime = it }
+ } finally { runCatching { src.close() } }
+ }
+ return Entry(uri, mime ?: CastFormats.byName(fallbackName), length)
+ }
+
+ private fun source(): DataSource = com.music.spotui.data.offline.OfflineCrypto.Factory(Graph.app).createDataSource()
+
+ private fun readFully(src: DataSource, into: ByteArray): Int {
+ var got = 0
+ while (got < into.size) {
+ val n = src.read(into, got, into.size - got)
+ if (n == C.RESULT_END_OF_INPUT) break
+ got += n
+ }
+ return got
+ }
+
+ private fun accept(s: ServerSocket) {
+ while (!s.isClosed) {
+ val c = try { s.accept() } catch (e: IOException) { break }
+ if (busy.get() >= MAX_BUSY) { runCatching { c.close() }; continue }
+ busy.incrementAndGet()
+ pool.execute { try { serve(c) } finally { busy.decrementAndGet() } }
+ }
+ }
+
+ private fun serve(c: Socket) {
+ c.use { socket ->
+ socket.soTimeout = 20_000
+ val input = BufferedInputStream(socket.getInputStream())
+ val out = BufferedOutputStream(socket.getOutputStream(), 64 * 1024)
+ val head = try { readHead(input) } catch (e: IOException) { return } ?: return
+ val lines = head.split("\r\n")
+ val parts = lines.first().split(' ')
+ if (parts.size < 3) return status(out, 400, "Bad Request")
+ val method = parts[0]
+ val headers = lines.drop(1).mapNotNull { l -> l.indexOf(':').takeIf { it > 0 }?.let { l.substring(0, it).trim().lowercase() to l.substring(it + 1).trim() } }.toMap()
+ if (method == "OPTIONS") return write(out, 204, "No Content", listOf(
+ "Access-Control-Allow-Origin" to "*", "Access-Control-Allow-Methods" to "GET, HEAD, OPTIONS",
+ "Access-Control-Allow-Headers" to "Range, Content-Type", "Content-Length" to "0"))
+ if (method != "GET" && method != "HEAD") return status(out, 405, "Method Not Allowed")
+ val path = parts[1].substringBefore('?').trim('/').split('/')
+ val entry = path.takeIf { it.size == 3 && sameToken(it[0]) }?.let { p -> p[2].toIntOrNull()?.let { entries[it] } }
+ if (entry == null || (path[1] == "c") != entry.cover) return status(out, 404, "Not Found")
+ try {
+ if (entry.cover) cover(out, entry, method == "HEAD") else audio(out, entry, headers["range"], method == "HEAD")
+ } catch (e: IOException) {
+ // The device closes a request it no longer needs (a seek): nothing to say.
+ } catch (t: Throwable) {
+ log("serving failed: ${t.javaClass.simpleName}")
+ }
+ }
+ }
+
+ private fun audio(out: OutputStream, e: Entry, rangeHeader: String?, headOnly: Boolean) {
+ val total = e.length
+ val range = ByteRange.parse(rangeHeader, total)
+ if (range is ByteRange.Unsatisfiable) {
+ log("asked $rangeHeader of $total bytes: 416")
+ return write(out, 416, "Range Not Satisfiable", listOf("Content-Range" to "bytes */$total", "Content-Length" to "0"))
+ }
+ val start = (range as? ByteRange.Part)?.start ?: 0L
+ val length = (range as? ByteRange.Part)?.length ?: total
+ val headers = mutableListOf("Content-Type" to e.mime, "Access-Control-Allow-Origin" to "*")
+ if (total >= 0) headers += "Accept-Ranges" to "bytes"
+ if (length >= 0) headers += "Content-Length" to length.toString()
+ if (range is ByteRange.Part) headers += "Content-Range" to "bytes ${range.start}-${range.end}/$total"
+ val code = if (range is ByteRange.Part) 206 else 200
+ log("${if (headOnly) "HEAD" else "GET"} ${rangeHeader ?: "whole"}: $code, ${if (length >= 0) "$length bytes" else "length unknown"}")
+ if (headOnly) return write(out, code, if (code == 206) "Partial Content" else "OK", headers)
+ val src = source()
+ try {
+ src.open(DataSpec.Builder().setUri(e.uri).setPosition(start).setLength(if (length >= 0) length else C.LENGTH_UNSET.toLong()).build())
+ write(out, code, if (code == 206) "Partial Content" else "OK", headers, flush = false)
+ val buf = ByteArray(64 * 1024)
+ var left = if (length >= 0) length else Long.MAX_VALUE
+ while (left > 0) {
+ val n = src.read(buf, 0, minOf(buf.size.toLong(), left).toInt())
+ if (n == C.RESULT_END_OF_INPUT) break
+ out.write(buf, 0, n)
+ left -= n
+ }
+ out.flush()
+ } finally {
+ runCatching { src.close() }
+ }
+ }
+
+ private fun cover(out: OutputStream, e: Entry, headOnly: Boolean) {
+ val bytes = Graph.app.contentResolver.openInputStream(e.uri)?.use { it.readBytes() } ?: return status(out, 404, "Not Found")
+ val headers = listOf("Content-Type" to CastFormats.imageMime(bytes.copyOf(minOf(bytes.size, 16))),
+ "Content-Length" to bytes.size.toString(), "Access-Control-Allow-Origin" to "*")
+ write(out, 200, "OK", headers, flush = headOnly)
+ if (!headOnly) { out.write(bytes); out.flush() }
+ }
+
+ private fun sameToken(t: String): Boolean {
+ val mine = token
+ return mine.isNotEmpty() && MessageDigest.isEqual(mine.toByteArray(), t.toByteArray())
+ }
+
+ /** The request line and headers, up to the blank line (null past 8 KB or at the end of input). */
+ private fun readHead(input: InputStream): String? {
+ val b = StringBuilder()
+ while (b.length < 8192) {
+ val c = input.read()
+ if (c < 0) return null
+ b.append(c.toChar())
+ if (b.endsWith("\r\n\r\n")) return b.substring(0, b.length - 4)
+ }
+ return null
+ }
+
+ private fun status(out: OutputStream, code: Int, reason: String) = write(out, code, reason, listOf("Content-Length" to "0"))
+
+ private fun write(out: OutputStream, code: Int, reason: String, headers: List<Pair<String, String>>, flush: Boolean = true) {
+ val text = buildString {
+ append("HTTP/1.1 $code $reason\r\n")
+ headers.forEach { (k, v) -> append(k).append(": ").append(v).append("\r\n") }
+ append("Connection: close\r\n\r\n")
+ }
+ out.write(text.toByteArray(Charsets.ISO_8859_1))
+ if (flush) out.flush()
+ }
+
+ private fun log(line: String) = app.myspoti.host.android.Logbook.log("cast: $line")
+}
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
index 8066bfaf..0558fb26 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
@@ -11,6 +11,7 @@ import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import com.music.spotui.data.local.LocalTrack
import com.music.spotui.data.preferences.CrossfadePref
+import com.music.spotui.cast.CastPlayback
/**
* Plays the device's own audio files (Local Files). While it plays, the Spotify engine is
@@ -78,12 +79,15 @@ object LocalPlayer {
// Each change of what the player does, one line each, so a song that never starts says why.
override fun onPlaybackStateChanged(state: Int) {
log("state ${stateName(state)} at ${p.currentPosition} ms, item ${p.currentMediaItemIndex + 1}/${p.mediaItemCount}")
+ // Casting: this player keeps the queue only, stopped; the song plays on the device.
+ if (CastPlayback.active && state != Player.STATE_IDLE) { p.stop(); return }
if (state == Player.STATE_ENDED) atEnd(p)
}
override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
log("playWhenReady $playWhenReady (${PLAY_WHEN_READY_REASONS.getOrElse(reason - 1) { "reason $reason" }})")
// A pause (or a lost focus) during a fade stops the fading-out song too.
outgoing?.playWhenReady = playWhenReady
+ if (playWhenReady && CastPlayback.active) { p.pause(); CastPlayback.play() }
}
override fun onIsPlayingChanged(isPlaying: Boolean) {
log("isPlaying $isPlaying at ${p.currentPosition} ms")
@@ -217,6 +221,7 @@ object LocalPlayer {
/** Back to Spotify: stop and forget the local queue. */
fun stop() {
if (!active.value) return
+ CastPlayback.stop(back = false)
endFade()
active.value = false
// A page left muted by an extension's mirror must not stay silent once Spotify plays again.
@@ -261,7 +266,7 @@ object LocalPlayer {
private fun canFade(p: ExoPlayer): Boolean =
CrossfadePref.seconds > 0 && p.repeatMode != Player.REPEAT_MODE_ONE && p.nextMediaItemIndex != C.INDEX_UNSET &&
- p.currentMediaItem != null && p.playWhenReady
+ p.currentMediaItem != null && p.playWhenReady && !CastPlayback.active
private fun beginFade(p: ExoPlayer) {
val item = p.currentMediaItem ?: return
@@ -339,11 +344,12 @@ object LocalPlayer {
/** A player stopped by an error (idle) is prepared again first: a play alone does nothing there. */
fun resume() {
+ if (CastPlayback.active) return CastPlayback.play()
val p = exo ?: return
if (p.playbackState == Player.STATE_IDLE && p.mediaItemCount > 0) { log("resume after an error: preparing again"); p.prepare() }
p.play()
}
- fun pause() { exo?.pause() }
+ fun pause() { if (CastPlayback.active) CastPlayback.pause() else exo?.pause() }
fun next() {
// In the first half of a crossfade the main player is on the next song already, while the
// screens (and the ear) are still on the one going out: a skip there went two songs on.
@@ -362,7 +368,7 @@ object LocalPlayer {
fun previous() {
endFade()
exo?.let {
- if (it.currentPosition > 3000 || !it.hasPreviousMediaItem()) it.seekTo(0)
+ if (position() > 3000 || !it.hasPreviousMediaItem()) seekTo(0)
else { com.music.spotui.extensions.Extensions.skipAsked("backward"); it.seekToPreviousMediaItem() }
}
}
@@ -383,6 +389,7 @@ object LocalPlayer {
exo?.let { p ->
// A seek into the tail of a song is the user's choice: that song then ends as usual.
if (CrossfadeRamp.shouldStart(CrossfadePref.seconds, duration(), ms)) noFadeFor = p.currentMediaItemIndex
+ if (CastPlayback.active) CastPlayback.seek(ms)
p.seekTo(ms)
}
}
@@ -592,13 +599,13 @@ object LocalPlayer {
com.music.spotui.data.offline.OfflineStore.byLocalId(t.id)?.trackId
?: t.uri.takeIf { it.scheme == com.music.spotui.extensions.ExtensionAudio.SCHEME }?.lastPathSegment.orEmpty()
- fun isPlaying() = exo?.isPlaying == true
+ fun isPlaying() = if (CastPlayback.active) CastPlayback.isPlaying() else exo?.isPlaying == true
/** Waiting for audio (a stream that does not keep up, a seek still loading). */
- fun isBuffering() = exo?.playbackState == Player.STATE_BUFFERING
+ fun isBuffering() = if (CastPlayback.active) CastPlayback.isBuffering() else exo?.playbackState == Player.STATE_BUFFERING
/** For the diagnostic (`status`): whether it is to play, and its state (idle, buffering, ready, ended). */
- fun playWhenReady() = exo?.playWhenReady == true
- fun playbackState(): String = exo?.let { stateName(it.playbackState) } ?: "none"
- fun position() = exo?.currentPosition ?: 0L
+ fun playWhenReady() = if (CastPlayback.active) CastPlayback.playWhenReady() else exo?.playWhenReady == true
+ fun playbackState(): String = if (CastPlayback.active) CastPlayback.state() else exo?.let { stateName(it.playbackState) } ?: "none"
+ fun position() = if (CastPlayback.active) CastPlayback.position() else exo?.currentPosition ?: 0L
fun duration() = exo?.duration?.takeIf { it > 0 } ?: current()?.durationMs ?: 0L
fun current(): LocalTrack? = exo?.currentMediaItemIndex?.let { tracks.getOrNull(it) }
@@ -615,6 +622,49 @@ object LocalPlayer {
/** Player.PLAY_WHEN_READY_CHANGE_REASON_*, from 1. */
private val PLAY_WHEN_READY_REASONS = listOf("asked", "audio focus lost", "audio becoming noisy", "remote", "end of item", "suppressed too long")
+ // ── Cast (see CastPlayback): this player keeps the queue, the device plays ──
+
+ /** A Cast device takes the songs: this player stops where it was and the device goes on from there. */
+ internal fun castStarted() {
+ val p = exo ?: return
+ endFade()
+ val at = p.currentPosition
+ val playing = p.playWhenReady
+ p.pause(); p.stop()
+ log("casting from ${at / 1000} s")
+ CastPlayback.follow(current(), at, playing)
+ publish()
+ }
+
+ /** Back from the Cast device: this player goes on at [atMs], playing if the device was. */
+ internal fun castEnded(atMs: Long, playing: Boolean) {
+ val p = exo ?: return
+ if (!active.value || p.mediaItemCount == 0) return
+ log("back from casting at ${atMs / 1000} s")
+ p.seekTo(atMs.coerceAtLeast(0))
+ p.prepare()
+ p.playWhenReady = playing
+ publish()
+ }
+
+ /** The Cast device finished the song: the next one, as this player's own end would. */
+ internal fun castFinished() {
+ val p = exo ?: return
+ when {
+ p.repeatMode == Player.REPEAT_MODE_ONE -> CastPlayback.replay()
+ p.hasNextMediaItem() -> {
+ val before = current()
+ p.seekToNextMediaItem()
+ // A list of one song on repeat: the same song again.
+ if (current() === before) CastPlayback.replay()
+ }
+ else -> atEnd(p)
+ }
+ }
+
+ /** The Cast device's state changed (position, play/pause): the screens follow. */
+ internal fun castChanged() = publish()
+
private var arranging = false
private fun publish() {
@@ -623,7 +673,8 @@ object LocalPlayer {
// A queued song that started (or was skipped past) leaves the queue: it plays from there now.
if (t in queued) playingQueued = t
exo?.currentMediaItemIndex?.let { cur -> for (i in 0..minOf(cur, tracks.lastIndex)) queued -= tracks[i] }
- SongPlayer.onLocalState(t, exo?.playWhenReady == true, position(), duration())
+ if (CastPlayback.active) CastPlayback.follow(t, exo?.currentPosition ?: 0L)
+ SongPlayer.onLocalState(t, playWhenReady(), position(), duration())
SongPlayer.onLocalQueue(t, upcoming(), queuedCount())
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
index 742bb1fc..dda0392f 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
@@ -14,6 +14,7 @@ import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.background
import androidx.compose.material.icons.filled.DragHandle
+import androidx.compose.material.icons.filled.Cast
import androidx.compose.material.icons.filled.Delete
import kotlinx.coroutines.Job
import kotlinx.coroutines.isActive
@@ -104,6 +105,7 @@ private val SheetColor: androidx.compose.ui.graphics.Color get() = tone(0xFF2828
*/
@Composable
fun activeDeviceLabel(): String {
+ com.music.spotui.cast.CastPlayback.device.value?.let { return it.name }
SongPlayer.activeDevice.value?.let { return it.name }
val route = rememberAudioRoute()
return when (route.kind) {
@@ -118,6 +120,7 @@ fun activeDeviceLabel(): String {
/** The icon of the output playing now, matching [activeDeviceLabel]: a phone when this phone plays. */
@Composable
fun activeDeviceIcon(): ImageVector {
+ if (com.music.spotui.cast.CastPlayback.device.value != null) return Icons.Default.Cast
SongPlayer.activeDevice.value?.let { return deviceIcon(it.type) }
return when (rememberAudioRoute().kind) {
AudioRoute.Kind.SPEAKER -> Icons.Default.Smartphone
@@ -224,6 +227,7 @@ fun DevicesSheet(onDismiss: () -> Unit) {
}
Icon(
when {
+ com.music.spotui.cast.CastPlayback.device.value != null -> Icons.Default.Cast
remote != null -> deviceIcon(remote.type)
headphones -> Icons.Default.Headphones
else -> Icons.Default.Smartphone
@@ -257,9 +261,12 @@ fun DevicesSheet(onDismiss: () -> Unit) {
list.filter { !it.isSelf && !it.isActive }.forEach { d ->
DeviceRow(deviceIcon(d.type), d.name, null) { SongPlayer.transferTo(d); onDismiss() }
}
- if (list.none { !it.isSelf } && !headphones && remote == null)
+ if (list.none { !it.isSelf } && !headphones && remote == null && com.music.spotui.cast.CastDiscovery.devices.isEmpty() &&
+ com.music.spotui.cast.CastPlayback.device.value == null)
Text(stringResource(R.string.no_devices), color = AppText.copy(alpha = 0.7f), modifier = Modifier.padding(20.dp))
}
+ // Cast devices, for Myspoti's own songs (Spotify's go through Spotify Connect above).
+ com.music.spotui.cast.CastDeviceRows(onDismiss)
JamSection(onDismiss)
// Bluetooth: pair or pick headphones and speakers in the system settings.
Column(
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index d9160624..11416ef6 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -579,4 +579,9 @@
<string name="aa_home">Home</string>
<string name="aa_library">Library</string>
<string name="aa_downloads">Downloads</string>
+ <string name="cast_device_detail">Google Cast</string>
+ <string name="cast_spotify_via_connect">Spotify songs play on Cast devices through Spotify Connect</string>
+ <string name="cast_connecting">Connecting…</string>
+ <string name="cast_failed">Could not play on %1$s</string>
+ <string name="cast_lost">Lost %1$s: back on this phone</string>
</resources>
diff --git a/base/app/src/test/java/com/music/spotui/cast/CastWireTest.kt b/base/app/src/test/java/com/music/spotui/cast/CastWireTest.kt
new file mode 100644
index 00000000..9fe148d4
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/cast/CastWireTest.kt
@@ -0,0 +1,133 @@
+package com.music.spotui.cast
+
+import org.json.JSONObject
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import java.io.DataInputStream
+import java.io.IOException
+
+class CastWireTest {
+ @Test fun messageEncodesTheProtobufFields() {
+ val bytes = CastMessage("s", "r", "n", "{}").encode()
+ val expected = byteArrayOf(
+ 0x08, 0x00, // protocol_version CASTV2_1_0
+ 0x12, 0x01, 's'.code.toByte(),
+ 0x1a, 0x01, 'r'.code.toByte(),
+ 0x22, 0x01, 'n'.code.toByte(),
+ 0x28, 0x00, // payload_type STRING
+ 0x32, 0x02, '{'.code.toByte(), '}'.code.toByte(),
+ )
+ assertArrayEquals(expected, bytes)
+ }
+
+ @Test fun messageRoundTripsWithLongAndUnicodePayloads() {
+ val m = CastMessage("sender-1", "receiver-0", CastProtocol.NS_MEDIA, "{\"title\":\"Café ".padEnd(300, 'x') + "\"}")
+ assertEquals(m, CastMessage.decode(m.encode()))
+ val b = CastMessage("a", "b", "c", binary = byteArrayOf(1, 2, 3))
+ assertArrayEquals(byteArrayOf(1, 2, 3), CastMessage.decode(b.encode()).binary)
+ }
+
+ @Test fun decodeSkipsUnknownFields() {
+ // field 9 varint (0x48 0x05), field 10 fixed32 (0x55 + 4 bytes), then a known field
+ val bytes = byteArrayOf(0x48, 0x05, 0x55, 1, 2, 3, 4) + CastMessage("x", "y", "z", "p").encode()
+ assertEquals(CastMessage("x", "y", "z", "p"), CastMessage.decode(bytes))
+ }
+
+ @Test(expected = IOException::class) fun decodeRefusesATruncatedField() {
+ val bytes = CastMessage("sender", "receiver", "ns", "payload").encode()
+ CastMessage.decode(bytes.copyOf(bytes.size - 3))
+ }
+
+ @Test fun framesAreLengthPrefixedAndReadOneByOne() {
+ val out = ByteArrayOutputStream()
+ val a = CastMessage("s", "r", CastProtocol.NS_HEARTBEAT, "{\"type\":\"PING\"}")
+ val b = CastMessage("r", "s", CastProtocol.NS_HEARTBEAT, "{\"type\":\"PONG\"}")
+ CastMessage.write(out, a); CastMessage.write(out, b)
+ val raw = out.toByteArray()
+ assertEquals(a.encode().size, (raw[0].toInt() shl 24) or (raw[1].toInt() shl 16) or (raw[2].toInt() shl 8) or raw[3].toInt())
+ val input = DataInputStream(ByteArrayInputStream(raw))
+ assertEquals(a, CastMessage.read(input))
+ assertEquals(b, CastMessage.read(input))
+ }
+
+ @Test(expected = IOException::class) fun oversizedFrameIsRefused() {
+ val n = CastMessage.MAX_SIZE + 1
+ CastMessage.read(DataInputStream(ByteArrayInputStream(byteArrayOf((n ushr 24).toByte(), (n ushr 16).toByte(), (n ushr 8).toByte(), n.toByte()))))
+ }
+
+ @Test fun rangeParsing() {
+ assertEquals(ByteRange.Full, ByteRange.parse(null, 1000))
+ assertEquals(ByteRange.Part(0, 999), ByteRange.parse("bytes=0-", 1000))
+ assertEquals(ByteRange.Part(100, 199), ByteRange.parse("bytes=100-199", 1000))
+ assertEquals(ByteRange.Part(500, 999), ByteRange.parse("bytes=500-5000", 1000))
+ assertEquals(ByteRange.Part(900, 999), ByteRange.parse("bytes=-100", 1000))
+ assertEquals(ByteRange.Part(0, 999), ByteRange.parse("bytes=-5000", 1000))
+ assertEquals(ByteRange.Part(10, 10), ByteRange.parse("Bytes=10-10", 1000))
+ assertEquals(ByteRange.Unsatisfiable, ByteRange.parse("bytes=1000-", 1000))
+ assertEquals(ByteRange.Unsatisfiable, ByteRange.parse("bytes=-0", 1000))
+ // Ignored: several ranges, end before start, garbage, other units, length not known.
+ assertEquals(ByteRange.Full, ByteRange.parse("bytes=0-1,5-9", 1000))
+ assertEquals(ByteRange.Full, ByteRange.parse("bytes=200-100", 1000))
+ assertEquals(ByteRange.Full, ByteRange.parse("bytes=abc-", 1000))
+ assertEquals(ByteRange.Full, ByteRange.parse("items=0-1", 1000))
+ assertEquals(ByteRange.Full, ByteRange.parse("bytes=100-", -1))
+ assertEquals(100L, (ByteRange.parse("bytes=100-199", 1000) as ByteRange.Part).length)
+ }
+
+ @Test fun audioTypeFromFirstBytes() {
+ fun b(vararg x: Int) = ByteArray(x.size) { x[it].toByte() }
+ fun s(t: String) = t.toByteArray(Charsets.ISO_8859_1)
+ assertEquals("audio/flac", CastFormats.mime(s("fLaC\u0000\u0000")))
+ assertEquals("audio/ogg", CastFormats.mime(s("OggS\u0000")))
+ assertEquals("audio/mp4", CastFormats.mime(s("\u0000\u0000\u0000 ftypM4A ")))
+ assertEquals("audio/wav", CastFormats.mime(s("RIFF\u0000\u0000\u0000\u0000WAVEfmt ")))
+ assertEquals("audio/webm", CastFormats.mime(b(0x1A, 0x45, 0xDF, 0xA3, 0x01)))
+ assertEquals("audio/aac", CastFormats.mime(b(0xFF, 0xF1, 0x50, 0x80)))
+ assertEquals("audio/mpeg", CastFormats.mime(b(0xFF, 0xFB, 0x90, 0x64)))
+ assertNull(CastFormats.mime(s("hello")))
+ assertNull(CastFormats.mime(ByteArray(0)))
+ assertEquals("audio/flac", CastFormats.byName("song.FLAC"))
+ assertEquals("audio/mpeg", CastFormats.byName("1234"))
+ }
+
+ @Test fun id3TagSizeIsSyncsafe() {
+ // ID3v2.4, flags 0, size 0x00 0x00 0x02 0x01 = 257 (+10 header)
+ val head = byteArrayOf('I'.code.toByte(), 'D'.code.toByte(), '3'.code.toByte(), 4, 0, 0, 0, 0, 2, 1)
+ assertEquals(267L, CastFormats.id3Size(head))
+ head[5] = 0x10 // footer present
+ assertEquals(277L, CastFormats.id3Size(head))
+ assertEquals(0L, CastFormats.id3Size("fLaC000000".toByteArray()))
+ }
+
+ @Test fun loadAndStatusMessages() {
+ val load = CastProtocol.load(7, "sess", "http://192.168.1.2:4000/t/a/1", "audio/flac", 185_500,
+ "Title", "Artist", "Album", "https://i.example/c.jpg", 12_000, autoplay = true)
+ assertEquals("LOAD", load.getString("type"))
+ assertEquals(12.0, load.getDouble("currentTime"), 0.0)
+ val media = load.getJSONObject("media")
+ assertEquals("audio/flac", media.getString("contentType"))
+ assertEquals(185.5, media.getDouble("duration"), 0.0)
+ assertEquals(3, media.getJSONObject("metadata").getInt("metadataType"))
+ assertEquals("https://i.example/c.jpg", media.getJSONObject("metadata").getJSONArray("images").getJSONObject(0).getString("url"))
+
+ val receiver = CastProtocol.receiver(JSONObject("""{"type":"RECEIVER_STATUS","requestId":1,"status":{"applications":[
+ {"appId":"E8C28D3C","sessionId":"x","transportId":"y"},
+ {"appId":"CC1AD845","sessionId":"abc","transportId":"web-5"}],"volume":{"level":0.25,"muted":false}}}"""))
+ assertEquals(CastProtocol.App("abc", "web-5"), receiver.app)
+ assertEquals(0.25, receiver.volume!!, 0.0)
+ assertNull(CastProtocol.receiver(JSONObject("""{"status":{"applications":[]}}""")).app)
+
+ val st = CastProtocol.media(JSONObject("""{"type":"MEDIA_STATUS","status":[{"mediaSessionId":3,"playerState":"IDLE",
+ "idleReason":"FINISHED","currentTime":61.25,"media":{"contentId":"u"}}],"requestId":0}"""))!!
+ assertEquals(3, st.mediaSessionId)
+ assertEquals("FINISHED", st.idleReason)
+ assertEquals(61_250L, st.positionMs)
+ assertNull(CastProtocol.media(JSONObject("""{"type":"MEDIA_STATUS","status":[]}""")))
+ assertTrue(CastProtocol.seek(9, 3, 1500).getDouble("currentTime") == 1.5)
+ }
+}