From 2b882236d4ff4029543470b23b729b7c14bad53f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 20:24:57 +0000 Subject: [PATCH 01/14] Add sleep timer, per-speaker sound and known-speaker notes - Sleep timer on Now Playing (15-90 min) with a 30 s fade-out, plus a 1 s fade-in at the start of every cast. One MasterGain stage sits ahead of the audio bus, so it applies to every protocol and source. - Per-speaker bass/treble/level (-12..+12 dB) and a loudness leveler, applied per sink without touching the shared frames, and saved per speaker. Per-speaker sync delay is now saved and restored too. - DeviceQuirks: connection doctor notes for WiiM over DLNA and shairport-sync over AirPlay 2, and the speaker's manufacturer/model in the copied report. DLNA discovery now reads manufacturer and modelName. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01XZTMETapPkNvc9xdPLcfZu --- CHANGELOG.md | 12 ++ .../com/aria/ariacast/AudioCastService.kt | 112 ++++++++++- .../com/aria/ariacast/DiscoveryManager.kt | 2 + .../main/java/com/aria/ariacast/dlna/Dlna.kt | 16 +- .../com/aria/ariacast/pipeline/MasterGain.kt | 91 +++++++++ .../com/aria/ariacast/pipeline/SpeakerDsp.kt | 176 ++++++++++++++++++ .../com/aria/ariacast/quirks/DeviceQuirks.kt | 65 +++++++ .../aria/ariacast/ui/doctor/DoctorScreen.kt | 14 +- .../ui/nowplaying/NowPlayingScreen.kt | 88 +++++++++ app/src/main/res/values-it/strings.xml | 16 ++ app/src/main/res/values/strings.xml | 16 ++ .../java/com/aria/ariacast/dlna/DlnaTest.kt | 8 + .../aria/ariacast/pipeline/MasterGainTest.kt | 101 ++++++++++ .../aria/ariacast/pipeline/SpeakerDspTest.kt | 116 ++++++++++++ .../aria/ariacast/quirks/DeviceQuirksTest.kt | 49 +++++ docs/ROADMAP-2.0.md | 6 +- 16 files changed, 873 insertions(+), 15 deletions(-) create mode 100644 app/src/main/java/com/aria/ariacast/pipeline/MasterGain.kt create mode 100644 app/src/main/java/com/aria/ariacast/pipeline/SpeakerDsp.kt create mode 100644 app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt create mode 100644 app/src/test/java/com/aria/ariacast/pipeline/MasterGainTest.kt create mode 100644 app/src/test/java/com/aria/ariacast/pipeline/SpeakerDspTest.kt create mode 100644 app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 571e7566..77ba0a2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,18 @@ casting, a new interface, and AriaCompanion 2. recognizes apps that block audio capture. - **Onboarding**, Material You colors on Android 12+, home-screen **widget**. +### Sound and timing +- **Sleep timer** on Now Playing (15 to 90 minutes). The sound fades out over the last 30 + seconds, then the cast stops. Every cast also starts with a one-second fade-in. +- **Sound per speaker**: bass, treble and level (-12 to +12 dB) and an optional loudness + leveler, set for each speaker while casting and remembered for next time. Works with + AriaCast, AirPlay, Cast, DLNA, Snapcast and VBAN speakers. +- **Rooms stay lined up**: each speaker's sync delay is now saved and applied the next time + that speaker joins a cast. +- **Known speaker behavior**: the connection doctor now shows notes for brands and models with + documented quirks (WiiM over DLNA, shairport-sync over AirPlay 2) and adds the speaker's + manufacturer and model to the copied report. DLNA speakers now report both. + ### Built in, previously plugins - Music Assistant player picker, connection doctor, visualizer, add speaker by address. - **Plugin API v2**: plugins describe their UI with `ui.render()`; the v1 view methods diff --git a/app/src/main/java/com/aria/ariacast/AudioCastService.kt b/app/src/main/java/com/aria/ariacast/AudioCastService.kt index 6ca357fe..b820bfa4 100644 --- a/app/src/main/java/com/aria/ariacast/AudioCastService.kt +++ b/app/src/main/java/com/aria/ariacast/AudioCastService.kt @@ -59,6 +59,7 @@ import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.update import kotlinx.serialization.json.Json import org.json.JSONArray import org.json.JSONObject @@ -84,6 +85,8 @@ import com.aria.ariacast.pipeline.FgsTypes import com.aria.ariacast.pipeline.MicrophoneSource import com.aria.ariacast.pipeline.ProjectionCaptureSource import com.aria.ariacast.pipeline.SourceKind +import com.aria.ariacast.pipeline.SpeakerDsp +import com.aria.ariacast.pipeline.SpeakerSound import com.aria.ariacast.receiver.ReceiverHub import com.aria.ariacast.sendspin.SendspinHub import com.aria.ariacast.pipeline.PcmFormat @@ -275,6 +278,42 @@ class AudioCastService : Service() { private var mutedForSource = false + /** Fade-in at the start of a cast and the sleep timer's fade-out, ahead of every sink. */ + private val masterGain = com.aria.ariacast.pipeline.MasterGain() + private var sleepTimerJob: Job? = null + + private val _sleepTimerRemainingMs = MutableStateFlow(null) + /** Time left on the sleep timer, or null when none is set. */ + val sleepTimerRemainingMs: StateFlow = _sleepTimerRemainingMs.asStateFlow() + + /** Stops the cast after [minutes], fading the sound out over the last 30 seconds. */ + fun setSleepTimer(minutes: Int) { + if (minutes <= 0) { cancelSleepTimer(); return } + if (_state.value != CastState.CASTING && _state.value != CastState.CONNECTING) return + sleepTimerJob?.cancel() + masterGain.startTimer(minutes * 60_000L) + _sleepTimerRemainingMs.value = masterGain.remainingMs() + sleepTimerJob = scope.launch { + while (isActive) { + val left = masterGain.remainingMs() ?: break + _sleepTimerRemainingMs.value = left + if (left == 0L) { + PacketLogger.log(PacketDirection.IN, PacketType.CONTROL, "Sleep timer ended: stopping the cast") + withContext(Dispatchers.Main) { stopCasting() } + break + } + delay(minOf(left, 1_000L)) + } + } + } + + fun cancelSleepTimer() { + sleepTimerJob?.cancel() + sleepTimerJob = null + masterGain.cancelTimer() + _sleepTimerRemainingMs.value = null + } + private val _metadata = MutableStateFlow(null) val metadata: StateFlow = _metadata.asStateFlow() @@ -524,7 +563,7 @@ class AudioCastService : Service() { ) { sessionJob?.cancel() - _activeDestinations.value = destinations + _activeDestinations.value = destinations.map(::withSavedDelay) _state.value = CastState.CONNECTING sessionJob = SupervisorJob() val sessionScope = CoroutineScope(Dispatchers.IO + sessionJob!!) @@ -568,6 +607,8 @@ class AudioCastService : Service() { return } currentSource = source + cancelSleepTimer() + masterGain.beginSession() _sourceKind.value = source.kind if (source.muteLocalPlayback) { // Playback capture happens before the volume is applied, so muting the phone @@ -608,6 +649,7 @@ class AudioCastService : Service() { else "Source is producing a real audio signal" ) } + masterGain.process(frame) _audioBufferFlow.emit(frame) } PacketLogger.log(PacketDirection.IN, PacketType.AUDIO, "Source ${source.kind.id} ended") @@ -664,8 +706,9 @@ class AudioCastService : Service() { startDlnaHttpServer(); startArtworkServer() } if ((dest.platform == "AirPlay" || dest.platform == "AirPlay2") && dacpServer == null) startDacpServer() - _activeDestinations.value = _activeDestinations.value + dest - launchDestination(scope, dest, withVideo = false) + val withDelay = withSavedDelay(dest) + _activeDestinations.value = _activeDestinations.value + withDelay + launchDestination(scope, withDelay, withVideo = false) PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Added ${dest.name} to the cast") _metadata.value?.let { sendMetadata(it) } updateNotification() @@ -771,7 +814,9 @@ class AudioCastService : Service() { } output.write(header.array()) - audioBufferFlow.collect { buffer -> + val dsp = dspFor(clientSocket.inetAddress?.hostAddress ?: "") + audioBufferFlow.collect { raw -> + val buffer = dsp.process(raw) try { output.write(buffer) output.flush() @@ -971,7 +1016,8 @@ class AudioCastService : Service() { try { val reason = coroutineScope { val feeder = launch { - audioBufferFlow.collect { chunk -> streamer.writePcm(resampler.resample(chunk)) } + val dsp = dspFor(dest.host) + audioBufferFlow.collect { chunk -> streamer.writePcm(resampler.resample(dsp.process(chunk))) } } // "Streaming" alone doesn't say whether the receiver is playing: log what it // has asked for (timing requests, resends) once it has had time to start. @@ -1231,7 +1277,8 @@ class AudioCastService : Service() { updateNotification() PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "VBAN stream '$streamName' to ${dest.name} (${dest.host}:$port), ${PcmFormat.SAMPLE_RATE} Hz stereo 16-bit PCM") - audioBufferFlow.collect { streamer.send(it) } + val dsp = dspFor(dest.host) + audioBufferFlow.collect { streamer.send(dsp.process(it)) } } } catch (e: CancellationException) { throw e @@ -1375,8 +1422,9 @@ class AudioCastService : Service() { // 5. Stream audio try { - audioBufferFlow.collect { buffer -> - audioOut.write(buffer) + val dsp = dspFor(dest.host) + audioBufferFlow.collect { raw -> + audioOut.write(dsp.process(raw)) } } finally { try { audioSocket.close() } catch (_: Exception) {} @@ -1443,8 +1491,9 @@ class AudioCastService : Service() { val delayQueue = java.util.LinkedList() - audioBufferFlow.collect { buffer: ByteArray -> - delayQueue.add(buffer) + val dsp = dspFor(dest.host) + audioBufferFlow.collect { raw: ByteArray -> + delayQueue.add(dsp.process(raw)) val currentDelay = _activeDestinations.value.find { it.host == dest.host }?.delayMs ?: 0 val requiredFrames = currentDelay / 20 @@ -1670,7 +1719,49 @@ class AudioCastService : Service() { } catch (_: Exception) {} } + private val _speakerSounds = MutableStateFlow>(emptyMap()) + /** Sound settings per speaker host, saved across sessions. */ + val speakerSounds: StateFlow> = _speakerSounds.asStateFlow() + + private fun speakerKey(host: String, field: String) = "spk.$host.$field" + + /** The saved sound for [host]; read from storage once, then served from memory. */ + fun soundFor(host: String): SpeakerSound { + _speakerSounds.value[host]?.let { return it } + val loaded = SpeakerSound( + bassDb = sharedPreferences.getInt(speakerKey(host, "bass"), 0), + trebleDb = sharedPreferences.getInt(speakerKey(host, "treble"), 0), + trimDb = sharedPreferences.getInt(speakerKey(host, "trim"), 0), + leveling = sharedPreferences.getBoolean(speakerKey(host, "leveling"), false), + ).clamped() + _speakerSounds.update { it + (host to loaded) } + return loaded + } + + /** Applies the sound to the running stream at once and remembers it for next time. */ + fun setSpeakerSound(host: String, sound: SpeakerSound) { + val s = sound.clamped() + _speakerSounds.update { it + (host to s) } + sharedPreferences.edit() + .putInt(speakerKey(host, "bass"), s.bassDb) + .putInt(speakerKey(host, "treble"), s.trebleDb) + .putInt(speakerKey(host, "trim"), s.trimDb) + .putBoolean(speakerKey(host, "leveling"), s.leveling) + .apply() + } + + /** One processor per consumer of the audio bus; it follows this speaker's live settings. */ + private fun dspFor(host: String) = SpeakerDsp { soundFor(host) } + + /** Gives [dest] the delay saved for its host, unless one was already set. */ + private fun withSavedDelay(dest: CastDestination): CastDestination { + if (dest.delayMs != 0) return dest + val saved = sharedPreferences.getInt(speakerKey(dest.host, "delay"), 0) + return if (saved != 0) dest.copy(delayMs = saved) else dest + } + fun setDelay(host: String, delayMs: Int) { + sharedPreferences.edit().putInt(speakerKey(host, "delay"), delayMs).apply() val current = _activeDestinations.value.toMutableList() val index = current.indexOfFirst { it.host == host } if (index != -1) { @@ -1990,6 +2081,7 @@ class AudioCastService : Service() { } private fun cleanupSession() { + cancelSleepTimer() val destinations = _activeDestinations.value.toList() val teardownJobs = stopRemoteSessions(destinations) releaseWakeLock() diff --git a/app/src/main/java/com/aria/ariacast/DiscoveryManager.kt b/app/src/main/java/com/aria/ariacast/DiscoveryManager.kt index 6e326484..d7083748 100644 --- a/app/src/main/java/com/aria/ariacast/DiscoveryManager.kt +++ b/app/src/main/java/com/aria/ariacast/DiscoveryManager.kt @@ -533,6 +533,8 @@ class DiscoveryManager(private val context: Context) { val extraParts = mutableListOf(ExtraFields.encode("av_control", avTransportUrl)) if (renderingControlUrl != null) extraParts.add(ExtraFields.encode("rc_control", renderingControlUrl)) + desc.manufacturer?.let { extraParts.add(ExtraFields.encode("manufacturer", it)) } + desc.modelName?.let { extraParts.add(ExtraFields.encode("model", it)) } val server = Server( name = desc.friendlyName, diff --git a/app/src/main/java/com/aria/ariacast/dlna/Dlna.kt b/app/src/main/java/com/aria/ariacast/dlna/Dlna.kt index 6bc0b851..e2f8dd35 100644 --- a/app/src/main/java/com/aria/ariacast/dlna/Dlna.kt +++ b/app/src/main/java/com/aria/ariacast/dlna/Dlna.kt @@ -8,7 +8,15 @@ object Dlna { private const val CM = "urn:schemas-upnp-org:service:ConnectionManager:1" /** What discovery needs from a remote device description: who it is and where to control it. */ - data class RemoteRenderer(val udn: String?, val friendlyName: String, val avControl: String, val rcControl: String?) + data class RemoteRenderer( + val udn: String?, + val friendlyName: String, + val avControl: String, + val rcControl: String?, + /** `manufacturer` and `modelName` of the root device; they tell brands apart (see DeviceQuirks). */ + val manufacturer: String? = null, + val modelName: String? = null, + ) /** * Parses a UPnP device description fetched from an SSDP LOCATION. Returns null unless the @@ -23,7 +31,11 @@ object Dlna { fun control(kind: String) = services.firstOrNull { tag("serviceType", it)?.contains(":service:$kind:") == true } ?.let { tag("controlURL", it) }?.takeIf { it.isNotEmpty() } val av = control("AVTransport") ?: return null - return RemoteRenderer(tag("UDN", xml)?.takeIf { it.isNotEmpty() }, name, av, control("RenderingControl")) + return RemoteRenderer( + tag("UDN", xml)?.takeIf { it.isNotEmpty() }, name, av, control("RenderingControl"), + manufacturer = tag("manufacturer", xml)?.takeIf { it.isNotEmpty() }, + modelName = tag("modelName", xml)?.takeIf { it.isNotEmpty() }, + ) } fun serviceType(service: String) = when (service) { diff --git a/app/src/main/java/com/aria/ariacast/pipeline/MasterGain.kt b/app/src/main/java/com/aria/ariacast/pipeline/MasterGain.kt new file mode 100644 index 00000000..88683505 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/pipeline/MasterGain.kt @@ -0,0 +1,91 @@ +package com.aria.ariacast.pipeline + +/** + * One gain stage on the audio bus, ahead of every sink: a short fade-in when a cast starts and + * the sleep timer's fade-out. Because it sits before the bus, it works the same for every + * protocol and every source. + * + * The gain moves in a straight line from its previous value to the new one across each frame, + * so there are no steps (clicks) at frame edges. Frames are 16-bit little-endian stereo PCM. + * [process] is called from the single audio-source coroutine; the timer controls may be + * called from any thread. + */ +class MasterGain( + private val clock: () -> Long = System::currentTimeMillis, + private val fadeInMs: Long = FADE_IN_MS, + private val fadeOutMs: Long = FADE_OUT_MS, +) { + @Volatile private var fadeInStartedAt = NONE + @Volatile private var timerEndsAt = NONE + @Volatile private var timerFadeMs = fadeOutMs + private var lastGain = 1f + + /** Call when a cast starts: the next frames fade in from silence. */ + fun beginSession() { + fadeInStartedAt = clock() + lastGain = 0f + } + + /** Stops the audio after [durationMs], fading out over the last part of it. */ + fun startTimer(durationMs: Long) { + require(durationMs > 0) { "durationMs must be positive" } + // A short timer fades over at most half of its length, so it still plays for a while. + timerFadeMs = minOf(fadeOutMs, durationMs / 2) + timerEndsAt = clock() + durationMs + } + + fun cancelTimer() { + timerEndsAt = NONE + } + + /** Milliseconds until the timer ends, or null when no timer runs. */ + fun remainingMs(): Long? = timerEndsAt.takeIf { it != NONE }?.let { (it - clock()).coerceAtLeast(0) } + + /** True once the timer has run out. */ + fun timerExpired(): Boolean = remainingMs() == 0L + + /** The gain wanted right now, from 0 to 1. */ + fun targetGain(): Float { + var g = 1f + val inStart = fadeInStartedAt + if (inStart != NONE && fadeInMs > 0) { + g = minOf(g, ((clock() - inStart).toFloat() / fadeInMs).coerceIn(0f, 1f)) + } + remainingMs()?.let { left -> + if (timerFadeMs > 0) g = minOf(g, (left.toFloat() / timerFadeMs).coerceIn(0f, 1f)) + else if (left == 0L) g = 0f + } + return g + } + + /** Applies the gain to [frame] in place. */ + fun process(frame: ByteArray) { + val target = targetGain() + val from = lastGain + lastGain = target + if (from == 1f && target == 1f) return // the usual case: nothing to do + applyRamp(frame, from, target) + } + + companion object { + const val FADE_IN_MS = 1_000L + const val FADE_OUT_MS = 30_000L + private const val NONE = Long.MIN_VALUE + + /** Scales [pcm] by a gain that moves linearly from [from] to [to] across the frame. */ + fun applyRamp(pcm: ByteArray, from: Float, to: Float) { + val frames = pcm.size / PcmFormat.BYTES_PER_FRAME + if (frames == 0) return + for (i in 0 until frames) { + val g = from + (to - from) * (i + 1) / frames + for (ch in 0 until PcmFormat.CHANNELS) { + val at = i * PcmFormat.BYTES_PER_FRAME + ch * PcmFormat.BYTES_PER_SAMPLE + val sample = ((pcm[at].toInt() and 0xFF) or (pcm[at + 1].toInt() shl 8)).toShort().toInt() + val scaled = (sample * g).toInt().coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt()) + pcm[at] = scaled.toByte() + pcm[at + 1] = (scaled shr 8).toByte() + } + } + } + } +} diff --git a/app/src/main/java/com/aria/ariacast/pipeline/SpeakerDsp.kt b/app/src/main/java/com/aria/ariacast/pipeline/SpeakerDsp.kt new file mode 100644 index 00000000..0eb2f9c3 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/pipeline/SpeakerDsp.kt @@ -0,0 +1,176 @@ +package com.aria.ariacast.pipeline + +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.exp +import kotlin.math.log10 +import kotlin.math.pow +import kotlin.math.sign +import kotlin.math.sin +import kotlin.math.sqrt +import kotlin.math.tanh + +/** How one speaker should sound. All-zero and no leveling means "leave the audio alone". */ +data class SpeakerSound( + val bassDb: Int = 0, + val trebleDb: Int = 0, + /** Overall level of this speaker, to even out rooms that play louder than others. */ + val trimDb: Int = 0, + /** Evens out quiet and loud passages (night mode). */ + val leveling: Boolean = false, +) { + val isFlat: Boolean get() = bassDb == 0 && trebleDb == 0 && trimDb == 0 && !leveling + + fun clamped() = SpeakerSound(bassDb.coerceIn(RANGE), trebleDb.coerceIn(RANGE), trimDb.coerceIn(RANGE), leveling) + + companion object { + val RANGE = -12..12 + } +} + +/** + * Per-speaker sound shaping on 48 kHz stereo 16-bit PCM frames: a bass shelf, a treble shelf, + * a level trim and an optional leveler (compressor with make-up gain). A soft clip at the end + * keeps boosts from wrapping around. + * + * Frames on the audio bus are shared by every sink, so [process] never edits its input: it + * returns the same array when the speaker is flat and a new one otherwise. One instance per + * consumer; not thread-safe. [soundProvider] is read on every frame, so changes apply live. + */ +class SpeakerDsp(private val soundProvider: () -> SpeakerSound) { + private var applied: SpeakerSound? = null + private val bass = arrayOf(Biquad(), Biquad()) + private val treble = arrayOf(Biquad(), Biquad()) + private var trimGain = 1f + private var leveling = false + private var envelope = 0f + + fun process(frame: ByteArray): ByteArray { + val sound = soundProvider() + if (sound.isFlat) { + if (applied?.isFlat == false) resetState() + applied = sound + return frame + } + if (sound != applied) configure(sound) + + val out = ByteArray(frame.size) + val frames = frame.size / PcmFormat.BYTES_PER_FRAME + val shape = sound.bassDb != 0 || sound.trebleDb != 0 + for (i in 0 until frames) { + val base = i * PcmFormat.BYTES_PER_FRAME + var l = readSample(frame, base) / FULL_SCALE + var r = readSample(frame, base + 2) / FULL_SCALE + if (shape) { + l = treble[0].run(bass[0].run(l)); r = treble[1].run(bass[1].run(r)) + } + var gain = trimGain + if (leveling) gain *= levelerGain(maxOf(abs(l), abs(r))) + writeSample(out, base, softClip(l * gain)) + writeSample(out, base + 2, softClip(r * gain)) + } + return out + } + + private fun configure(sound: SpeakerSound) { + val first = applied == null + applied = sound + trimGain = dbToLinear(sound.trimDb.toFloat()) + if (!leveling && sound.leveling) envelope = 0f + leveling = sound.leveling + for (ch in 0..1) { + bass[ch].lowShelf(BASS_HZ, sound.bassDb.toDouble()) + treble[ch].highShelf(TREBLE_HZ, sound.trebleDb.toDouble()) + if (first) { bass[ch].clear(); treble[ch].clear() } + } + } + + private fun resetState() { + bass.forEach { it.clear() } + treble.forEach { it.clear() } + envelope = 0f + } + + /** Compressor gain for the next sample; the envelope follows the louder channel. */ + private fun levelerGain(level: Float): Float { + val coeff = if (level > envelope) ATTACK else RELEASE + envelope += (level - envelope) * coeff + val envDb = 20f * log10(envelope.coerceAtLeast(1e-5f)) + val over = envDb - LEVELER_THRESHOLD_DB + val reduction = if (over > 0f) over * (1f - 1f / LEVELER_RATIO) else 0f + return dbToLinear(LEVELER_MAKEUP_DB - reduction) + } + + private class Biquad { + private var b0 = 1.0; private var b1 = 0.0; private var b2 = 0.0 + private var a1 = 0.0; private var a2 = 0.0 + private var x1 = 0.0; private var x2 = 0.0; private var y1 = 0.0; private var y2 = 0.0 + + fun clear() { x1 = 0.0; x2 = 0.0; y1 = 0.0; y2 = 0.0 } + + fun run(x: Float): Float { + val y = b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2 + x2 = x1; x1 = x.toDouble(); y2 = y1; y1 = y + return y.toFloat() + } + + /** RBJ audio-EQ-cookbook shelves with slope 1. */ + fun lowShelf(freq: Double, gainDb: Double) = shelf(freq, gainDb, low = true) + fun highShelf(freq: Double, gainDb: Double) = shelf(freq, gainDb, low = false) + + private fun shelf(freq: Double, gainDb: Double, low: Boolean) { + if (gainDb == 0.0) { b0 = 1.0; b1 = 0.0; b2 = 0.0; a1 = 0.0; a2 = 0.0; return } + val a = 10.0.pow(gainDb / 40.0) + val w0 = 2 * PI * freq / PcmFormat.SAMPLE_RATE + val cosW = cos(w0) + val alpha = sin(w0) / 2 * sqrt(2.0) + val k = 2 * sqrt(a) * alpha + val n0: Double; val n1: Double; val n2: Double; val d0: Double; val d1: Double; val d2: Double + if (low) { + n0 = a * ((a + 1) - (a - 1) * cosW + k) + n1 = 2 * a * ((a - 1) - (a + 1) * cosW) + n2 = a * ((a + 1) - (a - 1) * cosW - k) + d0 = (a + 1) + (a - 1) * cosW + k + d1 = -2 * ((a - 1) + (a + 1) * cosW) + d2 = (a + 1) + (a - 1) * cosW - k + } else { + n0 = a * ((a + 1) + (a - 1) * cosW + k) + n1 = -2 * a * ((a - 1) + (a + 1) * cosW) + n2 = a * ((a + 1) + (a - 1) * cosW - k) + d0 = (a + 1) - (a - 1) * cosW + k + d1 = 2 * ((a - 1) - (a + 1) * cosW) + d2 = (a + 1) - (a - 1) * cosW - k + } + b0 = n0 / d0; b1 = n1 / d0; b2 = n2 / d0; a1 = d1 / d0; a2 = d2 / d0 + } + } + + companion object { + const val BASS_HZ = 150.0 + const val TREBLE_HZ = 5_000.0 + private const val FULL_SCALE = 32768f + private const val LEVELER_THRESHOLD_DB = -24f + private const val LEVELER_RATIO = 3f + private const val LEVELER_MAKEUP_DB = 6f + private val ATTACK = 1f - exp(-1f / (0.005f * PcmFormat.SAMPLE_RATE)) + private val RELEASE = 1f - exp(-1f / (0.250f * PcmFormat.SAMPLE_RATE)) + + fun dbToLinear(db: Float): Float = 10f.pow(db / 20f) + + /** Transparent up to 0.8 of full scale, then a smooth curve that never exceeds 1.0. */ + fun softClip(x: Float): Float { + val a = abs(x) + return if (a <= 0.8f) x else sign(x) * (0.8f + 0.2f * tanh((a - 0.8f) / 0.2f)) + } + + private fun readSample(pcm: ByteArray, at: Int): Float = + ((pcm[at].toInt() and 0xFF) or (pcm[at + 1].toInt() shl 8)).toShort().toFloat() + + private fun writeSample(pcm: ByteArray, at: Int, value: Float) { + val s = (value * FULL_SCALE).toInt().coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt()) + pcm[at] = s.toByte() + pcm[at + 1] = (s shr 8).toByte() + } + } +} diff --git a/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt b/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt new file mode 100644 index 00000000..5a998432 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt @@ -0,0 +1,65 @@ +package com.aria.ariacast.quirks + +import androidx.annotation.StringRes +import com.aria.ariacast.ExtraFields +import com.aria.ariacast.R + +/** + * What discovery learned about a speaker. [model] and [manufacturer] come from the device itself + * (mDNS TXT records, the UPnP description), so they are untrusted text: only ever compared, + * and shown as text. + */ +data class DeviceIdentity( + val platform: String?, + val name: String, + val model: String? = null, + val manufacturer: String? = null, +) { + companion object { + /** Reads the fields discovery packs into a destination's `extra` string. */ + fun of(platform: String?, name: String, extra: String?): DeviceIdentity { + val fields = ExtraFields.parse(extra) + return DeviceIdentity(platform, name, fields["model"], fields["manufacturer"]) + } + } + + /** One line to paste in an issue so a speaker's behavior can be told apart from a bug. */ + fun reportLine(): String = listOfNotNull( + platform?.let { "protocol=$it" }, + manufacturer?.let { "manufacturer=$it" }, + model?.let { "model=$it" }, + "name=$name", + ).joinToString(", ") +} + +/** + * A known behavior of one family of speakers, with a plain-language note for the connection + * doctor. Entries are added only for behavior that is documented in an issue or in the code + * that works around it; "report my speaker" in the doctor exists to find the next ones. + */ +data class Quirk( + val id: String, + @param:StringRes val note: Int, + val appliesTo: (DeviceIdentity) -> Boolean, +) + +object DeviceQuirks { + private fun DeviceIdentity.mentions(vararg needles: String): Boolean { + val haystack = listOfNotNull(name, model, manufacturer).joinToString(" ").lowercase() + return needles.any { haystack.contains(it) } + } + + val ALL: List = listOf( + // Issue #50: SetAVTransportURI leaves a WiiM paused at 0:00. AriaCast now sends Play + // after every track change for all DLNA renderers; the note explains it if it recurs. + Quirk("wiim-dlna-restart", R.string.quirk_wiim_dlna) { it.platform == "DLNA" && it.mentions("wiim", "linkplay") }, + // AirPlay 2 receivers built on shairport-sync + nqptp only accept PTP timing, which + // Android can't offer without root (see PtpMaster): AriaCast uses NTP timing or AirPlay 1. + Quirk("shairport-airplay2-ptp", R.string.quirk_shairport_ptp) { + it.platform == "AirPlay2" && it.mentions("shairport") + }, + ) + + /** Every known behavior that applies to [device]. */ + fun matching(device: DeviceIdentity): List = ALL.filter { it.appliesTo(device) } +} diff --git a/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt b/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt index 81dc3ab8..22abd394 100644 --- a/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt +++ b/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt @@ -13,6 +13,9 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Info +import com.aria.ariacast.quirks.DeviceIdentity +import com.aria.ariacast.quirks.DeviceQuirks import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.Error @@ -67,7 +70,7 @@ import kotlinx.coroutines.withContext import java.net.InetSocketAddress import java.net.Socket -enum class CheckStatus { OK, WARN, FAIL, PENDING } +enum class CheckStatus { OK, WARN, FAIL, PENDING, INFO } data class Check(val title: String, val status: CheckStatus, val detail: String, val fix: Pair Unit>? = null) @@ -139,6 +142,13 @@ fun DoctorScreen(controller: AppController, onBack: () -> Unit) { context.getString(if (ok) R.string.doctor_reach_ok else R.string.doctor_reach_fail, d.host, d.port)) } + // Known behavior of this brand or model, so a quirk isn't mistaken for a bug. + s.activeDestinations.value.forEach { d -> + DeviceQuirks.matching(DeviceIdentity.of(d.platform, d.name, d.extra)).forEach { q -> + list += Check(context.getString(R.string.doctor_known_behavior, d.name), CheckStatus.INFO, context.getString(q.note)) + } + } + // Data flowing? val stats = s.stats.value val flowing = stats.sentFrames > lastSent && lastSent >= 0 @@ -179,6 +189,7 @@ fun DoctorScreen(controller: AppController, onBack: () -> Unit) { CheckStatus.WARN -> Icons.Filled.Warning to StatusColors.Warning CheckStatus.FAIL -> Icons.Filled.Error to MaterialTheme.colorScheme.error CheckStatus.PENDING -> Icons.Filled.RadioButtonUnchecked to MaterialTheme.colorScheme.outline + CheckStatus.INFO -> Icons.Filled.Info to MaterialTheme.colorScheme.primary } ListRow( headline = c.title, @@ -195,6 +206,7 @@ fun DoctorScreen(controller: AppController, onBack: () -> Unit) { val report = buildString { appendLine("AriaCast connection report") checks.forEach { appendLine("[${it.status}] ${it.title}: ${it.detail}") } + service?.activeDestinations?.value?.forEach { appendLine("Speaker: " + DeviceIdentity.of(it.platform, it.name, it.extra).reportLine()) } service?.let { appendLine(it.getStatsJson()) } } context.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("AriaCast report", report)) diff --git a/app/src/main/java/com/aria/ariacast/ui/nowplaying/NowPlayingScreen.kt b/app/src/main/java/com/aria/ariacast/ui/nowplaying/NowPlayingScreen.kt index 3cf9a992..7c7ca320 100644 --- a/app/src/main/java/com/aria/ariacast/ui/nowplaying/NowPlayingScreen.kt +++ b/app/src/main/java/com/aria/ariacast/ui/nowplaying/NowPlayingScreen.kt @@ -14,10 +14,13 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material.icons.filled.Pause import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.SkipNext @@ -61,7 +64,10 @@ import com.aria.ariacast.TrackMetadata import com.aria.ariacast.lyrics.LrcLib import com.aria.ariacast.lyrics.Lyrics import com.aria.ariacast.ui.AppController +import com.aria.ariacast.pipeline.SpeakerSound +import com.aria.ariacast.sendspin.SendspinHub import com.aria.ariacast.ui.ListBlock +import com.aria.ariacast.ui.ListRow import com.aria.ariacast.ui.ListGroup import com.aria.ariacast.ui.SwitchListRow import com.aria.ariacast.ui.theme.StatTextStyle @@ -182,6 +188,8 @@ fun NowPlayingScreen(controller: AppController, onClose: () -> Unit) { s?.let { Visualizer(it, Modifier.fillMaxWidth().height(40.dp), color = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)) } s?.let { SpeakersInCast(controller, it) } s?.let { MultiroomSync(it) } + s?.let { SpeakerSounds(it) } + s?.let { SleepTimer(it) } LyricsSection(m, livePosition) Spacer(Modifier.height(24.dp)) } @@ -216,6 +224,86 @@ private fun MultiroomSync(service: AudioCastService) { } } +/** Bass, treble, level and leveling for each speaker, saved per speaker. */ +@Composable +private fun SpeakerSounds(service: AudioCastService) { + val destinations by service.activeDestinations.collectAsState() + val sounds by service.speakerSounds.collectAsState() + val state by service.state.collectAsState() + // A Sendspin server pulls the stream itself, so there is nothing of ours to shape. + val speakers = destinations.filter { it.platform != SendspinHub.PLATFORM } + if (state != CastState.CASTING || speakers.isEmpty()) return + ListGroup(title = stringResource(R.string.speaker_sound)) { + speakers.forEach { dest -> + val sound = sounds[dest.host] ?: service.soundFor(dest.host) + var open by remember(dest.host) { mutableStateOf(false) } + val flat = stringResource(R.string.speaker_sound_flat) + ListRow( + headline = dest.name, + supporting = if (sound.isFlat) flat else soundSummary(sound), + trailing = { Icon(if (open) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown, null) }, + onClick = { open = !open }, + ) + if (open) { + ListBlock { + DbSlider(stringResource(R.string.speaker_sound_bass), sound.bassDb) { service.setSpeakerSound(dest.host, sound.copy(bassDb = it)) } + DbSlider(stringResource(R.string.speaker_sound_treble), sound.trebleDb) { service.setSpeakerSound(dest.host, sound.copy(trebleDb = it)) } + DbSlider(stringResource(R.string.speaker_sound_level), sound.trimDb) { service.setSpeakerSound(dest.host, sound.copy(trimDb = it)) } + } + SwitchListRow(stringResource(R.string.speaker_sound_leveling), stringResource(R.string.speaker_sound_leveling_desc), sound.leveling, + { service.setSpeakerSound(dest.host, sound.copy(leveling = it)) }) + if (!sound.isFlat) { + ListRow(headline = stringResource(R.string.speaker_sound_reset), onClick = { service.setSpeakerSound(dest.host, SpeakerSound()) }) + } + } + } + } +} + +@Composable +private fun soundSummary(s: SpeakerSound): String = buildList { + if (s.bassDb != 0) add(stringResource(R.string.speaker_sound_bass) + " %+d".format(s.bassDb)) + if (s.trebleDb != 0) add(stringResource(R.string.speaker_sound_treble) + " %+d".format(s.trebleDb)) + if (s.trimDb != 0) add(stringResource(R.string.speaker_sound_level) + " %+d".format(s.trimDb)) + if (s.leveling) add(stringResource(R.string.speaker_sound_leveling)) +}.joinToString(" · ") + +/** A -12..+12 dB slider that applies when released. */ +@Composable +private fun DbSlider(label: String, value: Int, onCommit: (Int) -> Unit) { + var v by remember(value) { mutableFloatStateOf(value.toFloat()) } + Row(verticalAlignment = Alignment.CenterVertically) { + Text(label, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f)) + Text("%+d dB".format(v.toInt()), style = StatTextStyle, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Slider(value = v, onValueChange = { v = it }, valueRange = -12f..12f, steps = 23, onValueChangeFinished = { onCommit(v.toInt()) }) +} + +private val SLEEP_TIMER_CHOICES = listOf(15, 30, 45, 60, 90) + +/** Stops the cast after a while, fading the sound out over the last 30 seconds. */ +@Composable +private fun SleepTimer(service: AudioCastService) { + val state by service.state.collectAsState() + val left by service.sleepTimerRemainingMs.collectAsState() + if (state != CastState.CASTING) return + ListGroup(title = stringResource(R.string.sleep_timer)) { + ListBlock { + Text( + left?.let { stringResource(R.string.sleep_timer_left, formatTime(it + 999)) } ?: stringResource(R.string.sleep_timer_desc), + style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + FilterChip(selected = left == null, onClick = { service.cancelSleepTimer() }, label = { Text(stringResource(R.string.sleep_timer_off)) }) + SLEEP_TIMER_CHOICES.forEach { minutes -> + FilterChip(selected = false, onClick = { service.setSleepTimer(minutes) }, + label = { Text(stringResource(R.string.sleep_timer_minutes, minutes)) }) + } + } + } + } +} + /** Track position, extrapolated between metadata updates while playing. */ @Composable fun rememberLivePosition(m: TrackMetadata?): Long { diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 5569ea81..80c10c61 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -188,6 +188,19 @@ Nessuna riproduzione Sincronizza le stanze Ritarda un altoparlante che suona prima degli altri. + Timer di spegnimento + Ferma la trasmissione dopo un po\'. Il suono sfuma negli ultimi 30 secondi. + Si ferma tra %1$s + Disattivato + %1$d min + Suono per altoparlante + Neutro + Bassi + Acuti + Livello + Livellamento del volume + Uniforma i passaggi piano e forte, utile di notte. + Ripristina questo altoparlante Altoparlanti Ricerca degli altoparlanti su questa rete… Connesso @@ -250,6 +263,9 @@ Inviati %1$d · ricevuti %2$d · persi %3$d Firmware %1$s, %2$d interruzioni. Copia il report + %1$s: comportamento noto + I WiiM si fermano a 0:00 ogni volta che ricevono un nuovo indirizzo di stream. AriaCast riavvia la riproduzione a ogni cambio traccia. Se si ferma comunque, premi play una volta nell\'app WiiM e segnalalo. + I ricevitori AirPlay 2 basati su shairport-sync richiedono la sincronizzazione PTP, che le app Android non possono offrire senza root. AriaCast prova con NTP e passa da solo ad AirPlay 1. Report copiato Trasmetti qualsiasi audio, ovunque AriaCast invia l\'audio di questo dispositivo ad altoparlanti AirPlay, Google Cast, DLNA, Snapcast e Sendspin, e può trasformare questo dispositivo in un altoparlante. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 45d8dc8b..2753dad8 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -291,6 +291,19 @@ Nothing playing Keep rooms in sync Delay a speaker that plays ahead of the others. + Sleep timer + Stop the cast after a while. The sound fades out over the last 30 seconds. + Stops in %1$s + Off + %1$d min + Sound per speaker + Flat + Bass + Treble + Level + Loudness leveling + Evens out quiet and loud passages, handy at night. + Reset this speaker Speakers Looking for speakers on this network… Connected @@ -353,6 +366,9 @@ Sent %1$d · received %2$d · dropped %3$d Firmware %1$s, %2$d dropouts. Copy report + %1$s: known behavior + WiiM players pause at 0:00 whenever they receive a new stream address. AriaCast starts playback again after every track change. If it still stops, press play once in the WiiM app and report it. + AirPlay 2 receivers built on shairport-sync need PTP timing, which Android apps can\'t provide without root. AriaCast tries NTP timing and falls back to AirPlay 1 on its own. Report copied Cast any audio, anywhere AriaCast sends this device\'s audio to AirPlay, Google Cast, DLNA, Snapcast and Sendspin speakers, and can turn this device into a speaker too. diff --git a/app/src/test/java/com/aria/ariacast/dlna/DlnaTest.kt b/app/src/test/java/com/aria/ariacast/dlna/DlnaTest.kt index c76962fa..753c0afb 100644 --- a/app/src/test/java/com/aria/ariacast/dlna/DlnaTest.kt +++ b/app/src/test/java/com/aria/ariacast/dlna/DlnaTest.kt @@ -69,6 +69,14 @@ class DlnaTest { assertEquals(null, Dlna.parseRemoteDescription(mediaServer)) } + @Test fun remoteDescriptionReadsManufacturerAndModel() { + val xml = """DenLinkplay Technology Inc. +WiiM Pro Plus${svc("urn:schemas-upnp-org:service:AVTransport:1", "/avt")}""" + val r = Dlna.parseRemoteDescription(xml)!! + assertEquals("Linkplay Technology Inc.", r.manufacturer) + assertEquals("WiiM Pro Plus", r.modelName) + } + @Test fun remoteDescriptionAcceptsNewerAvTransportVersions() { val xml = """TV${svc("urn:schemas-upnp-org:service:AVTransport:3", "http://10.0.0.5:9197/avt")}""" val r = Dlna.parseRemoteDescription(xml)!! diff --git a/app/src/test/java/com/aria/ariacast/pipeline/MasterGainTest.kt b/app/src/test/java/com/aria/ariacast/pipeline/MasterGainTest.kt new file mode 100644 index 00000000..fd278619 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/pipeline/MasterGainTest.kt @@ -0,0 +1,101 @@ +package com.aria.ariacast.pipeline + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class MasterGainTest { + private var now = 1_000_000L + private fun gain(fadeIn: Long = 1_000, fadeOut: Long = 30_000) = MasterGain({ now }, fadeIn, fadeOut) + + /** A frame of constant full-scale-ish samples, so the gain is easy to read back. */ + private fun frame(value: Int = 10_000) = ByteArray(PcmFormat.FRAME_BYTES).also { + for (i in 0 until it.size / 2) { + it[2 * i] = value.toByte(); it[2 * i + 1] = (value shr 8).toByte() + } + } + + private fun sampleAt(pcm: ByteArray, index: Int) = + ((pcm[2 * index].toInt() and 0xFF) or (pcm[2 * index + 1].toInt() shl 8)).toShort().toInt() + + @Test fun passesAudioUntouchedWhenIdle() { + val g = gain() + val f = frame() + g.process(f) + assertTrue(f.contentEquals(frame())) + } + + @Test fun fadeInStartsSilentAndReachesFullVolume() { + val g = gain() + g.beginSession() + assertEquals(0f, g.targetGain(), 0.001f) + now += 500 + assertEquals(0.5f, g.targetGain(), 0.001f) + now += 600 + assertEquals(1f, g.targetGain(), 0.001f) + } + + @Test fun firstFrameOfAFadeInRampsFromZero() { + val g = gain() + g.beginSession() + val f = frame() + g.process(f) + // Gain is 0 at the start of the session, so the ramp begins at silence... + assertTrue(sampleAt(f, 0) in 0..10) + // ...and rises across the frame. + assertTrue(sampleAt(f, PcmFormat.FRAME_BYTES / 2 - 2) >= sampleAt(f, 0)) + } + + @Test fun timerFadesOutOverTheLastSeconds() { + val g = gain() + g.startTimer(60_000) + assertEquals(1f, g.targetGain(), 0.001f) + now += 30_000 // 30 s left: the fade starts + assertEquals(1f, g.targetGain(), 0.001f) + now += 15_000 // 15 s left: halfway down + assertEquals(0.5f, g.targetGain(), 0.001f) + now += 15_000 + assertEquals(0f, g.targetGain(), 0.001f) + assertTrue(g.timerExpired()) + } + + @Test fun shortTimerFadesOverHalfItsLength() { + val g = gain() + g.startTimer(10_000) + now += 5_000 + assertEquals(1f, g.targetGain(), 0.001f) + now += 2_500 + assertEquals(0.5f, g.targetGain(), 0.001f) + } + + @Test fun cancelRestoresFullVolume() { + val g = gain() + g.startTimer(60_000) + now += 59_000 + assertTrue(g.targetGain() < 0.1f) + g.cancelTimer() + assertEquals(1f, g.targetGain(), 0.001f) + assertNull(g.remainingMs()) + assertFalse(g.timerExpired()) + } + + @Test fun remainingCountsDown() { + val g = gain() + assertNull(g.remainingMs()) + g.startTimer(90_000) + now += 10_000 + assertEquals(80_000L, g.remainingMs()) + } + + @Test fun rampDoesNotClipOrWrap() { + val f = frame(32_767) + MasterGain.applyRamp(f, 1f, 1f) + assertEquals(32_767, sampleAt(f, 0)) + val neg = frame(-32_768) + MasterGain.applyRamp(neg, 1f, 0f) + assertEquals(0, sampleAt(neg, PcmFormat.FRAME_BYTES / 2 - 1)) + assertTrue(sampleAt(neg, 0) <= 0) + } +} diff --git a/app/src/test/java/com/aria/ariacast/pipeline/SpeakerDspTest.kt b/app/src/test/java/com/aria/ariacast/pipeline/SpeakerDspTest.kt new file mode 100644 index 00000000..54c03fe4 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/pipeline/SpeakerDspTest.kt @@ -0,0 +1,116 @@ +package com.aria.ariacast.pipeline + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.log10 +import kotlin.math.sin +import kotlin.math.sqrt + +class SpeakerDspTest { + private val frameSamples = PcmFormat.FRAME_BYTES / PcmFormat.BYTES_PER_FRAME + + /** Runs [seconds] of a stereo sine through [dsp] and returns the RMS of the second half. */ + private fun rmsOut(dsp: SpeakerDsp, freq: Double, amplitude: Double, seconds: Int = 1): Double { + val frames = seconds * 50 + var sum = 0.0 + var count = 0 + var n = 0 + repeat(frames) { f -> + val pcm = ByteArray(PcmFormat.FRAME_BYTES) + for (i in 0 until frameSamples) { + val v = (amplitude * 32767 * sin(2 * PI * freq * n++ / PcmFormat.SAMPLE_RATE)).toInt() + for (ch in 0..1) { + val at = i * 4 + ch * 2 + pcm[at] = v.toByte(); pcm[at + 1] = (v shr 8).toByte() + } + } + val out = dsp.process(pcm) + if (f >= frames / 2) { + for (i in 0 until out.size / 2) { + val s = ((out[2 * i].toInt() and 0xFF) or (out[2 * i + 1].toInt() shl 8)).toShort().toDouble() + sum += s * s; count++ + } + } + } + return sqrt(sum / count) / 32768 + } + + private fun db(ratio: Double) = 20 * log10(ratio) + private fun dspOf(sound: SpeakerSound) = SpeakerDsp { sound } + + @Test fun flatSpeakerGetsTheSameFrameBack() { + val frame = ByteArray(PcmFormat.FRAME_BYTES) { it.toByte() } + val dsp = dspOf(SpeakerSound()) + assertSame(frame, dsp.process(frame)) + } + + @Test fun neverEditsTheSharedInputFrame() { + val frame = ByteArray(PcmFormat.FRAME_BYTES) { (it % 100).toByte() } + val copy = frame.copyOf() + val out = dspOf(SpeakerSound(trimDb = -6)).process(frame) + assertNotSame(frame, out) + assertTrue(frame.contentEquals(copy)) + } + + @Test fun trimScalesTheLevel() { + val reference = rmsOut(dspOf(SpeakerSound()), 1000.0, 0.2) + val quieter = rmsOut(dspOf(SpeakerSound(trimDb = -6)), 1000.0, 0.2) + assertEquals(-6.0, db(quieter / reference), 0.2) + } + + @Test fun bassBoostLiftsLowsAndLeavesHighsAlone() { + val dsp = { SpeakerDsp { SpeakerSound(bassDb = 9) } } + val inLow = 0.1 / sqrt(2.0) + assertEquals(9.0, db(rmsOut(dsp(), 40.0, 0.1, 2) / inLow), 1.5) + assertEquals(0.0, db(rmsOut(dsp(), 4000.0, 0.1) / inLow), 0.5) + } + + @Test fun trebleCutLowersHighsAndLeavesLowsAlone() { + val dsp = { SpeakerDsp { SpeakerSound(trebleDb = -9) } } + val inLevel = 0.1 / sqrt(2.0) + assertEquals(-9.0, db(rmsOut(dsp(), 12000.0, 0.1) / inLevel), 1.5) + assertEquals(0.0, db(rmsOut(dsp(), 300.0, 0.1) / inLevel), 0.5) + } + + @Test fun boostsSoftClipInsteadOfWrapping() { + val out = ByteArray(PcmFormat.FRAME_BYTES) + for (i in 0 until out.size / 2) { out[2 * i] = 0xFF.toByte(); out[2 * i + 1] = 0x7F } // +32767 + val result = dspOf(SpeakerSound(trimDb = 12)).process(out) + for (i in 0 until result.size / 2) { + val s = ((result[2 * i].toInt() and 0xFF) or (result[2 * i + 1].toInt() shl 8)).toShort().toInt() + assertTrue("sample $i wrapped: $s", s > 30_000) + } + } + + @Test fun levelerNarrowsTheGapBetweenQuietAndLoud() { + val quietIn = 0.02 + val loudIn = 0.5 + val plainGap = db(loudIn / quietIn) + val levelled = SpeakerSound(leveling = true) + val quiet = rmsOut(dspOf(levelled), 1000.0, quietIn, 2) + val loud = rmsOut(dspOf(levelled), 1000.0, loudIn, 2) + val gap = db(loud / quiet) + assertTrue("gap $gap dB should be well under $plainGap dB", gap < plainGap - 6) + assertTrue("quiet passages should come up", quiet > quietIn / sqrt(2.0)) + } + + @Test fun changesApplyLiveAndReturnToFlat() { + var sound = SpeakerSound(trimDb = -12) + val dsp = SpeakerDsp { sound } + val frame = ByteArray(PcmFormat.FRAME_BYTES) { if (it % 2 == 1) 0x20 else 0 } // constant 0x2000 samples + val quiet = dsp.process(frame) + sound = SpeakerSound() + assertSame(frame, dsp.process(frame)) + assertTrue(abs(quiet[1].toInt()) < abs(frame[1].toInt())) + } + + @Test fun clampsUserValuesToRange() { + val s = SpeakerSound(bassDb = 40, trebleDb = -40, trimDb = 13).clamped() + assertEquals(12, s.bassDb); assertEquals(-12, s.trebleDb); assertEquals(12, s.trimDb) + } +} diff --git a/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt b/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt new file mode 100644 index 00000000..5c4c4bcf --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt @@ -0,0 +1,49 @@ +package com.aria.ariacast.quirks + +import com.aria.ariacast.ExtraFields +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class DeviceQuirksTest { + private fun ids(d: DeviceIdentity) = DeviceQuirks.matching(d).map { it.id } + + @Test fun matchesWiimOverDlnaByNameOrManufacturer() { + assertEquals(listOf("wiim-dlna-restart"), ids(DeviceIdentity("DLNA", "Living room", "WiiM Pro Plus", "Linkplay Technology Inc."))) + assertEquals(listOf("wiim-dlna-restart"), ids(DeviceIdentity("DLNA", "WiiM Mini-1234"))) + } + + @Test fun wiimOnAnotherProtocolIsNotMatched() { + assertTrue(ids(DeviceIdentity("AirPlay2", "WiiM Pro Plus")).isEmpty()) + } + + @Test fun matchesShairportOnAirPlay2Only() { + assertEquals(listOf("shairport-airplay2-ptp"), ids(DeviceIdentity("AirPlay2", "Kitchen", "ShairportSync"))) + assertTrue(ids(DeviceIdentity("AirPlay", "Kitchen", "ShairportSync")).isEmpty()) + } + + @Test fun ordinarySpeakersMatchNothing() { + assertTrue(ids(DeviceIdentity("Google Cast", "Nest Mini", "Google Home Mini")).isEmpty()) + assertTrue(ids(DeviceIdentity("AirPlay2", "HomePod", "AudioAccessory5,1")).isEmpty()) + } + + @Test fun readsIdentityFromDiscoveryExtraFields() { + val extra = ExtraFields.join(listOf("av_control" to "http://x/a;b", "manufacturer" to "Linkplay", "model" to "WiiM Pro")) + val d = DeviceIdentity.of("DLNA", "Den", extra) + assertEquals("Linkplay", d.manufacturer) + assertEquals("WiiM Pro", d.model) + } + + @Test fun aHostileModelCannotInjectFields() { + val extra = ExtraFields.join(listOf("model" to "x;manufacturer=Evil")) + val d = DeviceIdentity.of("DLNA", "Den", extra) + assertEquals("x;manufacturer=Evil", d.model) + assertEquals(null, d.manufacturer) + } + + @Test fun reportLineListsWhatIsKnown() { + assertEquals("protocol=DLNA, manufacturer=Linkplay, model=WiiM Pro, name=Den", + DeviceIdentity("DLNA", "Den", "WiiM Pro", "Linkplay").reportLine()) + assertEquals("name=Den", DeviceIdentity(null, "Den").reportLine()) + } +} diff --git a/docs/ROADMAP-2.0.md b/docs/ROADMAP-2.0.md index a2cb9db1..58f9f68e 100644 --- a/docs/ROADMAP-2.0.md +++ b/docs/ROADMAP-2.0.md @@ -29,8 +29,10 @@ this section before releasing. | Plugin catalog with signature checks | Not done | The existing GitHub sync with re-consent on change remains | | AirPlay receiver (UxPlay via NDK) | Not done | Large native integration | | Cast mirroring (libcast), AirPlay mirroring | Not done | | -| Per-app routing, EQ/loudness, AV sync offset | Not done | Multiroom delay sliders exist | -| Home Assistant `media_player`, quirk profiles, auto-cast on speaker appearance | Not done | | +| Sleep timer with fades, per-speaker EQ/loudness, saved per-speaker delay | Done | `MasterGain`, `SpeakerDsp`. Sendspin speakers aren't shaped (the server pulls the stream) | +| Per-app routing | Not done | Spike | +| Quirk profiles | Partial | `DeviceQuirks`: notes in the doctor for WiiM (DLNA) and shairport-sync (AirPlay 2); more entries come from "Copy report" | +| Home Assistant `media_player`, auto-cast on speaker appearance | Not done | | | Ktor 3 | Not done | Client and server on 2.3.8 | | Retire the standalone receiver repo | Not done | Needs a final release there pointing to AriaCast | From e4b9f9e240f9288efa7020889de1f66d55e3362c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 10:06:05 +0000 Subject: [PATCH 02/14] Add a known-speakers list and a Report speaker action - DeviceQuirks becomes a table of known speakers (works / works with a catch / does not work) with symptoms, what to do, version and evidence. Only behavior with evidence is listed. - docs/SPEAKERS.md is generated from that table; a unit test fails when they drift (UPDATE_SPEAKERS_DOC=1 regenerates it). - PacketLogger lines can carry the speaker's host, and the per-speaker cast logs now do. - "Report speaker" (long-press in the Send tab, and in the connection doctor) shares who the speaker is, what is known about it, the cast state, its settings and its log lines, with addresses shortened. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01XZTMETapPkNvc9xdPLcfZu --- CHANGELOG.md | 11 +- .../com/aria/ariacast/AudioCastService.kt | 48 ++++---- .../java/com/aria/ariacast/PacketLogger.kt | 12 +- .../com/aria/ariacast/quirks/DeviceQuirks.kt | 111 +++++++++++++++--- .../com/aria/ariacast/quirks/SpeakerReport.kt | 71 +++++++++++ .../aria/ariacast/ui/SpeakerReportAction.kt | 52 ++++++++ .../aria/ariacast/ui/doctor/DoctorScreen.kt | 11 +- .../com/aria/ariacast/ui/home/SendScreen.kt | 11 +- app/src/main/res/values-it/strings.xml | 3 + app/src/main/res/values/strings.xml | 3 + .../com/aria/ariacast/PacketLoggerTest.kt | 12 ++ .../aria/ariacast/quirks/DeviceQuirksTest.kt | 17 ++- .../aria/ariacast/quirks/SpeakerReportTest.kt | 74 ++++++++++++ .../com/aria/ariacast/quirks/SpeakersDoc.kt | 42 +++++++ .../aria/ariacast/quirks/SpeakersDocTest.kt | 32 +++++ docs/ROADMAP-2.0.md | 2 +- docs/SPEAKERS.md | 34 ++++++ 17 files changed, 491 insertions(+), 55 deletions(-) create mode 100644 app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt create mode 100644 app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt create mode 100644 app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt create mode 100644 app/src/test/java/com/aria/ariacast/quirks/SpeakersDoc.kt create mode 100644 app/src/test/java/com/aria/ariacast/quirks/SpeakersDocTest.kt create mode 100644 docs/SPEAKERS.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 77ba0a2f..7eca37e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,9 +46,14 @@ casting, a new interface, and AriaCompanion 2. AriaCast, AirPlay, Cast, DLNA, Snapcast and VBAN speakers. - **Rooms stay lined up**: each speaker's sync delay is now saved and applied the next time that speaker joins a cast. -- **Known speaker behavior**: the connection doctor now shows notes for brands and models with - documented quirks (WiiM over DLNA, shairport-sync over AirPlay 2) and adds the speaker's - manufacturer and model to the copied report. DLNA speakers now report both. +- **Known speakers**: [docs/SPEAKERS.md](docs/SPEAKERS.md) lists speakers known to work, to work + with a catch, or not to work, with the symptom to look for, what to do, and the evidence. It is + generated from the same table the app uses, and a test fails if the two drift apart. The + connection doctor shows a note while you cast to a speaker with a documented quirk (WiiM over + DLNA, shairport-sync over AirPlay 2). DLNA speakers now report manufacturer and model. +- **Report speaker**: long-press a speaker (or use the doctor) to share a report with who the + speaker is, what is known about it, the cast state and its log lines, with addresses shortened. + Works for speakers you never managed to connect to. ### Built in, previously plugins - Music Assistant player picker, connection doctor, visualizer, add speaker by address. diff --git a/app/src/main/java/com/aria/ariacast/AudioCastService.kt b/app/src/main/java/com/aria/ariacast/AudioCastService.kt index b820bfa4..b6186b15 100644 --- a/app/src/main/java/com/aria/ariacast/AudioCastService.kt +++ b/app/src/main/java/com/aria/ariacast/AudioCastService.kt @@ -709,7 +709,7 @@ class AudioCastService : Service() { val withDelay = withSavedDelay(dest) _activeDestinations.value = _activeDestinations.value + withDelay launchDestination(scope, withDelay, withVideo = false) - PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Added ${dest.name} to the cast") + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Added ${dest.name} to the cast", device = dest.host) _metadata.value?.let { sendMetadata(it) } updateNotification() } @@ -727,7 +727,7 @@ class AudioCastService : Service() { controlSessions.remove(dest.host) } _activeDestinations.value = remaining - PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Removed ${dest.name} from the cast") + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Removed ${dest.name} from the cast", device = dest.host) updateNotification() } @@ -917,14 +917,14 @@ class AudioCastService : Service() { client.launch(sharedPreferences.getString(KEY_CAST_RECEIVER_APP_ID, null) ?.trim()?.uppercase()?.takeIf { it.matches(Regex("[0-9A-F]{8}")) } ?: CastClient.DEFAULT_MEDIA_RECEIVER) client.load(streamUrl, "audio/wav", castMetadata(_metadata.value)) - PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Google Cast: ${dest.name} playing $streamUrl") + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Google Cast: ${dest.name} playing $streamUrl", device = dest.host) } catch (e: CancellationException) { client.close() throw e } catch (e: Exception) { client.close() Log.e(TAG, "Google Cast session failed for ${dest.name}: ${e.message}") - PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Google Cast ${dest.name} failed: ${e.message ?: e.javaClass.simpleName}") + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Google Cast ${dest.name} failed: ${e.message ?: e.javaClass.simpleName}", device = dest.host) if (++failures >= 3) { _state.value = CastState.ERROR return@withContext @@ -940,7 +940,7 @@ class AudioCastService : Service() { try { val reason = ended.await() Log.w(TAG, "Google Cast ${dest.name} ended: $reason") - PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Google Cast ${dest.name} ended: $reason") + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Google Cast ${dest.name} ended: $reason", device = dest.host) if (reason == "receiver app stopped" || reason == "receiver app closed") { // The user switched the device to something else - don't fight them for it. _state.value = CastState.ERROR @@ -990,7 +990,7 @@ class AudioCastService : Service() { } catch (e: Exception) { val label = if (airplay2) "AirPlay 2" else "AirPlay" Log.e(TAG, "$label session failed for ${dest.name}: ${e.message}") - PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "$label ${dest.name} failed: ${e.message ?: e.javaClass.simpleName}") + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "$label ${dest.name} failed: ${e.message ?: e.javaClass.simpleName}", device = dest.host) if (e is AirPlayBusyException || e is AirPlayAuthRequiredException || ++failures >= 3) { _state.value = CastState.ERROR return@withContext @@ -1007,7 +1007,7 @@ class AudioCastService : Service() { airplayStreamers[dest.host] = streamer lastSentMetadata.remove(dest.host) lastSentArtwork.remove(dest.host) - PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "${dest.name}: streaming (${streamer.javaClass.simpleName})") + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "${dest.name}: streaming (${streamer.javaClass.simpleName})", device = dest.host) _state.value = CastState.CASTING updateNotification() _metadata.value?.let { pushAirPlayMetadata(dest.host, streamer, it) } @@ -1025,7 +1025,7 @@ class AudioCastService : Service() { var elapsed = 0L for (at in longArrayOf(5_000, 30_000)) { delay(at - elapsed); elapsed = at - PacketLogger.log(PacketDirection.OUT, PacketType.STATS, "${dest.name} after ${at / 1000}s: ${streamer.statsSummary()}") + PacketLogger.log(PacketDirection.OUT, PacketType.STATS, "${dest.name} after ${at / 1000}s: ${streamer.statsSummary()}", device = dest.host) } } val r = ended.await() @@ -1034,7 +1034,7 @@ class AudioCastService : Service() { r } Log.w(TAG, "AirPlay ${dest.name} dropped: $reason (${streamer.statsSummary()})") - PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "${dest.name} dropped the session: $reason - reconnecting") + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "${dest.name} dropped the session: $reason - reconnecting", device = dest.host) } finally { airplayStreamers.remove(dest.host, streamer) withContext(NonCancellable) { @@ -1083,7 +1083,7 @@ class AudioCastService : Service() { // e.g. shairport-sync in AirPlay 2 mode, which needs PTP (privileged ports // on Android). Every AirPlay 2 receiver also speaks AirPlay 1 on the same port. Log.i(TAG, "${dest.name}: ${e.message}; falling back to AirPlay 1") - PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "${dest.name}: AirPlay 2 timing unsupported, using AirPlay 1") + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "${dest.name}: AirPlay 2 timing unsupported, using AirPlay 1", device = dest.host) val raop = RaopClient( host = dest.host, port = if (dest.port > 0) dest.port else 7000, @@ -1276,7 +1276,7 @@ class AudioCastService : Service() { _state.value = CastState.CASTING updateNotification() PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, - "VBAN stream '$streamName' to ${dest.name} (${dest.host}:$port), ${PcmFormat.SAMPLE_RATE} Hz stereo 16-bit PCM") + "VBAN stream '$streamName' to ${dest.name} (${dest.host}:$port), ${PcmFormat.SAMPLE_RATE} Hz stereo 16-bit PCM", device = dest.host) val dsp = dspFor(dest.host) audioBufferFlow.collect { streamer.send(dsp.process(it)) } } @@ -1284,7 +1284,7 @@ class AudioCastService : Service() { throw e } catch (e: Exception) { Log.e(TAG, "VBAN session failed for ${dest.name}: ${e.message}") - PacketLogger.log(PacketDirection.OUT, PacketType.AUDIO, "VBAN to ${dest.name} failed: ${e.message}") + PacketLogger.log(PacketDirection.OUT, PacketType.AUDIO, "VBAN to ${dest.name} failed: ${e.message}", device = dest.host) _state.value = CastState.ERROR } } @@ -1469,19 +1469,19 @@ class AudioCastService : Service() { try { client.webSocket(host = dest.host, port = dest.port, path = "/audio") audioSocket@{ reconnectAttempts = 0 - PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Audio socket connected to ${dest.name} (${dest.host}:${dest.port})") + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Audio socket connected to ${dest.name} (${dest.host}:${dest.port})", device = dest.host) if (dest.platform != "AriaCast") { val handshakeFrame = try { withTimeout(3000L) { incoming.receive() } } catch (e: Exception) { Log.w(TAG, "Audio handshake timed out for ${dest.host}: ${e.message}") - PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Handshake timed out for ${dest.name}: ${e.message}") + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Handshake timed out for ${dest.name}: ${e.message}", device = dest.host) return@audioSocket } if (handshakeFrame !is Frame.Text) { - PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Unexpected handshake frame type from ${dest.name}") + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Unexpected handshake frame type from ${dest.name}", device = dest.host) return@audioSocket } } @@ -1522,7 +1522,7 @@ class AudioCastService : Service() { } catch (e: Exception) { if (e is CancellationException) throw e Log.e(TAG, "Audio WS connection to ${dest.host}:${dest.port} failed: ${e.message}", e) - PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Audio connection to ${dest.name} failed: ${e.message ?: e.javaClass.simpleName}") + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Audio connection to ${dest.name} failed: ${e.message ?: e.javaClass.simpleName}", device = dest.host) reconnectAttempts++ val delayTime = (RECONNECT_INITIAL_BACKOFF * 2.0.pow(reconnectAttempts.toDouble().coerceAtMost(5.0))).toLong() delay(delayTime) @@ -1853,18 +1853,18 @@ class AudioCastService : Service() { setBody(mapOf("data" to finalMetadata)) timeout { requestTimeoutMillis = 5000 } } - PacketLogger.log(PacketDirection.OUT, PacketType.METADATA, "Metadata sent to ${dest.name}") + PacketLogger.log(PacketDirection.OUT, PacketType.METADATA, "Metadata sent to ${dest.name}", device = dest.host) } else if (dest.platform == "AirPlay" || dest.platform == "AirPlay2") { airplayStreamers[dest.host]?.let { streamer -> pushAirPlayMetadata(dest.host, streamer, finalMetadata) - PacketLogger.log(PacketDirection.OUT, PacketType.METADATA, "Metadata sent to ${dest.name} (AirPlay)") + PacketLogger.log(PacketDirection.OUT, PacketType.METADATA, "Metadata sent to ${dest.name} (AirPlay)", device = dest.host) } } else if (dest.platform == "Google Cast") { val cast = castClients[dest.host] if (cast != null && lastSentMetadata[dest.host] != metadataKey + currentArtworkBytes?.contentHashCode()) { lastSentMetadata[dest.host] = metadataKey + currentArtworkBytes?.contentHashCode() cast.updateMetadata(castMetadata(metadata)) - PacketLogger.log(PacketDirection.OUT, PacketType.METADATA, "Metadata sent to ${dest.name} (Google Cast)") + PacketLogger.log(PacketDirection.OUT, PacketType.METADATA, "Metadata sent to ${dest.name} (Google Cast)", device = dest.host) } } else if (dest.platform == "DLNA") { if (lastSentMetadata[dest.host] != metadataKey) { @@ -1964,7 +1964,7 @@ class AudioCastService : Service() { try { client.webSocket(host = dest.host, port = dest.port, path = "/control") { controlSessions[dest.host] = this - PacketLogger.log(PacketDirection.OUT, PacketType.CONTROL, "Control socket connected to ${dest.name}") + PacketLogger.log(PacketDirection.OUT, PacketType.CONTROL, "Control socket connected to ${dest.name}", device = dest.host) for (frame in incoming) { if (frame is Frame.Text) { val text = frame.readText() @@ -1976,7 +1976,7 @@ class AudioCastService : Service() { val key = if (json.has("position_ms")) "position_ms" else "value" if (json.has(key)) { val positionMs = json.getLong(key).coerceAtLeast(0) - PacketLogger.log(PacketDirection.IN, PacketType.CONTROL, "Seek to ${positionMs / 1000} s from ${dest.name}") + PacketLogger.log(PacketDirection.IN, PacketType.CONTROL, "Seek to ${positionMs / 1000} s from ${dest.name}", device = dest.host) _seekRequests.emit(positionMs) } continue @@ -1992,7 +1992,7 @@ class AudioCastService : Service() { } catch (e: Exception) { if (e is CancellationException) throw e Log.e(TAG, "Control WS connection to ${dest.host}:${dest.port} failed: ${e.message}", e) - PacketLogger.log(PacketDirection.IN, PacketType.CONTROL, "Control connection to ${dest.name} failed: ${e.message ?: e.javaClass.simpleName}") + PacketLogger.log(PacketDirection.IN, PacketType.CONTROL, "Control connection to ${dest.name} failed: ${e.message ?: e.javaClass.simpleName}", device = dest.host) controlSessions.remove(dest.host) delay(RECONNECT_INITIAL_BACKOFF) } @@ -2003,7 +2003,7 @@ class AudioCastService : Service() { while (currentCoroutineContext().isActive) { try { client.webSocket(host = dest.host, port = dest.port, path = "/stats") statsSocket@{ - PacketLogger.log(PacketDirection.OUT, PacketType.STATS, "Stats socket connected to ${dest.name}") + PacketLogger.log(PacketDirection.OUT, PacketType.STATS, "Stats socket connected to ${dest.name}", device = dest.host) while(isActive) { val frame = withTimeoutOrNull(STATS_TIMEOUT) { incoming.receive() } if (frame is Frame.Text) { @@ -2021,7 +2021,7 @@ class AudioCastService : Service() { } catch (e: Exception) { if (e is CancellationException) throw e Log.e(TAG, "Stats WS connection to ${dest.host}:${dest.port} failed: ${e.message}", e) - PacketLogger.log(PacketDirection.IN, PacketType.STATS, "Stats connection to ${dest.name} failed: ${e.message ?: e.javaClass.simpleName}") + PacketLogger.log(PacketDirection.IN, PacketType.STATS, "Stats connection to ${dest.name} failed: ${e.message ?: e.javaClass.simpleName}", device = dest.host) delay(RECONNECT_INITIAL_BACKOFF) } } diff --git a/app/src/main/java/com/aria/ariacast/PacketLogger.kt b/app/src/main/java/com/aria/ariacast/PacketLogger.kt index 522ec2de..09c8ebf0 100644 --- a/app/src/main/java/com/aria/ariacast/PacketLogger.kt +++ b/app/src/main/java/com/aria/ariacast/PacketLogger.kt @@ -15,7 +15,9 @@ data class PacketLog( val type: PacketType, val message: String, val payloadSize: Int = 0, - var count: Int = 1 + var count: Int = 1, + /** Host of the speaker this line is about, when it is about one (used by "Report speaker"). */ + val device: String? = null, ) object PacketLogger { @@ -32,14 +34,15 @@ object PacketLogger { override fun initialValue(): SimpleDateFormat = SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault()) } - fun log(direction: PacketDirection, type: PacketType, message: String, payloadSize: Int = 0) { + fun log(direction: PacketDirection, type: PacketType, message: String, payloadSize: Int = 0, device: String? = null) { val timestamp = dateFormat.get()!!.format(Date()) val entry = PacketLog( timestamp = timestamp, direction = direction, type = type, message = message, - payloadSize = payloadSize + payloadSize = payloadSize, + device = device, ) synchronized(_logs) { @@ -47,7 +50,8 @@ object PacketLogger { if (lastLog != null && lastLog.direction == direction && lastLog.type == type && - lastLog.message == message) { + lastLog.message == message && + lastLog.device == device) { lastLog.count++ lastLog.timestamp = timestamp // We still emit it to let the UI know something happened, diff --git a/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt b/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt index 5a998432..776e5409 100644 --- a/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt +++ b/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt @@ -32,34 +32,113 @@ data class DeviceIdentity( ).joinToString(", ") } +/** How a speaker behaves over one protocol. */ +enum class Verdict(val label: String) { + /** Plays as expected. */ + GOOD("Works"), + + /** Plays, with a limit the user should know about. */ + PARTIAL("Works with a catch"), + + /** Does not play, or breaks in a way the app cannot work around. */ + BAD("Does not work"), +} + /** - * A known behavior of one family of speakers, with a plain-language note for the connection - * doctor. Entries are added only for behavior that is documented in an issue or in the code - * that works around it; "report my speaker" in the doctor exists to find the next ones. + * One entry of the list of speakers we know something about (published as docs/SPEAKERS.md; a + * unit test keeps the two in step). Entries are added only for behavior with evidence: an issue, + * a maintainer's own test, or the code that works around it. "Report speaker" in the app exists + * to find the next ones. */ -data class Quirk( +data class KnownSpeaker( val id: String, - @param:StringRes val note: Int, + /** Brand and, where known, the model it was seen on. */ + val speaker: String, + val protocol: String, + val verdict: Verdict, + /** What a user sees when it goes wrong, in their words. */ + val symptoms: List = emptyList(), + val whatToDo: String? = null, + /** First version where this holds (for a fix), if it is tied to one. */ + val since: String? = null, + /** Where this comes from. */ + val evidence: String, + /** Message the connection doctor shows while casting to a matching speaker, if any. */ + @param:StringRes val note: Int? = null, val appliesTo: (DeviceIdentity) -> Boolean, ) object DeviceQuirks { + private const val ISSUES = "https://github.com/AriaCast/AriaCast-app/issues" + private fun DeviceIdentity.mentions(vararg needles: String): Boolean { val haystack = listOfNotNull(name, model, manufacturer).joinToString(" ").lowercase() return needles.any { haystack.contains(it) } } - val ALL: List = listOf( - // Issue #50: SetAVTransportURI leaves a WiiM paused at 0:00. AriaCast now sends Play - // after every track change for all DLNA renderers; the note explains it if it recurs. - Quirk("wiim-dlna-restart", R.string.quirk_wiim_dlna) { it.platform == "DLNA" && it.mentions("wiim", "linkplay") }, - // AirPlay 2 receivers built on shairport-sync + nqptp only accept PTP timing, which - // Android can't offer without root (see PtpMaster): AriaCast uses NTP timing or AirPlay 1. - Quirk("shairport-airplay2-ptp", R.string.quirk_shairport_ptp) { - it.platform == "AirPlay2" && it.mentions("shairport") - }, + val ALL: List = listOf( + KnownSpeaker( + id = "sonos-airplay2", + speaker = "Sonos (tested on Play:5)", + protocol = "AirPlay 2", + verdict = Verdict.GOOD, + symptoms = listOf("On 1.1.9 the AirPlay 2 stream did not play, while DLNA to the same speaker did."), + whatToDo = "Update. Until then, cast to it over DLNA.", + since = "1.1.9_hotfix", + evidence = "[#48]($ISSUES/48), confirmed by the reporter after the hotfix", + ) { it.platform == "AirPlay2" && it.mentions("sonos") }, + KnownSpeaker( + id = "sonos-dlna", + speaker = "Sonos (tested on Play:5)", + protocol = "DLNA", + verdict = Verdict.GOOD, + evidence = "[#48]($ISSUES/48), reporter: DLNA was working", + ) { it.platform == "DLNA" && it.mentions("sonos") }, + KnownSpeaker( + id = "wiim-dlna-restart", + speaker = "WiiM (tested on Pro Plus)", + protocol = "DLNA", + verdict = Verdict.GOOD, + symptoms = listOf( + "The track title changes but playback stays paused at 0:00 after every track change.", + "Pressing play in the WiiM app starts it again.", + ), + whatToDo = "Update: AriaCast now sends Play after every track change. If it still stops, press play once in the WiiM app and report it.", + since = "2.0.0", + evidence = "[#50]($ISSUES/50), fixed in the 2.0 line; the reporter's confirmation is not recorded", + note = R.string.quirk_wiim_dlna, + ) { it.platform == "DLNA" && it.mentions("wiim", "linkplay") }, + KnownSpeaker( + id = "shairport-airplay1", + speaker = "shairport-sync", + protocol = "AirPlay 1", + verdict = Verdict.GOOD, + evidence = "Maintainer's own test in [#48]($ISSUES/48); the AirPlay version is not stated there, so it is listed under AirPlay 1", + ) { it.platform == "AirPlay" && it.mentions("shairport") }, + KnownSpeaker( + id = "shairport-airplay2-ptp", + speaker = "shairport-sync", + protocol = "AirPlay 2", + verdict = Verdict.PARTIAL, + symptoms = listOf("The speaker accepts the connection but timing is off, or AriaCast drops to AirPlay 1."), + whatToDo = "Nothing to do: AriaCast tries NTP timing and falls back to AirPlay 1 on its own. Real PTP needs root.", + evidence = "Code: PtpMaster (shairport-sync with nqptp accepts only PTP timing)", + note = R.string.quirk_shairport_ptp, + ) { it.platform == "AirPlay2" && it.mentions("shairport") }, + KnownSpeaker( + id = "appletv-airplay-video-pairing", + speaker = "Apple TV", + protocol = "AirPlay (video)", + verdict = Verdict.PARTIAL, + symptoms = listOf("On Apple TVs that require pairing, casting a video fails with \"This AirPlay device requires pairing for video\". Audio casting is not affected."), + whatToDo = "Cast audio only. Video works with Apple TVs that allow unpaired access.", + evidence = "Roadmap status table and VideoTargets.kt", + ) { (it.platform == "AirPlay" || it.platform == "AirPlay2") && it.mentions("appletv") }, ) - /** Every known behavior that applies to [device]. */ - fun matching(device: DeviceIdentity): List = ALL.filter { it.appliesTo(device) } + /** Every known entry that applies to [device]. */ + fun matching(device: DeviceIdentity): List = ALL.filter { it.appliesTo(device) } + + /** The entries the connection doctor should explain while casting to [device]. */ + fun notesFor(device: DeviceIdentity): List = matching(device).filter { it.note != null } } diff --git a/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt b/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt new file mode 100644 index 00000000..57afe4f2 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt @@ -0,0 +1,71 @@ +package com.aria.ariacast.quirks + +import com.aria.ariacast.PacketLog + +/** + * The text behind "Report speaker": who the speaker is, what we know about it, and the log lines + * that concern it, ready to paste into an issue. Pure, so it is unit-tested. + */ +object SpeakerReport { + /** Newest lines kept, so a long session does not bury the handshake in noise. */ + const val MAX_LOG_LINES = 300 + + private val ipv4 = Regex("""\b(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}\b""") + + /** `192.168.1.20` becomes `192.168.x.x`: enough to tell networks apart, not to find a home. */ + fun maskAddresses(text: String): String = ipv4.replace(text) { "${it.groupValues[1]}.${it.groupValues[2]}.x.x" } + + /** + * The lines about this speaker, oldest first. A line counts if it is tagged with [host], or, + * for lines logged without a tag (protocol clients), if its text names the host or the speaker. + */ + fun logFor(logs: List, host: String, name: String): List = + logs.asReversed().filter { line -> + line.device == host || + (host.isNotEmpty() && line.message.contains(host)) || + (name.isNotEmpty() && line.message.contains(name)) + }.takeLast(MAX_LOG_LINES) + + class Context( + val app: String, + val android: String, + val device: String, + /** Cast state and last error, when the service is running. */ + val castState: String? = null, + /** Delay and sound settings saved for this speaker. */ + val settings: String? = null, + ) + + fun build( + context: Context, + identity: DeviceIdentity, + host: String, + known: List, + logs: List, + ): String = buildString { + appendLine("AriaCast speaker report") + appendLine("Addresses are shortened to their first two parts; speaker names are included.") + appendLine() + appendLine("App: ${context.app}") + appendLine("Phone: ${context.device}, Android ${context.android}") + appendLine("Speaker: ${identity.reportLine()}") + if (known.isEmpty()) { + appendLine("Known: nothing recorded for this speaker yet") + } else { + known.forEach { appendLine("Known: ${it.speaker}, ${it.protocol}: ${it.verdict.label}") } + } + context.castState?.let { appendLine("Cast: $it") } + context.settings?.let { appendLine("Settings: $it") } + appendLine() + val lines = logFor(logs, host, identity.name) + if (lines.isEmpty()) { + appendLine("No log lines for this speaker (it has not been cast to since the app started).") + } else { + appendLine("Log, oldest first (${lines.size} lines):") + lines.forEach { l -> + val repeat = if (l.count > 1) " x${l.count}" else "" + appendLine("${l.timestamp} ${l.direction} ${l.type}$repeat ${l.message}") + } + } + }.let(::maskAddresses) +} diff --git a/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt b/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt new file mode 100644 index 00000000..0d598bde --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt @@ -0,0 +1,52 @@ +package com.aria.ariacast.ui + +import android.content.Context +import android.content.Intent +import android.os.Build +import com.aria.ariacast.AudioCastService +import com.aria.ariacast.PacketLogger +import com.aria.ariacast.R +import com.aria.ariacast.quirks.DeviceIdentity +import com.aria.ariacast.quirks.DeviceQuirks +import com.aria.ariacast.quirks.SpeakerReport + +/** + * "Report speaker": opens the share sheet with who the speaker is, what is known about it and + * the log lines that concern it. The sheet's own "Copy" puts it on the clipboard. + * + * Works for any speaker in the list, cast to or not, so a speaker that never connects can be + * reported too (its report then says it has no log yet). + */ +fun shareSpeakerReport( + context: Context, + service: AudioCastService?, + platform: String?, + name: String, + host: String, + extra: String?, +) { + val identity = DeviceIdentity.of(platform, name, extra) + val version = runCatching { context.packageManager.getPackageInfo(context.packageName, 0).versionName }.getOrNull() + val active = service?.activeDestinations?.value?.firstOrNull { it.host == host } + val sound = service?.soundFor(host) + val report = SpeakerReport.build( + context = SpeakerReport.Context( + app = "${context.getString(R.string.app_name)} ${version ?: "?"}", + android = "${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})", + device = "${Build.MANUFACTURER} ${Build.MODEL}", + castState = service?.let { s -> listOfNotNull(s.state.value.name, s.lastError.value?.let { "last error: $it" }).joinToString(", ") }, + settings = if (service == null || sound == null) null else + "delay=${active?.delayMs ?: 0} ms, bass=${sound.bassDb} dB, treble=${sound.trebleDb} dB, level=${sound.trimDb} dB, leveling=${sound.leveling}", + ), + identity = identity, + host = host, + known = DeviceQuirks.matching(identity), + logs = PacketLogger.logs, + ) + val send = Intent(Intent.ACTION_SEND).apply { + type = "text/plain" + putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.report_speaker_subject, name)) + putExtra(Intent.EXTRA_TEXT, report) + } + context.startActivity(Intent.createChooser(send, context.getString(R.string.report_speaker)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) +} diff --git a/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt b/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt index 22abd394..c8ac8c6a 100644 --- a/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt +++ b/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt @@ -15,6 +15,8 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Info import com.aria.ariacast.quirks.DeviceIdentity +import com.aria.ariacast.ui.shareSpeakerReport +import androidx.compose.material.icons.filled.BugReport import com.aria.ariacast.quirks.DeviceQuirks import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.CheckCircle @@ -144,8 +146,8 @@ fun DoctorScreen(controller: AppController, onBack: () -> Unit) { // Known behavior of this brand or model, so a quirk isn't mistaken for a bug. s.activeDestinations.value.forEach { d -> - DeviceQuirks.matching(DeviceIdentity.of(d.platform, d.name, d.extra)).forEach { q -> - list += Check(context.getString(R.string.doctor_known_behavior, d.name), CheckStatus.INFO, context.getString(q.note)) + DeviceQuirks.notesFor(DeviceIdentity.of(d.platform, d.name, d.extra)).forEach { q -> + list += Check(context.getString(R.string.doctor_known_behavior, d.name), CheckStatus.INFO, context.getString(q.note!!)) } } @@ -215,6 +217,11 @@ fun DoctorScreen(controller: AppController, onBack: () -> Unit) { ListRow(stringResource(R.string.packet_exchange), leading = { LeadingIcon(Icons.AutoMirrored.Filled.ReceiptLong) }) { controller.openActivity(PacketLogActivity::class.java) } + service?.activeDestinations?.value?.forEach { d -> + ListRow(stringResource(R.string.report_speaker_named, d.name), leading = { LeadingIcon(Icons.Filled.BugReport) }) { + shareSpeakerReport(context, service, d.platform, d.name, d.host, d.extra) + } + } } } } diff --git a/app/src/main/java/com/aria/ariacast/ui/home/SendScreen.kt b/app/src/main/java/com/aria/ariacast/ui/home/SendScreen.kt index 8c6b24e1..02b23f03 100644 --- a/app/src/main/java/com/aria/ariacast/ui/home/SendScreen.kt +++ b/app/src/main/java/com/aria/ariacast/ui/home/SendScreen.kt @@ -28,6 +28,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.BugReport import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Cast import androidx.compose.material.icons.filled.Delete @@ -112,6 +113,7 @@ import com.aria.ariacast.ui.ListGroup import com.aria.ariacast.ui.ListRow import com.aria.ariacast.ui.Screen import com.aria.ariacast.ui.ScreenList +import com.aria.ariacast.ui.shareSpeakerReport import com.aria.ariacast.ui.SectionHeader import com.aria.ariacast.ui.StatusBanner import com.aria.ariacast.ui.SubScreenScaffold @@ -270,6 +272,7 @@ private fun Speakers(controller: AppController, selection: SourceSelection) { val servers by controller.servers.collectAsState() val discovery by controller.discoveryState.collectAsState() val service by controller.service.collectAsState() + val context = LocalContext.current val active by (service?.activeDestinations ?: remember { MutableStateFlow(emptyList()) }).collectAsState() var addDialog by remember { mutableStateOf(false) } fun isActive(s: Server) = active.any { it.host == s.host && it.platform == s.platform } @@ -285,7 +288,6 @@ private fun Speakers(controller: AppController, selection: SourceSelection) { } if (servers.isEmpty()) { // Every protocol but AriaCast starts off: say so, or the user hunts for network problems. - val context = LocalContext.current val protocolsOff = remember(discovery) { !ProtocolsActivity.anyOptionalEnabled(context) } EmptyState( Icons.Filled.Speaker, stringResource(R.string.speakers_empty_title), @@ -304,7 +306,8 @@ private fun Speakers(controller: AppController, selection: SourceSelection) { sorted.forEach { server -> SpeakerRow(server, isActive(server), onClick = { controller.castTo(listOf(server), selection.source, selection.inputDeviceId) }, - onRemove = { controller.removeServer(server) }) + onRemove = { controller.removeServer(server) }, + onReport = { shareSpeakerReport(context, service, server.platform, server.name, server.host, server.extra) }) } } } @@ -313,7 +316,7 @@ private fun Speakers(controller: AppController, selection: SourceSelection) { } @Composable -private fun SpeakerRow(server: Server, active: Boolean, onClick: () -> Unit, onRemove: () -> Unit) { +private fun SpeakerRow(server: Server, active: Boolean, onClick: () -> Unit, onRemove: () -> Unit, onReport: () -> Unit) { var menu by remember { mutableStateOf(false) } Box { ListRow( @@ -327,6 +330,8 @@ private fun SpeakerRow(server: Server, active: Boolean, onClick: () -> Unit, onR onClick = onClick, ) DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + DropdownMenuItem(text = { Text(stringResource(R.string.report_speaker)) }, leadingIcon = { Icon(Icons.Filled.BugReport, null) }, + onClick = { menu = false; onReport() }) DropdownMenuItem(text = { Text(stringResource(R.string.remove)) }, leadingIcon = { Icon(Icons.Filled.Delete, null) }, onClick = { menu = false; onRemove() }) } diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 80c10c61..b57b7f07 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -264,6 +264,9 @@ Firmware %1$s, %2$d interruzioni. Copia il report %1$s: comportamento noto + Segnala altoparlante + Segnala %1$s + Segnalazione AriaCast: %1$s I WiiM si fermano a 0:00 ogni volta che ricevono un nuovo indirizzo di stream. AriaCast riavvia la riproduzione a ogni cambio traccia. Se si ferma comunque, premi play una volta nell\'app WiiM e segnalalo. I ricevitori AirPlay 2 basati su shairport-sync richiedono la sincronizzazione PTP, che le app Android non possono offrire senza root. AriaCast prova con NTP e passa da solo ad AirPlay 1. Report copiato diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2753dad8..488e4e0f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -367,6 +367,9 @@ Firmware %1$s, %2$d dropouts. Copy report %1$s: known behavior + Report speaker + Report %1$s + AriaCast report: %1$s WiiM players pause at 0:00 whenever they receive a new stream address. AriaCast starts playback again after every track change. If it still stops, press play once in the WiiM app and report it. AirPlay 2 receivers built on shairport-sync need PTP timing, which Android apps can\'t provide without root. AriaCast tries NTP timing and falls back to AirPlay 1 on its own. Report copied diff --git a/app/src/test/java/com/aria/ariacast/PacketLoggerTest.kt b/app/src/test/java/com/aria/ariacast/PacketLoggerTest.kt index b9591fd2..4ca81342 100644 --- a/app/src/test/java/com/aria/ariacast/PacketLoggerTest.kt +++ b/app/src/test/java/com/aria/ariacast/PacketLoggerTest.kt @@ -81,4 +81,16 @@ class PacketLoggerTest { assertEquals(1, logs.size) assertEquals(5, logs[0].count) } + + @Test + fun `the same message about two speakers is two lines, and the tag is kept`() { + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "connected", device = "10.0.0.1") + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "connected", device = "10.0.0.2") + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "connected", device = "10.0.0.2") + val logs = PacketLogger.logs + assertEquals(2, logs.size) + assertEquals("10.0.0.2", logs[0].device) + assertEquals(2, logs[0].count) + assertEquals("10.0.0.1", logs[1].device) + } } diff --git a/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt b/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt index 5c4c4bcf..35a17164 100644 --- a/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt +++ b/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt @@ -17,11 +17,24 @@ class DeviceQuirksTest { assertTrue(ids(DeviceIdentity("AirPlay2", "WiiM Pro Plus")).isEmpty()) } - @Test fun matchesShairportOnAirPlay2Only() { + @Test fun matchesShairportPerAirPlayVersion() { assertEquals(listOf("shairport-airplay2-ptp"), ids(DeviceIdentity("AirPlay2", "Kitchen", "ShairportSync"))) - assertTrue(ids(DeviceIdentity("AirPlay", "Kitchen", "ShairportSync")).isEmpty()) + assertEquals(listOf("shairport-airplay1"), ids(DeviceIdentity("AirPlay", "Kitchen", "ShairportSync"))) } + @Test fun sonosMatchesByProtocol() { + assertEquals(listOf("sonos-airplay2"), ids(DeviceIdentity("AirPlay2", "Living", "Sonos Play:5"))) + assertEquals(listOf("sonos-dlna"), ids(DeviceIdentity("DLNA", "Living", "Play:5", "Sonos, Inc."))) + assertTrue(ids(DeviceIdentity("Google Cast", "Living", "Sonos Play:5")).isEmpty()) + } + + @Test fun onlyEntriesWithAMessageReachTheDoctor() { + assertEquals(listOf("wiim-dlna-restart"), DeviceQuirks.notesFor(wiimDevice).map { it.id }) + assertTrue(DeviceQuirks.notesFor(DeviceIdentity("DLNA", "Living", "Play:5", "Sonos, Inc.")).isEmpty()) + } + + private val wiimDevice = DeviceIdentity("DLNA", "Den", "WiiM Pro Plus", "Linkplay") + @Test fun ordinarySpeakersMatchNothing() { assertTrue(ids(DeviceIdentity("Google Cast", "Nest Mini", "Google Home Mini")).isEmpty()) assertTrue(ids(DeviceIdentity("AirPlay2", "HomePod", "AudioAccessory5,1")).isEmpty()) diff --git a/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt b/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt new file mode 100644 index 00000000..e208fb86 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt @@ -0,0 +1,74 @@ +package com.aria.ariacast.quirks + +import com.aria.ariacast.PacketDirection +import com.aria.ariacast.PacketLog +import com.aria.ariacast.PacketType +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class SpeakerReportTest { + private fun line(message: String, device: String? = null, count: Int = 1, time: String = "10:00:00.000") = + PacketLog(time, PacketDirection.OUT, PacketType.HANDSHAKE, message, 0, count, device) + + // PacketLogger keeps the newest line first. + private fun logs(vararg oldestFirst: PacketLog) = oldestFirst.toList().asReversed() + + private val context = SpeakerReport.Context(app = "AriaCast 2.0.0", android = "14 (API 34)", device = "Google Pixel 8") + private val wiim = DeviceIdentity("DLNA", "Den", "WiiM Pro Plus", "Linkplay") + + @Test fun addressesAreShortenedButVersionsAreNot() { + assertEquals("http://192.168.x.x:8092/s and 10.0.x.x", SpeakerReport.maskAddresses("http://192.168.1.20:8092/s and 10.0.3.4")) + assertEquals("version 1.1.9 and 2.0.0", SpeakerReport.maskAddresses("version 1.1.9 and 2.0.0")) + } + + @Test fun keepsTaggedLinesAndLinesThatNameTheSpeakerOldestFirst() { + val result = SpeakerReport.logFor( + logs( + line("first, tagged", device = "10.0.0.5", time = "1"), + line("unrelated", device = "10.0.0.9", time = "2"), + line("[AirPlay2Client] 10.0.0.5 info: model=X", time = "3"), + line("Added Den to the cast", time = "4"), + line("no speaker here", time = "5"), + ), + host = "10.0.0.5", name = "Den", + ) + assertEquals(listOf("first, tagged", "[AirPlay2Client] 10.0.0.5 info: model=X", "Added Den to the cast"), result.map { it.message }) + } + + @Test fun anEmptyNameDoesNotMatchEverything() { + val result = SpeakerReport.logFor(logs(line("anything")), host = "10.0.0.5", name = "") + assertTrue(result.isEmpty()) + } + + @Test fun keepsOnlyTheNewestLines() { + val many = (1..SpeakerReport.MAX_LOG_LINES + 50).map { line("n$it", device = "h", time = "$it") } + val result = SpeakerReport.logFor(many.asReversed(), host = "h", name = "") + assertEquals(SpeakerReport.MAX_LOG_LINES, result.size) + assertEquals("n${SpeakerReport.MAX_LOG_LINES + 50}", result.last().message) + assertEquals("n51", result.first().message) + } + + @Test fun reportListsEverythingAndHidesAddresses() { + val text = SpeakerReport.build( + SpeakerReport.Context("AriaCast 2.0.0", "14 (API 34)", "Google Pixel 8", castState = "ERROR, last error: boom", settings = "delay=350 ms"), + wiim, "192.168.1.20", DeviceQuirks.matching(wiim), + logs(line("Audio socket connected to Den (192.168.1.20:12889)", device = "192.168.1.20", count = 3, time = "10:00:01.250")), + ) + assertTrue(text.contains("App: AriaCast 2.0.0")) + assertTrue(text.contains("Phone: Google Pixel 8, Android 14 (API 34)")) + assertTrue(text.contains("Speaker: protocol=DLNA, manufacturer=Linkplay, model=WiiM Pro Plus, name=Den")) + assertTrue(text.contains("Known: WiiM (tested on Pro Plus), DLNA: Works")) + assertTrue(text.contains("Cast: ERROR, last error: boom")) + assertTrue(text.contains("Settings: delay=350 ms")) + assertTrue(text.contains("10:00:01.250 OUT HANDSHAKE x3 Audio socket connected to Den (192.168.x.x:12889)")) + assertFalse(text.contains("192.168.1.20")) + } + + @Test fun aSpeakerNeverCastToStillGetsAReport() { + val text = SpeakerReport.build(context, DeviceIdentity("AirPlay2", "Bedroom", "Strange1,1"), "10.0.0.7", emptyList(), emptyList()) + assertTrue(text.contains("Known: nothing recorded for this speaker yet")) + assertTrue(text.contains("No log lines for this speaker")) + } +} diff --git a/app/src/test/java/com/aria/ariacast/quirks/SpeakersDoc.kt b/app/src/test/java/com/aria/ariacast/quirks/SpeakersDoc.kt new file mode 100644 index 00000000..71e29ad3 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakersDoc.kt @@ -0,0 +1,42 @@ +package com.aria.ariacast.quirks + +/** Renders the known-speaker table as docs/SPEAKERS.md. */ +object SpeakersDoc { + fun render(): String = buildString { + appendLine("# Known speakers") + appendLine() + appendLine("") + appendLine() + appendLine("How speakers behave with AriaCast, what you see when something is wrong, and what to do.") + appendLine("Only behavior with evidence is listed; a speaker that is not here is untested, not broken.") + appendLine() + for (verdict in Verdict.entries) { + appendLine("## ${verdict.label}") + appendLine() + val rows = DeviceQuirks.ALL.filter { it.verdict == verdict } + if (rows.isEmpty()) { + appendLine("Nothing recorded yet.") + appendLine() + continue + } + appendLine("| Speaker | Protocol | If it goes wrong | What to do | Since | Evidence |") + appendLine("|---|---|---|---|---|---|") + rows.forEach { k -> + appendLine( + "| ${cell(k.speaker)} | ${cell(k.protocol)} | ${cell(k.symptoms.joinToString("
"))} | " + + "${cell(k.whatToDo ?: "")} | ${cell(k.since ?: "")} | ${cell(k.evidence)} |" + ) + } + appendLine() + } + appendLine("## Add a speaker") + appendLine() + appendLine("Long-press the speaker in the Send tab and choose **Report speaker** (or use the button in the") + appendLine("connection doctor). It shares who the speaker is and the log lines about it, with addresses") + appendLine("shortened. Paste that into a [new issue](https://github.com/AriaCast/AriaCast-app/issues/new) and") + appendLine("say whether it worked.") + } + + private fun cell(text: String) = text.replace("|", "\\|").replace("\n", " ") +} diff --git a/app/src/test/java/com/aria/ariacast/quirks/SpeakersDocTest.kt b/app/src/test/java/com/aria/ariacast/quirks/SpeakersDocTest.kt new file mode 100644 index 00000000..2840abe3 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakersDocTest.kt @@ -0,0 +1,32 @@ +package com.aria.ariacast.quirks + +import java.io.File +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class SpeakersDocTest { + // Unit tests run from the module directory (app/). + private val file = File("../docs/SPEAKERS.md") + + @Test fun docIsInSyncWithTheTable() { + val expected = SpeakersDoc.render() + if (System.getenv("UPDATE_SPEAKERS_DOC") == "1") file.writeText(expected) + assertEquals( + "docs/SPEAKERS.md is out of date. Regenerate it with: " + + "UPDATE_SPEAKERS_DOC=1 ./gradlew :app:testGithubDebugUnitTest --tests '*SpeakersDocTest*'", + expected, file.readText(), + ) + } + + @Test fun entriesAreUniqueAndBackedByEvidence() { + assertEquals(DeviceQuirks.ALL.size, DeviceQuirks.ALL.map { it.id }.toSet().size) + DeviceQuirks.ALL.forEach { assertTrue("${it.id} has no evidence", it.evidence.isNotBlank()) } + } + + @Test fun anythingThatIsNotPlainGoodSaysWhatTheUserWillSee() { + DeviceQuirks.ALL.filter { it.verdict != Verdict.GOOD }.forEach { + assertTrue("${it.id} lists no symptoms", it.symptoms.isNotEmpty()) + } + } +} diff --git a/docs/ROADMAP-2.0.md b/docs/ROADMAP-2.0.md index 58f9f68e..37c43540 100644 --- a/docs/ROADMAP-2.0.md +++ b/docs/ROADMAP-2.0.md @@ -31,7 +31,7 @@ this section before releasing. | Cast mirroring (libcast), AirPlay mirroring | Not done | | | Sleep timer with fades, per-speaker EQ/loudness, saved per-speaker delay | Done | `MasterGain`, `SpeakerDsp`. Sendspin speakers aren't shaped (the server pulls the stream) | | Per-app routing | Not done | Spike | -| Quirk profiles | Partial | `DeviceQuirks`: notes in the doctor for WiiM (DLNA) and shairport-sync (AirPlay 2); more entries come from "Copy report" | +| Quirk profiles, "report my device" | Done | `DeviceQuirks` table, published as `docs/SPEAKERS.md`; "Report speaker" shares identity and the speaker's log lines. The list only holds speakers with evidence, so it grows from reports | | Home Assistant `media_player`, auto-cast on speaker appearance | Not done | | | Ktor 3 | Not done | Client and server on 2.3.8 | | Retire the standalone receiver repo | Not done | Needs a final release there pointing to AriaCast | diff --git a/docs/SPEAKERS.md b/docs/SPEAKERS.md new file mode 100644 index 00000000..e0eabb40 --- /dev/null +++ b/docs/SPEAKERS.md @@ -0,0 +1,34 @@ +# Known speakers + + + +How speakers behave with AriaCast, what you see when something is wrong, and what to do. +Only behavior with evidence is listed; a speaker that is not here is untested, not broken. + +## Works + +| Speaker | Protocol | If it goes wrong | What to do | Since | Evidence | +|---|---|---|---|---|---| +| Sonos (tested on Play:5) | AirPlay 2 | On 1.1.9 the AirPlay 2 stream did not play, while DLNA to the same speaker did. | Update. Until then, cast to it over DLNA. | 1.1.9_hotfix | [#48](https://github.com/AriaCast/AriaCast-app/issues/48), confirmed by the reporter after the hotfix | +| Sonos (tested on Play:5) | DLNA | | | | [#48](https://github.com/AriaCast/AriaCast-app/issues/48), reporter: DLNA was working | +| WiiM (tested on Pro Plus) | DLNA | The track title changes but playback stays paused at 0:00 after every track change.
Pressing play in the WiiM app starts it again. | Update: AriaCast now sends Play after every track change. If it still stops, press play once in the WiiM app and report it. | 2.0.0 | [#50](https://github.com/AriaCast/AriaCast-app/issues/50), fixed in the 2.0 line; the reporter's confirmation is not recorded | +| shairport-sync | AirPlay 1 | | | | Maintainer's own test in [#48](https://github.com/AriaCast/AriaCast-app/issues/48); the AirPlay version is not stated there, so it is listed under AirPlay 1 | + +## Works with a catch + +| Speaker | Protocol | If it goes wrong | What to do | Since | Evidence | +|---|---|---|---|---|---| +| shairport-sync | AirPlay 2 | The speaker accepts the connection but timing is off, or AriaCast drops to AirPlay 1. | Nothing to do: AriaCast tries NTP timing and falls back to AirPlay 1 on its own. Real PTP needs root. | | Code: PtpMaster (shairport-sync with nqptp accepts only PTP timing) | +| Apple TV | AirPlay (video) | On Apple TVs that require pairing, casting a video fails with "This AirPlay device requires pairing for video". Audio casting is not affected. | Cast audio only. Video works with Apple TVs that allow unpaired access. | | Roadmap status table and VideoTargets.kt | + +## Does not work + +Nothing recorded yet. + +## Add a speaker + +Long-press the speaker in the Send tab and choose **Report speaker** (or use the button in the +connection doctor). It shares who the speaker is and the log lines about it, with addresses +shortened. Paste that into a [new issue](https://github.com/AriaCast/AriaCast-app/issues/new) and +say whether it worked. From 0812eaa74bf23500249a031ec22f7fef851d6f6d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 10:12:47 +0000 Subject: [PATCH 03/14] Log what speakers do, per speaker - PacketLogger tags each line with the speaker it is about, by default from the coroutine it runs in (DeviceContext), and keeps a history per speaker (400 lines, up to 32 speakers) beside the global 500, so a chatty speaker cannot evict another's. Report speaker reads from it. - Session start and end lines, with the speaker's identity and how it ended. - DLNA: status and timing of Stop/SetAVTransportURI/Play/SetVolume, the UPnP fault when refused, who fetches the stream and for how long, and the renderer's transport state after Play and on every change. - Google Cast: player state changes with the idle reason. - AriaCast: the receiver's handshake, connection lifetime, reconnects and the receiver's underrun/overrun counts. Volume failures that were swallowed are now logged. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01XZTMETapPkNvc9xdPLcfZu --- CHANGELOG.md | 10 + .../com/aria/ariacast/AudioCastService.kt | 207 ++++++++++++++---- .../java/com/aria/ariacast/DeviceContext.kt | 17 ++ .../java/com/aria/ariacast/PacketLogger.kt | 80 ++++++- .../java/com/aria/ariacast/cast/CastClient.kt | 4 + .../main/java/com/aria/ariacast/dlna/Dlna.kt | 17 ++ .../com/aria/ariacast/quirks/SpeakerReport.kt | 2 +- .../aria/ariacast/ui/SpeakerReportAction.kt | 2 +- .../com/aria/ariacast/DeviceContextTest.kt | 62 ++++++ .../com/aria/ariacast/PacketLoggerTest.kt | 51 +++++ .../java/com/aria/ariacast/dlna/DlnaTest.kt | 23 ++ 11 files changed, 425 insertions(+), 50 deletions(-) create mode 100644 app/src/main/java/com/aria/ariacast/DeviceContext.kt create mode 100644 app/src/test/java/com/aria/ariacast/DeviceContextTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 7eca37e8..fe74ce8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,16 @@ casting, a new interface, and AriaCompanion 2. generated from the same table the app uses, and a test fails if the two drift apart. The connection doctor shows a note while you cast to a speaker with a documented quirk (WiiM over DLNA, shairport-sync over AirPlay 2). DLNA speakers now report manufacturer and model. +- **More speaker logging**: every line logged while casting to a speaker is now attributed to it, + and each speaker keeps its own history, so a chatty one can't push another's out. New lines: + session start and end (with the speaker's model and why it ended); for DLNA the HTTP status and + timing of every Stop, SetAVTransportURI, Play and SetVolume, the UPnP error when a renderer + refuses, what the renderer does with the stream (its user-agent, how long it listened), and + its transport state (`PLAYING`, `PAUSED_PLAYBACK`, `STOPPED`) a moment after Play and on every + change; for Google Cast every player state change and why it went idle; for AriaCast the + receiver's handshake, how long a connection lasted and each reconnect, and the receiver's own + underrun and overrun counts. DLNA speakers are asked their state every 10 seconds while you + cast to them, which is one small request. - **Report speaker**: long-press a speaker (or use the doctor) to share a report with who the speaker is, what is known about it, the cast state and its log lines, with addresses shortened. Works for speakers you never managed to connect to. diff --git a/app/src/main/java/com/aria/ariacast/AudioCastService.kt b/app/src/main/java/com/aria/ariacast/AudioCastService.kt index b6186b15..349cd938 100644 --- a/app/src/main/java/com/aria/ariacast/AudioCastService.kt +++ b/app/src/main/java/com/aria/ariacast/AudioCastService.kt @@ -32,6 +32,7 @@ import android.os.Binder import android.os.Build import android.os.IBinder import android.os.PowerManager +import android.os.SystemClock import android.util.DisplayMetrics import android.util.Log import android.view.WindowManager @@ -87,6 +88,8 @@ import com.aria.ariacast.pipeline.ProjectionCaptureSource import com.aria.ariacast.pipeline.SourceKind import com.aria.ariacast.pipeline.SpeakerDsp import com.aria.ariacast.pipeline.SpeakerSound +import com.aria.ariacast.dlna.Dlna +import com.aria.ariacast.quirks.DeviceIdentity import com.aria.ariacast.receiver.ReceiverHub import com.aria.ariacast.sendspin.SendspinHub import com.aria.ariacast.pipeline.PcmFormat @@ -675,7 +678,10 @@ class AudioCastService : Service() { private fun destKey(d: CastDestination) = "${d.platform}|${d.host}|${d.port}" private fun launchDestination(scope: CoroutineScope, dest: CastDestination, withVideo: Boolean) { - destinationJobs[destKey(dest)] = scope.launch { + val started = SystemClock.elapsedRealtime() + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, + "Session start: ${DeviceIdentity.of(dest.platform, dest.name, dest.extra).reportLine()}, address=${dest.host}:${dest.port}", device = dest.host) + val job = scope.launch(DeviceContext.element(dest.host)) { when (dest.platform) { "DLNA" -> startDlnaSession(dest) "Google Cast" -> startGoogleCastSession(dest) @@ -692,6 +698,16 @@ class AudioCastService : Service() { } } } + job.invokeOnCompletion { cause -> + val how = when (cause) { + null -> "finished" + is CancellationException -> "stopped" + else -> "failed: ${cause.message ?: cause.javaClass.simpleName}" + } + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, + "Session end: ${dest.name} after ${(SystemClock.elapsedRealtime() - started) / 1000} s ($how)", device = dest.host) + } + destinationJobs[destKey(dest)] = job } /** @@ -749,6 +765,10 @@ class AudioCastService : Service() { while (isActive) { val clientSocket = try { serverSocket.accept() } catch (e: Exception) { null } ?: continue launch { + val peer = clientSocket.inetAddress?.hostAddress + var streamStarted = 0L + var streamedBytes = 0L + var streamEnd = "cast stopped" try { clientSocket.setTcpNoDelay(true) clientSocket.soTimeout = 30000 @@ -774,6 +794,8 @@ class AudioCastService : Service() { ua.contains("libmpv", ignoreCase = true) val contentType = if (isApple) "audio/x-wav" else "audio/wav" + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, + "Stream request from $peer: $requestLine, user-agent=\"${ua.take(80)}\"${headers["range"]?.let { ", range=$it" } ?: ""}, answering $contentType", device = peer) val responseHeaders = StringBuilder() responseHeaders.append("HTTP/1.1 200 OK\r\n") @@ -792,6 +814,7 @@ class AudioCastService : Service() { if (requestLine.startsWith("HEAD")) { output.flush() + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Answered a HEAD request from $peer", device = peer) return@launch } @@ -814,19 +837,27 @@ class AudioCastService : Service() { } output.write(header.array()) - val dsp = dspFor(clientSocket.inetAddress?.hostAddress ?: "") + val dsp = dspFor(peer ?: "") + streamStarted = SystemClock.elapsedRealtime() + PacketLogger.log(PacketDirection.OUT, PacketType.AUDIO, "Streaming to $peer", device = peer) audioBufferFlow.collect { raw -> val buffer = dsp.process(raw) try { output.write(buffer) output.flush() + streamedBytes += buffer.size } catch (e: Exception) { + streamEnd = "write failed: ${e.message ?: e.javaClass.simpleName}" throw CancellationException("Client disconnected") } } } catch (e: Exception) { Log.d(TAG, "Streaming session ended: ${e.message}") } finally { + if (streamStarted != 0L) { + PacketLogger.log(PacketDirection.IN, PacketType.AUDIO, + "Stream to $peer ended after ${(SystemClock.elapsedRealtime() - streamStarted) / 1000} s, ${streamedBytes / 1024} KB sent ($streamEnd)", device = peer) + } try { clientSocket.close() } catch (e: Exception) {} } } @@ -839,6 +870,77 @@ class AudioCastService : Service() { } } + /** + * Posts one SOAP action to a renderer and logs what came back: the HTTP status, how long it + * took and the UPnP error if it sent one. Network errors are logged and rethrown; an HTTP + * error status is only logged, as it always was. + */ + private suspend fun dlnaSoap(dest: CastDestination, url: String, service: String, action: String, body: String): HttpResponse { + val started = SystemClock.elapsedRealtime() + try { + val response = client.post(url) { + header("SoapAction", "\"urn:schemas-upnp-org:service:$service:1#$action\"") + contentType(ContentType.parse("text/xml; charset=utf-8")) + setBody(body) + } + val ms = SystemClock.elapsedRealtime() - started + val fault = if (response.status.isSuccess()) null else runCatching { Dlna.soapFault(response.bodyAsText()) }.getOrNull() + PacketLogger.log(PacketDirection.OUT, PacketType.CONTROL, + "DLNA $action -> ${response.status.value} in $ms ms${fault?.let { " ($it)" } ?: ""}", device = dest.host) + return response + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + PacketLogger.log(PacketDirection.IN, PacketType.CONTROL, + "DLNA $action failed after ${SystemClock.elapsedRealtime() - started} ms: ${e.message ?: e.javaClass.simpleName}", device = dest.host) + throw e + } + } + + private fun soapEnvelope(service: String, action: String, args: String) = + "" + + "$args" + + /** + * Asks the renderer what it is doing, a moment after Play and then every few seconds, and logs + * every change. "Play was accepted" and "it is playing" are different facts, and renderers + * that stall (paused at 0:00, stopped after a track) only show it here. + */ + private suspend fun watchDlnaTransport(dest: CastDestination, controlUrl: String) { + var last: String? = null + var failures = 0 + delay(DLNA_FIRST_CHECK_MS) + while (currentCoroutineContext().isActive) { + try { + val text = dlnaStateCheck(controlUrl) + val state = Dlna.transportState(text) ?: "unknown" + if (state != last) { + PacketLogger.log(PacketDirection.IN, PacketType.CONTROL, + "DLNA transport state: $state${last?.let { " (was $it)" } ?: ""}", device = dest.host) + last = state + } + failures = 0 + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + failures++ + if (failures == 1 || failures == DLNA_CHECK_GIVE_UP) { + PacketLogger.log(PacketDirection.IN, PacketType.CONTROL, + "DLNA state check failed ($failures in a row): ${e.message ?: e.javaClass.simpleName}", device = dest.host) + } + if (failures >= DLNA_CHECK_GIVE_UP) return + } + delay(DLNA_CHECK_EVERY_MS) + } + } + + private suspend fun dlnaStateCheck(controlUrl: String): String = + client.post(controlUrl) { + header("SoapAction", "\"urn:schemas-upnp-org:service:AVTransport:1#GetTransportInfo\"") + contentType(ContentType.parse("text/xml; charset=utf-8")) + setBody(soapEnvelope("AVTransport", "GetTransportInfo", "0")) + }.bodyAsText() + private suspend fun startDlnaSession(dest: CastDestination) { val (controlUrl, _) = getDlnaControlUrls(dest.extra) if (controlUrl == null) return @@ -854,37 +956,29 @@ class AudioCastService : Service() { """.trimIndent() - client.post(controlUrl) { - header("SoapAction", "\"urn:schemas-upnp-org:service:AVTransport:1#Stop\"") - contentType(ContentType.parse("text/xml; charset=utf-8")) - setBody(stopBody) - } + dlnaSoap(dest, controlUrl, "AVTransport", "Stop", stopBody) + } catch (e: CancellationException) { + throw e } catch (e: Exception) {} val metadataXml = createDidlMetadata(streamUrl, _metadata.value) val setUriBody = """0${escapeXml(streamUrl)}${escapeXml(metadataXml)}""" - client.post(controlUrl) { - header("SoapAction", "\"urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI\"") - contentType(ContentType.parse("text/xml; charset=utf-8")) - setBody(setUriBody) - } + dlnaSoap(dest, controlUrl, "AVTransport", "SetAVTransportURI", setUriBody) val playBody = """01""" - client.post(controlUrl) { - header("SoapAction", "\"urn:schemas-upnp-org:service:AVTransport:1#Play\"") - contentType(ContentType.parse("text/xml; charset=utf-8")) - setBody(playBody) - } + dlnaSoap(dest, controlUrl, "AVTransport", "Play", playBody) _state.value = CastState.CASTING updateNotification() + watchDlnaTransport(dest, controlUrl) } catch (e: CancellationException) { throw e } catch (e: Exception) { Log.e(TAG, "DLNA session failed for ${dest.name}: ${e.message}") + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "DLNA session failed: ${e.message ?: e.javaClass.simpleName}", device = dest.host) _state.value = CastState.ERROR } } @@ -1464,11 +1558,13 @@ class AudioCastService : Service() { private suspend fun startAudioSession(dest: CastDestination) { var sentFramesCount = 0L var reconnectAttempts = 0 + var connectedAt = 0L while (currentCoroutineContext().isActive) { try { client.webSocket(host = dest.host, port = dest.port, path = "/audio") audioSocket@{ reconnectAttempts = 0 + connectedAt = SystemClock.elapsedRealtime() PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Audio socket connected to ${dest.name} (${dest.host}:${dest.port})", device = dest.host) if (dest.platform != "AriaCast") { @@ -1484,6 +1580,8 @@ class AudioCastService : Service() { PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Unexpected handshake frame type from ${dest.name}", device = dest.host) return@audioSocket } + // The receiver's own words (sample rate, frame size) say what it expects of us. + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Receiver handshake: ${handshakeFrame.readText().take(200)}", device = dest.host) } _state.value = CastState.CASTING @@ -1522,9 +1620,12 @@ class AudioCastService : Service() { } catch (e: Exception) { if (e is CancellationException) throw e Log.e(TAG, "Audio WS connection to ${dest.host}:${dest.port} failed: ${e.message}", e) - PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Audio connection to ${dest.name} failed: ${e.message ?: e.javaClass.simpleName}", device = dest.host) + val upFor = if (connectedAt != 0L) " after ${(SystemClock.elapsedRealtime() - connectedAt) / 1000} s, $sentFramesCount frames sent" else "" + connectedAt = 0L + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Audio connection to ${dest.name} failed$upFor: ${e.message ?: e.javaClass.simpleName}", device = dest.host) reconnectAttempts++ val delayTime = (RECONNECT_INITIAL_BACKOFF * 2.0.pow(reconnectAttempts.toDouble().coerceAtMost(5.0))).toLong() + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Reconnecting to ${dest.name} in $delayTime ms (attempt $reconnectAttempts)", device = dest.host) delay(delayTime) } } @@ -1668,14 +1769,17 @@ class AudioCastService : Service() { val dB = AirPlayVolume.percentToDb(p) Log.d(TAG, "Setting receiver volume to $p% ($dB dB)") scope.launch { - val airplay = synchronized(airplayStreamers) { airplayStreamers.values.toList() } - airplay.forEach { try { it.setVolume(dB) } catch (_: Exception) {} } + PacketLogger.log(PacketDirection.OUT, PacketType.CONTROL, "Volume set to $p%") + val airplay = synchronized(airplayStreamers) { airplayStreamers.toMap() } + airplay.forEach { (host, streamer) -> + try { streamer.setVolume(dB) } catch (e: Exception) { logVolumeFailure(host, "AirPlay", p, e) } + } - val casts = synchronized(castClients) { castClients.values.toList() } - casts.forEach { c -> + val casts = synchronized(castClients) { castClients.toMap() } + casts.forEach { (host, c) -> try { if (p == 0) c.setMuted(true) else { if (c.muted) c.setMuted(false); c.setVolume(p / 100.0) } - } catch (_: Exception) {} + } catch (e: Exception) { logVolumeFailure(host, "Google Cast", p, e) } } val controlSnapshot = synchronized(controlSessions) { controlSessions.values.toList() } @@ -1690,7 +1794,7 @@ class AudioCastService : Service() { _activeDestinations.value.filter { it.platform == "DLNA" }.forEach { dest -> val (_, rcUrl) = getDlnaControlUrls(dest.extra) - if (rcUrl != null) setDlnaVolume(rcUrl, p) + if (rcUrl != null) setDlnaVolume(dest.host, rcUrl, p) } } } @@ -1708,15 +1812,28 @@ class AudioCastService : Service() { PacketLogger.log(PacketDirection.IN, PacketType.CONTROL, "Receiver volume changed to $p%") } - private suspend fun setDlnaVolume(rcUrl: String, percent: Int) { + private fun logVolumeFailure(host: String, protocol: String, percent: Int, e: Exception) { + PacketLogger.log(PacketDirection.OUT, PacketType.CONTROL, + "$protocol volume $percent% failed: ${e.message ?: e.javaClass.simpleName}", device = host) + } + + private suspend fun setDlnaVolume(host: String, rcUrl: String, percent: Int) { try { val body = """0Master$percent""" - client.post(rcUrl) { + val response = client.post(rcUrl) { header("SoapAction", "\"urn:schemas-upnp-org:service:RenderingControl:1#SetVolume\"") contentType(ContentType.parse("text/xml; charset=utf-8")) setBody(body) } - } catch (_: Exception) {} + if (!response.status.isSuccess()) { + PacketLogger.log(PacketDirection.OUT, PacketType.CONTROL, + "DLNA SetVolume($percent) -> ${response.status.value}${runCatching { Dlna.soapFault(response.bodyAsText()) }.getOrNull()?.let { " ($it)" } ?: ""}", device = host) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + PacketLogger.log(PacketDirection.OUT, PacketType.CONTROL, "DLNA SetVolume($percent) failed: ${e.message ?: e.javaClass.simpleName}", device = host) + } } private val _speakerSounds = MutableStateFlow>(emptyMap()) @@ -1886,20 +2003,14 @@ class AudioCastService : Service() { try { val body = """0${escapeXml(streamUrl)}${escapeXml(metadataXml)}""" - client.post(avUrl) { - header("SoapAction", "\"urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI\"") - contentType(ContentType.parse("text/xml; charset=utf-8")) - setBody(body) - } + dlnaSoap(dest, avUrl, "AVTransport", "SetAVTransportURI", body) // SetAVTransportURI resets many renderers (e.g. WiiM) to a stopped state, // so playback must be restarted explicitly or it stays paused at 0:00. val playBody = """01""" - client.post(avUrl) { - header("SoapAction", "\"urn:schemas-upnp-org:service:AVTransport:1#Play\"") - contentType(ContentType.parse("text/xml; charset=utf-8")) - setBody(playBody) - } + dlnaSoap(dest, avUrl, "AVTransport", "Play", playBody) + } catch (e: CancellationException) { + throw e } catch (e: Exception) { Log.e(TAG, "Failed to update DLNA metadata: ${e.message}") } @@ -2000,6 +2111,9 @@ class AudioCastService : Service() { } private suspend fun startStatsSession(dest: CastDestination) { + var lastLoggedAt = 0L + var lastUnderruns = -1 + var lastOverruns = -1 while (currentCoroutineContext().isActive) { try { client.webSocket(host = dest.host, port = dest.port, path = "/stats") statsSocket@{ @@ -2012,6 +2126,17 @@ class AudioCastService : Service() { bufferedFrames = json.optInt("bufferedFrames"), receivedFrames = json.optInt("receivedFrames") ) + // Not every receiver reports underruns and overruns; -1 means it did not. + val underruns = json.optInt("underruns", -1) + val overruns = json.optInt("overruns", -1) + val now = SystemClock.elapsedRealtime() + if (now - lastLoggedAt >= RECEIVER_STATS_LOG_MS || underruns != lastUnderruns || overruns != lastOverruns) { + lastLoggedAt = now; lastUnderruns = underruns; lastOverruns = overruns + PacketLogger.log(PacketDirection.IN, PacketType.STATS, + "Receiver stats: received=${json.optInt("receivedFrames")}, buffered=${json.optInt("bufferedFrames")}" + + (if (underruns >= 0) ", underruns=$underruns" else "") + (if (overruns >= 0) ", overruns=$overruns" else ""), + device = dest.host) + } updateNotification() } else if (frame == null) { return@statsSocket @@ -2365,6 +2490,14 @@ class AudioCastService : Service() { const val VIDEO_IFRAME_INTERVAL = 2 private const val RECONNECT_INITIAL_BACKOFF = 1000L + + /** First look at a DLNA renderer's state after Play, then how often to look again. */ + private const val DLNA_FIRST_CHECK_MS = 1500L + private const val DLNA_CHECK_EVERY_MS = 10_000L + private const val DLNA_CHECK_GIVE_UP = 5 + + /** How often the receiver's own counters (buffer level, underruns) are written to the log. */ + private const val RECEIVER_STATS_LOG_MS = 30_000L private const val STATS_TIMEOUT = 10000L private const val ARTWORK_PORT = 8090 private const val STREAM_PORT = 8091 diff --git a/app/src/main/java/com/aria/ariacast/DeviceContext.kt b/app/src/main/java/com/aria/ariacast/DeviceContext.kt new file mode 100644 index 00000000..cc98bbf7 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/DeviceContext.kt @@ -0,0 +1,17 @@ +package com.aria.ariacast + +import kotlinx.coroutines.ThreadContextElement +import kotlinx.coroutines.asContextElement + +/** + * Which speaker the running code is working for. [PacketLogger] tags every line it logs with + * this, so a speaker's log needs no per-call bookkeeping: code that runs inside + * `launch(DeviceContext.element(host))`, including coroutines it starts, is attributed to that + * speaker. Code on threads outside a coroutine (a protocol client's own sender thread) is not, + * and falls back to matching the speaker's address or name in the text. + */ +object DeviceContext { + val current = ThreadLocal() + + fun element(host: String): ThreadContextElement = current.asContextElement(host) +} diff --git a/app/src/main/java/com/aria/ariacast/PacketLogger.kt b/app/src/main/java/com/aria/ariacast/PacketLogger.kt index 09c8ebf0..d83d749d 100644 --- a/app/src/main/java/com/aria/ariacast/PacketLogger.kt +++ b/app/src/main/java/com/aria/ariacast/PacketLogger.kt @@ -3,8 +3,11 @@ package com.aria.ariacast import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import java.text.SimpleDateFormat +import java.util.ArrayDeque import java.util.Date +import java.util.LinkedHashMap import java.util.Locale +import java.util.concurrent.atomic.AtomicLong enum class PacketDirection { IN, OUT } enum class PacketType { AUDIO, CONTROL, METADATA, STATS, HANDSHAKE } @@ -18,12 +21,30 @@ data class PacketLog( var count: Int = 1, /** Host of the speaker this line is about, when it is about one (used by "Report speaker"). */ val device: String? = null, + /** Order the line was logged in; repeats of a line keep the number of its first occurrence. */ + val seq: Long = 0, ) object PacketLogger { + /** Lines kept for the packet log screen, all speakers together, newest first. */ + const val GLOBAL_LIMIT = 500 + + /** Lines kept per speaker, so a chatty speaker cannot push another one's history out. */ + const val DEVICE_LIMIT = 400 + + /** Speakers whose history is kept; the least recently logged is dropped beyond this. */ + private const val DEVICE_COUNT_LIMIT = 32 + private val _logs = mutableListOf() val logs: List get() = synchronized(_logs) { _logs.toList() } + // Newest first, access-ordered so the speaker that has been quiet longest is the one dropped. + private val perDevice = object : LinkedHashMap>(16, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry>) = size > DEVICE_COUNT_LIMIT + } + + private val sequence = AtomicLong() + private val _logFlow = MutableSharedFlow(extraBufferCapacity = 100) val logFlow = _logFlow.asSharedFlow() @@ -34,7 +55,17 @@ object PacketLogger { override fun initialValue(): SimpleDateFormat = SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault()) } - fun log(direction: PacketDirection, type: PacketType, message: String, payloadSize: Int = 0, device: String? = null) { + /** + * [device] defaults to the speaker the calling code is working for (see [DeviceContext]), so + * lines logged inside a speaker's session are attributed to it without saying so. + */ + fun log( + direction: PacketDirection, + type: PacketType, + message: String, + payloadSize: Int = 0, + device: String? = DeviceContext.current.get(), + ) { val timestamp = dateFormat.get()!!.format(Date()) val entry = PacketLog( timestamp = timestamp, @@ -43,32 +74,59 @@ object PacketLogger { message = message, payloadSize = payloadSize, device = device, + seq = sequence.incrementAndGet(), ) - + synchronized(_logs) { val lastLog = _logs.firstOrNull() - if (lastLog != null && - lastLog.direction == direction && - lastLog.type == type && - lastLog.message == message && - lastLog.device == device) { + if (lastLog != null && lastLog.sameLine(entry)) { lastLog.count++ lastLog.timestamp = timestamp - // We still emit it to let the UI know something happened, + // We still emit it to let the UI know something happened, // but we need a way to distinguish between "new" and "update". - // For simplicity, we'll let the adapter handle the merging logic + // For simplicity, we'll let the adapter handle the merging logic // since it maintains its own list anyway. } else { _logs.add(0, entry) - if (_logs.size > 500) _logs.removeAt(_logs.size - 1) + if (_logs.size > GLOBAL_LIMIT) _logs.removeAt(_logs.size - 1) + } + + if (device != null) { + val ring = perDevice.getOrPut(device) { ArrayDeque() } + val last = ring.peekFirst() + if (last != null && last.sameLine(entry)) { + last.count++ + last.timestamp = timestamp + } else { + // A copy, because repeats are counted per list and each list counts its own. + ring.addFirst(entry.copy()) + if (ring.size > DEVICE_LIMIT) ring.removeLast() + } } } _logFlow.tryEmit(entry) } - + + /** + * Every line about one speaker, newest first: its own history plus untagged lines (written by + * threads outside its session) that name its address or its name. + */ + fun logsFor(host: String, name: String): List = synchronized(_logs) { + val own = perDevice[host]?.map { it.copy() } ?: emptyList() + val mentioned = _logs.filter { line -> + line.device == null && + ((host.isNotEmpty() && line.message.contains(host)) || (name.isNotEmpty() && line.message.contains(name))) + }.map { it.copy() } + (own + mentioned).sortedByDescending { it.seq } + } + fun clear() { synchronized(_logs) { _logs.clear() + perDevice.clear() } } + + private fun PacketLog.sameLine(other: PacketLog) = + direction == other.direction && type == other.type && message == other.message && device == other.device } diff --git a/app/src/main/java/com/aria/ariacast/cast/CastClient.kt b/app/src/main/java/com/aria/ariacast/cast/CastClient.kt index 9ee29c9f..1b47ce77 100644 --- a/app/src/main/java/com/aria/ariacast/cast/CastClient.kt +++ b/app/src/main/java/com/aria/ariacast/cast/CastClient.kt @@ -231,6 +231,10 @@ class CastClient( val state = status.str("playerState") ?: return val previous = playerState playerState = state + if (previous != state) { + val reason = status.str("idleReason")?.let { " (idleReason=$it)" } ?: "" + ProtoLog.i(TAG, "$host: player state ${previous ?: "-"} -> $state$reason") + } if (state == expectedState) { expectedState = null; return } if (previous != null && previous != state) { when (state) { diff --git a/app/src/main/java/com/aria/ariacast/dlna/Dlna.kt b/app/src/main/java/com/aria/ariacast/dlna/Dlna.kt index e2f8dd35..32ecf0dc 100644 --- a/app/src/main/java/com/aria/ariacast/dlna/Dlna.kt +++ b/app/src/main/java/com/aria/ariacast/dlna/Dlna.kt @@ -89,6 +89,23 @@ ${service("ConnectionManager")} Regex("<(?:\\w+:)?$name(?:\\s[^>]*)?>([\\s\\S]*?)").find(body)?.groupValues?.get(1) ?: if (Regex("<(?:\\w+:)?$name\\s*/>").containsMatchIn(body)) "" else null + /** + * The UPnP error a renderer reports in a SOAP fault, e.g. `701 Transition not available`, or + * null when the body is not a fault. The text is the device's own, so it is only ever logged. + */ + fun soapFault(body: String): String? { + val code = arg(body, "errorCode")?.trim()?.takeIf { it.isNotEmpty() } ?: return null + val description = arg(body, "errorDescription")?.let(::xmlUnescape)?.trim()?.takeIf { it.isNotEmpty() } + return if (description != null) "UPnP error $code: ${description.take(120)}" else "UPnP error $code" + } + + /** Transport state and status from a GetTransportInfo reply, as `PLAYING` or `STOPPED/ERROR_OCCURRED`. */ + fun transportState(body: String): String? { + val state = arg(body, "CurrentTransportState")?.trim()?.takeIf { it.isNotEmpty() } ?: return null + val status = arg(body, "CurrentTransportStatus")?.trim()?.takeIf { it.isNotEmpty() && it != "OK" } + return if (status != null) "$state/$status" else state + } + fun xmlEscape(s: String) = s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """) fun xmlUnescape(s: String) = s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&") diff --git a/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt b/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt index 57afe4f2..c16f94c0 100644 --- a/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt +++ b/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt @@ -8,7 +8,7 @@ import com.aria.ariacast.PacketLog */ object SpeakerReport { /** Newest lines kept, so a long session does not bury the handshake in noise. */ - const val MAX_LOG_LINES = 300 + const val MAX_LOG_LINES = 500 private val ipv4 = Regex("""\b(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}\b""") diff --git a/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt b/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt index 0d598bde..c33ccf5b 100644 --- a/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt +++ b/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt @@ -41,7 +41,7 @@ fun shareSpeakerReport( identity = identity, host = host, known = DeviceQuirks.matching(identity), - logs = PacketLogger.logs, + logs = PacketLogger.logsFor(host, name), ) val send = Intent(Intent.ACTION_SEND).apply { type = "text/plain" diff --git a/app/src/test/java/com/aria/ariacast/DeviceContextTest.kt b/app/src/test/java/com/aria/ariacast/DeviceContextTest.kt new file mode 100644 index 00000000..9355b03c --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/DeviceContextTest.kt @@ -0,0 +1,62 @@ +package com.aria.ariacast + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class DeviceContextTest { + @Before fun setUp() = PacketLogger.clear() + + private fun deviceOf(message: String) = PacketLogger.logs.first { it.message == message }.device + + @Test fun linesLoggedInsideASpeakersCoroutineAreAttributedToIt() = runBlocking { + withContext(DeviceContext.element("10.0.0.1")) { + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "plain") + withContext(Dispatchers.IO) { PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "on another thread") } + coroutineScope { launch { PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "in a child") } } + } + assertEquals("10.0.0.1", deviceOf("plain")) + assertEquals("10.0.0.1", deviceOf("on another thread")) + assertEquals("10.0.0.1", deviceOf("in a child")) + } + + @Test fun linesOutsideAnySpeakerStayUntagged() = runBlocking { + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "outside") + withContext(DeviceContext.element("10.0.0.1")) { } + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "after") + assertNull(deviceOf("outside")) + assertNull(deviceOf("after")) // the context does not leak onto the thread once the block ends + } + + @Test fun anExplicitHostWins() = runBlocking { + withContext(DeviceContext.element("10.0.0.1")) { + PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "explicit", device = "10.0.0.9") + } + assertEquals("10.0.0.9", deviceOf("explicit")) + } + + @Test fun concurrentSpeakersDoNotMixTheirLines() = runBlocking { + // The messages must not name the host, or the text-matching fallback would find them + // without any tag and this would prove nothing. + val hosts = (1..8).map { "10.0.0.$it" } + hosts.mapIndexed { index, host -> + async(Dispatchers.IO + DeviceContext.element(host)) { + repeat(50) { PacketLogger.log(PacketDirection.OUT, PacketType.AUDIO, "speaker $index line $it") } + } + }.awaitAll() + hosts.forEachIndexed { index, host -> + val lines = PacketLogger.logsFor(host, "") + assertEquals(50, lines.size) + assertTrue(lines.all { it.message.startsWith("speaker $index line ") }) + } + } +} diff --git a/app/src/test/java/com/aria/ariacast/PacketLoggerTest.kt b/app/src/test/java/com/aria/ariacast/PacketLoggerTest.kt index 4ca81342..75a6b954 100644 --- a/app/src/test/java/com/aria/ariacast/PacketLoggerTest.kt +++ b/app/src/test/java/com/aria/ariacast/PacketLoggerTest.kt @@ -93,4 +93,55 @@ class PacketLoggerTest { assertEquals(2, logs[0].count) assertEquals("10.0.0.1", logs[1].device) } + + private fun log(message: String, device: String?) = + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, message, device = device) + + @Test + fun `a chatty speaker cannot push another speaker's history out`() { + log("quiet speaker: connected", "10.0.0.1") + repeat(PacketLogger.GLOBAL_LIMIT + 200) { log("noise $it", "10.0.0.2") } + assertTrue(PacketLogger.logs.none { it.message == "quiet speaker: connected" }) + assertEquals(listOf("quiet speaker: connected"), PacketLogger.logsFor("10.0.0.1", "").map { it.message }) + assertEquals(PacketLogger.DEVICE_LIMIT, PacketLogger.logsFor("10.0.0.2", "").size) + } + + @Test + fun `repeats are merged per speaker even when other speakers log in between`() { + repeat(3) { + log("tick", "10.0.0.1") + log("tock", "10.0.0.2") + } + val a = PacketLogger.logsFor("10.0.0.1", "") + assertEquals(1, a.size) + assertEquals(3, a[0].count) + } + + @Test + fun `logsFor adds untagged lines that name the speaker, in the order they were logged`() { + log("first, tagged", "10.0.0.5") + log("[AirPlay2Client] 10.0.0.5 info: model=X", null) + log("Added Den to the cast", null) + log("about someone else", null) + log("last, tagged", "10.0.0.5") + val lines = PacketLogger.logsFor("10.0.0.5", "Den") + assertEquals( + listOf("last, tagged", "Added Den to the cast", "[AirPlay2Client] 10.0.0.5 info: model=X", "first, tagged"), + lines.map { it.message }, + ) + } + + @Test + fun `only the most recently active speakers are remembered`() { + repeat(40) { log("hello", "10.1.0.$it") } + assertTrue(PacketLogger.logsFor("10.1.0.0", "").isEmpty()) + assertEquals(1, PacketLogger.logsFor("10.1.0.39", "").size) + } + + @Test + fun `clear forgets every speaker`() { + log("hello", "10.0.0.1") + PacketLogger.clear() + assertTrue(PacketLogger.logsFor("10.0.0.1", "").isEmpty()) + } } diff --git a/app/src/test/java/com/aria/ariacast/dlna/DlnaTest.kt b/app/src/test/java/com/aria/ariacast/dlna/DlnaTest.kt index 753c0afb..a4503307 100644 --- a/app/src/test/java/com/aria/ariacast/dlna/DlnaTest.kt +++ b/app/src/test/java/com/aria/ariacast/dlna/DlnaTest.kt @@ -84,4 +84,27 @@ class DlnaTest { assertEquals("http://10.0.0.5:9197/avt", r.avControl) assertEquals(null, r.rcControl) } + + @Test fun soapFaultNamesTheUpnpError() { + val fault = """s:Client +701Transition not available""" + assertEquals("UPnP error 701: Transition not available", Dlna.soapFault(fault)) + assertEquals("UPnP error 718", Dlna.soapFault("718")) + assertEquals(null, Dlna.soapFault("")) + } + + @Test fun soapFaultTextFromADeviceIsTrimmedAndUnescaped() { + val long = "x".repeat(500) + val text = Dlna.soapFault("500a & $long")!! + assertTrue(text.startsWith("UPnP error 500: a & x")) + assertTrue(text.length < 160) + } + + @Test fun transportStateIsReadFromGetTransportInfo() { + fun reply(state: String, status: String) = """ +$state$status1""" + assertEquals("PLAYING", Dlna.transportState(reply("PLAYING", "OK"))) + assertEquals("STOPPED/ERROR_OCCURRED", Dlna.transportState(reply("STOPPED", "ERROR_OCCURRED"))) + assertEquals(null, Dlna.transportState("")) + } } From e82726a70122fcf385dd45fc5f139c16565968c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 10:36:44 +0000 Subject: [PATCH 04/14] Make the known-speakers list a public file the app keeps up to date - data/speakers.json is the single source: shipped as an asset, published as docs/SPEAKERS.md (generated, with a test that fails on drift), and read from GitHub once a day by the app (opt-out, HTTPS only, no redirects, size-limited, must validate and have a higher version). - The file is treated as untrusted: a bad file is refused whole, a bad entry is skipped, every entry needs words to match so it cannot apply to everything, and the only settings it can change are five known ones within fixed limits. - Those settings are wired in: DLNA Play after SetAVTransportURI, DLNA initial Stop, DLNA stream content type, a starting delay, and whether metadata is sent. - Settings -> Known speakers shows the list, by verdict, with symptoms, what to do and evidence. Adds a "not supported" verdict (e.g. Echo Show 5 and Hub). - The doctor's notes come from the list, in the user's language. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01XZTMETapPkNvc9xdPLcfZu --- CHANGELOG.md | 15 +- app/build.gradle.kts | 6 + .../java/com/aria/ariacast/AriaCastApp.kt | 7 + .../com/aria/ariacast/AudioCastService.kt | 48 ++-- .../com/aria/ariacast/quirks/DeviceQuirks.kt | 123 ++-------- .../com/aria/ariacast/quirks/KnownSpeakers.kt | 215 ++++++++++++++++++ .../ariacast/quirks/KnownSpeakersStore.kt | 55 +++++ .../aria/ariacast/quirks/SpeakerListSync.kt | 118 ++++++++++ .../com/aria/ariacast/ui/AppController.kt | 2 +- .../main/java/com/aria/ariacast/ui/AriaApp.kt | 2 + .../aria/ariacast/ui/doctor/DoctorScreen.kt | 4 +- .../ui/settings/KnownSpeakersScreen.kt | 168 ++++++++++++++ .../ariacast/ui/settings/SettingsScreen.kt | 2 + app/src/main/res/values-it/strings.xml | 24 +- app/src/main/res/values/strings.xml | 24 +- .../aria/ariacast/quirks/DeviceQuirksTest.kt | 41 +++- .../ariacast/quirks/KnownSpeakersFileTest.kt | 139 +++++++++++ .../ariacast/quirks/SpeakerListSyncTest.kt | 114 ++++++++++ .../aria/ariacast/quirks/SpeakerReportTest.kt | 3 + .../com/aria/ariacast/quirks/SpeakersDoc.kt | 19 +- .../aria/ariacast/quirks/SpeakersDocTest.kt | 13 +- .../com/aria/ariacast/quirks/TestSpeakers.kt | 14 ++ data/speakers.json | 132 +++++++++++ docs/SPEAKERS.md | 19 +- 24 files changed, 1148 insertions(+), 159 deletions(-) create mode 100644 app/src/main/java/com/aria/ariacast/quirks/KnownSpeakers.kt create mode 100644 app/src/main/java/com/aria/ariacast/quirks/KnownSpeakersStore.kt create mode 100644 app/src/main/java/com/aria/ariacast/quirks/SpeakerListSync.kt create mode 100644 app/src/main/java/com/aria/ariacast/ui/settings/KnownSpeakersScreen.kt create mode 100644 app/src/test/java/com/aria/ariacast/quirks/KnownSpeakersFileTest.kt create mode 100644 app/src/test/java/com/aria/ariacast/quirks/SpeakerListSyncTest.kt create mode 100644 app/src/test/java/com/aria/ariacast/quirks/TestSpeakers.kt create mode 100644 data/speakers.json diff --git a/CHANGELOG.md b/CHANGELOG.md index fe74ce8b..92793fc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,11 +46,16 @@ casting, a new interface, and AriaCompanion 2. AriaCast, AirPlay, Cast, DLNA, Snapcast and VBAN speakers. - **Rooms stay lined up**: each speaker's sync delay is now saved and applied the next time that speaker joins a cast. -- **Known speakers**: [docs/SPEAKERS.md](docs/SPEAKERS.md) lists speakers known to work, to work - with a catch, or not to work, with the symptom to look for, what to do, and the evidence. It is - generated from the same table the app uses, and a test fails if the two drift apart. The - connection doctor shows a note while you cast to a speaker with a documented quirk (WiiM over - DLNA, shairport-sync over AirPlay 2). DLNA speakers now report manufacturer and model. +- **Known speakers**: the list of speakers known to work, to work with a catch, to fail, or that + AriaCast cannot reach is now a public file, [data/speakers.json](data/speakers.json), with + [docs/SPEAKERS.md](docs/SPEAKERS.md) generated from it (a test fails if they drift apart). The app + ships a copy, reads the file from GitHub once a day to stay current (Settings → Known speakers, + where it can be switched off, updated by hand and browsed), and only takes a newer, valid list. + The file can also carry settings for a speaker that needs something different from the usual: + whether DLNA gets a Stop first or a Play after each track, the stream's content type, a starting + delay, and whether titles and artwork are sent. Those five are the only things it can change, each + within fixed limits. The connection doctor shows a note, in your language where the list has one, + while you cast to a speaker with a documented quirk. DLNA speakers now report manufacturer and model. - **More speaker logging**: every line logged while casting to a speaker is now attributed to it, and each speaker keeps its own history, so a chatty one can't push another's out. New lines: session start and end (with the speaker's model and why it ended); for DLNA the HTTP status and diff --git a/app/build.gradle.kts b/app/build.gradle.kts index bb18388b..eeaabeab 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -26,6 +26,12 @@ android { compileSdk = 36 ndkVersion = "27.1.12297006" + // data/speakers.json is both the list of known speakers published for everyone and the copy + // the app ships, so there is one file and no second copy to forget. + sourceSets { + getByName("main") { assets.srcDir(rootProject.file("data")) } + } + // SBC decoder for the AriaCompanion BT board (docs/ariacompanion-bt.md). externalNativeBuild { cmake { diff --git a/app/src/main/java/com/aria/ariacast/AriaCastApp.kt b/app/src/main/java/com/aria/ariacast/AriaCastApp.kt index 36b4b2c8..a4af59e8 100644 --- a/app/src/main/java/com/aria/ariacast/AriaCastApp.kt +++ b/app/src/main/java/com/aria/ariacast/AriaCastApp.kt @@ -2,11 +2,18 @@ package com.aria.ariacast import android.app.Application import android.content.Context +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch class AriaCastApp : Application() { override fun onCreate() { super.onCreate() com.aria.ariacast.airplay.ProtoLog.sink = com.aria.ariacast.airplay.PacketLogSink + com.aria.ariacast.quirks.KnownSpeakersStore.init(this) + // A newer list of known speakers, at most once a day and only if the user keeps this on. + CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { com.aria.ariacast.quirks.SpeakerListSync.syncIfDue(this@AriaCastApp) } val sharedPreferences = getSharedPreferences(AudioCastService.PREFS_NAME, Context.MODE_PRIVATE) val themeMode = sharedPreferences.getInt(SettingsActivity.KEY_THEME, ThemeUtils.MODE_NIGHT_FOLLOW_SYSTEM) ThemeUtils.applyTheme(themeMode) diff --git a/app/src/main/java/com/aria/ariacast/AudioCastService.kt b/app/src/main/java/com/aria/ariacast/AudioCastService.kt index 349cd938..9eff2bd5 100644 --- a/app/src/main/java/com/aria/ariacast/AudioCastService.kt +++ b/app/src/main/java/com/aria/ariacast/AudioCastService.kt @@ -90,6 +90,8 @@ import com.aria.ariacast.pipeline.SpeakerDsp import com.aria.ariacast.pipeline.SpeakerSound import com.aria.ariacast.dlna.Dlna import com.aria.ariacast.quirks.DeviceIdentity +import com.aria.ariacast.quirks.DeviceQuirks +import com.aria.ariacast.quirks.SpeakerConfig import com.aria.ariacast.receiver.ReceiverHub import com.aria.ariacast.sendspin.SendspinHub import com.aria.ariacast.pipeline.PcmFormat @@ -681,6 +683,11 @@ class AudioCastService : Service() { val started = SystemClock.elapsedRealtime() PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, "Session start: ${DeviceIdentity.of(dest.platform, dest.name, dest.extra).reportLine()}, address=${dest.host}:${dest.port}", device = dest.host) + DeviceQuirks.matching(DeviceIdentity.of(dest.platform, dest.name, dest.extra)).takeIf { it.isNotEmpty() }?.let { known -> + val config = configFor(dest) + PacketLogger.log(PacketDirection.OUT, PacketType.HANDSHAKE, + "Known speaker: ${known.joinToString { it.id }}${if (config == SpeakerConfig()) "" else ", settings from the list: $config"}", device = dest.host) + } val job = scope.launch(DeviceContext.element(dest.host)) { when (dest.platform) { "DLNA" -> startDlnaSession(dest) @@ -793,7 +800,8 @@ class AudioCastService : Service() { ua.contains("Darwin", ignoreCase = true) || ua.contains("libmpv", ignoreCase = true) - val contentType = if (isApple) "audio/x-wav" else "audio/wav" + val listed = _activeDestinations.value.firstOrNull { it.host == peer }?.let(::configFor)?.dlnaContentType + val contentType = listed ?: if (isApple) "audio/x-wav" else "audio/wav" PacketLogger.log(PacketDirection.IN, PacketType.HANDSHAKE, "Stream request from $peer: $requestLine, user-agent=\"${ua.take(80)}\"${headers["range"]?.let { ", range=$it" } ?: ""}, answering $contentType", device = peer) @@ -948,18 +956,15 @@ class AudioCastService : Service() { val streamUrl = "http://$myIp:$STREAM_PORT/stream.wav" try { - try { - val stopBody = """ - - - 0 - - - """.trimIndent() - dlnaSoap(dest, controlUrl, "AVTransport", "Stop", stopBody) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) {} + if (configFor(dest).dlnaSkipInitialStop == true) { + PacketLogger.log(PacketDirection.OUT, PacketType.CONTROL, "DLNA Stop skipped (setting from the list)", device = dest.host) + } else { + try { + dlnaSoap(dest, controlUrl, "AVTransport", "Stop", soapEnvelope("AVTransport", "Stop", "0")) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) {} + } val metadataXml = createDidlMetadata(streamUrl, _metadata.value) @@ -1870,11 +1875,19 @@ class AudioCastService : Service() { /** One processor per consumer of the audio bus; it follows this speaker's live settings. */ private fun dspFor(host: String) = SpeakerDsp { soundFor(host) } - /** Gives [dest] the delay saved for its host, unless one was already set. */ + /** What the list of known speakers says this speaker needs, if anything. */ + private fun configFor(dest: CastDestination): SpeakerConfig = + DeviceQuirks.configFor(DeviceIdentity.of(dest.platform, dest.name, dest.extra)) + + /** + * Gives [dest] the delay saved for its host, unless one was already set. A speaker the user + * never adjusted starts from the delay the list suggests for it, if any. + */ private fun withSavedDelay(dest: CastDestination): CastDestination { if (dest.delayMs != 0) return dest - val saved = sharedPreferences.getInt(speakerKey(dest.host, "delay"), 0) - return if (saved != 0) dest.copy(delayMs = saved) else dest + val key = speakerKey(dest.host, "delay") + val delay = if (sharedPreferences.contains(key)) sharedPreferences.getInt(key, 0) else configFor(dest).defaultDelayMs ?: 0 + return if (delay != 0) dest.copy(delayMs = delay) else dest } fun setDelay(host: String, delayMs: Int) { @@ -1955,6 +1968,7 @@ class AudioCastService : Service() { } destinations.forEach { dest -> + if (configFor(dest).sendMetadata == false) return@forEach try { if (dest.platform == VbanProtocol.PLATFORM) { // VBAN AUDIO packets carry no metadata. @@ -2008,7 +2022,7 @@ class AudioCastService : Service() { // SetAVTransportURI resets many renderers (e.g. WiiM) to a stopped state, // so playback must be restarted explicitly or it stays paused at 0:00. val playBody = """01""" - dlnaSoap(dest, avUrl, "AVTransport", "Play", playBody) + if (configFor(dest).dlnaPlayAfterSetUri != false) dlnaSoap(dest, avUrl, "AVTransport", "Play", playBody) } catch (e: CancellationException) { throw e } catch (e: Exception) { diff --git a/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt b/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt index 776e5409..9b6a6101 100644 --- a/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt +++ b/app/src/main/java/com/aria/ariacast/quirks/DeviceQuirks.kt @@ -1,8 +1,7 @@ package com.aria.ariacast.quirks -import androidx.annotation.StringRes import com.aria.ariacast.ExtraFields -import com.aria.ariacast.R +import java.util.Locale /** * What discovery learned about a speaker. [model] and [manufacturer] come from the device itself @@ -32,113 +31,21 @@ data class DeviceIdentity( ).joinToString(", ") } -/** How a speaker behaves over one protocol. */ -enum class Verdict(val label: String) { - /** Plays as expected. */ - GOOD("Works"), - - /** Plays, with a limit the user should know about. */ - PARTIAL("Works with a catch"), - - /** Does not play, or breaks in a way the app cannot work around. */ - BAD("Does not work"), -} - -/** - * One entry of the list of speakers we know something about (published as docs/SPEAKERS.md; a - * unit test keeps the two in step). Entries are added only for behavior with evidence: an issue, - * a maintainer's own test, or the code that works around it. "Report speaker" in the app exists - * to find the next ones. - */ -data class KnownSpeaker( - val id: String, - /** Brand and, where known, the model it was seen on. */ - val speaker: String, - val protocol: String, - val verdict: Verdict, - /** What a user sees when it goes wrong, in their words. */ - val symptoms: List = emptyList(), - val whatToDo: String? = null, - /** First version where this holds (for a fix), if it is tied to one. */ - val since: String? = null, - /** Where this comes from. */ - val evidence: String, - /** Message the connection doctor shows while casting to a matching speaker, if any. */ - @param:StringRes val note: Int? = null, - val appliesTo: (DeviceIdentity) -> Boolean, -) - object DeviceQuirks { - private const val ISSUES = "https://github.com/AriaCast/AriaCast-app/issues" - - private fun DeviceIdentity.mentions(vararg needles: String): Boolean { - val haystack = listOfNotNull(name, model, manufacturer).joinToString(" ").lowercase() - return needles.any { haystack.contains(it) } - } - - val ALL: List = listOf( - KnownSpeaker( - id = "sonos-airplay2", - speaker = "Sonos (tested on Play:5)", - protocol = "AirPlay 2", - verdict = Verdict.GOOD, - symptoms = listOf("On 1.1.9 the AirPlay 2 stream did not play, while DLNA to the same speaker did."), - whatToDo = "Update. Until then, cast to it over DLNA.", - since = "1.1.9_hotfix", - evidence = "[#48]($ISSUES/48), confirmed by the reporter after the hotfix", - ) { it.platform == "AirPlay2" && it.mentions("sonos") }, - KnownSpeaker( - id = "sonos-dlna", - speaker = "Sonos (tested on Play:5)", - protocol = "DLNA", - verdict = Verdict.GOOD, - evidence = "[#48]($ISSUES/48), reporter: DLNA was working", - ) { it.platform == "DLNA" && it.mentions("sonos") }, - KnownSpeaker( - id = "wiim-dlna-restart", - speaker = "WiiM (tested on Pro Plus)", - protocol = "DLNA", - verdict = Verdict.GOOD, - symptoms = listOf( - "The track title changes but playback stays paused at 0:00 after every track change.", - "Pressing play in the WiiM app starts it again.", - ), - whatToDo = "Update: AriaCast now sends Play after every track change. If it still stops, press play once in the WiiM app and report it.", - since = "2.0.0", - evidence = "[#50]($ISSUES/50), fixed in the 2.0 line; the reporter's confirmation is not recorded", - note = R.string.quirk_wiim_dlna, - ) { it.platform == "DLNA" && it.mentions("wiim", "linkplay") }, - KnownSpeaker( - id = "shairport-airplay1", - speaker = "shairport-sync", - protocol = "AirPlay 1", - verdict = Verdict.GOOD, - evidence = "Maintainer's own test in [#48]($ISSUES/48); the AirPlay version is not stated there, so it is listed under AirPlay 1", - ) { it.platform == "AirPlay" && it.mentions("shairport") }, - KnownSpeaker( - id = "shairport-airplay2-ptp", - speaker = "shairport-sync", - protocol = "AirPlay 2", - verdict = Verdict.PARTIAL, - symptoms = listOf("The speaker accepts the connection but timing is off, or AriaCast drops to AirPlay 1."), - whatToDo = "Nothing to do: AriaCast tries NTP timing and falls back to AirPlay 1 on its own. Real PTP needs root.", - evidence = "Code: PtpMaster (shairport-sync with nqptp accepts only PTP timing)", - note = R.string.quirk_shairport_ptp, - ) { it.platform == "AirPlay2" && it.mentions("shairport") }, - KnownSpeaker( - id = "appletv-airplay-video-pairing", - speaker = "Apple TV", - protocol = "AirPlay (video)", - verdict = Verdict.PARTIAL, - symptoms = listOf("On Apple TVs that require pairing, casting a video fails with \"This AirPlay device requires pairing for video\". Audio casting is not affected."), - whatToDo = "Cast audio only. Video works with Apple TVs that allow unpaired access.", - evidence = "Roadmap status table and VideoTargets.kt", - ) { (it.platform == "AirPlay" || it.platform == "AirPlay2") && it.mentions("appletv") }, - ) + /** Every entry of the list in use. */ + val all: List get() = KnownSpeakersStore.current.speakers /** Every known entry that applies to [device]. */ - fun matching(device: DeviceIdentity): List = ALL.filter { it.appliesTo(device) } - - /** The entries the connection doctor should explain while casting to [device]. */ - fun notesFor(device: DeviceIdentity): List = matching(device).filter { it.note != null } + fun matching(device: DeviceIdentity): List = all.filter { it.appliesTo(device) } + + /** The entries the connection doctor should explain while casting to [device], in [locale]. */ + fun notesFor(device: DeviceIdentity, locale: Locale): List> = + matching(device).mapNotNull { k -> k.noteFor(locale)?.let { k to it } } + + /** + * What this speaker needs that differs from the usual. Where several entries apply, the first + * one in the list that sets a field decides it. + */ + fun configFor(device: DeviceIdentity): SpeakerConfig = + matching(device).fold(SpeakerConfig()) { acc, k -> acc.orElse(k.config) } } diff --git a/app/src/main/java/com/aria/ariacast/quirks/KnownSpeakers.kt b/app/src/main/java/com/aria/ariacast/quirks/KnownSpeakers.kt new file mode 100644 index 00000000..e1f84d6a --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/KnownSpeakers.kt @@ -0,0 +1,215 @@ +package com.aria.ariacast.quirks + +import java.util.Locale +import kotlinx.serialization.SerializationException +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +/** How a speaker behaves over one protocol. */ +enum class Verdict(val id: String, val label: String) { + /** Plays as expected. */ + GOOD("good", "Works"), + + /** Plays, with a limit the user should know about. */ + PARTIAL("partial", "Works with a catch"), + + /** Does not play, or breaks in a way the app cannot work around. */ + BAD("bad", "Does not work"), + + /** Has no local way in that AriaCast offers (Bluetooth only, cloud only). */ + UNSUPPORTED("unsupported", "Not supported"), + ; + + companion object { + fun of(id: String?) = entries.firstOrNull { it.id == id } + } +} + +/** + * Settings a speaker needs that differ from the usual ones. Every field is optional; null means + * "do what AriaCast normally does". The set is closed on purpose: the list is a public file, so + * it can only turn the knobs below, within the limits checked by [KnownSpeakersFile.parse]. + */ +data class SpeakerConfig( + /** DLNA: send Play after every track change. On by default. */ + val dlnaPlayAfterSetUri: Boolean? = null, + /** DLNA: content type of the stream, for renderers that refuse the other one. */ + val dlnaContentType: String? = null, + /** DLNA: skip the Stop sent before the stream address, for renderers that drop out on it. */ + val dlnaSkipInitialStop: Boolean? = null, + /** Delay in ms applied the first time this speaker is used, until the user sets their own. */ + val defaultDelayMs: Int? = null, + /** Send track titles and artwork to this speaker. On by default. */ + val sendMetadata: Boolean? = null, +) { + /** This config, with the fields it leaves unset taken from [other]. */ + fun orElse(other: SpeakerConfig) = SpeakerConfig( + dlnaPlayAfterSetUri = dlnaPlayAfterSetUri ?: other.dlnaPlayAfterSetUri, + dlnaContentType = dlnaContentType ?: other.dlnaContentType, + dlnaSkipInitialStop = dlnaSkipInitialStop ?: other.dlnaSkipInitialStop, + defaultDelayMs = defaultDelayMs ?: other.defaultDelayMs, + sendMetadata = sendMetadata ?: other.sendMetadata, + ) + + companion object { + val DLNA_CONTENT_TYPES = setOf("audio/wav", "audio/x-wav") + val DELAY_RANGE = 0..2000 + } +} + +/** Which speakers an entry is about: this protocol, and a name, model or maker containing one of these words. */ +data class Match(val platform: String?, val mentions: List) { + fun appliesTo(device: DeviceIdentity): Boolean { + if (platform != null && device.platform != platform) return false + val haystack = listOfNotNull(device.name, device.model, device.manufacturer).joinToString(" ").lowercase() + return mentions.any { haystack.contains(it) } + } +} + +/** + * One entry of the list of speakers we know something about (public as data/speakers.json and + * docs/SPEAKERS.md). Entries are added only for behavior with evidence: an issue, a maintainer's + * own test, or the code that works around it. + */ +data class KnownSpeaker( + val id: String, + /** Brand and, where known, the model it was seen on. */ + val speaker: String, + val protocol: String, + val verdict: Verdict, + val match: Match, + /** What a user sees when it goes wrong, in their words. */ + val symptoms: List = emptyList(), + val whatToDo: String? = null, + /** First version where this holds (for a fix), if it is tied to one. */ + val since: String? = null, + /** Where this comes from. */ + val evidence: String, + /** Message the connection doctor shows while casting to a matching speaker, by language. */ + val notes: Map = emptyMap(), + val config: SpeakerConfig = SpeakerConfig(), +) { + fun appliesTo(device: DeviceIdentity) = match.appliesTo(device) + + /** The doctor's message in the user's language, falling back to English; null if there is none. */ + fun noteFor(locale: Locale): String? = notes[locale.language] ?: notes["en"] +} + +/** The list as loaded: the entries that passed validation, and why the others did not. */ +data class KnownSpeakersFile( + val version: Int, + val updated: String, + val speakers: List, + val skipped: List = emptyList(), +) { + companion object { + const val SCHEMA = 1 + const val MAX_BYTES = 256 * 1024 + const val MAX_ENTRIES = 500 + + private val json = Json { ignoreUnknownKeys = true } + private val idPattern = Regex("[a-z0-9][a-z0-9-]{2,63}") + private val languagePattern = Regex("[a-z]{2}") + + /** + * Reads the list. The file is public and changes what the app does, so it is treated as + * untrusted: a file that is too big, of another schema or not valid JSON is refused whole + * (null); inside a good file, an entry that breaks a rule is skipped on its own, and a + * config value outside its limits is dropped rather than clamped. + */ + fun parse(text: String): KnownSpeakersFile? { + if (text.length > MAX_BYTES) return null + val raw = try { + json.decodeFromString(text) + } catch (_: SerializationException) { + return null + } catch (_: IllegalArgumentException) { + return null + } + if (raw.schema != SCHEMA || raw.version < 0) return null + val skipped = mutableListOf() + val seen = mutableSetOf() + val entries = raw.speakers.take(MAX_ENTRIES).mapNotNull { e -> + val id = e.id.trim() + val problem = when { + !idPattern.matches(id) -> "bad id" + !seen.add(id) -> "duplicate id" + Verdict.of(e.verdict) == null -> "unknown verdict" + e.speaker.isBlank() || e.protocol.isBlank() -> "no speaker or protocol" + cleanMentions(e.match.mentions).isEmpty() -> "needs at least one word to match" + e.evidence.isBlank() -> "no evidence" + else -> null + } + if (problem != null) { + skipped += "${id.ifBlank { "?" }}: $problem" + return@mapNotNull null + } + KnownSpeaker( + id = id, + speaker = clean(e.speaker, 80), + protocol = clean(e.protocol, 40), + verdict = Verdict.of(e.verdict)!!, + match = Match(e.match.platform?.let { clean(it, 20) }?.takeIf { it.isNotEmpty() }, cleanMentions(e.match.mentions)), + symptoms = e.symptoms.take(8).map { clean(it, 240) }.filter { it.isNotEmpty() }, + whatToDo = e.whatToDo?.let { clean(it, 320) }?.takeIf { it.isNotEmpty() }, + since = e.since?.let { clean(it, 24) }?.takeIf { it.isNotEmpty() }, + evidence = clean(e.evidence, 320), + notes = e.notes.filterKeys { languagePattern.matches(it) }.mapValues { clean(it.value, 700) }.filterValues { it.isNotEmpty() }, + config = e.config?.let(::validConfig) ?: SpeakerConfig(), + ) + } + return KnownSpeakersFile(raw.version, clean(raw.updated, 24), entries, skipped) + } + + private fun validConfig(c: RawConfig) = SpeakerConfig( + dlnaPlayAfterSetUri = c.dlnaPlayAfterSetUri, + dlnaContentType = c.dlnaContentType?.takeIf { it in SpeakerConfig.DLNA_CONTENT_TYPES }, + dlnaSkipInitialStop = c.dlnaSkipInitialStop, + defaultDelayMs = c.defaultDelayMs?.takeIf { it in SpeakerConfig.DELAY_RANGE }, + sendMetadata = c.sendMetadata, + ) + + /** Words to look for: lowercase, 3 to 40 characters, at most 8. Shorter ones would match far too much. */ + private fun cleanMentions(words: List) = + words.map { clean(it, 40).lowercase() }.filter { it.length >= 3 }.distinct().take(8) + + /** Trimmed, control characters removed, cut to [max]. */ + private fun clean(text: String, max: Int) = + text.filter { it >= ' ' && it != '\u007f' }.trim().take(max) + } + + @Serializable + private data class Raw( + val schema: Int = 0, + val version: Int = 0, + val updated: String = "", + val speakers: List = emptyList(), + ) + + @Serializable + private data class RawEntry( + val id: String = "", + val speaker: String = "", + val protocol: String = "", + val verdict: String = "", + val match: RawMatch = RawMatch(), + val symptoms: List = emptyList(), + val whatToDo: String? = null, + val since: String? = null, + val evidence: String = "", + val notes: Map = emptyMap(), + val config: RawConfig? = null, + ) + + @Serializable + private data class RawMatch(val platform: String? = null, val mentions: List = emptyList()) + + @Serializable + private data class RawConfig( + val dlnaPlayAfterSetUri: Boolean? = null, + val dlnaContentType: String? = null, + val dlnaSkipInitialStop: Boolean? = null, + val defaultDelayMs: Int? = null, + val sendMetadata: Boolean? = null, + ) +} diff --git a/app/src/main/java/com/aria/ariacast/quirks/KnownSpeakersStore.kt b/app/src/main/java/com/aria/ariacast/quirks/KnownSpeakersStore.kt new file mode 100644 index 00000000..fb32bc7b --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/KnownSpeakersStore.kt @@ -0,0 +1,55 @@ +package com.aria.ariacast.quirks + +import android.content.Context +import android.util.Log +import java.io.File + +/** + * The list of known speakers in use: the one shipped inside the app, or a newer one downloaded + * from the project (see [SpeakerListSync]). A downloaded list only ever replaces the shipped one + * if it is valid and has a higher version, so a bad download changes nothing. + */ +object KnownSpeakersStore { + private const val TAG = "KnownSpeakers" + private const val ASSET = "speakers.json" + private const val CACHE = "speakers-synced.json" + + @Volatile + var current: KnownSpeakersFile = KnownSpeakersFile(0, "", emptyList()) + private set + + /** Which of two lists to use: the higher version, the shipped one on a tie. */ + fun choose(shipped: KnownSpeakersFile?, synced: KnownSpeakersFile?): KnownSpeakersFile = + listOfNotNull(shipped, synced).maxWithOrNull(compareBy { it.version }.thenBy { if (it === shipped) 1 else 0 }) + ?: KnownSpeakersFile(0, "", emptyList()) + + /** Loads the shipped list and the cached download. Safe to call more than once. */ + @Synchronized + fun init(context: Context) { + if (current.speakers.isNotEmpty()) return + val shipped = runCatching { context.assets.open(ASSET).use { KnownSpeakersFile.parse(it.readBytes().toString(Charsets.UTF_8)) } }.getOrNull() + val synced = cacheFile(context).takeIf { it.exists() }?.let { KnownSpeakersFile.parse(runCatching { it.readText() }.getOrDefault("")) } + current = choose(shipped, synced) + Log.i(TAG, "Using list v${current.version} (${current.speakers.size} entries)") + } + + /** + * Takes a downloaded list. Returns true if it was newer and valid and is now in use; the text + * is then kept so the next start uses it too. + */ + @Synchronized + fun update(context: Context, text: String): Boolean { + val file = KnownSpeakersFile.parse(text) ?: return false + if (file.version <= current.version) return false + runCatching { cacheFile(context).writeText(text) } + current = file + return true + } + + /** For tests and previews. */ + fun setForTesting(file: KnownSpeakersFile) { + current = file + } + + private fun cacheFile(context: Context) = File(context.filesDir, CACHE) +} diff --git a/app/src/main/java/com/aria/ariacast/quirks/SpeakerListSync.kt b/app/src/main/java/com/aria/ariacast/quirks/SpeakerListSync.kt new file mode 100644 index 00000000..d97fe6e0 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/SpeakerListSync.kt @@ -0,0 +1,118 @@ +package com.aria.ariacast.quirks + +import android.content.Context +import android.content.SharedPreferences +import android.util.Log +import com.aria.ariacast.AudioCastService +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URL +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * Keeps the list of known speakers up to date by reading data/speakers.json from the project's + * repository. The only thing sent is an ordinary request for a public file; nothing about the + * user or their speakers leaves the phone. + * + * The file is public and changes what the app does, so a download is treated as untrusted: HTTPS + * only, no redirects, a size limit, and it must pass [KnownSpeakersFile.parse] and have a higher + * version than the list in use, or it is ignored. + */ +object SpeakerListSync { + const val URL = "https://raw.githubusercontent.com/AriaCast/AriaCast-app/main/data/speakers.json" + const val KEY_AUTO = "speakers_sync_auto" + const val KEY_LAST_TRY = "speakers_sync_last_try" + const val KEY_LAST_OK = "speakers_sync_last_ok" + const val MIN_INTERVAL_MS = 24L * 60 * 60 * 1000 + private const val TIMEOUT_MS = 10_000 + private const val TAG = "SpeakerListSync" + + sealed interface Outcome { + data class Updated(val version: Int) : Outcome + data class UpToDate(val version: Int) : Outcome + data class Failed(val why: String) : Outcome + } + + /** What a downloaded text means for the list in use. */ + sealed interface Verdict { + data object Invalid : Verdict + data class NotNewer(val version: Int) : Verdict + data class Newer(val file: KnownSpeakersFile) : Verdict + } + + fun evaluate(text: String, currentVersion: Int): Verdict { + val file = KnownSpeakersFile.parse(text) ?: return Verdict.Invalid + return if (file.version > currentVersion) Verdict.Newer(file) else Verdict.NotNewer(file.version) + } + + fun isEnabled(prefs: SharedPreferences) = prefs.getBoolean(KEY_AUTO, true) + + /** Due when a day has passed since the last try; a clock that went backwards counts as due. */ + fun isDue(lastTryMs: Long, nowMs: Long) = lastTryMs <= 0 || nowMs < lastTryMs || nowMs - lastTryMs >= MIN_INTERVAL_MS + + /** Checks for a newer list if the user allows it and a day has passed. */ + suspend fun syncIfDue(context: Context) { + val prefs = context.getSharedPreferences(AudioCastService.PREFS_NAME, Context.MODE_PRIVATE) + if (!isEnabled(prefs) || !isDue(prefs.getLong(KEY_LAST_TRY, 0), System.currentTimeMillis())) return + sync(context) + } + + /** Downloads the list now and uses it if it is newer. */ + suspend fun sync(context: Context, url: String = URL, requireHttps: Boolean = true): Outcome = withContext(Dispatchers.IO) { + val prefs = context.getSharedPreferences(AudioCastService.PREFS_NAME, Context.MODE_PRIVATE) + val now = System.currentTimeMillis() + prefs.edit().putLong(KEY_LAST_TRY, now).apply() + val text = try { + fetch(url, requireHttps) + } catch (e: IOException) { + Log.w(TAG, "Could not read the list: ${e.message}") + return@withContext Outcome.Failed(e.message ?: "network error") + } + when (val verdict = evaluate(text, KnownSpeakersStore.current.version)) { + Verdict.Invalid -> Outcome.Failed("the file is not a valid list") + is Verdict.NotNewer -> { + prefs.edit().putLong(KEY_LAST_OK, now).apply() + Outcome.UpToDate(KnownSpeakersStore.current.version) + } + is Verdict.Newer -> { + KnownSpeakersStore.update(context, text) + prefs.edit().putLong(KEY_LAST_OK, now).apply() + Outcome.Updated(verdict.file.version) + } + } + } + + /** One GET with no redirects and a size limit. */ + internal fun fetch(url: String, requireHttps: Boolean = true): String { + val target = try { URL(url) } catch (e: java.net.MalformedURLException) { throw IOException("bad address") } + if (requireHttps && target.protocol != "https") throw IOException("not https") + val connection = target.openConnection() as HttpURLConnection + try { + connection.connectTimeout = TIMEOUT_MS + connection.readTimeout = TIMEOUT_MS + connection.instanceFollowRedirects = false + connection.setRequestProperty("User-Agent", "AriaCast") + connection.setRequestProperty("Accept", "application/json") + if (connection.responseCode != HttpURLConnection.HTTP_OK) throw IOException("HTTP ${connection.responseCode}") + if (connection.contentLengthLong > KnownSpeakersFile.MAX_BYTES) throw IOException("file too big") + return connection.inputStream.use { readBounded(it, KnownSpeakersFile.MAX_BYTES) } + } finally { + connection.disconnect() + } + } + + internal fun readBounded(input: InputStream, max: Int): String { + val out = ByteArrayOutputStream() + val buffer = ByteArray(8192) + while (true) { + val n = input.read(buffer) + if (n < 0) break + if (out.size() + n > max) throw IOException("file too big") + out.write(buffer, 0, n) + } + return out.toString(Charsets.UTF_8.name()) + } +} diff --git a/app/src/main/java/com/aria/ariacast/ui/AppController.kt b/app/src/main/java/com/aria/ariacast/ui/AppController.kt index e7060827..651cd6e0 100644 --- a/app/src/main/java/com/aria/ariacast/ui/AppController.kt +++ b/app/src/main/java/com/aria/ariacast/ui/AppController.kt @@ -14,7 +14,7 @@ import kotlinx.coroutines.flow.StateFlow */ enum class Screen { HOME, RECEIVE, SETTINGS, - NOW_PLAYING, RECEIVER_DISPLAY, DOCTOR, ONBOARDING; + NOW_PLAYING, RECEIVER_DISPLAY, DOCTOR, KNOWN_SPEAKERS, ONBOARDING; val isDestination: Boolean get() = this == HOME || this == RECEIVE || this == SETTINGS } diff --git a/app/src/main/java/com/aria/ariacast/ui/AriaApp.kt b/app/src/main/java/com/aria/ariacast/ui/AriaApp.kt index 9d947d38..8a4b6efa 100644 --- a/app/src/main/java/com/aria/ariacast/ui/AriaApp.kt +++ b/app/src/main/java/com/aria/ariacast/ui/AriaApp.kt @@ -68,6 +68,7 @@ import com.aria.ariacast.ui.nowplaying.NowPlayingScreen import com.aria.ariacast.ui.onboarding.OnboardingScreen import com.aria.ariacast.ui.receive.ReceiveScreen import com.aria.ariacast.ui.receive.ReceiveTab +import com.aria.ariacast.ui.settings.KnownSpeakersScreen import com.aria.ariacast.ui.settings.SettingsScreen private data class Destination(val screen: Screen, val label: Int, val icon: ImageVector, val selectedIcon: ImageVector) @@ -114,6 +115,7 @@ fun AriaApp(controller: AppController) { Screen.NOW_PLAYING -> NowPlayingScreen(controller, onClose = back) Screen.RECEIVER_DISPLAY -> ReceiveScreen(controller, onBack = back) Screen.DOCTOR -> DoctorScreen(controller, onBack = back) + Screen.KNOWN_SPEAKERS -> KnownSpeakersScreen(onBack = back) else -> {} } } diff --git a/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt b/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt index c8ac8c6a..1addc88f 100644 --- a/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt +++ b/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt @@ -146,8 +146,8 @@ fun DoctorScreen(controller: AppController, onBack: () -> Unit) { // Known behavior of this brand or model, so a quirk isn't mistaken for a bug. s.activeDestinations.value.forEach { d -> - DeviceQuirks.notesFor(DeviceIdentity.of(d.platform, d.name, d.extra)).forEach { q -> - list += Check(context.getString(R.string.doctor_known_behavior, d.name), CheckStatus.INFO, context.getString(q.note!!)) + DeviceQuirks.notesFor(DeviceIdentity.of(d.platform, d.name, d.extra), context.resources.configuration.locales[0]).forEach { (_, note) -> + list += Check(context.getString(R.string.doctor_known_behavior, d.name), CheckStatus.INFO, note) } } diff --git a/app/src/main/java/com/aria/ariacast/ui/settings/KnownSpeakersScreen.kt b/app/src/main/java/com/aria/ariacast/ui/settings/KnownSpeakersScreen.kt new file mode 100644 index 00000000..52db3d85 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/ui/settings/KnownSpeakersScreen.kt @@ -0,0 +1,168 @@ +package com.aria.ariacast.ui.settings + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.text.format.DateUtils +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Block +import androidx.compose.material.icons.filled.BugReport +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Error +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.Sync +import androidx.compose.material.icons.filled.Warning +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.aria.ariacast.AudioCastService +import com.aria.ariacast.R +import com.aria.ariacast.quirks.KnownSpeaker +import com.aria.ariacast.quirks.KnownSpeakersStore +import com.aria.ariacast.quirks.SpeakerListSync +import com.aria.ariacast.quirks.Verdict +import com.aria.ariacast.ui.LeadingIcon +import com.aria.ariacast.ui.ListBlock +import com.aria.ariacast.ui.ListGroup +import com.aria.ariacast.ui.ListRow +import com.aria.ariacast.ui.ScreenList +import com.aria.ariacast.ui.SubScreenScaffold +import com.aria.ariacast.ui.SwitchListRow +import com.aria.ariacast.ui.theme.StatusColors +import kotlinx.coroutines.launch + +/** + * The public list of speakers we know something about: what works, what works with a catch, + * what does not, and what AriaCast cannot reach. The same list as docs/SPEAKERS.md, kept up to + * date from there (see [SpeakerListSync]). + */ +@Composable +fun KnownSpeakersScreen(onBack: () -> Unit) { + val context = LocalContext.current + val prefs = remember { context.getSharedPreferences(AudioCastService.PREFS_NAME, Context.MODE_PRIVATE) } + val scope = rememberCoroutineScope() + var list by remember { mutableStateOf(KnownSpeakersStore.current) } + var auto by remember { mutableStateOf(SpeakerListSync.isEnabled(prefs)) } + var busy by remember { mutableStateOf(false) } + var status by remember { mutableStateOf(null) } + var lastOk by remember { mutableStateOf(prefs.getLong(SpeakerListSync.KEY_LAST_OK, 0)) } + + SubScreenScaffold(title = stringResource(R.string.known_speakers), onBack = onBack) { padding -> + ScreenList(Modifier.padding(padding)) { + item { + Text( + stringResource(R.string.known_speakers_intro), style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + item { + ListGroup { + SwitchListRow(stringResource(R.string.known_speakers_auto), stringResource(R.string.known_speakers_auto_desc), auto, { + auto = it; prefs.edit().putBoolean(SpeakerListSync.KEY_AUTO, it).apply() + }) + val updated = if (lastOk > 0) DateUtils.getRelativeTimeSpanString(lastOk, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString() + else stringResource(R.string.known_speakers_never) + ListRow( + stringResource(R.string.known_speakers_version, list.version, list.speakers.size), + supporting = status ?: stringResource(R.string.known_speakers_checked, updated), + leading = { LeadingIcon(Icons.Filled.Sync) }, + trailing = { + TextButton(enabled = !busy, onClick = { + busy = true; status = null + scope.launch { + val outcome = SpeakerListSync.sync(context) + list = KnownSpeakersStore.current + lastOk = prefs.getLong(SpeakerListSync.KEY_LAST_OK, 0) + status = when (outcome) { + is SpeakerListSync.Outcome.Updated -> context.getString(R.string.known_speakers_now, outcome.version) + is SpeakerListSync.Outcome.UpToDate -> context.getString(R.string.known_speakers_current) + is SpeakerListSync.Outcome.Failed -> context.getString(R.string.known_speakers_failed, outcome.why) + } + busy = false + } + }) { Text(stringResource(R.string.known_speakers_update)) } + }, + ) + } + } + Verdict.entries.forEach { verdict -> + val rows = list.speakers.filter { it.verdict == verdict } + if (rows.isNotEmpty()) item(key = verdict.id) { + ListGroup(title = stringResource(verdictLabel(verdict))) { rows.forEach { SpeakerEntryRow(it) } } + } + } + item { + ListGroup(Modifier.padding(top = 8.dp)) { + ListRow(stringResource(R.string.known_speakers_report), supporting = stringResource(R.string.known_speakers_report_desc), + leading = { LeadingIcon(Icons.Filled.BugReport) }) { + context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(SPEAKER_ISSUE_URL)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + } + } + } + } +} + +private const val SPEAKER_ISSUE_URL = "https://github.com/AriaCast/AriaCast-app/issues/new?template=speaker-report.yml" + +private fun verdictLabel(v: Verdict) = when (v) { + Verdict.GOOD -> R.string.verdict_good + Verdict.PARTIAL -> R.string.verdict_partial + Verdict.BAD -> R.string.verdict_bad + Verdict.UNSUPPORTED -> R.string.verdict_unsupported +} + +private fun verdictIcon(v: Verdict): Pair = when (v) { + Verdict.GOOD -> Icons.Filled.CheckCircle to StatusColors.Connected + Verdict.PARTIAL -> Icons.Filled.Warning to StatusColors.Warning + Verdict.BAD -> Icons.Filled.Error to null + Verdict.UNSUPPORTED -> Icons.Filled.Block to StatusColors.Available +} + +/** `[#48](https://...)` shows as `#48`: the text is public but not trusted, so no links are made from it. */ +private fun plain(text: String) = text.replace(Regex("""\[([^\]]+)]\([^)]*\)"""), "$1") + +@Composable +private fun SpeakerEntryRow(k: KnownSpeaker) { + var open by remember(k.id) { mutableStateOf(false) } + val (icon, tint) = verdictIcon(k.verdict) + ListRow( + headline = k.speaker, + supporting = k.protocol, + leading = { Icon(icon, null, tint = tint ?: MaterialTheme.colorScheme.error, modifier = Modifier.padding(8.dp)) }, + trailing = { Icon(if (open) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown, null) }, + onClick = { open = !open }, + ) + if (open) { + ListBlock { + if (k.symptoms.isNotEmpty()) Detail(stringResource(R.string.known_speakers_symptoms), k.symptoms.joinToString("\n") { "• ${plain(it)}" }) + k.whatToDo?.let { Detail(stringResource(R.string.known_speakers_what_to_do), plain(it)) } + k.since?.let { Detail(stringResource(R.string.known_speakers_since), it) } + Detail(stringResource(R.string.known_speakers_evidence), plain(k.evidence)) + } + } +} + +@Composable +private fun Detail(label: String, text: String) { + androidx.compose.foundation.layout.Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary) + Text(text, style = MaterialTheme.typography.bodyMedium) + } +} diff --git a/app/src/main/java/com/aria/ariacast/ui/settings/SettingsScreen.kt b/app/src/main/java/com/aria/ariacast/ui/settings/SettingsScreen.kt index 57aec707..dfd7d01a 100644 --- a/app/src/main/java/com/aria/ariacast/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/aria/ariacast/ui/settings/SettingsScreen.kt @@ -25,6 +25,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ReceiptLong +import androidx.compose.material.icons.filled.Speaker import androidx.compose.material.icons.filled.Code import androidx.compose.material.icons.filled.DarkMode import androidx.compose.material.icons.filled.Extension @@ -185,6 +186,7 @@ fun SettingsScreen(controller: AppController, onBack: (() -> Unit)?) { item { ListGroup(title = stringResource(R.string.settings_diagnostics)) { ListRow(stringResource(R.string.doctor_title), supporting = stringResource(R.string.doctor_desc), leading = { LeadingIcon(Icons.Filled.HealthAndSafety) }) { controller.navigate(Screen.DOCTOR) } + ListRow(stringResource(R.string.known_speakers), supporting = stringResource(R.string.known_speakers_desc), leading = { LeadingIcon(Icons.Filled.Speaker) }) { controller.navigate(Screen.KNOWN_SPEAKERS) } ListRow(stringResource(R.string.packet_logs), supporting = stringResource(R.string.packet_logs_desc), leading = { LeadingIcon(Icons.AutoMirrored.Filled.ReceiptLong) }) { open(PacketLogActivity::class.java) } } } diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index b57b7f07..5dc0753c 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -267,8 +267,28 @@ Segnala altoparlante Segnala %1$s Segnalazione AriaCast: %1$s - I WiiM si fermano a 0:00 ogni volta che ricevono un nuovo indirizzo di stream. AriaCast riavvia la riproduzione a ogni cambio traccia. Se si ferma comunque, premi play una volta nell\'app WiiM e segnalalo. - I ricevitori AirPlay 2 basati su shairport-sync richiedono la sincronizzazione PTP, che le app Android non possono offrire senza root. AriaCast prova con NTP e passa da solo ad AirPlay 1. + Altoparlanti noti + Cosa funziona, cosa ha un limite e cosa AriaCast non può raggiungere. + Altoparlanti provati da altri, con cosa osservare e cosa fare. L\'elenco viene dal progetto e si aggiorna da solo. Le descrizioni sono in inglese. + Aggiorna l\'elenco automaticamente + Una volta al giorno AriaCast legge un file pubblico su GitHub. Non viene inviato nulla su di te o sui tuoi altoparlanti. + Elenco versione %1$d, %2$d altoparlanti + Controllato %1$s + mai + Aggiorna ora + Aggiornato alla versione %1$d + Hai l\'elenco più recente + Aggiornamento non riuscito: %1$s + Segnala un altoparlante + Raccontaci come funziona per te, su GitHub. + Se qualcosa va storto + Cosa fare + Da + Prove + Funziona + Funziona con un limite + Non funziona + Non supportato Report copiato Trasmetti qualsiasi audio, ovunque AriaCast invia l\'audio di questo dispositivo ad altoparlanti AirPlay, Google Cast, DLNA, Snapcast e Sendspin, e può trasformare questo dispositivo in un altoparlante. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 488e4e0f..8771bcea 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -370,8 +370,28 @@ Report speaker Report %1$s AriaCast report: %1$s - WiiM players pause at 0:00 whenever they receive a new stream address. AriaCast starts playback again after every track change. If it still stops, press play once in the WiiM app and report it. - AirPlay 2 receivers built on shairport-sync need PTP timing, which Android apps can\'t provide without root. AriaCast tries NTP timing and falls back to AirPlay 1 on its own. + Known speakers + What works, what has a catch, and what AriaCast cannot reach. + Speakers other people have tried, with what to look for and what to do. The list comes from the project and updates itself. Descriptions are in English. + Update the list automatically + Once a day, AriaCast reads a public file from GitHub. Nothing about you or your speakers is sent. + List version %1$d, %2$d speakers + Checked %1$s + never + Update now + Updated to version %1$d + You have the latest list + Could not update: %1$s + Report a speaker + Tell us how a speaker works for you, on GitHub. + If it goes wrong + What to do + Since + Evidence + Works + Works with a catch + Does not work + Not supported Report copied Cast any audio, anywhere AriaCast sends this device\'s audio to AirPlay, Google Cast, DLNA, Snapcast and Sendspin speakers, and can turn this device into a speaker too. diff --git a/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt b/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt index 35a17164..423eaadc 100644 --- a/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt +++ b/app/src/test/java/com/aria/ariacast/quirks/DeviceQuirksTest.kt @@ -2,10 +2,14 @@ package com.aria.ariacast.quirks import com.aria.ariacast.ExtraFields import org.junit.Assert.assertEquals +import java.util.Locale import org.junit.Assert.assertTrue +import org.junit.Before import org.junit.Test class DeviceQuirksTest { + @Before fun loadTheList() { TestSpeakers.load() } + private fun ids(d: DeviceIdentity) = DeviceQuirks.matching(d).map { it.id } @Test fun matchesWiimOverDlnaByNameOrManufacturer() { @@ -28,13 +32,44 @@ class DeviceQuirksTest { assertTrue(ids(DeviceIdentity("Google Cast", "Living", "Sonos Play:5")).isEmpty()) } - @Test fun onlyEntriesWithAMessageReachTheDoctor() { - assertEquals(listOf("wiim-dlna-restart"), DeviceQuirks.notesFor(wiimDevice).map { it.id }) - assertTrue(DeviceQuirks.notesFor(DeviceIdentity("DLNA", "Living", "Play:5", "Sonos, Inc.")).isEmpty()) + @Test fun theDoctorGetsTheNoteInTheUsersLanguage() { + val english = DeviceQuirks.notesFor(wiimDevice, Locale.ENGLISH) + assertEquals(listOf("wiim-dlna-restart"), english.map { it.first.id }) + assertTrue(english.single().second.startsWith("WiiM players pause")) + assertTrue(DeviceQuirks.notesFor(wiimDevice, Locale.ITALIAN).single().second.startsWith("I WiiM si fermano")) + // A language the list has no text for falls back to English. + assertTrue(DeviceQuirks.notesFor(wiimDevice, Locale.JAPANESE).single().second.startsWith("WiiM players pause")) + assertTrue(DeviceQuirks.notesFor(DeviceIdentity("DLNA", "Living", "Play:5", "Sonos, Inc."), Locale.ENGLISH).isEmpty()) + } + + @Test fun configComesFromTheMatchingEntries() { + assertEquals(true, DeviceQuirks.configFor(wiimDevice).dlnaPlayAfterSetUri) + assertEquals(SpeakerConfig(), DeviceQuirks.configFor(DeviceIdentity("Google Cast", "Nest Mini", "Google Home Mini"))) + } + + @Test fun theFirstEntryThatSetsAFieldDecidesIt() { + val entry = { id: String, config: SpeakerConfig -> + KnownSpeaker(id, "x", "DLNA", Verdict.GOOD, Match("DLNA", listOf("box")), evidence = "e", config = config) + } + KnownSpeakersStore.setForTesting( + KnownSpeakersFile( + 1, "", listOf( + entry("a", SpeakerConfig(defaultDelayMs = 300)), + entry("b", SpeakerConfig(defaultDelayMs = 900, sendMetadata = false)), + ) + ) + ) + val config = DeviceQuirks.configFor(DeviceIdentity("DLNA", "Kitchen box")) + assertEquals(300, config.defaultDelayMs) + assertEquals(false, config.sendMetadata) } private val wiimDevice = DeviceIdentity("DLNA", "Den", "WiiM Pro Plus", "Linkplay") + @Test fun anEchoIsListedAsNotSupported() { + assertEquals(Verdict.UNSUPPORTED, DeviceQuirks.matching(DeviceIdentity(null, "Echo Show 5 kitchen")).single().verdict) + } + @Test fun ordinarySpeakersMatchNothing() { assertTrue(ids(DeviceIdentity("Google Cast", "Nest Mini", "Google Home Mini")).isEmpty()) assertTrue(ids(DeviceIdentity("AirPlay2", "HomePod", "AudioAccessory5,1")).isEmpty()) diff --git a/app/src/test/java/com/aria/ariacast/quirks/KnownSpeakersFileTest.kt b/app/src/test/java/com/aria/ariacast/quirks/KnownSpeakersFileTest.kt new file mode 100644 index 00000000..0829d4d2 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/KnownSpeakersFileTest.kt @@ -0,0 +1,139 @@ +package com.aria.ariacast.quirks + +import java.util.Locale +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class KnownSpeakersFileTest { + private fun entry( + id: String = "wiim-dlna", + verdict: String = "good", + mentions: String = """["wiim"]""", + evidence: String = "an issue", + extra: String = "", + ) = """{"id":"$id","speaker":"WiiM","protocol":"DLNA","verdict":"$verdict","match":{"platform":"DLNA","mentions":$mentions},"evidence":"$evidence"$extra}""" + + private fun file(vararg entries: String, schema: Int = 1, version: Int = 3) = + """{"schema":$schema,"version":$version,"updated":"2026-11-27","speakers":[${entries.joinToString(",")}]}""" + + @Test fun readsAGoodFile() { + val list = KnownSpeakersFile.parse(file(entry()))!! + assertEquals(3, list.version) + assertEquals("wiim-dlna", list.speakers.single().id) + assertEquals(Verdict.GOOD, list.speakers.single().verdict) + assertTrue(list.skipped.isEmpty()) + } + + @Test fun refusesWholeFilesThatCannotBeTrusted() { + assertNull(KnownSpeakersFile.parse("not json")) + assertNull(KnownSpeakersFile.parse(file(entry(), schema = 2))) + assertNull(KnownSpeakersFile.parse(file(entry(), version = -1))) + assertNull(KnownSpeakersFile.parse(file(entry(evidence = "x".repeat(KnownSpeakersFile.MAX_BYTES))))) + assertNull(KnownSpeakersFile.parse("")) + } + + @Test fun skipsABadEntryAndKeepsTheRest() { + val list = KnownSpeakersFile.parse( + file( + entry(id = "ok-one"), + entry(id = "BAD ID"), + entry(id = "ok-one"), + entry(id = "weird-verdict", verdict = "great"), + entry(id = "no-words", mentions = "[]"), + entry(id = "short-words", mentions = """["ab","x"]"""), + entry(id = "no-evidence", evidence = " "), + entry(id = "ok-two"), + ) + )!! + assertEquals(listOf("ok-one", "ok-two"), list.speakers.map { it.id }) + assertEquals( + listOf("BAD ID: bad id", "ok-one: duplicate id", "weird-verdict: unknown verdict", "no-words: needs at least one word to match", + "short-words: needs at least one word to match", "no-evidence: no evidence"), + list.skipped, + ) + } + + @Test fun anEntryCannotMatchEverything() { + // Without a word to look for, an entry with a setting would apply to every speaker. + assertTrue(KnownSpeakersFile.parse(file(entry(mentions = "[]", extra = ""","config":{"sendMetadata":false}""")))!!.speakers.isEmpty()) + } + + @Test fun mentionsAreLowercasedAndMatchCaseInsensitively() { + val k = KnownSpeakersFile.parse(file(entry(mentions = """["WiiM"]""")))!!.speakers.single() + assertEquals(listOf("wiim"), k.match.mentions) + assertTrue(k.appliesTo(DeviceIdentity("DLNA", "LIVING ROOM WIIM"))) + assertFalse(k.appliesTo(DeviceIdentity("AirPlay2", "WiiM"))) + assertFalse(k.appliesTo(DeviceIdentity("DLNA", "Sonos"))) + } + + @Test fun anEntryWithoutAProtocolMatchesAnyProtocol() { + val k = KnownSpeakersFile.parse( + """{"schema":1,"version":1,"speakers":[{"id":"any-proto","speaker":"S","protocol":"p","verdict":"bad","match":{"mentions":["thing"]},"evidence":"e"}]}""" + )!!.speakers.single() + assertTrue(k.appliesTo(DeviceIdentity("DLNA", "a thing"))) + assertTrue(k.appliesTo(DeviceIdentity(null, "a thing"))) + } + + @Test fun configValuesOutsideTheirLimitsAreDroppedNotClamped() { + val config = KnownSpeakersFile.parse( + file(entry(extra = ""","config":{"defaultDelayMs":99999,"dlnaContentType":"text/html","sendMetadata":false,"dlnaSkipInitialStop":true,"unknownKnob":1}""")) + )!!.speakers.single().config + assertNull(config.defaultDelayMs) + assertNull(config.dlnaContentType) + assertEquals(false, config.sendMetadata) + assertEquals(true, config.dlnaSkipInitialStop) + } + + @Test fun validConfigValuesAreKept() { + val config = KnownSpeakersFile.parse( + file(entry(extra = ""","config":{"defaultDelayMs":350,"dlnaContentType":"audio/x-wav","dlnaPlayAfterSetUri":false}""")) + )!!.speakers.single().config + assertEquals(350, config.defaultDelayMs) + assertEquals("audio/x-wav", config.dlnaContentType) + assertEquals(false, config.dlnaPlayAfterSetUri) + } + + @Test fun textIsCleanedAndCapped() { + val k = KnownSpeakersFile.parse(file(entry(evidence = "ok\\u0000\\u001b[31m" + "y".repeat(1000))))!!.speakers.single() + assertTrue(k.evidence.none { it < ' ' }) + assertEquals(320, k.evidence.length) + } + + @Test fun onlyTwoLetterLanguagesAreKeptAndEnglishIsTheFallback() { + val k = KnownSpeakersFile.parse( + file(entry(extra = ""","notes":{"en":"English","it":"Italiano","EN":"x","english":"y","":"z"}""")) + )!!.speakers.single() + assertEquals(setOf("en", "it"), k.notes.keys) + assertEquals("Italiano", k.noteFor(Locale.ITALIAN)) + assertEquals("English", k.noteFor(Locale.GERMAN)) + assertNull(KnownSpeakersFile.parse(file(entry()))!!.speakers.single().noteFor(Locale.ENGLISH)) + } + + @Test fun unknownFieldsAreIgnoredSoNewerFilesStillLoad() { + val list = KnownSpeakersFile.parse("""{"schema":1,"version":2,"future":true,"speakers":[${entry(extra = ""","newField":{"a":1}""")}]}""") + assertNotNull(list) + assertEquals(1, list!!.speakers.size) + } + + @Test fun moreThanTheLimitIsCutOff() { + val many = (1..KnownSpeakersFile.MAX_ENTRIES + 20).map { entry(id = "speaker-$it") }.toTypedArray() + assertEquals(KnownSpeakersFile.MAX_ENTRIES, KnownSpeakersFile.parse(file(*many))!!.speakers.size) + } + + @Test fun theHigherVersionIsUsedAndTheShippedOneWinsATie() { + val shipped = KnownSpeakersFile(5, "", emptyList()) + val newer = KnownSpeakersFile(6, "", emptyList()) + val same = KnownSpeakersFile(5, "", emptyList()) + assertSame(newer, KnownSpeakersStore.choose(shipped, newer)) + assertSame(shipped, KnownSpeakersStore.choose(shipped, KnownSpeakersFile(4, "", emptyList()))) + assertSame(shipped, KnownSpeakersStore.choose(shipped, same)) + assertSame(shipped, KnownSpeakersStore.choose(shipped, null)) + assertSame(newer, KnownSpeakersStore.choose(null, newer)) + assertEquals(0, KnownSpeakersStore.choose(null, null).speakers.size) + } +} diff --git a/app/src/test/java/com/aria/ariacast/quirks/SpeakerListSyncTest.kt b/app/src/test/java/com/aria/ariacast/quirks/SpeakerListSyncTest.kt new file mode 100644 index 00000000..e76b0f26 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakerListSyncTest.kt @@ -0,0 +1,114 @@ +package com.aria.ariacast.quirks + +import java.io.ByteArrayInputStream +import java.io.IOException +import java.io.OutputStream +import java.net.InetAddress +import java.net.ServerSocket +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +class SpeakerListSyncTest { + private val servers = mutableListOf() + + @After fun stop() = servers.forEach { runCatching { it.close() } } + + /** A one-request-at-a-time HTTP server on a plain socket; [respond] writes the raw reply. */ + private fun serve(respond: (OutputStream) -> Unit): String { + val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1")) + servers += socket + thread(isDaemon = true) { + while (!socket.isClosed) { + try { + socket.accept().use { client -> + val input = client.getInputStream().bufferedReader() + while (input.readLine().let { it != null && it.isNotEmpty() }) { /* skip the request */ } + runCatching { respond(client.getOutputStream()) } + } + } catch (_: IOException) { + } + } + } + return "http://127.0.0.1:${socket.localPort}/speakers.json" + } + + private fun OutputStream.raw(text: String) = write(text.toByteArray()) + + private fun ok(body: String) = { out: OutputStream -> + out.raw("HTTP/1.1 200 OK\r\nContent-Length: ${body.length}\r\nConnection: close\r\n\r\n$body") + } + + private fun failsWith(block: () -> Unit): String { + try { block() } catch (e: IOException) { return e.message ?: "" } + fail("expected an IOException") + return "" + } + + @Test fun readsAFile() { + val url = serve(ok("""{"schema":1}""")) + assertEquals("""{"schema":1}""", SpeakerListSync.fetch(url, requireHttps = false)) + } + + @Test fun plainHttpIsRefusedUnlessAllowed() { + val url = serve(ok("x")) + assertEquals("not https", failsWith { SpeakerListSync.fetch(url) }) + } + + @Test fun anErrorStatusIsAFailure() { + assertEquals("HTTP 404", failsWith { SpeakerListSync.fetch(serve { it.raw("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") }, requireHttps = false) }) + } + + @Test fun redirectsAreNotFollowed() { + val target = serve(ok("secret")) + val url = serve { it.raw("HTTP/1.1 302 Found\r\nLocation: $target\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") } + assertEquals("HTTP 302", failsWith { SpeakerListSync.fetch(url, requireHttps = false) }) + } + + @Test fun aFileThatDeclaresItselfTooBigIsRefusedUpFront() { + val url = serve { it.raw("HTTP/1.1 200 OK\r\nContent-Length: ${KnownSpeakersFile.MAX_BYTES + 1}\r\nConnection: close\r\n\r\nxxxx") } + assertEquals("file too big", failsWith { SpeakerListSync.fetch(url, requireHttps = false) }) + } + + @Test fun aFileThatGrowsPastTheLimitWhileStreamingIsRefused() { + // No length is announced, so only the running count can catch it. + val url = serve { + it.raw("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n") + it.write(ByteArray(KnownSpeakersFile.MAX_BYTES + 100) { 'x'.code.toByte() }) + } + assertEquals("file too big", failsWith { SpeakerListSync.fetch(url, requireHttps = false) }) + } + + @Test fun theLimitItselfIsAllowed() { + assertEquals(5, SpeakerListSync.readBounded(ByteArrayInputStream("abcde".toByteArray()), 5).length) + assertEquals("file too big", failsWith { SpeakerListSync.readBounded(ByteArrayInputStream("abcdef".toByteArray()), 5) }) + } + + @Test fun aBadAddressIsAFailureNotACrash() { + assertEquals("bad address", failsWith { SpeakerListSync.fetch("not a url", requireHttps = false) }) + } + + private fun list(version: Int) = """{"schema":1,"version":$version,"speakers":[]}""" + + @Test fun onlyAValidNewerListIsTaken() { + assertTrue(SpeakerListSync.evaluate(list(5), currentVersion = 4) is SpeakerListSync.Verdict.Newer) + assertEquals(SpeakerListSync.Verdict.NotNewer(4), SpeakerListSync.evaluate(list(4), currentVersion = 4)) + assertEquals(SpeakerListSync.Verdict.NotNewer(3), SpeakerListSync.evaluate(list(3), currentVersion = 4)) + assertEquals(SpeakerListSync.Verdict.Invalid, SpeakerListSync.evaluate("captive portal", currentVersion = 4)) + assertEquals(SpeakerListSync.Verdict.Invalid, SpeakerListSync.evaluate("""{"schema":9,"version":99,"speakers":[]}""", currentVersion = 4)) + } + + @Test fun checksOncePerDay() { + val hour = 60 * 60 * 1000L + val now = 1_000_000_000_000L + assertTrue(SpeakerListSync.isDue(0, now)) + assertFalse(SpeakerListSync.isDue(now - hour, now)) + assertFalse(SpeakerListSync.isDue(now - 23 * hour, now)) + assertTrue(SpeakerListSync.isDue(now - 25 * hour, now)) + assertTrue(SpeakerListSync.isDue(now + hour, now)) // the clock went backwards + } +} diff --git a/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt b/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt index e208fb86..85d5e704 100644 --- a/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt @@ -6,9 +6,12 @@ import com.aria.ariacast.PacketType import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue +import org.junit.Before import org.junit.Test class SpeakerReportTest { + @Before fun loadTheList() { TestSpeakers.load() } + private fun line(message: String, device: String? = null, count: Int = 1, time: String = "10:00:00.000") = PacketLog(time, PacketDirection.OUT, PacketType.HANDSHAKE, message, 0, count, device) diff --git a/app/src/test/java/com/aria/ariacast/quirks/SpeakersDoc.kt b/app/src/test/java/com/aria/ariacast/quirks/SpeakersDoc.kt index 71e29ad3..1e343fdf 100644 --- a/app/src/test/java/com/aria/ariacast/quirks/SpeakersDoc.kt +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakersDoc.kt @@ -1,20 +1,21 @@ package com.aria.ariacast.quirks -/** Renders the known-speaker table as docs/SPEAKERS.md. */ +/** Renders the list of known speakers as docs/SPEAKERS.md. */ object SpeakersDoc { - fun render(): String = buildString { + fun render(list: KnownSpeakersFile): String = buildString { appendLine("# Known speakers") appendLine() - appendLine("") + appendLine("") appendLine() appendLine("How speakers behave with AriaCast, what you see when something is wrong, and what to do.") appendLine("Only behavior with evidence is listed; a speaker that is not here is untested, not broken.") + appendLine("The app reads the same list (Settings → Known speakers) and keeps it up to date.") appendLine() for (verdict in Verdict.entries) { appendLine("## ${verdict.label}") appendLine() - val rows = DeviceQuirks.ALL.filter { it.verdict == verdict } + val rows = list.speakers.filter { it.verdict == verdict } if (rows.isEmpty()) { appendLine("Nothing recorded yet.") appendLine() @@ -32,10 +33,10 @@ object SpeakersDoc { } appendLine("## Add a speaker") appendLine() - appendLine("Long-press the speaker in the Send tab and choose **Report speaker** (or use the button in the") - appendLine("connection doctor). It shares who the speaker is and the log lines about it, with addresses") - appendLine("shortened. Paste that into a [new issue](https://github.com/AriaCast/AriaCast-app/issues/new) and") - appendLine("say whether it worked.") + appendLine("In the app, long-press the speaker in the Send tab and choose **Report speaker**, or answer the") + appendLine("question that appears the first time you cast to a new one. It opens a pre-filled") + appendLine("[issue](https://github.com/AriaCast/AriaCast-app/issues/new?template=speaker-report.yml); the logs are") + appendLine("copied for you to paste in. A maintainer reviews it and it joins the list.") } private fun cell(text: String) = text.replace("|", "\\|").replace("\n", " ") diff --git a/app/src/test/java/com/aria/ariacast/quirks/SpeakersDocTest.kt b/app/src/test/java/com/aria/ariacast/quirks/SpeakersDocTest.kt index 2840abe3..823dad55 100644 --- a/app/src/test/java/com/aria/ariacast/quirks/SpeakersDocTest.kt +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakersDocTest.kt @@ -10,7 +10,7 @@ class SpeakersDocTest { private val file = File("../docs/SPEAKERS.md") @Test fun docIsInSyncWithTheTable() { - val expected = SpeakersDoc.render() + val expected = SpeakersDoc.render(TestSpeakers.load()) if (System.getenv("UPDATE_SPEAKERS_DOC") == "1") file.writeText(expected) assertEquals( "docs/SPEAKERS.md is out of date. Regenerate it with: " + @@ -20,12 +20,17 @@ class SpeakersDocTest { } @Test fun entriesAreUniqueAndBackedByEvidence() { - assertEquals(DeviceQuirks.ALL.size, DeviceQuirks.ALL.map { it.id }.toSet().size) - DeviceQuirks.ALL.forEach { assertTrue("${it.id} has no evidence", it.evidence.isNotBlank()) } + val list = TestSpeakers.load().speakers + assertEquals(list.size, list.map { it.id }.toSet().size) + list.forEach { assertTrue("${it.id} has no evidence", it.evidence.isNotBlank()) } + } + + @Test fun theShippedListHasNoRejectedEntries() { + assertEquals(emptyList(), TestSpeakers.load().skipped) } @Test fun anythingThatIsNotPlainGoodSaysWhatTheUserWillSee() { - DeviceQuirks.ALL.filter { it.verdict != Verdict.GOOD }.forEach { + TestSpeakers.load().speakers.filter { it.verdict != Verdict.GOOD }.forEach { assertTrue("${it.id} lists no symptoms", it.symptoms.isNotEmpty()) } } diff --git a/app/src/test/java/com/aria/ariacast/quirks/TestSpeakers.kt b/app/src/test/java/com/aria/ariacast/quirks/TestSpeakers.kt new file mode 100644 index 00000000..530411b7 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/TestSpeakers.kt @@ -0,0 +1,14 @@ +package com.aria.ariacast.quirks + +import java.io.File + +/** The real list, read from data/speakers.json, put in use for a test. Tests run from app/. */ +object TestSpeakers { + val file = File("../data/speakers.json") + + fun load(): KnownSpeakersFile { + val parsed = KnownSpeakersFile.parse(file.readText()) ?: error("data/speakers.json does not parse") + KnownSpeakersStore.setForTesting(parsed) + return parsed + } +} diff --git a/data/speakers.json b/data/speakers.json new file mode 100644 index 00000000..e8b24e64 --- /dev/null +++ b/data/speakers.json @@ -0,0 +1,132 @@ +{ + "schema": 1, + "version": 1, + "updated": "2026-11-27", + "speakers": [ + { + "id": "sonos-airplay2", + "speaker": "Sonos (tested on Play:5)", + "protocol": "AirPlay 2", + "verdict": "good", + "match": { + "platform": "AirPlay2", + "mentions": [ + "sonos" + ] + }, + "symptoms": [ + "On 1.1.9 the AirPlay 2 stream did not play, while DLNA to the same speaker did." + ], + "whatToDo": "Update. Until then, cast to it over DLNA.", + "since": "1.1.9_hotfix", + "evidence": "[#48](https://github.com/AriaCast/AriaCast-app/issues/48), confirmed by the reporter after the hotfix" + }, + { + "id": "sonos-dlna", + "speaker": "Sonos (tested on Play:5)", + "protocol": "DLNA", + "verdict": "good", + "match": { + "platform": "DLNA", + "mentions": [ + "sonos" + ] + }, + "evidence": "[#48](https://github.com/AriaCast/AriaCast-app/issues/48), reporter: DLNA was working" + }, + { + "id": "wiim-dlna-restart", + "speaker": "WiiM (tested on Pro Plus)", + "protocol": "DLNA", + "verdict": "good", + "match": { + "platform": "DLNA", + "mentions": [ + "wiim", + "linkplay" + ] + }, + "symptoms": [ + "The track title changes but playback stays paused at 0:00 after every track change.", + "Pressing play in the WiiM app starts it again." + ], + "whatToDo": "Update: AriaCast now sends Play after every track change. If it still stops, press play once in the WiiM app and report it.", + "since": "2.0.0", + "evidence": "[#50](https://github.com/AriaCast/AriaCast-app/issues/50), fixed in the 2.0 line; the reporter's confirmation is not recorded", + "notes": { + "en": "WiiM players pause at 0:00 whenever they receive a new stream address. AriaCast starts playback again after every track change. If it still stops, press play once in the WiiM app and report it.", + "it": "I WiiM si fermano a 0:00 ogni volta che ricevono un nuovo indirizzo di stream. AriaCast riavvia la riproduzione a ogni cambio traccia. Se si ferma comunque, premi play una volta nell'app WiiM e segnalalo." + }, + "config": { + "dlnaPlayAfterSetUri": true + } + }, + { + "id": "shairport-airplay1", + "speaker": "shairport-sync", + "protocol": "AirPlay 1", + "verdict": "good", + "match": { + "platform": "AirPlay", + "mentions": [ + "shairport" + ] + }, + "evidence": "Maintainer's own test in [#48](https://github.com/AriaCast/AriaCast-app/issues/48); the AirPlay version is not stated there, so it is listed under AirPlay 1" + }, + { + "id": "shairport-airplay2-ptp", + "speaker": "shairport-sync", + "protocol": "AirPlay 2", + "verdict": "partial", + "match": { + "platform": "AirPlay2", + "mentions": [ + "shairport" + ] + }, + "symptoms": [ + "The speaker accepts the connection but timing is off, or AriaCast drops to AirPlay 1." + ], + "whatToDo": "Nothing to do: AriaCast tries NTP timing and falls back to AirPlay 1 on its own. Real PTP needs root.", + "evidence": "Code: PtpMaster (shairport-sync with nqptp accepts only PTP timing)", + "notes": { + "en": "AirPlay 2 receivers built on shairport-sync need PTP timing, which Android apps can't provide without root. AriaCast tries NTP timing and falls back to AirPlay 1 on its own.", + "it": "I ricevitori AirPlay 2 basati su shairport-sync richiedono la sincronizzazione PTP, che le app Android non possono offrire senza root. AriaCast prova con NTP e passa da solo ad AirPlay 1." + } + }, + { + "id": "appletv-airplay-video-pairing", + "speaker": "Apple TV", + "protocol": "AirPlay (video)", + "verdict": "partial", + "match": { + "mentions": [ + "appletv" + ] + }, + "symptoms": [ + "On Apple TVs that require pairing, casting a video fails with \"This AirPlay device requires pairing for video\". Audio casting is not affected." + ], + "whatToDo": "Cast audio only. Video works with Apple TVs that allow unpaired access.", + "evidence": "Roadmap status table and VideoTargets.kt" + }, + { + "id": "echo-show5-hub-no-airplay", + "speaker": "Amazon Echo Show 5 (1st gen), Echo Hub", + "protocol": "No local protocol", + "verdict": "unsupported", + "match": { + "mentions": [ + "echo show 5", + "echo hub" + ] + }, + "symptoms": [ + "The speaker does not appear in AriaCast, and it has no AirPlay." + ], + "whatToDo": "Bluetooth is the only local way in, and AriaCast does not send to Bluetooth speakers yet.", + "evidence": "Maintainer's own devices; Alexa has no local streaming protocol" + } + ] +} diff --git a/docs/SPEAKERS.md b/docs/SPEAKERS.md index e0eabb40..9e5adba2 100644 --- a/docs/SPEAKERS.md +++ b/docs/SPEAKERS.md @@ -1,10 +1,11 @@ # Known speakers - + How speakers behave with AriaCast, what you see when something is wrong, and what to do. Only behavior with evidence is listed; a speaker that is not here is untested, not broken. +The app reads the same list (Settings → Known speakers) and keeps it up to date. ## Works @@ -26,9 +27,15 @@ Only behavior with evidence is listed; a speaker that is not here is untested, n Nothing recorded yet. +## Not supported + +| Speaker | Protocol | If it goes wrong | What to do | Since | Evidence | +|---|---|---|---|---|---| +| Amazon Echo Show 5 (1st gen), Echo Hub | No local protocol | The speaker does not appear in AriaCast, and it has no AirPlay. | Bluetooth is the only local way in, and AriaCast does not send to Bluetooth speakers yet. | | Maintainer's own devices; Alexa has no local streaming protocol | + ## Add a speaker -Long-press the speaker in the Send tab and choose **Report speaker** (or use the button in the -connection doctor). It shares who the speaker is and the log lines about it, with addresses -shortened. Paste that into a [new issue](https://github.com/AriaCast/AriaCast-app/issues/new) and -say whether it worked. +In the app, long-press the speaker in the Send tab and choose **Report speaker**, or answer the +question that appears the first time you cast to a new one. It opens a pre-filled +[issue](https://github.com/AriaCast/AriaCast-app/issues/new?template=speaker-report.yml); the logs are +copied for you to paste in. A maintainer reviews it and it joins the list. From 0201ee743995cb80ea9bdf209ac2a8ffca873b28 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 10:41:10 +0000 Subject: [PATCH 05/14] Report a speaker through a pre-filled GitHub issue, and propose list entries from it - "Report speaker" opens the Speaker report issue form pre-filled (speaker, protocol, details, version) and copies the log for the user to paste; "Share log" keeps the old share sheet. The form's options and the app's protocol names are checked against each other by a test. - scripts/speaker_report.py turns a report into a proposed entry for data/speakers.json. The issue text is untrusted: it is cut into fields, validated by the same rules the app applies, and written by a JSON serializer; the log is never stored, and config can never come from an issue. - The workflow opens a pull request for review, passes the issue to the script only through environment variables, and runs on a GitHub-hosted runner. - A golden file ties the script to the app: the script's tests check it produces exactly scripts/testdata/generated-sample.json, and the app's tests check it parses that file with no skipped entries. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01XZTMETapPkNvc9xdPLcfZu --- .github/ISSUE_TEMPLATE/speaker-report.yml | 67 ++++++ .github/workflows/scripts-test.yml | 14 ++ .github/workflows/speaker-report.yml | 56 +++++ .gitignore | 4 + CHANGELOG.md | 9 +- .../com/aria/ariacast/quirks/SpeakerIssue.kt | 62 ++++++ .../com/aria/ariacast/quirks/SpeakerReport.kt | 21 +- .../aria/ariacast/ui/SpeakerReportAction.kt | 77 ++++--- .../aria/ariacast/ui/doctor/DoctorScreen.kt | 4 +- .../com/aria/ariacast/ui/home/SendScreen.kt | 11 +- app/src/main/res/values-it/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + .../ariacast/quirks/KnownSpeakersFileTest.kt | 13 ++ .../aria/ariacast/quirks/SpeakerIssueTest.kt | 69 +++++++ .../aria/ariacast/quirks/SpeakerReportTest.kt | 11 + scripts/speaker_report.py | 158 +++++++++++++++ scripts/test_speaker_report.py | 191 ++++++++++++++++++ scripts/testdata/base.json | 20 ++ scripts/testdata/generated-sample.json | 37 ++++ scripts/testdata/issue-acme.md | 31 +++ 20 files changed, 817 insertions(+), 42 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/speaker-report.yml create mode 100644 .github/workflows/scripts-test.yml create mode 100644 .github/workflows/speaker-report.yml create mode 100644 app/src/main/java/com/aria/ariacast/quirks/SpeakerIssue.kt create mode 100644 app/src/test/java/com/aria/ariacast/quirks/SpeakerIssueTest.kt create mode 100644 scripts/speaker_report.py create mode 100644 scripts/test_speaker_report.py create mode 100644 scripts/testdata/base.json create mode 100644 scripts/testdata/generated-sample.json create mode 100644 scripts/testdata/issue-acme.md diff --git a/.github/ISSUE_TEMPLATE/speaker-report.yml b/.github/ISSUE_TEMPLATE/speaker-report.yml new file mode 100644 index 00000000..6a414a26 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/speaker-report.yml @@ -0,0 +1,67 @@ +name: Speaker report +description: Tell us how a speaker works, or doesn't, with AriaCast +title: "Speaker: " +labels: ["speaker-report"] +body: + - type: markdown + attributes: + value: | + Thanks. A bot turns this into a proposed entry for the [list of known speakers](../blob/main/docs/SPEAKERS.md), + and a maintainer reviews it before it is added. **Only the fields below are used; the log is never copied into the list.** + The app fills most of this in for you (Long-press a speaker, **Report speaker**). + - type: input + id: speaker + attributes: + label: Speaker + description: Brand and model, for example "WiiM Pro Plus". + validations: + required: true + - type: dropdown + id: protocol + attributes: + label: Protocol + options: + - AirPlay 2 + - AirPlay 1 + - DLNA + - Google Cast + - Snapcast + - Sendspin + - AriaCast + - VBAN + - No local protocol + - Other + validations: + required: true + - type: dropdown + id: verdict + attributes: + label: How does it work? + options: + - Works + - Works with a catch + - Does not work + - Not supported (AriaCast cannot find or reach it) + validations: + required: true + - type: textarea + id: symptoms + attributes: + label: What happens + description: What you see or hear when something goes wrong. One thing per line. Leave empty if it works. + - type: textarea + id: fingerprint + attributes: + label: Speaker details + description: Filled in by the app. Addresses are shortened. + render: text + - type: textarea + id: logs + attributes: + label: Log + description: The app copied it for you; paste it here. It helps us, and stays in this issue. + render: text + - type: input + id: version + attributes: + label: AriaCast version diff --git a/.github/workflows/scripts-test.yml b/.github/workflows/scripts-test.yml new file mode 100644 index 00000000..03004926 --- /dev/null +++ b/.github/workflows/scripts-test.yml @@ -0,0 +1,14 @@ +name: Scripts + +on: + push: + paths: ["scripts/**", "data/**", ".github/ISSUE_TEMPLATE/**"] + pull_request: + paths: ["scripts/**", "data/**", ".github/ISSUE_TEMPLATE/**"] + +jobs: + speaker-report: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: python3 -B -m unittest discover -s scripts -p "test_*.py" -v diff --git a/.github/workflows/speaker-report.yml b/.github/workflows/speaker-report.yml new file mode 100644 index 00000000..8e9dafa6 --- /dev/null +++ b/.github/workflows/speaker-report.yml @@ -0,0 +1,56 @@ +name: Speaker report + +# Turns a "Speaker report" issue into a pull request that proposes an entry for data/speakers.json. +# A maintainer reviews and merges it; nothing reaches the list, or the apps that read it, before that. +# +# The issue text is written by anyone, so: +# - it only reaches the script through environment variables, never inside a shell command; +# - the script validates every field and writes the file with a JSON serializer; +# - the job runs on a GitHub-hosted runner, not the self-hosted one the build uses. +# The repository setting "Allow GitHub Actions to create and approve pull requests" must be on. + +on: + issues: + types: [opened] + +permissions: + contents: write + pull-requests: write + issues: write + +jobs: + propose: + if: contains(github.event.issue.labels.*.name, 'speaker-report') + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Make the proposed entry + id: entry + env: + ISSUE_BODY: ${{ github.event.issue.body }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + run: python3 scripts/speaker_report.py data/speakers.json "$RUNNER_TEMP/comment.md" + + - name: Open a pull request + if: steps.entry.outputs.changed == 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + run: | + branch="speaker-report/${ISSUE_NUMBER}" + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git checkout -b "$branch" + git add data/speakers.json + git commit -m "Propose a speaker entry from issue #${ISSUE_NUMBER}" + git push origin "$branch" + gh pr create --base main --head "$branch" \ + --title "Speaker report #${ISSUE_NUMBER}" \ + --body "Proposed from #${ISSUE_NUMBER}. The entry is unverified: check the verdict and the symptoms against the issue's log, then regenerate docs/SPEAKERS.md with \`UPDATE_SPEAKERS_DOC=1 ./gradlew :app:testGithubDebugUnitTest --tests '*SpeakersDocTest*'\` before merging." + + - name: Reply on the issue + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + run: gh issue comment "$ISSUE_NUMBER" --body-file "$RUNNER_TEMP/comment.md" diff --git a/.gitignore b/.gitignore index a3fb63f4..76d68936 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,7 @@ fastlane/test_output .codegraph/ .rtk/ CLAUDE.md + +# Generated +.kotlin/ +__pycache__/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 92793fc4..70bf7a97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,9 +66,12 @@ casting, a new interface, and AriaCompanion 2. receiver's handshake, how long a connection lasted and each reconnect, and the receiver's own underrun and overrun counts. DLNA speakers are asked their state every 10 seconds while you cast to them, which is one small request. -- **Report speaker**: long-press a speaker (or use the doctor) to share a report with who the - speaker is, what is known about it, the cast state and its log lines, with addresses shortened. - Works for speakers you never managed to connect to. +- **Report speaker**: long-press a speaker (or use the doctor) to open a pre-filled report on GitHub + with who the speaker is, what is known about it and the cast state; its log lines are copied to + paste in, with addresses shortened. Works for speakers you never managed to connect to. A bot turns + the report into a proposed entry for the list of known speakers in a pull request, which a + maintainer reviews; the log is never copied into the list. "Share log" in the same menu sends + the whole report through the share sheet instead. ### Built in, previously plugins - Music Assistant player picker, connection doctor, visualizer, add speaker by address. diff --git a/app/src/main/java/com/aria/ariacast/quirks/SpeakerIssue.kt b/app/src/main/java/com/aria/ariacast/quirks/SpeakerIssue.kt new file mode 100644 index 00000000..ae5c7c17 --- /dev/null +++ b/app/src/main/java/com/aria/ariacast/quirks/SpeakerIssue.kt @@ -0,0 +1,62 @@ +package com.aria.ariacast.quirks + +import java.net.URLEncoder + +/** + * The address of a pre-filled "Speaker report" issue on GitHub. The field names are the ids in + * .github/ISSUE_TEMPLATE/speaker-report.yml, and the dropdown values are its option labels. + */ +object SpeakerIssue { + private const val NEW_ISSUE = "https://github.com/AriaCast/AriaCast-app/issues/new" + const val TEMPLATE = "speaker-report.yml" + + /** A browser refuses very long addresses, and GitHub's limit is lower than most. */ + const val MAX_URL = 6000 + + val VERDICT_WORKS = "Works" + val VERDICT_CATCH = "Works with a catch" + val VERDICT_FAILS = "Does not work" + + /** How the app names a protocol, in the words of the form's dropdown. */ + fun protocolLabel(platform: String?): String = when (platform) { + "AirPlay2" -> "AirPlay 2" + "AirPlay" -> "AirPlay 1" + "DLNA" -> "DLNA" + "Google Cast" -> "Google Cast" + "Snapcast" -> "Snapcast" + "Sendspin" -> "Sendspin" + "AriaCast" -> "AriaCast" + "VBAN" -> "VBAN" + null -> "No local protocol" + else -> "Other" + } + + /** The name to propose: brand and model if the speaker said them, else what it is called. */ + fun speakerName(identity: DeviceIdentity): String = + listOfNotNull(identity.manufacturer, identity.model).joinToString(" ").trim().ifEmpty { identity.name } + + fun url(identity: DeviceIdentity, details: String, appVersion: String?, verdict: String? = null): String { + fun build(details: String): String { + val fields = listOfNotNull( + "template" to TEMPLATE, + "title" to "Speaker: ${speakerName(identity)}", + "speaker" to speakerName(identity), + "protocol" to protocolLabel(identity.platform), + verdict?.let { "verdict" to it }, + "fingerprint" to details, + appVersion?.let { "version" to it }, + ) + return NEW_ISSUE + "?" + fields.joinToString("&") { (k, v) -> "$k=${encode(v)}" } + } + // The details are the long part: cut them rather than lose the address altogether. + var text = details + var url = build(text) + while (url.length > MAX_URL && text.length > 200) { + text = text.take(text.length * 3 / 4) + url = build(text) + } + return url + } + + private fun encode(value: String) = URLEncoder.encode(value, "UTF-8").replace("+", "%20") +} diff --git a/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt b/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt index c16f94c0..dd5a3e0f 100644 --- a/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt +++ b/app/src/main/java/com/aria/ariacast/quirks/SpeakerReport.kt @@ -36,16 +36,12 @@ object SpeakerReport { val settings: String? = null, ) - fun build( + /** Who the speaker is and what is known about it, without the log. Addresses are shortened. */ + fun summary( context: Context, identity: DeviceIdentity, - host: String, known: List, - logs: List, ): String = buildString { - appendLine("AriaCast speaker report") - appendLine("Addresses are shortened to their first two parts; speaker names are included.") - appendLine() appendLine("App: ${context.app}") appendLine("Phone: ${context.device}, Android ${context.android}") appendLine("Speaker: ${identity.reportLine()}") @@ -56,6 +52,19 @@ object SpeakerReport { } context.castState?.let { appendLine("Cast: $it") } context.settings?.let { appendLine("Settings: $it") } + }.trimEnd().let(::maskAddresses) + + fun build( + context: Context, + identity: DeviceIdentity, + host: String, + known: List, + logs: List, + ): String = buildString { + appendLine("AriaCast speaker report") + appendLine("Addresses are shortened to their first two parts; speaker names are included.") + appendLine() + appendLine(summary(context, identity, known)) appendLine() val lines = logFor(logs, host, identity.name) if (lines.isEmpty()) { diff --git a/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt b/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt index c33ccf5b..9285242f 100644 --- a/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt +++ b/app/src/main/java/com/aria/ariacast/ui/SpeakerReportAction.kt @@ -1,52 +1,73 @@ package com.aria.ariacast.ui +import android.content.ClipData +import android.content.ClipboardManager import android.content.Context import android.content.Intent +import android.net.Uri import android.os.Build +import android.widget.Toast import com.aria.ariacast.AudioCastService import com.aria.ariacast.PacketLogger import com.aria.ariacast.R import com.aria.ariacast.quirks.DeviceIdentity import com.aria.ariacast.quirks.DeviceQuirks +import com.aria.ariacast.quirks.SpeakerIssue import com.aria.ariacast.quirks.SpeakerReport /** - * "Report speaker": opens the share sheet with who the speaker is, what is known about it and - * the log lines that concern it. The sheet's own "Copy" puts it on the clipboard. - * - * Works for any speaker in the list, cast to or not, so a speaker that never connects can be - * reported too (its report then says it has no log yet). + * What the report needs about the phone, the app and the cast in progress. Works for any speaker + * in the list, cast to or not, so a speaker that never connects can be reported too (its report + * then says it has no log yet). */ -fun shareSpeakerReport( - context: Context, - service: AudioCastService?, - platform: String?, - name: String, - host: String, - extra: String?, -) { - val identity = DeviceIdentity.of(platform, name, extra) +private fun reportContext(context: Context, service: AudioCastService?, host: String): SpeakerReport.Context { val version = runCatching { context.packageManager.getPackageInfo(context.packageName, 0).versionName }.getOrNull() val active = service?.activeDestinations?.value?.firstOrNull { it.host == host } val sound = service?.soundFor(host) - val report = SpeakerReport.build( - context = SpeakerReport.Context( - app = "${context.getString(R.string.app_name)} ${version ?: "?"}", - android = "${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})", - device = "${Build.MANUFACTURER} ${Build.MODEL}", - castState = service?.let { s -> listOfNotNull(s.state.value.name, s.lastError.value?.let { "last error: $it" }).joinToString(", ") }, - settings = if (service == null || sound == null) null else - "delay=${active?.delayMs ?: 0} ms, bass=${sound.bassDb} dB, treble=${sound.trebleDb} dB, level=${sound.trimDb} dB, leveling=${sound.leveling}", - ), - identity = identity, - host = host, - known = DeviceQuirks.matching(identity), - logs = PacketLogger.logsFor(host, name), + return SpeakerReport.Context( + app = "${context.getString(R.string.app_name)} ${version ?: "?"}", + android = "${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})", + device = "${Build.MANUFACTURER} ${Build.MODEL}", + castState = service?.let { s -> listOfNotNull(s.state.value.name, s.lastError.value?.let { "last error: $it" }).joinToString(", ") }, + settings = if (service == null || sound == null) null else + "delay=${active?.delayMs ?: 0} ms, bass=${sound.bassDb} dB, treble=${sound.trebleDb} dB, level=${sound.trimDb} dB, leveling=${sound.leveling}", ) +} + +private fun fullReport(context: Context, service: AudioCastService?, platform: String?, name: String, host: String, extra: String?): String { + val identity = DeviceIdentity.of(platform, name, extra) + return SpeakerReport.build(reportContext(context, service, host), identity, host, DeviceQuirks.matching(identity), PacketLogger.logsFor(host, name)) +} + +/** Opens the share sheet with the full report; its own "Copy" puts it on the clipboard. */ +fun shareSpeakerLog(context: Context, service: AudioCastService?, platform: String?, name: String, host: String, extra: String?) { val send = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.report_speaker_subject, name)) - putExtra(Intent.EXTRA_TEXT, report) + putExtra(Intent.EXTRA_TEXT, fullReport(context, service, platform, name, host, extra)) } context.startActivity(Intent.createChooser(send, context.getString(R.string.report_speaker)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } + +/** + * "Report speaker": opens a pre-filled issue on GitHub and puts the log on the clipboard, since a + * log is far too long for an address. [verdict] pre-selects how it works when the user has said so + * already (see [SpeakerIssue]). + */ +fun reportSpeaker( + context: Context, + service: AudioCastService?, + platform: String?, + name: String, + host: String, + extra: String?, + verdict: String? = null, +) { + val identity = DeviceIdentity.of(platform, name, extra) + val ctx = reportContext(context, service, host) + val log = SpeakerReport.build(ctx, identity, host, DeviceQuirks.matching(identity), PacketLogger.logsFor(host, name)) + context.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("AriaCast speaker report", log)) + val url = SpeakerIssue.url(identity, SpeakerReport.summary(ctx, identity, DeviceQuirks.matching(identity)), ctx.app.substringAfter(' '), verdict) + Toast.makeText(context, context.getString(R.string.report_speaker_log_copied), Toast.LENGTH_LONG).show() + context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) +} diff --git a/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt b/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt index 1addc88f..f0f9d81e 100644 --- a/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt +++ b/app/src/main/java/com/aria/ariacast/ui/doctor/DoctorScreen.kt @@ -15,7 +15,7 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Info import com.aria.ariacast.quirks.DeviceIdentity -import com.aria.ariacast.ui.shareSpeakerReport +import com.aria.ariacast.ui.reportSpeaker import androidx.compose.material.icons.filled.BugReport import com.aria.ariacast.quirks.DeviceQuirks import androidx.compose.material.icons.automirrored.filled.ArrowBack @@ -219,7 +219,7 @@ fun DoctorScreen(controller: AppController, onBack: () -> Unit) { } service?.activeDestinations?.value?.forEach { d -> ListRow(stringResource(R.string.report_speaker_named, d.name), leading = { LeadingIcon(Icons.Filled.BugReport) }) { - shareSpeakerReport(context, service, d.platform, d.name, d.host, d.extra) + reportSpeaker(context, service, d.platform, d.name, d.host, d.extra) } } } diff --git a/app/src/main/java/com/aria/ariacast/ui/home/SendScreen.kt b/app/src/main/java/com/aria/ariacast/ui/home/SendScreen.kt index 02b23f03..c8466ba1 100644 --- a/app/src/main/java/com/aria/ariacast/ui/home/SendScreen.kt +++ b/app/src/main/java/com/aria/ariacast/ui/home/SendScreen.kt @@ -28,6 +28,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Share import androidx.compose.material.icons.filled.BugReport import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Cast @@ -113,7 +114,8 @@ import com.aria.ariacast.ui.ListGroup import com.aria.ariacast.ui.ListRow import com.aria.ariacast.ui.Screen import com.aria.ariacast.ui.ScreenList -import com.aria.ariacast.ui.shareSpeakerReport +import com.aria.ariacast.ui.reportSpeaker +import com.aria.ariacast.ui.shareSpeakerLog import com.aria.ariacast.ui.SectionHeader import com.aria.ariacast.ui.StatusBanner import com.aria.ariacast.ui.SubScreenScaffold @@ -307,7 +309,8 @@ private fun Speakers(controller: AppController, selection: SourceSelection) { SpeakerRow(server, isActive(server), onClick = { controller.castTo(listOf(server), selection.source, selection.inputDeviceId) }, onRemove = { controller.removeServer(server) }, - onReport = { shareSpeakerReport(context, service, server.platform, server.name, server.host, server.extra) }) + onReport = { reportSpeaker(context, service, server.platform, server.name, server.host, server.extra) }, + onShareLog = { shareSpeakerLog(context, service, server.platform, server.name, server.host, server.extra) }) } } } @@ -316,7 +319,7 @@ private fun Speakers(controller: AppController, selection: SourceSelection) { } @Composable -private fun SpeakerRow(server: Server, active: Boolean, onClick: () -> Unit, onRemove: () -> Unit, onReport: () -> Unit) { +private fun SpeakerRow(server: Server, active: Boolean, onClick: () -> Unit, onRemove: () -> Unit, onReport: () -> Unit, onShareLog: () -> Unit) { var menu by remember { mutableStateOf(false) } Box { ListRow( @@ -332,6 +335,8 @@ private fun SpeakerRow(server: Server, active: Boolean, onClick: () -> Unit, onR DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { DropdownMenuItem(text = { Text(stringResource(R.string.report_speaker)) }, leadingIcon = { Icon(Icons.Filled.BugReport, null) }, onClick = { menu = false; onReport() }) + DropdownMenuItem(text = { Text(stringResource(R.string.share_speaker_log)) }, leadingIcon = { Icon(Icons.Filled.Share, null) }, + onClick = { menu = false; onShareLog() }) DropdownMenuItem(text = { Text(stringResource(R.string.remove)) }, leadingIcon = { Icon(Icons.Filled.Delete, null) }, onClick = { menu = false; onRemove() }) } diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 5dc0753c..f7f92f50 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -267,6 +267,8 @@ Segnala altoparlante Segnala %1$s Segnalazione AriaCast: %1$s + Log copiato. Incollalo nel campo «Log» della segnalazione. + Condividi il log Altoparlanti noti Cosa funziona, cosa ha un limite e cosa AriaCast non può raggiungere. Altoparlanti provati da altri, con cosa osservare e cosa fare. L\'elenco viene dal progetto e si aggiorna da solo. Le descrizioni sono in inglese. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8771bcea..ebc0c25c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -370,6 +370,8 @@ Report speaker Report %1$s AriaCast report: %1$s + Log copied. Paste it in the “Log” field of the report. + Share log Known speakers What works, what has a catch, and what AriaCast cannot reach. Speakers other people have tried, with what to look for and what to do. The list comes from the project and updates itself. Descriptions are in English. diff --git a/app/src/test/java/com/aria/ariacast/quirks/KnownSpeakersFileTest.kt b/app/src/test/java/com/aria/ariacast/quirks/KnownSpeakersFileTest.kt index 0829d4d2..5bf1bb73 100644 --- a/app/src/test/java/com/aria/ariacast/quirks/KnownSpeakersFileTest.kt +++ b/app/src/test/java/com/aria/ariacast/quirks/KnownSpeakersFileTest.kt @@ -136,4 +136,17 @@ class KnownSpeakersFileTest { assertSame(newer, KnownSpeakersStore.choose(null, newer)) assertEquals(0, KnownSpeakersStore.choose(null, null).speakers.size) } + + @Test fun whatTheBotProposesIsAcceptedByTheApp() { + // scripts/testdata/generated-sample.json is written by scripts/speaker_report.py, and its own + // tests check the script still produces exactly this file. + val list = KnownSpeakersFile.parse(java.io.File("../scripts/testdata/generated-sample.json").readText())!! + assertEquals(emptyList(), list.skipped) + assertEquals(listOf("wiim-dlna-restart", "acme-play-3-dlna"), list.speakers.map { it.id }) + val acme = list.speakers.last() + assertEquals(Verdict.PARTIAL, acme.verdict) + assertTrue(acme.evidence.contains("unverified")) + assertTrue(acme.appliesTo(DeviceIdentity("DLNA", "Den", "Play 3 Pro", "Acme Audio"))) + assertFalse(acme.appliesTo(DeviceIdentity("AirPlay2", "Den", "Play 3 Pro"))) + } } diff --git a/app/src/test/java/com/aria/ariacast/quirks/SpeakerIssueTest.kt b/app/src/test/java/com/aria/ariacast/quirks/SpeakerIssueTest.kt new file mode 100644 index 00000000..6867be73 --- /dev/null +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakerIssueTest.kt @@ -0,0 +1,69 @@ +package com.aria.ariacast.quirks + +import java.net.URLDecoder +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class SpeakerIssueTest { + private val wiim = DeviceIdentity("DLNA", "Den", "WiiM Pro Plus", "Linkplay") + + /** The query of [url] as a map, decoded the way GitHub decodes it. */ + private fun query(url: String): Map = + url.substringAfter('?').split('&').associate { it.substringBefore('=') to URLDecoder.decode(it.substringAfter('='), "UTF-8") } + + @Test fun pointsAtTheFormWithItsFieldIds() { + val url = SpeakerIssue.url(wiim, "Speaker: x", "2.0.0") + assertTrue(url.startsWith("https://github.com/AriaCast/AriaCast-app/issues/new?")) + val q = query(url) + assertEquals("speaker-report.yml", q["template"]) + assertEquals("Linkplay WiiM Pro Plus", q["speaker"]) + assertEquals("Speaker: Linkplay WiiM Pro Plus", q["title"]) + assertEquals("DLNA", q["protocol"]) + assertEquals("Speaker: x", q["fingerprint"]) + assertEquals("2.0.0", q["version"]) + } + + @Test fun theVerdictIsOnlySetWhenKnown() { + assertNull(query(SpeakerIssue.url(wiim, "d", null))["verdict"]) + assertEquals("Does not work", query(SpeakerIssue.url(wiim, "d", null, SpeakerIssue.VERDICT_FAILS))["verdict"]) + } + + @Test fun protocolsUseTheFormsWords() { + assertEquals("AirPlay 2", SpeakerIssue.protocolLabel("AirPlay2")) + assertEquals("AirPlay 1", SpeakerIssue.protocolLabel("AirPlay")) + assertEquals("No local protocol", SpeakerIssue.protocolLabel(null)) + assertEquals("Other", SpeakerIssue.protocolLabel("SomethingNew")) + } + + @Test fun everyProtocolTheAppUsesIsAnOptionInTheForm() { + val form = java.io.File("../.github/ISSUE_TEMPLATE/speaker-report.yml").readText() + listOf("AirPlay2", "AirPlay", "DLNA", "Google Cast", "Snapcast", "Sendspin", "AriaCast", "VBAN", null, "x").forEach { + assertTrue("${SpeakerIssue.protocolLabel(it)} is not an option in the form", form.contains("- ${SpeakerIssue.protocolLabel(it)}\n")) + } + listOf(SpeakerIssue.VERDICT_WORKS, SpeakerIssue.VERDICT_CATCH, SpeakerIssue.VERDICT_FAILS).forEach { + assertTrue("$it is not an option in the form", form.contains("- $it\n")) + } + } + + @Test fun textThatLooksLikeUrlSyntaxIsEncoded() { + val nasty = DeviceIdentity("DLNA", "a&b=c#d") + val q = query(SpeakerIssue.url(nasty, "line one\nline two & more = # ?", null)) + assertEquals("a&b=c#d", q["speaker"]) + assertEquals("line one\nline two & more = # ?", q["fingerprint"]) + assertFalse(SpeakerIssue.url(nasty, "x", null).contains(" ")) + } + + @Test fun aLongDetailIsCutSoTheAddressStillWorks() { + val url = SpeakerIssue.url(wiim, "y".repeat(50_000), "2.0.0") + assertTrue(url.length <= SpeakerIssue.MAX_URL) + assertEquals("Linkplay WiiM Pro Plus", query(url)["speaker"]) + assertTrue(query(url)["fingerprint"]!!.isNotEmpty()) + } + + @Test fun aSpeakerThatNamesNothingIsCalledByItsName() { + assertEquals("Kitchen", SpeakerIssue.speakerName(DeviceIdentity("AirPlay2", "Kitchen"))) + } +} diff --git a/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt b/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt index 85d5e704..ab5e8036 100644 --- a/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt +++ b/app/src/test/java/com/aria/ariacast/quirks/SpeakerReportTest.kt @@ -74,4 +74,15 @@ class SpeakerReportTest { assertTrue(text.contains("Known: nothing recorded for this speaker yet")) assertTrue(text.contains("No log lines for this speaker")) } + + @Test fun theSummaryIsTheReportWithoutTheLog() { + val summary = SpeakerReport.summary( + SpeakerReport.Context("AriaCast 2.0.0", "14 (API 34)", "Google Pixel 8", castState = "CASTING"), + wiim, DeviceQuirks.matching(wiim), + ) + assertTrue(summary.startsWith("App: AriaCast 2.0.0")) + assertTrue(summary.contains("Speaker: protocol=DLNA, manufacturer=Linkplay, model=WiiM Pro Plus, name=Den")) + assertTrue(summary.contains("Cast: CASTING")) + assertFalse(summary.contains("Log")) + } } diff --git a/scripts/speaker_report.py b/scripts/speaker_report.py new file mode 100644 index 00000000..2757a0a6 --- /dev/null +++ b/scripts/speaker_report.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Turn a "Speaker report" issue into a proposed entry in data/speakers.json. + +Run by .github/workflows/speaker-report.yml, which then opens a pull request for a maintainer +to review. The issue text is written by anyone, so it is only ever read as data here: it is +cut into fields, each field is checked against a fixed set of rules (the same ones the app +applies when it reads the list), and the file is written back by a JSON serializer. Nothing +from the issue is run, interpolated into a command, or copied unchecked, and the log field is +never stored. + + ISSUE_BODY, ISSUE_NUMBER, GITHUB_REPOSITORY from the workflow's environment + python3 scripts/speaker_report.py data/speakers.json comment.md +""" +import datetime +import json +import os +import re +import sys + +PLATFORMS = { + "AirPlay 2": "AirPlay2", + "AirPlay 1": "AirPlay", + "DLNA": "DLNA", + "Google Cast": "Google Cast", + "Snapcast": "Snapcast", + "Sendspin": "Sendspin", + "AriaCast": "AriaCast", + "VBAN": "VBAN", + "No local protocol": None, + "Other": None, +} +VERDICTS = { + "Works": "good", + "Works with a catch": "partial", + "Does not work": "bad", + "Not supported (AriaCast cannot find or reach it)": "unsupported", +} +ID_PATTERN = re.compile(r"[a-z0-9][a-z0-9-]{2,63}") +CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]") +MAX_ENTRIES = 500 + + +def parse_form(body): + """Cut a rendered issue form into {label: text}. GitHub writes each field as `### Label`.""" + fields = {} + label = None + lines = [] + for line in (body or "").replace("\r\n", "\n").split("\n"): + if line.startswith("### "): + if label is not None: + fields[label] = "\n".join(lines).strip() + label, lines = line[4:].strip(), [] + elif label is not None: + lines.append(line) + if label is not None: + fields[label] = "\n".join(lines).strip() + return {k: ("" if v == "_No response_" else v) for k, v in fields.items()} + + +def clean(text, limit): + """One line of plain text: control characters out, whitespace collapsed, cut to `limit`.""" + text = CONTROL.sub("", text or "") + return re.sub(r"\s+", " ", text).strip()[:limit] + + +def slug(text): + return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:60] + + +def mention_for(fields, speaker): + """The phrase a speaker is recognised by: the model the app reported, else what was typed.""" + found = re.search(r"model=(.*?)(?:, (?:name|manufacturer|protocol)=|$)", fields.get("Speaker details", ""), re.M) + phrase = clean(found.group(1) if found else speaker, 40).lower() + # At least three letters or digits: a name of punctuation would recognise nothing. + return phrase if len(re.sub(r"[^a-z0-9]", "", phrase)) >= 3 else None + + +def build_entry(fields, number, repo, doc): + """Returns (entry, None) or (None, why not).""" + speaker = clean(fields.get("Speaker", ""), 80) + protocol = clean(fields.get("Protocol", ""), 40) + verdict = VERDICTS.get(clean(fields.get("How does it work?", ""), 80)) + if not speaker: + return None, "The *Speaker* field is empty." + if protocol not in PLATFORMS: + return None, "The *Protocol* is not one of the options in the form." + if verdict is None: + return None, "*How does it work?* is not one of the options in the form." + symptoms = [s for s in (clean(l, 240) for l in fields.get("What happens", "").split("\n")) if s][:8] + if verdict != "good" and not symptoms: + return None, "Please describe what happens in *What happens*: an entry that does not simply work needs its symptoms." + mention = mention_for(fields, speaker) + if mention is None: + return None, "The speaker's name is too short to recognise it by." + platform = PLATFORMS[protocol] + for existing in doc["speakers"]: + if mention in existing["match"].get("mentions", []) and existing["match"].get("platform") == platform: + return None, "This speaker is already listed as `%s`; a maintainer can add your report as evidence there." % existing["id"] + if len(doc["speakers"]) >= MAX_ENTRIES: + return None, "The list is full." + + base = slug("%s %s" % (speaker, protocol)) or "speaker" + taken = {s["id"] for s in doc["speakers"]} + entry_id, n = base, 2 + while entry_id in taken or not ID_PATTERN.fullmatch(entry_id): + entry_id = "%s-%d" % (base, n) + n += 1 + if n > 99: + return None, "Could not make an id for this speaker." + + entry = { + "id": entry_id, + "speaker": speaker, + "protocol": protocol, + "verdict": verdict, + "match": {"platform": platform, "mentions": [mention]} if platform else {"mentions": [mention]}, + } + if symptoms: + entry["symptoms"] = symptoms + entry["evidence"] = "[#%d](https://github.com/%s/issues/%d), unverified report" % (number, repo, number) + return entry, None + + +def main(argv, env): + data_path, comment_path = argv[1], argv[2] + number = int(env["ISSUE_NUMBER"]) + repo = env["GITHUB_REPOSITORY"] + if not re.fullmatch(r"[A-Za-z0-9._-]+/[A-Za-z0-9._-]+", repo): + raise SystemExit("unexpected repository name") + with open(data_path, encoding="utf-8") as f: + doc = json.load(f) + entry, why = build_entry(parse_form(env.get("ISSUE_BODY", "")), number, repo, doc) + if entry is None: + comment = "Thanks for the report. I could not turn it into a list entry: %s\n\nEdit the issue and I will try again." % why + changed = False + else: + doc["speakers"].append(entry) + doc["version"] = int(doc["version"]) + 1 + # SPEAKER_REPORT_TODAY only exists so the tests can pin the date. + doc["updated"] = env.get("SPEAKER_REPORT_TODAY") or datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d") + with open(data_path, "w", encoding="utf-8") as f: + f.write(json.dumps(doc, indent=2, ensure_ascii=False) + "\n") + comment = ( + "Thanks. I proposed this entry in a pull request for a maintainer to review (verdict: **%s**, " + "protocol: **%s**). Your log stays in this issue and is not copied into the list." % (entry["verdict"], entry["protocol"]) + ) + changed = True + with open(comment_path, "w", encoding="utf-8") as f: + f.write(comment + "\n") + out = env.get("GITHUB_OUTPUT") + if out: + with open(out, "a", encoding="utf-8") as f: + f.write("changed=%s\n" % ("true" if changed else "false")) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv, os.environ)) diff --git a/scripts/test_speaker_report.py b/scripts/test_speaker_report.py new file mode 100644 index 00000000..2cbdddd2 --- /dev/null +++ b/scripts/test_speaker_report.py @@ -0,0 +1,191 @@ +import json +import os +import shutil +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(__file__)) +import speaker_report as sr # noqa: E402 + +HERE = os.path.dirname(__file__) +DATA = os.path.join(HERE, "testdata") + + +def read(name): + with open(os.path.join(DATA, name), encoding="utf-8") as f: + return f.read() + + +def form(speaker="Acme Play 3", protocol="DLNA", verdict="Works with a catch", happens="It stops", details="", log=""): + return ( + "### Speaker\n\n%s\n\n### Protocol\n\n%s\n\n### How does it work?\n\n%s\n\n### What happens\n\n%s\n\n" + "### Speaker details\n\n%s\n\n### Log\n\n%s\n\n### AriaCast version\n\n2.0.0\n" + ) % (speaker, protocol, verdict, happens, details, log) + + +class Run: + """Runs the script the way the workflow does, on a copy of the base list.""" + + def __init__(self, body, number="77", repo="AriaCast/AriaCast-app", base="base.json"): + self.dir = tempfile.mkdtemp() + self.data = os.path.join(self.dir, "speakers.json") + self.comment = os.path.join(self.dir, "comment.md") + self.output = os.path.join(self.dir, "output") + shutil.copy(os.path.join(DATA, base), self.data) + self.before = read(base) + env = {"ISSUE_BODY": body, "ISSUE_NUMBER": number, "GITHUB_REPOSITORY": repo, + "GITHUB_OUTPUT": self.output, "SPEAKER_REPORT_TODAY": "2026-11-27"} + sr.main(["x", self.data, self.comment], env) + + def doc(self): + with open(self.data, encoding="utf-8") as f: + return json.load(f) + + def text(self): + with open(self.data, encoding="utf-8") as f: + return f.read() + + def said(self): + with open(self.comment, encoding="utf-8") as f: + return f.read() + + def changed(self): + with open(self.output, encoding="utf-8") as f: + return f.read().strip() == "changed=true" + + def unchanged_file(self): + return self.text() == self.before + + +class ParseForm(unittest.TestCase): + def test_cuts_the_form_into_fields(self): + fields = sr.parse_form(read("issue-acme.md")) + self.assertEqual(fields["Speaker"], "Acme Play 3") + self.assertEqual(fields["How does it work?"], "Works with a catch") + self.assertIn("Needs a manual play", fields["What happens"]) + + def test_an_empty_field_is_empty(self): + self.assertEqual(sr.parse_form("### Speaker\n\n_No response_\n")["Speaker"], "") + + def test_windows_line_endings(self): + self.assertEqual(sr.parse_form("### Speaker\r\n\r\nX\r\n")["Speaker"], "X") + + def test_nothing_to_parse(self): + self.assertEqual(sr.parse_form(""), {}) + self.assertEqual(sr.parse_form(None), {}) + + +class Proposal(unittest.TestCase): + def test_a_report_becomes_an_entry_matching_the_golden_file(self): + r = Run(read("issue-acme.md")) + self.assertTrue(r.changed()) + # The app's own parser reads this same file (KnownSpeakersFileTest), so what the bot + # writes is what the app accepts. + self.assertEqual(r.text(), read("generated-sample.json")) + + def test_the_entry_and_the_version(self): + doc = Run(read("issue-acme.md")).doc() + self.assertEqual(doc["version"], 5) + self.assertEqual(doc["updated"], "2026-11-27") + entry = doc["speakers"][-1] + self.assertEqual(entry["id"], "acme-play-3-dlna") + self.assertEqual(entry["verdict"], "partial") + self.assertEqual(entry["match"], {"platform": "DLNA", "mentions": ["play 3 pro"]}) + self.assertEqual(entry["symptoms"], ["Stops after the first track", "Needs a manual play in the Acme app"]) + self.assertEqual(entry["evidence"], "[#77](https://github.com/AriaCast/AriaCast-app/issues/77), unverified report") + + def test_the_log_is_never_stored(self): + self.assertNotIn("THE-LOG-MARKER", Run(read("issue-acme.md")).text()) + + def test_the_existing_entries_are_untouched(self): + self.assertEqual(Run(read("issue-acme.md")).doc()["speakers"][0], json.loads(read("base.json"))["speakers"][0]) + + def test_a_speaker_without_a_protocol_has_no_platform_to_match(self): + r = Run(form(speaker="Echo Show 5", protocol="No local protocol", verdict="Not supported (AriaCast cannot find or reach it)", happens="Not found")) + self.assertEqual(r.doc()["speakers"][-1]["match"], {"mentions": ["echo show 5"]}) + self.assertEqual(r.doc()["speakers"][-1]["verdict"], "unsupported") + + def test_a_working_speaker_needs_no_symptoms(self): + r = Run(form(verdict="Works", happens="")) + self.assertTrue(r.changed()) + self.assertNotIn("symptoms", r.doc()["speakers"][-1]) + + def test_the_comment_says_what_happened(self): + self.assertIn("pull request", Run(read("issue-acme.md")).said()) + + +class Refusals(unittest.TestCase): + def assertRefused(self, body, words, **kwargs): + r = Run(body, **kwargs) + self.assertFalse(r.changed()) + self.assertTrue(r.unchanged_file(), "a refused report must not touch the list") + self.assertIn(words, r.said()) + + def test_no_speaker(self): + self.assertRefused(form(speaker=""), "Speaker") + + def test_a_protocol_the_form_does_not_offer(self): + self.assertRefused(form(protocol="Telepathy"), "Protocol") + + def test_a_verdict_the_form_does_not_offer(self): + self.assertRefused(form(verdict="Great"), "How does it work") + + def test_something_that_fails_must_say_how(self): + self.assertRefused(form(verdict="Does not work", happens=""), "What happens") + + def test_a_name_too_short_to_recognise(self): + self.assertRefused(form(speaker="TV"), "too short") + + def test_a_speaker_that_is_already_listed(self): + self.assertRefused(form(speaker="WiiM", protocol="DLNA"), "already listed as `wiim-dlna-restart`") + + def test_the_same_name_on_another_protocol_is_a_new_entry(self): + self.assertTrue(Run(form(speaker="WiiM", protocol="AirPlay 2")).changed()) + + def test_an_empty_issue(self): + self.assertRefused("", "Speaker") + + +class Hostile(unittest.TestCase): + def test_quotes_backslashes_and_markup_stay_data(self): + r = Run(form(speaker='Evil "speaker" \\